sqllens 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +409 -255
  2. package/dist/api.d.ts +9 -7
  3. package/dist/api.js +15 -6
  4. package/dist/bigquery/parse.d.ts +5 -18
  5. package/dist/bigquery/parse.js +1 -1
  6. package/dist/completion/complete.d.ts +3 -1
  7. package/dist/completion/complete.js +4 -2
  8. package/dist/completion/config.d.ts +1 -1
  9. package/dist/completion/parser-factory.d.ts +1 -1
  10. package/dist/databricks/parse.d.ts +4 -17
  11. package/dist/derived-dialects.d.ts +8 -0
  12. package/dist/derived-dialects.js +50 -0
  13. package/dist/dialect-symbols.d.ts +1 -1
  14. package/dist/dialect.d.ts +3 -0
  15. package/dist/dialect.js +1 -0
  16. package/dist/document/document.d.ts +159 -5
  17. package/dist/document/document.js +473 -18
  18. package/dist/document/node-at.js +2 -132
  19. package/dist/document/shift.d.ts +6 -0
  20. package/dist/document/shift.js +11 -0
  21. package/dist/document/split.d.ts +1 -1
  22. package/dist/duckdb/parse.d.ts +4 -16
  23. package/dist/index.d.ts +12 -7
  24. package/dist/index.js +15 -10
  25. package/dist/ir/ir.d.ts +19 -1
  26. package/dist/ir/part-span.d.ts +11 -0
  27. package/dist/ir/part-span.js +35 -1
  28. package/dist/ir/walk.d.ts +9 -0
  29. package/dist/ir/walk.js +135 -0
  30. package/dist/lineage/lineage.d.ts +4 -1
  31. package/dist/lineage/lineage.js +5 -1
  32. package/dist/minijinja/apply-tags.d.ts +12 -3
  33. package/dist/minijinja/apply-tags.js +30 -16
  34. package/dist/minijinja/engine.d.ts +4 -0
  35. package/dist/minijinja/engine.js +11 -0
  36. package/dist/minijinja/index.d.ts +8 -0
  37. package/dist/minijinja/index.js +8 -0
  38. package/dist/minijinja/parse.d.ts +3 -44
  39. package/dist/minijinja/parse.js +71 -11
  40. package/dist/minijinja/tag-ast.js +16 -2
  41. package/dist/minijinja/variants.d.ts +10 -2
  42. package/dist/minijinja/variants.js +43 -6
  43. package/dist/parse-result.d.ts +11 -0
  44. package/dist/parse-result.js +1 -0
  45. package/dist/postgres/parse.d.ts +4 -16
  46. package/dist/qualify/qualify.d.ts +8 -1
  47. package/dist/qualify/qualify.js +21 -5
  48. package/dist/qualify/template-provider.d.ts +2 -19
  49. package/dist/redshift/parse.d.ts +4 -16
  50. package/dist/references/references.js +2 -0
  51. package/dist/scope/walk.d.ts +15 -0
  52. package/dist/scope/walk.js +73 -0
  53. package/dist/session.d.ts +83 -0
  54. package/dist/session.js +159 -0
  55. package/dist/signature/signatures.d.ts +1 -1
  56. package/dist/snowflake/parse.d.ts +4 -16
  57. package/dist/symbols/symbols.d.ts +14 -0
  58. package/dist/symbols/symbols.js +115 -3
  59. package/dist/template/engine.d.ts +65 -0
  60. package/dist/template/engine.js +1 -0
  61. package/dist/token/classify.d.ts +1 -1
  62. package/dist/token/map.d.ts +1 -1
  63. package/dist/token/tokenize.d.ts +1 -1
  64. package/dist/trino/parse.d.ts +4 -15
  65. package/dist/tsql/parse.d.ts +4 -16
  66. package/package.json +95 -91
  67. package/dist/adapters.d.ts +0 -8
  68. package/dist/adapters.js +0 -43
