=== modified file 'includes/bootstrap.inc'
--- includes/bootstrap.inc	
+++ includes/bootstrap.inc	
@@ -286,10 +286,10 @@ function variable_get($name, $default) {
 function variable_set($name, $value) {
   global $conf;
 
-  db_lock_table('variable');
-  db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
-  db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, serialize($value));
-  db_unlock_tables();
+  db_query_replace(
+    array("DELETE FROM {variable} WHERE name = '%s'", $name),
+    array("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, serialize($value))
+  );
 
   cache_clear_all('variables');
 
=== modified file 'includes/cache.inc'
--- includes/cache.inc	
+++ includes/cache.inc	
@@ -63,12 +63,10 @@ function cache_get($key) {
  *   A string containing HTTP header information for cached pages.
  */
 function cache_set($cid, $data, $expire = CACHE_PERMANENT, $headers = NULL) {
-  db_lock_table('cache');
-  db_query("UPDATE {cache} SET data = %b, created = %d, expire = %d, headers = '%s' WHERE cid = '%s'", $data, time(), $expire, $headers, $cid);
-  if (!db_affected_rows()) {
-    @db_query("INSERT INTO {cache} (cid, data, created, expire, headers) VALUES ('%s', %b, %d, %d, '%s')", $cid, $data, time(), $expire, $headers);
-  }
-  db_unlock_tables();
+  db_query_replace(
+    array("DELETE FROM {cache} WHERE cid = '%s'", $cid),
+    array("INSERT INTO {cache} (cid, data, created, expire, headers) VALUES ('%s', ". DB_BLOB_PLACEHOLDER .", %d, %d, '%s')", $cid, $data, time(), $expire, $headers)
+  );
 }
 
 /**
=== modified file 'includes/database.inc'
--- includes/database.inc	
+++ includes/database.inc	
@@ -136,32 +136,6 @@ function db_set_active($name = 'default'
 }
 
 /**
- * Helper function for db_query().
- */
-function _db_query_callback($match, $init = FALSE) {
-  static $args = NULL;
-  if ($init) {
-    $args = $match;
-    return;
-  }
-
-  switch ($match[1]) {
-    case '%d': // We must use type casting to int to convert FALSE/NULL/(TRUE?)
-      return (int) array_shift($args); // We don't need db_escape_string as numbers are db-safe
-    case '%s':
-      return db_escape_string(array_shift($args));
-    case '%%':
-      return '%';
-    case '%f':
-      return (float) array_shift($args);
-    case '%b': // binary data
-      return db_encode_blob(array_shift($args));
-  }
-}
-
-define('DB_QUERY_REGEXP', '/(%d|%s|%%|%f|%b)/');
-
-/**
  * Runs a basic query in the active database.
  *
  * User-supplied arguments to the query should be passed in as separate
@@ -192,8 +166,7 @@ function db_query($query) {
   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
     $args = $args[0];
   }
-  _db_query_callback($args, TRUE);
-  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query = _db_query_sprintf($query, $args);
   return _db_query($query);
 }
 
@@ -209,8 +182,7 @@ function db_queryd($query) {
   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
     $args = $args[0];
   }
-  _db_query_callback($args, TRUE);
-  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query = _db_query_sprintf($query, $args);
   return _db_query($query, 1);
 }
 
=== modified file 'includes/database.mysql.inc'
--- includes/database.mysql.inc	
+++ includes/database.mysql.inc	
@@ -11,6 +11,8 @@
  * @{
  */
 
+define('DB_BLOB_PLACEHOLDER', "'%s'");
+
 /**
  * Initialize a database connection.
  *
@@ -203,21 +205,25 @@ function db_error() {
 }
 
 /**
- * Return a new unique ID in the given sequence.
- *
- * For compatibility reasons, Drupal does not use auto-numbered fields in its
- * database tables. Instead, this function is used to return a new unique ID
- * of the type requested. If necessary, a new sequence with the given name
- * will be created.
+ * Return a new unique ID.
  */
 function db_next_id($name) {
-  $name = db_prefix_tables($name);
-  db_query('LOCK TABLES {sequences} WRITE');
-  $id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + 1;
-  db_query("REPLACE INTO {sequences} VALUES ('%s', %d)", $name, $id);
-  db_query('UNLOCK TABLES');
-
-  return $id;
+  // Prefix any curly-bracket "{table}" names
+   $name = db_prefix_tables($name);
+  // Assume initially that the sequence already exists.  Attempt to update it atomically.
+  // LAST_INSERT_ID lets us get its value later. IGNORE suppresses update failures.
+  db_query("UPDATE IGNORE {sequences} SET id=LAST_INSERT_ID(id + 1) WHERE name = '%s'", $name);
+  // Check whether that worked
+  if (!db_affected_rows()) {
+    // Updated failed, so the sequence doesn't exist yet.
+    // In either case, try to create a new sequence starting from zero
+    // IGNORE suppresses insert error if e.g. a concurrent process got there first.
+    db_query("INSERT IGNORE INTO {sequences} VALUES ('%s', %d)", $name, 0);
+    // Sequence now exists (unless some database error occurred to prevent it)
+    // Retry update, allowing for possible concurrent process. It should work this time.
+    db_query("UPDATE {sequences} SET id = LAST_INSERT_ID(id + 1) WHERE name = '%s'", $name);
+  }
+  return mysql_insert_id();
 }
 
 /**
@@ -228,6 +234,12 @@ function db_affected_rows() {
   return mysql_affected_rows($active_db);
 }
 
+function _db_query_sprintf($query, $args) {
+  $args = array_map('db_escape_string', $args);
+  array_unshift($args, $query);
+  return call_user_func_array('sprintf', $args);
+}
+
 /**
  * Runs a limited-range query in the active database.
  *
@@ -271,8 +283,7 @@ function db_query_range($query) {
   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
     $args = $args[0];
   }
-  _db_query_callback($args, TRUE);
-  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query = _db_query_sprintf($query, $args);
   $query .= ' LIMIT '. (int)$from .', '. (int)$count;
   return _db_query($query);
 }
@@ -319,8 +330,7 @@ function db_query_temporary($query) {
   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
     $args = $args[0];
   }
-  _db_query_callback($args, TRUE);
-  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query = sprintf($query, $args);
   return _db_query($query);
 }
 
@@ -379,7 +389,20 @@ function db_table_exists($table) {
 }
 
 /**
+ * Perform a replace query.
+ *
+ * @param $delete
+ *   An array, where the first value is a query which deletes one row,
+ *   subsequent values are arguments. Same syntax as of db_query.
+ * @param
+ *   An array, where the first value is a query which inserts the new row,
+ *   subsequent values are arguments. Same syntax as of db_query.
+ */
+function db_query_replace($delete, $insert) {
+  $insert_query = array_shift($insert);
+  db_query(preg_replace('/^INSERT /', 'REPLACE ', $insert_query), $insert);
+}
+
+/**
  * @} End of "ingroup database".
  */
-
-
=== modified file 'includes/database.mysqli.inc'
--- includes/database.mysqli.inc	
+++ includes/database.mysqli.inc	
@@ -15,6 +15,8 @@
  * @{
  */
 
+define('DB_BLOB_PLACEHOLDER', "'%s'");
+
 /**
  * Initialise a database connection.
  *
@@ -198,21 +200,29 @@ function db_error() {
 }
 
 /**
- * Return a new unique ID in the given sequence.
- *
- * For compatibility reasons, Drupal does not use auto-numbered fields in its
- * database tables. Instead, this function is used to return a new unique ID
- * of the type requested. If necessary, a new sequence with the given name
- * will be created.
+ * Return a new unique ID.
+ */
+function db_next_id() {
+/**
+ * Return a new unique ID.
  */
 function db_next_id($name) {
-  $name = db_prefix_tables($name);
-  db_query('LOCK TABLES {sequences} WRITE');
-  $id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + 1;
-  db_query("REPLACE INTO {sequences} VALUES ('%s', %d)", $name, $id);
-  db_query('UNLOCK TABLES');
-
-  return $id;
+  // Prefix any curly-bracket "{table}" names
+   $name = db_prefix_tables($name);
+  // Assume initially that the sequence already exists.  Attempt to update it atomically.
+  // LAST_INSERT_ID lets us get its value later. IGNORE suppresses update failures.
+  db_query("UPDATE IGNORE {sequences} SET id = LAST_INSERT_ID(id + 1) WHERE name = '%s'", $name);
+  // Check whether that worked
+  if (!db_affected_rows()) {
+    // Updated failed, so the sequence doesn't exist yet.
+    // In either case, try to create a new sequence starting from zero
+    // IGNORE suppresses insert error if e.g. a concurrent process got there first.
+    db_query("INSERT IGNORE INTO {sequences} VALUES ('%s', %d)", $name, 0);
+    // Sequence now exists (unless some database error occurred to prevent it)
+    // Retry update, allowing for possible concurrent process. It should work this time.
+    db_query("UPDATE {sequences} SET id = LAST_INSERT_ID(id + 1) WHERE name = '%s'", $name);
+  }
+  return db_result(db_query("SELECT LAST_INSERT_ID() FROM {sequences} WHERE name = '%s'", $name));
 }
 
 /**
@@ -223,6 +233,12 @@ function db_affected_rows() {
   return mysqli_affected_rows($active_db);
 }
 
+function _db_query_sprintf($query, $args) {
+  $args = array_map('db_escape_string', $args);
+  array_unshift($args, $query);
+  return call_user_func_array('sprintf', $args);
+}
+
 /**
  * Runs a limited-range query in the active database.
  *
@@ -266,8 +282,7 @@ function db_query_range($query) {
   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
     $args = $args[0];
   }
-  _db_query_callback($args, TRUE);
-  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query = _db_query_sprintf($query, $args);
   $query .= ' LIMIT '. (int)$from .', '. (int)$count;
   return _db_query($query);
 }
@@ -314,8 +329,7 @@ function db_query_temporary($query) {
   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
     $args = $args[0];
   }
-  _db_query_callback($args, TRUE);
-  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query = _db_query_sprintf($query, $args);
   return _db_query($query);
 }
 
@@ -374,6 +388,21 @@ function db_table_exists($table) {
 }
 
 /**
+ * Perform a replace query.
+ *
+ * @param $delete
+ *   An array, where the first value is a query which deletes one row,
+ *   subsequent values are arguments. Same syntax as of db_query.
+ * @param
+ *   An array, where the first value is a query which inserts the new row,
+ *   subsequent values are arguments. Same syntax as of db_query.
+ */
+function db_query_replace($delete, $insert) {
+  $insert_query = array_shift($insert);
+  db_query(preg_replace('/^INSERT /', 'REPLACE ', $insert_query), $insert);
+}
+
+/**
  * @} End of "ingroup database".
  */
 
=== modified file 'includes/database.pgsql.inc'
--- includes/database.pgsql.inc	
+++ includes/database.pgsql.inc	
@@ -11,6 +11,8 @@
  * @{
  */
 
+define('DB_BLOB_PLACEHOLDER', '%b');
+
 /**
  * Initialize a database connection.
  *
@@ -202,6 +204,37 @@ function db_affected_rows() {
 }
 
 /**
+ * Helper function for db_query().
+ */
+function _db_query_callback($match, $init = FALSE) {
+  static $args = NULL;
+  if ($init) {
+    $args = $match;
+    return;
+  }
+
+  switch ($match[1]) {
+    case '%d': // We must use type casting to int to convert FALSE/NULL/(TRUE?)
+      return (int) array_shift($args); // We don't need db_escape_string as numbers are db-safe
+    case '%s':
+      return db_escape_string(array_shift($args));
+    case '%%':
+      return '%';
+    case '%f':
+      return (float) array_shift($args);
+    case '%b': // binary data
+      return db_encode_blob(array_shift($args));
+  }
+}
+
+define('DB_QUERY_REGEXP', '/(%d|%s|%%|%f|%b)/');
+
+function _db_query_sprintf($query, $args) {
+  _db_query_callback($args, TRUE);
+  return preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+}
+
+/**
  * Runs a limited-range query in the active database.
  *
  * Use this as a substitute for db_query() when a subset of the query
@@ -240,8 +273,7 @@ function db_query_range($query) {
   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
     $args = $args[0];
   }
-  _db_query_callback($args, TRUE);
-  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query = _db_query_sprintf($query, $args);
   $query .= ' LIMIT '. (int)$count .' OFFSET '. (int)$from;
   return _db_query($query);
 }
@@ -361,6 +393,26 @@ function db_check_setup() {
 }
 
 /**
+ * Perform a replace query.
+ *
+ * @param $delete
+ *   An array, where the first value is a query which deletes one row,
+ *   subsequent values are arguments. Same syntax as of db_query.
+ * @param
+ *   An array, where the first value is a query which inserts the new row,
+ *   subsequent values are arguments. Same syntax as of db_query.
+ */
+function db_query_replace($delete, $insert) {
+  $delete_query = array_shift($delete);
+  db_query('BEGIN');
+  db_query(preg_replace('/^DELETE /', 'SELECT FOR UPDATE ', $delete_query), $delete);
+  db_query($delete_query, $delete);
+  $insert_query = array_shift($insert);
+  db_query($insert_query, $insert);
+  db_query('COMMIT');
+}
+
+/**
  * @} End of "ingroup database".
  */
 
