rawsql-ts 0.24.4 → 0.26.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 (78) hide show
  1. package/dist/esm/index.d.ts +8 -0
  2. package/dist/esm/index.js +8 -0
  3. package/dist/esm/index.js.map +1 -1
  4. package/dist/esm/index.min.js +5 -5
  5. package/dist/esm/index.min.js.map +4 -4
  6. package/dist/esm/parsers/FunctionExpressionParser.d.ts +3 -0
  7. package/dist/esm/parsers/FunctionExpressionParser.js +50 -2
  8. package/dist/esm/parsers/FunctionExpressionParser.js.map +1 -1
  9. package/dist/esm/parsers/SqlPrintTokenParser.d.ts +1 -0
  10. package/dist/esm/parsers/SqlPrintTokenParser.js +11 -1
  11. package/dist/esm/parsers/SqlPrintTokenParser.js.map +1 -1
  12. package/dist/esm/transformers/AstCommentAttachmentExtractor.d.ts +61 -0
  13. package/dist/esm/transformers/AstCommentAttachmentExtractor.js +221 -0
  14. package/dist/esm/transformers/AstCommentAttachmentExtractor.js.map +1 -0
  15. package/dist/esm/transformers/ClauseScopedColumnReferenceCollector.d.ts +47 -0
  16. package/dist/esm/transformers/ClauseScopedColumnReferenceCollector.js +235 -0
  17. package/dist/esm/transformers/ClauseScopedColumnReferenceCollector.js.map +1 -0
  18. package/dist/esm/transformers/ConditionOptimization.d.ts +66 -0
  19. package/dist/esm/transformers/ConditionOptimization.js +294 -0
  20. package/dist/esm/transformers/ConditionOptimization.js.map +1 -0
  21. package/dist/esm/transformers/NamedQueryDefinitionExtractor.d.ts +53 -0
  22. package/dist/esm/transformers/NamedQueryDefinitionExtractor.js +370 -0
  23. package/dist/esm/transformers/NamedQueryDefinitionExtractor.js.map +1 -0
  24. package/dist/esm/transformers/ParameterConditionPlacementOptimizer.d.ts +85 -0
  25. package/dist/esm/transformers/ParameterConditionPlacementOptimizer.js +942 -0
  26. package/dist/esm/transformers/ParameterConditionPlacementOptimizer.js.map +1 -0
  27. package/dist/esm/transformers/SelectBodyExtractor.d.ts +21 -0
  28. package/dist/esm/transformers/SelectBodyExtractor.js +137 -0
  29. package/dist/esm/transformers/SelectBodyExtractor.js.map +1 -0
  30. package/dist/esm/transformers/SelectOutputCollector.d.ts +47 -0
  31. package/dist/esm/transformers/SelectOutputCollector.js +281 -0
  32. package/dist/esm/transformers/SelectOutputCollector.js.map +1 -0
  33. package/dist/esm/transformers/SelectValueCollector.d.ts +9 -1
  34. package/dist/esm/transformers/SelectValueCollector.js +83 -58
  35. package/dist/esm/transformers/SelectValueCollector.js.map +1 -1
  36. package/dist/esm/transformers/WildcardColumnInferenceCollector.d.ts +129 -0
  37. package/dist/esm/transformers/WildcardColumnInferenceCollector.js +373 -0
  38. package/dist/esm/transformers/WildcardColumnInferenceCollector.js.map +1 -0
  39. package/dist/index.js +8 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/index.min.js +5 -5
  42. package/dist/index.min.js.map +4 -4
  43. package/dist/parsers/FunctionExpressionParser.js +49 -1
  44. package/dist/parsers/FunctionExpressionParser.js.map +1 -1
  45. package/dist/parsers/SqlPrintTokenParser.js +11 -1
  46. package/dist/parsers/SqlPrintTokenParser.js.map +1 -1
  47. package/dist/src/index.d.ts +8 -0
  48. package/dist/src/parsers/FunctionExpressionParser.d.ts +3 -0
  49. package/dist/src/parsers/SqlPrintTokenParser.d.ts +1 -0
  50. package/dist/src/transformers/AstCommentAttachmentExtractor.d.ts +61 -0
  51. package/dist/src/transformers/ClauseScopedColumnReferenceCollector.d.ts +47 -0
  52. package/dist/src/transformers/ConditionOptimization.d.ts +66 -0
  53. package/dist/src/transformers/NamedQueryDefinitionExtractor.d.ts +53 -0
  54. package/dist/src/transformers/ParameterConditionPlacementOptimizer.d.ts +85 -0
  55. package/dist/src/transformers/SelectBodyExtractor.d.ts +21 -0
  56. package/dist/src/transformers/SelectOutputCollector.d.ts +47 -0
  57. package/dist/src/transformers/SelectValueCollector.d.ts +9 -1
  58. package/dist/src/transformers/WildcardColumnInferenceCollector.d.ts +129 -0
  59. package/dist/transformers/AstCommentAttachmentExtractor.js +231 -0
  60. package/dist/transformers/AstCommentAttachmentExtractor.js.map +1 -0
  61. package/dist/transformers/ClauseScopedColumnReferenceCollector.js +239 -0
  62. package/dist/transformers/ClauseScopedColumnReferenceCollector.js.map +1 -0
  63. package/dist/transformers/ConditionOptimization.js +311 -0
  64. package/dist/transformers/ConditionOptimization.js.map +1 -0
  65. package/dist/transformers/NamedQueryDefinitionExtractor.js +374 -0
  66. package/dist/transformers/NamedQueryDefinitionExtractor.js.map +1 -0
  67. package/dist/transformers/ParameterConditionPlacementOptimizer.js +952 -0
  68. package/dist/transformers/ParameterConditionPlacementOptimizer.js.map +1 -0
  69. package/dist/transformers/SelectBodyExtractor.js +141 -0
  70. package/dist/transformers/SelectBodyExtractor.js.map +1 -0
  71. package/dist/transformers/SelectOutputCollector.js +291 -0
  72. package/dist/transformers/SelectOutputCollector.js.map +1 -0
  73. package/dist/transformers/SelectValueCollector.js +83 -58
  74. package/dist/transformers/SelectValueCollector.js.map +1 -1
  75. package/dist/transformers/WildcardColumnInferenceCollector.js +377 -0
  76. package/dist/transformers/WildcardColumnInferenceCollector.js.map +1 -0
  77. package/dist/tsconfig.browser.tsbuildinfo +1 -1
  78. package/package.json +1 -1
