Puedes simplificar una consulta recursiva usando arrays de ruta:
WITH RECURSIVE search_graph AS (
SELECT parent_id,
ARRAY[acct_id] AS path
FROM account
UNION ALL
SELECT g.parent_id,
sg.path || g.acct_id
FROM search_graph sg
JOIN account g ON g.acct_id = sg.parent_id
WHERE NOT (g.acct_id = ANY(sg.path))
)
SELECT path[1] AS child,
path[array_upper(path, 1)] AS parent,
path
FROM search_graph
ORDER BY path;La condición WHERE debe salir de la recursión antes de que el nodo superior se duplique.
Si el único ciclo posible es una autorreferencia, puedes optimizarlo:
WITH RECURSIVE search_graph AS (
SELECT parent_id,
ARRAY[acct_id] AS path,
NOT (acct_id = parent_id) AS keep_going
FROM account
UNION ALL
SELECT g.parent_id,
sg.path || g.acct_id,
NOT (g.acct_id = g.parent_id)
FROM search_graph sg
JOIN account g ON g.acct_id = sg.parent_id
WHERE sg.keep_going
)
SELECT path[1] AS child,
path[array_upper(path, 1)] AS parent,
path
FROM search_graph
ORDER BY path;