@memberjunction/sql-parser 5.14.0 → 5.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,48 +1,733 @@
1
+ /**
2
+ * SQLParser — Unified parser for MemberJunction's SQL superset
3
+ *
4
+ * Parses SQL that may contain Nunjucks templates ({{ }}, {% %}), composition
5
+ * tokens ({{query:"..."}}), and standard SQL into a structured AST.
6
+ *
7
+ * Three-pass pipeline:
8
+ * 1. MJLexer tokenizes MJ extensions with position tracking
9
+ * 2. MJPlaceholderSubstitution replaces tokens with SQL-safe placeholders
10
+ * 3. node-sql-parser produces the standard SQL AST
11
+ *
12
+ * The result contains both the SQL AST and the MJ token structure,
13
+ * enabling SQL-level analysis and faithful MJ SQL reconstruction.
14
+ */
1
15
  import NodeSqlParser from 'node-sql-parser';
2
16
  const { Parser } = NodeSqlParser;
3
- import * as nunjucks from 'nunjucks';
17
+ import { MJLexer } from './mj-lexer.js';
18
+ import { MJPlaceholderSubstitution } from './mj-placeholder.js';
19
+ // ═══════════════════════════════════════════════════
20
+ // SQLParser class
21
+ // ═══════════════════════════════════════════════════
4
22
  /**
5
- * Reusable SQL parsing utility that extracts table/view references and column references
6
- * from SQL statements using node-sql-parser with a regex fallback.
23
+ * Unified parser for MemberJunction's SQL superset.
24
+ *
25
+ * Handles standard SQL, Nunjucks template expressions (`{{ var | filter }}`),
26
+ * Nunjucks block tags (`{% if %}...{% endif %}`), composition tokens
27
+ * (`{{query:"Path/Name(params)"}}`), and template comments (`{# ... #}`).
7
28
  *
8
- * This class has no dependency on MJ Metadata — it returns raw parse results.
9
- * Callers are responsible for cross-referencing against entity metadata.
29
+ * All methods are static — no instance state is needed.
10
30
  */
