Skip to content

feat: add SQL support with ER / schema diagrams - #78

Merged
DataDave-Dev merged 3 commits into
mainfrom
feat/sql-er-diagrams
Jun 17, 2026
Merged

feat: add SQL support with ER / schema diagrams#78
DataDave-Dev merged 3 commits into
mainfrom
feat/sql-er-diagrams

Conversation

@DataDave-Dev

@DataDave-Dev DataDave-Dev commented Jun 17, 2026

Copy link
Copy Markdown
Owner

Closes #19

Resumen

Soporte para SQL generando diagramas entidad-relación (ER) — un tipo de diagrama distinto al call graph. Orientado a PostgreSQL.

A partir de DDL (CREATE TABLE, ALTER TABLE, CREATE INDEX) detecta:

  • Tablas como nodos, con columnas + tipos.
  • PK / FK / UNIQUE / NOT NULL por columna (badges PK/FK en el nodo).
  • Relaciones FK como aristas (references) con cardinalidad (1:1, 1:N).
  • N:M inferida desde tablas puente (PK compuesta de dos FKs).
  • Resolución de FKs entre archivos por nombre de tabla (incluye ALTER TABLE ADD FOREIGN KEY).

Diseño

SQL no encaja en el modelo call-graph (analyzeProjectWith/LangSpec), así que:

  • types.ts: se extiende NodeKind (+table), EdgeKind (+references), GraphNode.columns, y GraphEdge.column/cardinality + tipo Cardinality.
  • analyzers/sql.ts: implementa LanguageAnalyzer directamente (walk del AST de tree-sitter-sql).
  • Diagram.tsx: nuevo nodo custom TableNode (header + filas de columnas con badges), sizing por nº de columnas, color/label de aristas references (muestra cardinalidad), y leyenda dinámica (solo kinds presentes en el grafo).
  • Grammar vendorizada: public/wasm/tree-sitter-sql.wasm (compilada desde @derekstride/tree-sitter-sql v0.3.11).

Cableado estándar: registry, route EXT, CodeWorkspace (selector + sample + project exts + label "schema diagram"), docs (en/es) y README (en/es), chips de Hero/Features.

Test plan

  • pnpm typecheck / pnpm lint / pnpm build OK
  • pnpm test — 31 tests (6 nuevos de SQL: tablas/columnas/PK/UNIQUE, FK inline 1:N, FK por ALTER cross-file, N:M por tabla puente, grafo vacío)
  • End-to-end vía /api/analyze y render verificado (tablas, PK/FK, 1:N y N:M)

Nota: el check build de CI puede salir rojo por el problema preexistente de runners de Actions del repo (no relacionado con este PR). Todo verificado localmente.

Summary by CodeRabbit

  • New Features
    • Added SQL as a supported language, including SQL DDL-based ER/schema diagram generation (tables/columns with PK/FK indicators, cardinality, and junction-driven many-to-many links).
    • Updated the editor/UI to recognize SQL (chips, sample, schema vs call-graph labeling, and SQL-specific “no tables” empty state).
  • Documentation
    • Updated English and Spanish MVP/roadmap notes and diagram documentation to include SQL ER/schema details.
  • Tests
    • Added/extended SQL analyzer test coverage for table extraction, PK/FK detection (inline and via ALTER), 1:1/1:N/N:M inference, and empty inputs.

@ecc-tools

ecc-tools Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@coderabbitai

coderabbitai Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: afcc772b-9092-4129-aa12-9ac7324343c6

📥 Commits

Reviewing files that changed from the base of the PR and between d846994 and b55ec72.

📒 Files selected for processing (8)
  • README.es.md
  • README.md
  • src/app/[lang]/app/page.tsx
  • src/components/ui/CodeWorkspace.tsx
  • src/i18n/dictionaries/en.json
  • src/i18n/dictionaries/es.json
  • src/lib/analysis/analyzers/analyzers.test.ts
  • src/lib/analysis/analyzers/sql.ts
