ShareLock
ShareLock is the row-level locking mechanism used internally by PostgreSQL.
Deadlocks and prevention
When several DB transactions are acting on multiple rows of the same table, it's possible to incur in a deadlock and so into an error. This can be prevented by enforcing the same consistent order of lock acquisition on all the transactions performing INSERT
, UPDATE
or DELETE
on a given table.
On top of this, if multiple DB transactions act on multiple tables a deadlock will occur, even if they follow the order on each table described above, if they acquire locks on said tables in a different order. This can also be prevented by using a consistent order of lock acquisition between different tables.
Imposing the lock acquisition order on a table with Ecto
When INSERT
ing a list of rows Postgres will respect the order in which they appear in the query, so the reordering can happen beforehand.
For example, this will work:
Performing UPDATE
s is trickier because there is no ORDER BY
clause. The solution to this is to JOIN
on a subquery that SELECT
s with the option FOR UPDATE
.
Using Ecto this can be done, for example, like this:
DELETE
has the same quirks as UPDATE
and it is too solved in the same way.
For example:
Imposing the lock acquisition order between tables with Ecto
When using an Ecto.Multi
to perform INSERT
, UPDATE
or DELETE
on multiple tables the order to keep is between different operation. For example, supposing EntryA
was established to be modified before EntryB
, this is not correct:
When possible, the simple solution is to move :update_a
to be before :update_b
. When not possible, for instance if :update_a
depends on the result of :update_b
, this can be solved by acquiring the locks in a separate operation.
For example:
Note also that for the same reasons multiple operations on the same table in the same transaction are not safe to perform if they each acquire locks in order, because locks are not released until the transaction is committed.
Order used for Explorer's tables
This is a complete list of the ordering currently in use on each table. It also specifies the order between tables in the same transaction: locks for a table on top need to be acquired before those from a table on the bottom.
Note that this should always be enforced because as long as there is one DB transaction performing in a different order there is the possibility of a deadlock.
Last updated