3

Is it possible to lock a table for a specified time in PostgreSQL database by running psql commands via shell script or sql file?

If we run the LOCK TABLE command, when the script exits the lock will also be gone, so that is not sufficient.

1
  • 2
    Why do you want to lock a table for a longer time than the script? You are probably doing something wrong. Commented Jun 14, 2013 at 8:28

2 Answers 2

6

Use pg_sleep for your specified time in conjunction with LOCK TABLE? Something like the script below should lock a table for 60 seconds (note this is untested):

BEGIN WORK;
LOCK TABLE MyTable IN ACCESS EXCLUSIVE MODE;
SELECT pg_sleep(60);
COMMIT WORK;
Sign up to request clarification or add additional context in comments.

1 Comment

If the suggested script works, then please mark this as the accepted answer and upvote when possible. :)
0

You can use pg_sleep(), pg_sleep_for() and pg_sleep_until() to lock a table for a specified time as shown below according to Delaying Execution:

BEGIN;
LOCK TABLE person;
SELECT pg_sleep(10);
COMMIT;
BEGIN;
LOCK TABLE person;
SELECT pg_sleep_for('20 seconds');
COMMIT;
BEGIN;
LOCK TABLE person;
SELECT pg_sleep_for('3 minutes');
COMMIT;
BEGIN;
LOCK TABLE person;
SELECT pg_sleep_until('today 21:45');
COMMIT;
BEGIN;
LOCK TABLE person;
SELECT pg_sleep_until('tomorrow 03:00');
COMMIT;

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.