How to prevent anomalies in a tree data structure
2
votes
0
answers
66
views
I have two tables
node
and node_tree
:
CREATE TABLE node (
id integer PRIMARY KEY
);
CREATE TABLE node_tree (
node_id integer references node(id) UNIQUE,
parent_id integer references node(id)
);
node_tree
is an adjacency list. There is a limit on the height of the tree, so, (1) the depth of the parent node before inserting a new node must be checked and (2), the sum of the height of the node being relocated and the depth of its new parent must not exceed the established threshold and to prevent infinite loops, it is essential to verify that the new parent is not included among the descendants of the node being relocated.
Using recursive CTEs, it is easy to apply any of those constraints. But with multiple, concurrent transactions, anomalies can happen. I can think of the following solutions:
1. Locking the whole node_tree
table. Although I have read locking tables is an anti-pattern and almost always the wrong thing to do.
2. Using advisory locks at the application level.
3. Using serializable isolation level.
4. Row level locking using for update
.
I like the last one but the problem with it is that, you cannot use for update
with recursive CTEs (trust me, I have tested), and it seems complex to me. Now my question is what is the best option and why?
Asked by Dante
(177 rep)
Nov 23, 2024, 10:47 PM