title: MySQL 5 atomic id generator
body: <p>My logic need to know the ID of a table before INSERT (setting the id manually while inserting). Because the logic using this ID is on more than one server, letting mysql create an id might be a good idea but the function I wrote is not atomic so calling it under high load will return some identic, not unique numbers:</p>
  
  <pre><code>CREATE FUNCTION `generate_document_log_id`() RETURNS BIGINT(16)
  BEGIN
      DECLARE R_ID BIGINT(16);
      UPDATE document_log_sequence SET id = id + 1;
      SELECT id INTO R_ID FROM document_log_sequence;
      RETURN R_ID;
  END
  </code></pre>
  
  <p>I'm using a table "document_log_sequence" with one column "id" to store the last ID and increment it for each new ID.
  Maybe the solution is far from this but I've no more ideas.</p>
  
  <p>I forgotten to explain:
  There's only one database-server and n number of clients. The function above is not (kind of) thread safe. </p>