Skip to content

Instantly share code, notes, and snippets.

@mvodep
Created February 4, 2022 11:58
Show Gist options
  • Save mvodep/08415699c0493d5f7866b4bc5167d5b3 to your computer and use it in GitHub Desktop.
Save mvodep/08415699c0493d5f7866b4bc5167d5b3 to your computer and use it in GitHub Desktop.
WITH RECURSIVE search_graph(id, link, data, depth, path, cycle) AS (
SELECT g.id, g.link, g.data, 1,
ARRAY[g.id],
false
FROM graph g
UNION ALL
SELECT g.id, g.link, g.data, sg.depth + 1,
path || g.id,
g.id = ANY(path)
FROM graph g, search_graph sg
WHERE g.id = sg.link AND NOT cycle
)
SELECT * FROM search_graph;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment