@memberjunction/generic-database-provider 5.13.0 → 5.14.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/GenericDatabaseProvider.d.ts +27 -6
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +121 -15
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/queryCompositionEngine.d.ts +267 -0
- package/dist/queryCompositionEngine.d.ts.map +1 -0
- package/dist/queryCompositionEngine.js +870 -0
- package/dist/queryCompositionEngine.js.map +1 -0
- package/package.json +12 -10
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
import { UUIDsEqual } from "@memberjunction/global";
|
|
2
|
+
import { SQLServerDialect, PostgreSQLDialect } from "@memberjunction/sql-dialect";
|
|
3
|
+
import { Metadata, QueryInfo } from "@memberjunction/core";
|
|
4
|
+
import NodeSqlParser from 'node-sql-parser';
|
|
5
|
+
const { Parser: SqlParser } = NodeSqlParser;
|
|
6
|
+
/**
|
|
7
|
+
* Maximum depth for recursive query composition resolution.
|
|
8
|
+
* Prevents runaway recursion from deeply nested compositions.
|
|
9
|
+
*/
|
|
10
|
+
const MAX_COMPOSITION_DEPTH = 10;
|
|
11
|
+
/**
|
|
12
|
+
* Regex for matching {{query:"CategoryPath/QueryName(params)"}} tokens.
|
|
13
|
+
* Captures the full content inside the quotes including optional parameters.
|
|
14
|
+
*/
|
|
15
|
+
const COMPOSITION_TOKEN_REGEX = /\{\{query:"([^"]+)"\}\}/g;
|
|
16
|
+
/**
|
|
17
|
+
* Regex for parsing the inner reference: path/QueryName(param1=value1, param2=value2)
|
|
18
|
+
* Group 1: full path including query name (everything before optional parentheses)
|
|
19
|
+
* Group 2: parameters string (inside parentheses, optional)
|
|
20
|
+
*/
|
|
21
|
+
const REFERENCE_PARSE_REGEX = /^(.+?)(?:\((.+)\))?$/;
|
|
22
|
+
/**
|
|
23
|
+
* Regex for parsing individual parameter assignments: key=value or key='literal'
|
|
24
|
+
*/
|
|
25
|
+
const PARAM_PARSE_REGEX = /^\s*(\w+)\s*=\s*(?:'([^']*)'|(\w+))\s*$/;
|
|
26
|
+
/**
|
|
27
|
+
* QueryCompositionEngine resolves {{query:"CategoryPath/QueryName(params)"}} tokens
|
|
28
|
+
* in query SQL into Common Table Expressions (CTEs). It handles:
|
|
29
|
+
*
|
|
30
|
+
* - Recursive resolution of nested compositions
|
|
31
|
+
* - Cycle detection via an in-progress set
|
|
32
|
+
* - Parameter modes: static literals and pass-through from outer query
|
|
33
|
+
* - Deduplication of identical query+params references
|
|
34
|
+
* - Platform-aware SQL resolution via QueryInfo.GetPlatformSQL()
|
|
35
|
+
*
|
|
36
|
+
* This engine runs BEFORE Nunjucks template processing, so regular {{param}}
|
|
37
|
+
* tokens are preserved for later substitution.
|
|
38
|
+
*/
|
|
39
|
+
export class QueryCompositionEngine {
|
|
40
|
+
/**
|
|
41
|
+
* Checks whether SQL contains any {{query:"..."}} composition tokens.
|
|
42
|
+
* Use this as a fast guard before calling ResolveComposition().
|
|
43
|
+
* Only considers tokens outside of SQL comments.
|
|
44
|
+
*/
|
|
45
|
+
HasCompositionTokens(sql) {
|
|
46
|
+
if (!sql)
|
|
47
|
+
return false;
|
|
48
|
+
const stripped = this.stripSQLComments(sql);
|
|
49
|
+
return stripped.includes('{{query:"');
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Parses all {{query:"..."}} tokens from SQL without resolving them.
|
|
53
|
+
* Useful for dependency extraction during the save pipeline.
|
|
54
|
+
* Only considers tokens outside of SQL comments.
|
|
55
|
+
*
|
|
56
|
+
* @param sql - The SQL text to parse
|
|
57
|
+
* @returns Array of parsed token metadata
|
|
58
|
+
*/
|
|
59
|
+
ParseCompositionTokens(sql) {
|
|
60
|
+
if (!sql)
|
|
61
|
+
return [];
|
|
62
|
+
const stripped = this.stripSQLComments(sql);
|
|
63
|
+
const tokens = [];
|
|
64
|
+
let match;
|
|
65
|
+
const regex = new RegExp(COMPOSITION_TOKEN_REGEX.source, 'g');
|
|
66
|
+
while ((match = regex.exec(stripped)) !== null) {
|
|
67
|
+
const parsed = this.parseTokenContent(match[0], match[1]);
|
|
68
|
+
if (parsed) {
|
|
69
|
+
tokens.push(parsed);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return tokens;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Resolves all {{query:"..."}} composition tokens in the given SQL into CTEs.
|
|
76
|
+
*
|
|
77
|
+
* @param sql - The SQL containing composition tokens
|
|
78
|
+
* @param platform - Target database platform for SQL resolution
|
|
79
|
+
* @param contextUser - User context for permission checks on referenced queries
|
|
80
|
+
* @param outerParams - Parameter values from the outer/parent query (for pass-through resolution)
|
|
81
|
+
* @param inlineDependencies - Optional inline dependency specs for transient query testing.
|
|
82
|
+
* When provided, these are checked first before falling back to Metadata.Provider.Queries.
|
|
83
|
+
* Inline dependencies skip governance validation (Reusable, IsApproved, UserCanRun).
|
|
84
|
+
* @returns CompositionResult with fully resolved SQL and provenance metadata
|
|
85
|
+
* @throws Error if a referenced query is not found, not composable, or creates a cycle
|
|
86
|
+
*/
|
|
87
|
+
ResolveComposition(sql, platform, contextUser, outerParams, inlineDependencies) {
|
|
88
|
+
const cteEntries = [];
|
|
89
|
+
const dependencyGraph = new Map();
|
|
90
|
+
const inProgressSet = new Set();
|
|
91
|
+
// Mutable flag passed by reference through recursion — short-circuits once true
|
|
92
|
+
const templateFlag = { value: false };
|
|
93
|
+
const resolvedSQL = this.resolveTokensRecursive(sql, platform, contextUser, outerParams || {}, cteEntries, dependencyGraph, inProgressSet, templateFlag, 0, inlineDependencies);
|
|
94
|
+
const hasCompositions = cteEntries.length > 0;
|
|
95
|
+
let finalSQL = resolvedSQL;
|
|
96
|
+
if (hasCompositions) {
|
|
97
|
+
finalSQL = this.assembleCTEs(cteEntries, resolvedSQL, platform);
|
|
98
|
+
}
|
|
99
|
+
// If any dependency uses templates, Nunjucks will run on the resolved SQL.
|
|
100
|
+
// Neutralize any {{ }} patterns inside SQL comments so Nunjucks doesn't
|
|
101
|
+
// try to parse them as template expressions (e.g. -- Demonstrates {{query:"..."}}).
|
|
102
|
+
if (templateFlag.value) {
|
|
103
|
+
finalSQL = this.escapeTemplateTokensInComments(finalSQL);
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
ResolvedSQL: finalSQL,
|
|
107
|
+
CTEs: cteEntries.map(e => e.Info),
|
|
108
|
+
DependencyGraph: dependencyGraph,
|
|
109
|
+
HasCompositions: hasCompositions,
|
|
110
|
+
AnyDependencyUsesTemplates: templateFlag.value
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Recursively resolves composition tokens in SQL, building up CTE entries.
|
|
115
|
+
*/
|
|
116
|
+
resolveTokensRecursive(sql, platform, contextUser, outerParams, cteEntries, dependencyGraph, inProgressSet, templateFlag, depth, inlineDependencies) {
|
|
117
|
+
if (depth > MAX_COMPOSITION_DEPTH) {
|
|
118
|
+
throw new Error(`Query composition depth exceeds maximum of ${MAX_COMPOSITION_DEPTH}. ` +
|
|
119
|
+
`This likely indicates an overly deep nesting chain.`);
|
|
120
|
+
}
|
|
121
|
+
const tokens = this.ParseCompositionTokens(sql);
|
|
122
|
+
if (tokens.length === 0)
|
|
123
|
+
return sql;
|
|
124
|
+
let resolvedSQL = sql;
|
|
125
|
+
for (const token of tokens) {
|
|
126
|
+
const lookupResult = this.lookupQueryWithInline(token, inlineDependencies);
|
|
127
|
+
const referencedQuery = lookupResult.Query;
|
|
128
|
+
// Only validate governance (Reusable, IsApproved, permissions) for metadata-backed queries.
|
|
129
|
+
// Inline dependencies are inherently authorized by the caller.
|
|
130
|
+
if (!lookupResult.IsInline) {
|
|
131
|
+
this.validateQueryComposable(referencedQuery, token, contextUser);
|
|
132
|
+
}
|
|
133
|
+
// Depth-first transitive UsesTemplate check — short-circuit once true
|
|
134
|
+
if (!templateFlag.value && referencedQuery.UsesTemplate) {
|
|
135
|
+
templateFlag.value = true;
|
|
136
|
+
}
|
|
137
|
+
// Cycle detection
|
|
138
|
+
if (inProgressSet.has(referencedQuery.ID)) {
|
|
139
|
+
const cyclePath = [...inProgressSet, referencedQuery.ID].join(' → ');
|
|
140
|
+
throw new Error(`Circular query dependency detected: ${cyclePath}. ` +
|
|
141
|
+
`Query "${referencedQuery.Name}" is already being resolved.`);
|
|
142
|
+
}
|
|
143
|
+
// Resolve parameter values
|
|
144
|
+
const resolvedParams = this.resolveParameters(token.Parameters, outerParams);
|
|
145
|
+
// Build deduplication key
|
|
146
|
+
const dedupeKey = this.buildDeduplicationKey(referencedQuery.ID, resolvedParams);
|
|
147
|
+
// Check if we already have this exact CTE
|
|
148
|
+
const existingCTE = cteEntries.find(e => e.DeduplicationKey === dedupeKey);
|
|
149
|
+
if (existingCTE) {
|
|
150
|
+
resolvedSQL = resolvedSQL.replace(token.FullToken, existingCTE.CTEName);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
// Get platform-specific SQL for the referenced query
|
|
154
|
+
const refSQL = referencedQuery.GetPlatformSQL(platform);
|
|
155
|
+
// Substitute static parameter values directly into the referenced query's SQL
|
|
156
|
+
const paramSubstitutedSQL = this.substituteStaticParams(refSQL, resolvedParams);
|
|
157
|
+
// Track in-progress for cycle detection
|
|
158
|
+
inProgressSet.add(referencedQuery.ID);
|
|
159
|
+
// For inline deps, pass their nested dependencies into the recursive call.
|
|
160
|
+
// For metadata deps, pass the parent's inline deps so sibling references work.
|
|
161
|
+
const nestedInlineDeps = lookupResult.IsInline
|
|
162
|
+
? lookupResult.NestedDependencies
|
|
163
|
+
: inlineDependencies;
|
|
164
|
+
// Recursively resolve any nested composition tokens in the referenced query
|
|
165
|
+
const nestedResolvedSQL = this.resolveTokensRecursive(paramSubstitutedSQL, platform, contextUser, resolvedParams, cteEntries, dependencyGraph, inProgressSet, templateFlag, depth + 1, nestedInlineDeps);
|
|
166
|
+
inProgressSet.delete(referencedQuery.ID);
|
|
167
|
+
// Track dependency
|
|
168
|
+
const parentDeps = dependencyGraph.get('__current__') || [];
|
|
169
|
+
if (!parentDeps.some(id => UUIDsEqual(id, referencedQuery.ID))) {
|
|
170
|
+
parentDeps.push(referencedQuery.ID);
|
|
171
|
+
dependencyGraph.set('__current__', parentDeps);
|
|
172
|
+
}
|
|
173
|
+
// Generate CTE name (platform-aware: brackets for SQL Server, double quotes for PG)
|
|
174
|
+
const cteName = this.generateCTEName(referencedQuery, resolvedParams, platform);
|
|
175
|
+
const cteEntry = {
|
|
176
|
+
DeduplicationKey: dedupeKey,
|
|
177
|
+
CTEName: cteName,
|
|
178
|
+
SQL: nestedResolvedSQL,
|
|
179
|
+
Info: {
|
|
180
|
+
QueryID: referencedQuery.ID,
|
|
181
|
+
QueryName: referencedQuery.Name,
|
|
182
|
+
CategoryPath: token.FullPath,
|
|
183
|
+
CTEName: cteName,
|
|
184
|
+
OriginalSQL: refSQL,
|
|
185
|
+
ResolvedSQL: nestedResolvedSQL,
|
|
186
|
+
Parameters: resolvedParams
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
cteEntries.push(cteEntry);
|
|
190
|
+
resolvedSQL = resolvedSQL.replace(token.FullToken, cteName);
|
|
191
|
+
}
|
|
192
|
+
return resolvedSQL;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Parses the content inside a {{query:"..."}} token.
|
|
196
|
+
*/
|
|
197
|
+
parseTokenContent(fullToken, content) {
|
|
198
|
+
const refMatch = REFERENCE_PARSE_REGEX.exec(content.trim());
|
|
199
|
+
if (!refMatch)
|
|
200
|
+
return null;
|
|
201
|
+
const fullPath = refMatch[1].trim();
|
|
202
|
+
const paramsString = refMatch[2] || '';
|
|
203
|
+
// Split path into segments; last segment is the query name
|
|
204
|
+
const segments = fullPath.split('/').map(s => s.trim()).filter(s => s.length > 0);
|
|
205
|
+
if (segments.length === 0)
|
|
206
|
+
return null;
|
|
207
|
+
const queryName = segments[segments.length - 1];
|
|
208
|
+
const categorySegments = segments.slice(0, -1);
|
|
209
|
+
// Parse parameters
|
|
210
|
+
const parameters = [];
|
|
211
|
+
if (paramsString.trim().length > 0) {
|
|
212
|
+
const paramParts = this.splitParams(paramsString);
|
|
213
|
+
for (const part of paramParts) {
|
|
214
|
+
const paramMatch = PARAM_PARSE_REGEX.exec(part);
|
|
215
|
+
if (paramMatch) {
|
|
216
|
+
parameters.push({
|
|
217
|
+
Name: paramMatch[1],
|
|
218
|
+
StaticValue: paramMatch[2] !== undefined ? paramMatch[2] : null,
|
|
219
|
+
PassThroughName: paramMatch[3] !== undefined ? paramMatch[3] : null
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
FullToken: fullToken,
|
|
226
|
+
CategorySegments: categorySegments,
|
|
227
|
+
QueryName: queryName,
|
|
228
|
+
FullPath: fullPath,
|
|
229
|
+
Parameters: parameters
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Splits parameter string by commas, respecting quoted values.
|
|
234
|
+
*/
|
|
235
|
+
splitParams(paramsString) {
|
|
236
|
+
const parts = [];
|
|
237
|
+
let current = '';
|
|
238
|
+
let inQuote = false;
|
|
239
|
+
for (const ch of paramsString) {
|
|
240
|
+
if (ch === "'" && !inQuote) {
|
|
241
|
+
inQuote = true;
|
|
242
|
+
current += ch;
|
|
243
|
+
}
|
|
244
|
+
else if (ch === "'" && inQuote) {
|
|
245
|
+
inQuote = false;
|
|
246
|
+
current += ch;
|
|
247
|
+
}
|
|
248
|
+
else if (ch === ',' && !inQuote) {
|
|
249
|
+
parts.push(current.trim());
|
|
250
|
+
current = '';
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
current += ch;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (current.trim().length > 0) {
|
|
257
|
+
parts.push(current.trim());
|
|
258
|
+
}
|
|
259
|
+
return parts;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Looks up a query by category path + name in the metadata provider.
|
|
263
|
+
*/
|
|
264
|
+
lookupQuery(token) {
|
|
265
|
+
const result = this.lookupQueryWithInline(token);
|
|
266
|
+
return result.Query;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Looks up a query by category path + name, checking inline dependencies first,
|
|
270
|
+
* then falling back to the metadata provider.
|
|
271
|
+
*
|
|
272
|
+
* For inline dependencies, creates a synthetic QueryInfo with the SQL and flags set
|
|
273
|
+
* appropriately. Inline queries skip governance validation (Reusable, IsApproved, etc.)
|
|
274
|
+
* since they are inherently authorized by the caller.
|
|
275
|
+
*/
|
|
276
|
+
lookupQueryWithInline(token, inlineDependencies) {
|
|
277
|
+
// Check inline dependencies first
|
|
278
|
+
if (inlineDependencies && inlineDependencies.length > 0) {
|
|
279
|
+
const inlineMatch = this.findInlineDependency(token, inlineDependencies);
|
|
280
|
+
if (inlineMatch) {
|
|
281
|
+
const syntheticQuery = this.buildSyntheticQueryInfo(inlineMatch);
|
|
282
|
+
return {
|
|
283
|
+
Query: syntheticQuery,
|
|
284
|
+
IsInline: true,
|
|
285
|
+
NestedDependencies: inlineMatch.Dependencies,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
// Fall back to metadata provider
|
|
290
|
+
return {
|
|
291
|
+
Query: this.lookupQueryFromMetadata(token),
|
|
292
|
+
IsInline: false,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Finds a matching inline dependency spec for the given token.
|
|
297
|
+
*/
|
|
298
|
+
findInlineDependency(token, inlineDependencies) {
|
|
299
|
+
const queryName = token.QueryName.toLowerCase();
|
|
300
|
+
// Try category path + name match first
|
|
301
|
+
if (token.CategorySegments.length > 0) {
|
|
302
|
+
const expectedPath = `/${token.CategorySegments.join('/')}/`;
|
|
303
|
+
const match = inlineDependencies.find(d => d.Name.toLowerCase() === queryName &&
|
|
304
|
+
d.CategoryPath.toLowerCase() === expectedPath.toLowerCase());
|
|
305
|
+
if (match)
|
|
306
|
+
return match;
|
|
307
|
+
}
|
|
308
|
+
// Fall back to name-only match
|
|
309
|
+
return inlineDependencies.find(d => d.Name.toLowerCase() === queryName);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Builds a synthetic QueryInfo from an inline dependency spec.
|
|
313
|
+
* Sets flags so that GetPlatformSQL returns the inline SQL directly.
|
|
314
|
+
*/
|
|
315
|
+
buildSyntheticQueryInfo(dep) {
|
|
316
|
+
const synthetic = new QueryInfo();
|
|
317
|
+
// Use a deterministic synthetic ID based on name+path to support cycle detection and deduplication
|
|
318
|
+
synthetic.ID = `__inline__${dep.CategoryPath}${dep.Name}`.toLowerCase();
|
|
319
|
+
synthetic.Name = dep.Name;
|
|
320
|
+
synthetic.SQL = dep.SQL;
|
|
321
|
+
synthetic.UsesTemplate = dep.UsesTemplate ?? false;
|
|
322
|
+
synthetic.Reusable = true;
|
|
323
|
+
synthetic.Status = 'Approved';
|
|
324
|
+
return synthetic;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Looks up a query by category path + name from the metadata provider only.
|
|
328
|
+
*/
|
|
329
|
+
lookupQueryFromMetadata(token) {
|
|
330
|
+
const allQueries = Metadata.Provider.Queries;
|
|
331
|
+
const queryName = token.QueryName.toLowerCase();
|
|
332
|
+
// If category segments provided, build expected category path
|
|
333
|
+
if (token.CategorySegments.length > 0) {
|
|
334
|
+
const expectedPath = `/${token.CategorySegments.join('/')}/`;
|
|
335
|
+
const match = allQueries.find(q => q.Name.toLowerCase() === queryName &&
|
|
336
|
+
q.CategoryPath.toLowerCase() === expectedPath.toLowerCase());
|
|
337
|
+
if (match)
|
|
338
|
+
return match;
|
|
339
|
+
}
|
|
340
|
+
// Fall back to name-only match
|
|
341
|
+
const matches = allQueries.filter(q => q.Name.toLowerCase() === queryName);
|
|
342
|
+
if (matches.length === 0) {
|
|
343
|
+
throw new Error(`Referenced query not found: "${token.FullPath}". ` +
|
|
344
|
+
`Ensure the query exists and the category path is correct.`);
|
|
345
|
+
}
|
|
346
|
+
if (matches.length > 1) {
|
|
347
|
+
throw new Error(`Ambiguous query reference: "${token.FullPath}" matches ${matches.length} queries. ` +
|
|
348
|
+
`Use the full category path to disambiguate.`);
|
|
349
|
+
}
|
|
350
|
+
return matches[0];
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Validates that a referenced query is eligible for composition.
|
|
354
|
+
*/
|
|
355
|
+
validateQueryComposable(query, token, contextUser) {
|
|
356
|
+
if (!query.Reusable) {
|
|
357
|
+
throw new Error(`Query "${token.FullPath}" (${query.Name}) is not marked as Reusable. ` +
|
|
358
|
+
`Set Reusable=true on the query to allow composition.`);
|
|
359
|
+
}
|
|
360
|
+
if (!query.IsApproved) {
|
|
361
|
+
throw new Error(`Query "${token.FullPath}" (${query.Name}) is not Approved (status: ${query.Status}). ` +
|
|
362
|
+
`Only Approved queries can be composed.`);
|
|
363
|
+
}
|
|
364
|
+
if (!query.UserCanRun(contextUser)) {
|
|
365
|
+
throw new Error(`User does not have permission to run referenced query "${token.FullPath}" (${query.Name}).`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Resolves parameter values for a composition reference.
|
|
370
|
+
* Static values are used directly; pass-through values are looked up from outer params.
|
|
371
|
+
*/
|
|
372
|
+
resolveParameters(params, outerParams) {
|
|
373
|
+
const resolved = {};
|
|
374
|
+
for (const param of params) {
|
|
375
|
+
if (param.StaticValue !== null) {
|
|
376
|
+
resolved[param.Name] = param.StaticValue;
|
|
377
|
+
}
|
|
378
|
+
else if (param.PassThroughName !== null) {
|
|
379
|
+
// Pass-through: the value comes from the outer query's parameters
|
|
380
|
+
// At composition time, we create a Nunjucks placeholder so that
|
|
381
|
+
// the downstream Nunjucks processor can substitute the actual value
|
|
382
|
+
resolved[param.Name] = `{{${param.PassThroughName}}}`;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return resolved;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Substitutes resolved parameter values into a query's SQL.
|
|
389
|
+
* - Static values: replaces {{paramName}} with 'value'
|
|
390
|
+
* - Pass-through values: renames {{paramName}} to {{outerParamName}} so
|
|
391
|
+
* the downstream Nunjucks processor can resolve it from the outer query's parameters.
|
|
392
|
+
*/
|
|
393
|
+
substituteStaticParams(sql, params) {
|
|
394
|
+
let result = sql;
|
|
395
|
+
for (const [name, value] of Object.entries(params)) {
|
|
396
|
+
const paramRegex = new RegExp(`\\{\\{\\s*${name}\\s*\\}\\}`, 'g');
|
|
397
|
+
if (value.startsWith('{{') && value.endsWith('}}')) {
|
|
398
|
+
// Pass-through: rename the inner param token to the outer param name
|
|
399
|
+
// e.g., {{region}} → {{userRegion}} when the mapping is region=userRegion
|
|
400
|
+
result = result.replace(paramRegex, value);
|
|
401
|
+
}
|
|
402
|
+
else if (/^-?\d+(\.\d+)?$/.test(value)) {
|
|
403
|
+
// Numeric value: substitute as bare literal (no quotes)
|
|
404
|
+
// so expressions like DATEADD(DAY, -{{lookbackDays}}, ...) work correctly
|
|
405
|
+
result = result.replace(paramRegex, value);
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
// String value: substitute as a quoted literal
|
|
409
|
+
result = result.replace(paramRegex, `'${value.replace(/'/g, "''")}'`);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return result;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Builds a deduplication key for a CTE based on query ID and sorted parameter values.
|
|
416
|
+
*/
|
|
417
|
+
buildDeduplicationKey(queryID, params) {
|
|
418
|
+
const sortedParams = Object.entries(params)
|
|
419
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
420
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
421
|
+
.join('&');
|
|
422
|
+
return `${queryID}|${sortedParams}`;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Generates a SQL-safe CTE name from the query name + short hash for uniqueness.
|
|
426
|
+
*/
|
|
427
|
+
generateCTEName(query, params, platform) {
|
|
428
|
+
// Sanitize query name: remove non-alphanumeric chars, replace spaces with underscores
|
|
429
|
+
const sanitized = query.Name
|
|
430
|
+
.replace(/[^a-zA-Z0-9_ ]/g, '')
|
|
431
|
+
.replace(/\s+/g, '_')
|
|
432
|
+
.substring(0, 50);
|
|
433
|
+
// Create a short hash suffix from query ID + params for uniqueness
|
|
434
|
+
const hashInput = query.ID + JSON.stringify(params);
|
|
435
|
+
const hash = this.simpleHash(hashInput);
|
|
436
|
+
const identifier = `__cte_${sanitized}_${hash}`;
|
|
437
|
+
return this.getDialect(platform).QuoteIdentifier(identifier);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Resolves a DatabasePlatform string to the corresponding SQLDialect instance.
|
|
441
|
+
*/
|
|
442
|
+
getDialect(platform) {
|
|
443
|
+
switch (platform) {
|
|
444
|
+
case 'postgresql': return new PostgreSQLDialect();
|
|
445
|
+
case 'sqlserver': return new SQLServerDialect();
|
|
446
|
+
default: throw new Error(`Unsupported database platform: ${platform}`);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Simple string hash for generating short, deterministic suffixes.
|
|
451
|
+
*/
|
|
452
|
+
simpleHash(input) {
|
|
453
|
+
let hash = 0;
|
|
454
|
+
for (let i = 0; i < input.length; i++) {
|
|
455
|
+
const char = input.charCodeAt(i);
|
|
456
|
+
hash = ((hash << 5) - hash) + char;
|
|
457
|
+
hash = hash & hash; // Convert to 32bit integer
|
|
458
|
+
}
|
|
459
|
+
return Math.abs(hash).toString(36).substring(0, 6);
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Assembles CTE entries into a WITH clause prepended to the main SQL.
|
|
463
|
+
*/
|
|
464
|
+
assembleCTEs(cteEntries, mainSQL, platform) {
|
|
465
|
+
if (cteEntries.length === 0)
|
|
466
|
+
return mainSQL;
|
|
467
|
+
// Check if the main SQL already starts with a WITH clause
|
|
468
|
+
const trimmedMain = mainSQL.trimStart();
|
|
469
|
+
const startsWithWith = /^WITH\s/i.test(trimmedMain);
|
|
470
|
+
const dialect = this.getDialect(platform);
|
|
471
|
+
const cteDefinitions = cteEntries.map(entry => `${entry.CTEName} AS (\n${this.stripTrailingOrderBy(entry.SQL, dialect)}\n)`);
|
|
472
|
+
if (startsWithWith) {
|
|
473
|
+
// Main SQL has its own WITH — merge by removing the leading WITH
|
|
474
|
+
// and prepending our CTEs before it
|
|
475
|
+
const mainWithoutWith = trimmedMain.replace(/^WITH\s+/i, '');
|
|
476
|
+
return `WITH ${cteDefinitions.join(',\n')},\n${mainWithoutWith}`;
|
|
477
|
+
}
|
|
478
|
+
return `WITH ${cteDefinitions.join(',\n')}\n${mainSQL}`;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Strips a trailing ORDER BY clause from SQL that will be wrapped in a CTE.
|
|
482
|
+
*
|
|
483
|
+
* SQL Server disallows ORDER BY inside CTEs unless TOP, OFFSET, or FOR XML is present.
|
|
484
|
+
* PostgreSQL allows ORDER BY in CTEs, so no stripping is needed there.
|
|
485
|
+
*
|
|
486
|
+
* Uses a 4-tier strategy:
|
|
487
|
+
* 1. Fast exit — no ORDER keyword at all, or dialect allows ORDER BY in CTEs
|
|
488
|
+
* 2. AST path — parse (with Nunjucks preprocessing if needed), check if ORDER BY is legal
|
|
489
|
+
* (TOP/OFFSET/FOR XML via AST nodes), null out orderby if not, regenerate.
|
|
490
|
+
* Handles window functions, UNION/EXCEPT, subqueries, string literals, and Nunjucks templates.
|
|
491
|
+
* 3. Regex fallback — paren-depth heuristic for SQL the parser still can't handle
|
|
492
|
+
* (e.g. STRING_AGG WITHIN GROUP)
|
|
493
|
+
* 4. OFFSET 0 ROWS injection — last resort when both AST and regex fail to strip ORDER BY.
|
|
494
|
+
* Injects OFFSET 0 ROWS after the ORDER BY clause to make it legal in CTEs.
|
|
495
|
+
* This is semantically neutral (returns all rows starting from 0) but switches
|
|
496
|
+
* SQL Server into paging mode internally, which may affect query plan shape.
|
|
497
|
+
*/
|
|
498
|
+
stripTrailingOrderBy(sql, dialect) {
|
|
499
|
+
if (!sql)
|
|
500
|
+
return sql;
|
|
501
|
+
const trimmed = sql.trimEnd();
|
|
502
|
+
if (!/ORDER/i.test(trimmed))
|
|
503
|
+
return sql;
|
|
504
|
+
if (dialect.AllowsOrderByInCTE)
|
|
505
|
+
return sql;
|
|
506
|
+
// Tier 2: AST-based stripping
|
|
507
|
+
const astResult = this.stripOrderByViaAST(trimmed, dialect.ParserDialect);
|
|
508
|
+
if (astResult !== null)
|
|
509
|
+
return astResult;
|
|
510
|
+
// Tier 3: Regex fallback
|
|
511
|
+
const regexResult = this.stripOrderByViaRegex(trimmed);
|
|
512
|
+
if (regexResult !== trimmed)
|
|
513
|
+
return regexResult;
|
|
514
|
+
// Tier 4: OFFSET 0 ROWS injection — last resort.
|
|
515
|
+
// If we reach here, the SQL has an ORDER BY that neither AST nor regex could strip
|
|
516
|
+
// (e.g. STRING_AGG WITHIN GROUP with a trailing ORDER BY). Rather than returning
|
|
517
|
+
// the SQL unchanged (which would cause a SQL Server CTE error), inject OFFSET 0 ROWS
|
|
518
|
+
// after the ORDER BY to make it legal. This is semantically neutral but may affect
|
|
519
|
+
// query plan shape on large result sets.
|
|
520
|
+
return this.injectOffset0Rows(trimmed);
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Attempts to strip the top-level ORDER BY clause using AST parsing.
|
|
524
|
+
* Tries direct parsing first, then Nunjucks-preprocessed parsing if the SQL
|
|
525
|
+
* contains template syntax. Handles UNION/EXCEPT by walking the _next chain.
|
|
526
|
+
*/
|
|
527
|
+
stripOrderByViaAST(sql, parserDialect) {
|
|
528
|
+
const directResult = this.tryASTStrip(sql, parserDialect);
|
|
529
|
+
if (directResult !== null)
|
|
530
|
+
return directResult;
|
|
531
|
+
if (/\{[%{#]/.test(sql)) {
|
|
532
|
+
return this.tryNunjucksAwareStrip(sql, parserDialect);
|
|
533
|
+
}
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Core AST stripping: parse, analyze, and regenerate SQL without ORDER BY.
|
|
538
|
+
*/
|
|
539
|
+
tryASTStrip(sql, parserDialect) {
|
|
540
|
+
try {
|
|
541
|
+
const parser = new SqlParser();
|
|
542
|
+
const ast = parser.astify(sql, { database: parserDialect });
|
|
543
|
+
const stmt = Array.isArray(ast) ? ast[0] : ast;
|
|
544
|
+
if (!stmt)
|
|
545
|
+
return sql;
|
|
546
|
+
const stmtRecord = stmt;
|
|
547
|
+
const orderByStmt = this.findOrderByStatement(stmtRecord);
|
|
548
|
+
if (!orderByStmt)
|
|
549
|
+
return sql;
|
|
550
|
+
if (this.isOrderByLegalInCTE(orderByStmt))
|
|
551
|
+
return sql;
|
|
552
|
+
orderByStmt.orderby = null;
|
|
553
|
+
return parser.sqlify(Array.isArray(ast) ? ast : [stmt], { database: parserDialect });
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
return null;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Walks the _next chain (UNION/EXCEPT/INTERSECT) to find the statement
|
|
561
|
+
* that carries the ORDER BY clause.
|
|
562
|
+
*/
|
|
563
|
+
findOrderByStatement(stmt) {
|
|
564
|
+
if (stmt.orderby)
|
|
565
|
+
return stmt;
|
|
566
|
+
if (stmt._next)
|
|
567
|
+
return this.findOrderByStatement(stmt._next);
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Nunjucks-aware ORDER BY stripping: preprocess templates into placeholder SQL,
|
|
572
|
+
* parse with AST to confirm top-level ORDER BY exists, then use the position-aware
|
|
573
|
+
* scanner on the original SQL to strip only the last top-level ORDER BY.
|
|
574
|
+
*/
|
|
575
|
+
tryNunjucksAwareStrip(sql, parserDialect) {
|
|
576
|
+
const preprocessed = this.preprocessNunjucks(sql);
|
|
577
|
+
try {
|
|
578
|
+
const parser = new SqlParser();
|
|
579
|
+
const ast = parser.astify(preprocessed, { database: parserDialect });
|
|
580
|
+
const stmt = Array.isArray(ast) ? ast[0] : ast;
|
|
581
|
+
if (!stmt)
|
|
582
|
+
return sql;
|
|
583
|
+
const stmtRecord = stmt;
|
|
584
|
+
const orderByStmt = this.findOrderByStatement(stmtRecord);
|
|
585
|
+
if (!orderByStmt)
|
|
586
|
+
return sql;
|
|
587
|
+
if (this.isOrderByLegalInCTE(orderByStmt))
|
|
588
|
+
return sql;
|
|
589
|
+
return this.stripLastTopLevelOrderBy(sql);
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Checks AST properties to determine if ORDER BY is legal in a CTE context.
|
|
597
|
+
*/
|
|
598
|
+
isOrderByLegalInCTE(stmt) {
|
|
599
|
+
if (stmt.top)
|
|
600
|
+
return true;
|
|
601
|
+
if (stmt.limit)
|
|
602
|
+
return true;
|
|
603
|
+
const forClause = stmt.for;
|
|
604
|
+
if (forClause && typeof forClause === 'object' && forClause.type &&
|
|
605
|
+
String(forClause.type).toLowerCase().includes('xml')) {
|
|
606
|
+
return true;
|
|
607
|
+
}
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Strips the last top-level ORDER BY clause using position-aware scanning.
|
|
612
|
+
* Skips strings, comments, Nunjucks tags, and tracks paren depth.
|
|
613
|
+
*/
|
|
614
|
+
stripLastTopLevelOrderBy(sql) {
|
|
615
|
+
const positions = this.findTopLevelOrderByPositions(sql);
|
|
616
|
+
if (positions.length === 0)
|
|
617
|
+
return sql;
|
|
618
|
+
const lastPos = positions[positions.length - 1];
|
|
619
|
+
return sql.substring(0, lastPos).trimEnd();
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Finds character positions of all ORDER BY keywords at the outermost level
|
|
623
|
+
* (paren depth 0, not inside strings, comments, or Nunjucks tags).
|
|
624
|
+
*/
|
|
625
|
+
findTopLevelOrderByPositions(sql) {
|
|
626
|
+
const positions = [];
|
|
627
|
+
let i = 0;
|
|
628
|
+
let parenDepth = 0;
|
|
629
|
+
while (i < sql.length) {
|
|
630
|
+
if (sql[i] === "'") {
|
|
631
|
+
i++;
|
|
632
|
+
while (i < sql.length) {
|
|
633
|
+
if (sql[i] === "'" && i + 1 < sql.length && sql[i + 1] === "'") {
|
|
634
|
+
i += 2;
|
|
635
|
+
}
|
|
636
|
+
else if (sql[i] === "'") {
|
|
637
|
+
i++;
|
|
638
|
+
break;
|
|
639
|
+
}
|
|
640
|
+
else {
|
|
641
|
+
i++;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
if (sql[i] === '-' && i + 1 < sql.length && sql[i + 1] === '-') {
|
|
647
|
+
while (i < sql.length && sql[i] !== '\n')
|
|
648
|
+
i++;
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
if (sql[i] === '/' && i + 1 < sql.length && sql[i + 1] === '*') {
|
|
652
|
+
i += 2;
|
|
653
|
+
while (i < sql.length) {
|
|
654
|
+
if (sql[i] === '*' && i + 1 < sql.length && sql[i + 1] === '/') {
|
|
655
|
+
i += 2;
|
|
656
|
+
break;
|
|
657
|
+
}
|
|
658
|
+
i++;
|
|
659
|
+
}
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
if (sql[i] === '{' && i + 1 < sql.length && sql[i + 1] === '%') {
|
|
663
|
+
i += 2;
|
|
664
|
+
while (i < sql.length) {
|
|
665
|
+
if (sql[i] === '%' && i + 1 < sql.length && sql[i + 1] === '}') {
|
|
666
|
+
i += 2;
|
|
667
|
+
break;
|
|
668
|
+
}
|
|
669
|
+
i++;
|
|
670
|
+
}
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if (sql[i] === '{' && i + 1 < sql.length && sql[i + 1] === '{') {
|
|
674
|
+
i += 2;
|
|
675
|
+
while (i < sql.length) {
|
|
676
|
+
if (sql[i] === '}' && i + 1 < sql.length && sql[i + 1] === '}') {
|
|
677
|
+
i += 2;
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
i++;
|
|
681
|
+
}
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
if (sql[i] === '(') {
|
|
685
|
+
parenDepth++;
|
|
686
|
+
i++;
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
if (sql[i] === ')') {
|
|
690
|
+
parenDepth--;
|
|
691
|
+
i++;
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
if (parenDepth === 0 && /^ORDER\s+BY\b/i.test(sql.substring(i))) {
|
|
695
|
+
if (i === 0 || /[\s,;()\n]/.test(sql[i - 1])) {
|
|
696
|
+
positions.push(i);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
i++;
|
|
700
|
+
}
|
|
701
|
+
return positions;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Preprocesses Nunjucks templates into valid SQL for AST parsing.
|
|
705
|
+
*/
|
|
706
|
+
preprocessNunjucks(sql) {
|
|
707
|
+
let processed = sql;
|
|
708
|
+
processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlString\s*\}\}/g, "'placeholder'");
|
|
709
|
+
processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlNumber\s*\}\}/g, '0');
|
|
710
|
+
processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlDate\s*\}\}/g, "'2000-01-01'");
|
|
711
|
+
processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlIn\s*\}\}/g, "('placeholder')");
|
|
712
|
+
processed = processed.replace(/\{\{\s*[\w.]+\s*\|\s*sqlIdentifier\s*\}\}/g, 'placeholder');
|
|
713
|
+
processed = processed.replace(/\{\{\s*[\w.]+\s*(?:\|[^}]*)?\}\}/g, "'placeholder'");
|
|
714
|
+
processed = processed.replace(/\{%[-\s]*if\s+[^%]*[-\s]*%\}/g, '');
|
|
715
|
+
processed = processed.replace(/\{%[-\s]*endif[-\s]*%\}/g, '');
|
|
716
|
+
processed = processed.replace(/\{%[-\s]*else[-\s]*%\}/g, '');
|
|
717
|
+
processed = processed.replace(/\{%[-\s]*elif\s+[^%]*[-\s]*%\}/g, '');
|
|
718
|
+
processed = processed.replace(/\{%[-\s]*for\s+[^%]*[-\s]*%\}/g, '');
|
|
719
|
+
processed = processed.replace(/\{%[-\s]*endfor[-\s]*%\}/g, '');
|
|
720
|
+
processed = processed.replace(/\{%[-\s]*set\s+[^%]*[-\s]*%\}/g, '');
|
|
721
|
+
processed = processed.replace(/\{#[^#]*#\}/g, '');
|
|
722
|
+
return processed;
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Injects OFFSET 0 ROWS after the last top-level ORDER BY clause to make it
|
|
726
|
+
* legal in a CTE without changing the result set. Uses the position-aware scanner
|
|
727
|
+
* to find the correct insertion point after the ORDER BY columns.
|
|
728
|
+
*/
|
|
729
|
+
injectOffset0Rows(sql) {
|
|
730
|
+
// Find the end of the last top-level ORDER BY clause.
|
|
731
|
+
// We append OFFSET 0 ROWS right at the end of the SQL.
|
|
732
|
+
const trimmed = sql.trimEnd();
|
|
733
|
+
// Remove trailing semicolon if present
|
|
734
|
+
const withoutSemicolon = trimmed.replace(/;\s*$/, '');
|
|
735
|
+
return `${withoutSemicolon} OFFSET 0 ROWS`;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Regex-based fallback for stripping trailing ORDER BY.
|
|
739
|
+
* Uses parenthesis depth counting to avoid stripping ORDER BY inside subqueries.
|
|
740
|
+
*/
|
|
741
|
+
stripOrderByViaRegex(sql) {
|
|
742
|
+
const orderByMatch = sql.match(/\bORDER\s+BY\s+[\s\S]+$/i);
|
|
743
|
+
if (!orderByMatch)
|
|
744
|
+
return sql;
|
|
745
|
+
const beforeOrderBy = sql.substring(0, orderByMatch.index);
|
|
746
|
+
let parenDepth = 0;
|
|
747
|
+
for (const ch of beforeOrderBy) {
|
|
748
|
+
if (ch === '(')
|
|
749
|
+
parenDepth++;
|
|
750
|
+
else if (ch === ')')
|
|
751
|
+
parenDepth--;
|
|
752
|
+
}
|
|
753
|
+
if (parenDepth !== 0)
|
|
754
|
+
return sql;
|
|
755
|
+
return sql.substring(0, orderByMatch.index).trimEnd();
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Strips SQL comments from the input string so that composition tokens
|
|
759
|
+
* inside comments are not treated as real references.
|
|
760
|
+
* Handles both single-line (-- ...) and multi-line block comments.
|
|
761
|
+
* Preserves string literals (single-quoted) to avoid stripping inside them.
|
|
762
|
+
*/
|
|
763
|
+
stripSQLComments(sql) {
|
|
764
|
+
let result = '';
|
|
765
|
+
let i = 0;
|
|
766
|
+
while (i < sql.length) {
|
|
767
|
+
// Single-quoted string literal — preserve as-is
|
|
768
|
+
if (sql[i] === "'") {
|
|
769
|
+
result += sql[i++];
|
|
770
|
+
while (i < sql.length) {
|
|
771
|
+
if (sql[i] === "'" && i + 1 < sql.length && sql[i + 1] === "'") {
|
|
772
|
+
// Escaped quote inside string
|
|
773
|
+
result += "''";
|
|
774
|
+
i += 2;
|
|
775
|
+
}
|
|
776
|
+
else if (sql[i] === "'") {
|
|
777
|
+
result += sql[i++];
|
|
778
|
+
break;
|
|
779
|
+
}
|
|
780
|
+
else {
|
|
781
|
+
result += sql[i++];
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
// Single-line comment: -- to end of line
|
|
786
|
+
else if (sql[i] === '-' && i + 1 < sql.length && sql[i + 1] === '-') {
|
|
787
|
+
// Skip to end of line
|
|
788
|
+
while (i < sql.length && sql[i] !== '\n') {
|
|
789
|
+
i++;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// Block comment: /* ... */
|
|
793
|
+
else if (sql[i] === '/' && i + 1 < sql.length && sql[i + 1] === '*') {
|
|
794
|
+
i += 2; // skip /*
|
|
795
|
+
while (i < sql.length) {
|
|
796
|
+
if (sql[i] === '*' && i + 1 < sql.length && sql[i + 1] === '/') {
|
|
797
|
+
i += 2; // skip */
|
|
798
|
+
break;
|
|
799
|
+
}
|
|
800
|
+
i++;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
// Normal character
|
|
804
|
+
else {
|
|
805
|
+
result += sql[i++];
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return result;
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Escapes {{ and }} inside SQL comments so that Nunjucks doesn't try to parse them.
|
|
812
|
+
* This is needed because dependency queries may carry comments containing
|
|
813
|
+
* {{query:"..."}} examples or documentation that would otherwise cause
|
|
814
|
+
* Nunjucks "expected variable end" errors.
|
|
815
|
+
*
|
|
816
|
+
* Only modifies content inside -- single-line and block comments.
|
|
817
|
+
* Leaves string literals and normal SQL untouched.
|
|
818
|
+
*/
|
|
819
|
+
escapeTemplateTokensInComments(sql) {
|
|
820
|
+
let result = '';
|
|
821
|
+
let i = 0;
|
|
822
|
+
while (i < sql.length) {
|
|
823
|
+
// Single-quoted string literal — preserve as-is
|
|
824
|
+
if (sql[i] === "'") {
|
|
825
|
+
result += sql[i++];
|
|
826
|
+
while (i < sql.length) {
|
|
827
|
+
if (sql[i] === "'" && i + 1 < sql.length && sql[i + 1] === "'") {
|
|
828
|
+
result += "''";
|
|
829
|
+
i += 2;
|
|
830
|
+
}
|
|
831
|
+
else if (sql[i] === "'") {
|
|
832
|
+
result += sql[i++];
|
|
833
|
+
break;
|
|
834
|
+
}
|
|
835
|
+
else {
|
|
836
|
+
result += sql[i++];
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
// Single-line comment: -- to end of line — escape {{ and }} inside
|
|
841
|
+
else if (sql[i] === '-' && i + 1 < sql.length && sql[i + 1] === '-') {
|
|
842
|
+
let comment = '';
|
|
843
|
+
while (i < sql.length && sql[i] !== '\n') {
|
|
844
|
+
comment += sql[i++];
|
|
845
|
+
}
|
|
846
|
+
result += comment.replace(/\{\{/g, '{ {').replace(/\}\}/g, '} }');
|
|
847
|
+
}
|
|
848
|
+
// Block comment: /* ... */ — escape {{ and }} inside
|
|
849
|
+
else if (sql[i] === '/' && i + 1 < sql.length && sql[i + 1] === '*') {
|
|
850
|
+
let comment = '/*';
|
|
851
|
+
i += 2;
|
|
852
|
+
while (i < sql.length) {
|
|
853
|
+
if (sql[i] === '*' && i + 1 < sql.length && sql[i + 1] === '/') {
|
|
854
|
+
comment += '*/';
|
|
855
|
+
i += 2;
|
|
856
|
+
break;
|
|
857
|
+
}
|
|
858
|
+
comment += sql[i++];
|
|
859
|
+
}
|
|
860
|
+
result += comment.replace(/\{\{/g, '{ {').replace(/\}\}/g, '} }');
|
|
861
|
+
}
|
|
862
|
+
// Normal character
|
|
863
|
+
else {
|
|
864
|
+
result += sql[i++];
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
return result;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
//# sourceMappingURL=queryCompositionEngine.js.map
|