我有两个关于在Postgres函数中使用SELECT … FOR UPDATE行级锁定的问题:
>我选择哪一列是否重要?他们与什么数据有任何关系,我需要锁定然后更新?
SELECT * FROM table WHERE x=y FOR UPDATE;
VS
SELECT 1 FROM table WHERE x=y FOR UPDATE;
>我不能在函数中进行选择而不保存数据,所以我保存到一个虚拟变量。这似乎是黑客这是做事的正确方法吗?
这是我的功能:
CREATE OR REPLACE FUNCTION update_message(v_1 INTEGER,v_timestamp INTEGER,v_version INTEGER) RETURNS void AS $$ DECLARE v_timestamp_conv TIMESTAMP; dummy INTEGER; BEGIN SELECT timestamp 'epoch' + v_timestamp * interval '1 second' INTO v_timestamp_conv; SELECT 1 INTO dummy FROM my_table WHERE userid=v_1 LIMIT 1 FOR UPDATE; UPDATE my_table SET (timestamp) = (v_timestamp_conv) WHERE userid=v_1 AND version < v_version; END; $$ LANGUAGE plpgsql;
Does it matter which columns I select?
不,没关系。即使使用SELECT 1 FROM TABLE WHERE … FOR UPDATE,查询将锁定满足条件的所有行。
如果查询从连接中检索行,并且我们不想从连接中涉及的所有表中锁定行,但只能从特定表中的行中锁定行,则可以使用SELECT … FOR UPDATE OF list-of-tablenames语法:
http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE
I can’t do a select in a function without saving the data somewhere,so I save to a dummy variable. This seems hacky; is it the right way to do things?
在Pl / Pgsql中使用PERFORM命令来丢弃查询结果:
http://www.postgresql.org/docs/9.2/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-NORESULT
代替:
SELECT 1 INTO dummy FROM my_table WHERE userid=v_1 LIMIT 1 FOR UPDATE;
使用:
PERFORM 1 FROM my_table WHERE userid=v_1 LIMIT 1 FOR UPDATE;