@questdb/sql-parser 0.1.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.
- package/CHANGELOG.md +4 -0
- package/LICENSE +190 -0
- package/README.md +228 -0
- package/dist/autocomplete/content-assist.d.ts +52 -0
- package/dist/autocomplete/index.d.ts +5 -0
- package/dist/autocomplete/provider.d.ts +20 -0
- package/dist/autocomplete/suggestion-builder.d.ts +16 -0
- package/dist/autocomplete/token-classification.d.ts +45 -0
- package/dist/autocomplete/types.d.ts +78 -0
- package/dist/grammar/constants.d.ts +1 -0
- package/dist/grammar/dataTypes.d.ts +1 -0
- package/dist/grammar/functions.d.ts +1 -0
- package/dist/grammar/index.cjs +709 -0
- package/dist/grammar/index.d.ts +5 -0
- package/dist/grammar/index.js +678 -0
- package/dist/grammar/keywords.d.ts +1 -0
- package/dist/grammar/operators.d.ts +1 -0
- package/dist/index.cjs +10363 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +10302 -0
- package/dist/parser/ast.d.ts +794 -0
- package/dist/parser/lexer.d.ts +53 -0
- package/dist/parser/parser.d.ts +170 -0
- package/dist/parser/toSql.d.ts +2 -0
- package/dist/parser/tokens.d.ts +311 -0
- package/dist/parser/visitor.d.ts +191 -0
- package/package.json +88 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2025 QuestDB
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# @questdb/sql-parser
|
|
2
|
+
|
|
3
|
+
An SQL parser for [QuestDB](https://questdb.io/) syntax, built with [Chevrotain](https://chevrotain.io/). Parses SQL into a fully typed AST, converts AST back to SQL, and provides context-aware autocomplete — all in a single package.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Complete QuestDB SQL coverage** — 45 statement types including SELECT, INSERT, UPDATE, CREATE TABLE, ALTER TABLE, GRANT/REVOKE, COPY, PIVOT, and more
|
|
8
|
+
- **QuestDB-specific syntax** — `SAMPLE BY`, `LATEST ON`, `ASOF JOIN`, `LT JOIN`, `SPLICE JOIN`, `WINDOW JOIN`, implicit SELECT, duration literals, geohash types
|
|
9
|
+
- **Lossless round-trip** — parse SQL to AST and convert back with `toSql()`. Verified against 1,726 real-world queries from QuestDB documentation with full round-trip coverage
|
|
10
|
+
- **Context-aware autocomplete** — schema-driven suggestions for tables, columns, keywords, functions, and operators at any cursor position
|
|
11
|
+
- **Fully typed** — complete TypeScript type definitions for the entire AST
|
|
12
|
+
- **Single dependency** — only Chevrotain at runtime
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
## Quick Start
|
|
16
|
+
|
|
17
|
+
### Parse SQL to AST
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { parseToAst } from "@questdb/sql-parser";
|
|
21
|
+
|
|
22
|
+
const result = parseToAst("SELECT * FROM trades WHERE symbol = 'BTC-USD'");
|
|
23
|
+
|
|
24
|
+
if (result.errors.length === 0) {
|
|
25
|
+
console.log(result.ast[0]);
|
|
26
|
+
// {
|
|
27
|
+
// type: "select",
|
|
28
|
+
// columns: [{ type: "star" }],
|
|
29
|
+
// from: [{ type: "tableRef", table: { type: "qualifiedName", parts: ["trades"] } }],
|
|
30
|
+
// where: {
|
|
31
|
+
// type: "binary", operator: "=",
|
|
32
|
+
// left: { type: "column", name: { type: "qualifiedName", parts: ["symbol"] } },
|
|
33
|
+
// right: { type: "literal", value: "BTC-USD", literalType: "string" }
|
|
34
|
+
// }
|
|
35
|
+
// }
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Convert AST back to SQL
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
import { parseToAst, toSql } from "@questdb/sql-parser";
|
|
43
|
+
|
|
44
|
+
const result = parseToAst("SELECT avg(price) FROM trades SAMPLE BY 1h FILL(PREV)");
|
|
45
|
+
const sql = toSql(result.ast);
|
|
46
|
+
// "SELECT avg(price) FROM trades SAMPLE BY 1h FILL(PREV)"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Parse a single statement
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { parseOne } from "@questdb/sql-parser";
|
|
53
|
+
|
|
54
|
+
const stmt = parseOne("INSERT INTO trades VALUES (now(), 'BTC', 42000.50)");
|
|
55
|
+
console.log(stmt.type); // "insert"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Parse multiple statements
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
import { parseStatements } from "@questdb/sql-parser";
|
|
62
|
+
|
|
63
|
+
const statements = parseStatements(`
|
|
64
|
+
SELECT * FROM trades
|
|
65
|
+
INSERT INTO logs VALUES (1)
|
|
66
|
+
CREATE TABLE orders (id LONG, ts TIMESTAMP) TIMESTAMP(ts) PARTITION BY DAY WAL
|
|
67
|
+
`);
|
|
68
|
+
|
|
69
|
+
console.log(statements.length); // 3
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Autocomplete
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
import { createAutocompleteProvider } from "@questdb/sql-parser";
|
|
76
|
+
|
|
77
|
+
const provider = createAutocompleteProvider({
|
|
78
|
+
tables: [
|
|
79
|
+
{ name: "trades", designatedTimestamp: "ts" },
|
|
80
|
+
{ name: "orders" },
|
|
81
|
+
],
|
|
82
|
+
columns: {
|
|
83
|
+
trades: [
|
|
84
|
+
{ name: "ts", type: "TIMESTAMP" },
|
|
85
|
+
{ name: "symbol", type: "SYMBOL" },
|
|
86
|
+
{ name: "price", type: "DOUBLE" },
|
|
87
|
+
],
|
|
88
|
+
orders: [
|
|
89
|
+
{ name: "id", type: "LONG" },
|
|
90
|
+
{ name: "created_at", type: "TIMESTAMP" },
|
|
91
|
+
],
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const suggestions = provider.getSuggestions("SELECT * FROM t", 16);
|
|
96
|
+
// [{ label: "trades", kind: "Table", insertText: "trades", ... }, ...]
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Supported Statements
|
|
100
|
+
|
|
101
|
+
| Category | Statements |
|
|
102
|
+
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
103
|
+
| **Query** | `SELECT`, implicit SELECT, `PIVOT`, `EXPLAIN` |
|
|
104
|
+
| **DML** | `INSERT`, `INSERT ATOMIC`, `INSERT BATCH`, `UPDATE` |
|
|
105
|
+
| **DDL** | `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`, `TRUNCATE TABLE`, `RENAME TABLE` |
|
|
106
|
+
| **Views** | `CREATE VIEW`, `ALTER VIEW`, `DROP VIEW`, `COMPILE VIEW` |
|
|
107
|
+
| **Materialized Views** | `CREATE MATERIALIZED VIEW`, `ALTER MATERIALIZED VIEW`, `DROP MATERIALIZED VIEW`, `REFRESH MATERIALIZED VIEW` |
|
|
108
|
+
| **Access Control** | `CREATE/ALTER/DROP USER`, `CREATE/ALTER/DROP GROUP`, `CREATE/ALTER/DROP SERVICE ACCOUNT`, `ADD/REMOVE USER`, `ASSUME/EXIT SERVICE ACCOUNT` |
|
|
109
|
+
| **Permissions** | `GRANT`, `REVOKE`, `GRANT/REVOKE ASSUME SERVICE ACCOUNT` |
|
|
110
|
+
| **Operations** | `COPY FROM/TO`, `BACKUP`, `VACUUM TABLE`, `REINDEX TABLE`, `CANCEL QUERY`, `CHECKPOINT`, `SNAPSHOT` |
|
|
111
|
+
| **WAL** | `RESUME WAL`, `SET TYPE WAL` |
|
|
112
|
+
| **Introspection** | `SHOW TABLES/COLUMNS/PARTITIONS/CREATE TABLE/PARAMETERS/...` |
|
|
113
|
+
|
|
114
|
+
## QuestDB-Specific Syntax
|
|
115
|
+
|
|
116
|
+
The parser handles QuestDB extensions that standard SQL parsers don't support:
|
|
117
|
+
|
|
118
|
+
```sql
|
|
119
|
+
-- Time-series sampling
|
|
120
|
+
SELECT avg(price) FROM trades SAMPLE BY 1h FILL(PREV) ALIGN TO CALENDAR
|
|
121
|
+
|
|
122
|
+
-- Latest value per partition
|
|
123
|
+
SELECT * FROM trades LATEST ON ts PARTITION BY symbol
|
|
124
|
+
|
|
125
|
+
-- Time-ordered joins
|
|
126
|
+
SELECT * FROM trades ASOF JOIN quotes ON (symbol)
|
|
127
|
+
SELECT * FROM trades LT JOIN quotes ON (symbol) TOLERANCE 5s
|
|
128
|
+
SELECT * FROM a WINDOW JOIN b ON a.ts = b.ts
|
|
129
|
+
RANGE BETWEEN 1h PRECEDING AND CURRENT ROW FOLLOWING
|
|
130
|
+
|
|
131
|
+
-- Implicit SELECT (table name without SELECT * FROM)
|
|
132
|
+
trades WHERE symbol = 'BTC-USD'
|
|
133
|
+
|
|
134
|
+
-- Duration literals
|
|
135
|
+
SELECT * FROM trades WHERE ts > now() - 2d
|
|
136
|
+
|
|
137
|
+
-- Geohash literals and types
|
|
138
|
+
CREATE TABLE geo (pos GEOHASH(8c), area GEOHASH(4b))
|
|
139
|
+
|
|
140
|
+
-- Array subscripts and slices
|
|
141
|
+
SELECT arr[2:], data[1:3] FROM t
|
|
142
|
+
|
|
143
|
+
-- WAL tables with deduplication and TTL
|
|
144
|
+
CREATE TABLE trades (ts TIMESTAMP, price DOUBLE)
|
|
145
|
+
TIMESTAMP(ts) PARTITION BY DAY WAL
|
|
146
|
+
DEDUP UPSERT KEYS(ts)
|
|
147
|
+
TTL 30 DAYS
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Architecture
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
SQL String
|
|
154
|
+
|
|
|
155
|
+
v
|
|
156
|
+
Lexer (tokenize)
|
|
157
|
+
|
|
|
158
|
+
v
|
|
159
|
+
Tokens
|
|
160
|
+
|
|
|
161
|
+
v
|
|
162
|
+
Parser (Chevrotain CstParser)
|
|
163
|
+
|
|
|
164
|
+
v
|
|
165
|
+
Concrete Syntax Tree (CST)
|
|
166
|
+
|
|
|
167
|
+
v
|
|
168
|
+
Visitor (CST -> AST)
|
|
169
|
+
|
|
|
170
|
+
v
|
|
171
|
+
AST -----> toSql() -----> SQL String
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The parser uses Chevrotain's [CST pattern](https://chevrotain.io/docs/guide/concrete_syntax_tree.html): the parser produces a lossless CST, then a visitor transforms it into a clean, typed AST. The `toSql()` function serializes any AST back to valid SQL.
|
|
175
|
+
|
|
176
|
+
## API Reference
|
|
177
|
+
|
|
178
|
+
### High-Level API
|
|
179
|
+
|
|
180
|
+
| Function | Description |
|
|
181
|
+
| ---------------------- | ----------------------------------------------------------------- |
|
|
182
|
+
| `parseToAst(sql)` | Parse SQL string into `{ ast: Statement[], errors: Error[] }` |
|
|
183
|
+
| `parseOne(sql)` | Parse a single statement, throws on errors or multiple statements |
|
|
184
|
+
| `parseStatements(sql)` | Parse multiple statements, throws on errors |
|
|
185
|
+
| `toSql(ast)` | Convert `Statement[]` back to a SQL string |
|
|
186
|
+
|
|
187
|
+
### Low-Level API
|
|
188
|
+
|
|
189
|
+
| Function | Description |
|
|
190
|
+
| --------------- | --------------------------------------------------------- |
|
|
191
|
+
| `tokenize(sql)` | Tokenize SQL into Chevrotain tokens |
|
|
192
|
+
| `parse(sql)` | Parse SQL to CST with lex/parse errors |
|
|
193
|
+
| `visitor` | Chevrotain CST visitor instance for CST-to-AST conversion |
|
|
194
|
+
|
|
195
|
+
### Autocomplete API
|
|
196
|
+
|
|
197
|
+
| Function | Description |
|
|
198
|
+
| ------------------------------------ | ------------------------------------------------------------ |
|
|
199
|
+
| `createAutocompleteProvider(schema)` | Create a provider with `getSuggestions(query, cursorOffset)` |
|
|
200
|
+
| `getContentAssist(sql, offset)` | Low-level: get valid tokens at cursor position |
|
|
201
|
+
|
|
202
|
+
### Grammar Exports
|
|
203
|
+
|
|
204
|
+
Arrays of keywords, functions, data types, operators, and constants for syntax highlighting integration:
|
|
205
|
+
|
|
206
|
+
```typescript
|
|
207
|
+
import { keywords, functions, dataTypes, operators, constants } from "@questdb/sql-parser/grammar";
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Development
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
yarn # Install dependencies
|
|
214
|
+
yarn build # Compile TypeScript (tsup + tsc)
|
|
215
|
+
yarn test # Run all tests (6,100+ tests)
|
|
216
|
+
yarn test:watch # Run tests in watch mode
|
|
217
|
+
yarn typecheck # Type-check without emitting
|
|
218
|
+
yarn lint # Run ESLint
|
|
219
|
+
yarn lint:fix # Auto-fix lint issues
|
|
220
|
+
yarn generate:cst # Regenerate CST type definitions from parser grammar
|
|
221
|
+
yarn clean # Remove dist/ and coverage/
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
See [DEVELOPMENT.md](DEVELOPMENT.md) for the full development workflow guide — how to add keywords, statement types, modify autocomplete, and more.
|
|
225
|
+
|
|
226
|
+
## License
|
|
227
|
+
|
|
228
|
+
Apache-2.0
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type ILexingError, IToken, TokenType } from "chevrotain";
|
|
2
|
+
/**
|
|
3
|
+
* A table reference found in the SQL query
|
|
4
|
+
*/
|
|
5
|
+
export interface TableRef {
|
|
6
|
+
/** The table name */
|
|
7
|
+
table: string;
|
|
8
|
+
/** Optional alias */
|
|
9
|
+
alias?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Result from content assist analysis
|
|
13
|
+
*/
|
|
14
|
+
export interface ContentAssistResult {
|
|
15
|
+
/** Token types that are syntactically valid at the cursor position */
|
|
16
|
+
nextTokenTypes: TokenType[];
|
|
17
|
+
/** Tables/aliases found in the query (for column suggestions) */
|
|
18
|
+
tablesInScope: TableRef[];
|
|
19
|
+
/** Columns from CTEs, keyed by CTE name (lowercase) */
|
|
20
|
+
cteColumns: Record<string, {
|
|
21
|
+
name: string;
|
|
22
|
+
type: string;
|
|
23
|
+
}[]>;
|
|
24
|
+
/** The tokens before the cursor */
|
|
25
|
+
tokensBefore: IToken[];
|
|
26
|
+
/** Whether the cursor is in the middle of a word (partial token being typed) */
|
|
27
|
+
isMidWord: boolean;
|
|
28
|
+
/** Any lexer errors */
|
|
29
|
+
lexErrors: ILexingError[];
|
|
30
|
+
/**
|
|
31
|
+
* When the cursor is after a qualified reference (e.g., "t1." or "trades."),
|
|
32
|
+
* this contains the qualifier name (e.g., "t1" or "trades"). The provider
|
|
33
|
+
* should resolve this against tablesInScope aliases/names to filter columns.
|
|
34
|
+
*/
|
|
35
|
+
qualifiedTableRef?: string;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Get content assist suggestions for a SQL string at a given cursor position
|
|
39
|
+
*
|
|
40
|
+
* @param fullSql - The complete SQL string
|
|
41
|
+
* @param cursorOffset - The cursor position (0-indexed character offset)
|
|
42
|
+
* @returns Content assist result with next valid tokens and tables in scope
|
|
43
|
+
*/
|
|
44
|
+
export declare function getContentAssist(fullSql: string, cursorOffset: number): ContentAssistResult;
|
|
45
|
+
/**
|
|
46
|
+
* Simplified version that just returns next valid token names
|
|
47
|
+
*/
|
|
48
|
+
export declare function getNextValidTokens(sql: string): string[];
|
|
49
|
+
/**
|
|
50
|
+
* Check if a token type is expected at the current position
|
|
51
|
+
*/
|
|
52
|
+
export declare function isTokenExpected(sql: string, tokenName: string): boolean;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createAutocompleteProvider } from "./provider";
|
|
2
|
+
export type { AutocompleteProvider, Suggestion, SchemaInfo, TableInfo, ColumnInfo, } from "./types";
|
|
3
|
+
export { SuggestionKind, SuggestionPriority } from "./types";
|
|
4
|
+
export { IDENTIFIER_TOKENS, IDENTIFIER_KEYWORD_TOKENS, SKIP_TOKENS, tokenNameToKeyword, isIdentifierToken, shouldSkipToken, } from "./token-classification";
|
|
5
|
+
export { buildSuggestions } from "./suggestion-builder";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { AutocompleteProvider, SchemaInfo } from "./types";
|
|
2
|
+
/**
|
|
3
|
+
* Create an autocomplete provider with the given schema
|
|
4
|
+
*
|
|
5
|
+
* @param schema - Schema information (tables and columns)
|
|
6
|
+
* @returns AutocompleteProvider instance
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* const provider = createAutocompleteProvider({
|
|
11
|
+
* tables: [{ name: "trades" }],
|
|
12
|
+
* columns: { trades: [{ name: "symbol", type: "STRING" }] },
|
|
13
|
+
* });
|
|
14
|
+
*
|
|
15
|
+
* // Get suggestions after "SELECT "
|
|
16
|
+
* const suggestions = provider.getSuggestions("SELECT FROM trades", 7);
|
|
17
|
+
* // suggestions will include "symbol" column from trades
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare function createAutocompleteProvider(schema: SchemaInfo): AutocompleteProvider;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { TokenType } from "chevrotain";
|
|
2
|
+
import { Suggestion, SchemaInfo } from "./types";
|
|
3
|
+
import type { TableRef } from "./content-assist";
|
|
4
|
+
/**
|
|
5
|
+
* Build suggestions from parser's nextTokenTypes
|
|
6
|
+
*
|
|
7
|
+
* @param tokenTypes - Valid next tokens from parser.computeContentAssist()
|
|
8
|
+
* @param schema - Schema information (tables, columns)
|
|
9
|
+
* @param tablesInScope - Tables found in the query
|
|
10
|
+
* @returns Array of suggestions
|
|
11
|
+
*/
|
|
12
|
+
export declare function buildSuggestions(tokenTypes: TokenType[], schema: SchemaInfo, tablesInScope: TableRef[], options?: {
|
|
13
|
+
includeColumns?: boolean;
|
|
14
|
+
includeTables?: boolean;
|
|
15
|
+
isMidWord?: boolean;
|
|
16
|
+
}): Suggestion[];
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token types that represent actual identifiers
|
|
3
|
+
*/
|
|
4
|
+
export declare const IDENTIFIER_TOKENS: Set<string>;
|
|
5
|
+
/**
|
|
6
|
+
* Keywords that can be used as identifiers in the grammar.
|
|
7
|
+
*
|
|
8
|
+
* These are tokens that appear as alternatives in the parser's `identifier` rule.
|
|
9
|
+
* When these appear in nextTokenTypes, it means an identifier/column is expected,
|
|
10
|
+
* so we should suggest columns and tables, not these keywords.
|
|
11
|
+
*
|
|
12
|
+
* Derived from IDENTIFIER_KEYWORD_NAMES in tokens.ts — single source of truth.
|
|
13
|
+
*/
|
|
14
|
+
export declare const IDENTIFIER_KEYWORD_TOKENS: Set<string>;
|
|
15
|
+
/**
|
|
16
|
+
* Expression-continuation operators that are valid after any expression but
|
|
17
|
+
* should be deprioritized so clause-level keywords (ASC, DESC, LIMIT, etc.)
|
|
18
|
+
* appear first in the suggestion list.
|
|
19
|
+
*/
|
|
20
|
+
export declare const EXPRESSION_OPERATORS: Set<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Punctuation tokens — worth suggesting in fallback (e.g., "(" after "VALUES (1), ")
|
|
23
|
+
*/
|
|
24
|
+
export declare const PUNCTUATION_TOKENS: Set<string>;
|
|
25
|
+
/**
|
|
26
|
+
* Token types that should NOT be suggested (internal/structural tokens)
|
|
27
|
+
*/
|
|
28
|
+
export declare const SKIP_TOKENS: Set<string>;
|
|
29
|
+
/**
|
|
30
|
+
* Operator map for converting token names to display strings
|
|
31
|
+
*/
|
|
32
|
+
export declare const OPERATOR_MAP: Record<string, string>;
|
|
33
|
+
/**
|
|
34
|
+
* Convert a token type name to a keyword string for display
|
|
35
|
+
* e.g., "Table" → "TABLE", "DataPageSize" → "DATA_PAGE_SIZE"
|
|
36
|
+
*/
|
|
37
|
+
export declare function tokenNameToKeyword(name: string): string;
|
|
38
|
+
/**
|
|
39
|
+
* Check if a token represents an identifier context
|
|
40
|
+
*/
|
|
41
|
+
export declare function isIdentifierToken(tokenName: string): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Check if a token should be skipped in suggestions
|
|
44
|
+
*/
|
|
45
|
+
export declare function shouldSkipToken(tokenName: string): boolean;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Kind of suggestion - maps to Monaco CompletionItemKind in the UI
|
|
3
|
+
*/
|
|
4
|
+
export declare enum SuggestionKind {
|
|
5
|
+
Keyword = "keyword",
|
|
6
|
+
Function = "function",
|
|
7
|
+
Table = "table",
|
|
8
|
+
Column = "column",
|
|
9
|
+
Operator = "operator",
|
|
10
|
+
DataType = "dataType"
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Priority for sorting suggestions
|
|
14
|
+
*/
|
|
15
|
+
export declare enum SuggestionPriority {
|
|
16
|
+
High = 1,
|
|
17
|
+
Medium = 2,
|
|
18
|
+
MediumLow = 3,
|
|
19
|
+
Low = 4
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A generic autocomplete suggestion
|
|
23
|
+
*/
|
|
24
|
+
export interface Suggestion {
|
|
25
|
+
/** Display label */
|
|
26
|
+
label: string;
|
|
27
|
+
/** Kind of suggestion */
|
|
28
|
+
kind: SuggestionKind;
|
|
29
|
+
/** Text to insert when selected */
|
|
30
|
+
insertText: string;
|
|
31
|
+
/** Text used for filtering (optional, defaults to label) */
|
|
32
|
+
filterText?: string;
|
|
33
|
+
/** Sort priority (lower = higher priority) */
|
|
34
|
+
priority: SuggestionPriority;
|
|
35
|
+
/** Additional detail text shown inline after label (e.g., " (trades)") */
|
|
36
|
+
detail?: string;
|
|
37
|
+
/** Description text shown on the right side (e.g., "DOUBLE") */
|
|
38
|
+
description?: string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Column information for schema-aware suggestions
|
|
42
|
+
*/
|
|
43
|
+
export interface ColumnInfo {
|
|
44
|
+
/** Column name */
|
|
45
|
+
name: string;
|
|
46
|
+
/** Column data type (e.g., "STRING", "DOUBLE", "TIMESTAMP") */
|
|
47
|
+
type: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Table information for schema-aware suggestions
|
|
51
|
+
*/
|
|
52
|
+
export interface TableInfo {
|
|
53
|
+
/** Table name */
|
|
54
|
+
name: string;
|
|
55
|
+
/** Designated timestamp column (if any) */
|
|
56
|
+
designatedTimestamp?: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Schema information passed to the autocomplete provider
|
|
60
|
+
*/
|
|
61
|
+
export interface SchemaInfo {
|
|
62
|
+
/** Available tables */
|
|
63
|
+
tables: TableInfo[];
|
|
64
|
+
/** Columns indexed by table name (lowercase) */
|
|
65
|
+
columns: Record<string, ColumnInfo[]>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Autocomplete provider interface
|
|
69
|
+
*/
|
|
70
|
+
export interface AutocompleteProvider {
|
|
71
|
+
/**
|
|
72
|
+
* Get suggestions for a SQL query at the given cursor position
|
|
73
|
+
* @param query - The SQL query string
|
|
74
|
+
* @param cursorOffset - Cursor position (0-indexed character offset)
|
|
75
|
+
* @returns Array of suggestions
|
|
76
|
+
*/
|
|
77
|
+
getSuggestions(query: string, cursorOffset: number): Suggestion[];
|
|
78
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const constants: string[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const dataTypes: string[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const functions: string[];
|