I am running this query:
WITH RECURSIVE base_record AS (
-- Base case: start from the initial defined term
SELECT
dt.id AS defined_term_id,
dt.name AS term_name,
1 AS depth,
ARRAY[dt.id] AS path -- Track visited terms in an array
FROM
"DefinedTerm" dt
WHERE
dt.id = 'cm1avefkf003pe5h46ntdclns' -- Start with the initial defined term
), graph as (
SELECT * FROM base_record
-- Traverse to related defined terms through ConditionSegments
UNION ALL
SELECT
csdt.id AS defined_term_id,
csdt.name AS term_name,
dt.depth + 1 AS depth,
dt.path || csdt.id
FROM
graph dt
JOIN
"Condition" c ON c."definedTermId" = dt.defined_term_id
JOIN
"ConditionSegment" cs ON cs."conditionId" = c.id
JOIN
"DefinedTerm" csdt ON cs."referencedDefinedTermId" = csdt.id
WHERE
NOT csdt.id = ANY(dt.path)
-- Traverse to related defined terms through FormulaSegments
UNION all
SELECT
fsdt.id AS defined_term_id,
fsdt.name AS term_name,
dt.depth + 1 AS depth,
dt.path || fsdt.id
FROM
graph dt
JOIN
"FormulaSegment" fs ON fs."definedTermId" = dt.defined_term_id
JOIN
"DefinedTerm" fsdt ON fs."referencedDefinedTermId" = fsdt.id
WHERE
NOT fsdt.id = ANY(dt.path)
)
-- Select the recursive traversal results
SELECT *
FROM
graph
ORDER BY
depth, defined_term_id;
This is always throwing the error:
ERROR: recursive reference to query "graph" must not appear within its non-recursive term
If i remove one of the UNION ALL, so running this query:
WITH RECURSIVE base_record AS (
-- Base case: start from the initial defined term
SELECT
dt.id AS defined_term_id,
dt.name AS term_name,
1 AS depth,
ARRAY[dt.id] AS path -- Track visited terms in an array
FROM
"DefinedTerm" dt
WHERE
dt.id = 'cm1avefkf003pe5h46ntdclns' -- Start with the initial defined term
), graph as (
SELECT * FROM base_record
-- Traverse to related defined terms through ConditionSegments
UNION ALL
SELECT
csdt.id AS defined_term_id,
csdt.name AS term_name,
dt.depth + 1 AS depth,
dt.path || csdt.id
FROM
graph dt
JOIN
"Condition" c ON c."definedTermId" = dt.defined_term_id
JOIN
"ConditionSegment" cs ON cs."conditionId" = c.id
JOIN
"DefinedTerm" csdt ON cs."referencedDefinedTermId" = csdt.id
WHERE
NOT csdt.id = ANY(dt.path)
)
-- Select the recursive traversal results
SELECT *
FROM
graph
ORDER BY
depth, defined_term_id;
Then it functions as expected.
Am I missing some specific syntax to specify that it is still in the recursion? I've tried to restructure the query in multiple different ways but can't seem to find the correct way to write it.