@memberjunction/sql-parser 6.1.3 → 6.1.5

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/callerSqlFunctions.d.ts +9 -0
  2. package/dist/callerSqlFunctions.d.ts.map +1 -0
  3. package/dist/callerSqlFunctions.js +39 -0
  4. package/dist/callerSqlFunctions.js.map +1 -0
  5. package/dist/index.d.ts +7 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +5 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/mj-lexer.d.ts.map +1 -1
  10. package/dist/mj-lexer.js +2 -1
  11. package/dist/mj-lexer.js.map +1 -1
  12. package/dist/mj-placeholder.d.ts +11 -0
  13. package/dist/mj-placeholder.d.ts.map +1 -1
  14. package/dist/mj-placeholder.js +61 -6
  15. package/dist/mj-placeholder.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 +52 -30
  24. package/dist/sql-parser.d.ts.map +1 -1
  25. package/dist/sql-parser.js +180 -372
  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 +159 -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
@@ -412,6 +351,8 @@ export class SQLParser {
412
351
  const n = sql.length;
413
352
  let i = 0;
414
353
  let sawSemicolon = false;
354
+ // A semicolon before any content (the `;WITH` idiom) separates nothing.
355
+ let sawContent = false;
415
356
  while (i < n) {
416
357
  const c = sql[i];
417
358
  // line / block comments
@@ -433,11 +374,15 @@ export class SQLParser {
433
374
  (recognizeBrackets && c === '[') ||
434
375
  (recognizeBackticks && c === '`')) {
435
376
  const close = c === '[' ? ']' : c;
377
+ if (sawSemicolon)
378
+ return true;
379
+ sawContent = true;
436
380
  i = SQLParser.skipQuotedFrom(sql, i, close);
437
381
  continue;
438
382
  }
439
383
  if (c === ';') {
440
- sawSemicolon = true;
384
+ if (sawContent)
385
+ sawSemicolon = true;
441
386
  i++;
442
387
  continue;
443
388
  }
@@ -449,143 +394,24 @@ export class SQLParser {
449
394
  // semicolon already appeared, this content is a second statement
450
395
  if (sawSemicolon)
451
396
  return true;
397
+ sawContent = true;
452
398
  i++;
453
399
  }
454
400
  return false;
455
401
  }
456
402
  /**
457
- * Strip line and block comments from SQL, preserving content inside
458
- * string literals and quoted identifiers. Block comments support nesting.
403
+ * Strip line and block comments from SQL, preserving content inside string literals and
404
+ * quoted identifiers. Block comments nest. A block comment is replaced by a space, so two
405
+ * tokens it separated with no whitespace stay apart; a line comment's ending newline is kept.
459
406
  *
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.
407
+ * The dialect determines which literal and identifier forms are recognized: SQL Server
408
+ * `[…]`, PostgreSQL `E'…'` and dollar-quoted strings (`$$…$$`, `$tag$…$tag$`), MySQL
409
+ * `` `…` ``. Double-quoted identifiers are honored on every dialect.
463
410
  */
464
411
  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;
412
+ return LexSQL(sql, dialect)
413
+ .map(t => t.Kind !== 'comment' ? t.Text : t.Text.startsWith('/*') ? ' ' : '')
414
+ .join('');
589
415
  }
