title: Doctrine entity manager and multiple threads updating database
body: <p>I currently have an XHR request that can fire off N times from the client. This requests are handled by the server and each requests typically creates a new row in the database (all doctrine / xml). </p>
  
  <p>Before I persist() the object, I make sure if has a unique filename (I am uploading assets) and I do this by overriding persist(), calling my getUniqueFilename() and then calling parent::persist. </p>
  
  <p>I get a race condition when I perform multiple XHR requests w/the same filename. What happens if that multiple threads are running at the exact same time and checking the database for duplicates in order to generate the unique filename.</p>
  
  <ul>
  <li>Upload file</li>
  <li>Check database if filename exists</li>
  <li>Increment filename (eg: filename_1)</li>
  </ul>
  
  <p>However, when multiple XHR requests occur in multiple threads a race condition occurs where multiple files are inserted into the database w/the same name (filename_1 is generated multiple times).</p>
  
  <p>I think the way to solve this is either</p>
  
  <ul>
  <li>A mysql trigger</li>
  <li>Adding a unique constraint to the table for filename, and wrapping in try/catch in code</li>
  </ul>
  
  <p>What would you do?</p>