@memberjunction/sql-parser 5.51.2 → 5.51.4

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 (43) hide show
  1. package/dist/aggregateExpression.d.ts +39 -0
  2. package/dist/aggregateExpression.d.ts.map +1 -0
  3. package/dist/aggregateExpression.js +446 -0
  4. package/dist/aggregateExpression.js.map +1 -0
  5. package/dist/balancedFragment.d.ts +51 -0
  6. package/dist/balancedFragment.d.ts.map +1 -0
  7. package/dist/balancedFragment.js +189 -0
  8. package/dist/balancedFragment.js.map +1 -0
  9. package/dist/callerSqlFunctions.d.ts +9 -0
  10. package/dist/callerSqlFunctions.d.ts.map +1 -0
  11. package/dist/callerSqlFunctions.js +39 -0
  12. package/dist/callerSqlFunctions.js.map +1 -0
  13. package/dist/index.d.ts +11 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +8 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/mj-lexer.d.ts.map +1 -1
  18. package/dist/mj-lexer.js +2 -1
  19. package/dist/mj-lexer.js.map +1 -1
  20. package/dist/orderByAnalyzer.d.ts.map +1 -1
  21. package/dist/orderByAnalyzer.js +40 -18
  22. package/dist/orderByAnalyzer.js.map +1 -1
  23. package/dist/pagingShape.d.ts +59 -0
  24. package/dist/pagingShape.d.ts.map +1 -0
  25. package/dist/pagingShape.js +185 -0
  26. package/dist/pagingShape.js.map +1 -0
  27. package/dist/sql-parser.d.ts +96 -34
  28. package/dist/sql-parser.d.ts.map +1 -1
  29. package/dist/sql-parser.js +255 -416
  30. package/dist/sql-parser.js.map +1 -1
  31. package/dist/sqlLexer.d.ts +49 -0
  32. package/dist/sqlLexer.d.ts.map +1 -0
  33. package/dist/sqlLexer.js +164 -0
  34. package/dist/sqlLexer.js.map +1 -0
  35. package/dist/sqlShape.d.ts +49 -0
  36. package/dist/sqlShape.d.ts.map +1 -0
  37. package/dist/sqlShape.js +138 -0
  38. package/dist/sqlShape.js.map +1 -0
  39. package/dist/templateTagVariables.d.ts +17 -0
  40. package/dist/templateTagVariables.d.ts.map +1 -0
  41. package/dist/templateTagVariables.js +91 -0
  42. package/dist/templateTagVariables.js.map +1 -0
  43. package/package.json +2 -2
@@ -15,8 +15,15 @@
15
15
  import NodeSqlParser from 'node-sql-parser';
16
16
  const { Parser } = NodeSqlParser;
17
17
  import { MJLexer } from './mj-lexer.js';
18
+ import { ReplaceVariableInTag, VARIABLE_READING_TAGS } from './templateTagVariables.js';
18
19
  import { MJPlaceholderSubstitution } from './mj-placeholder.js';
20
+ import { SQLServerDialect } from '@memberjunction/sql-dialect';
19
21
  import { getASTDialectAdapter } from './ASTDialectAdapter.js';
22
+ import { IsKeyword, LexSQL, SignificantTokens } from './sqlLexer.js';
23
+ /** Lexing rules for FOR XML, which only SQL Server has. */
24
+ const SQL_SERVER_LEXING = new SQLServerDialect();
25
+ /** The FOR XML modes node-sql-parser knows. */
26
+ const FOR_XML_DIRECTIVES = ['PATH', 'RAW', 'AUTO', 'EXPLICIT'];
20
27
  // ═══════════════════════════════════════════════════
21
28
  // SQLParser class
22
29
  // ═══════════════════════════════════════════════════
@@ -44,8 +51,8 @@ export class SQLParser {
44
51
  *
45
52
  * On a direct-parse failure, applies preprocessing fallbacks — splitting a
46
53
  * 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}
54
+ * (`[Active People]`, `[my-cte]`, bracket-quoted CTE names) — so a wider
55
+ * class of SQL becomes AST-addressable. {@link ToSQL}
49
56
  * transparently restores both transforms.
50
57
  *
51
58
  * Never throws on unparseable SQL — check {@link IsValid}.
