gpt4 book ai didi

database - 从数据修改中锁定表行

转载 作者:搜寻专家 更新时间:2023-10-30 20:25:45 25 4
gpt4 key购买 nike

CREATE TABLE t1 (
id serial int,
col text
);

insert into t1(col) values('old_value');

现在,我需要在下面的 plsql block 运行时锁定此表以防止数据修改

DO $$
declare
res1 TEXT;
res2 TEXT;
BEGIN
--PERFORM pg_advisory_lock( )
select col from t1 where id = 1 into res1;
FOR i in 1..2000000000 LOOP
-- this is just for waiting several second
END LOOP;
select col from t1 where id = 1 into res2;
RAISE NOTICE '% - %', res1, res2;
--PERFORM pg_advisory_unlock( )
END;
$$ LANGUAGE PLPGSQL

所以当这个 block 运行时,我运行其他查询:

update t1 SET col = 'new_value' where id = 1;

当运行 plsql block 未完成时,此查询会立即运行并更新行。

我需要相反,我需要更新不工作并等待,而 plsql block 运行。

我想 pg_advisory_lock()pg_advisory_unlock() 会有所帮助,但是如何使用它,我不明白,这些函数的关键参数是什么,我不明白。

也不确定这些功能是否有效。

如有任何帮助,我们将不胜感激。

最佳答案

你想要select col from t1 where id = 1 FOR UPDATE into res1;获得锁,所以整个 block 应该如下所示:

DO $$
declare
res1 TEXT;
res2 TEXT;
BEGIN
--PERFORM pg_advisory_lock( )<br/>
select col from t1 where id = 1 into FOR UPDATE res1;
FOR i in 1..2000000000 LOOP
-- this is just for waiting several second
END LOOP;
select col from t1 where id = 1 into res2;
RAISE NOTICE '% - %', res1, res2;
--PERFORM pg_advisory_unlock( )<br/>
END;
$$ LANGUAGE PLPGSQL

参见 http://www.postgresql.org/docs/9.4/static/explicit-locking.html

关于database - 从数据修改中锁定表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34902541/

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