I would like to understand better a mechanism of locking in postgres.
Let\'s say that tree can have apples (via foreign key on apple table). It seems that when selecting
Just a wild guess: you're running into an issue related to an implementation detail...
Specifically, your select tree for update
statement acquires an exclusive lock on the trees. And the update apples
statements obtain an exclusive lock on the relevant apples.
When you run the update on apples, Postgres' foreign-key related per row triggers fire, to ensure that the tree_id
exists. I don't recall their precise names off the top of my head, but they're in the catalog and there are bits and pieces in the documentation that reference them explicitly or implicitly, e.g.:
create constraint trigger ... on ... from ...
http://www.postgresql.org/docs/current/static/sql-createtrigger.html
At any rate, these triggers will run something that amounts to the following:
select exists (select 1 from trees where id = 1);
And therein lies your problem: the exclusive access due to the select for update
makes it wait for transaction 2 to release the lock on trees in order to finalize its update statement on apples, but transaction 2 is waiting for transaction 1 to complete in order to obtain a lock on apples so as to begin its update statement on apples.
As a result, Postgres bails with a deadlock.