@memberjunction/sql-parser 0.0.1 → 5.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/mj-ast-types.d.ts +234 -0
- package/dist/mj-ast-types.d.ts.map +1 -0
- package/dist/mj-ast-types.js +8 -0
- package/dist/mj-ast-types.js.map +1 -0
- package/dist/mj-lexer.d.ts +88 -0
- package/dist/mj-lexer.d.ts.map +1 -0
- package/dist/mj-lexer.js +431 -0
- package/dist/mj-lexer.js.map +1 -0
- package/dist/mj-placeholder.d.ts +55 -0
- package/dist/mj-placeholder.d.ts.map +1 -0
- package/dist/mj-placeholder.js +156 -0
- package/dist/mj-placeholder.js.map +1 -0
- package/dist/sql-parser.d.ts +288 -0
- package/dist/sql-parser.d.ts.map +1 -0
- package/dist/sql-parser.js +1096 -0
- package/dist/sql-parser.js.map +1 -0
- package/package.json +27 -7
- package/README.md +0 -45
|
@@ -0,0 +1,1096 @@
|
|
|
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
|
+
*/
|
|
15
|
+
import NodeSqlParser from 'node-sql-parser';
|
|
16
|
+
const { Parser } = NodeSqlParser;
|
|
17
|
+
import { MJLexer } from './mj-lexer.js';
|
|
18
|
+
import { MJPlaceholderSubstitution } from './mj-placeholder.js';
|
|
19
|
+
// ═══════════════════════════════════════════════════
|
|
20
|
+
// SQLParser class
|
|
21
|
+
// ═══════════════════════════════════════════════════
|
|
22
|
+
/**
|
|
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 (`{# ... #}`).
|
|
28
|
+
*
|
|
29
|
+
* All methods are static — no instance state is needed.
|
|
30
|
+
*/
|
|
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 ────────────────────────────────
|
|
85
|
+
/**
|
|
86
|
+
* Parse plain SQL into a node-sql-parser AST.
|
|
87
|
+
* Handles FOR XML multi-directive workaround automatically.
|
|
88
|
+
* Returns null if parsing fails.
|
|
89
|
+
*/
|
|
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);
|
|
161
|
+
if (!sql || sql.trim().length === 0) {
|
|
162
|
+
return { Tables: [], Columns: [], UsedASTParsing: false };
|
|
163
|
+
}
|
|
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)
|
|
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 [];
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// ─── CTE Extraction ────────────────────────────────
|
|
234
|
+
/**
|
|
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).
|
|
242
|
+
*/
|
|
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);
|
|
411
|
+
}
|
|
412
|
+
return SQLParser.buildWalkResult(annotations);
|
|
413
|
+
}
|
|
414
|
+
// ═══════════════════════════════════════════════════
|
|
415
|
+
// Private: AST Walker
|
|
416
|
+
// ═══════════════════════════════════════════════════
|
|
417
|
+
/**
|
|
418
|
+
* Recursively walks an AST node, checking values against the placeholder map.
|
|
419
|
+
*/
|
|
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) {
|
|
731
|
+
try {
|
|
732
|
+
const parser = new Parser();
|
|
733
|
+
const ast = parser.astify(sql, { database: dialect });
|
|
734
|
+
const tableAliasMap = new Map();
|
|
735
|
+
const columnRefs = new Set();
|
|
736
|
+
const statements = Array.isArray(ast) ? ast : [ast];
|
|
737
|
+
for (const statement of statements) {
|
|
738
|
+
SQLParser.walkAST(statement, tableAliasMap, columnRefs);
|
|
739
|
+
}
|
|
740
|
+
return SQLParser.deduplicateTables(tableAliasMap);
|
|
741
|
+
}
|
|
742
|
+
catch {
|
|
743
|
+
return null;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
static extractTablesViaRegex(sql) {
|
|
747
|
+
const tableAliasMap = new Map();
|
|
748
|
+
const tablePattern = /(?:FROM|JOIN|INTO)\s+(?:\[?(\w+)\]?\.)?\[?(\w+)\]?(?:\s+(?:AS\s+)?(\w+))?/gi;
|
|
749
|
+
const matches = [...sql.matchAll(tablePattern)];
|
|
750
|
+
for (const match of matches) {
|
|
751
|
+
const schemaName = match[1] || 'dbo';
|
|
752
|
+
const tableName = match[2];
|
|
753
|
+
const alias = match[3] || tableName;
|
|
754
|
+
if (!tableAliasMap.has(alias)) {
|
|
755
|
+
tableAliasMap.set(alias, { schemaName, tableName });
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
return SQLParser.deduplicateTables(tableAliasMap);
|
|
759
|
+
}
|
|
760
|
+
static deduplicateTables(tableAliasMap) {
|
|
761
|
+
const seen = new Set();
|
|
762
|
+
const tables = [];
|
|
763
|
+
for (const [alias, info] of tableAliasMap) {
|
|
764
|
+
const key = `${info.schemaName.toLowerCase()}.${info.tableName.toLowerCase()}`;
|
|
765
|
+
if (!seen.has(key)) {
|
|
766
|
+
seen.add(key);
|
|
767
|
+
tables.push({ TableName: info.tableName, SchemaName: info.schemaName, Alias: alias });
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
return tables;
|
|
771
|
+
}
|
|
772
|
+
static buildColumnRefs(columnRefs) {
|
|
773
|
+
const columns = [];
|
|
774
|
+
for (const ref of columnRefs) {
|
|
775
|
+
const dotIndex = ref.lastIndexOf('.');
|
|
776
|
+
if (dotIndex >= 0) {
|
|
777
|
+
columns.push({ ColumnName: ref.substring(dotIndex + 1), TableQualifier: ref.substring(0, dotIndex) });
|
|
778
|
+
}
|
|
779
|
+
else {
|
|
780
|
+
columns.push({ ColumnName: ref, TableQualifier: null });
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
return columns;
|
|
784
|
+
}
|
|
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) {
|
|
889
|
+
if (!node || typeof node !== 'object')
|
|
890
|
+
return;
|
|
891
|
+
if (node.with) {
|
|
892
|
+
const ctes = Array.isArray(node.with) ? node.with : [node.with];
|
|
893
|
+
for (const cte of ctes) {
|
|
894
|
+
const cteRecord = cte;
|
|
895
|
+
if (cteRecord.stmt) {
|
|
896
|
+
const stmtRecord = cteRecord.stmt;
|
|
897
|
+
const cteAst = (stmtRecord.ast || stmtRecord);
|
|
898
|
+
SQLParser.walkAST(cteAst, tableAliasMap, columnRefs);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
if (node.from) {
|
|
903
|
+
const fromItems = Array.isArray(node.from) ? node.from : [node.from];
|
|
904
|
+
for (const fromItem of fromItems) {
|
|
905
|
+
SQLParser.walkFromItem(fromItem, tableAliasMap, columnRefs);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
if (node.columns) {
|
|
909
|
+
const cols = Array.isArray(node.columns) ? node.columns : [node.columns];
|
|
910
|
+
for (const col of cols) {
|
|
911
|
+
if (col === '*')
|
|
912
|
+
continue;
|
|
913
|
+
const colRecord = col;
|
|
914
|
+
if (colRecord.expr) {
|
|
915
|
+
SQLParser.walkExpression(colRecord.expr, columnRefs, tableAliasMap);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
if (node.where) {
|
|
920
|
+
SQLParser.walkExpression(node.where, columnRefs, tableAliasMap);
|
|
921
|
+
}
|
|
922
|
+
if (node.groupby) {
|
|
923
|
+
const groupbyRecord = node.groupby;
|
|
924
|
+
const groupItems = groupbyRecord.columns || node.groupby;
|
|
925
|
+
const items = Array.isArray(groupItems) ? groupItems : [groupItems];
|
|
926
|
+
for (const group of items) {
|
|
927
|
+
SQLParser.walkExpression(group, columnRefs, tableAliasMap);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
if (node.orderby) {
|
|
931
|
+
const orders = Array.isArray(node.orderby) ? node.orderby : [node.orderby];
|
|
932
|
+
for (const order of orders) {
|
|
933
|
+
const orderRecord = order;
|
|
934
|
+
SQLParser.walkExpression((orderRecord.expr || orderRecord), columnRefs, tableAliasMap);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
if (node._next) {
|
|
938
|
+
SQLParser.walkAST(node._next, tableAliasMap, columnRefs);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
static walkFromItem(fromItem, tableAliasMap, columnRefs) {
|
|
942
|
+
if (!fromItem)
|
|
943
|
+
return;
|
|
944
|
+
if (fromItem.table) {
|
|
945
|
+
const alias = (fromItem.as || fromItem.table);
|
|
946
|
+
tableAliasMap.set(alias, {
|
|
947
|
+
schemaName: fromItem.db || 'dbo',
|
|
948
|
+
tableName: fromItem.table,
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
if (fromItem.expr) {
|
|
952
|
+
const exprRecord = fromItem.expr;
|
|
953
|
+
const subqueryAst = (exprRecord.ast || exprRecord);
|
|
954
|
+
SQLParser.walkAST(subqueryAst, tableAliasMap, columnRefs);
|
|
955
|
+
}
|
|
956
|
+
if (fromItem.on) {
|
|
957
|
+
SQLParser.walkExpression(fromItem.on, columnRefs, tableAliasMap);
|
|
958
|
+
}
|
|
959
|
+
if (fromItem.using) {
|
|
960
|
+
const usings = Array.isArray(fromItem.using) ? fromItem.using : [fromItem.using];
|
|
961
|
+
for (const col of usings) {
|
|
962
|
+
if (typeof col === 'string') {
|
|
963
|
+
columnRefs.add(col);
|
|
964
|
+
}
|
|
965
|
+
else if (col && typeof col === 'object' && 'column' in col) {
|
|
966
|
+
columnRefs.add(col.column);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
static walkExpression(expr, columnRefs, tableAliasMap) {
|
|
972
|
+
if (!expr || typeof expr !== 'object')
|
|
973
|
+
return;
|
|
974
|
+
if (expr.type === 'column_ref') {
|
|
975
|
+
const colName = expr.table ? `${expr.table}.${expr.column}` : expr.column;
|
|
976
|
+
columnRefs.add(colName);
|
|
977
|
+
}
|
|
978
|
+
if (expr.ast && tableAliasMap) {
|
|
979
|
+
SQLParser.walkAST(expr.ast, tableAliasMap, columnRefs);
|
|
980
|
+
}
|
|
981
|
+
if (expr.left)
|
|
982
|
+
SQLParser.walkExpression(expr.left, columnRefs, tableAliasMap);
|
|
983
|
+
if (expr.right)
|
|
984
|
+
SQLParser.walkExpression(expr.right, columnRefs, tableAliasMap);
|
|
985
|
+
if (expr.args) {
|
|
986
|
+
const argsRecord = expr.args;
|
|
987
|
+
const args = argsRecord.value || expr.args;
|
|
988
|
+
const argList = Array.isArray(args) ? args : [args];
|
|
989
|
+
for (const arg of argList) {
|
|
990
|
+
SQLParser.walkExpression(arg, columnRefs, tableAliasMap);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
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;
|
|
1013
|
+
}
|
|
1014
|
+
return 'unknown';
|
|
1015
|
+
}
|
|
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
|
+
}
|
|
1021
|
+
}
|
|
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);
|
|
1056
|
+
}
|
|
1057
|
+
return { onlyInConditional, outsideConditional };
|
|
1058
|
+
}
|
|
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
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
//# sourceMappingURL=sql-parser.js.map
|