rawsql-ts 0.19.0 → 0.20.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/esm/index.min.js +3 -3
- package/dist/esm/index.min.js.map +3 -3
- package/dist/esm/transformers/SSSQLFilterBuilder.d.ts +48 -1
- package/dist/esm/transformers/SSSQLFilterBuilder.js +577 -31
- package/dist/esm/transformers/SSSQLFilterBuilder.js.map +1 -1
- package/dist/index.min.js +3 -3
- package/dist/index.min.js.map +3 -3
- package/dist/src/transformers/SSSQLFilterBuilder.d.ts +48 -1
- package/dist/transformers/SSSQLFilterBuilder.js +575 -29
- package/dist/transformers/SSSQLFilterBuilder.js.map +1 -1
- package/dist/tsconfig.browser.tsbuildinfo +1 -1
- package/package.json +1 -1
|
@@ -1,14 +1,38 @@
|
|
|
1
|
-
import { WhereClause, TableSource } from "../models/Clause";
|
|
2
|
-
import {
|
|
1
|
+
import { WhereClause, SubQuerySource, TableSource } from "../models/Clause";
|
|
2
|
+
import { SimpleSelectQuery } from "../models/SelectQuery";
|
|
3
|
+
import { BinaryExpression, ColumnReference, IdentifierString, InlineQuery, LiteralValue, ParameterExpression, ParenExpression, RawString, UnaryExpression } from "../models/ValueComponent";
|
|
3
4
|
import { SelectQueryParser } from "../parsers/SelectQueryParser";
|
|
4
5
|
import { UpstreamSelectQueryFinder } from "./UpstreamSelectQueryFinder";
|
|
5
|
-
import { SelectableColumnCollector, DuplicateDetectionMode } from "./SelectableColumnCollector";
|
|
6
6
|
import { ColumnReferenceCollector } from "./ColumnReferenceCollector";
|
|
7
|
+
import { SelectableColumnCollector, DuplicateDetectionMode } from "./SelectableColumnCollector";
|
|
8
|
+
import { ParameterCollector } from "./ParameterCollector";
|
|
9
|
+
import { SqlFormatter } from "./SqlFormatter";
|
|
10
|
+
import { CTECollector } from "./CTECollector";
|
|
7
11
|
import { collectSupportedOptionalConditionBranches } from "./PruneOptionalConditionBranches";
|
|
12
|
+
const formatter = new SqlFormatter();
|
|
13
|
+
const SUPPORTED_SCALAR_OPERATORS = new Set(["=", "<>", "<", "<=", ">", ">=", "like", "ilike"]);
|
|
8
14
|
const normalizeIdentifier = (value) => value.trim().toLowerCase();
|
|
15
|
+
const normalizeSql = (value) => value.replace(/\s+/g, " ").trim().toLowerCase();
|
|
9
16
|
const normalizeColumnReferenceKey = (reference) => {
|
|
10
17
|
return `${normalizeIdentifier(reference.getNamespace())}.${normalizeIdentifier(reference.column.name)}`;
|
|
11
18
|
};
|
|
19
|
+
const normalizeColumnReferenceText = (reference) => {
|
|
20
|
+
const namespace = reference.getNamespace();
|
|
21
|
+
return namespace ? `${namespace}.${reference.column.name}` : reference.column.name;
|
|
22
|
+
};
|
|
23
|
+
const normalizeScalarOperator = (value) => {
|
|
24
|
+
if (!value) {
|
|
25
|
+
return "=";
|
|
26
|
+
}
|
|
27
|
+
const normalized = value.trim().toLowerCase();
|
|
28
|
+
if (normalized === "!=") {
|
|
29
|
+
return "<>";
|
|
30
|
+
}
|
|
31
|
+
if (SUPPORTED_SCALAR_OPERATORS.has(normalized)) {
|
|
32
|
+
return normalized;
|
|
33
|
+
}
|
|
34
|
+
throw new Error(`Unsupported SSSQL operator '${value}'.`);
|
|
35
|
+
};
|
|
12
36
|
const isExplicitEqualityScaffoldValue = (value) => {
|
|
13
37
|
var _a;
|
|
14
38
|
if (value === null || value === undefined) {
|
|
@@ -40,26 +64,69 @@ const makeParameterName = (filterName) => {
|
|
|
40
64
|
.replace(/\./g, "_")
|
|
41
65
|
.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
42
66
|
};
|
|
43
|
-
const
|
|
44
|
-
|
|
67
|
+
const unwrapParens = (expression) => {
|
|
68
|
+
let candidate = expression;
|
|
69
|
+
while (candidate instanceof ParenExpression) {
|
|
70
|
+
candidate = candidate.expression;
|
|
71
|
+
}
|
|
72
|
+
return candidate;
|
|
73
|
+
};
|
|
74
|
+
const isBinaryOperator = (expression, operator) => {
|
|
75
|
+
return expression instanceof BinaryExpression && expression.operator.value.trim().toLowerCase() === operator;
|
|
76
|
+
};
|
|
77
|
+
const collectTopLevelAndTerms = (expression) => {
|
|
78
|
+
const candidate = unwrapParens(expression);
|
|
79
|
+
if (!isBinaryOperator(candidate, "and")) {
|
|
80
|
+
return [expression];
|
|
81
|
+
}
|
|
82
|
+
return [
|
|
83
|
+
...collectTopLevelAndTerms(candidate.left),
|
|
84
|
+
...collectTopLevelAndTerms(candidate.right)
|
|
85
|
+
];
|
|
86
|
+
};
|
|
87
|
+
const collectTopLevelOrTerms = (expression) => {
|
|
88
|
+
const candidate = unwrapParens(expression);
|
|
89
|
+
if (!isBinaryOperator(candidate, "or")) {
|
|
90
|
+
return [expression];
|
|
91
|
+
}
|
|
92
|
+
return [
|
|
93
|
+
...collectTopLevelOrTerms(candidate.left),
|
|
94
|
+
...collectTopLevelOrTerms(candidate.right)
|
|
95
|
+
];
|
|
96
|
+
};
|
|
97
|
+
const getGuardedParameterName = (expression) => {
|
|
98
|
+
const candidate = unwrapParens(expression);
|
|
99
|
+
if (!isBinaryOperator(candidate, "is")) {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
if (!(candidate.left instanceof ParameterExpression)) {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
const right = unwrapParens(candidate.right);
|
|
106
|
+
const isNull = (right instanceof LiteralValue && right.value === null)
|
|
107
|
+
|| (right instanceof RawString && right.value.trim().toLowerCase() === "null");
|
|
108
|
+
if (!isNull) {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
return candidate.left.name.value;
|
|
112
|
+
};
|
|
113
|
+
const buildOptionalScalarBranch = (column, parameterName, operator) => {
|
|
114
|
+
const guard = new BinaryExpression(new ParameterExpression(parameterName), "is", new LiteralValue(null));
|
|
115
|
+
const predicate = new BinaryExpression(new ColumnReference(column.getNamespace() || null, column.column.name), operator, new ParameterExpression(parameterName));
|
|
116
|
+
return new ParenExpression(new BinaryExpression(guard, "or", predicate));
|
|
117
|
+
};
|
|
118
|
+
const buildOptionalExistsBranch = (parameterName, subquery, kind) => {
|
|
45
119
|
const guard = new BinaryExpression(new ParameterExpression(parameterName), "is", new LiteralValue(null));
|
|
46
|
-
const
|
|
47
|
-
|
|
120
|
+
const existsExpression = new UnaryExpression("exists", new InlineQuery(subquery));
|
|
121
|
+
const predicate = kind === "exists"
|
|
122
|
+
? existsExpression
|
|
123
|
+
: new UnaryExpression("not", existsExpression);
|
|
124
|
+
return new ParenExpression(new BinaryExpression(guard, "or", predicate));
|
|
48
125
|
};
|
|
49
126
|
const rebuildWhereWithoutTerm = (query, termToRemove) => {
|
|
50
127
|
if (!query.whereClause) {
|
|
51
128
|
return;
|
|
52
129
|
}
|
|
53
|
-
const collectTopLevelAndTerms = (expression) => {
|
|
54
|
-
if (expression instanceof BinaryExpression &&
|
|
55
|
-
expression.operator.value.trim().toLowerCase() === "and") {
|
|
56
|
-
return [
|
|
57
|
-
...collectTopLevelAndTerms(expression.left),
|
|
58
|
-
...collectTopLevelAndTerms(expression.right)
|
|
59
|
-
];
|
|
60
|
-
}
|
|
61
|
-
return [expression];
|
|
62
|
-
};
|
|
63
130
|
const terms = collectTopLevelAndTerms(query.whereClause.condition).filter(term => term !== termToRemove);
|
|
64
131
|
if (terms.length === 0) {
|
|
65
132
|
query.whereClause = null;
|
|
@@ -71,6 +138,212 @@ const rebuildWhereWithoutTerm = (query, termToRemove) => {
|
|
|
71
138
|
}
|
|
72
139
|
query.whereClause = new WhereClause(rebuilt);
|
|
73
140
|
};
|
|
141
|
+
const formatSqlComponent = (component) => {
|
|
142
|
+
return formatter.format(component).formattedSql;
|
|
143
|
+
};
|
|
144
|
+
const enforceSubqueryConstraints = (sql) => {
|
|
145
|
+
if (!sql.trim()) {
|
|
146
|
+
throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not be empty.");
|
|
147
|
+
}
|
|
148
|
+
if (sql.includes(";")) {
|
|
149
|
+
throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not contain semicolons or multiple statements.");
|
|
150
|
+
}
|
|
151
|
+
if (/\blateral\b/i.test(sql)) {
|
|
152
|
+
throw new Error("LATERAL is not supported in SSSQL EXISTS/NOT EXISTS scaffold.");
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const substituteAnchorPlaceholders = (sql, formattedColumns) => {
|
|
156
|
+
const usedIndexes = new Set();
|
|
157
|
+
const replaced = sql.replace(/\$c(\d+)/g, (_, indexDigits) => {
|
|
158
|
+
const index = Number(indexDigits);
|
|
159
|
+
if (!Number.isInteger(index)) {
|
|
160
|
+
throw new Error(`Invalid placeholder '$c${indexDigits}' in SSSQL scaffold query.`);
|
|
161
|
+
}
|
|
162
|
+
if (index < 0 || index >= formattedColumns.length) {
|
|
163
|
+
throw new Error(`Placeholder '$c${index}' references a missing SSSQL scaffold anchor column.`);
|
|
164
|
+
}
|
|
165
|
+
usedIndexes.add(index);
|
|
166
|
+
return formattedColumns[index];
|
|
167
|
+
});
|
|
168
|
+
if (formattedColumns.length === 0) {
|
|
169
|
+
return replaced;
|
|
170
|
+
}
|
|
171
|
+
for (let index = 0; index < formattedColumns.length; index += 1) {
|
|
172
|
+
if (!usedIndexes.has(index)) {
|
|
173
|
+
throw new Error(`Missing placeholder '$c${index}' for SSSQL scaffold anchor column.`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return replaced;
|
|
177
|
+
};
|
|
178
|
+
const getScalarBranchDetails = (expression, parameterName) => {
|
|
179
|
+
const meaningfulTerms = collectTopLevelOrTerms(expression)
|
|
180
|
+
.filter(term => getGuardedParameterName(term) !== parameterName);
|
|
181
|
+
if (meaningfulTerms.length !== 1) {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
const predicate = unwrapParens(meaningfulTerms[0]);
|
|
185
|
+
if (!(predicate instanceof BinaryExpression)) {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
const left = unwrapParens(predicate.left);
|
|
189
|
+
const right = unwrapParens(predicate.right);
|
|
190
|
+
if (left instanceof ColumnReference && right instanceof ParameterExpression && right.name.value === parameterName) {
|
|
191
|
+
try {
|
|
192
|
+
return {
|
|
193
|
+
operator: normalizeScalarOperator(predicate.operator.value),
|
|
194
|
+
target: normalizeColumnReferenceText(left)
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
catch (_a) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (right instanceof ColumnReference && left instanceof ParameterExpression && left.name.value === parameterName) {
|
|
202
|
+
try {
|
|
203
|
+
return {
|
|
204
|
+
operator: normalizeScalarOperator(predicate.operator.value),
|
|
205
|
+
target: normalizeColumnReferenceText(right)
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
catch (_b) {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return null;
|
|
213
|
+
};
|
|
214
|
+
const hasSelectQuery = (value) => {
|
|
215
|
+
return typeof value === "object" && value !== null && "selectQuery" in value;
|
|
216
|
+
};
|
|
217
|
+
const collectColumnReferencesDeep = (value) => {
|
|
218
|
+
const references = [];
|
|
219
|
+
const visited = new WeakSet();
|
|
220
|
+
const walk = (candidate) => {
|
|
221
|
+
if (!candidate || typeof candidate !== "object") {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (candidate instanceof ColumnReference) {
|
|
225
|
+
references.push(candidate);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (visited.has(candidate)) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
visited.add(candidate);
|
|
232
|
+
if (Array.isArray(candidate)) {
|
|
233
|
+
for (const item of candidate) {
|
|
234
|
+
walk(item);
|
|
235
|
+
}
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
for (const child of Object.values(candidate)) {
|
|
239
|
+
walk(child);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
walk(value);
|
|
243
|
+
return references;
|
|
244
|
+
};
|
|
245
|
+
const getExistsBranchKind = (expression, parameterName) => {
|
|
246
|
+
const meaningfulTerms = collectTopLevelOrTerms(expression)
|
|
247
|
+
.filter(term => getGuardedParameterName(term) !== parameterName);
|
|
248
|
+
if (meaningfulTerms.length !== 1) {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
const predicate = unwrapParens(meaningfulTerms[0]);
|
|
252
|
+
const isInlineQueryValue = (value) => {
|
|
253
|
+
return value instanceof InlineQuery || hasSelectQuery(value);
|
|
254
|
+
};
|
|
255
|
+
if (predicate instanceof UnaryExpression && predicate.operator.value.trim().toLowerCase() === "exists") {
|
|
256
|
+
return isInlineQueryValue(unwrapParens(predicate.expression)) ? "exists" : null;
|
|
257
|
+
}
|
|
258
|
+
if (predicate instanceof UnaryExpression && predicate.operator.value.trim().toLowerCase() === "not exists") {
|
|
259
|
+
return isInlineQueryValue(unwrapParens(predicate.expression)) ? "not-exists" : null;
|
|
260
|
+
}
|
|
261
|
+
if (predicate instanceof UnaryExpression &&
|
|
262
|
+
predicate.operator.value.trim().toLowerCase() === "not" &&
|
|
263
|
+
unwrapParens(predicate.expression) instanceof UnaryExpression) {
|
|
264
|
+
const nested = unwrapParens(predicate.expression);
|
|
265
|
+
if (nested.operator.value.trim().toLowerCase() === "exists"
|
|
266
|
+
&& isInlineQueryValue(unwrapParens(nested.expression))) {
|
|
267
|
+
return "not-exists";
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return null;
|
|
271
|
+
};
|
|
272
|
+
const getExistsPredicateDetails = (expression, parameterName) => {
|
|
273
|
+
const meaningfulTerms = collectTopLevelOrTerms(expression)
|
|
274
|
+
.filter(term => getGuardedParameterName(term) !== parameterName);
|
|
275
|
+
if (meaningfulTerms.length !== 1) {
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
278
|
+
const predicate = unwrapParens(meaningfulTerms[0]);
|
|
279
|
+
const isInlineQueryValue = (value) => {
|
|
280
|
+
return value instanceof InlineQuery || hasSelectQuery(value);
|
|
281
|
+
};
|
|
282
|
+
if (predicate instanceof UnaryExpression && predicate.operator.value.trim().toLowerCase() === "exists") {
|
|
283
|
+
const candidate = unwrapParens(predicate.expression);
|
|
284
|
+
if (isInlineQueryValue(candidate)) {
|
|
285
|
+
return {
|
|
286
|
+
kind: "exists",
|
|
287
|
+
subquery: candidate.selectQuery
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
if (predicate instanceof UnaryExpression && predicate.operator.value.trim().toLowerCase() === "not exists") {
|
|
293
|
+
const candidate = unwrapParens(predicate.expression);
|
|
294
|
+
if (isInlineQueryValue(candidate)) {
|
|
295
|
+
return {
|
|
296
|
+
kind: "not-exists",
|
|
297
|
+
subquery: candidate.selectQuery
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
if (predicate instanceof UnaryExpression &&
|
|
303
|
+
predicate.operator.value.trim().toLowerCase() === "not" &&
|
|
304
|
+
unwrapParens(predicate.expression) instanceof UnaryExpression) {
|
|
305
|
+
const nested = unwrapParens(predicate.expression);
|
|
306
|
+
const candidate = unwrapParens(nested.expression);
|
|
307
|
+
if (nested.operator.value.trim().toLowerCase() === "exists" && isInlineQueryValue(candidate)) {
|
|
308
|
+
return {
|
|
309
|
+
kind: "not-exists",
|
|
310
|
+
subquery: candidate.selectQuery
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
};
|
|
316
|
+
const getBranchInfo = (branch) => {
|
|
317
|
+
const scalar = getScalarBranchDetails(branch.expression, branch.parameterName);
|
|
318
|
+
if (scalar) {
|
|
319
|
+
return {
|
|
320
|
+
parameterName: branch.parameterName,
|
|
321
|
+
kind: "scalar",
|
|
322
|
+
operator: scalar.operator,
|
|
323
|
+
target: scalar.target,
|
|
324
|
+
query: branch.query,
|
|
325
|
+
expression: branch.expression,
|
|
326
|
+
sql: formatSqlComponent(branch.expression)
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
const existsKind = getExistsBranchKind(branch.expression, branch.parameterName);
|
|
330
|
+
if (existsKind) {
|
|
331
|
+
return {
|
|
332
|
+
parameterName: branch.parameterName,
|
|
333
|
+
kind: existsKind,
|
|
334
|
+
query: branch.query,
|
|
335
|
+
expression: branch.expression,
|
|
336
|
+
sql: formatSqlComponent(branch.expression)
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
return {
|
|
340
|
+
parameterName: branch.parameterName,
|
|
341
|
+
kind: "expression",
|
|
342
|
+
query: branch.query,
|
|
343
|
+
expression: branch.expression,
|
|
344
|
+
sql: formatSqlComponent(branch.expression)
|
|
345
|
+
};
|
|
346
|
+
};
|
|
74
347
|
/**
|
|
75
348
|
* Builds and refreshes truthful SSSQL optional filter branches.
|
|
76
349
|
* Runtime callers should use pruning, not dynamic predicate injection.
|
|
@@ -80,49 +353,180 @@ export class SSSQLFilterBuilder {
|
|
|
80
353
|
this.tableColumnResolver = tableColumnResolver;
|
|
81
354
|
this.finder = new UpstreamSelectQueryFinder(this.tableColumnResolver);
|
|
82
355
|
}
|
|
356
|
+
list(query) {
|
|
357
|
+
const parsed = this.parseQuery(query);
|
|
358
|
+
return collectSupportedOptionalConditionBranches(parsed).map(getBranchInfo);
|
|
359
|
+
}
|
|
83
360
|
scaffold(query, filters) {
|
|
84
361
|
const parsed = this.parseQuery(query);
|
|
85
362
|
for (const [filterName, filterValue] of Object.entries(filters)) {
|
|
86
363
|
if (!isExplicitEqualityScaffoldValue(filterValue)) {
|
|
87
|
-
throw new Error(`SSSQL scaffold only supports equality filters in v1. Use refresh for pre-authored branches: '${filterName}'.`);
|
|
364
|
+
throw new Error(`SSSQL scaffold only supports equality filters in v1. Use structured scaffold or refresh for pre-authored branches: '${filterName}'.`);
|
|
88
365
|
}
|
|
89
|
-
|
|
90
|
-
|
|
366
|
+
this.scaffoldBranch(parsed, {
|
|
367
|
+
target: filterName,
|
|
368
|
+
parameterName: makeParameterName(filterName),
|
|
369
|
+
operator: "="
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
return parsed;
|
|
373
|
+
}
|
|
374
|
+
scaffoldBranch(query, spec) {
|
|
375
|
+
const parsed = this.parseQuery(query);
|
|
376
|
+
if (spec.kind === "exists" || spec.kind === "not-exists") {
|
|
377
|
+
this.scaffoldExistsBranch(parsed, spec);
|
|
378
|
+
return parsed;
|
|
91
379
|
}
|
|
380
|
+
this.scaffoldScalarBranch(parsed, spec);
|
|
92
381
|
return parsed;
|
|
93
382
|
}
|
|
94
383
|
refresh(query, filters) {
|
|
95
384
|
const parsed = this.parseQuery(query);
|
|
96
385
|
for (const [filterName, filterValue] of Object.entries(filters)) {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
386
|
+
let parameterName = filterName;
|
|
387
|
+
let target = null;
|
|
388
|
+
let matches = collectSupportedOptionalConditionBranches(parsed)
|
|
389
|
+
.filter(branch => branch.parameterName === parameterName);
|
|
390
|
+
if (matches.length === 0) {
|
|
391
|
+
target = this.resolveTarget(parsed, filterName);
|
|
392
|
+
parameterName = target.parameterName;
|
|
393
|
+
matches = collectSupportedOptionalConditionBranches(parsed)
|
|
394
|
+
.filter(branch => branch.parameterName === parameterName);
|
|
395
|
+
}
|
|
100
396
|
if (matches.length === 0) {
|
|
397
|
+
if (!target) {
|
|
398
|
+
target = this.resolveTarget(parsed, filterName);
|
|
399
|
+
parameterName = target.parameterName;
|
|
400
|
+
}
|
|
101
401
|
if (!isExplicitEqualityScaffoldValue(filterValue)) {
|
|
102
402
|
throw new Error(`No existing SSSQL branch was found for '${filterName}', and v1 scaffold only supports equality filters.`);
|
|
103
403
|
}
|
|
104
|
-
|
|
404
|
+
this.scaffoldScalarBranch(parsed, {
|
|
405
|
+
target: filterName,
|
|
406
|
+
parameterName: target.parameterName,
|
|
407
|
+
operator: "="
|
|
408
|
+
});
|
|
105
409
|
continue;
|
|
106
410
|
}
|
|
107
411
|
if (matches.length > 1) {
|
|
108
|
-
throw new Error(`Multiple SSSQL branches matched parameter ':${
|
|
412
|
+
throw new Error(`Multiple SSSQL branches matched parameter ':${parameterName}'. Refresh is ambiguous.`);
|
|
109
413
|
}
|
|
110
414
|
const [match] = matches;
|
|
111
415
|
if (!match) {
|
|
112
416
|
continue;
|
|
113
417
|
}
|
|
114
|
-
|
|
418
|
+
const correlatedPlan = this.buildCorrelatedRefreshPlan(parsed, match);
|
|
419
|
+
if (correlatedPlan) {
|
|
420
|
+
if (correlatedPlan.target.query === match.query) {
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
this.rebaseMovedBranchByAlias(match.expression, correlatedPlan.sourceAlias, correlatedPlan.target.column);
|
|
424
|
+
rebuildWhereWithoutTerm(match.query, match.expression);
|
|
425
|
+
correlatedPlan.target.query.appendWhere(match.expression);
|
|
115
426
|
continue;
|
|
116
427
|
}
|
|
117
|
-
|
|
428
|
+
if (!target) {
|
|
429
|
+
target = this.resolveTarget(parsed, filterName);
|
|
430
|
+
}
|
|
431
|
+
if (match.query !== target.query) {
|
|
432
|
+
this.rebaseMovedBranch(match.expression, match.query, target.column);
|
|
433
|
+
rebuildWhereWithoutTerm(match.query, match.expression);
|
|
434
|
+
target.query.appendWhere(match.expression);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return parsed;
|
|
438
|
+
}
|
|
439
|
+
remove(query, spec) {
|
|
440
|
+
const parsed = this.parseQuery(query);
|
|
441
|
+
const matches = this.findMatchingBranchInfos(parsed, spec);
|
|
442
|
+
if (matches.length === 0) {
|
|
443
|
+
return parsed;
|
|
444
|
+
}
|
|
445
|
+
if (matches.length > 1) {
|
|
446
|
+
throw new Error(`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`);
|
|
447
|
+
}
|
|
448
|
+
const [match] = matches;
|
|
449
|
+
if (!match) {
|
|
450
|
+
return parsed;
|
|
451
|
+
}
|
|
452
|
+
rebuildWhereWithoutTerm(match.query, match.expression);
|
|
453
|
+
return parsed;
|
|
454
|
+
}
|
|
455
|
+
removeAll(query) {
|
|
456
|
+
const parsed = this.parseQuery(query);
|
|
457
|
+
const matches = this.list(parsed);
|
|
458
|
+
for (const match of matches) {
|
|
118
459
|
rebuildWhereWithoutTerm(match.query, match.expression);
|
|
119
|
-
target.query.appendWhere(match.expression);
|
|
120
460
|
}
|
|
121
461
|
return parsed;
|
|
122
462
|
}
|
|
123
463
|
parseQuery(query) {
|
|
124
464
|
return typeof query === "string" ? SelectQueryParser.parse(query) : query;
|
|
125
465
|
}
|
|
466
|
+
findMatchingBranchInfos(root, spec) {
|
|
467
|
+
const normalizedOperator = spec.operator ? normalizeScalarOperator(spec.operator) : undefined;
|
|
468
|
+
const normalizedTarget = spec.target ? normalizeIdentifier(spec.target) : undefined;
|
|
469
|
+
return this.list(root).filter(branch => {
|
|
470
|
+
if (branch.parameterName !== spec.parameterName) {
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
473
|
+
if (spec.kind && branch.kind !== spec.kind) {
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
if (normalizedOperator && branch.operator !== normalizedOperator) {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
if (normalizedTarget && (!branch.target || normalizeIdentifier(branch.target) !== normalizedTarget)) {
|
|
480
|
+
return false;
|
|
481
|
+
}
|
|
482
|
+
return true;
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
scaffoldScalarBranch(root, spec) {
|
|
486
|
+
var _a;
|
|
487
|
+
const target = this.resolveTarget(root, spec.target);
|
|
488
|
+
const parameterName = ((_a = spec.parameterName) === null || _a === void 0 ? void 0 : _a.trim()) || target.parameterName;
|
|
489
|
+
const operator = normalizeScalarOperator(spec.operator);
|
|
490
|
+
const branch = buildOptionalScalarBranch(target.column, parameterName, operator);
|
|
491
|
+
const branchSql = normalizeSql(formatSqlComponent(branch));
|
|
492
|
+
const duplicate = this.list(root).find(existing => existing.query === target.query &&
|
|
493
|
+
normalizeSql(existing.sql) === branchSql);
|
|
494
|
+
if (duplicate) {
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
target.query.appendWhere(branch);
|
|
498
|
+
}
|
|
499
|
+
scaffoldExistsBranch(root, spec) {
|
|
500
|
+
const parameterName = spec.parameterName.trim();
|
|
501
|
+
if (!parameterName) {
|
|
502
|
+
throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");
|
|
503
|
+
}
|
|
504
|
+
if (spec.anchorColumns.length === 0) {
|
|
505
|
+
throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");
|
|
506
|
+
}
|
|
507
|
+
const anchorTargets = spec.anchorColumns.map(anchorColumn => this.resolveTarget(root, anchorColumn));
|
|
508
|
+
const targetQueries = [...new Set(anchorTargets.map(target => target.query))];
|
|
509
|
+
if (targetQueries.length !== 1) {
|
|
510
|
+
throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");
|
|
511
|
+
}
|
|
512
|
+
const targetQuery = targetQueries[0];
|
|
513
|
+
const formattedColumns = anchorTargets.map(target => formatSqlComponent(target.column));
|
|
514
|
+
const substitutedSql = substituteAnchorPlaceholders(spec.query, formattedColumns).trim();
|
|
515
|
+
enforceSubqueryConstraints(substitutedSql);
|
|
516
|
+
const subquery = SelectQueryParser.parse(substitutedSql);
|
|
517
|
+
const parameterNames = new Set(ParameterCollector.collect(subquery).map(parameter => parameter.name.value));
|
|
518
|
+
if (parameterNames.size !== 1 || !parameterNames.has(parameterName)) {
|
|
519
|
+
throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);
|
|
520
|
+
}
|
|
521
|
+
const branch = buildOptionalExistsBranch(parameterName, subquery, spec.kind);
|
|
522
|
+
const branchSql = normalizeSql(formatSqlComponent(branch));
|
|
523
|
+
const duplicate = this.list(root).find(existing => existing.query === targetQuery &&
|
|
524
|
+
normalizeSql(existing.sql) === branchSql);
|
|
525
|
+
if (duplicate) {
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
targetQuery.appendWhere(branch);
|
|
529
|
+
}
|
|
126
530
|
resolveTarget(root, filterName) {
|
|
127
531
|
var _a;
|
|
128
532
|
const qualified = parseQualifiedFilterName(filterName);
|
|
@@ -210,14 +614,140 @@ export class SSSQLFilterBuilder {
|
|
|
210
614
|
}
|
|
211
615
|
return (_a = source.getAliasName()) !== null && _a !== void 0 ? _a : source.datasource.table.name;
|
|
212
616
|
}
|
|
617
|
+
buildCorrelatedRefreshPlan(root, branch) {
|
|
618
|
+
const details = getExistsPredicateDetails(branch.expression, branch.parameterName);
|
|
619
|
+
if (!details) {
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
const sourceAliases = this.collectSourceAliases(branch.query);
|
|
623
|
+
const candidatesByKey = new Map();
|
|
624
|
+
for (const reference of new ColumnReferenceCollector().collect(details.subquery)) {
|
|
625
|
+
const namespace = normalizeIdentifier(reference.getNamespace());
|
|
626
|
+
if (!namespace || !sourceAliases.has(namespace)) {
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
const column = normalizeIdentifier(reference.column.name);
|
|
630
|
+
const key = `${namespace}.${column}`;
|
|
631
|
+
if (!candidatesByKey.has(key)) {
|
|
632
|
+
candidatesByKey.set(key, { namespace, column });
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
const candidates = [...candidatesByKey.values()];
|
|
636
|
+
if (candidates.length === 0) {
|
|
637
|
+
throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);
|
|
638
|
+
}
|
|
639
|
+
if (candidates.length > 1) {
|
|
640
|
+
const listed = candidates.map(candidate => `${candidate.namespace}.${candidate.column}`).join(", ");
|
|
641
|
+
throw new Error(`SSSQL refresh found multiple correlated anchor candidates for ':${branch.parameterName}' (${listed}).`);
|
|
642
|
+
}
|
|
643
|
+
const [anchor] = candidates;
|
|
644
|
+
if (!anchor) {
|
|
645
|
+
throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);
|
|
646
|
+
}
|
|
647
|
+
return {
|
|
648
|
+
target: this.resolveCorrelatedAnchorTarget(root, branch.query, anchor, branch.parameterName),
|
|
649
|
+
sourceAlias: anchor.namespace
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
collectSourceAliases(query) {
|
|
653
|
+
var _a, _b;
|
|
654
|
+
const aliases = new Set();
|
|
655
|
+
for (const source of (_b = (_a = query.fromClause) === null || _a === void 0 ? void 0 : _a.getSources()) !== null && _b !== void 0 ? _b : []) {
|
|
656
|
+
const sourceAlias = this.getSourceAlias(source);
|
|
657
|
+
if (sourceAlias) {
|
|
658
|
+
aliases.add(sourceAlias);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return aliases;
|
|
662
|
+
}
|
|
663
|
+
resolveCorrelatedAnchorTarget(root, sourceQuery, anchor, parameterName) {
|
|
664
|
+
const sourceExpression = this.findSourceExpressionByAlias(sourceQuery, anchor.namespace, parameterName);
|
|
665
|
+
const upstreamQuery = this.resolveSourceExpressionToUpstreamQuery(root, sourceExpression, parameterName);
|
|
666
|
+
if (!upstreamQuery) {
|
|
667
|
+
return {
|
|
668
|
+
query: sourceQuery,
|
|
669
|
+
column: new ColumnReference(anchor.namespace, anchor.column),
|
|
670
|
+
parameterName
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
return this.resolveAnchorTargetInQuery(upstreamQuery, anchor, parameterName);
|
|
674
|
+
}
|
|
675
|
+
findSourceExpressionByAlias(query, alias, parameterName) {
|
|
676
|
+
var _a, _b;
|
|
677
|
+
const matches = ((_b = (_a = query.fromClause) === null || _a === void 0 ? void 0 : _a.getSources()) !== null && _b !== void 0 ? _b : [])
|
|
678
|
+
.filter(source => this.getSourceAlias(source) === alias);
|
|
679
|
+
if (matches.length === 0) {
|
|
680
|
+
throw new Error(`SSSQL refresh could not resolve correlated alias '${alias}' for ':${parameterName}'.`);
|
|
681
|
+
}
|
|
682
|
+
if (matches.length > 1) {
|
|
683
|
+
throw new Error(`SSSQL refresh found multiple correlated sources for alias '${alias}' and ':${parameterName}'.`);
|
|
684
|
+
}
|
|
685
|
+
return matches[0];
|
|
686
|
+
}
|
|
687
|
+
resolveSourceExpressionToUpstreamQuery(root, source, parameterName) {
|
|
688
|
+
if (source.datasource instanceof SubQuerySource) {
|
|
689
|
+
if (source.datasource.query instanceof SimpleSelectQuery) {
|
|
690
|
+
return source.datasource.query;
|
|
691
|
+
}
|
|
692
|
+
throw new Error(`SSSQL refresh requires a simple query anchor for ':${parameterName}'.`);
|
|
693
|
+
}
|
|
694
|
+
if (!(source.datasource instanceof TableSource)) {
|
|
695
|
+
return null;
|
|
696
|
+
}
|
|
697
|
+
const cteName = normalizeIdentifier(source.datasource.table.name);
|
|
698
|
+
const cteMatches = new CTECollector()
|
|
699
|
+
.collect(root)
|
|
700
|
+
.filter(cte => normalizeIdentifier(cte.getSourceAliasName()) === cteName);
|
|
701
|
+
if (cteMatches.length === 0) {
|
|
702
|
+
return null;
|
|
703
|
+
}
|
|
704
|
+
if (cteMatches.length > 1) {
|
|
705
|
+
throw new Error(`SSSQL refresh found multiple CTE anchors for ':${parameterName}' (${source.datasource.table.name}).`);
|
|
706
|
+
}
|
|
707
|
+
const [cte] = cteMatches;
|
|
708
|
+
if (!cte) {
|
|
709
|
+
return null;
|
|
710
|
+
}
|
|
711
|
+
const cteQuery = cte.query;
|
|
712
|
+
if (!(cteQuery instanceof SimpleSelectQuery)) {
|
|
713
|
+
throw new Error(`SSSQL refresh requires a simple CTE anchor for ':${parameterName}'.`);
|
|
714
|
+
}
|
|
715
|
+
return cteQuery;
|
|
716
|
+
}
|
|
717
|
+
resolveAnchorTargetInQuery(query, anchor, parameterName) {
|
|
718
|
+
const collector = new SelectableColumnCollector(this.tableColumnResolver, false, DuplicateDetectionMode.FullName, { upstream: true });
|
|
719
|
+
const matches = collector.collect(query)
|
|
720
|
+
.filter((entry) => entry.value instanceof ColumnReference)
|
|
721
|
+
.filter(entry => normalizeIdentifier(entry.name) === anchor.column);
|
|
722
|
+
if (matches.length === 0) {
|
|
723
|
+
throw new Error(`SSSQL refresh could not resolve correlated anchor column '${anchor.column}' for ':${parameterName}'.`);
|
|
724
|
+
}
|
|
725
|
+
if (matches.length > 1) {
|
|
726
|
+
throw new Error(`SSSQL refresh found multiple correlated anchor columns '${anchor.column}' for ':${parameterName}'.`);
|
|
727
|
+
}
|
|
728
|
+
return {
|
|
729
|
+
query,
|
|
730
|
+
column: matches[0].value,
|
|
731
|
+
parameterName
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
getSourceAlias(source) {
|
|
735
|
+
const explicitAlias = source.getAliasName();
|
|
736
|
+
if (explicitAlias) {
|
|
737
|
+
return normalizeIdentifier(explicitAlias);
|
|
738
|
+
}
|
|
739
|
+
if (source.datasource instanceof TableSource) {
|
|
740
|
+
return normalizeIdentifier(source.datasource.table.name);
|
|
741
|
+
}
|
|
742
|
+
return null;
|
|
743
|
+
}
|
|
213
744
|
rebaseMovedBranch(expression, sourceQuery, targetColumn) {
|
|
214
745
|
var _a, _b, _c;
|
|
215
746
|
const targetNamespace = targetColumn.qualifiedName.namespaces
|
|
216
747
|
? targetColumn.qualifiedName.namespaces.map(namespace => namespace.name)
|
|
217
748
|
: null;
|
|
218
749
|
const targetColumnName = normalizeIdentifier(targetColumn.column.name);
|
|
219
|
-
const sourceAliases = new Set(
|
|
220
|
-
.collect(expression)
|
|
750
|
+
const sourceAliases = new Set(collectColumnReferencesDeep(expression)
|
|
221
751
|
.filter(reference => normalizeIdentifier(reference.column.name) === targetColumnName)
|
|
222
752
|
.map(reference => normalizeIdentifier(reference.getNamespace()))
|
|
223
753
|
.filter(namespace => namespace.length > 0));
|
|
@@ -236,13 +766,29 @@ export class SSSQLFilterBuilder {
|
|
|
236
766
|
if (!availableAliases.has(sourceAlias)) {
|
|
237
767
|
return;
|
|
238
768
|
}
|
|
239
|
-
for (const reference of
|
|
769
|
+
for (const reference of collectColumnReferencesDeep(expression)) {
|
|
240
770
|
if (normalizeIdentifier(reference.getNamespace()) !== sourceAlias) {
|
|
241
771
|
continue;
|
|
242
772
|
}
|
|
243
773
|
reference.qualifiedName.namespaces = (_c = targetNamespace === null || targetNamespace === void 0 ? void 0 : targetNamespace.map(namespace => new IdentifierString(namespace))) !== null && _c !== void 0 ? _c : null;
|
|
244
774
|
}
|
|
245
775
|
}
|
|
776
|
+
rebaseMovedBranchByAlias(expression, sourceAlias, targetColumn) {
|
|
777
|
+
var _a;
|
|
778
|
+
const normalizedSourceAlias = normalizeIdentifier(sourceAlias);
|
|
779
|
+
if (!normalizedSourceAlias) {
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
const targetNamespace = targetColumn.qualifiedName.namespaces
|
|
783
|
+
? targetColumn.qualifiedName.namespaces.map(namespace => namespace.name)
|
|
784
|
+
: null;
|
|
785
|
+
for (const reference of collectColumnReferencesDeep(expression)) {
|
|
786
|
+
if (normalizeIdentifier(reference.getNamespace()) !== normalizedSourceAlias) {
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
reference.qualifiedName.namespaces = (_a = targetNamespace === null || targetNamespace === void 0 ? void 0 : targetNamespace.map(namespace => new IdentifierString(namespace))) !== null && _a !== void 0 ? _a : null;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
246
792
|
}
|
|
247
793
|
export const scaffoldSssqlQuery = (sqlContent, filters) => ({
|
|
248
794
|
query: new SSSQLFilterBuilder().scaffold(sqlContent, filters)
|