gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:31:40 24 4
gpt4 key购买 nike

我有一个查询可能会被多个用户连续执行。我担心如果我运行 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com