feat: add SQL support with ER / schema diagrams - #78
Conversation
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (8)
💤 Files with no reviewable changes (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds SQL as a sixth supported language producing entity-relationship diagrams from DDL. Introduces a new ChangesSQL ER Diagram Support
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
There was a problem hiding this comment.
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 winUse SQL-specific empty-state text for SQL mode.
language === "sql"correctly changes the header to “schema diagram”, butDiagramstill receivesemptyLabel={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 winAdd 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 TABLEis parsed beforeCREATE 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
⛔ Files ignored due to path filters (1)
public/wasm/tree-sitter-sql.wasmis excluded by!**/*.wasm
📒 Files selected for processing (12)
README.es.mdREADME.mdsrc/app/api/analyze/route.tssrc/components/docs/pages/Languages.tsxsrc/components/sections/Features.tsxsrc/components/sections/Hero.tsxsrc/components/ui/CodeWorkspace.tsxsrc/components/ui/Diagram.tsxsrc/lib/analysis/analyzers/analyzers.test.tssrc/lib/analysis/analyzers/sql.tssrc/lib/analysis/registry.tssrc/lib/analysis/types.ts
| 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"]} /> |
There was a problem hiding this comment.
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.
…, SQL empty state
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
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:references) con cardinalidad (1:1,1:N).ALTER TABLE ADD FOREIGN KEY).Diseño
SQL no encaja en el modelo call-graph (
analyzeProjectWith/LangSpec), así que:types.ts: se extiendeNodeKind(+table),EdgeKind(+references),GraphNode.columns, yGraphEdge.column/cardinality+ tipoCardinality.analyzers/sql.ts: implementaLanguageAnalyzerdirectamente (walk del AST de tree-sitter-sql).Diagram.tsx: nuevo nodo customTableNode(header + filas de columnas con badges), sizing por nº de columnas, color/label de aristasreferences(muestra cardinalidad), y leyenda dinámica (solo kinds presentes en el grafo).public/wasm/tree-sitter-sql.wasm(compilada desde@derekstride/tree-sitter-sqlv0.3.11).Cableado estándar:
registry,routeEXT,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 buildOKpnpm 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)/api/analyzey render verificado (tablas, PK/FK, 1:N y N:M)Summary by CodeRabbit