@@ -76,10 +83,31 @@ export class SQLParser {
76
83
  get AST() {
77
84
  return this._ast;
78
85
  }
86
+ /**
87
+ * The bracket identifiers the fallback parse renamed, as the name in {@link AST} mapped to the
88
+ * original bracketed text (for example `[My CTE]`). Null when the direct parse succeeded, so
89
+ * every identifier in the tree is as written. A name in this map is in the tree only where the
90
+ * fallback put it: no such name occurs in the SQL, and none runs into the text next to it.
91
+ */
92
+ get IdentifierAliases() {
93
+ return this._aliasMap;
94
+ }
95
+ /**
96
+ * True when `name` has the form of a name the fallback parse gives a renamed bracket
97
+ * identifier ({@link IdentifierAliases}), ignoring case: `_mjid_<n>`, or `_mjid<k>_<n>` when
98
+ * the SQL already contains `_mjid_`.
99
+ */
100
+ static IsIdentifierAliasName(name) {
101
+ return SQLParser.ALIAS_NAME.test(name);
102
+ }
79
103
  /** The dialect supplied at construction. */
80
104
  get Dialect() {
81
105
  return this._dialect;
82
106
  }
107
+ /** The SQL supplied at construction, as written. */
108
+ get SQL() {
109
+ return this._sql;
110
+ }
83
111
  /**
84
112
  * Fixes a known node-sql-parser bug where CAST(x AS NVARCHAR(MAX)) is
85
113
  * serialized as CAST(x AS NVARCHARmax). Applies to NVARCHAR, VARCHAR,
@@ -310,88 +338,20 @@ export class SQLParser {
310
338
  return root;
311
339
  }
312
340
  /**
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 (…)`
341
+ * Whether the statement ends in a clause that cannot legally appear inside a derived table,
342
+ * so wrapping it in `SELECT ... FROM (<sql>) AS t` would produce invalid SQL:
343
+ * - `FOR JSON …` / `FOR XML …` at the top level
344
+ * - a trailing query-hint clause ({@link SQLParserDialect.QueryHintKeyword}, `OPTION (…)` on SQL Server)
322
345
  *
323
- * The dialect determines which identifier quoting styles are recognized
324
- * (`[…]` for SQL Server, `` `…` `` for MySQL, `"…"` always).
346
+ * Only the top level of the statement counts. The same words inside a subquery (a correlated
347
+ * `(SELECT … FOR JSON PATH)` column), a string literal, a quoted identifier or a comment do
348
+ * not stop a wrap.
325
349
  */
326
350
  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;
351
+ const top = SignificantTokens(LexSQL(sql, dialect)).filter(t => t.Depth === 0);
352
+ const hintKeyword = dialect.QueryHintKeyword?.toUpperCase();
353
+ return top.some((t, i) => (IsKeyword(t, 'FOR') && (IsKeyword(top[i + 1], 'JSON') || IsKeyword(top[i + 1], 'XML'))) ||
354
+ (hintKeyword !== undefined && IsKeyword(t, hintKeyword) && top[i + 1]?.Kind === 'open'));
395
355
  }
396
356
  /**
397
357
  * Token-aware detection of stacked statements: a statement-separating
@@ -399,6 +359,11 @@ export class SQLParser {
399
359
  * quoted identifiers, and comments). A single trailing semicolon — or a run
400
360
  * of them followed only by whitespace/comments — is allowed.
401
361
  *
362
+ * Reads the tokens {@link LexSQL} produces for the dialect, so every quoted
363
+ * form the database recognizes hides its contents: `[…]` identifiers on SQL
364
+ * Server, `E'…'` strings with backslash escapes and dollar-quoted strings on
365
+ * PostgreSQL, and nested block comments on both.
366
+ *
402
367
  * Unlike an AST check, this fires even when the trailing payload makes the
403
368
  * SQL unparseable (`SELECT 1; EXEC xp_cmdshell '…'`, `SELECT 1; WAITFOR
404
369
  * DELAY '…'`), which is exactly the stacked-injection class an AST scan
@@ -406,186 +371,35 @@ export class SQLParser {
406
371
  * read query must be a single statement, so any internal `;` is rejected.
407
372
  */
408
373
  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
374
  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;
375
+ // A semicolon before any content (the `;WITH` idiom) separates nothing.
376
+ let sawContent = false;
377
+ for (const token of SignificantTokens(LexSQL(sql, dialect))) {
378
+ if (token.Kind === 'semicolon') {
379
+ if (sawContent)
380
+ sawSemicolon = true;
429
381
  continue;
430
382
  }
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
383
+ // Real content after a separating semicolon is a second statement.
450
384
  if (sawSemicolon)
451
385
  return true;
452
- i++;
386
+ sawContent = true;
453
387
  }
454
388
  return false;
455
389
  }
456
390
  /**
457
- * Strip line and block comments from SQL, preserving content inside
458
- * string literals and quoted identifiers. Block comments support nesting.
391
+ * Strip line and block comments from SQL, preserving content inside string literals and
392
+ * quoted identifiers. Block comments nest. A block comment is replaced by a space, so two
393
+ * tokens it separated with no whitespace stay apart; a line comment's ending newline is kept.
459
394
  *
460
- * The dialect determines which identifier quoting styles are recognized:
461
- * SQL Server uses `[…]`, PostgreSQL uses `"…"`, MySQL uses `` `…` ``.
462
- * Double-quoted identifiers are honored on every dialect.
395
+ * The dialect determines which literal and identifier forms are recognized: SQL Server
396
+ * `[…]`, PostgreSQL `E'…'` and dollar-quoted strings (`$$…$$`, `$tag$…$tag$`), MySQL
397
+ * `` `…` ``. Double-quoted identifiers are honored on every dialect.
463
398
  */
