In prior posts, I've gone over some methods to prevent cycles from being added to your database. However, imagine that someone has handed you an existing adjacency list tree -- perhaps migrated from another DBMS -- and you need to find all of the cycles as part of data cleaning? How do you do that?
One way, obviously, would be just explore all paths and flag the ones where any ID appeared twice:
WITH RECURSIVE prev AS (
SELECT folders.id, 1 AS depth, array[id] as seen, false as cycle
FROM folders
UNION ALL
SELECT folders.id, prev.depth + 1, path || folders.id as seen,
folders.id = any(seen) as cycle
FROM prev
INNER JOIN folders on prev.id = parent_id
)
SELECT *
FROM prev;
However, the above has a serious issue: the query itself will cycle and never complete (in fact, it will error out). So we need to terminate each cycle when the first repeat happens. Fortunately, that's easy to do, and we'll filter for only the cycles while we're at it:
WITH RECURSIVE prev AS (
SELECT folders.id, 1 AS depth, array[id] as seen, false as cycle
FROM folders
UNION ALL
SELECT folders.id, prev.depth + 1, seen || folders.id as seen,
folders.id = any(seen) as cycle
FROM prev
INNER JOIN folders on prev.id = parent_id
AND prev.cycle = false
)
SELECT *
FROM prev
WHERE cycle = true;
The results of the above query look like this:
id | depth | seen | cycle
----+-------+------------------+-------
21 | 2 | {21,21} | t
13 | 5 | {13,14,15,11,13} | t
14 | 5 | {14,15,11,13,14} | t
15 | 5 | {15,11,13,14,15} | t
11 | 5 | {11,13,14,15,11} | t
(5 rows)
One thing to notice is that you'll get a row for every node in a cycle loop. That's because with cycles, the choice of starting point is arbitrary. So the above query isn't the best choice for a deep tree where you have a lot of existing cycles. There's a 2nd way to detect cycles in a tree; lets see if any of the commentors can post that query.