@dbsp/core 6.1.2 → 6.2.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.
@@ -368,12 +368,12 @@ function walkIncludes(includes, visit, path) {
368
368
  var hasPathRef = (node) => own(node, "pathRef") === true && own(node, "kind") !== "relationFilter";
369
369
  function refuseTableRootedQuantifier(relation) {
370
370
  throw new Error(
371
- `RelationRef '${String(relation)}' follows a relation from its table; inside a relation predicate, quantifier callback or subquery body its path would be read from that body's row (#1005).`
371
+ `RelationRef '${String(relation)}' follows a relation from its table; inside a relation predicate, quantifier callback or subquery body its path would be read from that body's row (#1014).`
372
372
  );
373
373
  }
374
374
  function refusePathRef(node) {
375
375
  throw new Error(
376
- `ColumnRef '${String(own(node, "field"))}' follows a relation; inside a relation predicate, quantifier callback or subquery body its path would be read from that body's row (#1005).`
376
+ `ColumnRef '${String(own(node, "field"))}' follows a relation; inside a relation predicate, quantifier callback or subquery body its path would be read from that body's row (#1014).`
377
377
  );
378
378
  }
379
379
  function assertNoPathRefInQueryBodies(query) {
@@ -392,7 +392,7 @@ function assertCallbackScope(condition, scopeKey, scope, mode) {
392
392
  (node) => {
393
393
  const name = own(node, "field") ?? own(node, "relation");
394
394
  throw new Error(
395
- `'${String(name)}' comes from the ${mode}() callback parameter and is used inside a nested relation predicate or subquery body, where it would be read from that body's row (#1005).`
395
+ `'${String(name)}' comes from the ${mode}() callback parameter and is used inside a nested relation predicate or subquery body, where it would be read from that body's row (#1014).`
396
396
  );
397
397
  }
398
398
  );
@@ -668,15 +668,29 @@ function resolveSelectWhere(where, root, visible, allocator, model, initialAlias
668
668
  }
669
669
  function resolveConditionContext(where, root, visible, enclosing, allocator, model, initialAliasCount = 0, additionalOuterRanges = [], mode) {
670
670
  const label = mode?.label ?? "WHERE";
671
+ const labels = [label];
672
+ const currentLabel = () => labels[labels.length - 1];
673
+ let filterDepth = 0;
674
+ const within = (position, run) => {
675
+ const relabel = label === "HAVING" || mode?.fromHaving === true;
676
+ if (position === "FILTER") filterDepth++;
677
+ if (relabel) labels.push(position);
678
+ try {
679
+ return run();
680
+ } finally {
681
+ if (relabel) labels.pop();
682
+ if (position === "FILTER") filterDepth--;
683
+ }
684
+ };
671
685
  const entryDepth = enclosing.length;
672
686
  const assertTableRootedQuantifier = (node, current, ranges, scopes) => {
673
687
  const table = node.pathTable;
674
688
  if (table === void 0) return;
675
- if (mode?.unknownBody !== true && scopes.length <= entryDepth) return;
689
+ if (scopes.length <= entryDepth) return;
676
690
  const sameTable = new Set(
677
691
  [ranges, ...scopes].flat().filter((range) => range.table === table).map((range) => range.id)
678
692
  );
679
- if (mode?.unknownBody === true || current.table !== table || sameTable.size !== 1 || !sameTable.has(current.id))
693
+ if (current.table !== table || sameTable.size !== 1 || !sameTable.has(current.id))
680
694
  refuseTableRootedQuantifier(node.relation);
681
695
  };
682
696
  const subqueryRefusal = mode?.subqueryRefusal;
@@ -704,7 +718,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
704
718
  const assertQualifierVisible = (qualifier, ranges) => {
705
719
  if ((ranges === visible || ranges === rootScope || enclosing.includes(ranges)) && mode?.firstJoinByQualifier !== void 0 && mode.intentIndex !== void 0 && (mode.firstJoinByQualifier.get(qualifier) ?? -1) > mode.intentIndex && !visible.some((range) => range.alias === qualifier))
706
720
  throw new Error(
707
- `${label} qualifier '${qualifier}' is not visible in this query.`
721
+ `${currentLabel()} qualifier '${qualifier}' is not visible in this query.`
708
722
  );
709
723
  };
710
724
  const matchQualifier = (qualifier, scope, outer) => {
@@ -714,7 +728,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
714
728
  if (exact) return exact;
715
729
  if (candidates.length > 1)
716
730
  throw new Error(
717
- `${outer ? "outerRef" : label} qualifier '${qualifier}' is ambiguous between ${candidates.map((r) => `'${r.alias}'`).sort().join(", ")}${outer ? " in an enclosing query" : ""}.`
731
+ `${outer ? "outerRef" : currentLabel()} qualifier '${qualifier}' is ambiguous between ${candidates.map((r) => `'${r.alias}'`).sort().join(", ")}${outer ? " in an enclosing query" : ""}.`
718
732
  );
719
733
  return candidates[0];
720
734
  };
@@ -746,7 +760,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
746
760
  else if (mode?.include) range = allocator.bind(qualifier, qualifier);
747
761
  else
748
762
  throw new Error(
749
- `${label} qualifier '${qualifier}' is not visible in this query.`
763
+ `${currentLabel()} qualifier '${qualifier}' is not visible in this query.`
750
764
  );
751
765
  }
752
766
  if (mode?.include && parts.join(".") !== "*" && model && !model.getTable(range.table)?.columns.some((c) => c.name === parts.join(".")))
@@ -781,7 +795,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
781
795
  );
782
796
  if (rel.type === "belongsToMany")
783
797
  throw new Error(
784
- `${label} ${kind}('${segments.join(".")}'): many-to-many traversal is not supported yet (#787).`
798
+ `${currentLabel()} ${kind}('${segments.join(".")}'): many-to-many traversal is not supported yet (#787).`
785
799
  );
786
800
  names.push(rel.name);
787
801
  table = rel.target;
@@ -922,7 +936,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
922
936
  const trusted = getTrustedNqlRelationFilterFields2(node);
923
937
  if ("recursive" in node && node.recursive !== void 0 || trusted?.recursive)
924
938
  throw new Error(
925
- `${label} ${node.kind}('${segments.join(".")}'): recursive relation predicates are not supported inside ${label}.`
939
+ `${currentLabel()} ${node.kind}('${segments.join(".")}'): recursive relation predicates are not supported inside ${currentLabel()}.`
926
940
  );
927
941
  const path = trusted ? {
928
942
  ok: true,
@@ -1024,6 +1038,36 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1024
1038
  }
1025
1039
  };