@@ -0,0 +1,952 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.optimizeParameterConditionPlacement = exports.planParameterConditionOptimization = exports.ParameterConditionPlacementOptimizer = 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 SqlFormatter_1 = require("./SqlFormatter");
10
+ const SUPPORTED_OPERATORS = new Set(["=", "<>", "!=", "<", "<=", ">", ">=", "like", "ilike", "in"]);
11
+ const VOLATILE_OR_UNSUPPORTED_FUNCTION_REASON = "Condition 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 formatSqlComponent = (component) => {
14
+ return new SqlFormatter_1.SqlFormatter().format(component).formattedSql;
15
+ };
16
+ const unwrapParens = (expression) => {
17
+ let candidate = expression;
18
+ while (candidate instanceof ValueComponent_1.ParenExpression) {
19
+ candidate = candidate.expression;
20
+ }
21
+ return candidate;
22
+ };
23
+ const isBinaryOperator = (expression, operator) => {
24
+ const candidate = unwrapParens(expression);
25
+ return candidate instanceof ValueComponent_1.BinaryExpression
26
+ && candidate.operator.value.trim().toLowerCase() === operator;
27
+ };
28
+ const collectTopLevelAndTerms = (expression) => {
29
+ const candidate = unwrapParens(expression);
30
+ if (!isBinaryOperator(candidate, "and")) {
31
+ return [expression];
32
+ }
33
+ return [
34
+ ...collectTopLevelAndTerms(candidate.left),
35
+ ...collectTopLevelAndTerms(candidate.right)
36
+ ];
37
+ };
38
+ const rebuildWhereWithoutTerms = (query, termsToRemove) => {
39
+ if (!query.whereClause || termsToRemove.size === 0) {
40
+ return;
41
+ }
42
+ const remaining = collectTopLevelAndTerms(query.whereClause.condition)
43
+ .filter(term => !termsToRemove.has(term));
44
+ if (remaining.length === 0) {
45
+ query.whereClause = null;
46
+ return;
47
+ }
48
+ let rebuilt = remaining[0];
49
+ for (let index = 1; index < remaining.length; index += 1) {
50
+ rebuilt = new ValueComponent_1.BinaryExpression(rebuilt, "and", remaining[index]);
51
+ }
52
+ query.whereClause = new Clause_1.WhereClause(rebuilt);
53
+ };
54
+ const cloneValueComponent = (expression) => {
55
+ return ValueParser_1.ValueParser.parse(formatSqlComponent(expression));
56
+ };
57
+ const cloneColumnReference = (reference) => {
58
+ var _a, _b;
59
+ const namespaces = (_b = (_a = reference.namespaces) === null || _a === void 0 ? void 0 : _a.map(namespace => namespace.name)) !== null && _b !== void 0 ? _b : null;
60
+ return new ValueComponent_1.ColumnReference(namespaces, reference.column.name);
61
+ };
62
+ const columnReferenceText = (reference) => {
63
+ const namespace = reference.getNamespace();
64
+ return namespace ? `${namespace}.${reference.column.name}` : reference.column.name;
65
+ };
66
+ const sameColumnReference = (left, right) => {
67
+ return normalizeIdentifier(left.column.name) === normalizeIdentifier(right.column.name)
68
+ && normalizeIdentifier(left.getNamespace()) === normalizeIdentifier(right.getNamespace());
69
+ };
70
+ const appendUnique = (items, value) => {
71
+ if (!items.includes(value)) {
72
+ items.push(value);
73
+ }
74
+ };
75
+ class ParameterConditionPlacementOptimizer {
76
+ plan(input, options = {}) {
77
+ var _a, _b, _c;
78
+ const parsed = this.parseInput(input);
79
+ const warnings = [...parsed.warnings];
80
+ const errors = [...parsed.errors];
81
+ if (!parsed.query) {
82
+ return this.buildResult({
83
+ sql: parsed.sql,
84
+ applied: [],
85
+ skipped: [],
86
+ warnings,
87
+ errors,
88
+ dryRun: (_a = options.dryRun) !== null && _a !== void 0 ? _a : true,
89
+ formatterGeneratedSource: parsed.formatterGeneratedSource
90
+ });
91
+ }
92
+ if (!(parsed.query instanceof SelectQuery_1.SimpleSelectQuery)) {
93
+ warnings.push({
94
+ code: "UNSUPPORTED_ROOT_QUERY",
95
+ message: "Parameter condition placement currently supports only SimpleSelectQuery roots."
96
+ });
97
+ return this.buildResult({
98
+ sql: parsed.sql,
99
+ applied: [],
100
+ skipped: [],
101
+ warnings,
102
+ errors,
103
+ dryRun: (_b = options.dryRun) !== null && _b !== void 0 ? _b : true,
104
+ formatterGeneratedSource: parsed.formatterGeneratedSource
105
+ });
106
+ }
107
+ const query = parsed.query;
108
+ const applied = [];
109
+ const skipped = [];
110
+ const movedTerms = [];
111
+ for (const term of query.whereClause ? collectTopLevelAndTerms(query.whereClause.condition) : []) {
112
+ const candidate = this.analyzeCandidate(term);
113
+ if (!candidate) {
114
+ continue;
115
+ }
116
+ if ("code" in candidate) {
117
+ skipped.push(this.makeSkipped(term, candidate));
118
+ continue;
119
+ }
120
+ const target = this.resolveTarget(query, candidate);
121
+ if ("code" in target) {
122
+ skipped.push(this.makeSkipped(term, target));
123
+ continue;
124
+ }
125
+ const targetColumn = this.resolveTargetColumn(target.query, target.outputColumnName);
126
+ if ("code" in targetColumn) {
127
+ skipped.push(this.makeSkipped(term, targetColumn));
128
+ continue;
129
+ }
130
+ const movedCondition = this.rebaseCondition(candidate.expression, candidate.column, targetColumn.column);
131
+ target.query.appendWhere(movedCondition);
132
+ movedTerms.push(term);
133
+ applied.push({
134
+ kind: "move_condition",
135
+ conditionSql: candidate.conditionSql,
136
+ fromScopeId: "scope:root",
137
+ toScopeId: target.scopeId,
138
+ reason: "All referenced columns resolve to a single direct upstream output before unsafe query boundaries.",
139
+ parameterNames: candidate.parameterNames,
140
+ columnReferences: [columnReferenceText(candidate.column)]
141
+ });
142
+ }
143
+ rebuildWhereWithoutTerms(query, new Set(movedTerms));
144
+ const sql = applied.length > 0 ? formatSqlComponent(query) : parsed.sql;
145
+ return this.buildResult({
146
+ sql,
147
+ applied,
148
+ skipped,
149
+ warnings,
150
+ errors,
151
+ dryRun: (_c = options.dryRun) !== null && _c !== void 0 ? _c : true,
152
+ formatterGeneratedSource: parsed.formatterGeneratedSource
153
+ });
154
+ }
155
+ optimize(input, options = {}) {
156
+ var _a;
157
+ return this.plan(input, { ...options, dryRun: (_a = options.dryRun) !== null && _a !== void 0 ? _a : false });
158
+ }
159
+ parseInput(input) {
160
+ const warnings = [];
161
+ const errors = [];
162
+ try {
163
+ const sourceSql = typeof input === "string"
164
+ ? input
165
+ : formatSqlComponent(input);
166
+ if (typeof input !== "string") {
167
+ warnings.push({
168
+ code: "AST_INPUT_FORMATTED",
169
+ message: "AST input is cloned through formatter output so the caller-owned query is not mutated."
170
+ });
171
+ }
172
+ return {
173
+ query: SelectQueryParser_1.SelectQueryParser.parse(sourceSql),
174
+ sql: sourceSql,
175
+ formatterGeneratedSource: typeof input !== "string",
176
+ warnings,
177
+ errors
178
+ };
179
+ }
180
+ catch (error) {
181
+ const detail = error instanceof Error ? error.message : String(error);
182
+ errors.push({
183
+ code: "PARSE_FAILED",
184
+ message: "Parameter condition optimization could not parse the input SQL.",
185
+ detail
186
+ });
187
+ return {
188
+ query: null,
189
+ sql: typeof input === "string" ? input : "",
190
+ formatterGeneratedSource: typeof input !== "string",
191
+ warnings,
192
+ errors
193
+ };
194
+ }
195
+ }
196
+ analyzeCandidate(expression) {
197
+ const parameterNames = this.collectParameterNames(expression);
198
+ if (parameterNames.length === 0) {
199
+ return null;
200
+ }
201
+ const unsupported = this.findUnsupportedExpression(expression);
202
+ if (unsupported) {
203
+ return unsupported;
204
+ }
205
+ const candidate = unwrapParens(expression);
206
+ if (!(candidate instanceof ValueComponent_1.BinaryExpression)) {
207
+ return {
208
+ code: "UNSUPPORTED_PARAMETER_CONDITION",
209
+ reason: "Only simple binary parameter predicates are moved in the safe-only implementation."
210
+ };
211
+ }
212
+ const operator = candidate.operator.value.trim().toLowerCase();
213
+ if (!SUPPORTED_OPERATORS.has(operator)) {
214
+ return {
215
+ code: "UNSUPPORTED_OPERATOR",
216
+ reason: `Operator '${candidate.operator.value}' is not supported for safe-only parameter condition placement.`
217
+ };
218
+ }
219
+ const columnReferences = this.collectColumnReferences(expression);
220
+ if (columnReferences.length !== 1) {
221
+ return {
222
+ code: "AMBIGUOUS_COLUMN_REFERENCE",
223
+ reason: columnReferences.length === 0
224
+ ? "Parameter condition has no column reference to anchor the move."
225
+ : "Parameter condition references multiple columns; moving it may change semantics."
226
+ };
227
+ }
228
+ if (operator === "in" && !this.isSupportedInPredicate(candidate)) {
229
+ return {
230
+ code: "UNSUPPORTED_IN_PREDICATE",
231
+ reason: "Only simple column IN (:parameter) predicates are moved in the safe-only implementation."
232
+ };
233
+ }
234
+ return {
235
+ expression,
236
+ conditionSql: formatSqlComponent(expression),
237
+ parameterNames,
238
+ column: columnReferences[0]
239
+ };
240
+ }
241
+ findUnsupportedExpression(expression) {
242
+ let found = null;
243
+ const visit = (value) => {
244
+ if (found) {
245
+ return;
246
+ }
247
+ const candidate = unwrapParens(value);
248
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
249
+ if (candidate.operator.value.trim().toLowerCase() === "or") {
250
+ found = {
251
+ code: "OR_PREDICATE_UNSUPPORTED",
252
+ reason: "Condition contains OR predicates, which are not moved in the first safe-only implementation."
253
+ };
254
+ return;
255
+ }
256
+ visit(candidate.left);
257
+ visit(candidate.right);
258
+ return;
259
+ }
260
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
261
+ found = {
262
+ code: "FUNCTION_PREDICATE_UNSUPPORTED",
263
+ reason: VOLATILE_OR_UNSUPPORTED_FUNCTION_REASON
264
+ };
265
+ return;
266
+ }
267
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
268
+ found = {
269
+ code: "CASE_PREDICATE_UNSUPPORTED",
270
+ reason: "CASE predicates are not moved in the first safe-only implementation."
271
+ };
272
+ return;
273
+ }
274
+ if (candidate instanceof ValueComponent_1.InlineQuery || candidate instanceof ValueComponent_1.ArrayQueryExpression) {
275
+ found = {
276
+ code: "SUBQUERY_PREDICATE_UNSUPPORTED",
277
+ reason: "Subquery predicates are not moved in the first safe-only implementation."
278
+ };
279
+ return;
280
+ }
281
+ if (candidate instanceof ValueComponent_1.BetweenExpression) {
282
+ found = {
283
+ code: "BETWEEN_PREDICATE_UNSUPPORTED",
284
+ reason: "BETWEEN predicates are not moved in the first safe-only implementation."
285
+ };
286
+ return;
287
+ }
288
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
289
+ visit(candidate.expression);
290
+ return;
291
+ }
292
+ if (candidate instanceof ValueComponent_1.CastExpression) {
293
+ visit(candidate.input);
294
+ return;
295
+ }
296
+ if (candidate instanceof ValueComponent_1.JsonPredicateExpression) {
297
+ visit(candidate.expression);
298
+ return;
299
+ }
300
+ if (candidate instanceof ValueComponent_1.ArrayExpression) {
301
+ visit(candidate.expression);
302
+ return;
303
+ }
304
+ if (candidate instanceof ValueComponent_1.ValueList) {
305
+ candidate.values.forEach(visit);
306
+ return;
307
+ }
308
+ if (candidate instanceof ValueComponent_1.TupleExpression) {
309
+ candidate.values.forEach(visit);
310
+ return;
311
+ }
312
+ if (candidate instanceof ValueComponent_1.TypeValue && candidate.argument) {
313
+ visit(candidate.argument);
314
+ }
315
+ };
316
+ visit(expression);
317
+ return found;
318
+ }
319
+ isSupportedInPredicate(expression) {
320
+ const left = unwrapParens(expression.left);
321
+ const right = unwrapParens(expression.right);
322
+ if (!(left instanceof ValueComponent_1.ColumnReference)) {
323
+ return false;
324
+ }
325
+ if (right instanceof ValueComponent_1.ParameterExpression) {
326
+ return true;
327
+ }
328
+ if (!(right instanceof ValueComponent_1.ValueList)) {
329
+ return false;
330
+ }
331
+ return right.values.length > 0
332
+ && right.values.every(value => unwrapParens(value) instanceof ValueComponent_1.ParameterExpression);
333
+ }
334
+ resolveTarget(root, candidate) {
335
+ const boundary = this.findCurrentQueryBoundary(root);
336
+ if (boundary) {
337
+ return boundary;
338
+ }
339
+ if (!root.fromClause) {
340
+ return {
341
+ code: "NO_FROM_CLAUSE",
342
+ reason: "Condition has no FROM source that can receive the predicate safely."
343
+ };
344
+ }
345
+ const bindingResult = this.resolveSourceBinding(root, candidate.column);
346
+ if ("code" in bindingResult) {
347
+ return bindingResult;
348
+ }
349
+ const nullableSide = this.findNullableSideBoundary(root.fromClause, bindingResult);
350
+ if (nullableSide) {
351
+ return nullableSide;
352
+ }
353
+ const upstream = this.resolveUpstreamQuery(root, bindingResult, candidate.column.column.name);
354
+ if ("code" in upstream) {
355
+ return upstream;
356
+ }
357
+ const targetBoundary = this.findTargetQueryBoundary(upstream.query);
358
+ if (targetBoundary) {
359
+ return targetBoundary;
360
+ }
361
+ return upstream;
362
+ }
363
+ findCurrentQueryBoundary(query) {
364
+ if (query.selectClause.distinct) {
365
+ return {
366
+ code: "DISTINCT_BOUNDARY",
367
+ reason: "Condition crosses DISTINCT boundary; moving it may change semantics."
368
+ };
369
+ }
370
+ if (query.groupByClause || query.havingClause) {
371
+ return {
372
+ code: "GROUP_BY_BOUNDARY",
373
+ reason: "Condition crosses GROUP BY boundary; moving it may change semantics."
374
+ };
375
+ }
376
+ if (this.hasWindowUsage(query)) {
377
+ return {
378
+ code: "WINDOW_BOUNDARY",
379
+ reason: "Condition crosses WINDOW boundary; moving it may change semantics."
380
+ };
381
+ }
382
+ return null;
383
+ }
384
+ findTargetQueryBoundary(query) {
385
+ const commonBoundary = this.findCurrentQueryBoundary(query);
386
+ if (commonBoundary) {
387
+ return commonBoundary;
388
+ }
389
+ if (query.limitClause || query.offsetClause || query.fetchClause) {
390
+ return {
391
+ code: "ROW_LIMIT_BOUNDARY",
392
+ reason: "Condition crosses LIMIT/OFFSET/FETCH boundary; moving it may change row selection semantics."
393
+ };
394
+ }
395
+ if (query.fromClause && this.hasOuterJoin(query.fromClause)) {
396
+ return {
397
+ code: "OUTER_JOIN_BOUNDARY",
398
+ reason: "Target query contains an OUTER JOIN boundary that is not moved across in the safe-only implementation."
399
+ };
400
+ }
401
+ return null;
402
+ }
403
+ resolveSourceBinding(root, column) {
404
+ const fromClause = root.fromClause;
405
+ if (!fromClause) {
406
+ return {
407
+ code: "NO_FROM_CLAUSE",
408
+ reason: "Condition has no FROM source that can receive the predicate safely."
409
+ };
410
+ }
411
+ const bindings = this.getSourceBindings(fromClause);
412
+ const namespace = normalizeIdentifier(column.getNamespace());
413
+ const columnName = column.column.name;
414
+ if (namespace) {
415
+ const matches = bindings.filter(binding => normalizeIdentifier(binding.alias) === namespace);
416
+ if (matches.length !== 1) {
417
+ return {
418
+ code: "AMBIGUOUS_COLUMN_SOURCE",
419
+ reason: `Column source alias '${column.getNamespace()}' is not uniquely resolvable.`
420
+ };
421
+ }
422
+ if (this.resolveSourceQueryForColumns(root, matches[0].source) instanceof SelectQuery_1.BinarySelectQuery) {
423
+ return matches[0];
424
+ }
425
+ const matchCount = this.getOutputColumnMatchCount(root, matches[0], columnName);
426
+ if (matchCount === 0) {
427
+ return {
428
+ code: "COLUMN_NOT_AVAILABLE_UPSTREAM",
429
+ reason: `Column '${columnReferenceText(column)}' is not a direct output of the referenced source.`
430
+ };
431
+ }
432
+ if (matchCount > 1) {
433
+ return {
434
+ code: "AMBIGUOUS_COLUMN_REFERENCE",
435
+ reason: `Column '${columnReferenceText(column)}' resolves to multiple outputs in the referenced source.`
436
+ };
437
+ }
438
+ return matches[0];
439
+ }
440
+ const matches = [];
441
+ let unionSource = null;
442
+ for (const binding of bindings) {
443
+ if (this.resolveSourceQueryForColumns(root, binding.source) instanceof SelectQuery_1.BinarySelectQuery) {
444
+ unionSource !== null && unionSource !== void 0 ? unionSource : (unionSource = binding);
445
+ continue;
446
+ }
447
+ const matchCount = this.getOutputColumnMatchCount(root, binding, columnName);
448
+ if (matchCount > 1) {
449
+ return {
450
+ code: "AMBIGUOUS_COLUMN_REFERENCE",
451
+ reason: `Column '${columnName}' resolves to multiple outputs in source '${binding.alias}'.`
452
+ };
453
+ }
454
+ if (matchCount === 1) {
455
+ matches.push(binding);
456
+ }
457
+ }
458
+ if (matches.length === 0 && unionSource) {
459
+ return {
460
+ code: "UNION_BOUNDARY",
461
+ reason: "Condition would need distribution into a UNION branch, which is unsupported."
462
+ };
463
+ }
464
+ if (matches.length !== 1) {
465
+ return {
466
+ code: "AMBIGUOUS_COLUMN_REFERENCE",
467
+ reason: matches.length === 0
468
+ ? `Column '${columnName}' is not uniquely resolvable to a safe upstream source.`
469
+ : `Column '${columnName}' is ambiguous across source query blocks.`
470
+ };
471
+ }
472
+ return matches[0];
473
+ }
474
+ resolveUpstreamQuery(root, binding, outputColumnName) {
475
+ const source = binding.source.datasource;
476
+ if (source instanceof Clause_1.SubQuerySource) {
477
+ if (source.query instanceof SelectQuery_1.SimpleSelectQuery) {
478
+ return {
479
+ query: source.query,
480
+ scopeId: `subquery:${binding.alias}`,
481
+ outputColumnName,
482
+ sourceBinding: binding
483
+ };
484
+ }
485
+ return {
486
+ code: "UNION_BOUNDARY",
487
+ reason: "Condition would need distribution into a UNION or non-simple subquery, which is unsupported."
488
+ };
489
+ }
490
+ if (!(source instanceof Clause_1.TableSource)) {
491
+ return {
492
+ code: "UNSUPPORTED_SOURCE",
493
+ reason: "Only CTE and simple derived-table sources can receive moved parameter conditions."
494
+ };
495
+ }
496
+ const cteName = source.table.name;
497
+ const commonTable = this.findCte(root, cteName);
498
+ if (!commonTable) {
499
+ return {
500
+ code: "NO_SAFE_UPSTREAM_QUERY",
501
+ reason: "The referenced source is a base table, so there is no upstream query block to move into."
502
+ };
503
+ }
504
+ const referenceCount = this.countTableSourceReferences(root, cteName);
505
+ if (referenceCount !== 1) {
506
+ return {
507
+ code: "CTE_REUSE_UNSUPPORTED",
508
+ reason: `CTE '${cteName}' is referenced ${referenceCount} times; moving a predicate into it may affect other consumers.`
509
+ };
510
+ }
511
+ if (commonTable.query instanceof SelectQuery_1.BinarySelectQuery) {
512
+ return {
513
+ code: "UNION_BOUNDARY",
514
+ reason: "Condition would need distribution into a UNION branch, which is unsupported."
515
+ };
516
+ }
517
+ if (!(commonTable.query instanceof SelectQuery_1.SimpleSelectQuery)) {
518
+ return {
519
+ code: "UNSUPPORTED_CTE_QUERY",
520
+ reason: "Writable or non-select CTE bodies are not moved into by parameter condition placement."
521
+ };
522
+ }
523
+ return {
524
+ query: commonTable.query,
525
+ scopeId: `cte:${commonTable.getSourceAliasName()}`,
526
+ outputColumnName,
527
+ sourceBinding: binding,
528
+ cteName: commonTable.getSourceAliasName()
529
+ };
530
+ }
531
+ resolveTargetColumn(query, outputColumnName) {
532
+ const matches = query.selectClause.items.filter(item => { var _a; return normalizeIdentifier((_a = this.getSelectItemOutputName(item)) !== null && _a !== void 0 ? _a : "") === normalizeIdentifier(outputColumnName); });
533
+ if (matches.length !== 1) {
534
+ return {
535
+ code: "AMBIGUOUS_TARGET_COLUMN",
536
+ reason: matches.length === 0
537
+ ? `Target query does not expose '${outputColumnName}' as a direct output column.`
538
+ : `Target query exposes multiple '${outputColumnName}' columns.`
539
+ };
540
+ }
541
+ const value = matches[0].value;
542
+ if (!(value instanceof ValueComponent_1.ColumnReference)) {
543
+ return {
544
+ code: "EXPRESSION_OUTPUT_UNSUPPORTED",
545
+ reason: `Target output '${outputColumnName}' is an expression, not a direct column reference.`
546
+ };
547
+ }
548
+ const sourceResolution = this.verifyColumnResolvableInQuery(query, value);
549
+ if (sourceResolution) {
550
+ return sourceResolution;
551
+ }
552
+ return { column: value };
553
+ }
554
+ verifyColumnResolvableInQuery(query, column) {
555
+ if (!query.fromClause) {
556
+ return {
557
+ code: "NO_TARGET_FROM_CLAUSE",
558
+ reason: "Target query has no FROM clause where the moved column can be resolved."
559
+ };
560
+ }
561
+ const bindings = this.getSourceBindings(query.fromClause);
562
+ const namespace = normalizeIdentifier(column.getNamespace());
563
+ if (namespace) {
564
+ const matches = bindings.filter(binding => normalizeIdentifier(binding.alias) === namespace);
565
+ return matches.length === 1
566
+ ? null
567
+ : {
568
+ code: "AMBIGUOUS_TARGET_COLUMN",
569
+ reason: `Target column '${columnReferenceText(column)}' is not uniquely resolvable in the destination query.`
570
+ };
571
+ }
572
+ if (bindings.length === 1) {
573
+ return null;
574
+ }
575
+ return {
576
+ code: "AMBIGUOUS_TARGET_COLUMN",
577
+ reason: `Unqualified target column '${column.column.name}' is ambiguous in a multi-source destination query.`
578
+ };
579
+ }
580
+ rebaseCondition(expression, sourceColumn, targetColumn) {
581
+ const cloned = cloneValueComponent(expression);
582
+ for (const reference of this.collectColumnReferences(cloned)) {
583
+ if (!sameColumnReference(reference, sourceColumn)) {
584
+ continue;
585
+ }
586
+ reference.qualifiedName = cloneColumnReference(targetColumn).qualifiedName;
587
+ }
588
+ return cloned;
589
+ }
590
+ getSourceBindings(fromClause) {
591
+ var _a, _b, _c;
592
+ const bindings = [{
593
+ source: fromClause.source,
594
+ alias: (_a = fromClause.source.getAliasName()) !== null && _a !== void 0 ? _a : "",
595
+ join: null,
596
+ isPrimary: true
597
+ }];
598
+ for (const join of (_b = fromClause.joins) !== null && _b !== void 0 ? _b : []) {
599
+ bindings.push({
600
+ source: join.source,
601
+ alias: (_c = join.source.getAliasName()) !== null && _c !== void 0 ? _c : "",
602
+ join,
603
+ isPrimary: false
604
+ });
605
+ }
606
+ return bindings;
607
+ }
608
+ findNullableSideBoundary(fromClause, binding) {
609
+ var _a;
610
+ if (!binding.join) {
611
+ const rightOrFull = ((_a = fromClause.joins) !== null && _a !== void 0 ? _a : []).some(join => {
612
+ const joinType = join.joinType.value.toLowerCase();
613
+ return joinType.includes("right") || joinType.includes("full");
614
+ });
615
+ return rightOrFull
616
+ ? {
617
+ code: "OUTER_JOIN_NULLABLE_SIDE",
618
+ reason: "Condition crosses OUTER JOIN nullable side; moving it may change semantics."
619
+ }
620
+ : null;
621
+ }
622
+ const joinType = binding.join.joinType.value.toLowerCase();
623
+ if (joinType.includes("left")) {
624
+ return {
625
+ code: "OUTER_JOIN_NULLABLE_SIDE",
626
+ reason: "Condition crosses LEFT JOIN nullable side; moving it may change semantics."
627
+ };
628
+ }
629
+ if (joinType.includes("full")) {
630
+ return {
631
+ code: "OUTER_JOIN_NULLABLE_SIDE",
632
+ reason: "Condition crosses FULL JOIN nullable side; moving it may change semantics."
633
+ };
634
+ }
635
+ return null;
636
+ }
637
+ hasOuterJoin(fromClause) {
638
+ var _a;
639
+ return ((_a = fromClause.joins) !== null && _a !== void 0 ? _a : []).some(join => {
640
+ const joinType = join.joinType.value.toLowerCase();
641
+ return joinType.includes("left") || joinType.includes("right") || joinType.includes("full") || joinType.includes("outer");
642
+ });
643
+ }
644
+ getOutputColumnMatchCount(root, binding, columnName) {
645
+ const target = this.resolveSourceQueryForColumns(root, binding.source);
646
+ if (!target || !(target instanceof SelectQuery_1.SimpleSelectQuery)) {
647
+ return 0;
648
+ }
649
+ return target.selectClause.items.filter(item => { var _a; return normalizeIdentifier((_a = this.getSelectItemOutputName(item)) !== null && _a !== void 0 ? _a : "") === normalizeIdentifier(columnName); }).length;
650
+ }
651
+ resolveSourceQueryForColumns(root, source) {
652
+ var _a;
653
+ if (source.datasource instanceof Clause_1.SubQuerySource) {
654
+ return source.datasource.query;
655
+ }
656
+ if (source.datasource instanceof Clause_1.TableSource) {
657
+ const cteQuery = (_a = this.findCte(root, source.datasource.table.name)) === null || _a === void 0 ? void 0 : _a.query;
658
+ return cteQuery instanceof SelectQuery_1.SimpleSelectQuery || cteQuery instanceof SelectQuery_1.BinarySelectQuery
659
+ ? cteQuery
660
+ : null;
661
+ }
662
+ return null;
663
+ }
664
+ getSelectItemOutputName(item) {
665
+ if (item.identifier) {
666
+ return item.identifier.name;
667
+ }
668
+ if (item.value instanceof ValueComponent_1.ColumnReference) {
669
+ return item.value.column.name;
670
+ }
671
+ return null;
672
+ }
673
+ findCte(root, name) {
674
+ var _a, _b;
675
+ const normalized = normalizeIdentifier(name);
676
+ const matches = ((_b = (_a = root.withClause) === null || _a === void 0 ? void 0 : _a.tables) !== null && _b !== void 0 ? _b : [])
677
+ .filter(table => normalizeIdentifier(table.getSourceAliasName()) === normalized);
678
+ return matches.length === 1 ? matches[0] : null;
679
+ }
680
+ countTableSourceReferences(query, tableName) {
681
+ const normalized = normalizeIdentifier(tableName);
682
+ let count = 0;
683
+ const visitSelect = (select) => {
684
+ var _a, _b;
685
+ if (select instanceof SelectQuery_1.BinarySelectQuery) {
686
+ visitSelect(select.left);
687
+ visitSelect(select.right);
688
+ return;
689
+ }
690
+ if (!(select instanceof SelectQuery_1.SimpleSelectQuery)) {
691
+ return;
692
+ }
693
+ if (select.fromClause) {
694
+ for (const binding of this.getSourceBindings(select.fromClause)) {
695
+ const source = binding.source.datasource;
696
+ if (source instanceof Clause_1.TableSource && normalizeIdentifier(source.table.name) === normalized) {
697
+ count += 1;
698
+ }
699
+ if (source instanceof Clause_1.SubQuerySource) {
700
+ visitSelect(source.query);
701
+ }
702
+ }
703
+ }
704
+ for (const cte of (_b = (_a = select.withClause) === null || _a === void 0 ? void 0 : _a.tables) !== null && _b !== void 0 ? _b : []) {
705
+ if (cte.query instanceof SelectQuery_1.SimpleSelectQuery || cte.query instanceof SelectQuery_1.BinarySelectQuery) {
706
+ visitSelect(cte.query);
707
+ }
708
+ }
709
+ };
710
+ visitSelect(query);
711
+ return count;
712
+ }
713
+ hasWindowUsage(query) {
714
+ if (query.windowClause) {
715
+ return true;
716
+ }
717
+ let found = false;
718
+ const visit = (value) => {
719
+ if (found) {
720
+ return;
721
+ }
722
+ const candidate = unwrapParens(value);
723
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
724
+ if (candidate.over) {
725
+ found = true;
726
+ return;
727
+ }
728
+ if (candidate.argument) {
729
+ visit(candidate.argument);
730
+ }
731
+ if (candidate.filterCondition) {
732
+ visit(candidate.filterCondition);
733
+ }
734
+ return;
735
+ }
736
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
737
+ visit(candidate.left);
738
+ visit(candidate.right);
739
+ return;
740
+ }
741
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
742
+ visit(candidate.expression);
743
+ return;
744
+ }
745
+ if (candidate instanceof ValueComponent_1.CastExpression) {
746
+ visit(candidate.input);
747
+ return;
748
+ }
749
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
750
+ if (candidate.condition) {
751
+ visit(candidate.condition);
752
+ }
753
+ for (const pair of candidate.switchCase.cases) {
754
+ visit(pair.key);
755
+ visit(pair.value);
756
+ }
757
+ if (candidate.switchCase.elseValue) {
758
+ visit(candidate.switchCase.elseValue);
759
+ }
760
+ return;
761
+ }
762
+ if (candidate instanceof ValueComponent_1.ValueList) {
763
+ candidate.values.forEach(visit);
764
+ }
765
+ };
766
+ query.selectClause.items.forEach(item => visit(item.value));
767
+ return found;
768
+ }
769
+ collectColumnReferences(expression) {
770
+ const references = [];
771
+ const visit = (value) => {
772
+ const candidate = unwrapParens(value);
773
+ if (candidate instanceof ValueComponent_1.ColumnReference) {
774
+ if (!references.some(existing => sameColumnReference(existing, candidate))) {
775
+ references.push(candidate);
776
+ }
777
+ return;
778
+ }
779
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
780
+ visit(candidate.left);
781
+ visit(candidate.right);
782
+ return;
783
+ }
784
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
785
+ visit(candidate.expression);
786
+ return;
787
+ }
788
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
789
+ if (candidate.argument) {
790
+ visit(candidate.argument);
791
+ }
792
+ if (candidate.filterCondition) {
793
+ visit(candidate.filterCondition);
794
+ }
795
+ return;
796
+ }
797
+ if (candidate instanceof ValueComponent_1.CastExpression) {
798
+ visit(candidate.input);
799
+ return;
800
+ }
801
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
802
+ if (candidate.condition) {
803
+ visit(candidate.condition);
804
+ }
805
+ for (const pair of candidate.switchCase.cases) {
806
+ visit(pair.key);
807
+ visit(pair.value);
808
+ }
809
+ if (candidate.switchCase.elseValue) {
810
+ visit(candidate.switchCase.elseValue);
811
+ }
812
+ return;
813
+ }
814
+ if (candidate instanceof ValueComponent_1.BetweenExpression) {
815
+ visit(candidate.expression);
816
+ visit(candidate.lower);
817
+ visit(candidate.upper);
818
+ return;
819
+ }
820
+ if (candidate instanceof ValueComponent_1.JsonPredicateExpression) {
821
+ visit(candidate.expression);
822
+ return;
823
+ }
824
+ if (candidate instanceof ValueComponent_1.ArrayExpression) {
825
+ visit(candidate.expression);
826
+ return;
827
+ }
828
+ if (candidate instanceof ValueComponent_1.ValueList) {
829
+ candidate.values.forEach(visit);
830
+ return;
831
+ }
832
+ if (candidate instanceof ValueComponent_1.TupleExpression) {
833
+ candidate.values.forEach(visit);
834
+ return;
835
+ }
836
+ if (candidate instanceof ValueComponent_1.TypeValue && candidate.argument) {
837
+ visit(candidate.argument);
838
+ }
839
+ };
840
+ visit(expression);
841
+ return references;
842
+ }
843
+ collectParameterNames(expression) {
844
+ const names = [];
845
+ const visit = (value) => {
846
+ const candidate = unwrapParens(value);
847
+ if (candidate instanceof ValueComponent_1.ParameterExpression) {
848
+ appendUnique(names, candidate.name.value);
849
+ return;
850
+ }
851
+ if (candidate instanceof ValueComponent_1.BinaryExpression) {
852
+ visit(candidate.left);
853
+ visit(candidate.right);
854
+ return;
855
+ }
856
+ if (candidate instanceof ValueComponent_1.UnaryExpression) {
857
+ visit(candidate.expression);
858
+ return;
859
+ }
860
+ if (candidate instanceof ValueComponent_1.FunctionCall) {
861
+ if (candidate.argument) {
862
+ visit(candidate.argument);
863
+ }
864
+ if (candidate.filterCondition) {
865
+ visit(candidate.filterCondition);
866
+ }
867
+ return;
868
+ }
869
+ if (candidate instanceof ValueComponent_1.CastExpression) {
870
+ visit(candidate.input);
871
+ return;
872
+ }
873
+ if (candidate instanceof ValueComponent_1.CaseExpression) {
874
+ if (candidate.condition) {
875
+ visit(candidate.condition);
876
+ }
877
+ for (const pair of candidate.switchCase.cases) {
878
+ visit(pair.key);
879
+ visit(pair.value);
880
+ }
881
+ if (candidate.switchCase.elseValue) {
882
+ visit(candidate.switchCase.elseValue);
883
+ }
884
+ return;
885
+ }
886
+ if (candidate instanceof ValueComponent_1.BetweenExpression) {
887
+ visit(candidate.expression);
888
+ visit(candidate.lower);
889
+ visit(candidate.upper);
890
+ return;
891
+ }
892
+ if (candidate instanceof ValueComponent_1.JsonPredicateExpression) {
893
+ visit(candidate.expression);
894
+ return;
895
+ }
896
+ if (candidate instanceof ValueComponent_1.ArrayExpression) {
897
+ visit(candidate.expression);
898
+ return;
899
+ }
900
+ if (candidate instanceof ValueComponent_1.ArrayQueryExpression || candidate instanceof ValueComponent_1.InlineQuery) {
901
+ return;
902
+ }
903
+ if (candidate instanceof ValueComponent_1.ValueList) {
904
+ candidate.values.forEach(visit);
905
+ return;
906
+ }
907
+ if (candidate instanceof ValueComponent_1.TupleExpression) {
908
+ candidate.values.forEach(visit);
909
+ return;
910
+ }
911
+ if (candidate instanceof ValueComponent_1.TypeValue && candidate.argument) {
912
+ visit(candidate.argument);
913
+ }
914
+ };
915
+ visit(expression);
916
+ return names;
917
+ }
918
+ makeSkipped(expression, draft) {
919
+ return {
920
+ conditionSql: formatSqlComponent(expression),
921
+ scopeId: "scope:root",
922
+ ...draft
923
+ };
924
+ }
925
+ buildResult(params) {
926
+ return {
927
+ ok: params.errors.length === 0,
928
+ sql: params.sql,
929
+ applied: params.applied,
930
+ skipped: params.skipped,
931
+ warnings: params.warnings,
932
+ errors: params.errors,
933
+ safety: {
934
+ mode: "safe_only",
935
+ unsafeRewriteApplied: false,
936
+ dryRun: params.dryRun,
937
+ formatterGeneratedSource: params.formatterGeneratedSource
938
+ },
939
+ conditionMoves: params.applied
940
+ };
941
+ }
942
+ }
943
+ exports.ParameterConditionPlacementOptimizer = ParameterConditionPlacementOptimizer;
944
+ const planParameterConditionOptimization = (input, options = {}) => {
945
+ return new ParameterConditionPlacementOptimizer().plan(input, options);
946
+ };
947
+ exports.planParameterConditionOptimization = planParameterConditionOptimization;
948
+ const optimizeParameterConditionPlacement = (input, options = {}) => {
949
+ return new ParameterConditionPlacementOptimizer().optimize(input, options);
950
+ };
951
+ exports.optimizeParameterConditionPlacement = optimizeParameterConditionPlacement;
952
+ //# sourceMappingURL=ParameterConditionPlacementOptimizer.js.map