@memberjunction/sql-parser 5.37.0 → 5.39.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/dist/ASTDialectAdapter.d.ts +58 -0
- package/dist/ASTDialectAdapter.d.ts.map +1 -0
- package/dist/ASTDialectAdapter.js +113 -0
- package/dist/ASTDialectAdapter.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/sql-parser.d.ts +225 -4
- package/dist/sql-parser.d.ts.map +1 -1
- package/dist/sql-parser.js +631 -9
- package/dist/sql-parser.js.map +1 -1
- package/package.json +2 -2
package/dist/sql-parser.js
CHANGED
|
@@ -16,6 +16,7 @@ import NodeSqlParser from 'node-sql-parser';
|
|
|
16
16
|
const { Parser } = NodeSqlParser;
|
|
17
17
|
import { MJLexer } from './mj-lexer.js';
|
|
18
18
|
import { MJPlaceholderSubstitution } from './mj-placeholder.js';
|
|
19
|
+
import { getASTDialectAdapter } from './ASTDialectAdapter.js';
|
|
19
20
|
// ═══════════════════════════════════════════════════
|
|
20
21
|
// SQLParser class
|
|
21
22
|
// ═══════════════════════════════════════════════════
|
|
@@ -26,9 +27,59 @@ import { MJPlaceholderSubstitution } from './mj-placeholder.js';
|
|
|
26
27
|
* Nunjucks block tags (`{% if %}...{% endif %}`), composition tokens
|
|
27
28
|
* (`{{query:"Path/Name(params)"}}`), and template comments (`{# ... #}`).
|
|
28
29
|
*
|
|
29
|
-
*
|
|
30
|
+
* Two-tier API:
|
|
31
|
+
* - **Instance** (`new SQLParser(sql, dialect)`) — parses once (with a
|
|
32
|
+
* preprocessing fallback) and exposes typed, dialect-neutral AST
|
|
33
|
+
* inspection/mutation (`StatementKind`, `OuterCap`, `SetOuterCap`,
|
|
34
|
+
* `ToSQL`) plus extraction helpers (`ExtractCTEs`, `ExtractTableRefs`,
|
|
35
|
+
* `ExtractColumnRefs`, `ExtractSelectColumns`).
|
|
36
|
+
* - **Static utilities** — pure string/token operations that need no parsed
|
|
37
|
+
* state (`StripComments`, `Tokenize`, `Analyze`, `ParseSQL`, `SqlifyAST`,
|
|
38
|
+
* `HasUnwrappableTrailingClause`, the MJ-template helpers, etc.).
|
|
30
39
|
*/
|
|
31
40
|
export class SQLParser {
|
|
41
|
+
/**
|
|
42
|
+
* Parse SQL into an instance exposing dialect-neutral AST inspection,
|
|
43
|
+
* mutation, and extraction.
|
|
44
|
+
*
|
|
45
|
+
* On a direct-parse failure, applies preprocessing fallbacks — splitting a
|
|
46
|
+
* trailing `OPTION (...)` clause and aliasing bracket-quoted identifiers
|
|
47
|
+
* whose interior contains parser-defeating characters (`[Active People]`,
|
|
48
|
+
* `[my-cte]`) — so a wider class of SQL becomes AST-addressable. {@link ToSQL}
|
|
49
|
+
* transparently restores both transforms.
|
|
50
|
+
*
|
|
51
|
+
* Never throws on unparseable SQL — check {@link IsValid}.
|
|
52
|
+
*/
|
|
53
|
+
constructor(sql, dialect) {
|
|
54
|
+
this._sql = sql;
|
|
55
|
+
this._dialect = dialect;
|
|
56
|
+
this._adapter = getASTDialectAdapter(dialect);
|
|
57
|
+
// Fast path: direct parse (matches the old static ParseSQL contract).
|
|
58
|
+
const direct = SQLParser.parseSQL(sql, dialect.ParserDialect);
|
|
59
|
+
if (direct) {
|
|
60
|
+
this._ast = direct;
|
|
61
|
+
this._aliasMap = null;
|
|
62
|
+
this._trailingOption = null;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
// Fallback: preprocess (OPTION split, then bracket aliasing) and retry.
|
|
66
|
+
const pre = SQLParser.preprocessForParse(sql, dialect);
|
|
67
|
+
this._ast = pre.ast;
|
|
68
|
+
this._aliasMap = pre.aliasMap;
|
|
69
|
+
this._trailingOption = pre.trailingOption;
|
|
70
|
+
}
|
|
71
|
+
/** Whether the SQL parsed into an AST (directly or via preprocessing). */
|
|
72
|
+
get IsValid() {
|
|
73
|
+
return this._ast !== null;
|
|
74
|
+
}
|
|
75
|
+
/** The raw AST. Prefer the typed accessors; this is an escape hatch. */
|
|
76
|
+
get AST() {
|
|
77
|
+
return this._ast;
|
|
78
|
+
}
|
|
79
|
+
/** The dialect supplied at construction. */
|
|
80
|
+
get Dialect() {
|
|
81
|
+
return this._dialect;
|
|
82
|
+
}
|
|
32
83
|
/**
|
|
33
84
|
* Fixes a known node-sql-parser bug where CAST(x AS NVARCHAR(MAX)) is
|
|
34
85
|
* serialized as CAST(x AS NVARCHARmax). Applies to NVARCHAR, VARCHAR,
|
|
@@ -109,6 +160,299 @@ export class SQLParser {
|
|
|
109
160
|
const sql = parser.sqlify(Array.isArray(ast) ? ast[0] : ast, { database: dialect.ParserDialect });
|
|
110
161
|
return SQLParser.fixMaxTypeSerialization(sql);
|
|
111
162
|
}
|
|
163
|
+
// ─── AST primitives (instance) ──────────────────────
|
|
164
|
+
//
|
|
165
|
+
// These operate on the instance's parsed AST and hide node-sql-parser's
|
|
166
|
+
// shape behind typed, dialect-neutral accessors. The shape of `top`,
|
|
167
|
+
// `limit`, `into`, `set_op`, etc. is confined to this region and to
|
|
168
|
+
// ASTDialectAdapter — the only places that track those details.
|
|
169
|
+
//
|
|
170
|
+
// All inspect the FIRST statement only (matching SqlifyAST, which
|
|
171
|
+
// serializes only the first); MJ query SQL is single-statement.
|
|
172
|
+
/**
|
|
173
|
+
* High-level classification of the parsed statement:
|
|
174
|
+
* `'select'` | `'select-into'` | `'set-op'` | `'mutation'` | `'other'`.
|
|
175
|
+
*/
|
|
176
|
+
get StatementKind() {
|
|
177
|
+
const root = SQLParser.unwrapRoot(this._ast);
|
|
178
|
+
if (!root)
|
|
179
|
+
return 'other';
|
|
180
|
+
const type = root.type;
|
|
181
|
+
if (type !== 'select') {
|
|
182
|
+
if (type === 'insert' || type === 'update' || type === 'delete' || type === 'merge') {
|
|
183
|
+
return 'mutation';
|
|
184
|
+
}
|
|
185
|
+
return 'other';
|
|
186
|
+
}
|
|
187
|
+
const into = root.into;
|
|
188
|
+
if (into && into.position)
|
|
189
|
+
return 'select-into';
|
|
190
|
+
if (root.set_op)
|
|
191
|
+
return 'set-op';
|
|
192
|
+
return 'select';
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* node-sql-parser statement `type` values that write/modify rather than read.
|
|
196
|
+
* Used by {@link HasWriteStatement} to reject such statements anywhere in a
|
|
197
|
+
* rendered read query (including a stacked injection payload).
|
|
198
|
+
*/
|
|
199
|
+
static { this.WRITE_STATEMENT_TYPES = new Set([
|
|
200
|
+
'insert', 'update', 'delete', 'merge', 'replace', // DML
|
|
201
|
+
'drop', 'create', 'alter', 'truncate', 'rename', // DDL
|
|
202
|
+
'call', 'exec', 'execute', 'grant', 'revoke', 'use', // exec / DCL / context
|
|
203
|
+
]); }
|
|
204
|
+
/**
|
|
205
|
+
* Whether ANY top-level statement is a write — a DML mutation
|
|
206
|
+
* (INSERT/UPDATE/DELETE/MERGE/REPLACE), DDL (DROP/CREATE/ALTER/TRUNCATE/
|
|
207
|
+
* RENAME), or EXEC/CALL/GRANT/REVOKE/USE.
|
|
208
|
+
*
|
|
209
|
+
* Unlike {@link StatementKind} (which classifies only the first statement),
|
|
210
|
+
* this inspects EVERY top-level statement, so a stacked payload such as
|
|
211
|
+
* `SELECT 1; DROP TABLE x` is detected. Benign session prefixes (`SET`,
|
|
212
|
+
* `DECLARE`) and SELECTs are not writes. Matching is on the AST statement
|
|
213
|
+
* type, so the `REPLACE()` string function inside a SELECT is never
|
|
214
|
+
* mistaken for a `REPLACE` statement.
|
|
215
|
+
*/
|
|
216
|
+
get HasWriteStatement() {
|
|
217
|
+
if (!this._ast)
|
|
218
|
+
return false;
|
|
219
|
+
const statements = Array.isArray(this._ast) ? this._ast : [this._ast];
|
|
220
|
+
for (const stmt of statements) {
|
|
221
|
+
const type = stmt.type;
|
|
222
|
+
if (typeof type === 'string' && SQLParser.WRITE_STATEMENT_TYPES.has(type.toLowerCase())) {
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* The outermost row cap on the parsed SELECT, dialect-neutral, or `null`
|
|
230
|
+
* when none is present. Backed by the dialect's ASTDialectAdapter, so the
|
|
231
|
+
* caller never needs to know whether the cap was a `TOP` or `LIMIT`.
|
|
232
|
+
*/
|
|
233
|
+
get OuterCap() {
|
|
234
|
+
const root = SQLParser.unwrapRoot(this._ast);
|
|
235
|
+
if (!root || root.type !== 'select')
|
|
236
|
+
return null;
|
|
237
|
+
return this._adapter.ReadRowCap(root);
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Sets the outermost row cap. The adapter writes the dialect's form
|
|
241
|
+
* (`TOP N` on SQL Server, `LIMIT N` elsewhere), preserving any existing
|
|
242
|
+
* OFFSET. No-op when the root isn't a SELECT.
|
|
243
|
+
*/
|
|
244
|
+
SetOuterCap(cap) {
|
|
245
|
+
const root = SQLParser.unwrapRoot(this._ast);
|
|
246
|
+
if (!root || root.type !== 'select')
|
|
247
|
+
return;
|
|
248
|
+
this._adapter.WriteRowCap(root, cap);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Removes the outermost row cap (TOP on SQL Server, LIMIT on PostgreSQL)
|
|
252
|
+
* from the parsed SELECT. No-op when the root isn't a SELECT.
|
|
253
|
+
*
|
|
254
|
+
* Used by the count-SQL builder (`queryPagingEngine.stripCountBody`) so a
|
|
255
|
+
* paged query's count reflects the full set rather than the capped subset.
|
|
256
|
+
* It clears both forms, so a PostgreSQL count drops an explicit `LIMIT` —
|
|
257
|
+
* consistent with how SQL Server's `TOP` is dropped.
|
|
258
|
+
*/
|
|
259
|
+
ClearOuterCap() {
|
|
260
|
+
const root = SQLParser.unwrapRoot(this._ast);
|
|
261
|
+
if (!root || root.type !== 'select')
|
|
262
|
+
return;
|
|
263
|
+
this._adapter.ClearRowCap(root);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Removes the top-level ORDER BY from the parsed statement, following the
|
|
267
|
+
* set-op (`UNION` / `INTERSECT` / `EXCEPT`) chain so an ORDER BY on any
|
|
268
|
+
* branch is cleared. No-op when there is none. Dialect-universal — the
|
|
269
|
+
* `orderby` field has the same shape across dialects.
|
|
270
|
+
*
|
|
271
|
+
* Used by the count-SQL builder: ORDER BY is irrelevant for a COUNT and is
|
|
272
|
+
* illegal inside a SQL Server CTE without TOP.
|
|
273
|
+
*/
|
|
274
|
+
ClearOrderBy() {
|
|
275
|
+
let node = SQLParser.unwrapRoot(this._ast);
|
|
276
|
+
while (node) {
|
|
277
|
+
if (node.orderby)
|
|
278
|
+
node.orderby = null;
|
|
279
|
+
node = node._next ?? null;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Serialize the (possibly mutated) AST back to SQL, restoring any
|
|
284
|
+
* preprocessing transforms applied at construction (bracket-identifier
|
|
285
|
+
* aliases, then the trailing `OPTION (...)` clause).
|
|
286
|
+
*
|
|
287
|
+
* Throws if the SQL was not parseable (check {@link IsValid} first).
|
|
288
|
+
*/
|
|
289
|
+
ToSQL() {
|
|
290
|
+
if (!this._ast)
|
|
291
|
+
throw new Error('SQLParser.ToSQL: SQL was not parseable');
|
|
292
|
+
let sql = SQLParser.SqlifyAST(this._ast, this._dialect);
|
|
293
|
+
if (this._aliasMap)
|
|
294
|
+
sql = SQLParser.restoreAliases(sql, this._aliasMap);
|
|
295
|
+
if (this._trailingOption)
|
|
296
|
+
sql = `${sql} ${this._trailingOption}`;
|
|
297
|
+
return sql;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Internal helper: unwrap the root statement from an AST (or AST array)
|
|
301
|
+
* and present it as a mutable record. Returns `null` if the input is null
|
|
302
|
+
* or empty.
|
|
303
|
+
*/
|
|
304
|
+
static unwrapRoot(ast) {
|
|
305
|
+
if (!ast)
|
|
306
|
+
return null;
|
|
307
|
+
const root = Array.isArray(ast) ? ast[0] : ast;
|
|
308
|
+
if (!root)
|
|
309
|
+
return null;
|
|
310
|
+
return root;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Token-aware scan for SQL clauses that cannot legally appear inside a
|
|
314
|
+
* derived table — wrapping a query that contains one of these in
|
|
315
|
+
* `SELECT ... FROM (<sql>) AS t` would produce invalid SQL.
|
|
316
|
+
*
|
|
317
|
+
* Detects (case-insensitive, outside string literals and quoted
|
|
318
|
+
* identifiers):
|
|
319
|
+
* - `FOR JSON …`
|
|
320
|
+
* - `FOR XML …`
|
|
321
|
+
* - `OPTION (…)`
|
|
322
|
+
*
|
|
323
|
+
* The dialect determines which identifier quoting styles are recognized
|
|
324
|
+
* (`[…]` for SQL Server, `` `…` `` for MySQL, `"…"` always).
|
|
325
|
+
*/
|
|
326
|
+
static HasUnwrappableTrailingClause(sql, dialect) {
|
|
327
|
+
const quoteSample = dialect.QuoteIdentifier('x');
|
|
328
|
+
const recognizeBrackets = quoteSample.startsWith('[');
|
|
329
|
+
const recognizeBackticks = quoteSample.startsWith('`');
|
|
330
|
+
const len = sql.length;
|
|
331
|
+
let i = 0;
|
|
332
|
+
const isWordChar = (ch) => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') ||
|
|
333
|
+
(ch >= '0' && ch <= '9') || ch === '_';
|
|
334
|
+
const isWS = (ch) => ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r';
|
|
335
|
+
const matchWord = (start, word) => {
|
|
336
|
+
if (start + word.length > len)
|
|
337
|
+
return false;
|
|
338
|
+
if (sql.substring(start, start + word.length).toUpperCase() !== word)
|
|
339
|
+
return false;
|
|
340
|
+
const after = start + word.length;
|
|
341
|
+
return after === len || !isWordChar(sql[after]);
|
|
342
|
+
};
|
|
343
|
+
const skipQuoted = (close) => {
|
|
344
|
+
i++;
|
|
345
|
+
while (i < len) {
|
|
346
|
+
if (sql[i] === close) {
|
|
347
|
+
if (i + 1 < len && sql[i + 1] === close) {
|
|
348
|
+
i += 2;
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
i++;
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
i++;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
while (i < len) {
|
|
358
|
+
const c = sql[i];
|
|
359
|
+
if (c === "'") {
|
|
360
|
+
skipQuoted("'");
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (recognizeBrackets && c === '[') {
|
|
364
|
+
skipQuoted(']');
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (c === '"') {
|
|
368
|
+
skipQuoted('"');
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (recognizeBackticks && c === '`') {
|
|
372
|
+
skipQuoted('`');
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
const prevIsWord = i > 0 && isWordChar(sql[i - 1]);
|
|
376
|
+
if (!prevIsWord) {
|
|
377
|
+
if (matchWord(i, 'FOR')) {
|
|
378
|
+
let j = i + 3;
|
|
379
|
+
while (j < len && isWS(sql[j]))
|
|
380
|
+
j++;
|
|
381
|
+
if (matchWord(j, 'JSON') || matchWord(j, 'XML'))
|
|
382
|
+
return true;
|
|
383
|
+
}
|
|
384
|
+
if (matchWord(i, 'OPTION')) {
|
|
385
|
+
let j = i + 6;
|
|
386
|
+
while (j < len && isWS(sql[j]))
|
|
387
|
+
j++;
|
|
388
|
+
if (j < len && sql[j] === '(')
|
|
389
|
+
return true;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
i++;
|
|
393
|
+
}
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Token-aware detection of stacked statements: a statement-separating
|
|
398
|
+
* semicolon that has real content after it (outside string literals,
|
|
399
|
+
* quoted identifiers, and comments). A single trailing semicolon — or a run
|
|
400
|
+
* of them followed only by whitespace/comments — is allowed.
|
|
401
|
+
*
|
|
402
|
+
* Unlike an AST check, this fires even when the trailing payload makes the
|
|
403
|
+
* SQL unparseable (`SELECT 1; EXEC xp_cmdshell '…'`, `SELECT 1; WAITFOR
|
|
404
|
+
* DELAY '…'`), which is exactly the stacked-injection class an AST scan
|
|
405
|
+
* misses (the whole string fails to parse, so the AST is null). A rendered
|
|
406
|
+
* read query must be a single statement, so any internal `;` is rejected.
|
|
407
|
+
*/
|
|
408
|
+
static HasStackedStatements(sql, dialect) {
|
|
409
|
+
const quoteSample = dialect.QuoteIdentifier('x');
|
|
410
|
+
const recognizeBrackets = quoteSample.startsWith('[');
|
|
411
|
+
const recognizeBackticks = quoteSample.startsWith('`');
|
|
412
|
+
const n = sql.length;
|
|
413
|
+
let i = 0;
|
|
414
|
+
let sawSemicolon = false;
|
|
415
|
+
while (i < n) {
|
|
416
|
+
const c = sql[i];
|
|
417
|
+
// line / block comments
|
|
418
|
+
if (c === '-' && i + 1 < n && sql[i + 1] === '-') {
|
|
419
|
+
while (i < n && sql[i] !== '\n')
|
|
420
|
+
i++;
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
if (c === '/' && i + 1 < n && sql[i + 1] === '*') {
|
|
424
|
+
i += 2;
|
|
425
|
+
while (i < n && !(sql[i] === '*' && i + 1 < n && sql[i + 1] === '/'))
|
|
426
|
+
i++;
|
|
427
|
+
if (i < n)
|
|
428
|
+
i += 2;
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
// string literals + quoted identifiers (skip wholesale)
|
|
432
|
+
if (c === "'" || c === '"' ||
|
|
433
|
+
(recognizeBrackets && c === '[') ||
|
|
434
|
+
(recognizeBackticks && c === '`')) {
|
|
435
|
+
const close = c === '[' ? ']' : c;
|
|
436
|
+
i = SQLParser.skipQuotedFrom(sql, i, close);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (c === ';') {
|
|
440
|
+
sawSemicolon = true;
|
|
441
|
+
i++;
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
|
|
445
|
+
i++;
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
// any other character is real statement content; if a top-level
|
|
449
|
+
// semicolon already appeared, this content is a second statement
|
|
450
|
+
if (sawSemicolon)
|
|
451
|
+
return true;
|
|
452
|
+
i++;
|
|
453
|
+
}
|
|
454
|
+
return false;
|
|
455
|
+
}
|
|
112
456
|
/**
|
|
113
457
|
* Strip line and block comments from SQL, preserving content inside
|
|
114
458
|
* string literals and quoted identifiers. Block comments support nesting.
|
|
@@ -312,7 +656,7 @@ export class SQLParser {
|
|
|
312
656
|
const ast = parser.astify(cleanSQL, { database: parserDialect });
|
|
313
657
|
const statements = Array.isArray(ast) ? ast : [ast];
|
|
314
658
|
for (const stmt of statements) {
|
|
315
|
-
SQLParser.
|
|
659
|
+
SQLParser.walkASTForExtraction(stmt, tableAliasMap, columnRefs);
|
|
316
660
|
}
|
|
317
661
|
}
|
|
318
662
|
catch { /* columns will be empty */ }
|
|
@@ -334,6 +678,13 @@ export class SQLParser {
|
|
|
334
678
|
return SQLParser.Parse(options, dialect);
|
|
335
679
|
}
|
|
336
680
|
// ─── Table & Column Extraction ─────────────────────
|
|
681
|
+
/**
|
|
682
|
+
* Extract all table/view references from this instance's SQL.
|
|
683
|
+
* Convenience delegate to the static overload.
|
|
684
|
+
*/
|
|
685
|
+
ExtractTableRefs() {
|
|
686
|
+
return SQLParser.ExtractTableRefs(this._sql, this._dialect);
|
|
687
|
+
}
|
|
337
688
|
/**
|
|
338
689
|
* Extract all table/view references from SQL.
|
|
339
690
|
* Handles Nunjucks templates via placeholder substitution before AST parsing.
|
|
@@ -348,6 +699,13 @@ export class SQLParser {
|
|
|
348
699
|
return astResult;
|
|
349
700
|
return SQLParser.extractTablesViaRegex(cleanSQL);
|
|
350
701
|
}
|
|
702
|
+
/**
|
|
703
|
+
* Extract all column references from this instance's SQL.
|
|
704
|
+
* Convenience delegate to the static overload.
|
|
705
|
+
*/
|
|
706
|
+
ExtractColumnRefs() {
|
|
707
|
+
return SQLParser.ExtractColumnRefs(this._sql, this._dialect);
|
|
708
|
+
}
|
|
351
709
|
/**
|
|
352
710
|
* Extract all column references from SQL.
|
|
353
711
|
* Handles Nunjucks templates via placeholder substitution before AST parsing.
|
|
@@ -364,7 +722,7 @@ export class SQLParser {
|
|
|
364
722
|
const ast = parser.astify(cleanSQL, { database: parserDialect });
|
|
365
723
|
const statements = Array.isArray(ast) ? ast : [ast];
|
|
366
724
|
for (const statement of statements) {
|
|
367
|
-
SQLParser.
|
|
725
|
+
SQLParser.walkASTForExtraction(statement, tableAliasMap, columnRefs);
|
|
368
726
|
}
|
|
369
727
|
return SQLParser.buildColumnRefs(columnRefs);
|
|
370
728
|
}
|
|
@@ -373,6 +731,13 @@ export class SQLParser {
|
|
|
373
731
|
}
|
|
374
732
|
}
|
|
375
733
|
// ─── SELECT Column Extraction ─────────────────────────
|
|
734
|
+
/**
|
|
735
|
+
* Extract SELECT clause columns from this instance's SQL.
|
|
736
|
+
* Convenience delegate to the static overload.
|
|
737
|
+
*/
|
|
738
|
+
ExtractSelectColumns() {
|
|
739
|
+
return SQLParser.ExtractSelectColumns(this._sql, this._dialect);
|
|
740
|
+
}
|
|
376
741
|
/**
|
|
377
742
|
* Extracts the SELECT clause columns with their output names, source columns, and table qualifiers.
|
|
378
743
|
*
|
|
@@ -472,6 +837,13 @@ export class SQLParser {
|
|
|
472
837
|
return 'EXPR';
|
|
473
838
|
}
|
|
474
839
|
// ─── CTE Extraction ────────────────────────────────
|
|
840
|
+
/**
|
|
841
|
+
* Extract CTE definitions from this instance's SQL.
|
|
842
|
+
* Convenience delegate to the static overload.
|
|
843
|
+
*/
|
|
844
|
+
ExtractCTEs() {
|
|
845
|
+
return SQLParser.ExtractCTEs(this._sql, this._dialect);
|
|
846
|
+
}
|
|
475
847
|
/**
|
|
476
848
|
* Extract CTE definitions from SQL starting with a WITH clause.
|
|
477
849
|
*
|
|
@@ -1147,6 +1519,256 @@ export class SQLParser {
|
|
|
1147
1519
|
return null;
|
|
1148
1520
|
}
|
|
1149
1521
|
}
|
|
1522
|
+
// ═══════════════════════════════════════════════════
|
|
1523
|
+
// Private: Parse Preprocessing (fallback + restoration)
|
|
1524
|
+
// ═══════════════════════════════════════════════════
|
|
1525
|
+
/**
|
|
1526
|
+
* Last-resort parse used when a direct parse fails. Rewrites SQL into a
|
|
1527
|
+
* form node-sql-parser accepts:
|
|
1528
|
+
* 1. Split a trailing `OPTION (...)` query hint (SQL Server).
|
|
1529
|
+
* 2. Alias bracket-quoted identifiers whose interior contains
|
|
1530
|
+
* parser-defeating characters (`[Active People]`, `[my-cte]`).
|
|
1531
|
+
*
|
|
1532
|
+
* Returns the AST plus the data needed to restore the original SQL on
|
|
1533
|
+
* {@link ToSQL}. `ast` is `null` when even the rewritten SQL is unparseable
|
|
1534
|
+
* (or when no transform applied — nothing new to try).
|
|
1535
|
+
*/
|
|
1536
|
+
static preprocessForParse(sql, dialect) {
|
|
1537
|
+
const noResult = { ast: null, aliasMap: null, trailingOption: null };
|
|
1538
|
+
let work = sql;
|
|
1539
|
+
// 1. Trailing OPTION (...) — always at the outermost level.
|
|
1540
|
+
const optionSplit = SQLParser.splitTrailingOption(work, dialect);
|
|
1541
|
+
const trailingOption = optionSplit ? optionSplit.optionClause : null;
|
|
1542
|
+
if (optionSplit)
|
|
1543
|
+
work = optionSplit.sqlWithoutOption;
|
|
1544
|
+
// 2. Bracket-identifier aliasing (SQL Server bracket quoting only).
|
|
1545
|
+
const aliased = SQLParser.aliasBracketIdentifiers(work, dialect);
|
|
1546
|
+
if (aliased.forward.size > 0)
|
|
1547
|
+
work = aliased.rewritten;
|
|
1548
|
+
const aliasMap = aliased.forward.size > 0
|
|
1549
|
+
? new Map(Array.from(aliased.forward, ([interior, alias]) => [alias, `[${interior}]`]))
|
|
1550
|
+
: null;
|
|
1551
|
+
// No transform applied → re-parsing the same SQL would just fail again.
|
|
1552
|
+
if (work === sql)
|
|
1553
|
+
return noResult;
|
|
1554
|
+
const ast = SQLParser.parseSQL(work, dialect.ParserDialect);
|
|
1555
|
+
if (!ast)
|
|
1556
|
+
return noResult;
|
|
1557
|
+
return { ast, aliasMap, trailingOption };
|
|
1558
|
+
}
|
|
1559
|
+
/**
|
|
1560
|
+
* Token-aware scan for a trailing `OPTION (...)` query hint at the
|
|
1561
|
+
* outermost level (outside string literals, quoted identifiers, and
|
|
1562
|
+
* comments). Returns the SQL without the clause plus the clause text, or
|
|
1563
|
+
* `null` when there is no trailing OPTION.
|
|
1564
|
+
*/
|
|
1565
|
+
static splitTrailingOption(sql, dialect) {
|
|
1566
|
+
const quoteSample = dialect.QuoteIdentifier('x');
|
|
1567
|
+
const recognizeBrackets = quoteSample.startsWith('[');
|
|
1568
|
+
const recognizeBackticks = quoteSample.startsWith('`');
|
|
1569
|
+
const n = sql.length;
|
|
1570
|
+
const isWordChar = (ch) => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') ||
|
|
1571
|
+
(ch >= '0' && ch <= '9') || ch === '_';
|
|
1572
|
+
let i = 0;
|
|
1573
|
+
let optionStart = -1;
|
|
1574
|
+
while (i < n) {
|
|
1575
|
+
const ch = sql[i];
|
|
1576
|
+
if (ch === "'") {
|
|
1577
|
+
i = SQLParser.skipQuotedFrom(sql, i, "'");
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1580
|
+
if (ch === '"') {
|
|
1581
|
+
i = SQLParser.skipQuotedFrom(sql, i, '"');
|
|
1582
|
+
continue;
|
|
1583
|
+
}
|
|
1584
|
+
if (recognizeBrackets && ch === '[') {
|
|
1585
|
+
i = SQLParser.skipQuotedFrom(sql, i, ']');
|
|
1586
|
+
continue;
|
|
1587
|
+
}
|
|
1588
|
+
if (recognizeBackticks && ch === '`') {
|
|
1589
|
+
i = SQLParser.skipQuotedFrom(sql, i, '`');
|
|
1590
|
+
continue;
|
|
1591
|
+
}
|
|
1592
|
+
if (ch === '-' && i + 1 < n && sql[i + 1] === '-') {
|
|
1593
|
+
while (i < n && sql[i] !== '\n')
|
|
1594
|
+
i++;
|
|
1595
|
+
continue;
|
|
1596
|
+
}
|
|
1597
|
+
if (ch === '/' && i + 1 < n && sql[i + 1] === '*') {
|
|
1598
|
+
i += 2;
|
|
1599
|
+
while (i < n && !(sql[i] === '*' && i + 1 < n && sql[i + 1] === '/'))
|
|
1600
|
+
i++;
|
|
1601
|
+
if (i < n)
|
|
1602
|
+
i += 2;
|
|
1603
|
+
continue;
|
|
1604
|
+
}
|
|
1605
|
+
const prevIsWord = i > 0 && isWordChar(sql[i - 1]);
|
|
1606
|
+
if (!prevIsWord && i + 6 <= n && sql.substring(i, i + 6).toUpperCase() === 'OPTION' &&
|
|
1607
|
+
(i + 6 === n || !isWordChar(sql[i + 6]))) {
|
|
1608
|
+
let j = i + 6;
|
|
1609
|
+
while (j < n && /\s/.test(sql[j]))
|
|
1610
|
+
j++;
|
|
1611
|
+
if (j < n && sql[j] === '(') {
|
|
1612
|
+
optionStart = i; // remember the last top-level OPTION (
|
|
1613
|
+
i = j;
|
|
1614
|
+
continue;
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
i++;
|
|
1618
|
+
}
|
|
1619
|
+
if (optionStart === -1)
|
|
1620
|
+
return null;
|
|
1621
|
+
// Match the balanced paren group following OPTION.
|
|
1622
|
+
let k = optionStart + 6;
|
|
1623
|
+
while (k < n && /\s/.test(sql[k]))
|
|
1624
|
+
k++;
|
|
1625
|
+
let depth = 0;
|
|
1626
|
+
for (; k < n; k++) {
|
|
1627
|
+
const ch = sql[k];
|
|
1628
|
+
if (ch === "'") {
|
|
1629
|
+
k = SQLParser.skipQuotedFrom(sql, k, "'") - 1;
|
|
1630
|
+
continue;
|
|
1631
|
+
}
|
|
1632
|
+
if (ch === '(')
|
|
1633
|
+
depth++;
|
|
1634
|
+
else if (ch === ')') {
|
|
1635
|
+
depth--;
|
|
1636
|
+
if (depth === 0) {
|
|
1637
|
+
k++;
|
|
1638
|
+
break;
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
if (depth !== 0)
|
|
1643
|
+
return null; // unbalanced — leave alone
|
|
1644
|
+
const rest = sql.substring(k).trim();
|
|
1645
|
+
if (rest !== '' && rest !== ';')
|
|
1646
|
+
return null; // not a trailing OPTION
|
|
1647
|
+
return {
|
|
1648
|
+
sqlWithoutOption: sql.substring(0, optionStart).trimEnd(),
|
|
1649
|
+
optionClause: sql.substring(optionStart, k).trim(),
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
/**
|
|
1653
|
+
* Token-aware scan that aliases bracket-quoted identifiers whose interior
|
|
1654
|
+
* contains characters node-sql-parser can't handle (`[Active People]`,
|
|
1655
|
+
* `[my-cte]`, `[dbo.table]`). Aliases are stable, collision-safe tokens
|
|
1656
|
+
* (`_mjid_<seq>`). Applies only to bracket-quoting dialects (SQL Server).
|
|
1657
|
+
*
|
|
1658
|
+
* Returns the rewritten SQL plus a forward map (original interior → alias).
|
|
1659
|
+
*/
|
|
1660
|
+
static { this.BRACKET_ALIAS_PREFIX = '_mjid_'; }
|
|
1661
|
+
static aliasBracketIdentifiers(sql, dialect) {
|
|
1662
|
+
const forward = new Map();
|
|
1663
|
+
if (!dialect.QuoteIdentifier('x').startsWith('['))
|
|
1664
|
+
return { rewritten: sql, forward };
|
|
1665
|
+
const n = sql.length;
|
|
1666
|
+
let out = '';
|
|
1667
|
+
let i = 0;
|
|
1668
|
+
let seq = 0;
|
|
1669
|
+
while (i < n) {
|
|
1670
|
+
const ch = sql[i];
|
|
1671
|
+
if (ch === '-' && i + 1 < n && sql[i + 1] === '-') {
|
|
1672
|
+
while (i < n && sql[i] !== '\n') {
|
|
1673
|
+
out += sql[i];
|
|
1674
|
+
i++;
|
|
1675
|
+
}
|
|
1676
|
+
continue;
|
|
1677
|
+
}
|
|
1678
|
+
if (ch === '/' && i + 1 < n && sql[i + 1] === '*') {
|
|
1679
|
+
out += '/*';
|
|
1680
|
+
i += 2;
|
|
1681
|
+
while (i < n && !(sql[i] === '*' && i + 1 < n && sql[i + 1] === '/')) {
|
|
1682
|
+
out += sql[i];
|
|
1683
|
+
i++;
|
|
1684
|
+
}
|
|
1685
|
+
if (i < n) {
|
|
1686
|
+
out += '*/';
|
|
1687
|
+
i += 2;
|
|
1688
|
+
}
|
|
1689
|
+
continue;
|
|
1690
|
+
}
|
|
1691
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
1692
|
+
const close = ch;
|
|
1693
|
+
const end = SQLParser.skipQuotedFrom(sql, i, close);
|
|
1694
|
+
out += sql.substring(i, end);
|
|
1695
|
+
i = end;
|
|
1696
|
+
continue;
|
|
1697
|
+
}
|
|
1698
|
+
if (ch === '[') {
|
|
1699
|
+
// Read the interior, honoring the ]] escape for a literal ].
|
|
1700
|
+
let j = i + 1;
|
|
1701
|
+
let interior = '';
|
|
1702
|
+
while (j < n) {
|
|
1703
|
+
if (sql[j] === ']') {
|
|
1704
|
+
if (j + 1 < n && sql[j + 1] === ']') {
|
|
1705
|
+
interior += ']';
|
|
1706
|
+
j += 2;
|
|
1707
|
+
continue;
|
|
1708
|
+
}
|
|
1709
|
+
j++;
|
|
1710
|
+
break;
|
|
1711
|
+
}
|
|
1712
|
+
interior += sql[j];
|
|
1713
|
+
j++;
|
|
1714
|
+
}
|
|
1715
|
+
if (interior.length > 0 && /[^A-Za-z0-9_]/.test(interior)) {
|
|
1716
|
+
let alias = forward.get(interior);
|
|
1717
|
+
if (!alias) {
|
|
1718
|
+
alias = `${SQLParser.BRACKET_ALIAS_PREFIX}${seq++}`;
|
|
1719
|
+
forward.set(interior, alias);
|
|
1720
|
+
}
|
|
1721
|
+
// Emit a BARE identifier — node-sql-parser rejects bracket-quoted
|
|
1722
|
+
// CTE names entirely, so the alias must be unbracketed. sqlify
|
|
1723
|
+
// re-quotes it ([_mjid_0]); restoreAliases handles every form.
|
|
1724
|
+
out += alias;
|
|
1725
|
+
}
|
|
1726
|
+
else {
|
|
1727
|
+
out += sql.substring(i, j); // leave non-problematic identifiers untouched
|
|
1728
|
+
}
|
|
1729
|
+
i = j;
|
|
1730
|
+
continue;
|
|
1731
|
+
}
|
|
1732
|
+
out += ch;
|
|
1733
|
+
i++;
|
|
1734
|
+
}
|
|
1735
|
+
return { rewritten: out, forward };
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Reverses bracket-identifier aliasing on a sqlify result. node-sql-parser
|
|
1739
|
+
* may emit the alias bare, bracketed, or backticked; all three forms are
|
|
1740
|
+
* restored to the original bracketed identifier. Aliases are unique
|
|
1741
|
+
* `BRACKET_ALIAS_PREFIX<seq>` tokens, so replacement is unambiguous.
|
|
1742
|
+
*/
|
|
1743
|
+
static restoreAliases(sql, aliasMap) {
|
|
1744
|
+
let out = sql;
|
|
1745
|
+
for (const [alias, originalBracketed] of aliasMap) {
|
|
1746
|
+
out = out.split(`[${alias}]`).join(originalBracketed);
|
|
1747
|
+
out = out.split('`' + alias + '`').join(originalBracketed);
|
|
1748
|
+
out = out.replace(new RegExp(`\\b${alias}\\b`, 'g'), originalBracketed);
|
|
1749
|
+
}
|
|
1750
|
+
return out;
|
|
1751
|
+
}
|
|
1752
|
+
/**
|
|
1753
|
+
* Advances past a quoted span starting at `start` (whose opening char is
|
|
1754
|
+
* `sql[start]`), honoring the doubled-delimiter escape (`''`, `]]`, `""`,
|
|
1755
|
+
* `` `` ``). Returns the index just past the closing delimiter.
|
|
1756
|
+
*/
|
|
1757
|
+
static skipQuotedFrom(sql, start, close) {
|
|
1758
|
+
const n = sql.length;
|
|
1759
|
+
let i = start + 1;
|
|
1760
|
+
while (i < n) {
|
|
1761
|
+
if (sql[i] === close) {
|
|
1762
|
+
if (i + 1 < n && sql[i + 1] === close) {
|
|
1763
|
+
i += 2;
|
|
1764
|
+
continue;
|
|
1765
|
+
}
|
|
1766
|
+
return i + 1;
|
|
1767
|
+
}
|
|
1768
|
+
i++;
|
|
1769
|
+
}
|
|
1770
|
+
return n;
|
|
1771
|
+
}
|
|
1150
1772
|
/**
|
|
1151
1773
|
* Detects FOR XML clauses that node-sql-parser can't handle and simplifies them.
|
|
1152
1774
|
*
|
|
@@ -1224,7 +1846,7 @@ export class SQLParser {
|
|
|
1224
1846
|
const columnRefs = new Set();
|
|
1225
1847
|
const statements = Array.isArray(ast) ? ast : [ast];
|
|
1226
1848
|
for (const statement of statements) {
|
|
1227
|
-
SQLParser.
|
|
1849
|
+
SQLParser.walkASTForExtraction(statement, tableAliasMap, columnRefs);
|
|
1228
1850
|
}
|
|
1229
1851
|
return SQLParser.deduplicateTables(tableAliasMap);
|
|
1230
1852
|
}
|
|
@@ -1374,7 +1996,7 @@ export class SQLParser {
|
|
|
1374
1996
|
// ═══════════════════════════════════════════════════
|
|
1375
1997
|
// Private: AST Walking (table/column extraction)
|
|
1376
1998
|
// ═══════════════════════════════════════════════════
|
|
1377
|
-
static
|
|
1999
|
+
static walkASTForExtraction(node, tableAliasMap, columnRefs) {
|
|
1378
2000
|
if (!node || typeof node !== 'object')
|
|
1379
2001
|
return;
|
|
1380
2002
|
if (node.with) {
|
|
@@ -1384,7 +2006,7 @@ export class SQLParser {
|
|
|
1384
2006
|
if (cteRecord.stmt) {
|
|
1385
2007
|
const stmtRecord = cteRecord.stmt;
|
|
1386
2008
|
const cteAst = (stmtRecord.ast || stmtRecord);
|
|
1387
|
-
SQLParser.
|
|
2009
|
+
SQLParser.walkASTForExtraction(cteAst, tableAliasMap, columnRefs);
|
|
1388
2010
|
}
|
|
1389
2011
|
}
|
|
1390
2012
|
}
|
|
@@ -1424,7 +2046,7 @@ export class SQLParser {
|
|
|
1424
2046
|
}
|
|
1425
2047
|
}
|
|
1426
2048
|
if (node._next) {
|
|
1427
|
-
SQLParser.
|
|
2049
|
+
SQLParser.walkASTForExtraction(node._next, tableAliasMap, columnRefs);
|
|
1428
2050
|
}
|
|
1429
2051
|
}
|
|
1430
2052
|
static walkFromItem(fromItem, tableAliasMap, columnRefs) {
|
|
@@ -1440,7 +2062,7 @@ export class SQLParser {
|
|
|
1440
2062
|
if (fromItem.expr) {
|
|
1441
2063
|
const exprRecord = fromItem.expr;
|
|
1442
2064
|
const subqueryAst = (exprRecord.ast || exprRecord);
|
|
1443
|
-
SQLParser.
|
|
2065
|
+
SQLParser.walkASTForExtraction(subqueryAst, tableAliasMap, columnRefs);
|
|
1444
2066
|
}
|
|
1445
2067
|
if (fromItem.on) {
|
|
1446
2068
|
SQLParser.walkExpression(fromItem.on, columnRefs, tableAliasMap);
|
|
@@ -1465,7 +2087,7 @@ export class SQLParser {
|
|
|
1465
2087
|
columnRefs.add(colName);
|
|
1466
2088
|
}
|
|
1467
2089
|
if (expr.ast && tableAliasMap) {
|
|
1468
|
-
SQLParser.
|
|
2090
|
+
SQLParser.walkASTForExtraction(expr.ast, tableAliasMap, columnRefs);
|
|
1469
2091
|
}
|
|
1470
2092
|
if (expr.left)
|
|
1471
2093
|
SQLParser.walkExpression(expr.left, columnRefs, tableAliasMap);
|