rawsql-ts 0.26.0 → 0.27.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.
Files changed (42) hide show
  1. package/dist/esm/index.d.ts +2 -0
  2. package/dist/esm/index.js +1 -0
  3. package/dist/esm/index.js.map +1 -1
  4. package/dist/esm/index.min.js +2 -2
  5. package/dist/esm/index.min.js.map +4 -4
  6. package/dist/esm/transformers/ConditionOptimization.d.ts +11 -1
  7. package/dist/esm/transformers/ConditionOptimization.js +122 -66
  8. package/dist/esm/transformers/ConditionOptimization.js.map +1 -1
  9. package/dist/esm/transformers/ParameterConditionPlacementOptimizer.d.ts +26 -7
  10. package/dist/esm/transformers/ParameterConditionPlacementOptimizer.js +408 -141
  11. package/dist/esm/transformers/ParameterConditionPlacementOptimizer.js.map +1 -1
  12. package/dist/esm/transformers/SSSQLFilterBuilder.d.ts +6 -0
  13. package/dist/esm/transformers/SSSQLFilterBuilder.js +84 -8
  14. package/dist/esm/transformers/SSSQLFilterBuilder.js.map +1 -1
  15. package/dist/esm/transformers/SqlComponentFormatter.d.ts +11 -0
  16. package/dist/esm/transformers/SqlComponentFormatter.js +16 -0
  17. package/dist/esm/transformers/SqlComponentFormatter.js.map +1 -0
  18. package/dist/esm/transformers/StaticPredicatePlacementOptimizer.d.ts +103 -0
  19. package/dist/esm/transformers/StaticPredicatePlacementOptimizer.js +1435 -0
  20. package/dist/esm/transformers/StaticPredicatePlacementOptimizer.js.map +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.min.js +2 -2
  24. package/dist/index.min.js.map +4 -4
  25. package/dist/src/index.d.ts +2 -0
  26. package/dist/src/transformers/ConditionOptimization.d.ts +11 -1
  27. package/dist/src/transformers/ParameterConditionPlacementOptimizer.d.ts +26 -7
  28. package/dist/src/transformers/SSSQLFilterBuilder.d.ts +6 -0
  29. package/dist/src/transformers/SqlComponentFormatter.d.ts +11 -0
  30. package/dist/src/transformers/StaticPredicatePlacementOptimizer.d.ts +103 -0
  31. package/dist/transformers/ConditionOptimization.js +146 -65
  32. package/dist/transformers/ConditionOptimization.js.map +1 -1
  33. package/dist/transformers/ParameterConditionPlacementOptimizer.js +407 -140
  34. package/dist/transformers/ParameterConditionPlacementOptimizer.js.map +1 -1
  35. package/dist/transformers/SSSQLFilterBuilder.js +92 -16
  36. package/dist/transformers/SSSQLFilterBuilder.js.map +1 -1
  37. package/dist/transformers/SqlComponentFormatter.js +21 -0
  38. package/dist/transformers/SqlComponentFormatter.js.map +1 -0
  39. package/dist/transformers/StaticPredicatePlacementOptimizer.js +1445 -0
  40. package/dist/transformers/StaticPredicatePlacementOptimizer.js.map +1 -0
  41. package/dist/tsconfig.browser.tsbuildinfo +1 -1
  42. package/package.json +1 -1
