rawsql-ts 0.19.0 → 0.20.0

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