💤 Files with no reviewable changes (2)
  • README.es.md
  • README.md
✅ Files skipped from review due to trivial changes (1)
  • src/i18n/dictionaries/es.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/lib/analysis/analyzers/analyzers.test.ts
  • src/lib/analysis/analyzers/sql.ts

📝 Walkthrough

Walkthrough

Adds SQL as a sixth supported language producing entity-relationship diagrams from DDL. Introduces a new sqlAnalyzer (tree-sitter), extends the graph type system with table nodes, references edges, and cardinality, adds a TableNode ReactFlow renderer, wires SQL through the API route and CodeWorkspace, updates UI surfaces including docs, and refreshes READMEs.

Changes

SQL ER Diagram Support

Layer / File(s) Summary
Graph type contracts for ER nodes and edges
src/lib/analysis/types.ts
NodeKind gains "table", EdgeKind gains "references", new TableColumn and Cardinality types are introduced, and GraphNode/GraphEdge gain optional columns and cardinality/column fields.
SQL tree-sitter analyzer
src/lib/analysis/analyzers/sql.ts
New 314-line module initializes a SQL parser via tree-sitter WASM, walks each parsed AST to extract tables, columns with PK/FK/unique/nullable attributes, FK constraints (inline and ALTER TABLE), defers UNIQUE indexes, applies constraints, computes cardinality (1:1, 1:N), detects junction tables for N:M inference, and emits { nodes, edges }.
Analyzer registry and API route wiring
src/lib/analysis/registry.ts, src/app/api/analyze/route.ts
sqlAnalyzer is added to the registry analyzers array; the API route EXT map gains sql: "sql" for snippet file-path generation.
TableNode renderer and ER diagram layout
src/components/ui/Diagram.tsx
Adds TableNode ReactFlow component with column rows and PK/FK badges, updates layout() to size table nodes by column count, emits type:"table" nodes and styled references edges with cardinality labels, extends the filtered legend with a references entry.
CodeWorkspace SQL language wiring and i18n
src/components/ui/CodeWorkspace.tsx, src/app/[lang]/app/page.tsx, src/i18n/dictionaries/{en,es}.json
Adds sql to the language list, EXT, and PROJECT_EXTS; provides a SQL DDL sample snippet; changes the diagram pane caption to "schema diagram" for SQL; updates Props to accept noTables localized string; AppPage passes noTables from dictionary; both EN/ES i18n dictionaries add noTables translation.
Hero, Features, and docs language surface
src/components/sections/Hero.tsx, src/components/sections/Features.tsx, src/components/docs/pages/Languages.tsx
SQL chip added to the hero and features badge list; the Languages docs page (EN + ES) is updated to six languages with a new SQL ER-diagram entry and an expanded warning callout.
Analyzer tests and README updates
src/lib/analysis/analyzers/analyzers.test.ts, README.md, README.es.md
New SQL describe suite covers column metadata, inline FK references edges, cross-file ALTER TABLE FK, table-level PK constraints, ALTER TABLE ordering, and N:M junction-table inference. Both READMEs document SQL support in MVP status and move the ER/UML schema diagram item from Later to Shipped.

Sequence Diagram(s)

sequenceDiagram
  participant UI as CodeWorkspace
  participant API as /api/analyze
  participant Registry as registry.ts
  participant Analyzer as sqlAnalyzer
  participant Diagram as Diagram.tsx

  UI->>API: POST { language: "sql", code: "CREATE TABLE ..." }
  API->>API: EXT["sql"] → snippet.sql
  API->>Registry: getAnalyzer("sql")
  Registry-->>API: sqlAnalyzer
  API->>Analyzer: analyzeProject([{ path: "snippet.sql", content }])
  Analyzer->>Analyzer: tree-sitter parse DDL
  Analyzer->>Analyzer: extract tables, PKs, FKs, cardinality
  Analyzer->>Analyzer: detect junction tables → N:M edges
  Analyzer-->>API: { nodes: [table nodes], edges: [references edges] }
  API-->>UI: graph JSON
  UI->>Diagram: render graph
  Diagram->>Diagram: layout() sizes table nodes by column count
  Diagram->>Diagram: emit TableNode with PK/FK column rows
  Diagram->>Diagram: references edges with cardinality labels
  Diagram-->>UI: ER schema diagram
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • DataDave-Dev/weftmap#1: The main PR's SQL support is built directly on the retrieved PR's new project-level /api/analyze + analyzeProject graph/analyzer architecture by adding a sqlAnalyzer/references edges and wiring SQL into the existing analyzer and UI flow.
  • DataDave-Dev/weftmap#20: Both PRs update the same README files' roadmap/status sections to incorporate SQL support/diagram-type items (English and Spanish).