@@ -0,0 +1,1445 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.optimizeStaticPredicatePlacement = exports.planStaticPredicatePlacement = exports.StaticPredicatePlacementOptimizer = void 0;
4
+ const Clause_1 = require("../models/Clause");
5
+ const SelectQuery_1 = require("../models/SelectQuery");
6
+ const ValueComponent_1 = require("../models/ValueComponent");
7
+ const SelectQueryParser_1 = require("../parsers/SelectQueryParser");
8
+ const ValueParser_1 = require("../parsers/ValueParser");
9
+ const SqlComponentFormatter_1 = require("./SqlComponentFormatter");
10
+ const SelectOutputCollector_1 = require("./SelectOutputCollector");
11
+ const VOLATILE_OR_UNSUPPORTED_FUNCTION_REASON = "Predicate contains a function call; volatile and expression predicates are not moved in the safe-only implementation.";
12
+ const normalizeIdentifier = (value) => value.trim().toLowerCase();
13
+ const unwrapParens = (expression) => {
14
+ let candidate = expression;
15
+ while (candidate instanceof ValueComponent_1.ParenExpression) {
16
+ candidate = candidate.expression;
17
+ }
18
+ return candidate;
19
+ };
20
+ const isBinaryOperator = (expression, operator) => {
21
+ const candidate = unwrapParens(expression);
22
+ return candidate instanceof ValueComponent_1.BinaryExpression
23
+ && candidate.operator.value.trim().toLowerCase() === operator;
24
+ };
25
+ const collectTopLevelAndTerms = (expression) => {
26
+ const candidate = unwrapParens(expression);
27
+ if (!isBinaryOperator(candidate, "and")) {
28
+ return [expression];
29
+ }
30
+ return [
31
+ ...collectTopLevelAndTerms(candidate.left),
32
+ ...collectTopLevelAndTerms(candidate.right)
33
+ ];
34
+ };
35
+ const rebuildWhereWithoutTerms = (query, termsToRemove) => {
36
+ if (!query.whereClause || termsToRemove.size === 0) {
37
+ return;
38
+ }
39
+ const remaining = collectTopLevelAndTerms(query.whereClause.condition)
40
+ .filter(term => !termsToRemove.has(term));
41
+ if (remaining.length === 0) {
42
+ query.whereClause = null;
43
+ return;
44
+ }
45
+ let rebuilt = remaining[0];
46
+ for (let index = 1; index < remaining.length; index += 1) {
47
+ rebuilt = new ValueComponent_1.BinaryExpression(rebuilt, "and", remaining[index]);
48
+ }
49
+ query.whereClause = new Clause_1.WhereClause(rebuilt);
50
+ };
51
+ const cloneValueComponent = (expression, options) => {
52
+ return ValueParser_1.ValueParser.parse((0, SqlComponentFormatter_1.formatSqlComponent)(expression, options));
53
+ };
54
+ const cloneColumnReference = (reference) => {
55
+ var _a, _b;
56
+ const namespaces = (_b = (_a = reference.namespaces) === null || _a === void 0 ? void 0 : _a.map(namespace => namespace.name)) !== null && _b !== void 0 ? _b : null;
57
+ return new ValueComponent_1.ColumnReference(namespaces, reference.column.name);
58
+ };
59
+ const columnReferenceText = (reference) => {
60
+ const namespace = reference.getNamespace();
61
+ return namespace ? `${namespace}.${reference.column.name}` : reference.column.name;
62
+ };
63
+ const sameColumnReference = (left, right) => {
64
+ return normalizeIdentifier(left.column.name) === normalizeIdentifier(right.column.name)
65
+ && normalizeIdentifier(left.getNamespace()) === normalizeIdentifier(right.getNamespace());
66
+ };
67
+ const appendUnique = (items, value) => {
68
+ if (!items.includes(value)) {
69
+ items.push(value);
70
+ }
71
+ };
72
+ class StaticPredicatePlacementOptimizer {
73
+ plan(input, options = {}) {
74
+ var _a, _b, _c;
75
+ const parsed = this.parseInput(input, options);
76
+ const warnings = [...parsed.warnings];
77
+ const errors = [...parsed.errors];
78
+ if (!parsed.query) {
79
+ return this.buildResult({
80
+ query: null,
81
+ sql: parsed.sql,
82
+ applied: [],
83
+ skipped: [],
84
+ warnings,
85
+ errors,
86
+ dryRun: (_a = options.dryRun) !== null && _a !== void 0 ? _a : true,
87
+ formatterGeneratedSource: parsed.formatterGeneratedSource
88
+ });
89
+ }
90
+ if (!(parsed.query instanceof SelectQuery_1.SimpleSelectQuery)) {
91
+ warnings.push({
92
+ code: "UNSUPPORTED_ROOT_QUERY",
93
+ message: "Static predicate placement currently supports only SimpleSelectQuery roots."
94
+ });
95
+ return this.buildResult({
96
+ query: parsed.query,
97
+ sql: parsed.sql,
98
+ applied: [],
99
+ skipped: [],
100
+ warnings,
101
+ errors,
102
+ dryRun: (_b = options.dryRun) !== null && _b !== void 0 ? _b : true,
103
+ formatterGeneratedSource: parsed.formatterGeneratedSource
104
+ });
105
+ }
106
+ const query = parsed.query;
107
+ const applied = [];
108
+ const skipped = [];
109
+ const movedTerms = [];
110
+ for (const term of query.whereClause ? collectTopLevelAndTerms(query.whereClause.condition) : []) {
111
+ const candidate = this.analyzeCandidate(query, term, options);
112
+ if (!candidate) {
113
+ continue;
114
+ }
115
+ if ("code" in candidate) {
116
+ skipped.push(this.makeSkipped(term, candidate, options));
117
+ continue;
118
+ }
119
+ const target = this.resolveTarget(query, candidate);
120
+ if ("code" in target) {
121
+ skipped.push(this.makeSkipped(term, target, options));
122
+ continue;
123
+ }
124
+ let appliedReason = "";
125
+ if (target.kind === "simple") {
126
+ const targetColumns = this.resolveTargetColumns(query, target.query, candidate.references);
127
+ if ("code" in targetColumns) {
128
+ skipped.push(this.makeSkipped(term, targetColumns, options));
129
+ continue;
130
+ }
131
+ const placement = this.resolveTargetPlacement(target.query, targetColumns);
132
+ if ("code" in placement) {
133
+ skipped.push(this.makeSkipped(term, placement, options));
134
+ continue;
135
+ }
136
+ const movedPredicate = this.rebasePredicate(candidate.expression, targetColumns, options);
137
+ target.query.appendWhere(movedPredicate);
138
+ appliedReason = placement.reason;
139
+ }
140
+ else {
141
+ const placements = [];
142
+ let skip = null;
143
+ for (const branch of target.branches) {
144
+ const placement = this.resolveTargetPlacement(branch.query, branch.targetColumns);
145
+ if ("code" in placement) {
146
+ skip = placement;
147
+ break;
148
+ }
149
+ placements.push(placement);
150
+ }
151
+ if (skip) {
152
+ skipped.push(this.makeSkipped(term, skip, options));
153
+ continue;
154
+ }
155
+ for (const branch of target.branches) {
156
+ const movedPredicate = this.rebasePredicate(candidate.expression, branch.targetColumns, options);
157
+ branch.query.appendWhere(movedPredicate);
158
+ }
159
+ appliedReason = placements.some(item => /group by/i.test(item.reason))
160
+ ? "Predicate is distributed to every UNION branch by output column position; grouped branches only receive GROUP BY-key predicates."
161
+ : "Predicate is distributed to every UNION branch by output column position before unsafe query boundaries.";
162
+ }
163
+ movedTerms.push(term);
164
+ applied.push({
165
+ kind: "move_static_predicate",
166
+ predicateSql: candidate.predicateSql,
167
+ fromScopeId: "scope:root",
168
+ toScopeId: target.scopeId,
169
+ reason: appliedReason,
170
+ columnReferences: candidate.references.map(columnReferenceText)
171
+ });
172
+ }
173
+ rebuildWhereWithoutTerms(query, new Set(movedTerms));
174
+ const sql = applied.length > 0 || (0, SqlComponentFormatter_1.hasSqlComponentFormatOverride)(options)
175
+ ? (0, SqlComponentFormatter_1.formatSqlComponent)(query, options)
176
+ : parsed.sql;
177
+ return this.buildResult({
178
+ query,
179
+ sql,
180
+ applied,
181
+ skipped,
182
+ warnings,
183
+ errors,
184
+ dryRun: (_c = options.dryRun) !== null && _c !== void 0 ? _c : true,
185
+ formatterGeneratedSource: parsed.formatterGeneratedSource
186
+ });
187
+ }
188
+ optimize(input, options = {}) {
189
+ var _a;
190
+ return this.plan(input, { ...options, dryRun: (_a = options.dryRun) !== null && _a !== void 0 ? _a : false });
191
+ }
192
+ parseInput(input, options) {
193
+ const warnings = [];
194
+ const errors = [];
195
+ try {
196
+ const sourceSql = typeof input === "string"
197
+ ? input
198
+ : (0, SqlComponentFormatter_1.formatSqlComponent)(input, options);
199
+ if (typeof input !== "string" && options.cloneInput === false) {
200
+ return {
201
+ query: input,
202
+ sql: sourceSql,
203
+ formatterGeneratedSource: false,
204
+ warnings,
205
+ errors
206
+ };
207
+ }
208
+ if (typeof input !== "string") {
209
+ warnings.push({
210
+ code: "AST_INPUT_FORMATTED",
211
+ message: "AST input is cloned through formatter output so the caller-owned query is not mutated."
212
+ });
213
+ }
214
+ return {
215
+ query: SelectQueryParser_1.SelectQueryParser.parse(sourceSql),
216
+ sql: sourceSql,
217
+ formatterGeneratedSource: typeof input !== "string",
218
+ warnings,
219
+ errors
220
+ };
221
+ }
222
+ catch (error) {
223
+ const detail = error instanceof Error ? error.message : String(error);
224
+ errors.push({
225
+ code: "PARSE_FAILED",
226
+ message: "Static predicate placement could not parse the input SQL.",
227
+ detail
228
+ });
229
+ return {
230
+ query: null,
231
+ sql: typeof input === "string" ? input : "",
232
+ formatterGeneratedSource: typeof input !== "string",
233
+ warnings,
234
+ errors
235
+ };
236
+ }
237
+ }
238
+ analyzeCandidate(root, expression, options) {
239
+ if (this.collectParameterNames(expression).length > 0) {
240
+ return null;
241
+ }
242
+ const unsupported = this.findUnsupportedExpression(expression, this.isExistsPredicate(expression));
243
+ if (unsupported) {
244
+ return unsupported;
245
+ }
246
+ const references = this.collectRootColumnReferences(root, expression);
247
+ if (references.length === 0) {
248
+ return {
249
+ code: "NO_COLUMN_REFERENCE",
250
+ reason: "Static predicate has no outer column reference to anchor the move."
251
+ };
252
+ }
253
+ return {
254
+ expression,
255
+ predicateSql: (0, SqlComponentFormatter_1.formatSqlComponent)(expression, options),
256
+ references
257
+ };
258
+ }
259
+ isExistsPredicate(expression) {
260
+ const candidate = unwrapParens(expression);
261
+ if (!(candidate instanceof ValueComponent_1.UnaryExpression)) {
262
+ return false;
263
+ }
264
+ const operator = candidate.operator.value.trim().toLowerCase();
265
+ return operator === "exists" && unwrapParens(candidate.expression) instanceof ValueComponent_1.InlineQuery;
266
+ }
267
+ findUnsupportedExpression(expression, allowExistsSubquery) {
268
+ let found = null;
269
+ const visitSelect = (query) => {
270
+ var _a, _b, _c, _d;
271
+ if (found) {
272
+ return;
273
+ }
274
+ if (query instanceof SelectQuery_1.BinarySelectQuery) {
275
+ found = {
276
+ code: "UNION_BOUNDARY",
277
+ reason: "Static predicate would need distribution into a UNION branch, which is unsupported."
278
+ };
279
+ return;
280
+ }
281
+ if (!(query instanceof SelectQuery_1.SimpleSelectQuery)) {
282
+ found = {
283
+ code: "UNSUPPORTED_SUBQUERY",
284
+ reason: "Static predicate contains a non-simple subquery, which is unsupported."
285
+ };
286
+ return;
287
+ }
288
+ query.selectClause.items.forEach(item => visit(item.value));
289
+ for (const join of (_b = (_a = query.fromClause) === null || _a === void 0 ? void 0 : _a.joins) !== null && _b !== void 0 ? _b : []) {
290
+ if (join.condition) {
291
+ visit(join.condition.condition);
292
+ }
293
+ const source = join.source.datasource;
294
+ if (source instanceof Clause_1.SubQuerySource) {
295
+ visitSelect(source.query);
296
+ }
297
+ }
298
+ if (query.whereClause) {
299
+ visit(query.whereClause.condition);
300
+ }
301
+ if (query.havingClause) {
302
+ visit(query.havingClause.condition);
303
+ }
304
+ for (const cte of (_d = (_c = query.withClause) === null || _c === void 0 ? void 0 : _c.tables) !== null && _d !== void 0 ? _d : []) {
305
+ if (cte.query instanceof SelectQuery_1.SimpleSelectQuery || cte.query instanceof SelectQuery_1.BinarySelectQuery) {
306
+ visitSelect(cte.query);
307
+ }
308
+ }
309
+ };
310
+ const visit = (value) => {
311
+ if (found) {
312
+ return;
313
+ }
314
+ const candidate = unwrapParens(value);
315
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
316
+ visit(candidate.left);
317
+ visit(candidate.right);
318
+ return;
319
+ }
320
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
321
+ found = {
322
+ code: "FUNCTION_PREDICATE_UNSUPPORTED",
323
+ reason: VOLATILE_OR_UNSUPPORTED_FUNCTION_REASON
324
+ };
325
+ return;
326
+ }
327
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
328
+ found = {
329
+ code: "CASE_PREDICATE_UNSUPPORTED",
330
+ reason: "CASE predicates are not moved in the first safe-only implementation."
331
+ };
332
+ return;
333
+ }
334
+ if (candidate instanceof ValueComponent_1.InlineQuery) {
335
+ if (!allowExistsSubquery) {
336
+ found = {
337
+ code: "SUBQUERY_PREDICATE_UNSUPPORTED",
338
+ reason: "Subquery predicates are only moved when they are simple EXISTS predicates."
339
+ };
340
+ return;
341
+ }
342
+ visitSelect(candidate.selectQuery);
343
+ return;
344
+ }
345
+ if (candidate instanceof ValueComponent_1.ArrayQueryExpression) {
346
+ found = {
347
+ code: "SUBQUERY_PREDICATE_UNSUPPORTED",
348
+ reason: "Array subquery predicates are not moved in the first safe-only implementation."
349
+ };
350
+ return;
351
+ }
352
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
353
+ visit(candidate.expression);
354
+ return;
355
+ }
356
+ if (candidate instanceof ValueComponent_1.CastExpression) {
357
+ visit(candidate.input);
358
+ return;
359
+ }
360
+ if (candidate instanceof ValueComponent_1.JsonPredicateExpression) {
361
+ visit(candidate.expression);
362
+ return;
363
+ }
364
+ if (candidate instanceof ValueComponent_1.ArrayExpression) {
365
+ visit(candidate.expression);
366
+ return;
367
+ }
368
+ if (candidate instanceof ValueComponent_1.ValueList) {
369
+ candidate.values.forEach(visit);
370
+ return;
371
+ }
372
+ if (candidate instanceof ValueComponent_1.TupleExpression) {
373
+ candidate.values.forEach(visit);
374
+ return;
375
+ }
376
+ if (candidate instanceof ValueComponent_1.TypeValue && candidate.argument) {
377
+ visit(candidate.argument);
378
+ }
379
+ };
380
+ visit(expression);
381
+ return found;
382
+ }
383
+ resolveTarget(root, candidate) {
384
+ const boundary = this.findRootQueryBoundary(root);
385
+ if (boundary) {
386
+ return boundary;
387
+ }
388
+ if (!root.fromClause) {
389
+ return {
390
+ code: "NO_FROM_CLAUSE",
391
+ reason: "Predicate has no FROM source that can receive it safely."
392
+ };
393
+ }
394
+ const bindings = [];
395
+ for (const reference of candidate.references) {
396
+ const binding = this.resolveSourceBinding(root, root, reference);
397
+ if ("code" in binding) {
398
+ return binding;
399
+ }
400
+ if (!bindings.some(item => item.source === binding.source)) {
401
+ bindings.push(binding);
402
+ }
403
+ }
404
+ if (bindings.length !== 1) {
405
+ return {
406
+ code: "MULTIPLE_SOURCE_REFERENCES",
407
+ reason: "Static predicate references multiple source query blocks; moving it may change semantics."
408
+ };
409
+ }
410
+ const binding = bindings[0];
411
+ const nullableSide = this.findNullableSideBoundary(root.fromClause, binding);
412
+ if (nullableSide) {
413
+ return nullableSide;
414
+ }
415
+ const upstream = this.resolveUpstreamQuery(root, binding, candidate.references);
416
+ if ("code" in upstream) {
417
+ return upstream;
418
+ }
419
+ return upstream;
420
+ }
421
+ findRootQueryBoundary(query) {
422
+ if (this.hasDistinctOnBoundary(query)) {
423
+ return {
424
+ code: "DISTINCT_BOUNDARY",
425
+ reason: "Predicate crosses DISTINCT ON boundary; moving it may change semantics."
426
+ };
427
+ }
428
+ if (this.hasWindowUsage(query)) {
429
+ return {
430
+ code: "WINDOW_BOUNDARY",
431
+ reason: "Predicate crosses WINDOW boundary; moving it may change semantics."
432
+ };
433
+ }
434
+ return null;
435
+ }
436
+ resolveTargetPlacement(query, targetColumns) {
437
+ const hasOrdinaryDistinct = this.hasOrdinaryDistinct(query);
438
+ if (this.hasDistinctOnBoundary(query)) {
439
+ return {
440
+ code: "DISTINCT_BOUNDARY",
441
+ reason: "Predicate crosses DISTINCT ON boundary; moving it may change semantics."
442
+ };
443
+ }
444
+ if (this.hasWindowUsage(query)) {
445
+ return {
446
+ code: "WINDOW_BOUNDARY",
447
+ reason: "Predicate crosses WINDOW boundary; moving it may change semantics."
448
+ };
449
+ }
450
+ if (query.limitClause || query.offsetClause || query.fetchClause) {
451
+ return {
452
+ code: "ROW_LIMIT_BOUNDARY",
453
+ reason: "Predicate crosses LIMIT/OFFSET/FETCH boundary; moving it may change row selection semantics."
454
+ };
455
+ }
456
+ if (query.fromClause && this.hasOuterJoin(query.fromClause)) {
457
+ return {
458
+ code: "OUTER_JOIN_BOUNDARY",
459
+ reason: "Target query contains an OUTER JOIN boundary that is not moved across in the safe-only implementation."
460
+ };
461
+ }
462
+ if (query.groupByClause) {
463
+ const allReferencesAreGroupKeys = targetColumns.every(item => this.isGroupKeyColumn(query, item.targetColumn));
464
+ if (!allReferencesAreGroupKeys) {
465
+ return {
466
+ code: "GROUP_BY_BOUNDARY",
467
+ reason: "Predicate references a target column that is not proven to be a GROUP BY key."
468
+ };
469
+ }
470
+ return {
471
+ reason: "Predicate references only GROUP BY keys; it is moved into pre-aggregation WHERE."
472
+ };
473
+ }
474
+ if (query.havingClause) {
475
+ return {
476
+ code: "GROUP_BY_BOUNDARY",
477
+ reason: "Predicate crosses HAVING aggregation boundary; moving it may change semantics."
478
+ };
479
+ }
480
+ if (hasOrdinaryDistinct) {
481
+ return {
482
+ reason: "Predicate references direct ordinary DISTINCT output columns; it is moved into the DISTINCT input WHERE."
483
+ };
484
+ }
485
+ return {
486
+ reason: "All outer references resolve to direct upstream outputs before unsafe query boundaries."
487
+ };
488
+ }
489
+ resolveSourceBinding(contextRoot, query, column) {
490
+ const fromClause = query.fromClause;
491
+ if (!fromClause) {
492
+ return {
493
+ code: "NO_FROM_CLAUSE",
494
+ reason: "Predicate has no FROM source that can receive it safely."
495
+ };
496
+ }
497
+ const bindings = this.getSourceBindings(fromClause);
498
+ const namespace = normalizeIdentifier(column.getNamespace());
499
+ const columnName = column.column.name;
500
+ if (namespace) {
501
+ const matches = bindings.filter(binding => normalizeIdentifier(binding.alias) === namespace);
502
+ if (matches.length !== 1) {
503
+ return {
504
+ code: "AMBIGUOUS_COLUMN_SOURCE",
505
+ reason: `Column source alias '${column.getNamespace()}' is not uniquely resolvable.`
506
+ };
507
+ }
508
+ const matchCount = this.getOutputColumnMatchCount(contextRoot, matches[0], columnName);
509
+ if (matchCount === 0) {
510
+ return {
511
+ code: "COLUMN_NOT_AVAILABLE_UPSTREAM",
512
+ reason: `Column '${columnReferenceText(column)}' is not a direct output of the referenced source.`
513
+ };
514
+ }
515
+ if (matchCount > 1) {
516
+ return {
517
+ code: "AMBIGUOUS_COLUMN_REFERENCE",
518
+ reason: `Column '${columnReferenceText(column)}' resolves to multiple outputs in the referenced source.`
519
+ };
520
+ }
521
+ return matches[0];
522
+ }
523
+ const matches = [];
524
+ for (const binding of bindings) {
525
+ const matchCount = this.getOutputColumnMatchCount(contextRoot, binding, columnName);
526
+ if (matchCount > 1) {
527
+ return {
528
+ code: "AMBIGUOUS_COLUMN_REFERENCE",
529
+ reason: `Column '${columnName}' resolves to multiple outputs in source '${binding.alias}'.`
530
+ };
531
+ }
532
+ if (matchCount === 1) {
533
+ matches.push(binding);
534
+ }
535
+ }
536
+ if (matches.length !== 1) {
537
+ return {
538
+ code: "AMBIGUOUS_COLUMN_REFERENCE",
539
+ reason: matches.length === 0
540
+ ? `Column '${columnName}' is not uniquely resolvable to a safe upstream source.`
541
+ : `Column '${columnName}' is ambiguous across source query blocks.`
542
+ };
543
+ }
544
+ return matches[0];
545
+ }
546
+ resolveUpstreamQuery(root, binding, references) {
547
+ const source = binding.source.datasource;
548
+ if (source instanceof Clause_1.SubQuerySource) {
549
+ if (source.query instanceof SelectQuery_1.SimpleSelectQuery) {
550
+ return {
551
+ kind: "simple",
552
+ query: source.query,
553
+ scopeId: `subquery:${binding.alias}`,
554
+ sourceBinding: binding
555
+ };
556
+ }
557
+ if (source.query instanceof SelectQuery_1.BinarySelectQuery) {
558
+ return this.resolveUnionTarget(root, source.query, `subquery:${binding.alias}`, references);
559
+ }
560
+ return {
561
+ code: "UNION_BOUNDARY",
562
+ reason: "Predicate would need distribution into a UNION or non-simple subquery, which is unsupported."
563
+ };
564
+ }
565
+ if (!(source instanceof Clause_1.TableSource)) {
566
+ return {
567
+ code: "UNSUPPORTED_SOURCE",
568
+ reason: "Only CTE and simple derived-table sources can receive moved static predicates."
569
+ };
570
+ }
571
+ const cteName = source.table.name;
572
+ const commonTable = this.findCte(root, cteName);
573
+ if (!commonTable) {
574
+ return {
575
+ code: "NO_SAFE_UPSTREAM_QUERY",
576
+ reason: "The referenced source is a base table, so there is no upstream query block to move into."
577
+ };
578
+ }
579
+ const referenceCount = this.countTableSourceReferences(root, cteName);
580
+ if (referenceCount !== 1) {
581
+ return {
582
+ code: "CTE_REUSE_UNSUPPORTED",
583
+ reason: `CTE '${cteName}' is referenced ${referenceCount} times; moving a predicate into it may affect other consumers.`
584
+ };
585
+ }
586
+ if (commonTable.query instanceof SelectQuery_1.BinarySelectQuery) {
587
+ return this.resolveUnionTarget(root, commonTable.query, `cte:${commonTable.getSourceAliasName()}`, references);
588
+ }
589
+ if (!(commonTable.query instanceof SelectQuery_1.SimpleSelectQuery)) {
590
+ return {
591
+ code: "UNSUPPORTED_CTE_QUERY",
592
+ reason: "Writable or non-select CTE bodies are not moved into by static predicate placement."
593
+ };
594
+ }
595
+ return {
596
+ kind: "simple",
597
+ query: commonTable.query,
598
+ scopeId: `cte:${commonTable.getSourceAliasName()}`,
599
+ sourceBinding: binding,
600
+ cteName: commonTable.getSourceAliasName()
601
+ };
602
+ }
603
+ resolveUnionTarget(root, query, scopeId, references) {
604
+ const branches = this.collectUnionBranches(query);
605
+ if ("code" in branches) {
606
+ return branches;
607
+ }
608
+ const outputIndexes = new Map();
609
+ for (const reference of references) {
610
+ const outputIndex = this.resolveUnionOutputIndex(root, branches[0], reference.column.name);
611
+ if ("code" in outputIndex) {
612
+ return outputIndex;
613
+ }
614
+ outputIndexes.set(reference, outputIndex.index);
615
+ }
616
+ const branchTargets = [];
617
+ for (const branch of branches) {
618
+ const targetColumns = [];
619
+ for (const [reference, outputIndex] of outputIndexes.entries()) {
620
+ const targetColumn = this.resolveTargetColumnByOutputIndex(root, branch, outputIndex, reference);
621
+ if ("code" in targetColumn) {
622
+ return targetColumn;
623
+ }
624
+ targetColumns.push(targetColumn);
625
+ }
626
+ branchTargets.push(this.resolveDeepestBranchTarget(root, branch, targetColumns));
627
+ }
628
+ return {
629
+ kind: "union",
630
+ scopeId,
631
+ branches: branchTargets
632
+ };
633
+ }
634
+ resolveTargetColumns(root, query, references) {
635
+ const resolved = [];
636
+ for (const reference of references) {
637
+ const matches = this.collectSelectOutputs(root, query).filter(item => normalizeIdentifier(item.name) === normalizeIdentifier(reference.column.name));
638
+ if (matches.length !== 1) {
639
+ return {
640
+ code: "AMBIGUOUS_TARGET_COLUMN",
641
+ reason: matches.length === 0
642
+ ? `Target query does not expose '${reference.column.name}' as a direct output column.`
643
+ : `Target query exposes multiple '${reference.column.name}' columns.`
644
+ };
645
+ }
646
+ const value = matches[0].value;
647
+ if (!(value instanceof ValueComponent_1.ColumnReference)) {
648
+ return {
649
+ code: "EXPRESSION_OUTPUT_UNSUPPORTED",
650
+ reason: `Target output '${reference.column.name}' is an expression, not a direct column reference.`
651
+ };
652
+ }
653
+ const sourceResolution = this.verifyColumnResolvableInQuery(query, value);
654
+ if (sourceResolution) {
655
+ return sourceResolution;
656
+ }
657
+ resolved.push({
658
+ sourceColumn: reference,
659
+ targetColumn: value
660
+ });
661
+ }
662
+ return resolved;
663
+ }
664
+ resolveDeepestBranchTarget(contextRoot, query, targetColumns, visited = new Set()) {
665
+ if (visited.has(query) || targetColumns.length === 0) {
666
+ return { query, targetColumns: [...targetColumns] };
667
+ }
668
+ const nextVisited = new Set(visited);
669
+ nextVisited.add(query);
670
+ const bindings = [];
671
+ for (const item of targetColumns) {
672
+ const binding = this.resolveSourceBinding(contextRoot, query, item.targetColumn);
673
+ if ("code" in binding) {
674
+ return { query, targetColumns: [...targetColumns] };
675
+ }
676
+ if (!bindings.some(existing => existing.source === binding.source)) {
677
+ bindings.push(binding);
678
+ }
679
+ }
680
+ if (bindings.length !== 1) {
681
+ return { query, targetColumns: [...targetColumns] };
682
+ }
683
+ const binding = bindings[0];
684
+ const nullableSide = query.fromClause
685
+ ? this.findNullableSideBoundary(query.fromClause, binding)
686
+ : null;
687
+ if (nullableSide) {
688
+ return { query, targetColumns: [...targetColumns] };
689
+ }
690
+ const upstream = this.resolveUpstreamQuery(contextRoot, binding, targetColumns.map(item => item.targetColumn));
691
+ if ("code" in upstream || upstream.kind === "union") {
692
+ return { query, targetColumns: [...targetColumns] };
693
+ }
694
+ const upstreamColumns = this.resolveTargetColumns(contextRoot, upstream.query, targetColumns.map(item => item.targetColumn));
695
+ if ("code" in upstreamColumns) {
696
+ return { query, targetColumns: [...targetColumns] };
697
+ }
698
+ const placement = this.resolveTargetPlacement(upstream.query, upstreamColumns);
699
+ if ("code" in placement) {
700
+ return { query, targetColumns: [...targetColumns] };
701
+ }
702
+ const rebasedColumns = upstreamColumns.map((item, index) => ({
703
+ sourceColumn: targetColumns[index].sourceColumn,
704
+ targetColumn: item.targetColumn
705
+ }));
706
+ return this.resolveDeepestBranchTarget(contextRoot, upstream.query, rebasedColumns, nextVisited);
707
+ }
708
+ verifyColumnResolvableInQuery(query, column) {
709
+ if (!query.fromClause) {
710
+ return {
711
+ code: "NO_TARGET_FROM_CLAUSE",
712
+ reason: "Target query has no FROM clause where the moved column can be resolved."
713
+ };
714
+ }
715
+ const bindings = this.getSourceBindings(query.fromClause);
716
+ const namespace = normalizeIdentifier(column.getNamespace());
717
+ if (namespace) {
718
+ const matches = bindings.filter(binding => normalizeIdentifier(binding.alias) === namespace);
719
+ return matches.length === 1
720
+ ? null
721
+ : {
722
+ code: "AMBIGUOUS_TARGET_COLUMN",
723
+ reason: `Target column '${columnReferenceText(column)}' is not uniquely resolvable in the destination query.`
724
+ };
725
+ }
726
+ if (bindings.length === 1) {
727
+ return null;
728
+ }
729
+ return {
730
+ code: "AMBIGUOUS_TARGET_COLUMN",
731
+ reason: `Unqualified target column '${column.column.name}' is ambiguous in a multi-source destination query.`
732
+ };
733
+ }
734
+ isGroupKeyColumn(query, column) {
735
+ const groupBy = query.groupByClause;
736
+ if (!groupBy || groupBy.mode || groupBy.grouping.length === 0) {
737
+ return false;
738
+ }
739
+ return groupBy.grouping.some(grouping => {
740
+ const candidate = unwrapParens(grouping);
741
+ return candidate instanceof ValueComponent_1.ColumnReference
742
+ && this.sameResolvableColumnInQuery(query, candidate, column);
743
+ });
744
+ }
745
+ sameResolvableColumnInQuery(query, left, right) {
746
+ if (sameColumnReference(left, right)) {
747
+ return true;
748
+ }
749
+ if (normalizeIdentifier(left.column.name) !== normalizeIdentifier(right.column.name)) {
750
+ return false;
751
+ }
752
+ const leftSource = this.resolveColumnSourceAlias(query, left);
753
+ const rightSource = this.resolveColumnSourceAlias(query, right);
754
+ return leftSource !== null && leftSource === rightSource;
755
+ }
756
+ resolveColumnSourceAlias(query, column) {
757
+ if (!query.fromClause) {
758
+ return null;
759
+ }
760
+ const bindings = this.getSourceBindings(query.fromClause);
761
+ const namespace = normalizeIdentifier(column.getNamespace());
762
+ if (namespace) {
763
+ const matches = bindings.filter(binding => normalizeIdentifier(binding.alias) === namespace);
764
+ return matches.length === 1 ? normalizeIdentifier(matches[0].alias) : null;
765
+ }
766
+ return bindings.length === 1 ? normalizeIdentifier(bindings[0].alias) : null;
767
+ }
768
+ rebasePredicate(expression, targetColumns, options) {
769
+ const cloned = cloneValueComponent(expression, options);
770
+ const visitSelect = (query, inheritedLocalAliases) => {
771
+ var _a, _b, _c, _d;
772
+ if (!(query instanceof SelectQuery_1.SimpleSelectQuery)) {
773
+ return;
774
+ }
775
+ const localAliases = new Set(inheritedLocalAliases);
776
+ for (const alias of this.collectSourceAliases(query)) {
777
+ localAliases.add(alias);
778
+ }
779
+ query.selectClause.items.forEach(item => visit(item.value, localAliases));
780
+ for (const join of (_b = (_a = query.fromClause) === null || _a === void 0 ? void 0 : _a.joins) !== null && _b !== void 0 ? _b : []) {
781
+ if (join.condition) {
782
+ visit(join.condition.condition, localAliases);
783
+ }
784
+ const source = join.source.datasource;
785
+ if (source instanceof Clause_1.SubQuerySource) {
786
+ visitSelect(source.query, localAliases);
787
+ }
788
+ }
789
+ if (query.whereClause) {
790
+ visit(query.whereClause.condition, localAliases);
791
+ }
792
+ if (query.havingClause) {
793
+ visit(query.havingClause.condition, localAliases);
794
+ }
795
+ for (const cte of (_d = (_c = query.withClause) === null || _c === void 0 ? void 0 : _c.tables) !== null && _d !== void 0 ? _d : []) {
796
+ if (cte.query instanceof SelectQuery_1.SimpleSelectQuery || cte.query instanceof SelectQuery_1.BinarySelectQuery) {
797
+ visitSelect(cte.query, localAliases);
798
+ }
799
+ }
800
+ };
801
+ const visit = (value, localAliases) => {
802
+ const candidate = unwrapParens(value);
803
+ if (candidate instanceof ValueComponent_1.ColumnReference) {
804
+ const namespace = normalizeIdentifier(candidate.getNamespace());
805
+ if (namespace && localAliases.has(namespace)) {
806
+ return;
807
+ }
808
+ const target = targetColumns.find(item => sameColumnReference(candidate, item.sourceColumn));
809
+ if (target) {
810
+ candidate.qualifiedName = cloneColumnReference(target.targetColumn).qualifiedName;
811
+ }
812
+ return;
813
+ }
814
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
815
+ visit(candidate.left, localAliases);
816
+ visit(candidate.right, localAliases);
817
+ return;
818
+ }
819
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
820
+ visit(candidate.expression, localAliases);
821
+ return;
822
+ }
823
+ if (candidate instanceof ValueComponent_1.InlineQuery) {
824
+ visitSelect(candidate.selectQuery, localAliases);
825
+ return;
826
+ }
827
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
828
+ if (candidate.argument) {
829
+ visit(candidate.argument, localAliases);
830
+ }
831
+ if (candidate.filterCondition) {
832
+ visit(candidate.filterCondition, localAliases);
833
+ }
834
+ return;
835
+ }
836
+ if (candidate instanceof ValueComponent_1.CastExpression) {
837
+ visit(candidate.input, localAliases);
838
+ return;
839
+ }
840
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
841
+ if (candidate.condition) {
842
+ visit(candidate.condition, localAliases);
843
+ }
844
+ for (const pair of candidate.switchCase.cases) {
845
+ visit(pair.key, localAliases);
846
+ visit(pair.value, localAliases);
847
+ }
848
+ if (candidate.switchCase.elseValue) {
849
+ visit(candidate.switchCase.elseValue, localAliases);
850
+ }
851
+ return;
852
+ }
853
+ if (candidate instanceof ValueComponent_1.BetweenExpression) {
854
+ visit(candidate.expression, localAliases);
855
+ visit(candidate.lower, localAliases);
856
+ visit(candidate.upper, localAliases);
857
+ return;
858
+ }
859
+ if (candidate instanceof ValueComponent_1.JsonPredicateExpression) {
860
+ visit(candidate.expression, localAliases);
861
+ return;
862
+ }
863
+ if (candidate instanceof ValueComponent_1.ArrayExpression) {
864
+ visit(candidate.expression, localAliases);
865
+ return;
866
+ }
867
+ if (candidate instanceof ValueComponent_1.ValueList) {
868
+ candidate.values.forEach(item => visit(item, localAliases));
869
+ return;
870
+ }
871
+ if (candidate instanceof ValueComponent_1.TupleExpression) {
872
+ candidate.values.forEach(item => visit(item, localAliases));
873
+ return;
874
+ }
875
+ if (candidate instanceof ValueComponent_1.TypeValue && candidate.argument) {
876
+ visit(candidate.argument, localAliases);
877
+ }
878
+ };
879
+ visit(cloned, new Set());
880
+ return cloned;
881
+ }
882
+ getSourceBindings(fromClause) {
883
+ var _a, _b, _c;
884
+ const bindings = [{
885
+ source: fromClause.source,
886
+ alias: (_a = fromClause.source.getAliasName()) !== null && _a !== void 0 ? _a : "",
887
+ join: null,
888
+ joinIndex: -1,
889
+ isPrimary: true
890
+ }];
891
+ for (let index = 0; index < ((_b = fromClause.joins) !== null && _b !== void 0 ? _b : []).length; index += 1) {
892
+ const join = fromClause.joins[index];
893
+ bindings.push({
894
+ source: join.source,
895
+ alias: (_c = join.source.getAliasName()) !== null && _c !== void 0 ? _c : "",
896
+ join,
897
+ joinIndex: index,
898
+ isPrimary: false
899
+ });
900
+ }
901
+ return bindings;
902
+ }
903
+ findNullableSideBoundary(fromClause, binding) {
904
+ var _a;
905
+ const joins = (_a = fromClause.joins) !== null && _a !== void 0 ? _a : [];
906
+ if (binding.isPrimary) {
907
+ return this.hasLaterJoinThatNullsPriorSources(joins, -1)
908
+ ? {
909
+ code: "OUTER_JOIN_NULLABLE_SIDE",
910
+ reason: "Predicate crosses OUTER JOIN nullable side; moving it may change semantics."
911
+ }
912
+ : null;
913
+ }
914
+ const join = binding.join;
915
+ if (!join) {
916
+ return null;
917
+ }
918
+ const joinType = join.joinType.value.toLowerCase();
919
+ if (joinType.includes("left")) {
920
+ return {
921
+ code: "OUTER_JOIN_NULLABLE_SIDE",
922
+ reason: "Predicate crosses LEFT JOIN nullable side; moving it may change semantics."
923
+ };
924
+ }
925
+ if (joinType.includes("full")) {
926
+ return {
927
+ code: "OUTER_JOIN_NULLABLE_SIDE",
928
+ reason: "Predicate crosses FULL JOIN nullable side; moving it may change semantics."
929
+ };
930
+ }
931
+ if (this.hasLaterJoinThatNullsPriorSources(joins, binding.joinIndex)) {
932
+ return {
933
+ code: "OUTER_JOIN_NULLABLE_SIDE",
934
+ reason: "Predicate crosses later RIGHT/FULL JOIN nullable side; moving it may change semantics."
935
+ };
936
+ }
937
+ return null;
938
+ }
939
+ hasLaterJoinThatNullsPriorSources(joins, sourceJoinIndex) {
940
+ return joins
941
+ .slice(sourceJoinIndex + 1)
942
+ .some(join => {
943
+ const joinType = join.joinType.value.toLowerCase();
944
+ return joinType.includes("right") || joinType.includes("full");
945
+ });
946
+ }
947
+ hasOuterJoin(fromClause) {
948
+ var _a;
949
+ return ((_a = fromClause.joins) !== null && _a !== void 0 ? _a : []).some(join => {
950
+ const joinType = join.joinType.value.toLowerCase();
951
+ return joinType.includes("left") || joinType.includes("right") || joinType.includes("full") || joinType.includes("outer");
952
+ });
953
+ }
954
+ hasDistinctOnBoundary(query) {
955
+ return query.selectClause.distinct instanceof Clause_1.DistinctOn;
956
+ }
957
+ hasOrdinaryDistinct(query) {
958
+ return query.selectClause.distinct !== null && !this.hasDistinctOnBoundary(query);
959
+ }
960
+ getOutputColumnMatchCount(root, binding, columnName) {
961
+ const target = this.resolveSourceQueryForColumns(root, binding.source);
962
+ if (!target) {
963
+ return 0;
964
+ }
965
+ if (target instanceof SelectQuery_1.BinarySelectQuery) {
966
+ const branches = this.collectUnionBranches(target);
967
+ if ("code" in branches) {
968
+ return 0;
969
+ }
970
+ return this.collectSelectOutputs(root, branches[0]).filter(item => normalizeIdentifier(item.name) === normalizeIdentifier(columnName)).length;
971
+ }
972
+ if (!(target instanceof SelectQuery_1.SimpleSelectQuery)) {
973
+ return 0;
974
+ }
975
+ return this.collectSelectOutputs(root, target).filter(item => normalizeIdentifier(item.name) === normalizeIdentifier(columnName)).length;
976
+ }
977
+ collectUnionBranches(query) {
978
+ const branches = [];
979
+ const visit = (select) => {
980
+ var _a;
981
+ if (select instanceof SelectQuery_1.SimpleSelectQuery) {
982
+ branches.push(select);
983
+ return null;
984
+ }
985
+ if (!(select instanceof SelectQuery_1.BinarySelectQuery)) {
986
+ return {
987
+ code: "UNION_BOUNDARY",
988
+ reason: "Predicate would need distribution into a non-simple UNION branch, which is unsupported."
989
+ };
990
+ }
991
+ const operator = select.operator.value.trim().toLowerCase();
992
+ if (operator !== "union" && operator !== "union all") {
993
+ return {
994
+ code: "UNION_BOUNDARY",
995
+ reason: `Predicate would need distribution through '${select.operator.value}', which is unsupported.`
996
+ };
997
+ }
998
+ return (_a = visit(select.left)) !== null && _a !== void 0 ? _a : visit(select.right);
999
+ };
1000
+ const skip = visit(query);
1001
+ return skip !== null && skip !== void 0 ? skip : branches;
1002
+ }
1003
+ resolveUnionOutputIndex(root, firstBranch, outputColumnName) {
1004
+ const matches = [];
1005
+ this.collectSelectOutputs(root, firstBranch).forEach((item, index) => {
1006
+ if (normalizeIdentifier(item.name) === normalizeIdentifier(outputColumnName)) {
1007
+ matches.push(index);
1008
+ }
1009
+ });
1010
+ if (matches.length !== 1) {
1011
+ return {
1012
+ code: "AMBIGUOUS_TARGET_COLUMN",
1013
+ reason: matches.length === 0
1014
+ ? `UNION output does not expose '${outputColumnName}' from its first branch.`
1015
+ : `UNION first branch exposes multiple '${outputColumnName}' columns.`
1016
+ };
1017
+ }
1018
+ return { index: matches[0] };
1019
+ }
1020
+ resolveTargetColumnByOutputIndex(root, query, outputIndex, sourceColumn) {
1021
+ const output = this.collectSelectOutputs(root, query)[outputIndex];
1022
+ if (!output) {
1023
+ return {
1024
+ code: "UNION_COLUMN_MISMATCH",
1025
+ reason: `UNION branch does not expose column '${sourceColumn.column.name}' at output position ${outputIndex + 1}.`
1026
+ };
1027
+ }
1028
+ if (!(output.value instanceof ValueComponent_1.ColumnReference)) {
1029
+ return {
1030
+ code: "EXPRESSION_OUTPUT_UNSUPPORTED",
1031
+ reason: `UNION branch output at position ${outputIndex + 1} for '${sourceColumn.column.name}' is an expression, not a direct column reference.`
1032
+ };
1033
+ }
1034
+ const sourceResolution = this.verifyColumnResolvableInQuery(query, output.value);
1035
+ if (sourceResolution) {
1036
+ return sourceResolution;
1037
+ }
1038
+ return {
1039
+ sourceColumn,
1040
+ targetColumn: output.value
1041
+ };
1042
+ }
1043
+ collectSelectOutputs(root, query) {
1044
+ var _a, _b, _c, _d;
1045
+ const commonTables = [
1046
+ ...((_b = (_a = query.withClause) === null || _a === void 0 ? void 0 : _a.tables) !== null && _b !== void 0 ? _b : []),
1047
+ ...((_d = (_c = root.withClause) === null || _c === void 0 ? void 0 : _c.tables) !== null && _d !== void 0 ? _d : [])
1048
+ ];
1049
+ const collector = new SelectOutputCollector_1.SelectOutputCollector(null, commonTables.length > 0 ? commonTables : null);
1050
+ return collector.collect(query);
1051
+ }
1052
+ resolveSourceQueryForColumns(root, source) {
1053
+ var _a;
1054
+ if (source.datasource instanceof Clause_1.SubQuerySource) {
1055
+ return source.datasource.query;
1056
+ }
1057
+ if (source.datasource instanceof Clause_1.TableSource) {
1058
+ const cteQuery = (_a = this.findCte(root, source.datasource.table.name)) === null || _a === void 0 ? void 0 : _a.query;
1059
+ return cteQuery instanceof SelectQuery_1.SimpleSelectQuery || cteQuery instanceof SelectQuery_1.BinarySelectQuery
1060
+ ? cteQuery
1061
+ : null;
1062
+ }
1063
+ return null;
1064
+ }
1065
+ findCte(root, name) {
1066
+ var _a, _b;
1067
+ const normalized = normalizeIdentifier(name);
1068
+ const matches = ((_b = (_a = root.withClause) === null || _a === void 0 ? void 0 : _a.tables) !== null && _b !== void 0 ? _b : [])
1069
+ .filter(table => normalizeIdentifier(table.getSourceAliasName()) === normalized);
1070
+ return matches.length === 1 ? matches[0] : null;
1071
+ }
1072
+ countTableSourceReferences(query, tableName) {
1073
+ const normalized = normalizeIdentifier(tableName);
1074
+ let count = 0;
1075
+ const visitSelect = (select) => {
1076
+ var _a, _b;
1077
+ if (select instanceof SelectQuery_1.BinarySelectQuery) {
1078
+ visitSelect(select.left);
1079
+ visitSelect(select.right);
1080
+ return;
1081
+ }
1082
+ if (!(select instanceof SelectQuery_1.SimpleSelectQuery)) {
1083
+ return;
1084
+ }
1085
+ if (select.fromClause) {
1086
+ for (const binding of this.getSourceBindings(select.fromClause)) {
1087
+ const source = binding.source.datasource;
1088
+ if (source instanceof Clause_1.TableSource && normalizeIdentifier(source.table.name) === normalized) {
1089
+ count += 1;
1090
+ }
1091
+ if (source instanceof Clause_1.SubQuerySource) {
1092
+ visitSelect(source.query);
1093
+ }
1094
+ }
1095
+ }
1096
+ for (const cte of (_b = (_a = select.withClause) === null || _a === void 0 ? void 0 : _a.tables) !== null && _b !== void 0 ? _b : []) {
1097
+ if (cte.query instanceof SelectQuery_1.SimpleSelectQuery || cte.query instanceof SelectQuery_1.BinarySelectQuery) {
1098
+ visitSelect(cte.query);
1099
+ }
1100
+ }
1101
+ };
1102
+ visitSelect(query);
1103
+ return count;
1104
+ }
1105
+ collectSourceAliases(query) {
1106
+ var _a, _b;
1107
+ const aliases = new Set();
1108
+ for (const source of (_b = (_a = query.fromClause) === null || _a === void 0 ? void 0 : _a.getSources()) !== null && _b !== void 0 ? _b : []) {
1109
+ const alias = source.getAliasName();
1110
+ if (alias) {
1111
+ aliases.add(normalizeIdentifier(alias));
1112
+ }
1113
+ }
1114
+ return aliases;
1115
+ }
1116
+ collectRootColumnReferences(root, expression) {
1117
+ const references = [];
1118
+ const rootAliases = this.collectSourceAliases(root);
1119
+ const visitSelect = (query, inheritedLocalAliases) => {
1120
+ var _a, _b, _c, _d;
1121
+ if (!(query instanceof SelectQuery_1.SimpleSelectQuery)) {
1122
+ return;
1123
+ }
1124
+ const localAliases = new Set(inheritedLocalAliases);
1125
+ for (const alias of this.collectSourceAliases(query)) {
1126
+ localAliases.add(alias);
1127
+ }
1128
+ query.selectClause.items.forEach(item => visit(item.value, localAliases));
1129
+ for (const join of (_b = (_a = query.fromClause) === null || _a === void 0 ? void 0 : _a.joins) !== null && _b !== void 0 ? _b : []) {
1130
+ if (join.condition) {
1131
+ visit(join.condition.condition, localAliases);
1132
+ }
1133
+ const source = join.source.datasource;
1134
+ if (source instanceof Clause_1.SubQuerySource) {
1135
+ visitSelect(source.query, localAliases);
1136
+ }
1137
+ }
1138
+ if (query.whereClause) {
1139
+ visit(query.whereClause.condition, localAliases);
1140
+ }
1141
+ if (query.havingClause) {
1142
+ visit(query.havingClause.condition, localAliases);
1143
+ }
1144
+ for (const cte of (_d = (_c = query.withClause) === null || _c === void 0 ? void 0 : _c.tables) !== null && _d !== void 0 ? _d : []) {
1145
+ if (cte.query instanceof SelectQuery_1.SimpleSelectQuery || cte.query instanceof SelectQuery_1.BinarySelectQuery) {
1146
+ visitSelect(cte.query, localAliases);
1147
+ }
1148
+ }
1149
+ };
1150
+ const collect = (reference) => {
1151
+ if (!references.some(existing => sameColumnReference(existing, reference))) {
1152
+ references.push(reference);
1153
+ }
1154
+ };
1155
+ const visit = (value, localAliases) => {
1156
+ const candidate = unwrapParens(value);
1157
+ if (candidate instanceof ValueComponent_1.ColumnReference) {
1158
+ const namespace = normalizeIdentifier(candidate.getNamespace());
1159
+ if (namespace) {
1160
+ if (rootAliases.has(namespace) && !localAliases.has(namespace)) {
1161
+ collect(candidate);
1162
+ }
1163
+ return;
1164
+ }
1165
+ if (localAliases.size === 0) {
1166
+ collect(candidate);
1167
+ }
1168
+ return;
1169
+ }
1170
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
1171
+ visit(candidate.left, localAliases);
1172
+ visit(candidate.right, localAliases);
1173
+ return;
1174
+ }
1175
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
1176
+ visit(candidate.expression, localAliases);
1177
+ return;
1178
+ }
1179
+ if (candidate instanceof ValueComponent_1.InlineQuery) {
1180
+ visitSelect(candidate.selectQuery, localAliases);
1181
+ return;
1182
+ }
1183
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
1184
+ if (candidate.argument) {
1185
+ visit(candidate.argument, localAliases);
1186
+ }
1187
+ if (candidate.filterCondition) {
1188
+ visit(candidate.filterCondition, localAliases);
1189
+ }
1190
+ return;
1191
+ }
1192
+ if (candidate instanceof ValueComponent_1.CastExpression) {
1193
+ visit(candidate.input, localAliases);
1194
+ return;
1195
+ }
1196
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
1197
+ if (candidate.condition) {
1198
+ visit(candidate.condition, localAliases);
1199
+ }
1200
+ for (const pair of candidate.switchCase.cases) {
1201
+ visit(pair.key, localAliases);
1202
+ visit(pair.value, localAliases);
1203
+ }
1204
+ if (candidate.switchCase.elseValue) {
1205
+ visit(candidate.switchCase.elseValue, localAliases);
1206
+ }
1207
+ return;
1208
+ }
1209
+ if (candidate instanceof ValueComponent_1.BetweenExpression) {
1210
+ visit(candidate.expression, localAliases);
1211
+ visit(candidate.lower, localAliases);
1212
+ visit(candidate.upper, localAliases);
1213
+ return;
1214
+ }
1215
+ if (candidate instanceof ValueComponent_1.JsonPredicateExpression) {
1216
+ visit(candidate.expression, localAliases);
1217
+ return;
1218
+ }
1219
+ if (candidate instanceof ValueComponent_1.ArrayExpression) {
1220
+ visit(candidate.expression, localAliases);
1221
+ return;
1222
+ }
1223
+ if (candidate instanceof ValueComponent_1.ArrayQueryExpression) {
1224
+ visitSelect(candidate.query, localAliases);
1225
+ return;
1226
+ }
1227
+ if (candidate instanceof ValueComponent_1.ValueList) {
1228
+ candidate.values.forEach(item => visit(item, localAliases));
1229
+ return;
1230
+ }
1231
+ if (candidate instanceof ValueComponent_1.TupleExpression) {
1232
+ candidate.values.forEach(item => visit(item, localAliases));
1233
+ return;
1234
+ }
1235
+ if (candidate instanceof ValueComponent_1.TypeValue && candidate.argument) {
1236
+ visit(candidate.argument, localAliases);
1237
+ }
1238
+ };
1239
+ visit(expression, new Set());
1240
+ return references;
1241
+ }
1242
+ hasWindowUsage(query) {
1243
+ if (query.windowClause) {
1244
+ return true;
1245
+ }
1246
+ let found = false;
1247
+ const visit = (value) => {
1248
+ if (found) {
1249
+ return;
1250
+ }
1251
+ const candidate = unwrapParens(value);
1252
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
1253
+ if (candidate.over) {
1254
+ found = true;
1255
+ return;
1256
+ }
1257
+ if (candidate.argument) {
1258
+ visit(candidate.argument);
1259
+ }
1260
+ if (candidate.filterCondition) {
1261
+ visit(candidate.filterCondition);
1262
+ }
1263
+ return;
1264
+ }
1265
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
1266
+ visit(candidate.left);
1267
+ visit(candidate.right);
1268
+ return;
1269
+ }
1270
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
1271
+ visit(candidate.expression);
1272
+ return;
1273
+ }
1274
+ if (candidate instanceof ValueComponent_1.CastExpression) {
1275
+ visit(candidate.input);
1276
+ return;
1277
+ }
1278
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
1279
+ if (candidate.condition) {
1280
+ visit(candidate.condition);
1281
+ }
1282
+ for (const pair of candidate.switchCase.cases) {
1283
+ visit(pair.key);
1284
+ visit(pair.value);
1285
+ }
1286
+ if (candidate.switchCase.elseValue) {
1287
+ visit(candidate.switchCase.elseValue);
1288
+ }
1289
+ return;
1290
+ }
1291
+ if (candidate instanceof ValueComponent_1.ValueList) {
1292
+ candidate.values.forEach(visit);
1293
+ }
1294
+ };
1295
+ query.selectClause.items.forEach(item => visit(item.value));
1296
+ return found;
1297
+ }
1298
+ collectParameterNames(expression) {
1299
+ const names = [];
1300
+ const visitSelect = (query) => {
1301
+ var _a, _b, _c, _d;
1302
+ if (query instanceof SelectQuery_1.BinarySelectQuery) {
1303
+ visitSelect(query.left);
1304
+ visitSelect(query.right);
1305
+ return;
1306
+ }
1307
+ if (!(query instanceof SelectQuery_1.SimpleSelectQuery)) {
1308
+ return;
1309
+ }
1310
+ query.selectClause.items.forEach(item => visit(item.value));
1311
+ for (const join of (_b = (_a = query.fromClause) === null || _a === void 0 ? void 0 : _a.joins) !== null && _b !== void 0 ? _b : []) {
1312
+ if (join.condition) {
1313
+ visit(join.condition.condition);
1314
+ }
1315
+ const source = join.source.datasource;
1316
+ if (source instanceof Clause_1.SubQuerySource) {
1317
+ visitSelect(source.query);
1318
+ }
1319
+ }
1320
+ if (query.whereClause) {
1321
+ visit(query.whereClause.condition);
1322
+ }
1323
+ if (query.havingClause) {
1324
+ visit(query.havingClause.condition);
1325
+ }
1326
+ for (const cte of (_d = (_c = query.withClause) === null || _c === void 0 ? void 0 : _c.tables) !== null && _d !== void 0 ? _d : []) {
1327
+ if (cte.query instanceof SelectQuery_1.SimpleSelectQuery || cte.query instanceof SelectQuery_1.BinarySelectQuery) {
1328
+ visitSelect(cte.query);
1329
+ }
1330
+ }
1331
+ };
1332
+ const visit = (value) => {
1333
+ const candidate = unwrapParens(value);
1334
+ if (candidate instanceof ValueComponent_1.ParameterExpression) {
1335
+ appendUnique(names, candidate.name.value);
1336
+ return;
1337
+ }
1338
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
1339
+ visit(candidate.left);
1340
+ visit(candidate.right);
1341
+ return;
1342
+ }
1343
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
1344
+ visit(candidate.expression);
1345
+ return;
1346
+ }
1347
+ if (candidate instanceof ValueComponent_1.InlineQuery) {
1348
+ visitSelect(candidate.selectQuery);
1349
+ return;
1350
+ }
1351
+ if (candidate instanceof ValueComponent_1.ArrayQueryExpression) {
1352
+ visitSelect(candidate.query);
1353
+ return;
1354
+ }
1355
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
1356
+ if (candidate.argument) {
1357
+ visit(candidate.argument);
1358
+ }
1359
+ if (candidate.filterCondition) {
1360
+ visit(candidate.filterCondition);
1361
+ }
1362
+ return;
1363
+ }
1364
+ if (candidate instanceof ValueComponent_1.CastExpression) {
1365
+ visit(candidate.input);
1366
+ return;
1367
+ }
1368
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
1369
+ if (candidate.condition) {
1370
+ visit(candidate.condition);
1371
+ }
1372
+ for (const pair of candidate.switchCase.cases) {
1373
+ visit(pair.key);
1374
+ visit(pair.value);
1375
+ }
1376
+ if (candidate.switchCase.elseValue) {
1377
+ visit(candidate.switchCase.elseValue);
1378
+ }
1379
+ return;
1380
+ }
1381
+ if (candidate instanceof ValueComponent_1.BetweenExpression) {
1382
+ visit(candidate.expression);
1383
+ visit(candidate.lower);
1384
+ visit(candidate.upper);
1385
+ return;
1386
+ }
1387
+ if (candidate instanceof ValueComponent_1.JsonPredicateExpression) {
1388
+ visit(candidate.expression);
1389
+ return;
1390
+ }
1391
+ if (candidate instanceof ValueComponent_1.ArrayExpression) {
1392
+ visit(candidate.expression);
1393
+ return;
1394
+ }
1395
+ if (candidate instanceof ValueComponent_1.ValueList) {
1396
+ candidate.values.forEach(visit);
1397
+ return;
1398
+ }
1399
+ if (candidate instanceof ValueComponent_1.TupleExpression) {
1400
+ candidate.values.forEach(visit);
1401
+ return;
1402
+ }
1403
+ if (candidate instanceof ValueComponent_1.TypeValue && candidate.argument) {
1404
+ visit(candidate.argument);
1405
+ }
1406
+ };
1407
+ visit(expression);
1408
+ return names;
1409
+ }
1410
+ makeSkipped(expression, draft, options) {
1411
+ return {
1412
+ predicateSql: (0, SqlComponentFormatter_1.formatSqlComponent)(expression, options),
1413
+ scopeId: "scope:root",
1414
+ ...draft
1415
+ };
1416
+ }
1417
+ buildResult(params) {
1418
+ return {
1419
+ ok: params.errors.length === 0,
1420
+ sql: params.sql,
1421
+ query: params.query,
1422
+ applied: params.applied,
1423
+ skipped: params.skipped,
1424
+ warnings: params.warnings,
1425
+ errors: params.errors,
1426
+ safety: {
1427
+ mode: "safe_only",
1428
+ unsafeRewriteApplied: false,
1429
+ dryRun: params.dryRun,
1430
+ formatterGeneratedSource: params.formatterGeneratedSource
1431
+ },
1432
+ staticPredicateMoves: params.applied
1433
+ };
1434
+ }
1435
+ }
1436
+ exports.StaticPredicatePlacementOptimizer = StaticPredicatePlacementOptimizer;
1437
+ const planStaticPredicatePlacement = (input, options = {}) => {
1438
+ return new StaticPredicatePlacementOptimizer().plan(input, options);
1439
+ };
1440
+ exports.planStaticPredicatePlacement = planStaticPredicatePlacement;
1441
+ const optimizeStaticPredicatePlacement = (input, options = {}) => {
1442
+ return new StaticPredicatePlacementOptimizer().optimize(input, options);
1443
+ };
1444
+ exports.optimizeStaticPredicatePlacement = optimizeStaticPredicatePlacement;
1445
+ //# sourceMappingURL=StaticPredicatePlacementOptimizer.js.map