开发者

PostgreSQL Locking Questions

I am trying to figure out how to lock an entire table from writing in Postgres however it doesn't seem to be working so I am assuming I am doing something wrong.

Table name is 'users' for example.

LOCK TABLE users IN EXCLUSIVE MODE;

When I check the view pg_locks it doesn't seem to be in there. I've tried other locking modes as well to no avail.

Other transactions are also capable of performing the LOCK function and do not block like I assumed they would.

In the psql tool (8.1) I simply get back LOCK TABLE.

Any help would be wonde开发者_开发百科rful.


There is no LOCK TABLE in the SQL standard, which instead uses SET TRANSACTION to specify concurrency levels on transactions. You should be able to use LOCK in transactions like this one

BEGIN WORK;
LOCK TABLE table_name IN ACCESS EXCLUSIVE MODE;
SELECT * FROM table_name WHERE id=10;
Update table_name SET field1=test WHERE id=10;
COMMIT WORK;

I actually tested this on my db.


Bear in mind that "lock table" only lasts until the end of a transaction. So it is ineffective unless you have already issued a "begin" in psql.

(in 9.0 this gives an error: "LOCK TABLE can only be used in transaction blocks". 8.1 is very old)


The lock is only active until the end of the current transaction and released when the transaction is committed (or rolled back).

Therefore, you have to embed the statement into a BEGIN and COMMIT/ROLLBACK block. After executing:

BEGIN;
LOCK TABLE users IN EXCLUSIVE MODE;

you could run the following query to see which locks are active on the users table at the moment:

SELECT * FROM pg_locks pl LEFT JOIN pg_stat_activity psa ON pl.pid = psa.pid WHERE relation = 'users'::regclass::oid;

The query should show the exclusive lock on the users table. After you perform a COMMIT and you re-run the above-mentioned query, the lock should not longer be present.

In addition, you could use a lock tracing tool like https://github.com/jnidzwetzki/pg-lock-tracer/ to get real-time insights into the locking activity of the PostgreSQL server. Using such lock tracing tools, you can see which locks are taken and released in real-time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