590
416
  /**
591
417
  * Convert a single AST expression node to a SQL string.
@@ -652,8 +478,7 @@ export class SQLParser {
652
478
  const columnRefs = new Set();
653
479
  if (usedAST) {
654
480
  try {
655
- const parser = new Parser();
656
- const ast = parser.astify(cleanSQL, { database: parserDialect });
481
+ const ast = SQLParser.astifyChecked(cleanSQL, parserDialect);
657
482
  const statements = Array.isArray(ast) ? ast : [ast];
658
483
  for (const stmt of statements) {
659
484
  SQLParser.walkASTForExtraction(stmt, tableAliasMap, columnRefs);
@@ -718,8 +543,7 @@ export class SQLParser {
718
543
  const tableAliasMap = new Map();
719
544
  const columnRefs = new Set();
720
545
  try {
721
- const parser = new Parser();
722
- const ast = parser.astify(cleanSQL, { database: parserDialect });
546
+ const ast = SQLParser.astifyChecked(cleanSQL, parserDialect);
723
547
  const statements = Array.isArray(ast) ? ast : [ast];
724
548
  for (const statement of statements) {
725
549
  SQLParser.walkASTForExtraction(statement, tableAliasMap, columnRefs);
@@ -752,8 +576,7 @@ export class SQLParser {
752
576
  return [];
753
577
  const cleanSQL = SQLParser.getCleanSQL(sql);
754
578
  try {
755
- const parser = new Parser();
756
- const ast = parser.astify(cleanSQL, { database: dialect.ParserDialect });
579
+ const ast = SQLParser.astifyChecked(cleanSQL, dialect.ParserDialect);
757
580
  const statements = Array.isArray(ast) ? ast : [ast];
758
581
  const columns = [];
759
582
  for (const statement of statements) {
@@ -928,8 +751,9 @@ export class SQLParser {
928
751
  }
929
752
  // ─── MJ Template Extraction ────────────────────────
930
753
  /**
931
- * Renames a template variable in all `{{ variable | filters }}` expressions throughout the SQL.
932
- * Preserves the filter chain and whitespace formatting.
754
+ * Renames a template variable throughout the SQL: in every `{{ variable | filters }}`
755
+ * expression, preserving the filter chain, and in every read of it inside `{% if %}`,
756
+ * `{% elif %}`, `{% for %}` and `{% set %}` tags.
933
757
  *
934
758
  * Example: `RenameTemplateVariable("WHERE x = {{ region | sqlString }}", "region", "userRegion")`
935
759
  * → `"WHERE x = {{ userRegion | sqlString }}"`
@@ -937,19 +761,7 @@ export class SQLParser {
937
761
  * Uses MJLexer for deterministic token identification — no regex guessing.
938
762
  */
939
763
  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;
764
+ return SQLParser.replaceTemplateVariable(sql, oldName, token => SQLParser.rebuildTemplateExpr(newName, token.parsed.filters), newName);
953
765
  }
