I have a function that needs to perform a long update on multiple large tables. During the update 2-3 tables at a time need to be locked in EXCLUSIVE mode.
Since not all the tables need to be locked at the same time, ideally I'd want to LOCK only those tables I'm updating at the time, and then remove the lock once I'm done.
Eg.
-- Lock first pair of tables
LOCK TABLE tbl1_a IN EXCLUSIVE MODE;
LOCK TABLE tbl1_b IN EXCLUSIVE MODE;
-- Perform the update on tbl1_a and tbl1_b
-- Release the locks on tbl1_a and tbl1_b
-- HOW???
-- Proceed to the next pair of tables
LOCK TABLE tbl2_a IN EXCLUSIVE MODE;
LOCK TABLE tbl2_b IN EXCLUSIVE MODE;
Unfortunately, there's no the equivalent of UNLOCK statement in plpgsql. The normal way to remove LOCK is to COMMIT the transaction, but that is not possible inside a function.
Is there any solution for this? Some way to explicitly release the lock before function is done? Or run some kind of sub-transaction (perhaps by running each update in a separate function)?
UPDATE
I accepted that there is no solution. I'll write each update into a separate function and coordinate from outside the db. Thanks everyone.
In Postgres 11 or later, consider a PROCEDURE
which allows transaction control. See:
With functions, there is no way. Functions in Postgres are atomic (always inside a transaction) and locks are released at the end of a transaction.
You might be able to work around this with advisory locks. But those are not the same thing. All competing transactions have to play along. Concurrent access that is not aware of advisory locks will spoil the party.
Code example on dba.SE:
Or you might get somewhere with "cheating" autonomous transactions with dblink:
Or you re-assess your problem and split it up into a couple of separate transactions.
In pg11 you now have PROCEDURE
s which let you release locks via COMMIT
. I just converted a bunch of parallel executed functions running ALTER TABLE ... ADD FOREIGN KEY ...
with lots of deadlock problems and it worked nicely.
https://www.postgresql.org/docs/current/sql-createprocedure.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With