[英]postgresql last insert id concurrency
I want to insert an user and get its id eg last insert id.我想插入一个用户并获取其 ID,例如最后插入的 ID。 through sql.通过 sql。
CREATE OR REPLACE FUNCTION create_user(registration_ip inet)
RETURNS integer AS
insert into users(registration_ip)
values($1);
select max(id) from users;
LANGUAGE sql VOLATILE
Is this function secure?这个 function 安全吗? I meant is it concurrency safe?我的意思是并发安全吗? eg n users are being created concurrently is it guaranteed that it will return the current user's id?例如,正在同时创建 n 个用户,是否保证它会返回当前用户的 ID?
No it's not safe (and it's terribly slow!)不,这不安全(而且速度非常慢!)
You should use sequences for this purpose.您应该为此目的使用序列。
If the id column is defined as serial, a sequence is automatically created for you and you can retrieve the last generated number using currval('users_id_seq')
.如果 id 列定义为 serial,则会自动为您创建一个序列,您可以使用currval('users_id_seq')
检索最后生成的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.