title: nodejs and sql queries - concurrent access
body: <p>I'm discovering nodejs and its asynchronous system and I'm doing a query in MySQL with the node-mysql package. I'm doing something like that:</p>
  
  <ul>
  <li>iterating a collection</li>
  <li>if the item is not in the DB, I insert</li>
  <li>if the item is in the DB, I update</li>
  </ul>
  
  <p>So my code look like that:</p>
  
  <pre><code>var stuff = ['a', 'b', 'a'];
  for(var i=0;i&lt;stuff.length;i++){
      connection.query("SELECT COUNT(*) AS count FROM table WHERE column = ?", [stuff[i]],
      (function(err, rows){
          if(rows.count == 0){
              connection.query("INSERT INTO table ...");
          } else {
              connection.query("UPDATE table SET ...");
          }
      }).bind(this)
  }
  </code></pre>
  
  <p>But I'm wondering, because of asynchronous mode, if sometimes there is a problem with this pattern. What is the behavior here ? </p>
  
  <ul>
  <li>"SELECT WHERE column = 'a'" ==> count == 0</li>
  <li>"SELECT WHERE column = 'b'" ==> count == 0</li>
  <li>"SELECT WHERE column = 'a'" ==> count == 0</li>
  <li>"INSERT 'a'"</li>
  <li>"INSERT 'b'"</li>
  <li>"<strong>INSERT</strong> 'a'" ==> unexpected behavior</li>
  </ul>
  
  <p>or</p>
  
  <ul>
  <li>"SELECT WHERE column = 'a'" ==> count == 0</li>
  <li>"INSERT 'a'"</li>
  <li>"SELECT WHERE column = 'b'" ==> count == 0</li>
  <li>"INSERT 'b'"</li>
  <li>"SELECT WHERE column = 'a'" ==> count == 1</li>
  <li>"<strong>UPDATE</strong> 'a'" ==> expected behavior !!</li>
  </ul>
  
  <p>I hope you will understand my problem, sorry for my bad english, it's a real handicap..</p>
  
  <p>Thank you.</p>