mysql - SQL 最后插入到 Drupal 中。它真的是线程安全的吗?

标签 mysql drupal concurrency multithreading

我有一个查询可能会被多个用户连续执行。我担心如果我运行 db_last_insert_id 命令,由于并发性,某些用户可能无法获得最后的插入 ID。但根据:http://api.drupal.org/api/function/db_last_insert_id/6 ,它说:

Returns the last insert id. This function is thread safe.

我的问题是,这个线程如何安全?代码只有:

<?php
  function db_last_insert_id($table, $field) {
   return db_result(db_query("SELECT CURRVAL('{". db_escape_table($table) ."}_". db_escape_table($field) ."_seq')"));
  }
?> 

我没有看到任何有关锁定表的信息或什么都没有?

最佳答案

使用 MySQL (正如您在问题中用标签表示的那样),函数 db_last_insert_id()是这样定义的:

function db_last_insert_id($table, $field) {
  return db_result(db_query('SELECT LAST_INSERT_ID()'));
}

database.mysql-common.inc


LAST_INSERT_ID()取决于连接(引用,强调我的):

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

所以,我想说这对 MySQL 来说是完全可以的 ;-)


您发布的定义实际上是用于 PostGreSQL 的定义:

function db_last_insert_id($table, $field) {
  return db_result(db_query("SELECT CURRVAL('{". db_escape_table($table) ."}_". db_escape_table($field) ."_seq')"));
}

database.pgsql.inc


来自 pgsql manual on sequences (引用;强调我的):

currval

Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Notice that because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did.

所以,我猜这对 PostGreSQL 来说也很好。

关于mysql - SQL 最后插入到 Drupal 中。它真的是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1410240/

相关文章:

linux - 如果两个核心试图同时写入主存中的同一个地方会发生什么?

mysql - 如何使 IF 语句在 SQL 级别检查是否为空?

mysql - 更新时间戳列时的奇怪行为

php - 更改 Drupal 网站的 settings.php 文件后是否需要重新启动 Apache?

c++ - 其他线程是否总是以相同的顺序看到不同线程中对同一位置的两次轻松写入?

java - ConcurrentHashmap 同时进行写入和获取操作

MySQL Coercibility 对表达式 : why both expressions are unicode, 的整理是一个错误?

mysql - 如何选择列中具有重复值类型的记录 - MySQL

drupal - 在 Drupal 中将表单插入 block 中?

linux - Memcached:放在哪里?