@memberjunction/sql-parser 6.2.0-edge.2 → 6.2.0-edge.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 (39) hide show
  1. package/dist/aggregateExpression.d.ts +39 -0
  2. package/dist/aggregateExpression.d.ts.map +1 -0
  3. package/dist/aggregateExpression.js +447 -0
  4. package/dist/aggregateExpression.js.map +1 -0
  5. package/dist/callerSqlFunctions.d.ts +9 -0
  6. package/dist/callerSqlFunctions.d.ts.map +1 -0
  7. package/dist/callerSqlFunctions.js +39 -0
  8. package/dist/callerSqlFunctions.js.map +1 -0
  9. package/dist/index.d.ts +9 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +7 -0
  12. package/dist/index.js.map +1 -1
  13. package/dist/mj-lexer.d.ts.map +1 -1
  14. package/dist/mj-lexer.js +2 -1
  15. package/dist/mj-lexer.js.map +1 -1
  16. package/dist/orderByAnalyzer.d.ts.map +1 -1
  17. package/dist/orderByAnalyzer.js +40 -18
  18. package/dist/orderByAnalyzer.js.map +1 -1
  19. package/dist/pagingShape.d.ts +59 -0
  20. package/dist/pagingShape.d.ts.map +1 -0
  21. package/dist/pagingShape.js +185 -0
  22. package/dist/pagingShape.js.map +1 -0
  23. package/dist/sql-parser.d.ts +57 -30
  24. package/dist/sql-parser.d.ts.map +1 -1
  25. package/dist/sql-parser.js +185 -410
  26. package/dist/sql-parser.js.map +1 -1
  27. package/dist/sqlLexer.d.ts +48 -0
  28. package/dist/sqlLexer.d.ts.map +1 -0
  29. package/dist/sqlLexer.js +160 -0
  30. package/dist/sqlLexer.js.map +1 -0
  31. package/dist/sqlShape.d.ts +49 -0
  32. package/dist/sqlShape.d.ts.map +1 -0
  33. package/dist/sqlShape.js +138 -0
  34. package/dist/sqlShape.js.map +1 -0
  35. package/dist/templateTagVariables.d.ts +17 -0
  36. package/dist/templateTagVariables.d.ts.map +1 -0
  37. package/dist/templateTagVariables.js +91 -0
  38. package/dist/templateTagVariables.js.map +1 -0
  39. 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}.
@@ -310,88 +317,20 @@ export class SQLParser {
310
317
  return root;
311
318
  }
312
319
  /**
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.
320
+ * Whether the statement ends in a clause that cannot legally appear inside a derived table,
321
+ * so wrapping it in `SELECT ... FROM (<sql>) AS t` would produce invalid SQL:
322
+ * - `FOR JSON …` / `FOR XML …` at the top level
323
+ * - a trailing query-hint clause ({@link SQLParserDialect.QueryHintKeyword}, `OPTION (…)` on SQL Server)
316
324
  *
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
+ * Only the top level of the statement counts. The same words inside a subquery (a correlated
326
+ * `(SELECT … FOR JSON PATH)` column), a string literal, a quoted identifier or a comment do
327
+ * not stop a wrap.
325
328
  */
326
329
  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;
330
+ const top = SignificantTokens(LexSQL(sql, dialect)).filter(t => t.Depth === 0);
331
+ const hintKeyword = dialect.QueryHintKeyword?.toUpperCase();
332
+ return top.some((t, i) => (IsKeyword(t, 'FOR') && (IsKeyword(top[i + 1], 'JSON') || IsKeyword(top[i + 1], 'XML'))) ||
333
+ (hintKeyword !== undefined && IsKeyword(t, hintKeyword) && top[i + 1]?.Kind === 'open'));
395
334
  }
