Reputation: 313
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.
Upvotes: 3
Views: 1701
Reputation: 1
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;
Upvotes: 0
Reputation: 7889
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;
Upvotes: 6