Poem

🐰 A table hops in, columns in tow,
PK and FK, all tidy in a row.
The ER graph blooms with edges that say
"One references many, N:M all day!"
Six languages now, the warren is wide —
SQL joins the warren with schema inside. 🗂️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add SQL support with ER / schema diagrams' clearly and concisely summarizes the primary change: adding SQL language support with entity-relationship diagram generation.
Description check ✅ Passed The PR description covers all required template sections, is comprehensive, and includes test verification details beyond minimum requirements.
Linked Issues check ✅ Passed All coding requirements from issue #19 are met: SQL parser via tree-sitter, custom table node component, column/type/constraint detection, FK relationships with cardinality (1:1, 1:N, N:M), and cross-file FK resolution.
Out of Scope Changes check ✅ Passed All code changes are directly aligned with issue #19 requirements for SQL support and ER diagram generation; no out-of-scope additions detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/sql-er-diagrams

Comment @coderabbitai help to get the list of available commands and usage tips.

@ecc-tools

ecc-tools Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/components/ui/CodeWorkspace.tsx (1)

479-501: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use SQL-specific empty-state text for SQL mode.

language === "sql" correctly changes the header to “schema diagram”, but Diagram still receives emptyLabel={noFunctions}. In SQL mode this can show function-oriented empty copy for an ER diagram state.