464
399
  static StripComments(sql, dialect) {
465
- const quoteSample = dialect.QuoteIdentifier('x');
466
- const recognizeBrackets = quoteSample.startsWith('[');
467
- const recognizeBackticks = quoteSample.startsWith('`');
468
- let out = '';
469
- let i = 0;
470
- const n = sql.length;
471
- while (i < n) {
472
- const ch = sql[i];
473
- const next = i + 1 < n ? sql[i + 1] : '';
474
- if (ch === '-' && next === '-') {
475
- while (i < n && sql[i] !== '\n')
476
- i++;
477
- continue;
478
- }
479
- if (ch === '/' && next === '*') {
480
- i += 2;
481
- let depth = 1;
482
- while (i < n && depth > 0) {
483
- if (i + 1 < n && sql[i] === '/' && sql[i + 1] === '*') {
484
- depth++;
485
- i += 2;
486
- }
487
- else if (i + 1 < n && sql[i] === '*' && sql[i + 1] === '/') {
488
- depth--;
489
- i += 2;
490
- }
491
- else {
492
- i++;
493
- }
494
- }
495
- continue;
496
- }
497
- if (ch === "'") {
498
- out += ch;
499
- i++;
500
- while (i < n) {
501
- if (sql[i] === "'") {
502
- if (i + 1 < n && sql[i + 1] === "'") {
503
- out += "''";
504
- i += 2;
505
- }
506
- else {
507
- out += "'";
508
- i++;
509
- break;
510
- }
511
- }
512
- else {
513
- out += sql[i];
514
- i++;
515
- }
516
- }
517
- continue;
518
- }
519
- if (recognizeBrackets && ch === '[') {
520
- out += ch;
521
- i++;
522
- while (i < n) {
523
- if (sql[i] === ']') {
524
- if (i + 1 < n && sql[i + 1] === ']') {
525
- out += ']]';
526
- i += 2;
527
- }
528
- else {
529
- out += ']';
530
- i++;
531
- break;
532
- }
533
- }
534
- else {
535
- out += sql[i];
536
- i++;
537
- }
538
- }
539
- continue;
540
- }
541
- if (ch === '"') {
542
- out += ch;
543
- i++;
544
- while (i < n) {
545
- if (sql[i] === '"') {
546
- if (i + 1 < n && sql[i + 1] === '"') {
547
- out += '""';
548
- i += 2;
549
- }
550
- else {
551
- out += '"';
552
- i++;
553
- break;
554
- }
555
- }
556
- else {
557
- out += sql[i];
558
- i++;
559
- }
560
- }
561
- continue;
562
- }
563
- if (recognizeBackticks && ch === '`') {
564
- out += ch;
565
- i++;
566
- while (i < n) {
567
- if (sql[i] === '`') {
568
- if (i + 1 < n && sql[i + 1] === '`') {
569
- out += '``';
570
- i += 2;
571
- }
572
- else {
573
- out += '`';
574
- i++;
575
- break;
576
- }
577
- }
578
- else {
579
- out += sql[i];
580
- i++;
581
- }
582
- }
583
- continue;
584
- }
585
- out += ch;
586
- i++;
587
- }
588
- return out;
400
+ return LexSQL(sql, dialect)
401
+ .map(t => t.Kind !== 'comment' ? t.Text : t.Text.startsWith('/*') ? ' ' : '')
402
+ .join('');
589
403
  }
590
404
  /**
591
405
  * Convert a single AST expression node to a SQL string.
@@ -652,8 +466,7 @@ export class SQLParser {
652
466
  const columnRefs = new Set();
653
467
  if (usedAST) {
654
468
  try {
655
- const parser = new Parser();
656
- const ast = parser.astify(cleanSQL, { database: parserDialect });
469
+ const ast = SQLParser.astifyChecked(cleanSQL, parserDialect);
657
470
  const statements = Array.isArray(ast) ? ast : [ast];
658
471
  for (const stmt of statements) {
659
472
  SQLParser.walkASTForExtraction(stmt, tableAliasMap, columnRefs);
@@ -718,8 +531,7 @@ export class SQLParser {
718
531
  const tableAliasMap = new Map();
719
532
  const columnRefs = new Set();
720
533
  try {
721
- const parser = new Parser();
722
- const ast = parser.astify(cleanSQL, { database: parserDialect });
534
+ const ast = SQLParser.astifyChecked(cleanSQL, parserDialect);
723
535
  const statements = Array.isArray(ast) ? ast : [ast];
724
536
  for (const statement of statements) {
725
537
  SQLParser.walkASTForExtraction(statement, tableAliasMap, columnRefs);
@@ -752,8 +564,7 @@ export class SQLParser {
752
564
  return [];
753
565
  const cleanSQL = SQLParser.getCleanSQL(sql);
754
566
  try {
755
- const parser = new Parser();
756
- const ast = parser.astify(cleanSQL, { database: dialect.ParserDialect });
567
+ const ast = SQLParser.astifyChecked(cleanSQL, dialect.ParserDialect);
757
568
  const statements = Array.isArray(ast) ? ast : [ast];
758
569
  const columns = [];
759
570
  for (const statement of statements) {
@@ -928,8 +739,9 @@ export class SQLParser {
928
739
  }
929
740
  // ─── MJ Template Extraction ────────────────────────
930
741
  /**
931
- * Renames a template variable in all `{{ variable | filters }}` expressions throughout the SQL.
932
- * Preserves the filter chain and whitespace formatting.
742
+ * Renames a template variable throughout the SQL: in every `{{ variable | filters }}`
743
+ * expression, preserving the filter chain, and in every read of it inside `{% if %}`,
744
+ * `{% elif %}`, `{% for %}` and `{% set %}` tags.
933
745
  *
934
746
  * Example: `RenameTemplateVariable("WHERE x = {{ region | sqlString }}", "region", "userRegion")`
935
747
  * → `"WHERE x = {{ userRegion | sqlString }}"`
@@ -937,19 +749,7 @@ export class SQLParser {
937
749
  * Uses MJLexer for deterministic token identification — no regex guessing.
938
750
  */
939
751
  static RenameTemplateVariable(sql, oldName, newName) {
940
- const tokens = MJLexer.Tokenize(sql);
941
- const oldNameLower = oldName.toLowerCase();
942
- // Collect matching tokens in reverse order so positional replacements don't shift offsets
943
- const matches = tokens
944
- .filter(t => t.type === 'MJ_TEMPLATE_EXPR' &&
945
- t.parsed.variable.toLowerCase() === oldNameLower)
946
- .sort((a, b) => b.start - a.start); // reverse order
947
- let result = sql;
948
- for (const token of matches) {
949
- const rebuilt = SQLParser.rebuildTemplateExpr(newName, token.parsed.filters);
950
- result = result.substring(0, token.start) + rebuilt + result.substring(token.end);
951
- }
952
- return result;
752
+ return SQLParser.replaceTemplateVariable(sql, oldName, token => SQLParser.rebuildTemplateExpr(newName, token.parsed.filters), newName);
953
753
  }