1026
1040
  };
1041
+ const aliasActive = (ranges) => mode?.havingAliases !== void 0 && filterDepth === 0 && ranges === visible;
1042
+ const aggregateOperand = (aggregate, enclosing2) => ({
1043
+ kind: "aggregate",
1044
+ function: aggregate.function,
1045
+ ...aggregate.field && aggregate.field !== "*" && {
1046
+ column: column(aggregate.field, root, visible, enclosing2)
1047
+ },
1048
+ ...aggregate.distinct === true && { distinct: true },
1049
+ ...aggregate.filter && {
1050
+ filter: within(
1051
+ "FILTER",
1052
+ () => visit(aggregate.filter, root, visible, enclosing2)
1053
+ )
1054
+ }
1055
+ });
1056
+ const aliasExpression = (name, ranges, enclosing2) => {
1057
+ const aggregate = aliasActive(ranges) ? mode.havingAliases.get(name) : void 0;
1058
+ if (!aggregate) return void 0;
1059
+ const operand = aggregateOperand(aggregate, enclosing2);
1060
+ return {
1061
+ kind: "call",
1062
+ aggregate: true,
1063
+ name: operand.function.toLowerCase(),
1064
+ args: [
1065
+ operand.column ? { kind: "ref", operand: operand.column } : { kind: "star" }
1066
+ ],
1067
+ ...operand.distinct && { distinct: true },
1068
+ ...operand.filter && { filter: operand.filter }
1069
+ };
1070
+ };
1027
1071
  const expression = (input, current, ranges, enclosing2) => {
1028
1072
  const ref3 = (name) => ({
1029
1073
  kind: "ref",
@@ -1051,6 +1095,10 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1051
1095
  };
1052
1096
  switch (input.kind) {
1053
1097
  case "ref":
1098
+ if (!("outer" in input && input.outer)) {
1099
+ const aliased = aliasExpression(input.column, ranges, enclosing2);
1100
+ if (aliased) return aliased;
1101
+ }
1054
1102
  return {
1055
1103
  kind: "ref",
1056
1104
  ...mode?.include && current.id !== root.id && !input.column.includes(".") && !("outer" in input && input.outer) && {
@@ -1066,7 +1114,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1066
1114
  };
1067
1115
  case "column":
1068
1116
  case "columnAlias":
1069
- return ref3(input.column);
1117
+ return aliasExpression(input.column, ranges, enclosing2) ?? ref3(input.column);
1070
1118
  case "relationColumn":
1071
1119
  return ref3(`${input.relation}.${input.column}`);
1072
1120
  case "param":
@@ -1148,7 +1196,10 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1148
1196
  args: input.args.map(expr),
1149
1197
  ...input.distinct !== void 0 && { distinct: input.distinct },
1150
1198
  ...input.filter && {
1151
- filter: visit(input.filter, current, ranges, enclosing2)
1199
+ filter: within(
1200
+ "FILTER",
1201
+ () => visit(input.filter, current, ranges, enclosing2)
1202
+ )
1152
1203
  },
1153
1204
  ...input.aggOrderBy && {
1154
1205
  orderBy: input.aggOrderBy.map((o) => ({
@@ -1168,14 +1219,20 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1168
1219
  ],
1169
1220
  ...input.distinct !== void 0 && { distinct: input.distinct },
1170
1221
  ...input.filter && {
1171
- filter: visit(input.filter, current, ranges, enclosing2)
1222
+ filter: within(
1223
+ "FILTER",
1224
+ () => visit(input.filter, current, ranges, enclosing2)
1225
+ )
1172
1226
  }
1173
1227
  };
1174
1228
  case "case":
1175
1229
  return {
1176
1230
  kind: "case",
1177
1231
  branches: input.when.map((b) => ({
1178
- condition: visit(b.condition, current, ranges, enclosing2),
1232
+ condition: within(
1233
+ "CASE WHEN",
1234
+ () => visit(b.condition, current, ranges, enclosing2)
1235
+ ),
1179
1236
  result: caseValue(b.result)
1180
1237
  })),
1181
1238
  ...input.else !== void 0 && { fallback: caseValue(input.else) }
@@ -1247,7 +1304,13 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1247
1304
  node.where
1248
1305
  );
1249
1306
  }
1250
- if (fieldOverride === void 0 && !mode?.include && "field" in node && node.field.includes(".")) {
1307
+ const alias = fieldOverride === void 0 && "field" in node && aliasActive(ranges) ? mode.havingAliases.get(node.field) : void 0;
1308
+ if (alias && (node.kind === "like" || node.kind === "range" || node.kind === "jsonContains" || node.kind === "jsonExists"))
1309
+ throw new Error(
1310
+ `HAVING alias '${node.field}' names an aggregate; a ${node.kind} condition does not apply to it.`
1311
+ );
1312
+ const aliasOperand = alias && aggregateOperand(alias, enclosing2);
1313
+ if (!aliasOperand && fieldOverride === void 0 && !mode?.include && "field" in node && node.field.includes(".")) {
1251
1314
  const parts = node.field.split(".");
1252
1315
  const qualifier = parts[0];
1253
1316
  const found = matchQualifier(qualifier, ranges, false);
@@ -1270,6 +1333,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1270
1333
  if (!("field" in node)) throw new Error("Condition requires a column");
1271
1334
  return column(fieldOverride ?? node.field, current, ranges, enclosing2);
1272
1335
  };
1336
+ const leftOperand = () => aliasOperand || left();
1273
1337
  const rhs = (value, cast2) => {
1274
1338
  if (isParamIntent3(value)) return parameter(value, cast2);
1275
1339
  if (isFieldRef(value))
@@ -1297,9 +1361,13 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1297
1361
  case "comparison":
1298
1362
  return {
1299
1363
  kind: "comparison",
1300
- left: left(),
1364
+ left: leftOperand(),
1301
1365
  operator: node.operator,
1302
- right: rhs(node.value, node.jsonPath ? "none" : "column-db-type"),
1366
+ // A param() wrapper compared with an aggregate keeps the aggregate's cast.
1367
+ right: rhs(
1368
+ aliasOperand ? authoredParam(node.value) : node.value,
1369
+ node.jsonPath ? "none" : "column-db-type"
1370
+ ),
1303
1371
  ...node.jsonPath && {
1304
1372
  jsonPath: node.jsonPath.map((v) => parameter(v))
1305
1373
  },
@@ -1316,7 +1384,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1316
1384
  case "in":
1317
1385
  return {
1318
1386
  kind: "in",
1319
- left: left(),
1387
+ left: leftOperand(),
1320
1388
  negated: node.not === true,
1321
1389
  operand: node.subquery ? {
1322
1390
  kind: "subquery",
@@ -1332,11 +1400,11 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1332
1400
  case "any":
1333
1401
  return {
1334
1402
  kind: "any",
1335
- left: left(),
1403
+ left: leftOperand(),
1336
1404
  values: parameter(node.values, "any-array")
1337
1405
  };
1338
1406
  case "null":
1339
- return { kind: "null", left: left(), operator: node.operator };
1407
+ return { kind: "null", left: leftOperand(), operator: node.operator };
1340
1408
  case "range":
1341
1409
  return {
1342
1410
  kind: "range",
@@ -1372,7 +1440,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1372
1440
  return {
1373
1441
  kind: "subquery",
1374
1442
  use: "scalar",
1375
- left: left(),
1443
+ left: leftOperand(),
1376
1444
  operator: node.operator,
1377
1445
  body: body(node.subquery, "scalar", ranges, enclosing2)
1378
1446
  };
@@ -1403,6 +1471,7 @@ function assertScanDefaultFilter(condition, range, model) {
1403
1471
  throw new Error(part);
1404
1472
  };
1405
1473
  const column = (operand) => {
1474
+ if (operand.kind === "aggregate") refuse("forbidden operand 'aggregate'");
1406
1475
  if (operand.kind !== "column" || operand.range !== range)
1407
1476
  refuse("forbidden column range or outer reference");
1408
1477
  if (model && !model.getTable(table)?.columns.some((column2) => column2.name === operand.column))
@@ -3837,6 +3906,163 @@ function relationJoinHops(relation, alias) {
3837
3906
  }
3838
3907
 
3839
3908
  // src/resolved-includes.ts
3909
+ function dataEntries(value) {
3910
+ const entries = [];
3911
+ for (const key of Object.keys(value)) {
3912
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3913
+ if (descriptor && "value" in descriptor)
3914
+ entries.push([key, descriptor.value]);
3915
+ }
3916
+ return entries;
3917
+ }
3918
+ function absorbsBody(node) {
3919
+ return [
3920
+ "exists",
3921
+ "notExists",
3922
+ "relationFilter",
3923
+ "rawExists",
3924
+ "rawNotExists"
3925
+ ].includes(String(node.kind)) || (node.kind === "subquery" || node.kind === "in") && (node.subquery !== void 0 || node.query !== void 0);
3926
+ }
3927
+ function copyNode(value, child) {
3928
+ const copy = Array.isArray(value) ? Object.setPrototypeOf(
3929
+ new Array(value.length),
3930
+ Object.getPrototypeOf(value)
3931
+ ) : Object.create(Object.getPrototypeOf(value));
3932
+ for (const key of Reflect.ownKeys(value)) {
3933
+ if (Array.isArray(value) && key === "length") continue;
3934
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3935
+ Object.defineProperty(
3936
+ copy,
3937
+ key,
3938
+ "value" in descriptor ? {
3939
+ ...descriptor,
3940
+ value: typeof key === "string" ? child(key, descriptor.value) : descriptor.value,
3941
+ writable: true,
3942
+ configurable: true
3943
+ } : { ...descriptor, configurable: true }
3944
+ );
3945
+ }
3946
+ return copy;
3947
+ }
3948
+ function copyRepeatedOccurrences(intent) {
3949
+ const counts = /* @__PURE__ */ new Map();
3950
+ const walk2 = (value, path) => {
3951
+ if (!value || typeof value !== "object" || isParamIntent4(value)) return;
3952
+ if (path.has(value)) return;
3953
+ const node = value;
3954
+ if (!Array.isArray(value)) {
3955
+ if (node.kind === "literal" || node.kind === "param") return;
3956
+ counts.set(value, (counts.get(value) ?? 0) + 1);
3957
+ if (absorbsBody(node)) return;
3958
+ }
3959
+ path.add(value);
3960
+ for (const [key, child] of dataEntries(node)) {
3961
+ if (!Array.isArray(value) && isBoundPayload(node, key, child)) continue;
3962
+ walk2(child, path);
3963
+ }
3964
+ path.delete(value);
3965
+ };
3966
+ const positions = ["where", "having", "select", "orderBy"];
3967
+ for (const position of positions) walk2(intent[position], /* @__PURE__ */ new Set());
3968
+ if (![...counts.values()].some((n) => n > 1)) return intent;
3969
+ const repeated = /* @__PURE__ */ new Map();
3970
+ const holdsRepeated = (value, path) => {
3971
+ if (!value || typeof value !== "object" || isParamIntent4(value))
3972
+ return false;
3973
+ const known = repeated.get(value);
3974
+ if (known !== void 0) return known;
3975
+ if (path.has(value)) return false;
3976
+ const node = value;
3977
+ let result = (counts.get(value) ?? 0) > 1;
3978
+ if (!result && (Array.isArray(value) || !absorbsBody(node))) {
3979
+ path.add(value);
3980
+ result = dataEntries(node).some(
3981
+ ([key, child]) => (Array.isArray(value) || !isBoundPayload(node, key, child)) && holdsRepeated(child, path)
3982
+ );
3983
+ path.delete(value);
3984
+ }
3985
+ repeated.set(value, result);
3986
+ return result;
3987
+ };
3988
+ const copy = (value, path) => {
3989
+ if (!holdsRepeated(value, /* @__PURE__ */ new Set()) || path.has(value))
3990
+ return value;
3991
+ const node = value;
3992
+ const absorbed = !Array.isArray(value) && absorbsBody(node);
3993
+ path.add(value);
3994
+ const result = copyNode(
3995
+ value,
3996
+ (key, child) => absorbed || !Array.isArray(value) && isBoundPayload(node, key, child) ? child : copy(child, path)
3997
+ );
3998
+ path.delete(value);
3999
+ return result;
4000
+ };
4001
+ const replaced = /* @__PURE__ */ new Map();
4002
+ for (const position of ["having", "select", "orderBy"]) {
4003
+ const next = copy(intent[position], /* @__PURE__ */ new Set());
4004
+ if (next !== intent[position]) replaced.set(position, next);
4005
+ }
4006
+ if (replaced.size === 0) return intent;
4007
+ return copyNode(
4008
+ intent,
4009
+ (key, child) => replaced.has(key) ? replaced.get(key) : child
4010
+ );
4011
+ }
4012
+ function havingAggregateAliases(select) {
4013
+ const aliases = /* @__PURE__ */ new Map();
4014
+ const add = (as, aggregate) => {
4015
+ if (as === void 0 || aliases.has(as)) return;
4016
+ aliases.set(as, {
4017
+ function: aggregate.function,
4018
+ ...aggregate.field !== void 0 && { field: aggregate.field },
4019
+ ...aggregate.distinct === true && { distinct: true },
4020
+ ...aggregate.filter !== void 0 && { filter: aggregate.filter }
4021
+ });
4022
+ };
4023
+ if (select?.type === "aggregate")
4024
+ for (const aggregate of select.aggregates) add(aggregate.as, aggregate);
4025
+ else if (select?.type === "expressions") {
4026
+ for (const column of select.columns)
4027
+ if (column.kind === "aggregate" && (column.field || column.function === "count" && !column.extraArgs?.length))
4028
+ add(column.as, column);
4029
+ }
4030
+ return aliases;
4031
+ }
4032
+ function dataValue(value, key) {
4033
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
4034
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
4035
+ }
4036
+ function conditionRefs(node) {
4037
+ const names = [];
4038
+ const walk2 = (value2) => {
4039
+ if (!value2 || typeof value2 !== "object" || isParamIntent4(value2)) return;
4040
+ if (Array.isArray(value2)) {
4041
+ value2.forEach(walk2);
4042
+ return;
4043
+ }
4044
+ const item = value2;
4045
+ const intent2 = dataValue(item, "intent");
4046
+ if (intent2 && typeof intent2 === "object") {
4047
+ walk2(intent2);
4048
+ return;
4049
+ }
4050
+ if (item.kind === "literal" || item.kind === "param") return;
4051
+ if (item.kind === "ref" && item.outer !== true || item.kind === "column" || item.kind === "columnAlias") {
4052
+ if (typeof item.column === "string") names.push(item.column);
4053
+ return;
4054
+ }
4055
+ for (const [key, child] of dataEntries(item)) {
4056
+ if (key === "query" || key === "subquery" || key === "filter") continue;
4057
+ walk2(child);
4058
+ }
4059
+ };
4060
+ const value = dataValue(node, "value");
4061
+ const intent = value && typeof value === "object" ? dataValue(value, "intent") : void 0;
4062
+ if (intent && typeof intent === "object") walk2(intent);
4063
+ if (node.kind === "expression") walk2(dataValue(node, "expr"));
4064
+ return names;
4065
+ }
3840
4066
  function assertSupportedIncludeWhere(includes, strategies, parent = "", intentParent = "", parentStrategy) {
3841
4067
  for (const [index, include] of (includes ?? []).entries()) {
3842
4068
  const path = `${parent}include[${index}](${include.relation})`;
@@ -4254,6 +4480,7 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4254
4480
  const alreadyApplied = intent.where === rootFilterIntent || intent.where?.kind === "and" && intent.where.conditions[0] === rootFilterIntent;
4255
4481
  if (rootDefaultFilter && !alreadyApplied)
4256
4482
  where = where ? { kind: "and", conditions: [rootDefaultFilter, where] } : rootDefaultFilter;
4483
+ const executable = copyRepeatedOccurrences(intent);
4257
4484
  const expressionConditions = [];
4258
4485
  const expressionSubqueries = [];
4259
4486
  const inspected = /* @__PURE__ */ new WeakSet();
@@ -4268,39 +4495,29 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4268
4495
  "jsonContains",
4269
4496
  "jsonExists"
4270
4497
  ].includes(String(node.kind)) && typeof node.field === "string" && node.field.includes(".");
4271
- const havingDotted = /* @__PURE__ */ new WeakSet();
4272
- const absorbsBody = (node) => [
4273
- "exists",
4274
- "notExists",
4275
- "relationFilter",
4276
- "rawExists",
4277
- "rawNotExists"
4278
- ].includes(String(node.kind)) || (node.kind === "subquery" || node.kind === "in") && (node.subquery !== void 0 || node.query !== void 0);
4279
- const collectHavingDotted = (value, seen) => {
4280
- if (!value || typeof value !== "object" || isParamIntent4(value)) return;
4281
- if (seen.has(value)) return;
4282
- seen.add(value);
4283
- if (Array.isArray(value)) {
4284
- for (const child of value) collectHavingDotted(child, seen);
4285
- return;
4286
- }
4287
- const node = value;
4288
- if (dottedField(node) || node.kind === "subquery" && typeof node.field === "string" && node.field.includes("."))
4289
- havingDotted.add(value);
4290
- if (absorbsBody(node)) return;
4291
- for (const [key, child] of Object.entries(node)) {
4292
- if (isBoundPayload(node, key, child)) continue;
4293
- collectHavingDotted(child, seen);
4294
- }
4295
- };
4296
- collectHavingDotted(intent.having, /* @__PURE__ */ new Set());
4297
- const inspect = (value, intentPath, condition, belowBody = false) => {
4498
+ const havingAliases = havingAggregateAliases(intent.select);
4499
+ const namesAlias = (node) => havingAliases.size > 0 && (typeof node.field === "string" && havingAliases.has(node.field) || conditionRefs(node).some((name) => havingAliases.has(name)));
4500
+ const invisibleQualifier = (node, inHaving) => conditionRefs(node).some((name) => {
4501
+ const dot = name.indexOf(".");
4502
+ if (dot < 0 || inHaving && havingAliases.has(name)) return false;
4503
+ const qualifier = name.slice(0, dot);
4504
+ return !visible.some(
4505
+ (range) => range.alias === qualifier || range.table === qualifier
4506
+ );
4507
+ });
4508
+ const inspect = (value, intentPath, condition, inHaving = false, underHaving = false) => {
4298
4509
  if (!value || typeof value !== "object" || isParamIntent4(value)) return;
4299
4510
  if (inspected.has(value)) return;
4300
4511
  inspected.add(value);
4301
4512
  if (Array.isArray(value)) {
4302
4513
  value.forEach((child, index) => {
4303
- inspect(child, `${intentPath}[${index}]`, condition, belowBody);
4514
+ inspect(
4515
+ child,
4516
+ `${intentPath}[${index}]`,
4517
+ condition,
4518
+ inHaving,
4519
+ underHaving
4520
+ );
4304
4521
  });
4305
4522
  inspected.delete(value);
4306
4523
  return;
@@ -4329,10 +4546,7 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4329
4546
  model,
4330
4547
  0,
4331
4548
  [],
4332
- {
4333
- defaultFilters: options.defaultFilters,
4334
- ...belowBody && { unknownBody: true }
4335
- }
4549
+ { defaultFilters: options.defaultFilters }
4336
4550
  );
4337
4551
  if (resolved?.kind === "expression" && resolved.expression.kind === "subquery")
4338
4552
  expressionSubqueries.push({
@@ -4342,21 +4556,14 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4342
4556
  inspected.delete(value);
4343
4557
  return;
4344
4558
  }
4345
- const predicate = [
4559
+ const relationSensitive = [
4346
4560
  "exists",
4347
4561
  "notExists",
4348
4562
  "relationFilter",
4349
4563
  "rawExists",
4350
4564
  "rawNotExists"
4351
4565
  ].includes(String(node.kind)) || node.kind === "subquery" && node.subquery || node.kind === "in" && node.subquery || dottedField(node);
4352
- const legacy = havingDotted.has(value);
4353
- if (predicate && model && condition && (!legacy || node.subquery && getRelationalReadPolicy(node.subquery) || findDefaultFilterScan(
4354
- { type: "select", from: rootRange.table, where: node },
4355
- model,
4356
- options.defaultFilters,
4357
- intentPath,
4358
- true
4359
- ))) {
4566
+ if (condition && (relationSensitive && model || inHaving && namesAlias(node) || invisibleQualifier(node, inHaving))) {
4360
4567
  const resolved = resolveConditionContext(
4361
4568
  node,
4362
4569
  rootRange,
@@ -4364,15 +4571,14 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4364
4571
  [],
4365
4572
  allocator,
4366
4573
  model,
4367
- legacy ? 0 : expressionAliases.count,
4574
+ expressionAliases.count,
4368
4575
  [],
4369
4576
  {
4370
- ...legacy ? { defaultFilters: options.defaultFilters } : {
4371
- defaultFilters: options.defaultFilters,
4372
- label: condition,
4373
- aliasState: expressionAliases
4374
- },
4375
- ...belowBody && { unknownBody: true }
4577
+ defaultFilters: options.defaultFilters,
4578
+ label: condition,
4579
+ aliasState: expressionAliases,
4580
+ ...inHaving && { havingAliases },
4581
+ ...underHaving && { fromHaving: true }
4376
4582
  }
4377
4583
  );
4378
4584
  if (!resolved)
@@ -4381,6 +4587,10 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4381
4587
  inspected.delete(value);
4382
4588
  return;
4383
4589
  }
4590
+ if (absorbsBody(node)) {
4591
+ inspected.delete(value);
4592
+ return;
4593
+ }
4384
4594
  for (const [key, child] of Object.entries(node)) {
4385
4595
  if (isBoundPayload(node, key, child)) continue;
4386
4596
  if (node.kind === "case" && key === "when" && Array.isArray(child)) {
@@ -4391,7 +4601,8 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4391
4601
  bchild,
4392
4602
  `${intentPath}.when[${index}].${bkey}`,
4393
4603
  bkey === "condition" ? "CASE WHEN" : condition,
4394
- belowBody
4604
+ inHaving,
4605
+ underHaving
4395
4606
  );
4396
4607
  }
4397
4608
  });
@@ -4402,23 +4613,25 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4402
4613
  child,
4403
4614
  `${intentPath}.${key}`,
4404
4615
  filterRoot ? "FILTER" : condition,
4405
- belowBody || key === "subquery" || key === "query" || key === "where" && ["exists", "notExists", "relationFilter"].includes(
4406
- String(node.kind)
4407
- )
4616
+ inHaving && !filterRoot,
4617
+ underHaving
4408
4618
  );
4409
4619
  }
4410
4620
  inspected.delete(value);
4411
4621
  };
4412
- inspect(intent.select, "select");
4413
- inspect(intent.orderBy, "orderBy");
4414
- inspect(intent.having, "having", "HAVING");
4622
+ inspect(executable.select, "select");
4623
+ inspect(executable.orderBy, "orderBy");
4624
+ inspect(executable.having, "having", "HAVING", true, true);
4415
4625
  return {
4416
- rootRange,
4417
- joins,
4418
- includes,
4419
- ...where && { where },
4420
- ...expressionSubqueries.length && { expressionSubqueries },
4421
- ...expressionConditions.length && { expressionConditions }
4626
+ execution: {
4627
+ rootRange,
4628
+ joins,
4629
+ includes,
4630
+ ...where && { where },
4631
+ ...expressionSubqueries.length && { expressionSubqueries },
4632
+ ...expressionConditions.length && { expressionConditions }
4633
+ },
4634
+ intent: executable
4422
4635
  };
4423
4636
  }
4424
4637
  function observeIncludeDecisions(decisions) {
@@ -4657,22 +4870,29 @@ function plan(intent, model, options = {}) {
4657
4870
  relationsAnalyzed: state.relationsAnalyzed,
4658
4871
  isAmbiguous: false
4659
4872
  });
4660
- const report = {
4661
- rootTable: intent.from,
4662
- execution: resolveReportIncludes(plannedIntent, state.decisions, model, {
4873
+ const resolution = resolveReportIncludes(
4874
+ plannedIntent,
4875
+ state.decisions,
4876
+ model,
4877
+ {
4663
4878
  whereReservedNames: opts.whereReservedNames,
4664
4879
  defaultFilters: opts.defaultFilters
4665
- }),
4880
+ }
4881
+ );
4882
+ const report = {
4883
+ rootTable: intent.from,
4884
+ execution: resolution.execution,
4666
4885
  decisions: Object.freeze(observeIncludeDecisions(state.decisions)),
4667
4886
  warnings: Object.freeze(state.warnings.slice()),
4668
4887
  ctes: Object.freeze(state.ctes.slice()),
4669
4888
  // intent is ALWAYS the original submitted intent (contract: observable via dump()).
4670
- // executableIntent carries the optimized WHERE (e.g. IN→EXISTS) when the
4671
- // optimizer rewrote it, so the adapter compiles the correct SQL from that field.
4672
- // When no optimization applies, executableIntent is left undefined and the
4673
- // adapter falls back to intent.
4889
+ // executableIntent is the intent the adapter compiles: the optimized WHERE
4890
+ // (e.g. IN→EXISTS) and per-occurrence copies of shared conditions. When it
4891
+ // equals intent it is left undefined and the adapter falls back to intent.
4674
4892
  intent,
4675
- ...plannedIntent !== intent && { executableIntent: plannedIntent },
4893
+ ...resolution.intent !== intent && {
4894
+ executableIntent: resolution.intent
4895
+ },
4676
4896
  metadata
4677
4897
  };
4678
4898
  return markPlannedReport(report);
@@ -21211,18 +21431,22 @@ function createBindingFinalPlan(intent, bundle, model, dialectCapabilities, defa
21211
21431
  )
21212
21432
  ];
21213
21433
  });
21434
+ const resolution = resolveReportIncludes(intent, decisions, model, {
21435
+ ...defaultFilters && {
21436
+ defaultFilters: queryLocalDefaultFilters(bundle, defaultFilters)
21437
+ },
21438
+ skipRootDefaultFilter: true
21439
+ });
21214
21440
  return markPlannedReport2({
21215
21441
  rootTable: intent.from,
21216
- execution: resolveReportIncludes(intent, decisions, model, {
21217
- ...defaultFilters && {
21218
- defaultFilters: queryLocalDefaultFilters(bundle, defaultFilters)
21219
- },
21220
- skipRootDefaultFilter: true
21221
- }),
21442
+ execution: resolution.execution,
21222
21443
  decisions: observeIncludeDecisions(decisions),
21223
21444
  warnings: [],
21224
21445
  ctes: [],
21225
21446
  intent,
21447
+ ...resolution.intent !== intent && {
21448
+ executableIntent: resolution.intent
21449
+ },
21226
21450
  metadata: {
21227
21451
  planningTimeMs: 0,
21228
21452
  relationsAnalyzed: 0,
@@ -27258,4 +27482,4 @@ export {
27258
27482
  runAssertions,
27259
27483
  isOverallSuccess
27260
27484
  };
27261
- //# sourceMappingURL=chunk-RIQOPLZ5.js.map
27485
+ //# sourceMappingURL=chunk-64RIEJGN.js.map