sql-recursive-graph-traversal
Execute graph pathfinding, hierarchy walking, cycle detection, path cost accumulation, and BFS shortest-path queries inside relational SQL. Do not use for dedicated graph databases (Neo4j) or unstructured property lookups.
- License 许可
- MIT
- 最近更新
- 2026-11-15
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- sql-recursive-graph-traversal
- description
- Execute graph pathfinding, hierarchy walking, cycle detection, path cost accumulation, and BFS shortest-path queries inside relational SQL. Do not use for dedicated graph databases (Neo4j) or unstructured property lookups.
02 资源文件 2
- 参考文档CARD.md4.0 KB
- 参考文档config.default.yaml305 B
03 SKILL.md 正文
SQL Recursive Graph Traversal Engine
sql-recursive-graph-traversal operationalizes relational SQL as a declarative graph query engine via Recursive Common Table Expressions (WITH RECURSIVE). It solves graph traversal, hierarchy walking, pathfinding, cost accumulation, and shortest-path breadth-first searches directly inside relational database engines (PostgreSQL, SQLite, MySQL 8+, SQL Server) without requiring external graph database dependencies or procedural scripts.
Every graph traversal workflow executes this five-stage progression:
[1. Topology & Anchor Identification] → [2. Recursive Expansion & State Tracking] → [3. Cycle Defense & Safety Brakes] → [4. Target Filtering & Shortest-Path Windowing] → [5. Index & Performance Tuning]
See CARD.md for the companion summary card, SQL recursion template library, and verification invariants.
Consult /data-topology-mapper for structural blast radius mapping and /epistemic-isnad-audit for dependency lineage.
1. Topology & Anchor Identification
Define the graph representation in relational tables and formulate the anchor member:
- Classify the Edge Schema:
- Direct Adjacency List:
(id, parent_id, label)— standard tree/hierarchy. - Directed Edge List:
(origin, destination, cost, distance)— weighted route graph. - Undirected / Bidirectional Network:
(node_a, node_b)— social graph (requires symmetric union in anchor or recursive step).
- Direct Adjacency List:
- Formulate the Anchor Query:
- Seed the initial working set (root nodes, start locations, or source individuals).
- Initialize state tracking columns:
depthorlevel(initialized to0or1).path_string(initialized toCAST(node_id AS TEXT)ororigin || ' -> ' || destination).accumulated_cost(initialized to0.0or direct edge cost).is_cycle(initialized to0orFALSE).
WITH RECURSIVE graph_traversal AS (
-- 1. Anchor Member: Seed the root / origin
SELECT
origin,
destination,
cost,
1 AS hop_count,
cost AS total_cost,
origin || ' -> ' || destination AS path_string,
0 AS is_cycle
FROM flights
WHERE origin = 'JFK'
UNION ALL
-- 2. Recursive Member (Structured in Stage 2 & 3)
...
)
Completion criterion: Anchor query defined, seeding initial working nodes with explicit
hop_count,total_cost,path_string, andis_cycletracker columns.
2. Recursive Expansion & State Tracking
Construct the recursive member to expand neighbor nodes while accumulating path metrics:
- Join Condition:
- Join the recursive working set
twith the base edge tableewheret.destination = e.origin(ort.child_id = e.parent_id).
- Join the recursive working set
- Metric Accumulation:
- Increment hop count:
t.hop_count + 1. - Add running costs:
t.total_cost + e.cost. - Concatenate path history:
t.path_string || ' -> ' || e.destination.
- Increment hop count:
- State Isolation:
- Ensure all derived columns maintain exact data type alignment across the
UNION ALLboundary.
- Ensure all derived columns maintain exact data type alignment across the
Completion criterion: Recursive member joins working set to edge table, propagating accumulated metrics and path history across iterative hops.
3. Cycle Defense & Safety Brakes
Prevent infinite recursion loops and memory exhaustion on cyclic or bidirectional graphs:
┌─────────────────────────────────────────────────────────────┐
│ CYCLE DEFENSE IN RECURSIVE SQL │
├──────────────────────────────┬──────────────────────────────┤
│ Mechanism 1: Visited Path │ Mechanism 2: Hard Depth Brake│
│ - String: instr(path, next) │ - WHERE hop_count < 20 │
│ - Array: next = ANY(path) │ - Guards unexpected loops │
└──────────────────────────────┴──────────────────────────────┘
- Visited Path Membership Check:
- SQLite / Text Engines: Use
instr(t.path_string, e.destination) > 0or delimited searchinstr('/' || t.path_string || '/', '/' || e.destination || '/') > 0. - PostgreSQL: Use array accumulator
e.destination = ANY(t.visited_nodes).
- SQLite / Text Engines: Use
- Prune Cyclic Branches:
- Add filter in the recursive
WHEREclause:WHERE instr(t.path_string, e.destination) = 0(or setis_cycle = 1and halt expansion).
- Add filter in the recursive
- Inject Hard Depth Brake:
- Enforce a hard recursion boundary:
AND t.hop_count < :max_depth(e.g.,< 20). This acts as a circuit breaker against unexpected dense cycles.
- Enforce a hard recursion boundary:
UNION ALL
SELECT
e.origin,
e.destination,
e.cost,
t.hop_count + 1,
t.total_cost + e.cost,
t.path_string || ' -> ' || e.destination,
CASE WHEN instr(t.path_string, e.destination) > 0 THEN 1 ELSE 0 END
FROM flights e
JOIN graph_traversal t ON t.destination = e.origin
WHERE instr(t.path_string, e.destination) = 0 -- Cycle Defense
AND t.hop_count < 10 -- Hard Depth Brake
Completion criterion: Cycle detection condition and hard depth ceiling embedded into the recursive
WHEREclause, eliminating infinite loop paths.
4. Target Filtering & Shortest-Path Windowing
Filter the completed working set for destination criteria and calculate shortest or cheapest paths:
- Terminal Destination Filter:
- In the outer
SELECT, filter for target vertices:WHERE destination = 'NRT'.
- In the outer
- Breadth-First Shortest Path (BFS Windowing):
- When multiple paths reach the same destination at different depths, rank them using window functions:
WITH ranked_paths AS ( SELECT destination, path_string, hop_count, total_cost, ROW_NUMBER() OVER ( PARTITION BY destination ORDER BY hop_count ASC, total_cost ASC ) AS rank_order FROM graph_traversal WHERE destination = 'NRT' ) SELECT * FROM ranked_paths WHERE rank_order = 1;
- When multiple paths reach the same destination at different depths, rank them using window functions:
- Format Output Hierarchies:
- For organizational trees, render formatted visual indentation using
substr(' ', 1, level * 2) || employee_name.
- For organizational trees, render formatted visual indentation using
Completion criterion: Outer query filters target destination, ranks paths via window partition, and returns deterministic shortest or lowest-cost trajectories.
5. Index & Performance Tuning
Profile query execution plans and protect database memory bounds:
- Index Recursive Join Columns:
- Ensure an index exists on the foreign key / join column:
CREATE INDEX idx_edges_origin ON flights(origin, destination, cost); - Failure to index results in a full table scan on every recursive iteration.
- Ensure an index exists on the foreign key / join column:
- Bound Working Table Size:
- For highly connected, dense networks (e.g., social networks with thousands of edges per node), avoid unconstrained multi-hop scans that spill intermediate tables to disk.
- Validate Execution Plan:
- Run
EXPLAIN QUERY PLAN(SQLite) orEXPLAIN ANALYZE(PostgreSQL) to verify index usage and scan costs.
- Run
Completion criterion: Join indexes verified, working table memory bounds checked, and query execution plan validated.
In-File Reference: SQL Recursion Patterns
Pattern A: Org Chart Tree Traversal (Hierarchy & Indentation)
WITH RECURSIVE org_tree AS (
SELECT id, name, manager_id, 0 AS level, name AS path
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, t.level + 1, t.path || ' -> ' || e.name
FROM employees e
JOIN org_tree t ON e.manager_id = t.id
WHERE t.level < 15
)
SELECT printf('%*s', level * 2, '') || name AS indented_tree, level, path
FROM org_tree ORDER BY path;
Pattern B: Shortest Path Breadth-First-Search (Six Degrees)
WITH RECURSIVE network_paths AS (
SELECT person_b AS current_node, 1 AS degree, person_a || ' -> ' || person_b AS path
FROM friendships WHERE person_a = 'Alice'
UNION ALL
SELECT f.person_b, p.degree + 1, p.path || ' -> ' || f.person_b
FROM friendships f
JOIN network_paths p ON f.person_a = p.current_node
WHERE instr(p.path, f.person_b) = 0 AND p.degree < 6
),
shortest AS (
SELECT current_node, degree, path,
ROW_NUMBER() OVER (PARTITION BY current_node ORDER BY degree ASC) AS rn
FROM network_paths
)
SELECT current_node AS target_person, degree, path
FROM shortest WHERE rn = 1;
The Three Foundational Pillars
1. The Visual Brief
Synthesize findings, structural matrices, and execution DAGs into a self-contained HTML visual brief written to %TEMP%\sql-recursive-graph-traversal-<timestamp>.html (or /tmp/sql-recursive-graph-traversal-<timestamp>.html on Unix) loading Tailwind CSS and Mermaid.js via CDN. Present the absolute clickable path to the user for visual review.
2. The Mandatory Checkpoint
When proposing structural modifications, refactors, or execution pipelines, always author an implementation_plan.md artifact with RequestFeedback: true. The agent must STOP and wait for explicit human confirmation before executing mutating actions.
3. Explicit Anti-Patterns
Rigid behavioral boundaries must be maintained to prevent catastrophic failure modes.
Anti-Patterns
- Unbounded Recursive Queries — Omitting depth brakes and cycle checks, allowing circular graphs to loop until out-of-memory crashes occur.
- Unindexed Recursive Joins — Joining recursive working sets to unindexed base tables, turning every recursion step into an $O(N)$ full table scan.
- Dense Graph Fan-Out Explosion — Running deep recursive CTEs across highly connected social networks where intermediate working tables explode exponentially.
- Missing Path String Delimiters — Using substring checks without delimiters (e.g. searching for
1inside10 -> 21), causing false-positive cycle triggers. Use delimited formats like/1/ -> /10/.
04 同仓库更多 Skills
ui-behavior-primitive-architect
Architect, audit, and verify zero-dependency headless UI behavior primitives, WebMCP agent bridges, WAI-ARIA/SSR/RTL tri-modal checks, and framework expert routing. Do not use for static CSS theme styling or backend database migrations.
trustgraph-ontology-governor
Govern knowledge graphs, SHACL-AF triple policies, OntologyRAG subclass validation, PROV-O dual named graphs, and Laya entropy decision scoring. Do not use for relational SQL queries or generic web scraping.
shim-harness-governor
Govern universal CLI agent loops, 4-tier tool permissions, ancestor-symlink workspace sandboxes, deterministic-first command routing, collision-safe MCP namespacing, and layered skill loading. Do not use for static UI styling or external SQL analytics.
graphiti-zep-memory-governor
Govern bi-temporal knowledge graphs with Graphiti future-edge clamping, MinHash/LSH entity dedup, RRF/MMR reranking, and Zep typed ontologies. Do not use for static SQL joins or generic web crawling.
agora-mcp-workbench-architect
Architect, audit, and orchestrate Agora Workbench MCP servers, loopback sidecars, unified state graphs, gateway/dispatcher connectors, and policy-enforced data lakes. Do not use for static frontend CSS styling or non-MCP desktop GUI automation.
skill-eval-assurance-runner
Evaluate and assure agent skills using small-N Wilson confidence intervals, unbiased pass^k reliability, deterministic trajectory graders, preflight boundary honesty, and sealed digest verification. Do not use for subjective prose review or unconstrained production deployment.