[drupal-devel] Replacing lock from http://drupal.org/node/34455

Joe Murray joe.murray at jmaconsulting.biz
Tue Oct 18 20:30:05 UTC 2005

function db_next_id($name) {
$name = db_prefix_tables($name);
$result = db_query("update {sequences} set id = last_insert_id(id+1) where
name = '%s'", $name);
if(!db_affected_rows($result)) {
db_query("insert into {sequences} (id, name) values (0, '%s')", $name);
db_query("update {sequences} set id = last_insert_id(id+1) where name =
'%s'", $name);
return mysql_insert_id();

Problem: a lock is needed to prevent multiple records from being inserted at
the same time in case of an empty resultset from first update. (If first
process is blocked after first update before the insert, and second process
ran first update query during the block, then you'd get two inserts.) If
sequences was initialized with appropriate records in some other way, then
this general approach would perform better than the current lock pattern.

Joe Murray, PhD
President, JMA Consulting
57 Grandview Ave, Toronto, Ontario, Canada  M4K 1J1
416.466.1281, 416.466.1277 (f)
joe.murray at jmaconsulting.biz 
Skype: josephpmurray

More information about the drupal-devel mailing list