@memberjunction/generic-database-provider 6.2.0-edge.5 → 6.2.0-edge.7
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/README.md +165 -1
- package/dist/GenericDatabaseProvider.d.ts +599 -69
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +2055 -403
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/SqlLogger.d.ts +26 -0
- package/dist/SqlLogger.d.ts.map +1 -1
- package/dist/SqlLogger.js +77 -20
- package/dist/SqlLogger.js.map +1 -1
- package/dist/clientClauseScreen.d.ts +44 -75
- package/dist/clientClauseScreen.d.ts.map +1 -1
- package/dist/clientClauseScreen.js +129 -267
- package/dist/clientClauseScreen.js.map +1 -1
- package/dist/composition/compositionAssembler.d.ts +33 -0
- package/dist/composition/compositionAssembler.d.ts.map +1 -0
- package/dist/composition/compositionAssembler.js +270 -0
- package/dist/composition/compositionAssembler.js.map +1 -0
- package/dist/composition/compositionInfo.d.ts +7 -0
- package/dist/composition/compositionInfo.d.ts.map +1 -0
- package/dist/composition/compositionInfo.js +31 -0
- package/dist/composition/compositionInfo.js.map +1 -0
- package/dist/composition/compositionLookup.d.ts +44 -0
- package/dist/composition/compositionLookup.d.ts.map +1 -0
- package/dist/composition/compositionLookup.js +122 -0
- package/dist/composition/compositionLookup.js.map +1 -0
- package/dist/composition/compositionRender.d.ts +136 -0
- package/dist/composition/compositionRender.d.ts.map +1 -0
- package/dist/composition/compositionRender.js +264 -0
- package/dist/composition/compositionRender.js.map +1 -0
- package/dist/composition/compositionTypes.d.ts +40 -0
- package/dist/composition/compositionTypes.d.ts.map +1 -0
- package/dist/composition/compositionTypes.js +2 -0
- package/dist/composition/compositionTypes.js.map +1 -0
- package/dist/composition/quotedTagRefusal.d.ts +44 -0
- package/dist/composition/quotedTagRefusal.d.ts.map +1 -0
- package/dist/composition/quotedTagRefusal.js +132 -0
- package/dist/composition/quotedTagRefusal.js.map +1 -0
- package/dist/composition/renderSteps.d.ts +16 -0
- package/dist/composition/renderSteps.d.ts.map +1 -0
- package/dist/composition/renderSteps.js +42 -0
- package/dist/composition/renderSteps.js.map +1 -0
- package/dist/composition/safetyGate.d.ts +46 -0
- package/dist/composition/safetyGate.d.ts.map +1 -0
- package/dist/composition/safetyGate.js +61 -0
- package/dist/composition/safetyGate.js.map +1 -0
- package/dist/composition/templateUnit.d.ts +95 -0
- package/dist/composition/templateUnit.d.ts.map +1 -0
- package/dist/composition/templateUnit.js +189 -0
- package/dist/composition/templateUnit.js.map +1 -0
- package/dist/describeStatement.d.ts +51 -0
- package/dist/describeStatement.d.ts.map +1 -0
- package/dist/describeStatement.js +19 -0
- package/dist/describeStatement.js.map +1 -0
- package/dist/fieldSecurity/projectionStars.d.ts +15 -0
- package/dist/fieldSecurity/projectionStars.d.ts.map +1 -0
- package/dist/fieldSecurity/projectionStars.js +116 -0
- package/dist/fieldSecurity/projectionStars.js.map +1 -0
- package/dist/fieldSecurity/queryColumnSecurity.d.ts +35 -0
- package/dist/fieldSecurity/queryColumnSecurity.d.ts.map +1 -0
- package/dist/fieldSecurity/queryColumnSecurity.js +84 -0
- package/dist/fieldSecurity/queryColumnSecurity.js.map +1 -0
- package/dist/index.d.ts +9 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/pagingLayout.d.ts +68 -0
- package/dist/pagingLayout.d.ts.map +1 -0
- package/dist/pagingLayout.js +190 -0
- package/dist/pagingLayout.js.map +1 -0
- package/dist/queryCompositionEngine.d.ts +22 -222
- package/dist/queryCompositionEngine.d.ts.map +1 -1
- package/dist/queryCompositionEngine.js +35 -729
- package/dist/queryCompositionEngine.js.map +1 -1
- package/dist/queryPagingEngine.d.ts +26 -5
- package/dist/queryPagingEngine.d.ts.map +1 -1
- package/dist/queryPagingEngine.js +51 -15
- package/dist/queryPagingEngine.js.map +1 -1
- package/dist/recordChangeSnapshot.d.ts +43 -0
- package/dist/recordChangeSnapshot.d.ts.map +1 -0
- package/dist/recordChangeSnapshot.js +85 -0
- package/dist/recordChangeSnapshot.js.map +1 -0
- package/dist/renderPipeline.d.ts +91 -72
- package/dist/renderPipeline.d.ts.map +1 -1
- package/dist/renderPipeline.js +71 -179
- package/dist/renderPipeline.js.map +1 -1
- package/dist/statementMemo.d.ts +29 -0
- package/dist/statementMemo.d.ts.map +1 -0
- package/dist/statementMemo.js +61 -0
- package/dist/statementMemo.js.map +1 -0
- package/dist/systemUserFieldAccess.d.ts +16 -1
- package/dist/systemUserFieldAccess.d.ts.map +1 -1
- package/dist/systemUserFieldAccess.js +39 -8
- package/dist/systemUserFieldAccess.js.map +1 -1
- package/dist/typedQueryParameter.d.ts +55 -0
- package/dist/typedQueryParameter.d.ts.map +1 -0
- package/dist/typedQueryParameter.js +122 -0
- package/dist/typedQueryParameter.js.map +1 -0
- package/dist/types.d.ts +47 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +14 -14
|
@@ -1,25 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { BuildQueryTemplateContext } from "@memberjunction/core";
|
|
2
2
|
import { GetDialect } from "@memberjunction/sql-dialect";
|
|
3
|
-
import { SQLParser,
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { SQLParser, LexSQL } from "@memberjunction/sql-parser";
|
|
4
|
+
import { DistinctQueryIDs, CTEInfoOf } from "./composition/compositionInfo.js";
|
|
5
|
+
import { AssembleComposition, NewCompositionRender, OuterRenderRequest } from "./composition/renderSteps.js";
|
|
6
6
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*/
|
|
10
|
-
const MAX_COMPOSITION_DEPTH = 10;
|
|
11
|
-
/**
|
|
12
|
-
* QueryCompositionEngine resolves {{query:"CategoryPath/QueryName(params)"}} tokens
|
|
13
|
-
* in query SQL into Common Table Expressions (CTEs). It handles:
|
|
7
|
+
* QueryCompositionEngine reads and resolves `{{query:"CategoryPath/QueryName(params)"}}`
|
|
8
|
+
* composition tokens.
|
|
14
9
|
*
|
|
15
|
-
* -
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* - Platform-aware SQL resolution via QueryInfo.GetPlatformSQL()
|
|
20
|
-
*
|
|
21
|
-
* This engine runs BEFORE Nunjucks template processing, so regular {{param}}
|
|
22
|
-
* tokens are preserved for later substitution.
|
|
10
|
+
* Composition itself is render-then-compose (see `RenderPipeline.Run`): each composed query is
|
|
11
|
+
* rendered with its own arguments and the plain SQL is assembled from the rendered parts. This
|
|
12
|
+
* class keeps the token-reading methods and {@link ResolveComposition}, which composes SQL whose
|
|
13
|
+
* compositions take static arguments only, without rendering the outer SQL.
|
|
23
14
|
*/
|
|
24
15
|
export class QueryCompositionEngine {
|
|
25
16
|
/**
|
|
@@ -46,13 +37,6 @@ export class QueryCompositionEngine {
|
|
|
46
37
|
: t.Text)
|
|
47
38
|
.join('');
|
|
48
39
|
}
|
|
49
|
-
/** Replaces the first occurrence of `token` that is real SQL, leaving comments and literals as written. */
|
|
50
|
-
replaceToken(sql, token, replacement, platform) {
|
|
51
|
-
const at = this.maskNonSQL(sql, platform).indexOf(token);
|
|
52
|
-
if (at === -1)
|
|
53
|
-
return sql;
|
|
54
|
-
return sql.substring(0, at) + replacement + sql.substring(at + token.length);
|
|
55
|
-
}
|
|
56
40
|
/**
|
|
57
41
|
* Parses all {{query:"..."}} tokens from SQL without resolving them.
|
|
58
42
|
* Useful for dependency extraction during the save pipeline.
|
|
@@ -88,719 +72,41 @@ export class QueryCompositionEngine {
|
|
|
88
72
|
});
|
|
89
73
|
}
|
|
90
74
|
/**
|
|
91
|
-
* Resolves
|
|
75
|
+
* Resolves the composition tokens of `sql` into CTEs without rendering `sql` itself: each
|
|
76
|
+
* composed query is rendered with the static arguments its token passes (its own compositions
|
|
77
|
+
* render as usual) and the result is assembled into one statement. The outer SQL's own template
|
|
78
|
+
* tags, if any, stay as written. References resolve by full category path and name only.
|
|
92
79
|
*
|
|
93
80
|
* @param sql - The SQL containing composition tokens
|
|
94
81
|
* @param platform - Target database platform for SQL resolution
|
|
95
82
|
* @param contextUser - User context for permission checks on referenced queries
|
|
96
|
-
* @param
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* Inline dependencies skip governance validation
|
|
100
|
-
*
|
|
101
|
-
* @
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
const
|
|
109
|
-
const
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
if (hasCompositions) {
|
|
113
|
-
finalSQL = this.assembleCTEs(cteEntries, resolvedSQL, platform);
|
|
114
|
-
}
|
|
115
|
-
// Comment-embedded {{ }} tokens (e.g. -- Example: {{query:"..."}}) are
|
|
116
|
-
// handled by the pipeline: RenderPipeline strips SQL comments before
|
|
117
|
-
// Nunjucks runs, so they never reach the template evaluator.
|
|
83
|
+
* @param _outerParams - Not used: the outer SQL is not rendered, so its compositions take
|
|
84
|
+
* static arguments only. Kept for the signature.
|
|
85
|
+
* @param inlineDependencies - Optional inline dependency specs for transient query testing,
|
|
86
|
+
* searched before the saved queries. Inline dependencies skip governance validation
|
|
87
|
+
* (Reusable, IsApproved, UserCanRun).
|
|
88
|
+
* @returns CompositionResult with the composed SQL and provenance metadata
|
|
89
|
+
* @throws Error if a referenced query is not found, not composable, creates a cycle, or a
|
|
90
|
+
* composition of `sql` passes a value of the outer query (pass-through)
|
|
91
|
+
*/
|
|
92
|
+
ResolveComposition(sql, platform, contextUser, _outerParams, inlineDependencies) {
|
|
93
|
+
const dialect = this.getDialect(platform);
|
|
94
|
+
const ctx = { Platform: platform, ContextUser: contextUser, Dependencies: inlineDependencies };
|
|
95
|
+
const render = NewCompositionRender(ctx, dialect, BuildQueryTemplateContext({ User: contextUser }), true);
|
|
96
|
+
const outer = render.RenderOuter(OuterRenderRequest(sql, ctx));
|
|
97
|
+
const assembled = AssembleComposition(outer.SQL, render.Instances, dialect);
|
|
98
|
+
const hasCompositions = render.Instances.length > 0;
|
|
118
99
|
return {
|
|
119
|
-
ResolvedSQL:
|
|
120
|
-
CTEs:
|
|
121
|
-
DependencyGraph:
|
|
100
|
+
ResolvedSQL: hasCompositions ? assembled.SQL : sql,
|
|
101
|
+
CTEs: render.Instances.map(CTEInfoOf),
|
|
102
|
+
DependencyGraph: new Map(hasCompositions ? [['__current__', DistinctQueryIDs(render.Instances)]] : []),
|
|
122
103
|
HasCompositions: hasCompositions,
|
|
123
|
-
AnyDependencyUsesTemplates:
|
|
104
|
+
AnyDependencyUsesTemplates: render.Instances.some(i => i.Resolved.Query.UsesTemplate === true),
|
|
124
105
|
};
|
|
125
106
|
}
|
|
126
|
-
/**
|
|
127
|
-
* Recursively resolves composition tokens in SQL, building up CTE entries.
|
|
128
|
-
*/
|
|
129
|
-
resolveTokensRecursive(sql, platform, contextUser, outerParams, cteEntries, dependencyGraph, inProgressSet, templateFlag, depth, inlineDependencies) {
|
|
130
|
-
if (depth > MAX_COMPOSITION_DEPTH) {
|
|
131
|
-
throw new Error(`Query composition depth exceeds maximum of ${MAX_COMPOSITION_DEPTH}. ` +
|
|
132
|
-
`This likely indicates an overly deep nesting chain.`);
|
|
133
|
-
}
|
|
134
|
-
const tokens = this.ParseCompositionTokens(sql, platform);
|
|
135
|
-
if (tokens.length === 0)
|
|
136
|
-
return sql;
|
|
137
|
-
let resolvedSQL = sql;
|
|
138
|
-
for (const token of tokens) {
|
|
139
|
-
const lookupResult = this.lookupQueryWithInline(token, inlineDependencies);
|
|
140
|
-
const referencedQuery = lookupResult.Query;
|
|
141
|
-
// Only validate governance (Reusable, IsApproved, permissions) for metadata-backed queries.
|
|
142
|
-
// Inline dependencies are inherently authorized by the caller.
|
|
143
|
-
if (!lookupResult.IsInline) {
|
|
144
|
-
this.validateQueryComposable(referencedQuery, token, contextUser);
|
|
145
|
-
}
|
|
146
|
-
// Depth-first transitive UsesTemplate check — short-circuit once true
|
|
147
|
-
if (!templateFlag.value && referencedQuery.UsesTemplate) {
|
|
148
|
-
templateFlag.value = true;
|
|
149
|
-
}
|
|
150
|
-
// Cycle detection
|
|
151
|
-
if (inProgressSet.has(referencedQuery.ID)) {
|
|
152
|
-
const cyclePath = [...inProgressSet, referencedQuery.ID].join(' → ');
|
|
153
|
-
throw new Error(`Circular query dependency detected: ${cyclePath}. ` +
|
|
154
|
-
`Query "${referencedQuery.Name}" is already being resolved.`);
|
|
155
|
-
}
|
|
156
|
-
// Resolve parameter values
|
|
157
|
-
const resolvedParams = this.resolveParameters(token.Parameters, outerParams);
|
|
158
|
-
// Build deduplication key
|
|
159
|
-
const dedupeKey = this.buildDeduplicationKey(referencedQuery.ID, resolvedParams);
|
|
160
|
-
// Check if we already have this exact CTE
|
|
161
|
-
const existingCTE = cteEntries.find(e => e.DeduplicationKey === dedupeKey);
|
|
162
|
-
if (existingCTE) {
|
|
163
|
-
resolvedSQL = this.replaceToken(resolvedSQL, token.FullToken, existingCTE.CTEName, platform);
|
|
164
|
-
continue;
|
|
165
|
-
}
|
|
166
|
-
// Get platform-specific SQL for the referenced query.
|
|
167
|
-
// Strip SQL comments immediately — they serve no runtime purpose and
|
|
168
|
-
// can contain {{ }} patterns that confuse substituteStaticParams,
|
|
169
|
-
// Nunjucks, or ORDER BY detection. The pipeline also strips comments
|
|
170
|
-
// from the outer query before Nunjucks, but dep SQL enters here
|
|
171
|
-
// before it reaches the pipeline's comment-stripping step.
|
|
172
|
-
const refSQL = this.stripSQLComments(referencedQuery.GetPlatformSQL(platform));
|
|
173
|
-
// Substitute static parameter values directly into the referenced query's SQL
|
|
174
|
-
const paramSubstitutedSQL = this.substituteStaticParams(refSQL, resolvedParams);
|
|
175
|
-
// Track in-progress for cycle detection
|
|
176
|
-
inProgressSet.add(referencedQuery.ID);
|
|
177
|
-
// For inline deps, pass their nested dependencies into the recursive call.
|
|
178
|
-
// For metadata deps, pass the parent's inline deps so sibling references work.
|
|
179
|
-
const nestedInlineDeps = lookupResult.IsInline
|
|
180
|
-
? lookupResult.NestedDependencies
|
|
181
|
-
: inlineDependencies;
|
|
182
|
-
// Recursively resolve any nested composition tokens in the referenced query
|
|
183
|
-
const nestedResolvedSQL = this.resolveTokensRecursive(paramSubstitutedSQL, platform, contextUser, resolvedParams, cteEntries, dependencyGraph, inProgressSet, templateFlag, depth + 1, nestedInlineDeps);
|
|
184
|
-
inProgressSet.delete(referencedQuery.ID);
|
|
185
|
-
// Track dependency
|
|
186
|
-
const parentDeps = dependencyGraph.get('__current__') || [];
|
|
187
|
-
if (!parentDeps.some(id => UUIDsEqual(id, referencedQuery.ID))) {
|
|
188
|
-
parentDeps.push(referencedQuery.ID);
|
|
189
|
-
dependencyGraph.set('__current__', parentDeps);
|
|
190
|
-
}
|
|
191
|
-
// Generate CTE name (platform-aware: brackets for SQL Server, double quotes for PG)
|
|
192
|
-
const cteName = this.generateCTEName(referencedQuery, resolvedParams, platform);
|
|
193
|
-
const cteEntry = {
|
|
194
|
-
DeduplicationKey: dedupeKey,
|
|
195
|
-
CTEName: cteName,
|
|
196
|
-
SQL: nestedResolvedSQL,
|
|
197
|
-
Info: {
|
|
198
|
-
QueryID: referencedQuery.ID,
|
|
199
|
-
QueryName: referencedQuery.Name,
|
|
200
|
-
CategoryPath: token.FullPath,
|
|
201
|
-
CTEName: cteName,
|
|
202
|
-
OriginalSQL: refSQL,
|
|
203
|
-
ResolvedSQL: nestedResolvedSQL,
|
|
204
|
-
Parameters: resolvedParams
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
cteEntries.push(cteEntry);
|
|
208
|
-
resolvedSQL = this.replaceToken(resolvedSQL, token.FullToken, cteName, platform);
|
|
209
|
-
}
|
|
210
|
-
return resolvedSQL;
|
|
211
|
-
}
|
|
212
|
-
// parseTokenContent and splitParams removed — composition token parsing
|
|
213
|
-
// is now handled by MJLexer via SQLParser.ExtractCompositionRefs()
|
|
214
|
-
/**
|
|
215
|
-
* Looks up a query by category path + name, checking inline dependencies first,
|
|
216
|
-
* then falling back to the metadata provider.
|
|
217
|
-
*
|
|
218
|
-
* For inline dependencies, creates a synthetic QueryInfo with the SQL and flags set
|
|
219
|
-
* appropriately. Inline queries skip governance validation (Reusable, IsApproved, etc.)
|
|
220
|
-
* since they are inherently authorized by the caller.
|
|
221
|
-
*/
|
|
222
|
-
lookupQueryWithInline(token, inlineDependencies) {
|
|
223
|
-
// Check inline dependencies first
|
|
224
|
-
if (inlineDependencies && inlineDependencies.length > 0) {
|
|
225
|
-
const inlineMatch = this.findInlineDependency(token, inlineDependencies);
|
|
226
|
-
if (inlineMatch) {
|
|
227
|
-
const syntheticQuery = this.buildSyntheticQuery(inlineMatch);
|
|
228
|
-
return {
|
|
229
|
-
Query: syntheticQuery,
|
|
230
|
-
IsInline: true,
|
|
231
|
-
NestedDependencies: inlineMatch.Dependencies,
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
// Fall back to metadata provider
|
|
236
|
-
return {
|
|
237
|
-
Query: this.lookupQueryFromMetadata(token),
|
|
238
|
-
IsInline: false,
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
/**
|
|
242
|
-
* Finds a matching inline dependency spec for the given token.
|
|
243
|
-
*/
|
|
244
|
-
findInlineDependency(token, inlineDependencies) {
|
|
245
|
-
const queryName = token.QueryName.toLowerCase();
|
|
246
|
-
// Try category path + name match first
|
|
247
|
-
if (token.CategorySegments.length > 0) {
|
|
248
|
-
const expectedPath = `/${token.CategorySegments.join('/')}/`;
|
|
249
|
-
const match = inlineDependencies.find(d => d.Name.toLowerCase() === queryName &&
|
|
250
|
-
d.CategoryPath.toLowerCase() === expectedPath.toLowerCase());
|
|
251
|
-
if (match)
|
|
252
|
-
return match;
|
|
253
|
-
}
|
|
254
|
-
// Fall back to name-only match
|
|
255
|
-
return inlineDependencies.find(d => d.Name.toLowerCase() === queryName);
|
|
256
|
-
}
|
|
257
|
-
/**
|
|
258
|
-
* Builds a synthetic IComposableQuery from an inline dependency spec.
|
|
259
|
-
* Returns a plain object (not a BaseEntity) since we cannot construct
|
|
260
|
-
* MJQueryEntityExtended directly. Inline queries skip governance
|
|
261
|
-
* validation, so only the fields needed for composition resolution
|
|
262
|
-
* (ID, Name, SQL, UsesTemplate, GetPlatformSQL) are meaningful.
|
|
263
|
-
*/
|
|
264
|
-
buildSyntheticQuery(dep) {
|
|
265
|
-
const sql = dep.SQL;
|
|
266
|
-
return {
|
|
267
|
-
// Use a deterministic synthetic ID based on name+path to support cycle detection and deduplication
|
|
268
|
-
ID: `__inline__${dep.CategoryPath}${dep.Name}`.toLowerCase(),
|
|
269
|
-
Name: dep.Name,
|
|
270
|
-
SQL: sql,
|
|
271
|
-
UsesTemplate: dep.UsesTemplate ?? false,
|
|
272
|
-
Reusable: true,
|
|
273
|
-
Status: 'Approved',
|
|
274
|
-
get IsApproved() { return true; },
|
|
275
|
-
UserCanRun() { return { canRun: true, deniedEntities: [] }; },
|
|
276
|
-
GetPlatformSQL() { return sql; },
|
|
277
|
-
};
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Looks up a query by category path + name from QueryEngine.
|
|
281
|
-
*/
|
|
282
|
-
lookupQueryFromMetadata(token) {
|
|
283
|
-
const allQueries = QueryEngine.Instance.Queries;
|
|
284
|
-
const queryName = token.QueryName.toLowerCase();
|
|
285
|
-
// If category segments provided, build expected category path.
|
|
286
|
-
// MJQueryEntityExtended.CategoryPath uses slash-separated segments
|
|
287
|
-
// without leading/trailing slashes (e.g. "Sales/Reports").
|
|
288
|
-
if (token.CategorySegments.length > 0) {
|
|
289
|
-
const expectedPath = token.CategorySegments.join('/');
|
|
290
|
-
const match = allQueries.find(q => q.Name.toLowerCase() === queryName &&
|
|
291
|
-
q.CategoryPath.toLowerCase() === expectedPath.toLowerCase());
|
|
292
|
-
if (match)
|
|
293
|
-
return match;
|
|
294
|
-
}
|
|
295
|
-
// Fall back to name-only match
|
|
296
|
-
const matches = allQueries.filter(q => q.Name.toLowerCase() === queryName);
|
|
297
|
-
if (matches.length === 0) {
|
|
298
|
-
throw new Error(`Referenced query not found: "${token.FullPath}". ` +
|
|
299
|
-
`Ensure the query exists and the category path is correct.`);
|
|
300
|
-
}
|
|
301
|
-
if (matches.length > 1) {
|
|
302
|
-
throw new Error(`Ambiguous query reference: "${token.FullPath}" matches ${matches.length} queries. ` +
|
|
303
|
-
`Use the full category path to disambiguate.`);
|
|
304
|
-
}
|
|
305
|
-
return matches[0];
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Validates that a referenced query is eligible for composition.
|
|
309
|
-
*/
|
|
310
|
-
validateQueryComposable(query, token, contextUser) {
|
|
311
|
-
if (!query.Reusable) {
|
|
312
|
-
throw new Error(`Query "${token.FullPath}" (${query.Name}) is not marked as Reusable. ` +
|
|
313
|
-
`Set Reusable=true on the query to allow composition.`);
|
|
314
|
-
}
|
|
315
|
-
if (!query.IsApproved) {
|
|
316
|
-
throw new Error(`Query "${token.FullPath}" (${query.Name}) is not Approved (status: ${query.Status}). ` +
|
|
317
|
-
`Only Approved queries can be composed.`);
|
|
318
|
-
}
|
|
319
|
-
const runResult = query.UserCanRun(contextUser);
|
|
320
|
-
if (!runResult.canRun) {
|
|
321
|
-
const deniedMsg = runResult.deniedEntities.length > 0
|
|
322
|
-
? ` Denied entities: ${runResult.deniedEntities.join(', ')}.`
|
|
323
|
-
: '';
|
|
324
|
-
throw new Error(`User does not have permission to run referenced query "${token.FullPath}" (${query.Name}).${deniedMsg}`);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Resolves parameter values for a composition reference.
|
|
329
|
-
* Static values are used directly; pass-through values are looked up from outer params.
|
|
330
|
-
*/
|
|
331
|
-
resolveParameters(params, outerParams) {
|
|
332
|
-
const resolved = {};
|
|
333
|
-
for (const param of params) {
|
|
334
|
-
if (param.StaticValue !== null) {
|
|
335
|
-
resolved[param.Name] = param.StaticValue;
|
|
336
|
-
}
|
|
337
|
-
else if (param.PassThroughName !== null) {
|
|
338
|
-
// Pass-through: the value comes from the outer query's parameters
|
|
339
|
-
// At composition time, we create a Nunjucks placeholder so that
|
|
340
|
-
// the downstream Nunjucks processor can substitute the actual value
|
|
341
|
-
resolved[param.Name] = `{{${param.PassThroughName}}}`;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
return resolved;
|
|
345
|
-
}
|
|
346
|
-
/**
|
|
347
|
-
* Substitutes resolved parameter values into a query's SQL.
|
|
348
|
-
* - Static values: replaces {{paramName}} with 'value'
|
|
349
|
-
* - Pass-through values: renames {{paramName}} to {{outerParamName}} so
|
|
350
|
-
* the downstream Nunjucks processor can resolve it from the outer query's parameters.
|
|
351
|
-
*/
|
|
352
|
-
/**
|
|
353
|
-
* Substitutes resolved parameter values into a query's SQL using the SQLParser's
|
|
354
|
-
* MJLexer-based template manipulation methods.
|
|
355
|
-
*
|
|
356
|
-
* - Pass-through values: renames the inner variable to the outer variable name,
|
|
357
|
-
* preserving any Nunjucks filter chain (e.g., `{{ lookbackDays | sqlNumber }}` → `{{ numDays | sqlNumber }}`)
|
|
358
|
-
* - Static values: replaces the entire template expression (including filters) with a literal value
|
|
359
|
-
*/
|
|
360
|
-
substituteStaticParams(sql, params) {
|
|
361
|
-
let result = sql;
|
|
362
|
-
for (const [name, value] of Object.entries(params)) {
|
|
363
|
-
if (value.startsWith('{{') && value.endsWith('}}')) {
|
|
364
|
-
// Pass-through: rename the inner variable, preserving filter chain
|
|
365
|
-
const outerVarName = value.slice(2, -2).trim();
|
|
366
|
-
result = SQLParser.RenameTemplateVariable(result, name, outerVarName);
|
|
367
|
-
}
|
|
368
|
-
else {
|
|
369
|
-
// Static value: replace entire template expression with a SQL literal, and reads of
|
|
370
|
-
// the variable in template tags with the same value as a template literal
|
|
371
|
-
const isNumeric = /^-?\d+(\.\d+)?$/.test(value);
|
|
372
|
-
const literal = isNumeric ? value : `'${value.replace(/'/g, "''")}'`;
|
|
373
|
-
const tagLiteral = isNumeric ? value : JSON.stringify(value);
|
|
374
|
-
result = SQLParser.SubstituteTemplateVariable(result, name, literal, tagLiteral);
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
return result;
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Builds a deduplication key for a CTE based on query ID and sorted parameter values.
|
|
381
|
-
*/
|
|
382
|
-
buildDeduplicationKey(queryID, params) {
|
|
383
|
-
const sortedParams = Object.entries(params)
|
|
384
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
385
|
-
.map(([k, v]) => `${k}=${v}`)
|
|
386
|
-
.join('&');
|
|
387
|
-
return `${queryID}|${sortedParams}`;
|
|
388
|
-
}
|
|
389
|
-
/**
|
|
390
|
-
* Generates a SQL-safe CTE name from the query name + short hash for uniqueness.
|
|
391
|
-
*/
|
|
392
|
-
generateCTEName(query, params, platform) {
|
|
393
|
-
// Sanitize query name: remove non-alphanumeric chars, replace spaces with underscores
|
|
394
|
-
const sanitized = query.Name
|
|
395
|
-
.replace(/[^a-zA-Z0-9_ ]/g, '')
|
|
396
|
-
.replace(/\s+/g, '_')
|
|
397
|
-
.substring(0, 50);
|
|
398
|
-
// Create a short hash suffix from query ID + params for uniqueness
|
|
399
|
-
const hashInput = query.ID + JSON.stringify(params);
|
|
400
|
-
const hash = this.simpleHash(hashInput);
|
|
401
|
-
const identifier = `__cte_${sanitized}_${hash}`;
|
|
402
|
-
return this.getDialect(platform).QuoteIdentifier(identifier);
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* Resolves a DatabasePlatform string to the corresponding SQLDialect instance.
|
|
406
|
-
*/
|
|
107
|
+
/** The dialect of a platform. */
|
|
407
108
|
getDialect(platform) {
|
|
408
109
|
return GetDialect(platform);
|
|
409
110
|
}
|
|
410
|
-
/**
|
|
411
|
-
* Simple string hash for generating short, deterministic suffixes.
|
|
412
|
-
*/
|
|
413
|
-
simpleHash(input) {
|
|
414
|
-
let hash = 0;
|
|
415
|
-
for (let i = 0; i < input.length; i++) {
|
|
416
|
-
const char = input.charCodeAt(i);
|
|
417
|
-
hash = ((hash << 5) - hash) + char;
|
|
418
|
-
hash = hash & hash; // Convert to 32bit integer
|
|
419
|
-
}
|
|
420
|
-
return Math.abs(hash).toString(36).substring(0, 6);
|
|
421
|
-
}
|
|
422
|
-
/**
|
|
423
|
-
* Assembles CTE entries into a WITH clause prepended to the main SQL.
|
|
424
|
-
*
|
|
425
|
-
* Handles the case where a dependency query's SQL itself contains a WITH clause
|
|
426
|
-
* (inner CTEs). SQL does not allow nested WITH clauses, so inner CTEs are "hoisted"
|
|
427
|
-
* out as sibling CTE definitions preceding the dependency's own CTE.
|
|
428
|
-
*
|
|
429
|
-
* Cross-dep CTE name collisions: when two different dependencies each declare
|
|
430
|
-
* an inner CTE with the same name (e.g. both declare `PoolNameBridge`), the
|
|
431
|
-
* naive concatenation produces a duplicate CTE error from SQL Server. We
|
|
432
|
-
* track allocated names across the entire WITH and rename colliding inner
|
|
433
|
-
* CTEs (and rewrite intra-dep references to the renamed CTE) so the assembled
|
|
434
|
-
* SQL is valid. See Skip-Brain Bug C in
|
|
435
|
-
* `__tests__/skip-failure-regressions.test.ts` and `SKIP-QUERY-RENDERING-BUGS.md`.
|
|
436
|
-
*/
|
|
437
|
-
assembleCTEs(cteEntries, mainSQL, platform) {
|
|
438
|
-
if (cteEntries.length === 0)
|
|
439
|
-
return mainSQL;
|
|
440
|
-
const dialect = this.getDialect(platform);
|
|
441
|
-
const outer = SplitLeadingCTEs(mainSQL, dialect);
|
|
442
|
-
// SymbolTable guarantees CTE name uniqueness at registration time.
|
|
443
|
-
const symTable = new SymbolTable(dialect);
|
|
444
|
-
// Seed the symbol table with every name the assembled WITH clause already holds, the
|
|
445
|
-
// dependency CTEs and the outer query's own, so a dependency's inner CTE that shares one
|
|
446
|
-
// of them is renamed instead of declared twice.
|
|
447
|
-
for (const entry of cteEntries) {
|
|
448
|
-
symTable.Seed(this.canonicalCTEName(entry.CTEName));
|
|
449
|
-
}
|
|
450
|
-
for (const definition of outer?.Definitions ?? []) {
|
|
451
|
-
symTable.Seed(this.canonicalCTEName(definition.Name));
|
|
452
|
-
}
|
|
453
|
-
let recursive = outer?.Recursive ?? false;
|
|
454
|
-
const cteDefinitions = [];
|
|
455
|
-
const queryHints = [];
|
|
456
|
-
for (const entry of cteEntries) {
|
|
457
|
-
const { Body: statement, Hints } = this.splitQueryHints(this.withoutStatementSemicolons(entry.SQL, dialect), dialect);
|
|
458
|
-
queryHints.push(...Hints);
|
|
459
|
-
const strippedSQL = this.stripTrailingOrderBy(statement, dialect);
|
|
460
|
-
const commentStrippedSQL = this.stripSQLComments(strippedSQL).trimStart();
|
|
461
|
-
if (/^WITH\s/i.test(commentStrippedSQL)) {
|
|
462
|
-
const { innerCTEDefinitions, mainSelect, isRecursive } = this.hoistInnerCTEs(commentStrippedSQL, dialect);
|
|
463
|
-
recursive = recursive || isRecursive;
|
|
464
|
-
// Use SymbolTable for deconfliction instead of raw Set
|
|
465
|
-
const { definitions, rewrittenMainSelect } = this.deconflictInnerCTEsViaSymbolTable(innerCTEDefinitions, mainSelect, symTable);
|
|
466
|
-
cteDefinitions.push(...definitions);
|
|
467
|
-
cteDefinitions.push(`${entry.CTEName} AS (\n${rewrittenMainSelect}\n)`);
|
|
468
|
-
}
|
|
469
|
-
else {
|
|
470
|
-
cteDefinitions.push(`${entry.CTEName} AS (\n${strippedSQL}\n)`);
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
if (!dialect.AllowsOrderByInCTE) {
|
|
474
|
-
this.validateCTEBodies(cteDefinitions, cteEntries, dialect);
|
|
475
|
-
}
|
|
476
|
-
// One WITH clause: the composed CTEs first, then the outer query's own. When any CTE in it
|
|
477
|
-
// refers to itself, the clause opens with the dialect's recursive form (`WITH RECURSIVE`
|
|
478
|
-
// on PostgreSQL; plain `WITH` on SQL Server, which has no keyword).
|
|
479
|
-
const withKeyword = recursive ? dialect.RecursiveCTESyntax() : 'WITH';
|
|
480
|
-
const composed = outer
|
|
481
|
-
? `${withKeyword} ${[...cteDefinitions, ...outer.Definitions.map(d => d.Text)].join(',\n')}\n${outer.Main}`
|
|
482
|
-
: `${withKeyword} ${cteDefinitions.join(',\n')}\n${mainSQL}`;
|
|
483
|
-
return this.appendQueryHints(composed, queryHints, dialect);
|
|
484
|
-
}
|
|
485
|
-
/**
|
|
486
|
-
* Takes a statement's trailing query-hint clause off ({@link SQLDialect.QueryHintKeyword},
|
|
487
|
-
* `OPTION (…)` on SQL Server), returning the hints in it. A CTE body cannot carry query hints;
|
|
488
|
-
* they belong to the statement the dependency is composed into. A dialect without a hint
|
|
489
|
-
* clause leaves the statement as it is.
|
|
490
|
-
*/
|
|
491
|
-
splitQueryHints(statement, dialect) {
|
|
492
|
-
const list = this.findOptionList(statement, dialect);
|
|
493
|
-
if (!list)
|
|
494
|
-
return { Body: statement, Hints: [] };
|
|
495
|
-
return { Body: statement.substring(0, list.OptionStart).trimEnd(), Hints: list.Hints };
|
|
496
|
-
}
|
|
497
|
-
/**
|
|
498
|
-
* Adds query hints to a statement: into its own hint clause when it has one, otherwise as a
|
|
499
|
-
* new clause (`OPTION (…)` on SQL Server) after its last token, ahead of any trailing
|
|
500
|
-
* semicolon or comment. A hint already present, compared ignoring case and spacing, is not
|
|
501
|
-
* added twice. Hints only come from a dialect with a hint clause, so one is always named.
|
|
502
|
-
*/
|
|
503
|
-
appendQueryHints(sql, hints, dialect) {
|
|
504
|
-
const keyword = dialect.QueryHintKeyword;
|
|
505
|
-
if (hints.length === 0 || keyword === null)
|
|
506
|
-
return sql;
|
|
507
|
-
const list = this.findOptionList(sql, dialect);
|
|
508
|
-
const merged = this.distinctHints([...(list?.Hints ?? []), ...hints]).join(', ');
|
|
509
|
-
if (list) {
|
|
510
|
-
return sql.substring(0, list.ListStart) + merged + sql.substring(list.ListEnd);
|
|
511
|
-
}
|
|
512
|
-
const tokens = SignificantTokens(LexSQL(sql, dialect));
|
|
513
|
-
let last = tokens.length - 1;
|
|
514
|
-
while (last > 0 && tokens[last].Kind === 'semicolon')
|
|
515
|
-
last--;
|
|
516
|
-
const at = tokens[last].End;
|
|
517
|
-
return `${sql.substring(0, at)} ${keyword} (${merged})${sql.substring(at)}`;
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Finds a statement's top-level trailing query-hint clause (`OPTION (…)` on SQL Server): where
|
|
521
|
-
* the keyword starts, where the list inside the parentheses starts and ends, and the hints in
|
|
522
|
-
* it split at top-level commas. `null` when the dialect has no hint clause or there is none.
|
|
523
|
-
*/
|
|
524
|
-
findOptionList(sql, dialect) {
|
|
525
|
-
const keyword = dialect.QueryHintKeyword;
|
|
526
|
-
if (keyword === null)
|
|
527
|
-
return null;
|
|
528
|
-
const shape = AnalyzePagingShape(sql, dialect);
|
|
529
|
-
const tokens = SignificantTokens(LexSQL(sql, dialect)).filter(t => t.Start >= shape.TailStart);
|
|
530
|
-
if (!IsKeyword(tokens[0], keyword.toUpperCase()) || tokens[1]?.Kind !== 'open')
|
|
531
|
-
return null;
|
|
532
|
-
const depth = tokens[1].Depth;
|
|
533
|
-
const close = tokens.findIndex((t, i) => i > 1 && t.Kind === 'close' && t.Depth === depth);
|
|
534
|
-
if (close === -1)
|
|
535
|
-
return null;
|
|
536
|
-
const hints = [];
|
|
537
|
-
let hintStart = 2;
|
|
538
|
-
for (let i = 2; i <= close; i++) {
|
|
539
|
-
const endsHint = i === close || (tokens[i].Kind === 'comma' && tokens[i].Depth === depth + 1);
|
|
540
|
-
if (!endsHint)
|
|
541
|
-
continue;
|
|
542
|
-
if (i > hintStart)
|
|
543
|
-
hints.push(sql.substring(tokens[hintStart].Start, tokens[i - 1].End));
|
|
544
|
-
hintStart = i + 1;
|
|
545
|
-
}
|
|
546
|
-
return { OptionStart: tokens[0].Start, ListStart: tokens[1].End, ListEnd: tokens[close].Start, Hints: hints };
|
|
547
|
-
}
|
|
548
|
-
/** Hints with repeats removed, comparing case- and spacing-insensitively; first spelling kept. */
|
|
549
|
-
distinctHints(hints) {
|
|
550
|
-
const seen = new Set();
|
|
551
|
-
return hints.filter(h => {
|
|
552
|
-
const key = h.replace(/\s+/g, ' ').toUpperCase();
|
|
553
|
-
if (seen.has(key))
|
|
554
|
-
return false;
|
|
555
|
-
seen.add(key);
|
|
556
|
-
return true;
|
|
557
|
-
});
|
|
558
|
-
}
|
|
559
|
-
/**
|
|
560
|
-
* A dependency's statement without the semicolons before or after it (`;WITH …`, `… ;`),
|
|
561
|
-
* which a CTE body cannot hold.
|
|
562
|
-
*/
|
|
563
|
-
withoutStatementSemicolons(sql, dialect) {
|
|
564
|
-
const tokens = SignificantTokens(LexSQL(sql, dialect));
|
|
565
|
-
const first = tokens.findIndex(t => t.Kind !== 'semicolon');
|
|
566
|
-
if (first === -1)
|
|
567
|
-
return sql;
|
|
568
|
-
let last = tokens.length - 1;
|
|
569
|
-
while (tokens[last].Kind === 'semicolon')
|
|
570
|
-
last--;
|
|
571
|
-
return sql.substring(tokens[first].Start, tokens[last].End);
|
|
572
|
-
}
|
|
573
|
-
/**
|
|
574
|
-
* Validates that no CTE body still contains an illegal top-level ORDER BY
|
|
575
|
-
* after stripping. Throws a diagnostic error with the dep name, category
|
|
576
|
-
* path, and specific reason — replacing the cryptic SQL Server error
|
|
577
|
-
* "The ORDER BY clause is invalid in views, inline functions...".
|
|
578
|
-
*/
|
|
579
|
-
validateCTEBodies(cteDefinitions, cteEntries, dialect) {
|
|
580
|
-
for (const def of cteDefinitions) {
|
|
581
|
-
// Extract the CTE body between the first "(" and the last ")"
|
|
582
|
-
const bodyMatch = def.match(/^([^\s]+)\s+AS\s*\(\n?([\s\S]*?)\n?\)$/i);
|
|
583
|
-
if (!bodyMatch)
|
|
584
|
-
continue;
|
|
585
|
-
const cteName = bodyMatch[1];
|
|
586
|
-
const body = bodyMatch[2];
|
|
587
|
-
const analysis = AnalyzeTopLevelOrderBy(body, dialect);
|
|
588
|
-
if (analysis.Positions.length > 0 && !analysis.IsLegalInCTE) {
|
|
589
|
-
const entry = cteEntries.find(e => e.CTEName === cteName);
|
|
590
|
-
const depName = entry?.Info.QueryName ?? cteName;
|
|
591
|
-
const categoryPath = entry?.Info.CategoryPath ?? '';
|
|
592
|
-
const position = analysis.Positions[analysis.Positions.length - 1];
|
|
593
|
-
throw new Error(`Composition error: dependency '${depName}'` +
|
|
594
|
-
(categoryPath ? ` (${categoryPath})` : '') +
|
|
595
|
-
` has a trailing ORDER BY at position ${position} that could not be stripped. ` +
|
|
596
|
-
`SQL Server does not allow ORDER BY in CTEs without TOP, OFFSET, or FOR XML. ` +
|
|
597
|
-
`Either remove the ORDER BY from the dependency, or add TOP/OFFSET.`);
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
/**
|
|
602
|
-
* Strips the surrounding bracket / quote characters from a CTE name so we
|
|
603
|
-
* can compare names case-insensitively across quoting styles. `[Foo]`,
|
|
604
|
-
* `"Foo"`, and bare `Foo` all canonicalize to `Foo`.
|
|
605
|
-
*/
|
|
606
|
-
canonicalCTEName(rawName) {
|
|
607
|
-
return rawName.replace(/^[\["]|[\]"]$/g, '');
|
|
608
|
-
}
|
|
609
|
-
/**
|
|
610
|
-
* Deconflicts inner CTE names using a SymbolTable for name allocation.
|
|
611
|
-
* The SymbolTable guarantees uniqueness at registration time — name
|
|
612
|
-
* collisions become impossible by construction.
|
|
613
|
-
*
|
|
614
|
-
* Reference rewriting uses word-boundary regex over raw SQL. It does
|
|
615
|
-
* NOT skip string literals or comments — inner-CTE names are unlikely
|
|
616
|
-
* to appear as quoted text or column aliases in practice.
|
|
617
|
-
*/
|
|
618
|
-
deconflictInnerCTEsViaSymbolTable(innerCTEDefinitions, mainSelect, symTable) {
|
|
619
|
-
const renames = new Map();
|
|
620
|
-
const finalDefinitionHeaders = [];
|
|
621
|
-
for (const def of innerCTEDefinitions) {
|
|
622
|
-
const headerMatch = def.match(/^(\[[^\]]+\]|"[^"]+"|[A-Za-z_]\w*)(\s+AS\s*\()/i);
|
|
623
|
-
if (!headerMatch) {
|
|
624
|
-
finalDefinitionHeaders.push({ original: def, rewritten: def });
|
|
625
|
-
continue;
|
|
626
|
-
}
|
|
627
|
-
const rawName = headerMatch[1];
|
|
628
|
-
const canonical = this.canonicalCTEName(rawName);
|
|
629
|
-
// SymbolTable.Register handles collision detection + suffix generation
|
|
630
|
-
const actual = symTable.Register(canonical);
|
|
631
|
-
if (actual !== canonical) {
|
|
632
|
-
renames.set(canonical, actual);
|
|
633
|
-
const rewrittenDef = actual + headerMatch[2] + def.substring(headerMatch[0].length);
|
|
634
|
-
finalDefinitionHeaders.push({ original: def, rewritten: rewrittenDef });
|
|
635
|
-
}
|
|
636
|
-
else {
|
|
637
|
-
finalDefinitionHeaders.push({ original: def, rewritten: def });
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
if (renames.size === 0) {
|
|
641
|
-
return { definitions: finalDefinitionHeaders.map(d => d.rewritten), rewrittenMainSelect: mainSelect };
|
|
642
|
-
}
|
|
643
|
-
const rewriteAll = (sql) => {
|
|
644
|
-
let result = sql;
|
|
645
|
-
for (const [oldName, newName] of renames) {
|
|
646
|
-
result = this.renameSQLIdentifier(result, oldName, newName);
|
|
647
|
-
}
|
|
648
|
-
return result;
|
|
649
|
-
};
|
|
650
|
-
const definitions = finalDefinitionHeaders.map(d => rewriteAll(d.rewritten));
|
|
651
|
-
const rewrittenMainSelect = rewriteAll(mainSelect);
|
|
652
|
-
return { definitions, rewrittenMainSelect };
|
|
653
|
-
}
|
|
654
|
-
/**
|
|
655
|
-
* Replaces every reference to `oldName` (bare, [bracketed], or "quoted")
|
|
656
|
-
* with bare `newName`. Case-insensitive. Word-boundary matched so
|
|
657
|
-
* `MyAcronymBridge` is not affected by renaming `AcronymBridge`.
|
|
658
|
-
*
|
|
659
|
-
* Does not attempt to skip string literals or comments — see the note on
|
|
660
|
-
* `deconflictInnerCTEsViaSymbolTable` for the trade-off rationale.
|
|
661
|
-
*/
|
|
662
|
-
renameSQLIdentifier(sql, oldName, newName) {
|
|
663
|
-
const escaped = oldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
664
|
-
// Three forms: [Name], "Name", or bare Name (with word boundaries).
|
|
665
|
-
const pattern = new RegExp(`\\[${escaped}\\]|"${escaped}"|\\b${escaped}\\b`, 'gi');
|
|
666
|
-
// Function replacement, not a string. `newName` comes from
|
|
667
|
-
// `SymbolTable.Register`, which returns the identifier verbatim (or
|
|
668
|
-
// `name__N`) with no sanitisation — and both SQL Server bracketed and
|
|
669
|
-
// PostgreSQL quoted identifiers may legally contain `$`. As a string
|
|
670
|
-
// replacement, `$$`/`$&`/`` $` ``/`$'` in it were expanded rather than
|
|
671
|
-
// inserted, splicing surrounding SQL into an identifier in executed SQL.
|
|
672
|
-
// Escaping the search side above and stopping there is exactly the
|
|
673
|
-
// half-applied defence issue #3171 was about.
|
|
674
|
-
return sql.replace(pattern, () => newName);
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Extracts inner CTE definitions from SQL that starts with a WITH clause, and whether the
|
|
678
|
-
* clause is `WITH RECURSIVE`.
|
|
679
|
-
*
|
|
680
|
-
* Splits by position ({@link SplitLeadingCTEs}) so each definition is kept as written; when
|
|
681
|
-
* that cannot read the clause, falls back to {@link SQLParser.ExtractCTEs}.
|
|
682
|
-
*
|
|
683
|
-
* @param sql SQL starting with a WITH clause
|
|
684
|
-
* @param dialect SQL dialect for AST parsing
|
|
685
|
-
*/
|
|
686
|
-
hoistInnerCTEs(sql, dialect) {
|
|
687
|
-
// Split by position, so each definition is kept exactly as written (no re-emission).
|
|
688
|
-
const split = SplitLeadingCTEs(sql, dialect);
|
|
689
|
-
if (split) {
|
|
690
|
-
return {
|
|
691
|
-
innerCTEDefinitions: split.Definitions.map(d => d.Text),
|
|
692
|
-
mainSelect: split.Main,
|
|
693
|
-
isRecursive: split.Recursive,
|
|
694
|
-
};
|
|
695
|
-
}
|
|
696
|
-
const extraction = SQLParser.ExtractCTEs(sql, dialect);
|
|
697
|
-
if (!extraction) {
|
|
698
|
-
// Should not happen since caller already verified WITH prefix,
|
|
699
|
-
// but handle gracefully by treating the whole SQL as the main select
|
|
700
|
-
return { innerCTEDefinitions: [], mainSelect: sql, isRecursive: false };
|
|
701
|
-
}
|
|
702
|
-
return {
|
|
703
|
-
innerCTEDefinitions: extraction.CTEDefinitions,
|
|
704
|
-
mainSelect: extraction.MainStatement,
|
|
705
|
-
isRecursive: false,
|
|
706
|
-
};
|
|
707
|
-
}
|
|
708
|
-
/**
|
|
709
|
-
* Strips a trailing ORDER BY clause from SQL that will be wrapped in a CTE.
|
|
710
|
-
*
|
|
711
|
-
* SQL Server disallows ORDER BY inside CTEs unless TOP, OFFSET, or FOR XML is present.
|
|
712
|
-
* PostgreSQL allows ORDER BY in CTEs, so no stripping is needed there.
|
|
713
|
-
*
|
|
714
|
-
* Delegates to the shared `AnalyzeTopLevelOrderBy` utility (orderByAnalyzer.ts)
|
|
715
|
-
* which implements a 2-tier strategy:
|
|
716
|
-
* Tier 1: AST parsing (with Nunjucks preprocessing if needed)
|
|
717
|
-
* Tier 2: MJLexer scanner with carried lexical state across token boundaries
|
|
718
|
-
*
|
|
719
|
-
* When both tiers fail to strip, falls back to OFFSET 0 ROWS injection as
|
|
720
|
-
* a last resort (semantically neutral but makes ORDER BY legal in CTEs).
|
|
721
|
-
*/
|
|
722
|
-
stripTrailingOrderBy(sql, dialect) {
|
|
723
|
-
if (!sql)
|
|
724
|
-
return sql;
|
|
725
|
-
const trimmed = sql.trimEnd();
|
|
726
|
-
if (!/ORDER/i.test(trimmed))
|
|
727
|
-
return sql;
|
|
728
|
-
if (dialect.AllowsOrderByInCTE)
|
|
729
|
-
return sql;
|
|
730
|
-
const analysis = AnalyzeTopLevelOrderBy(trimmed, dialect);
|
|
731
|
-
// No top-level ORDER BY found — nothing to strip
|
|
732
|
-
if (analysis.Positions.length === 0)
|
|
733
|
-
return sql;
|
|
734
|
-
// ORDER BY is legal in this CTE context (TOP/OFFSET/FOR XML)
|
|
735
|
-
if (analysis.IsLegalInCTE)
|
|
736
|
-
return sql;
|
|
737
|
-
// Stripping succeeded — use the stripped SQL
|
|
738
|
-
if (analysis.SqlWithoutOrderBy !== trimmed)
|
|
739
|
-
return analysis.SqlWithoutOrderBy;
|
|
740
|
-
// Last resort: OFFSET 0 ROWS injection
|
|
741
|
-
return this.injectOffset0Rows(trimmed);
|
|
742
|
-
}
|
|
743
|
-
/**
|
|
744
|
-
* Injects OFFSET 0 ROWS after the last top-level ORDER BY clause to make it
|
|
745
|
-
* legal in a CTE without changing the result set.
|
|
746
|
-
*/
|
|
747
|
-
injectOffset0Rows(sql) {
|
|
748
|
-
const trimmed = sql.trimEnd();
|
|
749
|
-
const withoutSemicolon = trimmed.replace(/;\s*$/, '');
|
|
750
|
-
return `${withoutSemicolon} OFFSET 0 ROWS`;
|
|
751
|
-
}
|
|
752
|
-
/**
|
|
753
|
-
* Strips SQL comments from the input string so that composition tokens
|
|
754
|
-
* inside comments are not treated as real references.
|
|
755
|
-
* Handles both single-line (-- ...) and multi-line block comments.
|
|
756
|
-
* Preserves string literals (single-quoted) to avoid stripping inside them.
|
|
757
|
-
*/
|
|
758
|
-
stripSQLComments(sql) {
|
|
759
|
-
let result = '';
|
|
760
|
-
let i = 0;
|
|
761
|
-
while (i < sql.length) {
|
|
762
|
-
// Single-quoted string literal — preserve as-is
|
|
763
|
-
if (sql[i] === "'") {
|
|
764
|
-
result += sql[i++];
|
|
765
|
-
while (i < sql.length) {
|
|
766
|
-
if (sql[i] === "'" && i + 1 < sql.length && sql[i + 1] === "'") {
|
|
767
|
-
// Escaped quote inside string
|
|
768
|
-
result += "''";
|
|
769
|
-
i += 2;
|
|
770
|
-
}
|
|
771
|
-
else if (sql[i] === "'") {
|
|
772
|
-
result += sql[i++];
|
|
773
|
-
break;
|
|
774
|
-
}
|
|
775
|
-
else {
|
|
776
|
-
result += sql[i++];
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
// Single-line comment: -- to end of line
|
|
781
|
-
else if (sql[i] === '-' && i + 1 < sql.length && sql[i + 1] === '-') {
|
|
782
|
-
// Skip to end of line
|
|
783
|
-
while (i < sql.length && sql[i] !== '\n') {
|
|
784
|
-
i++;
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
// Block comment: /* ... */
|
|
788
|
-
else if (sql[i] === '/' && i + 1 < sql.length && sql[i + 1] === '*') {
|
|
789
|
-
i += 2; // skip /*
|
|
790
|
-
while (i < sql.length) {
|
|
791
|
-
if (sql[i] === '*' && i + 1 < sql.length && sql[i + 1] === '/') {
|
|
792
|
-
i += 2; // skip */
|
|
793
|
-
break;
|
|
794
|
-
}
|
|
795
|
-
i++;
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
// Normal character
|
|
799
|
-
else {
|
|
800
|
-
result += sql[i++];
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
return result;
|
|
804
|
-
}
|
|
805
111
|
}
|
|
806
112
|
//# sourceMappingURL=queryCompositionEngine.js.map
|