1

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.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Ras Ram
  • 173
  • 1
  • 7
  • 2
    Why do you want to lock a table for a longer time than the script? You are probably doing something wrong. – LtWorf Jun 14 '13 at 08:28

2 Answers2

5

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;
Talvalin
  • 7,789
  • 2
  • 30
  • 40
  • 1
    If the suggested script works, then please mark this as the accepted answer and upvote when possible. :) – Talvalin Jun 14 '13 at 15:13
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;
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129