3

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 wonderful.

1
  • 1
    Why do you want to lock the table? Commented Feb 18, 2011 at 20:14

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

note that access exclusive mode prevents any other process from even reading from the table, not just writing to it. You can use share row exclusive mode to lock the table specifically against other processes running updates or inserts on it.
5

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.