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/