11
31
  export class SQLParser {
32
+ // ─── Core Pipeline ─────────────────────────────────
33
+ /**
34
+ * Parse MJ SQL into an extended AST.
35
+ *
36
+ * Pipeline:
37
+ * 1. MJLexer tokenizes MJ extensions
38
+ * 2. MJPlaceholder replaces tokens with SQL-safe placeholders
39
+ * 3. node-sql-parser produces the SQL AST
40
+ *
41
+ * @param sql The MJ SQL string to parse
42
+ * @param dialect SQL dialect ('TransactSQL' | 'PostgresQL', default: 'TransactSQL')
43
+ */
44
+ static Astify(sql, dialect = 'TransactSQL') {
45
+ const mjParse = MJLexer.Parse(sql);
46
+ if (!mjParse.hasMJExtensions) {
47
+ const ast = SQLParser.parseSQL(sql, dialect);
48
+ return {
49
+ ast,
50
+ mjParse,
51
+ positionMap: new Map(),
52
+ strippedTokens: [],
53
+ cleanSQL: sql,
54
+ astParsed: ast !== null,
55
+ dialect,
56
+ };
57
+ }
58
+ const { cleanSQL, positionMap, strippedTokens } = MJPlaceholderSubstitution.Substitute(sql);
59
+ const ast = SQLParser.parseSQL(cleanSQL, dialect);
60
+ return {
61
+ ast,
62
+ mjParse,
63
+ positionMap,
64
+ strippedTokens,
65
+ cleanSQL,
66
+ astParsed: ast !== null,
67
+ dialect,
68
+ };
69
+ }
70
+ /**
71
+ * Reconstruct MJ SQL from an Astify result.
72
+ *
73
+ * For plain SQL: uses node-sql-parser's sqlify for normalized output.
74
+ * For MJ SQL: reconstructs from tokens, preserving all Nunjucks and composition syntax verbatim.
75
+ */
76
+ static Sqlify(result) {
77
+ if (!result.mjParse.hasMJExtensions && result.ast) {
78
+ const parser = new Parser();
79
+ const astToSqlify = Array.isArray(result.ast) ? result.ast[0] : result.ast;
80
+ return parser.sqlify(astToSqlify, { database: result.dialect });
81
+ }
82
+ return result.mjParse.tokens.map(t => t.raw).join('');
83
+ }
84
+ // ─── Raw SQL Parsing ────────────────────────────────
12
85
  /**
13
- * Parse a plain SQL statement and extract all table and column references.
14
- * Uses AST parsing with the specified dialect, falls back to regex on failure.
15
- * @param sql The SQL statement to parse
16
- * @param dialect The SQL dialect to use for AST parsing (default: 'TransactSQL')
86
+ * Parse plain SQL into a node-sql-parser AST.
87
+ * Handles FOR XML multi-directive workaround automatically.
88
+ * Returns null if parsing fails.
17
89
  */
18
- static Parse(sql, dialect = 'TransactSQL') {
90
+ static ParseSQL(sql, dialect = 'TransactSQL') {
91
+ return SQLParser.parseSQL(sql, dialect);
92
+ }
93
+ /**
94
+ * Convert a node-sql-parser AST (or array of ASTs) back to a SQL string.
95
+ * This is a thin wrapper around node-sql-parser's sqlify.
96
+ */
97
+ static SqlifyAST(ast, dialect = 'TransactSQL') {
98
+ const parser = new Parser();
99
+ return parser.sqlify(Array.isArray(ast) ? ast[0] : ast, { database: dialect });
100
+ }
101
+ /**
102
+ * Convert a single AST expression node to a SQL string.
103
+ * Useful for extracting ORDER BY terms, column expressions, etc.
104
+ *
105
+ * node-sql-parser's exprToSQL always produces backtick-quoted identifiers
106
+ * regardless of dialect. This method converts to the appropriate quoting:
107
+ * - TransactSQL: backticks → square brackets
108
+ * - PostgresQL: backticks → double quotes
109
+ */
110
+ static ExprToSQL(expr, dialect = 'TransactSQL') {
111
+ const parser = new Parser();
112
+ const sql = parser.exprToSQL(expr);
113
+ if (dialect === 'TransactSQL') {
114
+ return sql.replace(/`([^`]+)`/g, '[$1]');
115
+ }
116
+ if (dialect === 'PostgresQL') {
117
+ return sql.replace(/`([^`]+)`/g, '"$1"');
118
+ }
119
+ return sql;
120
+ }
121
+ // ─── Tokenization ──────────────────────────────────
122
+ /**
123
+ * Tokenize MJ SQL into an ordered list of tokens.
124
+ * Returns MJ tokens (template expressions, composition refs, block tags, comments)
125
+ * interleaved with SQL_TEXT tokens for the plain SQL segments.
126
+ */
127
+ static Tokenize(sql) {
128
+ return MJLexer.Tokenize(sql);
129
+ }
130
+ /**
131
+ * Tokenize and return a summary with boolean flags.
132
+ * Useful for quick checks like "does this SQL have MJ extensions?"
133
+ */
134
+ static Analyze(sql) {
135
+ return MJLexer.Parse(sql);
136
+ }
137
+ // ─── Placeholder Substitution ──────────────────────
138
+ /**
139
+ * Replace MJ tokens with SQL-safe placeholders.
140
+ *
141
+ * Context-aware: `sqlString` → string literal, `sqlNumber` → numeric literal,
142
+ * `sqlIdentifier` → bare identifier. Block tags and comments are stripped.
143
+ * Returns a position map for reversing the substitution.
144
+ */
145
+ static Substitute(sql) {
146
+ return MJPlaceholderSubstitution.Substitute(sql);
147
+ }
148
+ // ─── Backward-Compatible API ─────────────────────────
149
+ // These methods preserve the original SQLParser interface for downstream
150
+ // consumers (mj-forge, migration toolchain). They delegate to the new
151
+ // extraction methods internally.
152
+ /**
153
+ * Parse SQL and extract table + column references.
154
+ * This is the original SQLParser.Parse() method signature.
155
+ * Automatically handles MJ Nunjucks templates via placeholder substitution.
156
+ *
157
+ * @param options Parse options, or just a SQL string for backward compatibility
158
+ */
159
+ static Parse(options, dialect) {
160
+ const { sql, parserDialect } = SQLParser.resolveParseArgs(options, dialect);
19
161
  if (!sql || sql.trim().length === 0) {
20
162
  return { Tables: [], Columns: [], UsedASTParsing: false };
21
163
  }
22
- const astResult = SQLParser.ParseViaAST(sql, dialect);
23
- if (astResult) {
164
+ const cleanSQL = SQLParser.getCleanSQL(sql);
165
+ const tables = SQLParser.extractTablesViaAST(cleanSQL, parserDialect);
166
+ const usedAST = tables !== null;
167
+ const tableAliasMap = new Map();
168
+ const columnRefs = new Set();
169
+ if (usedAST) {
170
+ try {
171
+ const parser = new Parser();
172
+ const ast = parser.astify(cleanSQL, { database: parserDialect });
173
+ const statements = Array.isArray(ast) ? ast : [ast];
174
+ for (const stmt of statements) {
175
+ SQLParser.walkAST(stmt, tableAliasMap, columnRefs);
176
+ }
177
+ }
178
+ catch { /* columns will be empty */ }
179
+ }
180
+ return {
181
+ Tables: tables || SQLParser.extractTablesViaRegex(cleanSQL),
182
+ Columns: SQLParser.buildColumnRefs(columnRefs),
183
+ UsedASTParsing: usedAST,
184
+ };
185
+ }
186
+ /**
187
+ * Parse SQL with MJ Nunjucks template preprocessing.
188
+ * This is the original SQLParser.ParseWithTemplatePreprocessing() signature.
189
+ * Now equivalent to Parse() since all methods handle templates automatically.
190
+ *
191
+ * @param options Parse options, or just a SQL string for backward compatibility
192
+ */
193
+ static ParseWithTemplatePreprocessing(options, dialect) {
194
+ return SQLParser.Parse(options, dialect);
195
+ }
196
+ // ─── Table & Column Extraction ─────────────────────
197
+ /**
198
+ * Extract all table/view references from SQL.
199
+ * Handles Nunjucks templates via placeholder substitution before AST parsing.
200
+ */
201
+ static ExtractTableRefs(sql, dialect = 'TransactSQL') {
202
+ if (!sql || sql.trim().length === 0)
203
+ return [];
204
+ const cleanSQL = SQLParser.getCleanSQL(sql);
205
+ const astResult = SQLParser.extractTablesViaAST(cleanSQL, dialect);
206
+ if (astResult)
24
207
  return astResult;
208
+ return SQLParser.extractTablesViaRegex(cleanSQL);
209
+ }
210
+ /**
211
+ * Extract all column references from SQL.
212
+ * Handles Nunjucks templates via placeholder substitution before AST parsing.
213
+ */
214
+ static ExtractColumnRefs(sql, dialect = 'TransactSQL') {
215
+ if (!sql || sql.trim().length === 0)
216
+ return [];
217
+ const cleanSQL = SQLParser.getCleanSQL(sql);
218
+ const tableAliasMap = new Map();
219
+ const columnRefs = new Set();
220
+ try {
221
+ const parser = new Parser();
222
+ const ast = parser.astify(cleanSQL, { database: dialect });
223
+ const statements = Array.isArray(ast) ? ast : [ast];
224
+ for (const statement of statements) {
225
+ SQLParser.walkAST(statement, tableAliasMap, columnRefs);
226
+ }
227
+ return SQLParser.buildColumnRefs(columnRefs);
228
+ }
229
+ catch {
230
+ return [];
25
231
  }
26
- return SQLParser.ParseViaRegex(sql);
27
232
  }
233
+ // ─── CTE Extraction ────────────────────────────────
28
234
  /**
29
- * Parse a SQL statement that may contain Nunjucks template syntax.
30
- * Pre-processes templates into valid SQL before parsing.
31
- * @param sql The SQL statement to parse
32
- * @param dialect The SQL dialect to use for AST parsing (default: 'TransactSQL')
235
+ * Extract CTE definitions from SQL starting with a WITH clause.
236
+ *
237
+ * Given: `WITH A AS (SELECT 1), B AS (SELECT 2) SELECT A.x, B.y FROM A, B`
238
+ * Returns: CTEDefinitions: ["A AS (...)", "B AS (...)"], MainStatement: "SELECT ..."
239
+ *
240
+ * Uses AST parsing first (produces bracket-quoted identifiers for SQL Server),
241
+ * falls back to paren-depth scanning if AST fails (e.g., Nunjucks-templated SQL).
33
242
  */
34
- static ParseWithTemplatePreprocessing(sql, dialect = 'TransactSQL') {
35
- if (!sql || sql.trim().length === 0) {
36
- return { Tables: [], Columns: [], UsedASTParsing: false };
243
+ static ExtractCTEs(sql, dialect = 'TransactSQL') {
244
+ const trimmed = sql.trimStart();
245
+ if (!/^WITH\s/i.test(trimmed))
246
+ return null;
247
+ const astResult = SQLParser.extractCTEsViaAST(trimmed, dialect);
248
+ if (astResult)
249
+ return astResult;
250
+ return SQLParser.extractCTEsViaRegex(trimmed);
251
+ }
252
+ // ─── MJ Template Extraction ────────────────────────
253
+ /**
254
+ * Extract all {{ variable | filter }} expressions from SQL.
255
+ * Returns structured info for each expression including variable name and filter chain.
256
+ */
257
+ static ExtractTemplateExpressions(sql) {
258
+ const tokens = MJLexer.Tokenize(sql);
259
+ const exprs = [];
260
+ for (const token of tokens) {
261
+ if (token.type === 'MJ_TEMPLATE_EXPR') {
262
+ const parsed = token.parsed;
263
+ exprs.push({
264
+ type: 'mj_template_expr',
265
+ variable: parsed.variable,
266
+ filters: parsed.filters,
267
+ raw: token.raw,
268
+ });
269
+ }
270
+ }
271
+ return exprs;
272
+ }
273
+ /**
274
+ * Extract all {{query:"..."}} composition references from SQL.
275
+ * Returns structured info including category path, query name, and parsed parameters.
276
+ */
277
+ static ExtractCompositionRefs(sql) {
278
+ const tokens = MJLexer.Tokenize(sql);
279
+ const refs = [];
280
+ for (const token of tokens) {
281
+ if (token.type === 'MJ_COMPOSITION_REF') {
282
+ const parsed = token.parsed;
283
+ refs.push({
284
+ type: 'mj_composition_ref',
285
+ categoryPath: parsed.categoryPath,
286
+ queryName: parsed.queryName,
287
+ parameters: parsed.parameters,
288
+ raw: token.raw,
289
+ });
290
+ }
291
+ }
292
+ return refs;
293
+ }
294
+ /**
295
+ * Extract conditional blocks, pairing if/elif/else/endif into structured trees.
296
+ */
297
+ static ExtractConditionalBlocks(sql) {
298
+ const tokens = MJLexer.Tokenize(sql);
299
+ const blocks = [];
300
+ const stack = [];
301
+ for (const token of tokens) {
302
+ switch (token.type) {
303
+ case 'MJ_IF_OPEN': {
304
+ const parsed = token.parsed;
305
+ stack.push({
306
+ branches: [{ condition: parsed.expression, body: { raw: '', nodes: [] } }],
307
+ raw: token.raw,
308
+ });
309
+ break;
310
+ }
311
+ case 'MJ_ELIF': {
312
+ const parsed = token.parsed;
313
+ const current = stack[stack.length - 1];
314
+ if (current) {
315
+ current.raw += token.raw;
316
+ current.branches.push({ condition: parsed.expression, body: { raw: '', nodes: [] } });
317
+ }
318
+ break;
319
+ }
320
+ case 'MJ_ELSE': {
321
+ const current = stack[stack.length - 1];
322
+ if (current) {
323
+ current.raw += token.raw;
324
+ current.branches.push({ condition: null, body: { raw: '', nodes: [] } });
325
+ }
326
+ break;
327
+ }
328
+ case 'MJ_ENDIF': {
329
+ const completed = stack.pop();
330
+ if (completed) {
331
+ completed.raw += token.raw;
332
+ blocks.push({ type: 'mj_conditional', branches: completed.branches, raw: completed.raw });
333
+ }
334
+ break;
335
+ }
336
+ default: {
337
+ const current = stack[stack.length - 1];
338
+ if (current && current.branches.length > 0) {
339
+ const lastBranch = current.branches[current.branches.length - 1];
340
+ lastBranch.body.raw += token.raw;
341
+ SQLParser.addNodeToFragment(token, lastBranch);
342
+ current.raw += token.raw;
343
+ }
344
+ }
345
+ }
346
+ }
347
+ return blocks;
348
+ }
349
+ /**
350
+ * Extract parameter metadata from template expressions.
351
+ * Infers type from filters, isRequired from conditional block context.
352
+ */
353
+ static ExtractParameterInfo(sql) {
354
+ const tokens = MJLexer.Tokenize(sql);
355
+ const paramMap = new Map();
356
+ for (const token of tokens) {
357
+ if (token.type === 'MJ_TEMPLATE_EXPR') {
358
+ const parsed = token.parsed;
359
+ const varName = parsed.variable;
360
+ if (!paramMap.has(varName)) {
361
+ paramMap.set(varName, {
362
+ name: varName,
363
+ type: SQLParser.inferTypeFromFilters(parsed.filters),
364
+ isRequired: true,
365
+ defaultValue: SQLParser.extractDefaultValue(parsed.filters),
366
+ filters: parsed.filters,
367
+ usageLocations: [],
368
+ });
369
+ }
370
+ paramMap.get(varName).usageLocations.push(token.raw);
371
+ }
372
+ }
373
+ const conditionalVars = SQLParser.findConditionalVariables(tokens);
374
+ for (const [varName, param] of paramMap) {
375
+ if (conditionalVars.onlyInConditional.has(varName)) {
376
+ param.isRequired = false;
377
+ }
378
+ }
379
+ return Array.from(paramMap.values());
380
+ }
381
+ // ─── AST Walker ──────────────────────────────────────
382
+ /**
383
+ * Walk the AST from an Astify result and annotate where MJ placeholders appear.
384
+ *
385
+ * Returns an MJASTWalkResult with annotations mapping each placeholder to its
386
+ * SQL clause context (SELECT, WHERE, ORDER BY, etc.) and the resolved MJ node.
387
+ *
388
+ * This enables queries like:
389
+ * - "Which template expressions appear in the WHERE clause?"
390
+ * - "What composition ref is in the FROM clause?"
391
+ * - "Does the ORDER BY reference an MJ token?"
392
+ *
393
+ * @param result The MJAstifyResult from Astify()
394
+ * @returns Walk result with annotations, or empty result if AST parsing failed
395
+ */
396
+ static WalkAST(result) {
397
+ const emptyResult = {
398
+ annotations: [],
399
+ byClause: new Map(),
400
+ byPlaceholder: new Map(),
401
+ templateExprs: [],
402
+ compositionRefs: [],
403
+ };
404
+ if (!result.astParsed || !result.ast || result.positionMap.size === 0) {
405
+ return emptyResult;
406
+ }
407
+ const annotations = [];
408
+ const stmt = (Array.isArray(result.ast) ? result.ast[0] : result.ast);
409
+ if (stmt) {
410
+ SQLParser.walkASTNode(stmt, '', 'unknown', result.positionMap, annotations);
37
411
  }
38
- const processedSQL = SQLParser.PreProcessNunjucksForParsing(sql);
39
- return SQLParser.Parse(processedSQL, dialect);
412
+ return SQLParser.buildWalkResult(annotations);
40
413
  }
414
+ // ═══════════════════════════════════════════════════
415
+ // Private: AST Walker
416
+ // ═══════════════════════════════════════════════════
41
417
  /**
42
- * Attempt to parse SQL via node-sql-parser AST.
43
- * Returns null if parsing fails (caller should fall back to regex).
418
+ * Recursively walks an AST node, checking values against the placeholder map.
44
419
  */
45
- static ParseViaAST(sql, dialect) {
420
+ static walkASTNode(node, path, context, positionMap, annotations) {
421
+ if (!node || typeof node !== 'object')
422
+ return;
423
+ // Walk standard SQL AST clauses with appropriate context
424
+ if (node.columns)
425
+ SQLParser.walkASTValue(node.columns, `${path}columns`, 'select', positionMap, annotations, node);
426
+ if (node.from)
427
+ SQLParser.walkASTValue(node.from, `${path}from`, 'from', positionMap, annotations, node);
428
+ if (node.where)
429
+ SQLParser.walkASTValue(node.where, `${path}where`, 'where', positionMap, annotations, node);
430
+ if (node.groupby) {
431
+ const groupby = node.groupby;
432
+ const groupItems = groupby.columns || node.groupby;
433
+ SQLParser.walkASTValue(groupItems, `${path}groupby`, 'group_by', positionMap, annotations, node);
434
+ }
435
+ if (node.having)
436
+ SQLParser.walkASTValue(node.having, `${path}having`, 'having', positionMap, annotations, node);
437
+ if (node.orderby)
438
+ SQLParser.walkASTValue(node.orderby, `${path}orderby`, 'order_by', positionMap, annotations, node);
439
+ // Walk CTEs
440
+ if (node.with && Array.isArray(node.with)) {
441
+ for (let i = 0; i < node.with.length; i++) {
442
+ const cte = node.with[i];
443
+ if (cte.stmt) {
444
+ const stmtRecord = cte.stmt;
445
+ const cteAst = (stmtRecord.ast || stmtRecord);
446
+ SQLParser.walkASTNode(cteAst, `${path}with[${i}].`, 'cte', positionMap, annotations);
447
+ }
448
+ }
449
+ }
450
+ // Walk JOIN ON conditions
451
+ if (Array.isArray(node.from)) {
452
+ for (let i = 0; i < node.from.length; i++) {
453
+ const fromItem = node.from[i];
454
+ if (fromItem?.on) {
455
+ SQLParser.walkASTValue(fromItem.on, `${path}from[${i}].on`, 'join_on', positionMap, annotations, fromItem);
456
+ }
457
+ // Walk subqueries in FROM
458
+ if (fromItem?.expr) {
459
+ const exprRecord = fromItem.expr;
460
+ const subAst = (exprRecord.ast || exprRecord);
461
+ if (subAst.type === 'select' || subAst.columns) {
462
+ SQLParser.walkASTNode(subAst, `${path}from[${i}].expr.`, 'subquery', positionMap, annotations);
463
+ }
464
+ }
465
+ }
466
+ }
467
+ // Walk UNION/EXCEPT chain
468
+ if (node._next) {
469
+ SQLParser.walkASTNode(node._next, `${path}_next.`, context, positionMap, annotations);
470
+ }
471
+ }
472
+ /**
473
+ * Walks any AST value (node, array, or primitive) checking for placeholder matches.
474
+ */
475
+ static walkASTValue(value, path, context, positionMap, annotations, parentNode) {
476
+ if (value === null || value === undefined)
477
+ return;
478
+ // Check string values against placeholders
479
+ if (typeof value === 'string') {
480
+ SQLParser.checkPlaceholder(value, path, context, positionMap, annotations, parentNode);
481
+ return;
482
+ }
483
+ // Check number values (sqlNumber placeholders are numeric)
484
+ if (typeof value === 'number') {
485
+ SQLParser.checkPlaceholder(String(value), path, context, positionMap, annotations, parentNode);
486
+ return;
487
+ }
488
+ // Walk arrays
489
+ if (Array.isArray(value)) {
490
+ for (let i = 0; i < value.length; i++) {
491
+ SQLParser.walkASTValue(value[i], `${path}[${i}]`, context, positionMap, annotations, parentNode);
492
+ }
493
+ return;
494
+ }
495
+ // Walk objects recursively
496
+ if (typeof value === 'object') {
497
+ const obj = value;
498
+ // Check column_ref nodes — the column name or table.column might be a placeholder
499
+ if (obj.type === 'column_ref') {
500
+ const col = obj.column;
501
+ if (col)
502
+ SQLParser.checkPlaceholder(col, `${path}.column`, context, positionMap, annotations, obj);
503
+ if (obj.table)
504
+ SQLParser.checkPlaceholder(obj.table, `${path}.table`, context, positionMap, annotations, obj);
505
+ return;
506
+ }
507
+ // Check string literal values
508
+ if (obj.type === 'single_quote_string' || obj.type === 'string') {
509
+ if (typeof obj.value === 'string') {
510
+ // String placeholder includes the quotes: '__MJT_001__'
511
+ SQLParser.checkPlaceholder(`'${obj.value}'`, `${path}.value`, context, positionMap, annotations, obj);
512
+ }
513
+ return;
514
+ }
515
+ // Check number literal values
516
+ if (obj.type === 'number') {
517
+ if (typeof obj.value === 'number') {
518
+ SQLParser.checkPlaceholder(String(obj.value), `${path}.value`, context, positionMap, annotations, obj);
519
+ }
520
+ return;
521
+ }
522
+ // Recurse into expression nodes
523
+ if (obj.left)
524
+ SQLParser.walkASTValue(obj.left, `${path}.left`, context, positionMap, annotations, obj);
525
+ if (obj.right)
526
+ SQLParser.walkASTValue(obj.right, `${path}.right`, context, positionMap, annotations, obj);
527
+ if (obj.expr)
528
+ SQLParser.walkASTValue(obj.expr, `${path}.expr`, context, positionMap, annotations, obj);
529
+ if (obj.args) {
530
+ const args = obj.args.value || obj.args;
531
+ SQLParser.walkASTValue(args, `${path}.args`, context, positionMap, annotations, obj);
532
+ }
533
+ // Walk CASE WHEN
534
+ if (obj.type === 'case' && Array.isArray(obj.args)) {
535
+ for (let i = 0; i < obj.args.length; i++) {
536
+ const caseArg = obj.args[i];
537
+ if (caseArg.cond)
538
+ SQLParser.walkASTValue(caseArg.cond, `${path}.args[${i}].cond`, context, positionMap, annotations, obj);
539
+ if (caseArg.result)
540
+ SQLParser.walkASTValue(caseArg.result, `${path}.args[${i}].result`, context, positionMap, annotations, obj);
541
+ }
542
+ }
543
+ // Walk subqueries in expressions (EXISTS, IN)
544
+ if (obj.ast) {
545
+ SQLParser.walkASTNode(obj.ast, `${path}.ast.`, 'subquery', positionMap, annotations);
546
+ }
547
+ }
548
+ }
549
+ /**
550
+ * Checks if a value matches a placeholder and creates an annotation if so.
551
+ */
552
+ static checkPlaceholder(value, path, context, positionMap, annotations, astNode) {
553
+ const entry = positionMap.get(value);
554
+ if (!entry)
555
+ return;
556
+ const originalToken = entry.originalToken;
557
+ let templateExpr = null;
558
+ let compositionRef = null;
559
+ if (originalToken.type === 'MJ_TEMPLATE_EXPR') {
560
+ const parsed = originalToken.parsed;
561
+ templateExpr = {
562
+ type: 'mj_template_expr',
563
+ variable: parsed.variable,
564
+ filters: parsed.filters,
565
+ raw: originalToken.raw,
566
+ };
567
+ }
568
+ else if (originalToken.type === 'MJ_COMPOSITION_REF') {
569
+ const parsed = originalToken.parsed;
570
+ compositionRef = {
571
+ type: 'mj_composition_ref',
572
+ categoryPath: parsed.categoryPath,
573
+ queryName: parsed.queryName,
574
+ parameters: parsed.parameters,
575
+ raw: originalToken.raw,
576
+ };
577
+ }
578
+ annotations.push({
579
+ path,
580
+ placeholder: value,
581
+ clauseContext: context,
582
+ templateExpr,
583
+ compositionRef,
584
+ placeholderContext: entry.context,
585
+ astNode,
586
+ });
587
+ }
588
+ /**
589
+ * Builds the MJASTWalkResult from a flat list of annotations.
590
+ */
591
+ static buildWalkResult(annotations) {
592
+ // Deduplicate — keep the first (most specific) annotation per placeholder.
593
+ // Subqueries can be reached via multiple AST walk paths, producing duplicates.
594
+ const seen = new Set();
595
+ const deduped = annotations.filter(ann => {
596
+ if (seen.has(ann.placeholder))
597
+ return false;
598
+ seen.add(ann.placeholder);
599
+ return true;
600
+ });
601
+ const byClause = new Map();
602
+ const byPlaceholder = new Map();
603
+ const templateExprs = [];
604
+ const compositionRefs = [];
605
+ for (const ann of deduped) {
606
+ // Index by clause
607
+ const clauseList = byClause.get(ann.clauseContext) || [];
608
+ clauseList.push(ann);
609
+ byClause.set(ann.clauseContext, clauseList);
610
+ // Index by placeholder
611
+ byPlaceholder.set(ann.placeholder, ann);
612
+ // Categorize
613
+ if (ann.templateExpr)
614
+ templateExprs.push(ann);
615
+ if (ann.compositionRef)
616
+ compositionRefs.push(ann);
617
+ }
618
+ return { annotations: deduped, byClause, byPlaceholder, templateExprs, compositionRefs };
619
+ }
620
+ // ═══════════════════════════════════════════════════
621
+ // Private: SQL Parsing
622
+ // ═══════════════════════════════════════════════════
623
+ /**
624
+ * Parse SQL safely, returning null on failure.
625
+ *
626
+ * Includes a workaround for node-sql-parser's inability to handle multi-directive
627
+ * FOR XML clauses (e.g., `FOR XML PATH('M'), ROOT('R')`). The parser handles
628
+ * `FOR XML PATH('M')` fine but chokes on the comma-separated directives.
629
+ * We strip the extra directives before parsing and restore them on the AST's `for` property.
630
+ */
631
+ /** Resolves overloaded Parse() args: (string, dialect?) or (options) */
632
+ static resolveParseArgs(options, dialect) {
633
+ if (typeof options === 'string') {
634
+ return { sql: options, parserDialect: dialect || 'TransactSQL' };
635
+ }
636
+ return { sql: options.sql, parserDialect: options.dialect || 'TransactSQL' };
637
+ }
638
+ static parseSQL(sql, dialect) {
639
+ try {
640
+ const parser = new Parser();
641
+ return parser.astify(sql, { database: dialect });
642
+ }
643
+ catch {
644
+ // If direct parse fails, try with FOR XML workaround
645
+ const forXmlResult = SQLParser.stripForXmlDirectives(sql);
646
+ if (forXmlResult) {
647
+ try {
648
+ const parser = new Parser();
649
+ const ast = parser.astify(forXmlResult.cleanedSQL, { database: dialect });
650
+ // Restore the original FOR XML clause on the AST
651
+ SQLParser.restoreForXmlOnAST(ast, forXmlResult.originalForXml);
652
+ return ast;
653
+ }
654
+ catch {
655
+ return null;
656
+ }
657
+ }
658
+ return null;
659
+ }
660
+ }
661
+ /**
662
+ * Detects FOR XML clauses that node-sql-parser can't handle and simplifies them.
663
+ *
664
+ * node-sql-parser handles: FOR XML PATH, FOR XML PATH('arg'), FOR XML RAW, FOR XML AUTO
665
+ * node-sql-parser fails on: FOR XML RAW('arg'), and any comma-separated directives
666
+ *
667
+ * Simplifies to a form the parser accepts, preserving the original for restoration.
668
+ * Returns null if no problematic FOR XML pattern is found.
669
+ */
670
+ static stripForXmlDirectives(sql) {
671
+ // Match FOR XML <directive> with optional quoted arg and optional comma-separated extras
672
+ const forXmlRegex = /\bFOR\s+XML\s+(PATH|RAW|AUTO|EXPLICIT)(\s*\('[^']*'\))?(\s*,\s*[^;]*)?$/i;
673
+ const match = sql.match(forXmlRegex);
674
+ if (!match)
675
+ return null;
676
+ const fullForXml = match[0];
677
+ const directive = match[1].toUpperCase(); // PATH, RAW, etc.
678
+ const hasQuotedArg = !!match[2];
679
+ const hasExtraDirectives = !!match[3];
680
+ // Only needs workaround if there are extra comma-separated directives
681
+ // OR if it's RAW/EXPLICIT with a quoted arg (parser can't handle those)
682
+ const needsWorkaround = hasExtraDirectives ||
683
+ (hasQuotedArg && (directive === 'RAW' || directive === 'EXPLICIT'));
684
+ if (!needsWorkaround)
685
+ return null;
686
+ // Simplify to a form the parser accepts:
687
+ // PATH('arg') → PATH('arg') (parser handles this)
688
+ // RAW('arg') → RAW (parser can't handle quoted arg on RAW)
689
+ // Any + comma extras → strip extras
690
+ let simplifiedDirective;
691
+ if (directive === 'PATH' && hasQuotedArg) {
692
+ simplifiedDirective = `FOR XML PATH${match[2]}`;
693
+ }
694
+ else {
695
+ simplifiedDirective = `FOR XML ${directive}`;
696
+ }
697
+ const cleanedSQL = sql.substring(0, match.index) + simplifiedDirective;
698
+ return { cleanedSQL, originalForXml: fullForXml };
699
+ }
700
+ /**
701
+ * Restores the original FOR XML clause text on the AST's `for` property.
702
+ * This ensures that when the AST is inspected (e.g., for isOrderByLegalInCTE checks),
703
+ * the FOR XML presence is correctly detected.
704
+ */
705
+ static restoreForXmlOnAST(ast, originalForXml) {
706
+ const stmt = (Array.isArray(ast) ? ast[0] : ast);
707
+ if (!stmt)
708
+ return;
709
+ // Walk the _next chain (UNION) to find the statement with the FOR clause
710
+ let current = stmt;
711
+ while (current) {
712
+ if (current.for && typeof current.for === 'object') {
713
+ // Attach the original text so downstream code can reconstruct it
714
+ current.for.__originalForXml = originalForXml;
715
+ return;
716
+ }
717
+ current = current._next;
718
+ }
719
+ }
720
+ /** Get clean SQL (MJ tokens replaced with placeholders) for AST parsing */
721
+ static getCleanSQL(sql) {
722
+ const analysis = MJLexer.Parse(sql);
723
+ if (!analysis.hasMJExtensions)
724
+ return sql;
725
+ return MJPlaceholderSubstitution.Substitute(sql).cleanSQL;
726
+ }
727
+ // ═══════════════════════════════════════════════════
728
+ // Private: Table Extraction
729
+ // ═══════════════════════════════════════════════════
730
+ static extractTablesViaAST(sql, dialect) {
46
731
  try {
47
732
  const parser = new Parser();
48
733
  const ast = parser.astify(sql, { database: dialect });
@@ -50,19 +735,15 @@ export class SQLParser {
50
735
  const columnRefs = new Set();
51
736
  const statements = Array.isArray(ast) ? ast : [ast];
52
737
  for (const statement of statements) {
53
- SQLParser.ExtractFromAST(statement, tableAliasMap, columnRefs);
738
+ SQLParser.walkAST(statement, tableAliasMap, columnRefs);
54
739
  }
55
- return SQLParser.BuildResult(tableAliasMap, columnRefs, true);
740
+ return SQLParser.deduplicateTables(tableAliasMap);
56
741
  }
57
742
  catch {
58
743
  return null;
59
744
  }
60
745
  }
61
- /**
62
- * Regex-based fallback for extracting table references from SQL.
63
- * Less accurate than AST but handles edge cases where the parser fails.
64
- */
65
- static ParseViaRegex(sql) {
746
+ static extractTablesViaRegex(sql) {
66
747
  const tableAliasMap = new Map();
67
748
  const tablePattern = /(?:FROM|JOIN|INTO)\s+(?:\[?(\w+)\]?\.)?\[?(\w+)\]?(?:\s+(?:AS\s+)?(\w+))?/gi;
68
749
  const matches = [...sql.matchAll(tablePattern)];
@@ -70,53 +751,30 @@ export class SQLParser {
70
751
  const schemaName = match[1] || 'dbo';
71
752
  const tableName = match[2];
72
753
  const alias = match[3] || tableName;
73
- const key = alias;
74
- if (!tableAliasMap.has(key)) {
75
- tableAliasMap.set(key, { schemaName, tableName });
754
+ if (!tableAliasMap.has(alias)) {
755
+ tableAliasMap.set(alias, { schemaName, tableName });
76
756
  }
77
757
  }
78
- // Regex can't reliably extract column references, return empty
79
- return SQLParser.BuildResult(tableAliasMap, new Set(), false);
80
- }
81
- /**
82
- * Converts internal maps into the public SQLParseResult shape.
83
- */
84
- static BuildResult(tableAliasMap, columnRefs, usedAST) {
85
- const tables = SQLParser.DeduplicateTables(tableAliasMap);
86
- const columns = SQLParser.ParseColumnRefs(columnRefs);
87
- return { Tables: tables, Columns: columns, UsedASTParsing: usedAST };
758
+ return SQLParser.deduplicateTables(tableAliasMap);
88
759
  }
89
- /**
90
- * Deduplicates table references by schema.table key, keeping distinct entries.
91
- */
92
- static DeduplicateTables(tableAliasMap) {
760
+ static deduplicateTables(tableAliasMap) {
93
761
  const seen = new Set();
94
762
  const tables = [];
95
763
  for (const [alias, info] of tableAliasMap) {
96
764
  const key = `${info.schemaName.toLowerCase()}.${info.tableName.toLowerCase()}`;
97
765
  if (!seen.has(key)) {
98
766
  seen.add(key);
99
- tables.push({
100
- TableName: info.tableName,
101
- SchemaName: info.schemaName,
102
- Alias: alias
103
- });
767
+ tables.push({ TableName: info.tableName, SchemaName: info.schemaName, Alias: alias });
104
768
  }
105
769
  }
106
770
  return tables;
107
771
  }
108
- /**
109
- * Converts raw column reference strings into structured SQLColumnReference objects.
110
- */
111
- static ParseColumnRefs(columnRefs) {
772
+ static buildColumnRefs(columnRefs) {
112
773
  const columns = [];
113
774
  for (const ref of columnRefs) {
114
775
  const dotIndex = ref.lastIndexOf('.');
115
776
  if (dotIndex >= 0) {
116
- columns.push({
117
- ColumnName: ref.substring(dotIndex + 1),
118
- TableQualifier: ref.substring(0, dotIndex)
119
- });
777
+ columns.push({ ColumnName: ref.substring(dotIndex + 1), TableQualifier: ref.substring(0, dotIndex) });
120
778
  }
121
779
  else {
122
780
  columns.push({ ColumnName: ref, TableQualifier: null });
@@ -124,16 +782,112 @@ export class SQLParser {
124
782
  }
125
783
  return columns;
126
784
  }
127
- // ─────────────────────────────────────────────────────
128
- // AST Walking (moved from MJQueryEntityServer)
129
- // ─────────────────────────────────────────────────────
130
- /**
131
- * Recursively extracts table references and column references from SQL AST.
132
- */
133
- static ExtractFromAST(node, tableAliasMap, referencedColumns) {
785
+ // ═══════════════════════════════════════════════════
786
+ // Private: CTE Extraction
787
+ // ═══════════════════════════════════════════════════
788
+ static extractCTEsViaAST(sql, dialect) {
789
+ try {
790
+ const parser = new Parser();
791
+ const ast = parser.astify(sql, { database: dialect });
792
+ const singleAst = (Array.isArray(ast) ? ast[0] : ast);
793
+ if (!singleAst.with || !Array.isArray(singleAst.with) || singleAst.with.length === 0) {
794
+ return null;
795
+ }
796
+ const cteDefinitions = [];
797
+ for (const cte of singleAst.with) {
798
+ const cteRecord = cte;
799
+ const cteName = cteRecord.name.value;
800
+ const bodySQL = parser.sqlify(cteRecord.stmt.ast, { database: dialect });
801
+ cteDefinitions.push(`${cteName} AS (\n${bodySQL}\n)`);
802
+ }
803
+ const mainAst = { ...singleAst, with: null };
804
+ const mainStatement = parser.sqlify(mainAst, { database: dialect });
805
+ return { CTEDefinitions: cteDefinitions, MainStatement: mainStatement, UsedASTParsing: true };
806
+ }
807
+ catch {
808
+ return null;
809
+ }
810
+ }
811
+ static extractCTEsViaRegex(sql) {
812
+ const withStripped = sql.trimStart().replace(/^WITH\s+/i, '');
813
+ const cteDefinitions = [];
814
+ let pos = 0;
815
+ const len = withStripped.length;
816
+ while (pos < len) {
817
+ pos = SQLParser.skipWhitespace(withStripped, pos);
818
+ if (pos >= len)
819
+ break;
820
+ const remaining = withStripped.substring(pos);
821
+ const cteHeaderMatch = remaining.match(/^(\[[^\]]+\]|"[^"]+"|[A-Za-z_]\w*)\s+AS\s*\(/i);
822
+ if (!cteHeaderMatch)
823
+ break;
824
+ const cteName = cteHeaderMatch[1];
825
+ pos += cteHeaderMatch[0].length;
826
+ const bodyStart = pos;
827
+ pos = SQLParser.findMatchingCloseParen(withStripped, pos);
828
+ const cteBody = withStripped.substring(bodyStart, pos);
829
+ cteDefinitions.push(`${cteName} AS (\n${cteBody}\n)`);
830
+ pos++;
831
+ pos = SQLParser.skipWhitespace(withStripped, pos);
832
+ if (pos < len && withStripped[pos] === ',')
833
+ pos++;
834
+ }
835
+ const mainStatement = withStripped.substring(pos).trim();
836
+ return { CTEDefinitions: cteDefinitions, MainStatement: mainStatement, UsedASTParsing: false };
837
+ }
838
+ static skipWhitespace(sql, pos) {
839
+ while (pos < sql.length && /\s/.test(sql[pos]))
840
+ pos++;
841
+ return pos;
842
+ }
843
+ static findMatchingCloseParen(sql, pos) {
844
+ let depth = 1;
845
+ const len = sql.length;
846
+ while (pos < len && depth > 0) {
847
+ const ch = sql[pos];
848
+ if (ch === "'") {
849
+ pos++;
850
+ while (pos < len) {
851
+ if (sql[pos] === "'") {
852
+ if (pos + 1 < len && sql[pos + 1] === "'") {
853
+ pos += 2;
854
+ continue;
855
+ }
856
+ break;
857
+ }
858
+ pos++;
859
+ }
860
+ }
861
+ else if (ch === '-' && pos + 1 < len && sql[pos + 1] === '-') {
862
+ pos += 2;
863
+ while (pos < len && sql[pos] !== '\n')
864
+ pos++;
865
+ }
866
+ else if (ch === '/' && pos + 1 < len && sql[pos + 1] === '*') {
867
+ pos += 2;
868
+ while (pos < len && !(sql[pos] === '*' && pos + 1 < len && sql[pos + 1] === '/'))
869
+ pos++;
870
+ if (pos < len)
871
+ pos++;
872
+ }
873
+ else if (ch === '(') {
874
+ depth++;
875
+ }
876
+ else if (ch === ')') {
877
+ depth--;
878
+ if (depth === 0)
879
+ return pos;
880
+ }
881
+ pos++;
882
+ }
883
+ return pos;
884
+ }
885
+ // ═══════════════════════════════════════════════════
886
+ // Private: AST Walking (table/column extraction)
887
+ // ═══════════════════════════════════════════════════
888
+ static walkAST(node, tableAliasMap, columnRefs) {
134
889
  if (!node || typeof node !== 'object')
135
890
  return;
136
- // Handle CTEs (WITH clause)
137
891
  if (node.with) {
138
892
  const ctes = Array.isArray(node.with) ? node.with : [node.with];
139
893
  for (const cte of ctes) {
@@ -141,18 +895,16 @@ export class SQLParser {
141
895
  if (cteRecord.stmt) {
142
896
  const stmtRecord = cteRecord.stmt;
143
897
  const cteAst = (stmtRecord.ast || stmtRecord);
144
- SQLParser.ExtractFromAST(cteAst, tableAliasMap, referencedColumns);
898
+ SQLParser.walkAST(cteAst, tableAliasMap, columnRefs);
145
899
  }
146
900
  }
147
901
  }
148
- // Extract FROM clause tables (including JOINs)
149
902
  if (node.from) {
150
903
  const fromItems = Array.isArray(node.from) ? node.from : [node.from];
151
904
  for (const fromItem of fromItems) {
152
- SQLParser.ExtractTableFromItem(fromItem, tableAliasMap, referencedColumns);
905
+ SQLParser.walkFromItem(fromItem, tableAliasMap, columnRefs);
153
906
  }
154
907
  }
155
- // Extract column references from SELECT
156
908
  if (node.columns) {
157
909
  const cols = Array.isArray(node.columns) ? node.columns : [node.columns];
158
910
  for (const col of cols) {
@@ -160,158 +912,185 @@ export class SQLParser {
160
912
  continue;
161
913
  const colRecord = col;
162
914
  if (colRecord.expr) {
163
- SQLParser.ExtractColumnReferences(colRecord.expr, referencedColumns, tableAliasMap);
915
+ SQLParser.walkExpression(colRecord.expr, columnRefs, tableAliasMap);
164
916
  }
165
917
  }
166
918
  }
167
- // Extract column references from WHERE
168
919
  if (node.where) {
169
- SQLParser.ExtractColumnReferences(node.where, referencedColumns, tableAliasMap);
920
+ SQLParser.walkExpression(node.where, columnRefs, tableAliasMap);
170
921
  }
171
- // Extract column references from GROUP BY
172
922
  if (node.groupby) {
173
923
  const groupbyRecord = node.groupby;
174
924
  const groupItems = groupbyRecord.columns || node.groupby;
175
925
  const items = Array.isArray(groupItems) ? groupItems : [groupItems];
176
926
  for (const group of items) {
177
- SQLParser.ExtractColumnReferences(group, referencedColumns, tableAliasMap);
927
+ SQLParser.walkExpression(group, columnRefs, tableAliasMap);
178
928
  }
179
929
  }
180
- // Extract column references from ORDER BY
181
930
  if (node.orderby) {
182
931
  const orders = Array.isArray(node.orderby) ? node.orderby : [node.orderby];
183
932
  for (const order of orders) {
184
933
  const orderRecord = order;
185
- SQLParser.ExtractColumnReferences((orderRecord.expr || orderRecord), referencedColumns, tableAliasMap);
934
+ SQLParser.walkExpression((orderRecord.expr || orderRecord), columnRefs, tableAliasMap);
186
935
  }
187
936
  }
188
- // Handle UNION/INTERSECT/EXCEPT
189
937
  if (node._next) {
190
- SQLParser.ExtractFromAST(node._next, tableAliasMap, referencedColumns);
938
+ SQLParser.walkAST(node._next, tableAliasMap, columnRefs);
191
939
  }
192
940
  }
193
- /**
194
- * Extracts table information from a FROM clause item, handling tables and JOINs.
195
- */
196
- static ExtractTableFromItem(fromItem, tableAliasMap, referencedColumns) {
941
+ static walkFromItem(fromItem, tableAliasMap, columnRefs) {
197
942
  if (!fromItem)
198
943
  return;
199
- // Direct table reference
200
944
  if (fromItem.table) {
201
945
  const alias = (fromItem.as || fromItem.table);
202
946
  tableAliasMap.set(alias, {
203
947
  schemaName: fromItem.db || 'dbo',
204
- tableName: fromItem.table
948
+ tableName: fromItem.table,
205
949
  });
206
950
  }
207
- // Handle subqueries in FROM (derived tables)
208
951
  if (fromItem.expr) {
209
952
  const exprRecord = fromItem.expr;
210
953
  const subqueryAst = (exprRecord.ast || exprRecord);
211
- SQLParser.ExtractFromAST(subqueryAst, tableAliasMap, referencedColumns);
954
+ SQLParser.walkAST(subqueryAst, tableAliasMap, columnRefs);
212
955
  }
213
- // Extract column references from ON conditions
214
956
  if (fromItem.on) {
215
- SQLParser.ExtractColumnReferences(fromItem.on, referencedColumns, tableAliasMap);
957
+ SQLParser.walkExpression(fromItem.on, columnRefs, tableAliasMap);
216
958
  }
217
- // Handle USING clause
218
959
  if (fromItem.using) {
219
960
  const usings = Array.isArray(fromItem.using) ? fromItem.using : [fromItem.using];
220
961
  for (const col of usings) {
221
962
  if (typeof col === 'string') {
222
- referencedColumns.add(col);
963
+ columnRefs.add(col);
223
964
  }
224
965
  else if (col && typeof col === 'object' && 'column' in col) {
225
- referencedColumns.add(col.column);
966
+ columnRefs.add(col.column);
226
967
  }
227
968
  }
228
969
  }
229
970
  }
230
- /**
231
- * Extracts column references from an expression node.
232
- * Also extracts tables from subqueries found in expressions (e.g., EXISTS, IN).
233
- */
234
- static ExtractColumnReferences(expr, referencedColumns, tableAliasMap) {
971
+ static walkExpression(expr, columnRefs, tableAliasMap) {
235
972
  if (!expr || typeof expr !== 'object')
236
973
  return;
237
974
  if (expr.type === 'column_ref') {
238
975
  const colName = expr.table ? `${expr.table}.${expr.column}` : expr.column;
239
- referencedColumns.add(colName);
976
+ columnRefs.add(colName);
240
977
  }
241
- // Handle subqueries in expressions (EXISTS, IN, scalar subqueries)
242
978
  if (expr.ast && tableAliasMap) {
243
- SQLParser.ExtractFromAST(expr.ast, tableAliasMap, referencedColumns);
244
- }
245
- // Recursively process nested expressions
246
- if (expr.left) {
247
- SQLParser.ExtractColumnReferences(expr.left, referencedColumns, tableAliasMap);
248
- }
249
- if (expr.right) {
250
- SQLParser.ExtractColumnReferences(expr.right, referencedColumns, tableAliasMap);
979
+ SQLParser.walkAST(expr.ast, tableAliasMap, columnRefs);
251
980
  }
981
+ if (expr.left)
982
+ SQLParser.walkExpression(expr.left, columnRefs, tableAliasMap);
983
+ if (expr.right)
984
+ SQLParser.walkExpression(expr.right, columnRefs, tableAliasMap);
252
985
  if (expr.args) {
253
986
  const argsRecord = expr.args;
254
987
  const args = argsRecord.value || expr.args;
255
988
  const argList = Array.isArray(args) ? args : [args];
256
989
  for (const arg of argList) {
257
- SQLParser.ExtractColumnReferences(arg, referencedColumns, tableAliasMap);
990
+ SQLParser.walkExpression(arg, columnRefs, tableAliasMap);
258
991
  }
259
992
  }
260
- if (expr.expr) {
261
- SQLParser.ExtractColumnReferences(expr.expr, referencedColumns, tableAliasMap);
993
+ if (expr.expr)
994
+ SQLParser.walkExpression(expr.expr, columnRefs, tableAliasMap);
995
+ }
996
+ // ═══════════════════════════════════════════════════
997
+ // Private: Parameter Analysis
998
+ // ═══════════════════════════════════════════════════
999
+ static inferTypeFromFilters(filters) {
1000
+ const filterTypeMap = {
1001
+ 'sqlString': 'string',
1002
+ 'sqlNumber': 'number',
1003
+ 'sqlDate': 'date',
1004
+ 'sqlBoolean': 'boolean',
1005
+ 'sqlIn': 'array',
1006
+ 'sqlIdentifier': 'string',
1007
+ 'sqlNoKeywordsExpression': 'string',
1008
+ };
1009
+ for (let i = filters.length - 1; i >= 0; i--) {
1010
+ const mapped = filterTypeMap[filters[i].name];
1011
+ if (mapped)
1012
+ return mapped;
262
1013
  }
1014
+ return 'unknown';
263
1015
  }
264
- // ─────────────────────────────────────────────────────
265
- // Nunjucks Preprocessing (moved from MJQueryEntityServer)
266
- // ─────────────────────────────────────────────────────
267
- /**
268
- * Pre-processes Nunjucks templates in SQL to create valid SQL for parsing.
269
- * Replaces Nunjucks syntax with placeholder values.
270
- */
271
- static PreProcessNunjucksForParsing(sql) {
272
- const env = new nunjucks.Environment(null, {
273
- autoescape: false,
274
- throwOnUndefined: false
275
- });
276
- // Add placeholder filters that return safe SQL values
277
- env.addFilter('sqlString', () => "'placeholder'");
278
- env.addFilter('sqlNumber', () => '0');
279
- env.addFilter('sqlDate', () => "'2000-01-01'");
280
- env.addFilter('sqlIn', () => "('placeholder')");
281
- env.addFilter('sqlIdentifier', (val) => val || 'placeholder');
282
- env.addFilter('sqlNoKeywordsExpression', (val) => val || 'placeholder');
283
- env.addFilter('default', (val, defaultVal) => val || defaultVal || 'placeholder');
284
- env.addFilter('safe', (val) => val || 'placeholder');
285
- env.addFilter('dump', (val) => JSON.stringify(val || {}));
286
- try {
287
- return env.renderString(sql, {});
1016
+ static extractDefaultValue(filters) {
1017
+ for (const filter of filters) {
1018
+ if (filter.name === 'default' && filter.args.length > 0) {
1019
+ return filter.args[0];
1020
+ }
288
1021
  }
289
- catch {
290
- return SQLParser.PreProcessNunjucksViaRegex(sql);
1022
+ return null;
1023
+ }
1024
+ static findConditionalVariables(tokens) {
1025
+ const insideConditional = new Set();
1026
+ const outsideConditional = new Set();
1027
+ let conditionalDepth = 0;
1028
+ for (const token of tokens) {
1029
+ switch (token.type) {
1030
+ case 'MJ_IF_OPEN':
1031
+ conditionalDepth++;
1032
+ SQLParser.addConditionVariables(token, insideConditional);
1033
+ break;
1034
+ case 'MJ_ELIF':
1035
+ SQLParser.addConditionVariables(token, insideConditional);
1036
+ break;
1037
+ case 'MJ_ENDIF':
1038
+ conditionalDepth = Math.max(0, conditionalDepth - 1);
1039
+ break;
1040
+ case 'MJ_TEMPLATE_EXPR': {
1041
+ const parsed = token.parsed;
1042
+ if (conditionalDepth > 0) {
1043
+ insideConditional.add(parsed.variable);
1044
+ }
1045
+ else {
1046
+ outsideConditional.add(parsed.variable);
1047
+ }
1048
+ break;
1049
+ }
1050
+ }
1051
+ }
1052
+ const onlyInConditional = new Set();
1053
+ for (const v of insideConditional) {
1054
+ if (!outsideConditional.has(v))
1055
+ onlyInConditional.add(v);
291
1056
  }
1057
+ return { onlyInConditional, outsideConditional };
292
1058
  }
293
- /**
294
- * Regex fallback for Nunjucks preprocessing when rendering fails.
295
- */
296
- static PreProcessNunjucksViaRegex(sql) {
297
- let processed = sql;
298
- // Replace {{ variable | filter }} patterns
299
- processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlString\s*\}\}/g, "'placeholder'");
300
- processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlNumber\s*\}\}/g, '0');
301
- processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlDate\s*\}\}/g, "'2000-01-01'");
302
- processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlIn\s*\}\}/g, "('placeholder')");
303
- processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlIdentifier\s*\}\}/g, 'placeholder');
304
- processed = processed.replace(/\{\{\s*[\w.]+\s*[^}]*\}\}/g, "'placeholder'");
305
- // Remove block tags but keep content between them
306
- processed = processed.replace(/\{%\s*if\s+[^%]+%\}/g, '');
307
- processed = processed.replace(/\{%\s*endif\s*%\}/g, '');
308
- processed = processed.replace(/\{%\s*else\s*%\}/g, '');
309
- processed = processed.replace(/\{%\s*elif\s+[^%]+%\}/g, '');
310
- processed = processed.replace(/\{%\s*for\s+[^%]+%\}/g, '');
311
- processed = processed.replace(/\{%\s*endfor\s*%\}/g, '');
312
- processed = processed.replace(/\{%\s*set\s+[^%]+%\}/g, '');
313
- processed = processed.replace(/\{#[^#]*#\}/g, ''); // Comments
314
- return processed;
1059
+ static addConditionVariables(token, varSet) {
1060
+ const parsed = token.parsed;
1061
+ if (parsed.expression) {
1062
+ const words = parsed.expression.split(/\s+(?:and|or|not)\s+|\s+/i);
1063
+ for (const word of words) {
1064
+ const trimmed = word.replace(/[!=<>'"()]/g, '').trim();
1065
+ if (trimmed && /^[A-Za-z_]\w*$/.test(trimmed)) {
1066
+ varSet.add(trimmed);
1067
+ }
1068
+ }
1069
+ }
1070
+ }
1071
+ // ═══════════════════════════════════════════════════
1072
+ // Private: Conditional Block Helpers
1073
+ // ═══════════════════════════════════════════════════
1074
+ static addNodeToFragment(token, branch) {
1075
+ if (token.type === 'MJ_TEMPLATE_EXPR') {
1076
+ const parsed = token.parsed;
1077
+ branch.body.nodes.push({
1078
+ type: 'mj_template_expr',
1079
+ variable: parsed.variable,
1080
+ filters: parsed.filters,
1081
+ raw: token.raw,
1082
+ });
1083
+ }
1084
+ else if (token.type === 'MJ_COMPOSITION_REF') {
1085
+ const parsed = token.parsed;
1086
+ branch.body.nodes.push({
1087
+ type: 'mj_composition_ref',
1088
+ categoryPath: parsed.categoryPath,
1089
+ queryName: parsed.queryName,
1090
+ parameters: parsed.parameters,
1091
+ raw: token.raw,
1092
+ });
1093
+ }
315
1094
  }
316
1095
  }
317
1096
  //# sourceMappingURL=sql-parser.js.map