panta82
panta82

Reputation: 2721

PostgreSQL obtain and release LOCK inside stored function

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.

Upvotes: 14

Views: 12880

Answers (3)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 659137

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.

Upvotes: 11

Jan Katins
Jan Katins

Reputation: 2319

In pg11 you now have PROCEDUREs 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

Upvotes: 4

user_0
user_0

Reputation: 3363

Not possible. From documentation: Once acquired, a lock is normally held till end of transaction. But if a lock is acquired after establishing a savepoint, the lock is released immediately if the savepoint is rolled back to. This is consistent with the principle that ROLLBACK cancels all effects of the commands since the savepoint. The same holds for locks acquired within a PL/pgSQL exception block: an error escape from the block releases locks acquired within it.

http://www.postgresql.org/docs/9.3/static/explicit-locking.html

Upvotes: 2

Related Questions