954
754
  /**
955
755
  * Substitutes a template variable with a literal value in all `{{ variable | filters }}` expressions.
@@ -959,19 +759,34 @@ export class SQLParser {
959
759
  * Example: `SubstituteTemplateVariable("WHERE x = {{ region | sqlString }}", "region", "'West'")`
960
760
  * → `"WHERE x = 'West'"`
961
761
  *
762
+ * When `tagLiteral` is given, reads of the variable inside `{% if %}`, `{% elif %}`,
763
+ * `{% for %}` and `{% set %}` tags are replaced with it too, so conditions see the value.
764
+ * It must be a template-language literal (`"West"`, `42`), not a SQL one.
765
+ *
962
766
  * Uses MJLexer for deterministic token identification — no regex guessing.
963
767
  */
964
- static SubstituteTemplateVariable(sql, variableName, literalValue) {
965
- const tokens = MJLexer.Tokenize(sql);
966
- const varNameLower = variableName.toLowerCase();
967
- // Collect matching tokens in reverse order
968
- const matches = tokens
969
- .filter(t => t.type === 'MJ_TEMPLATE_EXPR' &&
970
- t.parsed.variable.toLowerCase() === varNameLower)
971
- .sort((a, b) => b.start - a.start);
768
+ static SubstituteTemplateVariable(sql, variableName, literalValue, tagLiteral) {
769
+ return SQLParser.replaceTemplateVariable(sql, variableName, () => literalValue, tagLiteral);
770
+ }
771
+ /**
772
+ * Replaces a variable's `{{ }}` expressions with `exprText(token)` and, when `tagText` is
773
+ * given, its reads inside block tags with `tagText`. Edits apply from the end of the SQL so
774
+ * earlier offsets stay valid.
775
+ */
776
+ static replaceTemplateVariable(sql, variableName, exprText, tagText) {
777
+ const nameLower = variableName.toLowerCase();
778
+ const edits = [];
779
+ for (const token of MJLexer.Tokenize(sql)) {
780
+ if (token.type === 'MJ_TEMPLATE_EXPR' && token.parsed.variable.toLowerCase() === nameLower) {
781
+ edits.push({ token, text: exprText(token) });
782
+ }
783
+ else if (tagText !== undefined && VARIABLE_READING_TAGS.has(token.type)) {
784
+ edits.push({ token, text: ReplaceVariableInTag(token.raw, variableName, tagText) });
785
+ }
786
+ }
972
787
  let result = sql;
973
- for (const token of matches) {
974
- result = result.substring(0, token.start) + literalValue + result.substring(token.end);
788
+ for (const { token, text } of edits.sort((a, b) => b.token.start - a.token.start)) {
789
+ result = result.substring(0, token.start) + text + result.substring(token.end);
975
790
  }
976
791
  return result;
977
792
  }
@@ -1173,16 +988,27 @@ export class SQLParser {
1173
988
  const root = varName.split(/[.\s]/, 1)[0];
1174
989
  if (root.toLowerCase() === 'loop')
1175
990
  break;
1176
- if (!paramMap.has(varName)) {
991
+ // A `default(…)` filter renders the expression without the parameter, so a use
992
+ // with one does not make the parameter required; any use without one does.
993
+ const defaultValue = SQLParser.extractDefaultValue(parsed.filters);
994
+ const hasDefault = parsed.filters.some(f => f.name === 'default');
995
+ const existing = paramMap.get(varName);
996
+ if (!existing) {
1177
997
  paramMap.set(varName, {
1178
998
  name: varName,
1179
999
  type: SQLParser.inferTypeFromFilters(parsed.filters),
1180
- isRequired: true,
1181
- defaultValue: SQLParser.extractDefaultValue(parsed.filters),
1000
+ isRequired: !hasDefault,
1001
+ defaultValue,
1182
1002
  filters: parsed.filters,
1183
1003
  usageLocations: [],
1184
1004
  });
1185
1005
  }
1006
+ else {
1007
+ if (!hasDefault)
1008
+ existing.isRequired = true;
1009
+ if (existing.defaultValue === null)
1010
+ existing.defaultValue = defaultValue;
1011
+ }
1186
1012
  paramMap.get(varName).usageLocations.push(token.raw);
1187
1013
  break;
1188
1014
  }
@@ -1523,16 +1349,14 @@ export class SQLParser {
1523
1349
  }
1524
1350
  static parseSQL(sql, dialect) {
1525
1351
  try {
1526
- const parser = new Parser();
1527
- return parser.astify(sql, { database: dialect });
1352
+ return SQLParser.astifyChecked(sql, dialect);
1528
1353
  }
1529
1354
  catch {
1530
1355
  // If direct parse fails, try with FOR XML workaround
1531
1356
  const forXmlResult = SQLParser.stripForXmlDirectives(sql);
1532
1357
  if (forXmlResult) {
1533
1358
  try {
1534
- const parser = new Parser();
1535
- const ast = parser.astify(forXmlResult.cleanedSQL, { database: dialect });
1359
+ const ast = SQLParser.astifyChecked(forXmlResult.cleanedSQL, dialect);
1536
1360
  // Restore the original FOR XML clause on the AST
1537
1361
  SQLParser.restoreForXmlOnAST(ast, forXmlResult.originalForXml);
1538
1362
  return ast;
@@ -1544,6 +1368,30 @@ export class SQLParser {
1544
1368
  return null;
1545
1369
  }
1546
1370
  }
1371
+ /**
1372
+ * Parses with node-sql-parser and throws when the result is not a real reading of the SQL.
1373
+ *
1374
+ * The T-SQL grammar accepts some statements it cannot parse — notably a CTE with a
1375
+ * bracket-quoted name, `WITH [x] AS (…) SELECT …` — as a run of bare `name = value`
1376
+ * assignments (`WITH = [x]`, `AS = (…)`, `SELECT = …`). No real statement has that shape, so
1377
+ * such a result is treated as a parse failure and callers take their fallback paths instead
1378
+ * of reading a meaningless tree.
1379
+ */
1380
+ static astifyChecked(sql, dialect) {
1381
+ const ast = new Parser().astify(sql, { database: dialect });
1382
+ if (SQLParser.isMisreadAsAssignments(ast)) {
1383
+ throw new Error('SQLParser: the statement was read as variable assignments, not as SQL');
1384
+ }
1385
+ return ast;
1386
+ }
1387
+ /** Whether any top-level node is a bare assignment wrapper rather than a statement. */
1388
+ static isMisreadAsAssignments(ast) {
1389
+ const statements = Array.isArray(ast) ? ast : [ast];
1390
+ return statements.some(statement => {
1391
+ const node = statement;
1392
+ return !node || (typeof node.type !== 'string' && node.stmt?.type === 'assign');
1393
+ });
1394
+ }
1547
1395
  // ═══════════════════════════════════════════════════
1548
1396
  // Private: Parse Preprocessing (fallback + restoration)
1549
1397
  // ═══════════════════════════════════════════════════
@@ -1551,8 +1399,8 @@ export class SQLParser {
1551
1399
  * Last-resort parse used when a direct parse fails. Rewrites SQL into a
1552
1400
  * form node-sql-parser accepts:
1553
1401
  * 1. Split a trailing `OPTION (...)` query hint (SQL Server).
1554
- * 2. Alias bracket-quoted identifiers whose interior contains
1555
- * parser-defeating characters (`[Active People]`, `[my-cte]`).
1402
+ * 2. Alias bracket-quoted identifiers (`[Active People]`, `[my-cte]`,
1403
+ * bracket-quoted CTE names).
1556
1404
  *
1557
1405
  * Returns the AST plus the data needed to restore the original SQL on
1558
1406
  * {@link ToSQL}. `ast` is `null` when even the rewritten SQL is unparseable
@@ -1582,111 +1430,63 @@ export class SQLParser {
1582
1430
  return { ast, aliasMap, trailingOption };
1583
1431
  }
1584
1432
  /**
1585
- * Token-aware scan for a trailing `OPTION (...)` query hint at the
1586
- * outermost level (outside string literals, quoted identifiers, and
1587
- * comments). Returns the SQL without the clause plus the clause text, or
1588
- * `null` when there is no trailing OPTION.
1433
+ * Finds a trailing query-hint clause (the dialect's {@link SQLParserDialect.QueryHintKeyword},
1434
+ * `OPTION (...)` on SQL Server) at the top level of the statement, outside string literals,
1435
+ * quoted identifiers and comments. Returns the SQL without the clause plus the clause text, or
1436
+ * `null` when the dialect has no hint clause or the statement does not end in one (only a
1437
+ * semicolon may follow it).
1589
1438
  */
1590
1439
  static splitTrailingOption(sql, dialect) {
1591
- const quoteSample = dialect.QuoteIdentifier('x');
1592
- const recognizeBrackets = quoteSample.startsWith('[');
1593
- const recognizeBackticks = quoteSample.startsWith('`');
1594
- const n = sql.length;
1595
- const isWordChar = (ch) => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') ||
1596
- (ch >= '0' && ch <= '9') || ch === '_';
1597
- let i = 0;
1598
- let optionStart = -1;
1599
- while (i < n) {
1600
- const ch = sql[i];
1601
- if (ch === "'") {
1602
- i = SQLParser.skipQuotedFrom(sql, i, "'");
1603
- continue;
1604
- }
1605
- if (ch === '"') {
1606
- i = SQLParser.skipQuotedFrom(sql, i, '"');
1607
- continue;
1608
- }
1609
- if (recognizeBrackets && ch === '[') {
1610
- i = SQLParser.skipQuotedFrom(sql, i, ']');
1611
- continue;
1612
- }
1613
- if (recognizeBackticks && ch === '`') {
1614
- i = SQLParser.skipQuotedFrom(sql, i, '`');
1615
- continue;
1616
- }
1617
- if (ch === '-' && i + 1 < n && sql[i + 1] === '-') {
1618
- while (i < n && sql[i] !== '\n')
1619
- i++;
1620
- continue;
1621
- }
1622
- if (ch === '/' && i + 1 < n && sql[i + 1] === '*') {
1623
- i += 2;
1624
- while (i < n && !(sql[i] === '*' && i + 1 < n && sql[i + 1] === '/'))
1625
- i++;
1626
- if (i < n)
1627
- i += 2;
1628
- continue;
1629
- }
1630
- const prevIsWord = i > 0 && isWordChar(sql[i - 1]);
1631
- if (!prevIsWord && i + 6 <= n && sql.substring(i, i + 6).toUpperCase() === 'OPTION' &&
1632
- (i + 6 === n || !isWordChar(sql[i + 6]))) {
1633
- let j = i + 6;
1634
- while (j < n && /\s/.test(sql[j]))
1635
- j++;
1636
- if (j < n && sql[j] === '(') {
1637
- optionStart = i; // remember the last top-level OPTION (
1638
- i = j;
1639
- continue;
1640
- }
1641
- }
1642
- i++;
1643
- }
1644
- if (optionStart === -1)
1440
+ const keyword = dialect.QueryHintKeyword?.toUpperCase();
1441
+ if (!keyword)
1645
1442
  return null;
1646
- // Match the balanced paren group following OPTION.
1647
- let k = optionStart + 6;
1648
- while (k < n && /\s/.test(sql[k]))
1649
- k++;
1650
- let depth = 0;
1651
- for (; k < n; k++) {
1652
- const ch = sql[k];
1653
- if (ch === "'") {
1654
- k = SQLParser.skipQuotedFrom(sql, k, "'") - 1;
1655
- continue;
1656
- }
1657
- if (ch === '(')
1658
- depth++;
1659
- else if (ch === ')') {
1660
- depth--;
1661
- if (depth === 0) {
1662
- k++;
1663
- break;
1664
- }
1665
- }
1443
+ const tokens = SignificantTokens(LexSQL(sql, dialect));
1444
+ let open = -1;
1445
+ for (let i = 0; i < tokens.length - 1; i++) {
1446
+ if (tokens[i].Depth === 0 && IsKeyword(tokens[i], keyword) && tokens[i + 1].Kind === 'open')
1447
+ open = i;
1666
1448
  }
1667
- if (depth !== 0)
1449
+ if (open === -1)
1450
+ return null;
1451
+ const close = tokens.findIndex((t, k) => k > open + 1 && t.Kind === 'close' && t.Depth === 0);
1452
+ if (close === -1)
1668
1453
  return null; // unbalanced — leave alone
1669
- const rest = sql.substring(k).trim();
1670
- if (rest !== '' && rest !== ';')
1671
- return null; // not a trailing OPTION
1454
+ if (tokens.slice(close + 1).some(t => t.Kind !== 'semicolon'))
1455
+ return null; // not trailing
1672
1456
  return {
1673
- sqlWithoutOption: sql.substring(0, optionStart).trimEnd(),
1674
- optionClause: sql.substring(optionStart, k).trim(),
1457
+ sqlWithoutOption: sql.substring(0, tokens[open].Start).trimEnd(),
1458
+ optionClause: sql.substring(tokens[open].Start, tokens[close].End).trim(),
1675
1459
  };
1676
1460
  }
1461
+ /** The start of every alias name the fallback gives a bracket identifier. */
1462
+ static { this.BRACKET_ALIAS_STEM = '_mjid'; }
1463
+ /** Every alias name {@link aliasPrefixFor} and {@link aliasBracketIdentifiers} can produce. */
1464
+ static { this.ALIAS_NAME = /^_mjid\d*_\d+$/i; }
1465
+ /**
1466
+ * An alias prefix in lower-case text, with its digits captured. The lookahead leaves the
1467
+ * closing `_` unread, so a prefix that starts on that `_` is found too (`_mjid_mjid1_`).
1468
+ */
1469
+ static { this.ALIAS_PREFIX_IN_TEXT = /_mjid(\d*)(?=_)/g; }
1470
+ /** A character that would join an alias written next to it into one longer name. */
1471
+ static { this.NAME_CHAR = /[\w@#$\u0080-\uffff]/; }
1677
1472
  /**
1678
- * Token-aware scan that aliases bracket-quoted identifiers whose interior
1679
- * contains characters node-sql-parser can't handle (`[Active People]`,
1680
- * `[my-cte]`, `[dbo.table]`). Aliases are stable, collision-safe tokens
1681
- * (`_mjid_<seq>`). Applies only to bracket-quoting dialects (SQL Server).
1473
+ * Token-aware scan that aliases every bracket-quoted identifier. node-sql-parser
1474
+ * cannot handle brackets around some identifiers at all — interiors with spaces
1475
+ * or punctuation (`[Active People]`, `[my-cte]`, `[dbo.table]`), and CTE names of
1476
+ * any kind (`WITH [x] AS …`). Applies only to bracket-quoting dialects (SQL Server).
1477
+ *
1478
+ * Each alias is `<prefix><seq>`, with a prefix that does not occur in the SQL
1479
+ * ({@link aliasPrefixFor}). A space keeps an alias apart from a name character or
1480
+ * bracket written right next to the brackets, as SQL Server keeps them apart. So
1481
+ * an alias name appears in the rewritten SQL only where this scan put it.
1682
1482
  *
1683
1483
  * Returns the rewritten SQL plus a forward map (original interior → alias).
1684
1484
  */
1685
- static { this.BRACKET_ALIAS_PREFIX = '_mjid_'; }
1686
1485
  static aliasBracketIdentifiers(sql, dialect) {
1687
1486
  const forward = new Map();
1688
1487
  if (!dialect.QuoteIdentifier('x').startsWith('['))
1689
1488
  return { rewritten: sql, forward };
1489
+ const prefix = SQLParser.aliasPrefixFor(sql);
1690
1490
  const n = sql.length;
1691
1491
  let out = '';
1692
1492
  let i = 0;
@@ -1737,16 +1537,20 @@ export class SQLParser {
1737
1537
  interior += sql[j];
1738
1538
  j++;
1739
1539
  }
1740
- if (interior.length > 0 && /[^A-Za-z0-9_]/.test(interior)) {
1540
+ if (interior.length > 0) {
1741
1541
  let alias = forward.get(interior);
1742
1542
  if (!alias) {
1743
- alias = `${SQLParser.BRACKET_ALIAS_PREFIX}${seq++}`;
1543
+ alias = `${prefix}${seq++}`;
1744
1544
  forward.set(interior, alias);
1745
1545
  }
1746
1546
  // Emit a BARE identifier — node-sql-parser rejects bracket-quoted
1747
1547
  // CTE names entirely, so the alias must be unbracketed. sqlify
1748
1548
  // re-quotes it ([_mjid_0]); restoreAliases handles every form.
1749
- out += alias;
1549
+ // The character before the brackets comes from `sql`. A read from `out`, which
1550
+ // grows by `+=`, copies all of `out` each time.
1551
+ const before = i > 0 && SQLParser.NAME_CHAR.test(sql[i - 1]) ? ' ' : '';
1552
+ const after = j < n && (SQLParser.NAME_CHAR.test(sql[j]) || sql[j] === '[') ? ' ' : '';
1553
+ out += `${before}${alias}${after}`;
1750
1554
  }
1751
1555
  else {
1752
1556
  out += sql.substring(i, j); // leave non-problematic identifiers untouched
@@ -1759,11 +1563,25 @@ export class SQLParser {
1759
1563
  }
1760
1564
  return { rewritten: out, forward };
1761
1565
  }
1566
+ /**
1567
+ * The alias prefix for one SQL text: the first of `_mjid_`, `_mjid1_`, `_mjid2_`, … that does
1568
+ * not occur in it, ignoring case. No name the SQL writes can then equal or contain an alias.
1569
+ * One scan of the text collects the digits of every prefix it contains.
1570
+ */
1571
+ static aliasPrefixFor(sql) {
1572
+ const used = new Set();
1573
+ for (const match of sql.toLowerCase().matchAll(SQLParser.ALIAS_PREFIX_IN_TEXT))
1574
+ used.add(match[1]);
1575
+ let digits = '';
1576
+ for (let k = 1; used.has(digits); k++)
1577
+ digits = String(k);
1578
+ return `${SQLParser.BRACKET_ALIAS_STEM}${digits}_`;
1579
+ }
1762
1580
  /**
1763
1581
  * Reverses bracket-identifier aliasing on a sqlify result. node-sql-parser
1764
1582
  * may emit the alias bare, bracketed, or backticked; all three forms are
1765
- * restored to the original bracketed identifier. Aliases are unique
1766
- * `BRACKET_ALIAS_PREFIX<seq>` tokens, so replacement is unambiguous.
1583
+ * restored to the original bracketed identifier. No alias occurs in the
1584
+ * caller's SQL ({@link aliasPrefixFor}), so replacement is unambiguous.
1767
1585
  */
1768
1586
  static restoreAliases(sql, aliasMap) {
1769
1587
  let out = sql;
@@ -1804,34 +1622,43 @@ export class SQLParser {
1804
1622
  * Returns null if no problematic FOR XML pattern is found.
1805
1623
  */
1806
1624
  static stripForXmlDirectives(sql) {
1807
- // Match FOR XML <directive> with optional quoted arg and optional comma-separated extras
1808
- const forXmlRegex = /\bFOR\s+XML\s+(PATH|RAW|AUTO|EXPLICIT)(\s*\('[^']*'\))?(\s*,\s*[^;]*)?$/i;
1809
- const match = sql.match(forXmlRegex);
1810
- if (!match)
1625
+ // Read from tokens, not a regex: a trailing-clause regex backtracks polynomially on long
1626
+ // whitespace runs, and tokens also keep a FOR XML inside a subquery or string out of it.
1627
+ const tokens = SignificantTokens(LexSQL(sql, SQL_SERVER_LEXING));
1628
+ const forAt = tokens.findIndex((t, i) => t.Depth === 0 && IsKeyword(t, 'FOR') && IsKeyword(tokens[i + 1], 'XML') &&
1629
+ FOR_XML_DIRECTIVES.some(d => IsKeyword(tokens[i + 2], d)));
1630
+ if (forAt === -1)
1631
+ return null;
1632
+ const directive = tokens[forAt + 2].Text.toUpperCase(); // PATH, RAW, etc.
1633
+ let next = forAt + 3;
1634
+ let quotedArg = null;
1635
+ if (tokens[next]?.Kind === 'open' && tokens[next + 1]?.Kind === 'string' && tokens[next + 2]?.Kind === 'close') {
1636
+ quotedArg = sql.substring(tokens[next].Start, tokens[next + 2].End);
1637
+ next += 3;
1638
+ }
1639
+ const rest = tokens.slice(next);
1640
+ // The clause must run to the end of the statement: nothing may follow it except
1641
+ // comma-separated directives, and no statement may follow a semicolon.
1642
+ if (rest.some(t => t.Kind === 'semicolon'))
1643
+ return null;
1644
+ const hasExtraDirectives = rest.length > 0 && rest[0].Kind === 'comma';
1645
+ if (rest.length > 0 && !hasExtraDirectives)
1811
1646
  return null;
1812
- const fullForXml = match[0];
1813
- const directive = match[1].toUpperCase(); // PATH, RAW, etc.
1814
- const hasQuotedArg = !!match[2];
1815
- const hasExtraDirectives = !!match[3];
1816
1647
  // Only needs workaround if there are extra comma-separated directives
1817
1648
  // OR if it's RAW/EXPLICIT with a quoted arg (parser can't handle those)
1818
1649
  const needsWorkaround = hasExtraDirectives ||
1819
- (hasQuotedArg && (directive === 'RAW' || directive === 'EXPLICIT'));
1650
+ (quotedArg !== null && (directive === 'RAW' || directive === 'EXPLICIT'));
1820
1651
  if (!needsWorkaround)
1821
1652
  return null;
1822
1653
  // Simplify to a form the parser accepts:
1823
1654
  // PATH('arg') → PATH('arg') (parser handles this)
1824
1655
  // RAW('arg') → RAW (parser can't handle quoted arg on RAW)
1825
1656
  // Any + comma extras → strip extras
1826
- let simplifiedDirective;
1827
- if (directive === 'PATH' && hasQuotedArg) {
1828
- simplifiedDirective = `FOR XML PATH${match[2]}`;
1829
- }
1830
- else {
1831
- simplifiedDirective = `FOR XML ${directive}`;
1832
- }
1833
- const cleanedSQL = sql.substring(0, match.index) + simplifiedDirective;
1834
- return { cleanedSQL, originalForXml: fullForXml };
1657
+ const simplifiedDirective = directive === 'PATH' && quotedArg !== null
1658
+ ? `FOR XML PATH${quotedArg}`
1659
+ : `FOR XML ${directive}`;
1660
+ const clauseStart = tokens[forAt].Start;
1661
+ return { cleanedSQL: sql.substring(0, clauseStart) + simplifiedDirective, originalForXml: sql.substring(clauseStart) };
1835
1662
  }
1836
1663
  /**
1837
1664
  * Restores the original FOR XML clause text on the AST's `for` property.
@@ -1865,8 +1692,7 @@ export class SQLParser {
1865
1692
  // ═══════════════════════════════════════════════════
1866
1693
  static extractTablesViaAST(sql, dialect) {
1867
1694
  try {
1868
- const parser = new Parser();
1869
- const ast = parser.astify(sql, { database: dialect });
1695
+ const ast = SQLParser.astifyChecked(sql, dialect);
1870
1696
  const tableAliasMap = new Map();
1871
1697
  const columnRefs = new Set();
1872
1698
  const statements = Array.isArray(ast) ? ast : [ast];
@@ -1924,7 +1750,7 @@ export class SQLParser {
1924
1750
  static extractCTEsViaAST(sql, dialect) {
1925
1751
  try {
1926
1752
  const parser = new Parser();
1927
- const ast = parser.astify(sql, { database: dialect });
1753
+ const ast = SQLParser.astifyChecked(sql, dialect);
1928
1754
  const singleAst = (Array.isArray(ast) ? ast[0] : ast);
1929
1755
  if (!singleAst.with || !Array.isArray(singleAst.with) || singleAst.with.length === 0) {
1930
1756
  return null;
@@ -2077,11 +1903,12 @@ export class SQLParser {
2077
1903
  static walkFromItem(fromItem, tableAliasMap, columnRefs) {
2078
1904
  if (!fromItem)
2079
1905
  return;
2080
- if (fromItem.table) {
2081
- const alias = (fromItem.as || fromItem.table);
1906
+ const tableName = SQLParser.unwrapIdentifier(fromItem.table);
1907
+ if (tableName) {
1908
+ const alias = SQLParser.unwrapIdentifier(fromItem.as) ?? tableName;
2082
1909
  tableAliasMap.set(alias, {
2083
- schemaName: fromItem.db || 'dbo',
2084
- tableName: fromItem.table,
1910
+ schemaName: SQLParser.unwrapIdentifier(fromItem.db) || 'dbo',
1911
+ tableName,
2085
1912
  });
2086
1913
  }
2087
1914
  if (fromItem.expr) {
@@ -2095,12 +1922,11 @@ export class SQLParser {
2095
1922
  if (fromItem.using) {
2096
1923
  const usings = Array.isArray(fromItem.using) ? fromItem.using : [fromItem.using];
2097
1924
  for (const col of usings) {
2098
- if (typeof col === 'string') {
2099
- columnRefs.add(col);
2100
- }
2101
- else if (col && typeof col === 'object' && 'column' in col) {
2102
- columnRefs.add(col.column);
2103
- }
1925
+ const name = col && typeof col === 'object' && 'column' in col
1926
+ ? SQLParser.unwrapIdentifier(col.column)
1927
+ : SQLParser.unwrapIdentifier(col);
1928
+ if (name)
1929
+ columnRefs.add(name);
2104
1930
  }
2105
1931
  }
2106
1932
  }
@@ -2108,8 +1934,11 @@ export class SQLParser {
2108
1934
  if (!expr || typeof expr !== 'object')
2109
1935
  return;
2110
1936
  if (expr.type === 'column_ref') {
2111
- const colName = expr.table ? `${expr.table}.${expr.column}` : expr.column;
2112
- columnRefs.add(colName);
1937
+ // The PostgreSQL grammar returns identifier nodes here, not strings.
1938
+ const column = SQLParser.unwrapIdentifier(expr.column);
1939
+ const table = SQLParser.unwrapIdentifier(expr.table);
1940
+ if (column)
1941
+ columnRefs.add(table ? `${table}.${column}` : column);
2113
1942
  }
2114
1943
  if (expr.ast && tableAliasMap) {
2115
1944
  SQLParser.walkASTForExtraction(expr.ast, tableAliasMap, columnRefs);
@@ -2128,6 +1957,16 @@ export class SQLParser {
2128
1957
  }
2129
1958
  if (expr.expr)
2130
1959
  SQLParser.walkExpression(expr.expr, columnRefs, tableAliasMap);
1960
+ // IN (SELECT …) is an expr_list on `value`, not `args`. Without this walk,
1961
+ // ExtractTableRefs misses the subquery FROM (EXISTS uses `args` and was found).
1962
+ if (expr.value != null) {
1963
+ const values = Array.isArray(expr.value) ? expr.value : [expr.value];
1964
+ for (const v of values) {
1965
+ if (v && typeof v === 'object') {
1966
+ SQLParser.walkExpression(v, columnRefs, tableAliasMap);
1967
+ }
1968
+ }
1969
+ }
2131
1970
  }
2132
1971
  // ═══════════════════════════════════════════════════
2133
1972
  // Private: Parameter Analysis