396
335
  /**
397
336
  * Token-aware detection of stacked statements: a statement-separating
@@ -399,6 +338,11 @@ export class SQLParser {
399
338
  * quoted identifiers, and comments). A single trailing semicolon — or a run
400
339
  * of them followed only by whitespace/comments — is allowed.
401
340
  *
341
+ * Reads the tokens {@link LexSQL} produces for the dialect, so every quoted
342
+ * form the database recognizes hides its contents: `[…]` identifiers on SQL
343
+ * Server, `E'…'` strings with backslash escapes and dollar-quoted strings on
344
+ * PostgreSQL, and nested block comments on both.
345
+ *
402
346
  * Unlike an AST check, this fires even when the trailing payload makes the
403
347
  * SQL unparseable (`SELECT 1; EXEC xp_cmdshell '…'`, `SELECT 1; WAITFOR
404
348
  * DELAY '…'`), which is exactly the stacked-injection class an AST scan
@@ -406,186 +350,35 @@ export class SQLParser {
406
350
  * read query must be a single statement, so any internal `;` is rejected.
407
351
  */
408
352
  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
353
  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++;
354
+ // A semicolon before any content (the `;WITH` idiom) separates nothing.
355
+ let sawContent = false;
356
+ for (const token of SignificantTokens(LexSQL(sql, dialect))) {
357
+ if (token.Kind === 'semicolon') {
358
+ if (sawContent)
359
+ sawSemicolon = true;
446
360
  continue;
447
361
  }
448
- // any other character is real statement content; if a top-level
449
- // semicolon already appeared, this content is a second statement
362
+ // Real content after a separating semicolon is a second statement.
450
363
  if (sawSemicolon)
451
364
  return true;
452
- i++;
365
+ sawContent = true;
453
366
  }
454
367
  return false;
455
368
  }
456
369
  /**
457
- * Strip line and block comments from SQL, preserving content inside
458
- * string literals and quoted identifiers. Block comments support nesting.
370
+ * Strip line and block comments from SQL, preserving content inside string literals and
371
+ * quoted identifiers. Block comments nest. A block comment is replaced by a space, so two
372
+ * tokens it separated with no whitespace stay apart; a line comment's ending newline is kept.
459
373
  *
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.
374
+ * The dialect determines which literal and identifier forms are recognized: SQL Server
375
+ * `[…]`, PostgreSQL `E'…'` and dollar-quoted strings (`$$…$$`, `$tag$…$tag$`), MySQL
376
+ * `` `…` ``. Double-quoted identifiers are honored on every dialect.
463
377
  */
464
378
  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;
379
+ return LexSQL(sql, dialect)
380
+ .map(t => t.Kind !== 'comment' ? t.Text : t.Text.startsWith('/*') ? ' ' : '')
381
+ .join('');
589
382
  }
590
383
  /**
591
384
  * Convert a single AST expression node to a SQL string.
@@ -652,8 +445,7 @@ export class SQLParser {
652
445
  const columnRefs = new Set();
653
446
  if (usedAST) {
654
447
  try {
655
- const parser = new Parser();
656
- const ast = parser.astify(cleanSQL, { database: parserDialect });
448
+ const ast = SQLParser.astifyChecked(cleanSQL, parserDialect);
657
449
  const statements = Array.isArray(ast) ? ast : [ast];
658
450
  for (const stmt of statements) {
659
451
  SQLParser.walkASTForExtraction(stmt, tableAliasMap, columnRefs);
@@ -718,8 +510,7 @@ export class SQLParser {
718
510
  const tableAliasMap = new Map();
719
511
  const columnRefs = new Set();
720
512
  try {
721
- const parser = new Parser();
722
- const ast = parser.astify(cleanSQL, { database: parserDialect });
513
+ const ast = SQLParser.astifyChecked(cleanSQL, parserDialect);
723
514
  const statements = Array.isArray(ast) ? ast : [ast];
724
515
  for (const statement of statements) {
725
516
  SQLParser.walkASTForExtraction(statement, tableAliasMap, columnRefs);
@@ -752,8 +543,7 @@ export class SQLParser {
752
543
  return [];
753
544
  const cleanSQL = SQLParser.getCleanSQL(sql);
754
545
  try {
755
- const parser = new Parser();
756
- const ast = parser.astify(cleanSQL, { database: dialect.ParserDialect });
546
+ const ast = SQLParser.astifyChecked(cleanSQL, dialect.ParserDialect);
757
547
  const statements = Array.isArray(ast) ? ast : [ast];
758
548
  const columns = [];
759
549
  for (const statement of statements) {
@@ -928,8 +718,9 @@ export class SQLParser {
928
718
  }
929
719
  // ─── MJ Template Extraction ────────────────────────
930
720
  /**
931
- * Renames a template variable in all `{{ variable | filters }}` expressions throughout the SQL.
932
- * Preserves the filter chain and whitespace formatting.
721
+ * Renames a template variable throughout the SQL: in every `{{ variable | filters }}`
722
+ * expression, preserving the filter chain, and in every read of it inside `{% if %}`,
723
+ * `{% elif %}`, `{% for %}` and `{% set %}` tags.
933
724
  *
934
725
  * Example: `RenameTemplateVariable("WHERE x = {{ region | sqlString }}", "region", "userRegion")`
935
726
  * → `"WHERE x = {{ userRegion | sqlString }}"`
@@ -937,19 +728,7 @@ export class SQLParser {
937
728
  * Uses MJLexer for deterministic token identification — no regex guessing.
938
729
  */