package/README.md CHANGED
@@ -1,255 +1,409 @@
1
- # sqllens
2
-
3
- A TypeScript SQL parser and static analyzer. It parses SQL into a tree, lowers it
4
- to a dialect-neutral IR, and runs a semantic layer over that IR: name resolution
5
- (scope), schema-fed qualification, type inference, and column lineage. Give it a
6
- query and it tells you the query's sources, its output columns, their types, and
7
- where each column comes from. The parsers are generated TypeScript on the
8
- [antlr4ng](https://github.com/mike-lischke/antlr4ng) runtime.
9
-
10
- The front end is error-tolerant and token-first, so the same library powers
11
- editor tooling — an LSP and a SQL debugger — over incomplete, mid-edit text. See
12
- [Editor / language tooling](#editor--language-tooling).
13
-
14
- ## Dialects
15
-
16
- | Dialect | Parse + lower | Semantic layer | Notes |
17
- |---|---|---|---|
18
- | Databricks (Spark SQL) | yes | yes | grammar forked from apache/spark |
19
- | T-SQL | yes | yes | grammar forked from grammars-v4 `sql/tsql` |
20
- | Snowflake | yes | yes | grammar forked from grammars-v4 `sql/snowflake` |
21
- | BigQuery (GoogleSQL) | yes | yes | grammar forked from `bytebase/parser` `googlesql/`; gated against ZetaSQL's `.test` corpus |
22
- | Redshift | yes | yes | grammar forked from Bytebase's Postgres-derived Redshift grammar (BSD-3) |
23
- | PostgreSQL | yes | yes | grammar forked from `bytebase/parser` `postgresql/` (BSD-3, PG18 keywords) |
24
- | DuckDB | yes | yes | grammar forked from this repo's own postgres pair (no open ANTLR grammar exists) |
25
- | Trino | yes | yes | grammar is the first-party trinodb `SqlBase.g4` (release 482), mechanically split; covers dbt-trino + dbt-athena |
26
-
27
- The semantic layer is dialect-agnostic: it operates on the shared IR and runs
28
- unchanged on every dialect. Only the parse and lower stages are dialect-specific.
29
-
30
- ## The pipeline
31
-
32
- ```
33
- parse → lower → resolveScopes → qualify → infer / lineage / symbols
34
- ```
35
-
36
- - **parse** text concrete syntax tree (CST), with a syntax-error count.
37
- - **lower** CST a dialect-neutral IR (`QueryExpr` / `SelectExpr` / `Expr` …);
38
- also reports the statement kind (query / dml / ddl / …).
39
- - **resolveScopes** a schema-free symbol table: visible sources, CTE
40
- resolution, output columns.
41
- - **qualify** with a schema: `*` expansion, unknown-table/column diagnostics,
42
- column types.
43
- - **infer / lineage / symbols** type inference, base-table lineage per output
44
- column, and a kind×modifier symbol model.
45
-
46
- ## Status
47
-
48
- Pre-release, and not yet published to npm. The library is consumed as TypeScript
49
- (no build emit yet — packaging is a later step). The public API (`src/index.ts`)
50
- is uniform across all eight dialects: `parse` and `analyze` take the dialect as a
51
- parameter, and every per-dialect `parse*` / `lower` plus the shared passes stay
52
- exported as lower-level building blocks. The editor-facing surface `tokenize`,
53
- `SqlDocument`, `complete`, `signatureAt` lives on the same barrel.
54
-
55
- ## Usage
56
-
57
- `dialect` is `"databricks" | "tsql" | "snowflake" | "bigquery" | "redshift" | "postgres" | "duckdb" | "trino"`.
58
-
59
- Those eight grammars serve more dbt adapters than that, because several adapters
60
- are SQL front ends over an engine already covered. `adapterDialect` resolves a
61
- profiles.yml `type:` value (or a dialect name) to the dialect that parses its
62
- SQL so consumers don't re-derive the family knowledge:
63
-
64
- ```ts
65
- import { adapterDialect, ADAPTER_DIALECTS } from "sqllens";
66
-
67
- adapterDialect("athena"); // "trino" — Athena engine v3 executes on Trino
68
- adapterDialect("glue"); // "databricks" — AWS Glue runs Spark; Databricks SQL = Spark SQL
69
- adapterDialect("fabric"); // "tsql" — same for "synapse" and "sqlserver"
70
- adapterDialect("presto"); // "trino" — the pre-rename Trino adapter
71
- adapterDialect("oracle"); // undefined — not served; never a guess
72
- ```
73
-
74
- The map is exact by contract: only adapters whose SQL surface the corpus gates
75
- genuinely represent are listed. The LSP's `.sqllens.json` accepts adapter types
76
- through the same map, so `{ "dialect": "athena" }` works in rules and `default`.
77
-
78
- The surface is
79
- **layered** each tier is a terminal value you can stop at — and **composable**:
80
- every semantic method takes the closest upstream result (so passing it does no
81
- rework) or a raw string / IR via an idempotent lift helper.
82
-
83
- ```ts
84
- import { parse, analyze, Schema } from "sqllens";
85
-
86
- // Tier 1 just the IR. No semantic layer pulled in.
87
- const { ast, errors, cst } = parse("SELECT a, b FROM t WHERE a > 1", "tsql");
88
- // ast = dialect-neutral IR (frozen no pass mutates it); cst = raw antlr tree (escape hatch)
89
- // ast.statement -> "query" | "dml" | "ddl" | …
90
-
91
- // Whole pipeline in one call.
92
- const schema = new Schema({ t: { a: "int", b: "string" } });
93
- const a = analyze("SELECT a, b FROM t", "tsql", { schema });
94
- a.scopes; // name resolution (ScopeTree)
95
- a.diagnostics; // unknown-table/column diagnostics
96
- a.qualification.columnsOf(a.scopes.root); // * expansion
97
- a.types.typeOf(expr, scope); // per-expression types
98
- a.lineage.originsOf("a"); // base-table origins of an output column
99
- a.symbols; // kind × modifier symbol model
100
- ```
101
-
102
- Compose tier by tier pass any upstream result (or a string) to any later pass,
103
- and only the missing steps run. No exported signature takes or returns a raw
104
- `Map`/`Set`/`Record`:
105
-
106
- ```ts
107
- import { parse, qualify, lineage, deriveSymbols, toScopes, Schema } from "sqllens";
108
-
109
- const { ast } = parse(sql, "snowflake");
110
- const scopes = toScopes(ast, { dialect: "snowflake" }); // idempotent lift; identity if already a ScopeTree
111
- qualify(scopes, schema); // reuses scopes never re-parses or re-resolves
112
- lineage(scopes, schema); // safe to call on the same scopes, in any order
113
- deriveSymbols(scopes); // independent results, no cross-contamination
114
- ```
115
-
116
- The per-dialect entries (`parseDatabricks` / `parseTSql` / `parseSnowflake` /
117
- `parseBigQuery` / `parseRedshift` / `parsePostgres` / `parseDuckdb` / `parseTrino`,
118
- each `lower`, and the raw `resolveScopes` / `inferType`) remain exported for
119
- callers that want a single stage.
120
-
121
- ## Editor / language tooling
122
-
123
- The front end is error-tolerant and token-first, so it serves editor features
124
- that run on incomplete, mid-edit text — they never need a clean parse:
125
-
126
- - **`tokenize(sql, dialect)`** and **`parse(...).tokens`** give a first-class token
127
- stream: every token with its exact span, role, and channel. Always available,
128
- even when the parse has errors.
129
- - **`lower()` never throws** on broken or partial input — you get a flagged
130
- `query` IR back, so every downstream pass stays total.
131
- - **`SqlDocument`** is a persistent, immutable, position-addressable per-file
132
- model. It runs `parse → resolveScopes` once (plus lazy `analyze(schema)`),
133
- caches the result, and answers `tokenAt` / `nodeAt`. An edit yields a new
134
- document; an O(log n) `LineIndex` maps positions ↔ offsets.
135
- - **`complete(doc, offset, schema?)`** — scope-aware completion (keywords,
136
- columns, tables, functions) from an ATN candidate walk over the grammar (our
137
- own, no third-party dependency).
138
- - **`signatureAt(doc, offset)`** parameter hints from a curated per-dialect
139
- function-signature table; the long tail degrades to name + active-argument.
140
- - **`referencesAt(scopes, offset, schema?)`** — every occurrence (plus the
141
- declaration) of the symbol under the cursor; backs find-references, document
142
- highlight, and code-lens reference counts.
143
-
144
- ```ts
145
- import { SqlDocument, Schema } from "sqllens";
146
-
147
- const doc = SqlDocument.create("SELECT amount FROM sales", "databricks");
148
- doc.tokens; // first-class token stream (spans + roles)
149
- doc.tokenAt(7); // token under an offset
150
- const next = doc.withText("SELECT amount, id FROM sales", 2); // immutable edit → new doc
151
- ```
152
-
153
- ## Language server
154
-
155
- An LSP (Language Server Protocol) server built on the library, in `src/lsp/`. It
156
- holds one `SqlDocument` per open file (rebuilt on edit) and reaches the library
157
- only through the public API surface above it adds no analysis of its own, only
158
- protocol translation.
159
-
160
- LSP is a large protocol — roughly thirty request types across document-sync,
161
- language, and workspace features so "supports LSP" is not one bit but a long
162
- checklist. A SQL server needs a subset, but more of it maps to SQL than it first
163
- looks — a CTE / view / model is the SQL analog of a definition, and the
164
- dependency graph between them is a call hierarchy. A few features genuinely don't
165
- apply (type hierarchy, document color, monikers); a few are deliberately deferred
166
- (formatting, project-wide navigation). The coverage, feature by feature:
167
-
168
- **Language features**
169
-
170
- | Feature | Status |
171
- | --- | --- |
172
- | Completion (+ resolve) | |
173
- | Hover | ✅ |
174
- | Hover nullability | (` not null` / ` — nullable` suffix when provable) |
175
- | Signature help | |
176
- | Go to definition | ✅ |
177
- | Find references | ✅ |
178
- | Document highlight | |
179
- | Document symbols | |
180
- | Folding range | |
181
- | Selection range | |
182
- | Semantic tokens (full / range / delta) | ✅ all three |
183
- | Inlay hints | ✅ (no resolve) |
184
- | Code lens | ✅ (no resolve) |
185
- | Go to declaration | ◻️ not yet |
186
- | Go to type definition | ◻️ not yet |
187
- | Go to implementation | ◻️ not yet — name → its defining query (view / model); needs the project model |
188
- | Call hierarchy | ◻️ not yet — the CTE / dbt-model dependency graph |
189
- | Document link | ◻️ not yet |
190
- | Linked editing range | ◻️ not yet — live alias / name sync-edit |
191
- | Code action (quick fixes) | ◻️ next phase |
192
- | Rename (+ prepare) | ◻️ next phase |
193
- | Formatting / range / on-type | ◻️ deferred (external formatter) |
194
- | Inline values | ◻️ debugger surface |
195
- | Type hierarchy |n/a SQL has no type-inheritance relation |
196
- | Document color | n/a no color literals |
197
- | Moniker | — n/a — LSIF / cross-repo indexing concern |
198
-
199
- **Diagnostics & document sync**
200
-
201
- | Feature | Status |
202
- | --- | --- |
203
- | Diagnostics — push (`publishDiagnostics`) | ✅ |
204
- | Diagnostics call signature (arity / argument type) | ✅ (curated tables; never-wrong, per-dialect coercion) |
205
- | Diagnostics — pull (document) | ✅ |
206
- | Diagnostics pull (workspace) | ◻️ not yet |
207
- | Text sync open / change / close | (full-document) |
208
- | Incremental sync | ◻️ full-document only (fine at SQL file sizes) |
209
- | Save notifications (`didSave` / `willSave`) | ◻️ not yet |
210
- | Notebook document sync | ◻️ not yet |
211
-
212
- **Workspace features**
213
-
214
- | Feature | Status |
215
- | --- | --- |
216
- | Workspace symbols | ◻️ needs a project / multi-file model |
217
- | Execute command | ◻️ not yet |
218
- | Configuration / watched-files | ◻️ not yet (protocol config; file-based `.sqllens.json` config exists) |
219
- | File operations (create / rename / delete) | ◻️ not yet |
220
-
221
- Legend: implemented · ◻️ not yet / deferred · — not applicable to SQL. The
222
- deferred items are tracked work: rename and
223
- code actions are the next LSP phase, workspace symbols need the project model,
224
- and formatting is expected to wrap an existing external formatter.
225
-
226
- ## Generating the parsers
227
-
228
- `src/generated/` is a build product and is gitignored. After a fresh clone, or
229
- after editing any `.g4`, generate the parsers (the lexer must generate before the
230
- parser, which the driver handles):
231
-
232
- ```bash
233
- npm run gen -- databricks # | tsql | snowflake | bigquery | redshift | postgres | duckdb | trino
234
- npm run typecheck
235
- npm test
236
- ```
237
-
238
- ## Architecture
239
-
240
- One folder per dialect; no shared "core" grammar and no grammar inheritance. Each
241
- dialect is a standalone pair of split `.g4` files (a lexer grammar + a parser
242
- grammar), forked from its best starting point and edited in place. Everything
243
- downstream of `lower` is shared and dialect-neutral.
244
-
245
- ## Contributing
246
-
247
- See [CONTRIBUTING.md](CONTRIBUTING.md). In short: the conformance corpora are the
248
- gate a grammar change that regresses a corpus is not done — and grammar work is
249
- test-driven against those corpora.
250
-
251
- ## License
252
-
253
- MIT see [LICENSE](LICENSE). The forked grammars under `grammars/` keep their
254
- upstream licenses (Apache-2.0 for Databricks; MIT for T-SQL and Snowflake; BSD-3
255
- for BigQuery and Redshift); see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).
1
+ # sqllens
2
+
3
+ [![npm version](https://img.shields.io/npm/v/sqllens)](https://www.npmjs.com/package/sqllens) [![license](https://img.shields.io/npm/l/sqllens)](LICENSE)
4
+
5
+ A TypeScript SQL parser and static analyzer. It parses SQL into a tree, lowers it
6
+ to a dialect-neutral intermediate representation (IR), and runs a semantic layer
7
+ over that IR: name resolution (scope), schema-fed qualification, type inference,
8
+ and column lineage. Give it a
9
+ query and it tells you the query's sources, its output columns, their types, and
10
+ where each column comes from. The parsers are generated TypeScript on the
11
+ [antlr4ng](https://github.com/mike-lischke/antlr4ng) runtime.
12
+
13
+ The front end is error-tolerant and token-first, so the library drives editor
14
+ features (completion, hover, diagnostics, go-to-definition) over incomplete,
15
+ mid-edit text. See [Editor / language tooling](#editor--language-tooling). An LSP
16
+ (Language Server Protocol) server built on it lives in the repo, but it is
17
+ experimental and not part of the published package.
18
+
19
+ ```bash
20
+ npm install sqllens
21
+ ```
22
+
23
+ ```ts
24
+ import { analyze, Schema } from "sqllens";
25
+
26
+ const schema = new Schema({ orders: { id: "int", total: "decimal" } });
27
+ const q = analyze("SELECT total FROM orders WHERE total > 100", "postgres", { schema });
28
+
29
+ q.diagnostics; // [] — names and types check against the schema
30
+ q.lineage.originsOf("total"); // orders.total
31
+ ```
32
+
33
+ ## Dialects
34
+
35
+ sqllens implements eight SQL dialects directly, each with its own grammar. Seven
36
+ more engines are covered as *derived dialects*: their SQL is already parsed by one
37
+ of those eight grammars, for 15 engines in total.
38
+
39
+ | Dialect | Derived dialects | Parse + lower | Semantic layer | Notes |
40
+ |---|---|---|---|---|
41
+ | Databricks (Spark SQL) | Apache Spark, AWS Glue | yes | yes | grammar forked from apache/spark |
42
+ | T-SQL | SQL Server, Microsoft Fabric, Azure Synapse | yes | yes | grammar forked from grammars-v4 `sql/tsql` |
43
+ | Snowflake | | yes | yes | grammar forked from grammars-v4 `sql/snowflake` |
44
+ | BigQuery (GoogleSQL) | | yes | yes | grammar forked from `bytebase/parser` `googlesql/`; gated against ZetaSQL's `.test` corpus |
45
+ | Redshift | — | yes | yes | grammar forked from Bytebase's Postgres-derived Redshift grammar (BSD-3) |
46
+ | PostgreSQL | — | yes | yes | grammar forked from `bytebase/parser` `postgresql/` (BSD-3, PG18 keywords) |
47
+ | DuckDB | — | yes | yes | grammar forked from this repo's own postgres pair (no open ANTLR grammar exists) |
48
+ | Trino | Presto, Amazon Athena | yes | yes | grammar is the first-party trinodb `SqlBase.g4` (release 482), mechanically split |
49
+
50
+ Each grammar began as a fork of the upstream noted above, but most are now far from
51
+ verbatim copies. They've had substantial extension and correction, driven by a full
52
+ comparison against each dialect's official reference documentation and the reference
53
+ corpus extracted from those docs, so they reach well past their fork points.
54
+
55
+ A **derived dialect** is an engine that has no grammar of its own but whose SQL
56
+ the primary grammar already parses, because its SQL is a subset of (or the same as)
57
+ the primary dialect's. Microsoft Fabric runs a restricted subset of T-SQL, Amazon
58
+ Athena's engine is Trino, and AWS Glue runs Spark. Each one is checked against real
59
+ SQL from that engine before it goes on the list.
60
+
61
+ In code, the `dialect` argument is one of `"databricks" | "tsql" | "snowflake" | "bigquery" | "redshift" | "postgres" | "duckdb" | "trino"`. `resolveDialect` turns an
62
+ engine name (or a dialect name) into the one that parses it: `resolveDialect("athena")`
63
+ returns `"trino"`.
64
+
65
+ The semantic layer is dialect-agnostic: it operates on the shared IR and runs
66
+ unchanged on every dialect. Only the parse and lower stages are dialect-specific.
67
+
68
+ ## The pipeline
69
+
70
+ ```
71
+ parse lower resolveScopes qualify → infer / lineage / symbols
72
+ ```
73
+
74
+ Each stage produces one value, and that value is what a specific editor feature
75
+ reads from. Only the first two stages, parse and lower, are dialect-specific;
76
+ everything after them is shared and runs unchanged across all eight dialects.
77
+
78
+ **parse** turns SQL text into a *concrete syntax tree* (CST): the full parse tree,
79
+ every token and grammar node exactly as written, nothing dropped or simplified. It
80
+ also hands back the token stream and a syntax-error count. The CST is faithful but
81
+ verbose and dialect-shaped, so nothing downstream reads it directly. It backs
82
+ syntax squiggles (the underline under a parse error) and semantic tokens
83
+ (dialect-aware highlighting).
84
+
85
+ **lower** walks the CST into an *intermediate representation* (IR): a small,
86
+ dialect-neutral tree of nodes such as `QueryExpr`, `SelectExpr`, and `Expr` that
87
+ mean the same thing whether the SQL came from Snowflake or T-SQL. (In the API this
88
+ value is the `ast` field, the *abstract syntax tree*, a cleaned-up counterpart to
89
+ the CST.) It also tags each statement with its kind: a query, DML (data
90
+ manipulation: `INSERT` / `UPDATE` / `DELETE`), or DDL (data definition:
91
+ `CREATE` / `ALTER` / `DROP`). lower never throws, so even half-typed, broken SQL
92
+ still yields an IR the rest of the pipeline can run on.
93
+
94
+ **resolveScopes** builds a symbol table over the IR with no schema required. For
95
+ each query scope it works out the visible sources (tables, subqueries, and CTEs; a
96
+ *common table expression* is the `WITH name AS ()` temporary result set), resolves
97
+ names against them, and computes the query's output columns. It needs no catalog,
98
+ so the features it powers work on any file with zero configuration: go-to-definition,
99
+ find-references, and document highlight.
100
+
101
+ **qualify** is the first stage that takes a *schema*, the catalog of tables and
102
+ their column types. With it, qualify expands `SELECT *` into the real column list,
103
+ raises unknown-table and unknown-column diagnostics, and binds each column
104
+ reference to the source it comes from, with the column's type. This is what turns
105
+ on the schema-dependent semantic squiggles (an unknown column can only be flagged
106
+ once the schema is known) and answers `bindingOf`, which tells you which source a
107
+ given column resolves to.
108
+
109
+ **infer** computes the type and nullability of every expression, from a bare
110
+ column to `a + b`, `COALESCE(…)`, a `CASE`, or a function call. It powers hover
111
+ (the type shown when you point at an expression) and inlay hints (inline type
112
+ annotations).
113
+
114
+ **lineage** traces each output column back to the base-table columns it derives
115
+ from, through CTEs, subqueries, and joins, and records every hop on the way. It
116
+ powers the lineage panel and go-to-origin (jump from an output column to the
117
+ physical column it ultimately reads).
118
+
119
+ **symbols** derives a `Sym` model: every named thing (source, column, CTE),
120
+ classified by kind and modifier. It backs the editor outline / document-symbols
121
+ list and code-lens annotations.
122
+
123
+ ## Usage
124
+
125
+ Two ways in: `analyze` for one-shot analysis of a string, and a session for a
126
+ document you hold open and edit. Templated SQL (dbt models) is the same API with
127
+ one more option; it changes the input, not the shape of what you get back.
128
+ For a step-by-step walkthrough of the templated path, from a raw dbt model to
129
+ branch variants, see [TUTORIAL.md](TUTORIAL.md).
130
+
131
+ ### One-shot: `analyze`
132
+
133
+ `analyze` runs the whole pipeline and hands back a result you read directly:
134
+
135
+ ```ts
136
+ import { analyze, Schema } from "sqllens";
137
+
138
+ const schema = new Schema({ t: { a: "int", b: "string" } });
139
+ const a = analyze("SELECT a, b FROM t", "tsql", { schema });
140
+
141
+ a.scopes; // name resolution (ScopeTree)
142
+ a.diagnostics; // unknown-table / column diagnostics
143
+ a.qualification.columnsOf(a.scopes.root); // * expansion
144
+ a.types.typeOf(expr, scope); // per-expression types
145
+ a.lineage.originsOf("a"); // base-table origins of an output column
146
+ a.symbols; // kind × modifier symbol model
147
+ ```
148
+
149
+ ### A document you keep: the session
150
+
151
+ An editor holds a file that changes. The entry for that is a session: it parses on
152
+ construction, caches per statement, and an edit reuses everything it didn't touch.
153
+
154
+ ```ts
155
+ import { SqlSession, Schema } from "sqllens";
156
+
157
+ const s = SqlSession.create("SELECT amount FROM sales", "databricks", { schema });
158
+
159
+ // properties — cheap reads of what construction already produced
160
+ s.ast; // the dialect-neutral IR (frozen)
161
+ s.tokens; // the token stream: every token, exact spans present even mid-edit
162
+ s.scopes; // name resolution; needs no schema
163
+
164
+ // verbs parentheses execute a pass (memoized against the schema's version)
165
+ s.diagnostics(); // syntax + schema-fed, one document-ordered list
166
+ s.lineage(); // column lineage for the output columns
167
+ s.deriveSymbols(); // the outline / symbol model
168
+
169
+ // cursor verbs — offset in, spans out
170
+ s.completeAt(14); // completions at an offset (works on broken, mid-keystroke text)
171
+ s.referencesAt(9); // declaration + every occurrence of the symbol under the cursor
172
+ s.typeAt(9); // inferred type of the expression under the cursor
173
+
174
+ // edits are immutable: a new session, caches carried over
175
+ const next = s.withText("SELECT amount, id FROM sales");
176
+ ```
177
+
178
+ The convention throughout: properties are cheap, parentheses do work. Every verb
179
+ is a one-line delegation to a free function (`qualify`, `lineage`, `deriveSymbols`,
180
+ `referencesAt`, …) that stays exported, so a slim consumer can skip the session,
181
+ import only the functions it calls, and bundle nothing else.
182
+
183
+ ### Stage-wise building blocks
184
+
185
+ Every stage is also its own entry point, and each result is a value you can stop
186
+ at or pass to the next; hand a result forward and only the missing steps run:
187
+
188
+ ```ts
189
+ import { parse, qualify, lineage, deriveSymbols, toScopes, Schema } from "sqllens";
190
+
191
+ const { ast, errors, cst } = parse("SELECT a, b FROM t", "snowflake");
192
+ // ast = dialect-neutral IR (frozen); cst = the raw antlr tree (escape hatch)
193
+
194
+ const scopes = toScopes(ast, { dialect: "snowflake" }); // idempotent lift
195
+ qualify(scopes, schema); // reuses scopesnever re-parses or re-resolves
196
+ lineage(scopes, schema); // safe on the same scopes, in any order
197
+ deriveSymbols(scopes); // independent results
198
+ ```
199
+
200
+ The per-dialect entries (`parseDatabricks` … `parseTrino`, each `lower`, and the
201
+ raw `resolveScopes` / `inferType`) stay exported for callers that want a single
202
+ stage.
203
+
204
+ ### Templated SQL (dbt models)
205
+
206
+ A dbt model is not plain SQL; it is minijinja-templated SQL (`{{ ref('orders') }}`,
207
+ `{% if %}` …). sqllens parses that raw text natively, without rendering: tags get
208
+ exact spans, a `ref` in a FROM slot becomes a real table source that carries its
209
+ model name, and everything downstream (scopes, diagnostics, types, lineage,
210
+ completion) runs on the templated document unchanged.
211
+
212
+ Templating is declared, never guessed. You hand the session a template engine; no
213
+ engine means plain SQL:
214
+
215
+ ```ts
216
+ import { SqlSession } from "sqllens";
217
+ import { minijinja } from "sqllens/minijinja"; // its own entry point — plain-SQL consumers never load it
218
+
219
+ const s = SqlSession.create(modelText, "databricks", {
220
+ templating: minijinja(),
221
+ provider, // optional template knowledge, see extension points below
222
+ schema,
223
+ });
224
+
225
+ s.ast; // IR: {{ ref('orders') }} in FROM is a TableSource named "orders"
226
+ s.tokens; // ONE stream: SQL tokens + template tokens (channel 2, role "minijinja")
227
+ s.diagnostics(); // SQL + template + schema-fed, merged, all in document coordinates
228
+ s.tags; // every tag with exact spans (ref / source / macro / var / control)
229
+ s.regions; // {% if %} / {% for %} structure folding, branch enumeration
230
+ s.tagOf(node); // the tag an IR node came from; nodeOf(tag) goes the other way
231
+ ```
232
+
233
+ Why no auto-detection: `{{ }}` inside a SQL string literal is a template to dbt
234
+ and literal text to everyone else. No scanner can tell which was meant, and sqllens
235
+ never guesses. The host declares it (file association, language id, or config).
236
+ Declaring an engine on a file that turns out to have no tags costs nothing and
237
+ changes nothing: the result is byte-identical to a plain parse, with empty template
238
+ facets.
239
+
240
+ Everything works with no provider at all: the shipped defaults answer what they can
241
+ (a `ref` is a relation named by its literal argument; `config` renders nothing) and
242
+ everything else reports as unknown, never guessed. A provider only makes results
243
+ more precise.
244
+
245
+ ### Extension points
246
+
247
+ sqllens knows SQL and template *syntax*. Everything it cannot know (your catalog,
248
+ what your macros expand to, what `var('x')` holds) enters through three interfaces.
249
+ All are optional, and every one answers misses the same way: a miss is "unknown",
250
+ never a guess, and no diagnostic fires on missing knowledge.
251
+
252
+ `SchemaProvider` is the catalog: which tables exist, with their column types.
253
+ `Schema` is the upfront form (a plain mapping, as in the examples above).
254
+ `CallbackSchema` is the lazy form for hosts with a live catalog: sqllens records
255
+ what it missed, your `prime()` resolves the misses asynchronously and bumps a
256
+ version, and the next read reflects it. An LSP republishes diagnostics on exactly
257
+ that signal.
258
+
259
+ `TemplateProvider` is template knowledge: what template calls *mean*. Subclass
260
+ `DefaultTemplateProvider` and override only what your host knows; each method
261
+ answers one question:
262
+
263
+ ```ts
264
+ class MyDbtProvider extends DefaultTemplateProvider {
265
+ relationOf(call) { /* ref/source → the physical relation, with columns */ }
266
+ valueOf(call) { /* var/env_var → the scalar type it yields */ }
267
+ shapeOf(call) { /* a macro's expansion shape: "expr" | "predicate" | "column-list" | "statement" … */ }
268
+ columnsOf(call) { /* a column-list macro's output columns */ }
269
+ }
270
+ ```
271
+
272
+ One instance per document. Answers are synchronous, from a warm cache, with the
273
+ same miss-recording + `prime()` + version protocol as the schema. The base class
274
+ alone is fully functional; it is what the zero-provider examples above run on. The
275
+ payoff of each override is direct: `relationOf` turns "`{{ ref('orders') }}` is
276
+ exempt from checks" into "`orders` has these columns, and `o.totall` is a real
277
+ unknown-column diagnostic"; `shapeOf` makes a macro standing in a statement slot
278
+ parse cleanly; `valueOf` gives `{{ var('limit') }}` a type that inference can use.
279
+
280
+ `TemplateEngine` is template syntax, and is rare. The engine owns how templated
281
+ text is parsed; minijinja ships as the only implementation and nearly every
282
+ consumer just passes it. Implementing your own (another template language over SQL)
283
+ is supported, but it is a contract, not a callback: your result must satisfy the
284
+ invariants the conformance gates check. Tokens tile the source byte-for-byte, every
285
+ span is in original document coordinates, broken input never throws, and tag-free
286
+ text is identical to a plain parse.
287
+
288
+ ## Editor / language tooling
289
+
290
+ The front end is error-tolerant and token-first, so it serves editor features
291
+ that run on incomplete, mid-edit text. They never need a clean parse:
292
+
293
+ - `tokenize(sql, dialect)` and `parse(...).tokens` give a first-class token
294
+ stream: every token with its exact span, role, and channel. Available even when
295
+ the parse has errors.
296
+ - `lower()` never throws on broken or partial input; you get a flagged `query` IR
297
+ back, so every downstream pass stays total.
298
+ - `SqlDocument` is a persistent, immutable, position-addressable per-file model.
299
+ It runs `parse → resolveScopes` once (plus lazy `analyze(schema)`), caches the
300
+ result, and answers `tokenAt` / `nodeAt`. An edit yields a new document; an
301
+ O(log n) `LineIndex` maps positions to offsets.
302
+ - `completeAt(doc, offset, schema?)`: scope-aware completion (keywords, columns,
303
+ tables, functions) from an ATN (Augmented Transition Network, the grammar's
304
+ state-machine form) candidate walk over the grammar, our own, with no third-party
305
+ dependency.
306
+ - `signatureAt(doc, offset)`: parameter hints from a curated per-dialect
307
+ function-signature table; the long tail degrades to name + active-argument.
308
+ - `referencesAt(scopes, offset, schema?)`: every occurrence (plus the declaration)
309
+ of the symbol under the cursor; backs find-references, document highlight, and
310
+ code-lens reference counts.
311
+
312
+ ```ts
313
+ import { SqlDocument, Schema } from "sqllens";
314
+
315
+ const doc = SqlDocument.create("SELECT amount FROM sales", "databricks");
316
+ doc.tokens; // first-class token stream (spans + roles)
317
+ doc.tokenAt(7); // token under an offset
318
+ const next = doc.withText("SELECT amount, id FROM sales", 2); // immutable edit → new doc
319
+ ```
320
+
321
+ ## Language server (experimental)
322
+
323
+ An LSP (Language Server Protocol) server built on the library lives in `src/lsp/`.
324
+ It is experimental and **not part of the published npm package**: the package ships
325
+ the library only, and the server is source you run from the repo. It holds one
326
+ `SqlDocument` per open file (rebuilt on edit) and reaches the library only through
327
+ the public API, and adds no analysis of its own beyond protocol translation.
328
+
329
+ A SQL server needs only a subset of LSP's ~30 request types: some don't apply to
330
+ SQL (type hierarchy, document color, monikers), and a few are deferred (formatting,
331
+ project-wide navigation). Where the server stands today, feature by feature:
332
+
333
+ ### Language features
334
+
335
+ | Feature | Status |
336
+ | --- | --- |
337
+ | Completion (+ resolve) | ✅ |
338
+ | Hover | ✅ |
339
+ | Hover — nullability | ✅ (` — not null` / ` — nullable` suffix when provable) |
340
+ | Signature help | ✅ |
341
+ | Go to definition | ✅ |
342
+ | Find references | ✅ |
343
+ | Document highlight | ✅ |
344
+ | Document symbols | ✅ |
345
+ | Folding range | ✅ |
346
+ | Selection range | ✅ |
347
+ | Semantic tokens (full / range / delta) | ✅ all three |
348
+ | Inlay hints | ✅ (no resolve) |
349
+ | Code lens | ✅ (no resolve) |
350
+ | Go to declaration | ◻️ not yet |
351
+ | Go to type definition | ◻️ not yet |
352
+ | Go to implementation | ◻️ not yet — name → its defining query (view / model); needs the project model |
353
+ | Call hierarchy | ◻️ not yet — the CTE / view / model dependency graph |
354
+ | Document link | ◻️ not yet |
355
+ | Linked editing range | ◻️ not yet — live alias / name sync-edit |
356
+ | Code action (quick fixes) | ◻️ next phase |
357
+ | Rename (+ prepare) | ◻️ next phase |
358
+ | Formatting / range / on-type | ◻️ deferred (external formatter) |
359
+ | Inline values | ◻️ debugger surface |
360
+ | Type hierarchy | — n/a — SQL has no type-inheritance relation |
361
+ | Document color | — n/a — no color literals |
362
+ | Moniker | — n/a — LSIF / cross-repo indexing concern |
363
+
364
+ ### Diagnostics & document sync
365
+
366
+ | Feature | Status |
367
+ | --- | --- |
368
+ | Diagnostics — push (`publishDiagnostics`) | ✅ |
369
+ | Diagnostics — call signature (arity / argument type) | ✅ (curated tables; never-wrong, per-dialect coercion) |
370
+ | Diagnostics — pull (document) | ✅ |
371
+ | Diagnostics — pull (workspace) | ◻️ not yet |
372
+ | Text sync — open / change / close | ✅ (full-document) |
373
+ | Incremental sync | ◻️ full-document only (fine at SQL file sizes) |
374
+ | Save notifications (`didSave` / `willSave`) | ◻️ not yet |
375
+ | Notebook document sync | ◻️ not yet |
376
+
377
+ ### Workspace features
378
+
379
+ | Feature | Status |
380
+ | --- | --- |
381
+ | Workspace symbols | ◻️ needs a project / multi-file model |
382
+ | Execute command | ◻️ not yet |
383
+ | Configuration / watched-files | ◻️ not yet (protocol config; file-based `.sqllens.json` config exists) |
384
+ | File operations (create / rename / delete) | ◻️ not yet |
385
+
386
+ Legend: ✅ implemented · ◻️ not yet / deferred · — not applicable to SQL. The
387
+ deferred items are tracked work: rename and
388
+ code actions are the next LSP phase, workspace symbols need the project model,
389
+ and formatting is expected to wrap an existing external formatter.
390
+
391
+ ## Architecture
392
+
393
+ One folder per dialect; no shared "core" grammar and no grammar inheritance. Each
394
+ dialect is a standalone pair of split `.g4` files (a lexer grammar + a parser
395
+ grammar), forked from its best starting point and edited in place. Everything
396
+ downstream of `lower` is shared and dialect-neutral.
397
+
398
+ ## Building from source & contributing
399
+
400
+ `npm install sqllens` needs no build step on your side. To build it yourself from
401
+ source, or to work on a grammar, you regenerate the parsers from the `.g4` files
402
+ first. [CONTRIBUTING.md](CONTRIBUTING.md) has the setup, the command list, and the
403
+ corpus-gate workflow.
404
+
405
+ ## License
406
+
407
+ MIT. See [LICENSE](LICENSE). The forked grammars under `grammars/` keep their
408
+ upstream licenses (Apache-2.0 for Databricks; MIT for T-SQL and Snowflake; BSD-3
409
+ for BigQuery and Redshift); see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).