How can a dependency query list reachable tasks in a cyclic graph?

UNION in a recursive CTE discards repeated whole rows. Projecting only the node ID deduplicates visits by node.

SQLite example and interpretation

A reaches B, which links back to A and onward to C. Only three nodes are returned. Adding a changing depth to each deduplication row can defeat cycle termination.

WITH RECURSIVE edge(a,b) AS (VALUES('A','B'),('B','A'),('B','C')), seen(n) AS (VALUES('A') UNION SELECT b FROM edge JOIN seen ON a=n) SELECT n FROM seen ORDER BY n;

Result [["A"], ["B"], ["C"]]

中文

有回环的任务依赖图怎样列出可达任务?

递归 CTE 使用 UNION 时会剔除重复的完整递归行,只投影节点编号便可按节点去重。

SQLite 示例与适用条件

A 指向 B,B 又指回 A 并指向 C,最终只返回三个节点。若把变化的深度也放入去重行,环路就可能持续产生新行。

WITH RECURSIVE edge(a,b) AS (VALUES('A','B'),('B','A'),('B','C')), seen(n) AS (VALUES('A') UNION SELECT b FROM edge JOIN seen ON a=n) SELECT n FROM seen ORDER BY n;

结果 [["A"], ["B"], ["C"]]

References / 参考来源

Keep reading / 继续阅读