Suggested direction
-<Diagram graph={graph} emptyLabel={noFunctions} />
+<Diagram
+  graph={graph}
+  emptyLabel={language === "sql" ? /* localized schema-empty label */ noFunctions : noFunctions}
+/>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/ui/CodeWorkspace.tsx` around lines 479 - 501, The Diagram
component receives a hardcoded emptyLabel={noFunctions} that is
function-oriented copy, but when language === "sql" it should display
schema-specific empty state text instead. Apply the same language check used for
the header ("schema diagram" vs "call graph") to the emptyLabel prop passed to
the Diagram component, so it displays appropriate SQL schema empty text when in
SQL mode and the function-oriented noFunctions text for call graph mode.
🧹 Nitpick comments (1)
src/lib/analysis/analyzers/analyzers.test.ts (1)

317-365: ⚡ Quick win

Add regressions for table-level PK metadata and unordered ALTER files

Current SQL tests validate inline PK/FK and ordered ALTER flow, but they won’t catch the table-level PK metadata gap or FK loss when ALTER TABLE is parsed before CREATE TABLE.

Suggested test additions
 describe("sql", () => {
+  test("table-level PRIMARY KEY marks column as pk/non-null", async () => {
+    const graph = await run(sqlAnalyzer, [[
+      "schema.sql",
+      `CREATE TABLE users (
+        id INTEGER,
+        PRIMARY KEY (id)
+      );`,
+    ]]);
+    const id = graph.nodes.find((n) => n.id === "table::users")?.columns?.find((c) => c.name === "id");
+    expect(id?.pk).toBe(true);
+    expect(id?.nullable).toBe(false);
+  });
+
+  test("FK via ALTER TABLE resolves regardless of file order", async () => {
+    const graph = await run(sqlAnalyzer, [
+      ["c.sql", "ALTER TABLE posts ADD CONSTRAINT fk FOREIGN KEY (author_id) REFERENCES users (id);"],
+      ["a.sql", "CREATE TABLE users ( id INTEGER PRIMARY KEY );"],
+      ["b.sql", "CREATE TABLE posts ( id INTEGER PRIMARY KEY, author_id INTEGER );"],
+    ]);
+    expect(hasEdge(graph, "table::posts", "table::users", "references")).toBe(true);
+  });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/analysis/analyzers/analyzers.test.ts` around lines 317 - 365, Add two
new regression test cases to the test suite. First, add a test after the
existing tests that validates table-level PRIMARY KEY metadata by creating a
table with a table-level PRIMARY KEY constraint (using the syntax PRIMARY KEY
(columnName) at the table level rather than inline SERIAL PRIMARY KEY) and
verify the analyzer correctly identifies the pk property on the column. Second,
add a test that verifies Foreign Key handling when ALTER TABLE statements are
processed in a different file order than their corresponding CREATE TABLE
statements by reversing the file order in the test input (parsing the ALTER
TABLE file before the CREATE TABLE file) and confirm the analyzer still
correctly creates the references edge and marks the fk property on the column.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@README.es.md`:
- Line 159: The Spanish roadmap in README.es.md has inconsistent SQL deliverable
status. Remove the SQL-related item from the "Más adelante" section (around line
175) that lists it as pending, since SQL diagrams and schema items are already
marked as completed in the "Hecho" section at line 159. Ensure each deliverable
appears only once and with consistent completion status throughout the document.

In `@README.md`:
- Line 157: The README.md contains contradictory roadmap status for SQL support:
line 157 marks SQL schema diagrams as completed with a checked checkbox [x], but
the "Later" section around line 173 still lists SQL-related items as pending
TODOs. Remove or reword the SQL-related TODO items in the "Later" section to
eliminate this conflict and ensure the roadmap accurately reflects that SQL
support has been shipped. This ensures product status consistency throughout the
document.

In `@src/components/docs/pages/Languages.tsx`:
- Around line 61-67: The lead text claims that "Weftmap soporta seis lenguajes"
(Weftmap supports six languages), but the Matrix component is populated from the
ROWS variable which currently contains only five language entries. Add a sixth
language entry to the ROWS variable to match the "six languages" claim in the
text. Ensure the new entry follows the same structure as the existing rows with
columns for Lenguaje, Funciones, Clases, Imports, and Herencia.

In `@src/lib/analysis/analyzers/sql.ts`:
- Around line 94-96: When isPk is true and columns are added to table.pk, you
also need to update the individual TableColumn.pk property to true and set the
nullable property to false for each column being added. In the loop where
table.pk.add(c) is called, additionally set c.pk = true and c.nullable = false
for each column c to ensure the PK badge is properly displayed in node rows.
Apply this same fix to the similar code block mentioned at lines 274-279.
- Around line 175-184: The readAlterTable function returns early when the target
table is not yet in the tables map, causing ALTER TABLE constraint statements to
be permanently lost if files are processed out of order. Instead of returning
when the table is not found, defer processing of the constraint by collecting it
in a separate queue or map of pending constraints, then process these pending
constraints after all table definitions have been parsed to ensure cross-file
foreign key relationships are captured regardless of file order.
- Around line 90-112: The readConstraint function currently only handles primary
key and foreign key constraints, but ignores UNIQUE constraints that are
declared at the table or ALTER level. Add a new conditional block (similar to
the existing isPk and isFk checks) that detects when a constraint has the
keyword_unique type, extracts the columns using the orderedColumns function
pattern already used for PK constraints, and then marks those columns as unique
in the table object using an appropriate method call to track uniqueness on the
table instance.

---

Outside diff comments:
In `@src/components/ui/CodeWorkspace.tsx`:
- Around line 479-501: The Diagram component receives a hardcoded
emptyLabel={noFunctions} that is function-oriented copy, but when language ===
"sql" it should display schema-specific empty state text instead. Apply the same
language check used for the header ("schema diagram" vs "call graph") to the
emptyLabel prop passed to the Diagram component, so it displays appropriate SQL
schema empty text when in SQL mode and the function-oriented noFunctions text
for call graph mode.

---

Nitpick comments:
In `@src/lib/analysis/analyzers/analyzers.test.ts`:
- Around line 317-365: Add two new regression test cases to the test suite.
First, add a test after the existing tests that validates table-level PRIMARY
KEY metadata by creating a table with a table-level PRIMARY KEY constraint
(using the syntax PRIMARY KEY (columnName) at the table level rather than inline
SERIAL PRIMARY KEY) and verify the analyzer correctly identifies the pk property
on the column. Second, add a test that verifies Foreign Key handling when ALTER
TABLE statements are processed in a different file order than their
corresponding CREATE TABLE statements by reversing the file order in the test
input (parsing the ALTER TABLE file before the CREATE TABLE file) and confirm
the analyzer still correctly creates the references edge and marks the fk
property on the column.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a8c7c261-53d2-4354-b738-7ab3ab6d6699

📥 Commits

Reviewing files that changed from the base of the PR and between f571626 and 4dbe9a0.

⛔ Files ignored due to path filters (1)
  • public/wasm/tree-sitter-sql.wasm is excluded by !**/*.wasm
📒 Files selected for processing (12)
  • README.es.md
  • README.md
  • src/app/api/analyze/route.ts
  • src/components/docs/pages/Languages.tsx
  • src/components/sections/Features.tsx
  • src/components/sections/Hero.tsx
  • src/components/ui/CodeWorkspace.tsx
  • src/components/ui/Diagram.tsx
  • src/lib/analysis/analyzers/analyzers.test.ts
  • src/lib/analysis/analyzers/sql.ts
  • src/lib/analysis/registry.ts
  • src/lib/analysis/types.ts

Comment thread README.es.md
Comment thread README.md
Comment on lines +61 to 67
Weftmap soporta seis lenguajes hoy. La arquitectura es ampliable: cada
lenguaje es una gramática de tree-sitter más un conjunto de consultas.
Cinco generan un <strong>call graph</strong>; SQL genera un diagrama
<strong> entidad-relación</strong>.
</Lead>

<Matrix headers={["Lenguaje", "Funciones", "Clases", "Imports", "Herencia"]} />

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Keep the language matrix consistent with the “six languages” claim.

The lead now says six supported languages, but the matrix still renders from ROWS with only five entries. This creates conflicting documentation on the same page.

Possible fix
 const ROWS: Row[] = [
   { lang: "Python", fns: true, classes: true, imports: true, extends: true },
   { lang: "JavaScript", fns: true, classes: true, imports: true, extends: true },
   { lang: "TypeScript", fns: true, classes: true, imports: true, extends: true },
   { lang: "Go", fns: true, classes: false, imports: false, extends: false },
   { lang: "Rust", fns: true, classes: false, imports: false, extends: false },
+  { lang: "SQL", fns: false, classes: false, imports: false, extends: false },
 ];

Also applies to: 93-100

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/docs/pages/Languages.tsx` around lines 61 - 67, The lead text
claims that "Weftmap soporta seis lenguajes" (Weftmap supports six languages),
but the Matrix component is populated from the ROWS variable which currently
contains only five language entries. Add a sixth language entry to the ROWS
variable to match the "six languages" claim in the text. Ensure the new entry
follows the same structure as the existing rows with columns for Lenguaje,
Funciones, Clases, Imports, and Herencia.

Comment thread src/lib/analysis/analyzers/sql.ts Outdated
Comment thread src/lib/analysis/analyzers/sql.ts Outdated
Comment thread src/lib/analysis/analyzers/sql.ts Outdated
@ecc-tools

ecc-tools Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@DataDave-Dev
DataDave-Dev merged commit b52900e into main Jun 17, 2026
1 of 2 checks passed
@DataDave-Dev
DataDave-Dev deleted the feat/sql-er-diagrams branch June 17, 2026 02:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQL support: ER / UML schema diagrams

1 participant