954
766
  /**
955
767
  * Substitutes a template variable with a literal value in all `{{ variable | filters }}` expressions.
@@ -959,19 +771,34 @@ export class SQLParser {
959
771
  * Example: `SubstituteTemplateVariable("WHERE x = {{ region | sqlString }}", "region", "'West'")`
960
772
  * → `"WHERE x = 'West'"`
961
773
  *
774
+ * When `tagLiteral` is given, reads of the variable inside `{% if %}`, `{% elif %}`,
775
+ * `{% for %}` and `{% set %}` tags are replaced with it too, so conditions see the value.
776
+ * It must be a template-language literal (`"West"`, `42`), not a SQL one.
777
+ *
962
778
  * Uses MJLexer for deterministic token identification — no regex guessing.
963
779
  */
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);
780
+ static SubstituteTemplateVariable(sql, variableName, literalValue, tagLiteral) {
781
+ return SQLParser.replaceTemplateVariable(sql, variableName, () => literalValue, tagLiteral);
782
+ }
783
+ /**
784
+ * Replaces a variable's `{{ }}` expressions with `exprText(token)` and, when `tagText` is
785
+ * given, its reads inside block tags with `tagText`. Edits apply from the end of the SQL so
786
+ * earlier offsets stay valid.
787
+ */
788
+ static replaceTemplateVariable(sql, variableName, exprText, tagText) {
789
+ const nameLower = variableName.toLowerCase();
790
+ const edits = [];
791
+ for (const token of MJLexer.Tokenize(sql)) {
792
+ if (token.type === 'MJ_TEMPLATE_EXPR' && token.parsed.variable.toLowerCase() === nameLower) {
793
+ edits.push({ token, text: exprText(token) });
794
+ }
795
+ else if (tagText !== undefined && VARIABLE_READING_TAGS.has(token.type)) {
796
+ edits.push({ token, text: ReplaceVariableInTag(token.raw, variableName, tagText) });
797
+ }
798
+ }
972
799
  let result = sql;
973
- for (const token of matches) {
974
- result = result.substring(0, token.start) + literalValue + result.substring(token.end);
800
+ for (const { token, text } of edits.sort((a, b) => b.token.start - a.token.start)) {
801
+ result = result.substring(0, token.start) + text + result.substring(token.end);
975
802
  }
976
803
  return result;
977
804
  }
@@ -1173,16 +1000,27 @@ export class SQLParser {
1173
1000
  const root = varName.split(/[.\s]/, 1)[0];
1174
1001
  if (root.toLowerCase() === 'loop')
1175
1002
  break;
1176
- if (!paramMap.has(varName)) {
1003
+ // A `default(…)` filter renders the expression without the parameter, so a use
1004
+ // with one does not make the parameter required; any use without one does.
1005
+ const defaultValue = SQLParser.extractDefaultValue(parsed.filters);
1006
+ const hasDefault = parsed.filters.some(f => f.name === 'default');
1007
+ const existing = paramMap.get(varName);
1008
+ if (!existing) {
1177
1009
  paramMap.set(varName, {
1178
1010
  name: varName,
1179
1011
  type: SQLParser.inferTypeFromFilters(parsed.filters),
1180
- isRequired: true,
1181
- defaultValue: SQLParser.extractDefaultValue(parsed.filters),
1012
+ isRequired: !hasDefault,
1013
+ defaultValue,
1182
1014
  filters: parsed.filters,
1183
1015
  usageLocations: [],
1184
1016
  });
1185
1017
  }
1018
+ else {
1019
+ if (!hasDefault)
1020
+ existing.isRequired = true;
1021
+ if (existing.defaultValue === null)
1022
+ existing.defaultValue = defaultValue;
1023
+ }
1186
1024
  paramMap.get(varName).usageLocations.push(token.raw);
1187
1025
  break;
1188
1026
  }
@@ -1523,16 +1361,14 @@ export class SQLParser {
1523
1361
  }
1524
1362
  static parseSQL(sql, dialect) {
1525
1363
  try {
1526
- const parser = new Parser();
1527
- return parser.astify(sql, { database: dialect });
1364
+ return SQLParser.astifyChecked(sql, dialect);
1528
1365
  }
1529
1366
  catch {
1530
1367
  // If direct parse fails, try with FOR XML workaround
1531
1368
  const forXmlResult = SQLParser.stripForXmlDirectives(sql);
1532
1369
  if (forXmlResult) {
1533
1370
  try {
1534
- const parser = new Parser();
1535
- const ast = parser.astify(forXmlResult.cleanedSQL, { database: dialect });
1371
+ const ast = SQLParser.astifyChecked(forXmlResult.cleanedSQL, dialect);
1536
1372
  // Restore the original FOR XML clause on the AST
1537
1373
  SQLParser.restoreForXmlOnAST(ast, forXmlResult.originalForXml);
1538
1374
  return ast;
@@ -1544,6 +1380,30 @@ export class SQLParser {
1544
1380
  return null;
1545
1381
  }
1546
1382
  }
1383
+ /**
1384
+ * Parses with node-sql-parser and throws when the result is not a real reading of the SQL.
1385
+ *
1386
+ * The T-SQL grammar accepts some statements it cannot parse — notably a CTE with a
1387
+ * bracket-quoted name, `WITH [x] AS (…) SELECT …` — as a run of bare `name = value`
1388
+ * assignments (`WITH = [x]`, `AS = (…)`, `SELECT = …`). No real statement has that shape, so
1389
+ * such a result is treated as a parse failure and callers take their fallback paths instead
1390
+ * of reading a meaningless tree.
1391
+ */
1392
+ static astifyChecked(sql, dialect) {
1393
+ const ast = new Parser().astify(sql, { database: dialect });
1394
+ if (SQLParser.isMisreadAsAssignments(ast)) {
1395
+ throw new Error('SQLParser: the statement was read as variable assignments, not as SQL');
1396
+ }
1397
+ return ast;
1398
+ }
1399
+ /** Whether any top-level node is a bare assignment wrapper rather than a statement. */
1400
+ static isMisreadAsAssignments(ast) {
1401
+ const statements = Array.isArray(ast) ? ast : [ast];
1402
+ return statements.some(statement => {
1403
+ const node = statement;
1404
+ return !node || (typeof node.type !== 'string' && node.stmt?.type === 'assign');
1405
+ });
1406
+ }
1547
1407
  // ═══════════════════════════════════════════════════
1548
1408
  // Private: Parse Preprocessing (fallback + restoration)
1549
1409
  // ═══════════════════════════════════════════════════
@@ -1551,8 +1411,8 @@ export class SQLParser {
1551
1411
  * Last-resort parse used when a direct parse fails. Rewrites SQL into a
1552
1412
  * form node-sql-parser accepts:
1553
1413
  * 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]`).
1414
+ * 2. Alias bracket-quoted identifiers (`[Active People]`, `[my-cte]`,
1415
+ * bracket-quoted CTE names).
1556
1416
  *
1557
1417
  * Returns the AST plus the data needed to restore the original SQL on
1558
1418
  * {@link ToSQL}. `ast` is `null` when even the rewritten SQL is unparseable
@@ -1582,102 +1442,39 @@ export class SQLParser {
1582
1442
  return { ast, aliasMap, trailingOption };
1583
1443
  }
1584
1444
  /**
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.
1445
+ * Finds a trailing query-hint clause (the dialect's {@link SQLParserDialect.QueryHintKeyword},
1446
+ * `OPTION (...)` on SQL Server) at the top level of the statement, outside string literals,
1447
+ * quoted identifiers and comments. Returns the SQL without the clause plus the clause text, or
1448
+ * `null` when the dialect has no hint clause or the statement does not end in one (only a
1449
+ * semicolon may follow it).
1589
1450
  */
1590
1451
  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)
1452
+ const keyword = dialect.QueryHintKeyword?.toUpperCase();
1453
+ if (!keyword)
1645
1454
  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
- }
1455
+ const tokens = SignificantTokens(LexSQL(sql, dialect));
1456
+ let open = -1;
1457
+ for (let i = 0; i < tokens.length - 1; i++) {
1458
+ if (tokens[i].Depth === 0 && IsKeyword(tokens[i], keyword) && tokens[i + 1].Kind === 'open')
1459
+ open = i;
1666
1460
  }
1667
- if (depth !== 0)
1461
+ if (open === -1)
1462
+ return null;
1463
+ const close = tokens.findIndex((t, k) => k > open + 1 && t.Kind === 'close' && t.Depth === 0);
1464
+ if (close === -1)
1668
1465
  return null; // unbalanced — leave alone
1669
- const rest = sql.substring(k).trim();
1670
- if (rest !== '' && rest !== ';')
1671
- return null; // not a trailing OPTION
1466
+ if (tokens.slice(close + 1).some(t => t.Kind !== 'semicolon'))
1467
+ return null; // not trailing
1672
1468
  return {
1673
- sqlWithoutOption: sql.substring(0, optionStart).trimEnd(),
1674
- optionClause: sql.substring(optionStart, k).trim(),
1469
+ sqlWithoutOption: sql.substring(0, tokens[open].Start).trimEnd(),
1470
+ optionClause: sql.substring(tokens[open].Start, tokens[close].End).trim(),
1675
1471
  };
1676
1472
  }
1677
1473
  /**
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
1474
+ * Token-aware scan that aliases every bracket-quoted identifier. node-sql-parser
1475
+ * cannot handle brackets around some identifiers at all — interiors with spaces
1476
+ * or punctuation (`[Active People]`, `[my-cte]`, `[dbo.table]`), and CTE names of
1477
+ * any kind (`WITH [x] AS …`). Aliases are stable, collision-safe tokens
1681
1478
  * (`_mjid_<seq>`). Applies only to bracket-quoting dialects (SQL Server).
1682
1479
  *
1683
1480
  * Returns the rewritten SQL plus a forward map (original interior → alias).
@@ -1737,7 +1534,7 @@ export class SQLParser {
1737
1534
  interior += sql[j];
1738
1535
  j++;
1739
1536
  }
1740
- if (interior.length > 0 && /[^A-Za-z0-9_]/.test(interior)) {
1537
+ if (interior.length > 0) {
1741
1538
  let alias = forward.get(interior);
1742
1539
  if (!alias) {
1743
1540
  alias = `${SQLParser.BRACKET_ALIAS_PREFIX}${seq++}`;
@@ -1810,34 +1607,43 @@ export class SQLParser {
1810
1607
  * Returns null if no problematic FOR XML pattern is found.
1811
1608
  */
1812
1609
  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)
1610
+ // Read from tokens, not a regex: a trailing-clause regex backtracks polynomially on long
1611
+ // whitespace runs, and tokens also keep a FOR XML inside a subquery or string out of it.
1612
+ const tokens = SignificantTokens(LexSQL(sql, SQL_SERVER_LEXING));
1613
+ const forAt = tokens.findIndex((t, i) => t.Depth === 0 && IsKeyword(t, 'FOR') && IsKeyword(tokens[i + 1], 'XML') &&
1614
+ FOR_XML_DIRECTIVES.some(d => IsKeyword(tokens[i + 2], d)));
1615
+ if (forAt === -1)
1616
+ return null;
1617
+ const directive = tokens[forAt + 2].Text.toUpperCase(); // PATH, RAW, etc.
1618
+ let next = forAt + 3;
1619
+ let quotedArg = null;
1620
+ if (tokens[next]?.Kind === 'open' && tokens[next + 1]?.Kind === 'string' && tokens[next + 2]?.Kind === 'close') {
1621
+ quotedArg = sql.substring(tokens[next].Start, tokens[next + 2].End);
1622
+ next += 3;
1623
+ }
1624
+ const rest = tokens.slice(next);
1625
+ // The clause must run to the end of the statement: nothing may follow it except
1626
+ // comma-separated directives, and no statement may follow a semicolon.
1627
+ if (rest.some(t => t.Kind === 'semicolon'))
1628
+ return null;
1629
+ const hasExtraDirectives = rest.length > 0 && rest[0].Kind === 'comma';
1630
+ if (rest.length > 0 && !hasExtraDirectives)
1817
1631
  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
1632
  // Only needs workaround if there are extra comma-separated directives
1823
1633
  // OR if it's RAW/EXPLICIT with a quoted arg (parser can't handle those)
1824
1634
  const needsWorkaround = hasExtraDirectives ||
1825
- (hasQuotedArg && (directive === 'RAW' || directive === 'EXPLICIT'));
1635
+ (quotedArg !== null && (directive === 'RAW' || directive === 'EXPLICIT'));
1826
1636
  if (!needsWorkaround)
1827
1637
  return null;
1828
1638
  // Simplify to a form the parser accepts:
1829
1639
  // PATH('arg') → PATH('arg') (parser handles this)
1830
1640
  // RAW('arg') → RAW (parser can't handle quoted arg on RAW)
1831
1641
  // 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 };
1642
+ const simplifiedDirective = directive === 'PATH' && quotedArg !== null
1643
+ ? `FOR XML PATH${quotedArg}`
1644
+ : `FOR XML ${directive}`;
1645
+ const clauseStart = tokens[forAt].Start;
1646
+ return { cleanedSQL: sql.substring(0, clauseStart) + simplifiedDirective, originalForXml: sql.substring(clauseStart) };
1841
1647
  }
1842
1648
  /**
1843
1649
  * Restores the original FOR XML clause text on the AST's `for` property.
@@ -1871,8 +1677,7 @@ export class SQLParser {
1871
1677
  // ═══════════════════════════════════════════════════
1872
1678
  static extractTablesViaAST(sql, dialect) {
1873
1679
  try {
1874
- const parser = new Parser();
1875
- const ast = parser.astify(sql, { database: dialect });
1680
+ const ast = SQLParser.astifyChecked(sql, dialect);
1876
1681
  const tableAliasMap = new Map();
1877
1682
  const columnRefs = new Set();
1878
1683
  const statements = Array.isArray(ast) ? ast : [ast];
@@ -1930,7 +1735,7 @@ export class SQLParser {
1930
1735
  static extractCTEsViaAST(sql, dialect) {
1931
1736
  try {
1932
1737
  const parser = new Parser();
1933
- const ast = parser.astify(sql, { database: dialect });
1738
+ const ast = SQLParser.astifyChecked(sql, dialect);
1934
1739
  const singleAst = (Array.isArray(ast) ? ast[0] : ast);
1935
1740
  if (!singleAst.with || !Array.isArray(singleAst.with) || singleAst.with.length === 0) {
1936
1741
  return null;
@@ -2083,11 +1888,12 @@ export class SQLParser {
2083
1888
  static walkFromItem(fromItem, tableAliasMap, columnRefs) {
2084
1889
  if (!fromItem)
2085
1890
  return;
2086
- if (fromItem.table) {
2087
- const alias = (fromItem.as || fromItem.table);
1891
+ const tableName = SQLParser.unwrapIdentifier(fromItem.table);
1892
+ if (tableName) {
1893
+ const alias = SQLParser.unwrapIdentifier(fromItem.as) ?? tableName;
2088
1894
  tableAliasMap.set(alias, {
2089
- schemaName: fromItem.db || 'dbo',
2090
- tableName: fromItem.table,
1895
+ schemaName: SQLParser.unwrapIdentifier(fromItem.db) || 'dbo',
1896
+ tableName,
2091
1897
  });
2092
1898
  }
2093
1899
  if (fromItem.expr) {
@@ -2101,12 +1907,11 @@ export class SQLParser {
2101
1907
  if (fromItem.using) {
2102
1908
  const usings = Array.isArray(fromItem.using) ? fromItem.using : [fromItem.using];
2103
1909
  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
- }
1910
+ const name = col && typeof col === 'object' && 'column' in col
1911
+ ? SQLParser.unwrapIdentifier(col.column)
1912
+ : SQLParser.unwrapIdentifier(col);
1913
+ if (name)
1914
+ columnRefs.add(name);
2110
1915
  }
2111
1916
  }
2112
1917
  }
@@ -2114,8 +1919,11 @@ export class SQLParser {
2114
1919
  if (!expr || typeof expr !== 'object')
2115
1920
  return;
2116
1921
  if (expr.type === 'column_ref') {
2117
- const colName = expr.table ? `${expr.table}.${expr.column}` : expr.column;
2118
- columnRefs.add(colName);
1922
+ // The PostgreSQL grammar returns identifier nodes here, not strings.
1923
+ const column = SQLParser.unwrapIdentifier(expr.column);
1924
+ const table = SQLParser.unwrapIdentifier(expr.table);
1925
+ if (column)
1926
+ columnRefs.add(table ? `${table}.${column}` : column);
2119
1927
  }
2120
1928
  if (expr.ast && tableAliasMap) {
2121
1929
  SQLParser.walkASTForExtraction(expr.ast, tableAliasMap, columnRefs);