939
730
  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;
731
+ return SQLParser.replaceTemplateVariable(sql, oldName, token => SQLParser.rebuildTemplateExpr(newName, token.parsed.filters), newName);
953
732
  }
954
733
  /**
955
734
  * Substitutes a template variable with a literal value in all `{{ variable | filters }}` expressions.
@@ -959,19 +738,34 @@ export class SQLParser {
959
738
  * Example: `SubstituteTemplateVariable("WHERE x = {{ region | sqlString }}", "region", "'West'")`
960
739
  * → `"WHERE x = 'West'"`
961
740
  *
741
+ * When `tagLiteral` is given, reads of the variable inside `{% if %}`, `{% elif %}`,
742
+ * `{% for %}` and `{% set %}` tags are replaced with it too, so conditions see the value.
743
+ * It must be a template-language literal (`"West"`, `42`), not a SQL one.
744
+ *
962
745
  * Uses MJLexer for deterministic token identification — no regex guessing.
963
746
  */
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);
747
+ static SubstituteTemplateVariable(sql, variableName, literalValue, tagLiteral) {
748
+ return SQLParser.replaceTemplateVariable(sql, variableName, () => literalValue, tagLiteral);
749
+ }
750
+ /**
751
+ * Replaces a variable's `{{ }}` expressions with `exprText(token)` and, when `tagText` is
752
+ * given, its reads inside block tags with `tagText`. Edits apply from the end of the SQL so
753
+ * earlier offsets stay valid.
754
+ */
755
+ static replaceTemplateVariable(sql, variableName, exprText, tagText) {
756
+ const nameLower = variableName.toLowerCase();
757
+ const edits = [];
758
+ for (const token of MJLexer.Tokenize(sql)) {
759
+ if (token.type === 'MJ_TEMPLATE_EXPR' && token.parsed.variable.toLowerCase() === nameLower) {
760
+ edits.push({ token, text: exprText(token) });
761
+ }
762
+ else if (tagText !== undefined && VARIABLE_READING_TAGS.has(token.type)) {
763
+ edits.push({ token, text: ReplaceVariableInTag(token.raw, variableName, tagText) });
764
+ }
765
+ }
972
766
  let result = sql;
973
- for (const token of matches) {
974
- result = result.substring(0, token.start) + literalValue + result.substring(token.end);
767
+ for (const { token, text } of edits.sort((a, b) => b.token.start - a.token.start)) {
768
+ result = result.substring(0, token.start) + text + result.substring(token.end);
975
769
  }
976
770
  return result;
977
771
  }
@@ -1173,16 +967,27 @@ export class SQLParser {
1173
967
  const root = varName.split(/[.\s]/, 1)[0];
1174
968
  if (root.toLowerCase() === 'loop')
1175
969
  break;
1176
- if (!paramMap.has(varName)) {
970
+ // A `default(…)` filter renders the expression without the parameter, so a use
971
+ // with one does not make the parameter required; any use without one does.
972
+ const defaultValue = SQLParser.extractDefaultValue(parsed.filters);
973
+ const hasDefault = parsed.filters.some(f => f.name === 'default');
974
+ const existing = paramMap.get(varName);
975
+ if (!existing) {
1177
976
  paramMap.set(varName, {
1178
977
  name: varName,
1179
978
  type: SQLParser.inferTypeFromFilters(parsed.filters),
1180
- isRequired: true,
1181
- defaultValue: SQLParser.extractDefaultValue(parsed.filters),
979
+ isRequired: !hasDefault,
980
+ defaultValue,
1182
981
  filters: parsed.filters,
1183
982
  usageLocations: [],
1184
983
  });
1185
984
  }
985
+ else {
986
+ if (!hasDefault)
987
+ existing.isRequired = true;
988
+ if (existing.defaultValue === null)
989
+ existing.defaultValue = defaultValue;
990
+ }
1186
991
  paramMap.get(varName).usageLocations.push(token.raw);
1187
992
  break;
1188
993
  }
@@ -1523,16 +1328,14 @@ export class SQLParser {
1523
1328
  }
1524
1329
  static parseSQL(sql, dialect) {
1525
1330
  try {
1526
- const parser = new Parser();
1527
- return parser.astify(sql, { database: dialect });
1331
+ return SQLParser.astifyChecked(sql, dialect);
1528
1332
  }
1529
1333
  catch {
1530
1334
  // If direct parse fails, try with FOR XML workaround
1531
1335
  const forXmlResult = SQLParser.stripForXmlDirectives(sql);
1532
1336
  if (forXmlResult) {
1533
1337
  try {
1534
- const parser = new Parser();
1535
- const ast = parser.astify(forXmlResult.cleanedSQL, { database: dialect });
1338
+ const ast = SQLParser.astifyChecked(forXmlResult.cleanedSQL, dialect);
1536
1339
  // Restore the original FOR XML clause on the AST
1537
1340
  SQLParser.restoreForXmlOnAST(ast, forXmlResult.originalForXml);
1538
1341
  return ast;
@@ -1544,6 +1347,30 @@ export class SQLParser {
1544
1347
  return null;
1545
1348
  }
1546
1349
  }
1350
+ /**
1351
+ * Parses with node-sql-parser and throws when the result is not a real reading of the SQL.
1352
+ *
1353
+ * The T-SQL grammar accepts some statements it cannot parse — notably a CTE with a
1354
+ * bracket-quoted name, `WITH [x] AS (…) SELECT …` — as a run of bare `name = value`
1355
+ * assignments (`WITH = [x]`, `AS = (…)`, `SELECT = …`). No real statement has that shape, so
1356
+ * such a result is treated as a parse failure and callers take their fallback paths instead
1357
+ * of reading a meaningless tree.
1358
+ */
1359
+ static astifyChecked(sql, dialect) {
1360
+ const ast = new Parser().astify(sql, { database: dialect });
1361
+ if (SQLParser.isMisreadAsAssignments(ast)) {
1362
+ throw new Error('SQLParser: the statement was read as variable assignments, not as SQL');
1363
+ }
1364
+ return ast;
1365
+ }
1366
+ /** Whether any top-level node is a bare assignment wrapper rather than a statement. */
1367
+ static isMisreadAsAssignments(ast) {
1368
+ const statements = Array.isArray(ast) ? ast : [ast];
1369
+ return statements.some(statement => {
1370
+ const node = statement;
1371
+ return !node || (typeof node.type !== 'string' && node.stmt?.type === 'assign');
1372
+ });
1373
+ }
1547
1374
  // ═══════════════════════════════════════════════════
1548
1375
  // Private: Parse Preprocessing (fallback + restoration)
1549
1376
  // ═══════════════════════════════════════════════════
@@ -1551,8 +1378,8 @@ export class SQLParser {
1551
1378
  * Last-resort parse used when a direct parse fails. Rewrites SQL into a
1552
1379
  * form node-sql-parser accepts:
1553
1380
  * 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]`).
1381
+ * 2. Alias bracket-quoted identifiers (`[Active People]`, `[my-cte]`,
1382
+ * bracket-quoted CTE names).
1556
1383
  *
1557
1384
  * Returns the AST plus the data needed to restore the original SQL on
1558
1385
  * {@link ToSQL}. `ast` is `null` when even the rewritten SQL is unparseable
@@ -1582,102 +1409,39 @@ export class SQLParser {
1582
1409
  return { ast, aliasMap, trailingOption };
1583
1410
  }
1584
1411
  /**
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.
1412
+ * Finds a trailing query-hint clause (the dialect's {@link SQLParserDialect.QueryHintKeyword},
1413
+ * `OPTION (...)` on SQL Server) at the top level of the statement, outside string literals,
1414
+ * quoted identifiers and comments. Returns the SQL without the clause plus the clause text, or
1415
+ * `null` when the dialect has no hint clause or the statement does not end in one (only a
1416
+ * semicolon may follow it).
1589
1417
  */
1590
1418
  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)
1419
+ const keyword = dialect.QueryHintKeyword?.toUpperCase();
1420
+ if (!keyword)
1645
1421
  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
- }
1422
+ const tokens = SignificantTokens(LexSQL(sql, dialect));
1423
+ let open = -1;
1424
+ for (let i = 0; i < tokens.length - 1; i++) {
1425
+ if (tokens[i].Depth === 0 && IsKeyword(tokens[i], keyword) && tokens[i + 1].Kind === 'open')
1426
+ open = i;
1666
1427
  }
1667
- if (depth !== 0)
1428
+ if (open === -1)
1429
+ return null;
1430
+ const close = tokens.findIndex((t, k) => k > open + 1 && t.Kind === 'close' && t.Depth === 0);
1431
+ if (close === -1)
1668
1432
  return null; // unbalanced — leave alone
1669
- const rest = sql.substring(k).trim();
1670
- if (rest !== '' && rest !== ';')
1671
- return null; // not a trailing OPTION
1433
+ if (tokens.slice(close + 1).some(t => t.Kind !== 'semicolon'))
1434
+ return null; // not trailing
1672
1435
  return {
1673
- sqlWithoutOption: sql.substring(0, optionStart).trimEnd(),
1674
- optionClause: sql.substring(optionStart, k).trim(),
1436
+ sqlWithoutOption: sql.substring(0, tokens[open].Start).trimEnd(),
1437
+ optionClause: sql.substring(tokens[open].Start, tokens[close].End).trim(),
1675
1438
  };
1676
1439
  }
1677
1440
  /**
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
1441
+ * Token-aware scan that aliases every bracket-quoted identifier. node-sql-parser
1442
+ * cannot handle brackets around some identifiers at all — interiors with spaces
1443
+ * or punctuation (`[Active People]`, `[my-cte]`, `[dbo.table]`), and CTE names of
1444
+ * any kind (`WITH [x] AS …`). Aliases are stable, collision-safe tokens
1681
1445
  * (`_mjid_<seq>`). Applies only to bracket-quoting dialects (SQL Server).
1682
1446
  *
1683
1447
  * Returns the rewritten SQL plus a forward map (original interior → alias).
@@ -1737,7 +1501,7 @@ export class SQLParser {
1737
1501
  interior += sql[j];
1738
1502
  j++;
1739
1503
  }
1740
- if (interior.length > 0 && /[^A-Za-z0-9_]/.test(interior)) {
1504
+ if (interior.length > 0) {
1741
1505
  let alias = forward.get(interior);
1742
1506
  if (!alias) {
1743
1507
  alias = `${SQLParser.BRACKET_ALIAS_PREFIX}${seq++}`;
@@ -1810,34 +1574,43 @@ export class SQLParser {
1810
1574
  * Returns null if no problematic FOR XML pattern is found.
1811
1575
  */
1812
1576
  static stripForXmlDirectives(sql) {
1813
- // Match FOR XML <directive> with optional quoted arg and optional comma-separated extras
1814
- const forXmlRegex = /\bFOR\s+XML\s+(PATH|RAW|AUTO|EXPLICIT)(\s*\('[^']*'\))?(\s*,\s*[^;]*)?$/i;
1815
- const match = sql.match(forXmlRegex);
1816
- if (!match)
1577
+ // Read from tokens, not a regex: a trailing-clause regex backtracks polynomially on long
1578
+ // whitespace runs, and tokens also keep a FOR XML inside a subquery or string out of it.
1579
+ const tokens = SignificantTokens(LexSQL(sql, SQL_SERVER_LEXING));
1580
+ const forAt = tokens.findIndex((t, i) => t.Depth === 0 && IsKeyword(t, 'FOR') && IsKeyword(tokens[i + 1], 'XML') &&
1581
+ FOR_XML_DIRECTIVES.some(d => IsKeyword(tokens[i + 2], d)));
1582
+ if (forAt === -1)
1583
+ return null;
1584
+ const directive = tokens[forAt + 2].Text.toUpperCase(); // PATH, RAW, etc.
1585
+ let next = forAt + 3;
1586
+ let quotedArg = null;
1587
+ if (tokens[next]?.Kind === 'open' && tokens[next + 1]?.Kind === 'string' && tokens[next + 2]?.Kind === 'close') {
1588
+ quotedArg = sql.substring(tokens[next].Start, tokens[next + 2].End);
1589
+ next += 3;
1590
+ }
1591
+ const rest = tokens.slice(next);
1592
+ // The clause must run to the end of the statement: nothing may follow it except
1593
+ // comma-separated directives, and no statement may follow a semicolon.
1594
+ if (rest.some(t => t.Kind === 'semicolon'))
1595
+ return null;
1596
+ const hasExtraDirectives = rest.length > 0 && rest[0].Kind === 'comma';
1597
+ if (rest.length > 0 && !hasExtraDirectives)
1817
1598
  return null;
1818
- const fullForXml = match[0];
1819
- const directive = match[1].toUpperCase(); // PATH, RAW, etc.
1820
- const hasQuotedArg = !!match[2];
1821
- const hasExtraDirectives = !!match[3];
1822
1599
  // Only needs workaround if there are extra comma-separated directives
1823
1600
  // OR if it's RAW/EXPLICIT with a quoted arg (parser can't handle those)
1824
1601
  const needsWorkaround = hasExtraDirectives ||
1825
- (hasQuotedArg && (directive === 'RAW' || directive === 'EXPLICIT'));
1602
+ (quotedArg !== null && (directive === 'RAW' || directive === 'EXPLICIT'));
1826
1603
  if (!needsWorkaround)
1827
1604
  return null;
1828
1605
  // Simplify to a form the parser accepts:
1829
1606
  // PATH('arg') → PATH('arg') (parser handles this)
1830
1607
  // RAW('arg') → RAW (parser can't handle quoted arg on RAW)
1831
1608
  // Any + comma extras → strip extras
1832
- let simplifiedDirective;
1833
- if (directive === 'PATH' && hasQuotedArg) {
1834
- simplifiedDirective = `FOR XML PATH${match[2]}`;
1835
- }
1836
- else {
1837
- simplifiedDirective = `FOR XML ${directive}`;
1838
- }
1839
- const cleanedSQL = sql.substring(0, match.index) + simplifiedDirective;
1840
- return { cleanedSQL, originalForXml: fullForXml };
1609
+ const simplifiedDirective = directive === 'PATH' && quotedArg !== null
1610
+ ? `FOR XML PATH${quotedArg}`
1611
+ : `FOR XML ${directive}`;
1612
+ const clauseStart = tokens[forAt].Start;
1613
+ return { cleanedSQL: sql.substring(0, clauseStart) + simplifiedDirective, originalForXml: sql.substring(clauseStart) };
1841
1614
  }
1842
1615
  /**
1843
1616
  * Restores the original FOR XML clause text on the AST's `for` property.
@@ -1871,8 +1644,7 @@ export class SQLParser {
1871
1644
  // ═══════════════════════════════════════════════════
1872
1645
  static extractTablesViaAST(sql, dialect) {
1873
1646
  try {
1874
- const parser = new Parser();
1875
- const ast = parser.astify(sql, { database: dialect });
1647
+ const ast = SQLParser.astifyChecked(sql, dialect);
1876
1648
  const tableAliasMap = new Map();
1877
1649
  const columnRefs = new Set();
1878
1650
  const statements = Array.isArray(ast) ? ast : [ast];
@@ -1930,7 +1702,7 @@ export class SQLParser {
1930
1702
  static extractCTEsViaAST(sql, dialect) {
1931
1703
  try {
1932
1704
  const parser = new Parser();
1933
- const ast = parser.astify(sql, { database: dialect });
1705
+ const ast = SQLParser.astifyChecked(sql, dialect);
1934
1706
  const singleAst = (Array.isArray(ast) ? ast[0] : ast);
1935
1707
  if (!singleAst.with || !Array.isArray(singleAst.with) || singleAst.with.length === 0) {
1936
1708
  return null;
@@ -2083,11 +1855,12 @@ export class SQLParser {
2083
1855
  static walkFromItem(fromItem, tableAliasMap, columnRefs) {
2084
1856
  if (!fromItem)
2085
1857
  return;
2086
- if (fromItem.table) {
2087
- const alias = (fromItem.as || fromItem.table);
1858
+ const tableName = SQLParser.unwrapIdentifier(fromItem.table);
1859
+ if (tableName) {
1860
+ const alias = SQLParser.unwrapIdentifier(fromItem.as) ?? tableName;
2088
1861
  tableAliasMap.set(alias, {
2089
- schemaName: fromItem.db || 'dbo',
2090
- tableName: fromItem.table,
1862
+ schemaName: SQLParser.unwrapIdentifier(fromItem.db) || 'dbo',
1863
+ tableName,
2091
1864
  });
2092
1865
  }
2093
1866
  if (fromItem.expr) {
@@ -2101,12 +1874,11 @@ export class SQLParser {
2101
1874
  if (fromItem.using) {
2102
1875
  const usings = Array.isArray(fromItem.using) ? fromItem.using : [fromItem.using];
2103
1876
  for (const col of usings) {
2104
- if (typeof col === 'string') {
2105
- columnRefs.add(col);
2106
- }
2107
- else if (col && typeof col === 'object' && 'column' in col) {
2108
- columnRefs.add(col.column);
2109
- }
1877
+ const name = col && typeof col === 'object' && 'column' in col
1878
+ ? SQLParser.unwrapIdentifier(col.column)
1879
+ : SQLParser.unwrapIdentifier(col);
1880
+ if (name)
1881
+ columnRefs.add(name);
2110
1882
  }
2111
1883
  }
2112
1884
  }
@@ -2114,8 +1886,11 @@ export class SQLParser {
2114
1886
  if (!expr || typeof expr !== 'object')
2115
1887
  return;
2116
1888
  if (expr.type === 'column_ref') {
2117
- const colName = expr.table ? `${expr.table}.${expr.column}` : expr.column;
2118
- columnRefs.add(colName);
1889
+ // The PostgreSQL grammar returns identifier nodes here, not strings.
1890
+ const column = SQLParser.unwrapIdentifier(expr.column);
1891
+ const table = SQLParser.unwrapIdentifier(expr.table);
1892
+ if (column)
1893
+ columnRefs.add(table ? `${table}.${column}` : column);
2119
1894
  }
2120
1895
  if (expr.ast && tableAliasMap) {
2121
1896
  SQLParser.walkASTForExtraction(expr.ast, tableAliasMap, columnRefs);