@dbsp/core 6.1.1 → 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.
@@ -262,6 +262,142 @@ ${errors.map((e) => ` - ${e}`).join("\n")}`
262
262
  }
263
263
  };
264
264
 
265
+ // src/path-ref-scan.ts
266
+ import { EXPRESSION_BRAND } from "@dbsp/types";
267
+ var RELATION_BODIES = /* @__PURE__ */ new Set(["exists", "notExists", "relationFilter"]);
268
+ function isObject(value) {
269
+ return value !== null && typeof value === "object";
270
+ }
271
+ function own(node, key) {
272
+ const descriptor = Object.getOwnPropertyDescriptor(node, key);
273
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
274
+ }
275
+ function items(array2) {
276
+ return Object.values(Object.getOwnPropertyDescriptors(array2)).filter((descriptor) => descriptor.enumerable && "value" in descriptor).map((descriptor) => descriptor.value);
277
+ }
278
+ function isPayload(kind, key, child) {
279
+ if (key !== "value" && key !== "values") return false;
280
+ if (kind === "namedArg") return false;
281
+ return !isObject(child) || !(EXPRESSION_BRAND in child);
282
+ }
283
+ function hasDottedField(node) {
284
+ const field = own(node, "field");
285
+ return typeof field === "string" && field.includes(".");
286
+ }
287
+ function walk(value, inBody, path, matches, onHit) {
288
+ if (!isObject(value) || path.has(value)) return;
289
+ path.add(value);
290
+ if (Array.isArray(value)) {
291
+ for (const child of items(value)) walk(child, inBody, path, matches, onHit);
292
+ path.delete(value);
293
+ return;
294
+ }
295
+ const kind = own(value, "kind");
296
+ if (kind === "literal" || kind === "param") {
297
+ path.delete(value);
298
+ return;
299
+ }
300
+ if (inBody && matches(value)) onHit(value);
301
+ const relationBody = RELATION_BODIES.has(String(kind));
302
+ const dotted = hasDottedField(value);
303
+ for (const [key, descriptor] of Object.entries(
304
+ Object.getOwnPropertyDescriptors(value)
305
+ )) {
306
+ if (!("value" in descriptor) || !descriptor.enumerable) continue;
307
+ const child = descriptor.value;
308
+ if (key === "defaultValue" || isPayload(kind, key, child)) continue;
309
+ if ((key === "subquery" || key === "query") && isObject(child))
310
+ walkQuery(child, true, path, matches, onHit);
311
+ else
312
+ walk(
313
+ child,
314
+ inBody || relationBody || dotted && (key === "value" || key === "values"),
315
+ path,
316
+ matches,
317
+ onHit
318
+ );
319
+ }
320
+ path.delete(value);
321
+ }
322
+ function walkQuery(query, inBody, path, matches, onHit) {
323
+ if (path.has(query)) return;
324
+ path.add(query);
325
+ const visit = (child) => walk(child, inBody, path, matches, onHit);
326
+ if (own(query, "kind") === "setOperation") {
327
+ for (const side of [own(query, "left"), own(query, "right")])
328
+ if (isObject(side)) walkQuery(side, inBody, path, matches, onHit);
329
+ path.delete(query);
330
+ return;
331
+ }
332
+ visit(own(query, "where"));
333
+ visit(own(query, "having"));
334
+ const joins = own(query, "joins");
335
+ if (Array.isArray(joins)) {
336
+ for (const join of items(joins)) if (isObject(join)) visit(own(join, "on"));
337
+ }
338
+ walkIncludes(own(query, "include"), visit, path);
339
+ const select = own(query, "select");
340
+ if (isObject(select)) {
341
+ const columns = own(select, "columns");
342
+ if (Array.isArray(columns)) visit(columns);
343
+ const aggregates = own(select, "aggregates");
344
+ if (Array.isArray(aggregates)) {
345
+ for (const aggregate of items(aggregates))
346
+ if (isObject(aggregate)) visit(own(aggregate, "filter"));
347
+ }
348
+ }
349
+ const orderBy = own(query, "orderBy");
350
+ if (Array.isArray(orderBy)) {
351
+ for (const order of items(orderBy))
352
+ if (isObject(order)) visit(own(order, "expression"));
353
+ }
354
+ path.delete(query);
355
+ }
356
+ function walkIncludes(includes, visit, path) {
357
+ if (!Array.isArray(includes) || path.has(includes)) return;
358
+ path.add(includes);
359
+ for (const include of items(includes)) {
360
+ if (!isObject(include) || path.has(include)) continue;
361
+ path.add(include);
362
+ visit(own(include, "where"));
363
+ walkIncludes(own(include, "include"), visit, path);
364
+ path.delete(include);
365
+ }
366
+ path.delete(includes);
367
+ }
368
+ var hasPathRef = (node) => own(node, "pathRef") === true && own(node, "kind") !== "relationFilter";
369
+ function refuseTableRootedQuantifier(relation) {
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 (#1014).`
372
+ );
373
+ }
374
+ function refusePathRef(node) {
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 (#1014).`
377
+ );
378
+ }
379
+ function assertNoPathRefInQueryBodies(query) {
380
+ if (isObject(query))
381
+ walkQuery(query, false, /* @__PURE__ */ new Set(), hasPathRef, refusePathRef);
382
+ }
383
+ function assertNoPathRefInConditionBodies(condition) {
384
+ walk(condition, false, /* @__PURE__ */ new Set(), hasPathRef, refusePathRef);
385
+ }
386
+ function assertCallbackScope(condition, scopeKey, scope, mode) {
387
+ walk(
388
+ condition,
389
+ false,
390
+ /* @__PURE__ */ new Set(),
391
+ (node) => own(node, scopeKey) === scope,
392
+ (node) => {
393
+ const name = own(node, "field") ?? own(node, "relation");
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 (#1014).`
396
+ );
397
+ }
398
+ );
399
+ }
400
+
265
401
  // src/relational-read-plans.ts
266
402
  import {
267
403
  isParamIntent as isParamIntent2
@@ -272,11 +408,11 @@ import { isParamIntent } from "@dbsp/types";
272
408
  import { getTrustedNqlRelationFilterFields } from "@dbsp/types/internal";
273
409
 
274
410
  // src/intent-payload.ts
275
- import { EXPRESSION_BRAND } from "@dbsp/types";
411
+ import { EXPRESSION_BRAND as EXPRESSION_BRAND2 } from "@dbsp/types";
276
412
  function isBoundPayload(node, key, child) {
277
413
  if (key !== "value" && key !== "values") return false;
278
414
  if (node.kind === "namedArg") return false;
279
- return !child || typeof child !== "object" || !(EXPRESSION_BRAND in child);
415
+ return !child || typeof child !== "object" || !(EXPRESSION_BRAND2 in child);
280
416
  }
281
417
 
282
418
  // src/dx/default-filter-refusals.ts
@@ -492,7 +628,7 @@ function escapeDiagnosticText(value) {
492
628
 
493
629
  // src/resolved-conditions.ts
494
630
  import {
495
- EXPRESSION_BRAND as EXPRESSION_BRAND2,
631
+ EXPRESSION_BRAND as EXPRESSION_BRAND3,
496
632
  isParamIntent as isParamIntent3,
497
633
  RangeAllocator,
498
634
  REF_BRAND
@@ -505,7 +641,7 @@ import {
505
641
  resolveDeclaredRelationPath
506
642
  } from "@dbsp/types/internal";
507
643
  function isExpression(value) {
508
- return value !== null && typeof value === "object" && EXPRESSION_BRAND2 in value;
644
+ return value !== null && typeof value === "object" && EXPRESSION_BRAND3 in value;
509
645
  }
510
646
  function isRef(value) {
511
647
  return value !== null && typeof value === "object" && REF_BRAND in value;
@@ -518,6 +654,7 @@ function containsOuterReference(value) {
518
654
  );
519
655
  }
520
656
  function resolveSelectWhere(where, root, visible, allocator, model, initialAliasCount = 0, additionalOuterRanges = []) {
657
+ assertNoPathRefInConditionBodies(where);
521
658
  return resolveConditionContext(
522
659
  where,
523
660
  root,
@@ -530,6 +667,32 @@ function resolveSelectWhere(where, root, visible, allocator, model, initialAlias
530
667
  );
531
668
  }
532
669
  function resolveConditionContext(where, root, visible, enclosing, allocator, model, initialAliasCount = 0, additionalOuterRanges = [], mode) {
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
+ };
685
+ const entryDepth = enclosing.length;
686
+ const assertTableRootedQuantifier = (node, current, ranges, scopes) => {
687
+ const table = node.pathTable;
688
+ if (table === void 0) return;
689
+ if (scopes.length <= entryDepth) return;
690
+ const sameTable = new Set(
691
+ [ranges, ...scopes].flat().filter((range) => range.table === table).map((range) => range.id)
692
+ );
693
+ if (current.table !== table || sameTable.size !== 1 || !sameTable.has(current.id))
694
+ refuseTableRootedQuantifier(node.relation);
695
+ };
533
696
  const subqueryRefusal = mode?.subqueryRefusal;
534
697
  let activeFilters = mode?.defaultFilters;
535
698
  const rootScope = [.../* @__PURE__ */ new Set([root, ...visible, ...additionalOuterRanges])];
@@ -555,19 +718,17 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
555
718
  const assertQualifierVisible = (qualifier, ranges) => {
556
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))
557
720
  throw new Error(
558
- `WHERE qualifier '${qualifier}' is not visible in this query.`
721
+ `${currentLabel()} qualifier '${qualifier}' is not visible in this query.`
559
722
  );
560
723
  };
561
724
  const matchQualifier = (qualifier, scope, outer) => {
562
725
  assertQualifierVisible(qualifier, scope);
563
726
  const candidates = scope.filter((r) => r.table === qualifier);
564
- const exact = writtenQualifiers.get(scope)?.get(qualifier) ?? scope.find(
565
- (r) => r.alias === qualifier && (r !== scope[0] || r.alias !== r.table || candidates.length < 2)
566
- );
727
+ const exact = writtenQualifiers.get(scope)?.get(qualifier) ?? scope.find((r) => r.alias === qualifier);
567
728
  if (exact) return exact;
568
729
  if (candidates.length > 1)
569
730
  throw new Error(
570
- `${outer ? "outerRef" : "WHERE"} 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" : ""}.`
571
732
  );
572
733
  return candidates[0];
573
734
  };
@@ -599,7 +760,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
599
760
  else if (mode?.include) range = allocator.bind(qualifier, qualifier);
600
761
  else
601
762
  throw new Error(
602
- `WHERE qualifier '${qualifier}' is not visible in this query.`
763
+ `${currentLabel()} qualifier '${qualifier}' is not visible in this query.`
603
764
  );
604
765
  }
605
766
  if (mode?.include && parts.join(".") !== "*" && model && !model.getTable(range.table)?.columns.some((c) => c.name === parts.join(".")))
@@ -634,7 +795,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
634
795
  );
635
796
  if (rel.type === "belongsToMany")
636
797
  throw new Error(
637
- `WHERE ${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).`
638
799
  );
639
800
  names.push(rel.name);
640
801
  table = rel.target;
@@ -775,7 +936,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
775
936
  const trusted = getTrustedNqlRelationFilterFields2(node);
776
937
  if ("recursive" in node && node.recursive !== void 0 || trusted?.recursive)
777
938
  throw new Error(
778
- `WHERE ${node.kind}('${segments.join(".")}'): recursive relation predicates are not supported inside WHERE.`
939
+ `${currentLabel()} ${node.kind}('${segments.join(".")}'): recursive relation predicates are not supported inside ${currentLabel()}.`
779
940
  );
780
941
  const path = trusted ? {
781
942
  ok: true,
@@ -877,6 +1038,36 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
877
1038
  }
878
1039
  };
879
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
+ };
880
1071
  const expression = (input, current, ranges, enclosing2) => {
881
1072
  const ref3 = (name) => ({
882
1073
  kind: "ref",
@@ -904,6 +1095,10 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
904
1095
  };
905
1096
  switch (input.kind) {
906
1097
  case "ref":
1098
+ if (!("outer" in input && input.outer)) {
1099
+ const aliased = aliasExpression(input.column, ranges, enclosing2);
1100
+ if (aliased) return aliased;
1101
+ }
907
1102
  return {
908
1103
  kind: "ref",
909
1104
  ...mode?.include && current.id !== root.id && !input.column.includes(".") && !("outer" in input && input.outer) && {
@@ -919,7 +1114,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
919
1114
  };
920
1115
  case "column":
921
1116
  case "columnAlias":
922
- return ref3(input.column);
1117
+ return aliasExpression(input.column, ranges, enclosing2) ?? ref3(input.column);
923
1118
  case "relationColumn":
924
1119
  return ref3(`${input.relation}.${input.column}`);
925
1120
  case "param":
@@ -1001,7 +1196,10 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1001
1196
  args: input.args.map(expr),
1002
1197
  ...input.distinct !== void 0 && { distinct: input.distinct },
1003
1198
  ...input.filter && {
1004
- filter: visit(input.filter, current, ranges, enclosing2)
1199
+ filter: within(
1200
+ "FILTER",
1201
+ () => visit(input.filter, current, ranges, enclosing2)
1202
+ )
1005
1203
  },
1006
1204
  ...input.aggOrderBy && {
1007
1205
  orderBy: input.aggOrderBy.map((o) => ({
@@ -1021,14 +1219,20 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1021
1219
  ],
1022
1220
  ...input.distinct !== void 0 && { distinct: input.distinct },
1023
1221
  ...input.filter && {
1024
- filter: visit(input.filter, current, ranges, enclosing2)
1222
+ filter: within(
1223
+ "FILTER",
1224
+ () => visit(input.filter, current, ranges, enclosing2)
1225
+ )
1025
1226
  }
1026
1227
  };
1027
1228
  case "case":
1028
1229
  return {
1029
1230
  kind: "case",
1030
1231
  branches: input.when.map((b) => ({
1031
- condition: visit(b.condition, current, ranges, enclosing2),
1232
+ condition: within(
1233
+ "CASE WHEN",
1234
+ () => visit(b.condition, current, ranges, enclosing2)
1235
+ ),
1032
1236
  result: caseValue(b.result)
1033
1237
  })),
1034
1238
  ...input.else !== void 0 && { fallback: caseValue(input.else) }
@@ -1039,12 +1243,16 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1039
1243
  );
1040
1244
  }
1041
1245
  };
1042
- const parameter = (value, cast2 = "none") => ({
1043
- kind: "parameter",
1044
- value: isParamIntent3(value) ? value.value : value,
1045
- cast: cast2,
1046
- bound: isParamIntent3(value)
1047
- });
1246
+ const authoredParam = (value) => isExpression(value) && isParamIntent3(value.intent) ? value.intent : value;
1247
+ const parameter = (value, cast2 = "none") => {
1248
+ const authored = authoredParam(value);
1249
+ return {
1250
+ kind: "parameter",
1251
+ value: isParamIntent3(authored) ? authored.value : authored,
1252
+ cast: cast2,
1253
+ bound: isParamIntent3(authored)
1254
+ };
1255
+ };
1048
1256
  const rangeParameter = (value) => {
1049
1257
  const authored = parameter(value, "range");
1050
1258
  if (authored.bound) return authored;
@@ -1059,12 +1267,14 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1059
1267
  return authored;
1060
1268
  return { ...authored, cast: "range-element" };
1061
1269
  };
1062
- const normalizeList = (value) => {
1270
+ const normalizeList = (raw2) => {
1271
+ const value = authoredParam(raw2);
1063
1272
  if (isParamIntent3(value)) return value;
1064
1273
  if (!Array.isArray(value)) return value;
1065
- if (value.length === 1 && isParamIntent3(value[0]) && Array.isArray(value[0].value))
1066
- return value[0];
1067
- return value.map((v) => isParamIntent3(v) ? v.value : v);
1274
+ const items2 = value.map(authoredParam);
1275
+ if (items2.length === 1 && isParamIntent3(items2[0]) && Array.isArray(items2[0].value))
1276
+ return items2[0];
1277
+ return items2.map((v) => isParamIntent3(v) ? v.value : v);
1068
1278
  };
1069
1279
  const visit = (node, current, ranges, enclosing2, fieldOverride) => {
1070
1280
  if (current === root && node === getDefaultFilter(activeFilters, root.table) && mode?.rootDefaultFilter)
@@ -1082,6 +1292,8 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1082
1292
  condition: visit(node.condition, current, ranges, enclosing2)
1083
1293
  };
1084
1294
  if (node.kind === "exists" || node.kind === "notExists" || node.kind === "relationFilter") {
1295
+ if (node.kind === "relationFilter")
1296
+ assertTableRootedQuantifier(node, current, ranges, enclosing2);
1085
1297
  const name = getTrustedNqlRelationFilterFields2(node)?.relation ?? node.relation;
1086
1298
  return relation(
1087
1299
  node,
@@ -1092,7 +1304,13 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1092
1304
  node.where
1093
1305
  );
1094
1306
  }
1095
- 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(".")) {
1096
1314
  const parts = node.field.split(".");
1097
1315
  const qualifier = parts[0];
1098
1316
  const found = matchQualifier(qualifier, ranges, false);
@@ -1115,6 +1333,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1115
1333
  if (!("field" in node)) throw new Error("Condition requires a column");
1116
1334
  return column(fieldOverride ?? node.field, current, ranges, enclosing2);
1117
1335
  };
1336
+ const leftOperand = () => aliasOperand || left();
1118
1337
  const rhs = (value, cast2) => {
1119
1338
  if (isParamIntent3(value)) return parameter(value, cast2);
1120
1339
  if (isFieldRef(value))
@@ -1142,9 +1361,13 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1142
1361
  case "comparison":
1143
1362
  return {
1144
1363
  kind: "comparison",
1145
- left: left(),
1364
+ left: leftOperand(),
1146
1365
  operator: node.operator,
1147
- 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
+ ),
1148
1371
  ...node.jsonPath && {
1149
1372
  jsonPath: node.jsonPath.map((v) => parameter(v))
1150
1373
  },
@@ -1161,7 +1384,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1161
1384
  case "in":
1162
1385
  return {
1163
1386
  kind: "in",
1164
- left: left(),
1387
+ left: leftOperand(),
1165
1388
  negated: node.not === true,
1166
1389
  operand: node.subquery ? {
1167
1390
  kind: "subquery",
@@ -1177,11 +1400,11 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1177
1400
  case "any":
1178
1401
  return {
1179
1402
  kind: "any",
1180
- left: left(),
1403
+ left: leftOperand(),
1181
1404
  values: parameter(node.values, "any-array")
1182
1405
  };
1183
1406
  case "null":
1184
- return { kind: "null", left: left(), operator: node.operator };
1407
+ return { kind: "null", left: leftOperand(), operator: node.operator };
1185
1408
  case "range":
1186
1409
  return {
1187
1410
  kind: "range",
@@ -1217,7 +1440,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1217
1440
  return {
1218
1441
  kind: "subquery",
1219
1442
  use: "scalar",
1220
- left: left(),
1443
+ left: leftOperand(),
1221
1444
  operator: node.operator,
1222
1445
  body: body(node.subquery, "scalar", ranges, enclosing2)
1223
1446
  };
@@ -1248,6 +1471,7 @@ function assertScanDefaultFilter(condition, range, model) {
1248
1471
  throw new Error(part);
1249
1472
  };
1250
1473
  const column = (operand) => {
1474
+ if (operand.kind === "aggregate") refuse("forbidden operand 'aggregate'");
1251
1475
  if (operand.kind !== "column" || operand.range !== range)
1252
1476
  refuse("forbidden column range or outer reference");
1253
1477
  if (model && !model.getTable(table)?.columns.some((column2) => column2.name === operand.column))
@@ -1783,7 +2007,7 @@ var Errors = {
1783
2007
  };
1784
2008
 
1785
2009
  // src/dx/subquery-builder.ts
1786
- import { brandValue, EXPRESSION_BRAND as EXPRESSION_BRAND3 } from "@dbsp/types";
2010
+ import { brandValue, EXPRESSION_BRAND as EXPRESSION_BRAND4 } from "@dbsp/types";
1787
2011
  var SubqueryBuilder = class _SubqueryBuilder {
1788
2012
  _from;
1789
2013
  _select;
@@ -1961,7 +2185,7 @@ var SubqueryExpression = class {
1961
2185
  {
1962
2186
  intent: { kind: "subquery", query: this.intent, as: alias }
1963
2187
  },
1964
- EXPRESSION_BRAND3,
2188
+ EXPRESSION_BRAND4,
1965
2189
  true
1966
2190
  );
1967
2191
  }
@@ -2108,6 +2332,11 @@ var COLUMN_META = /* @__PURE__ */ Symbol.for("dbsp:column");
2108
2332
  var RELATION_META = /* @__PURE__ */ Symbol.for("dbsp:relation");
2109
2333
  var BRAND = /* @__PURE__ */ Symbol.for("dbsp:brand");
2110
2334
  var RELATION_PATH = /* @__PURE__ */ Symbol.for("dbsp:relationPath");
2335
+ var RELATION_REROOT = /* @__PURE__ */ Symbol("dbsp:relationReroot");
2336
+ var RELATION_FROM_TABLE = /* @__PURE__ */ Symbol.for(
2337
+ "dbsp:relationFromTable"
2338
+ );
2339
+ var CALLBACK_SCOPE = /* @__PURE__ */ Symbol.for("dbsp:callbackScope");
2111
2340
 
2112
2341
  // src/dx/table-ref-factory.ts
2113
2342
  var JS_RESERVED_WORDS = /* @__PURE__ */ new Set([
@@ -2160,7 +2389,7 @@ function warnReservedWord(tableName, columnName, suppress) {
2160
2389
  warnedReservedWords.add(dedupKey);
2161
2390
  }
2162
2391
  }
2163
- function createColumnRef(tableName, columnName, relationPath) {
2392
+ function createColumnRef(tableName, columnName, relationPath, scope) {
2164
2393
  const columnRef = {
2165
2394
  [TABLE_META]: tableName,
2166
2395
  [COLUMN_META]: columnName,
@@ -2173,16 +2402,24 @@ function createColumnRef(tableName, columnName, relationPath) {
2173
2402
  `Invalid alias "${alias}": must match /^[a-zA-Z_][a-zA-Z0-9_]*$/`
2174
2403
  );
2175
2404
  }
2176
- return {
2177
- ...this,
2178
- _alias: alias
2179
- };
2405
+ return withCallbackScope(
2406
+ { ...this, _alias: alias },
2407
+ this[CALLBACK_SCOPE]
2408
+ );
2180
2409
  }
2181
2410
  };
2182
- if (relationPath && relationPath.length > 0) {
2411
+ if (relationPath !== void 0) {
2183
2412
  columnRef[RELATION_PATH] = relationPath;
2184
2413
  }
2185
- return columnRef;
2414
+ return withCallbackScope(columnRef, scope);
2415
+ }
2416
+ function withCallbackScope(target, scope) {
2417
+ if (scope !== void 0)
2418
+ Object.defineProperty(target, CALLBACK_SCOPE, {
2419
+ value: scope,
2420
+ enumerable: false
2421
+ });
2422
+ return target;
2186
2423
  }
2187
2424
  function createAllColumns(tableName) {
2188
2425
  return {
@@ -2211,16 +2448,23 @@ function hasColumn(columns, columnName) {
2211
2448
  function getColumnNames(columns) {
2212
2449
  return columns.map((col2) => col2.name);
2213
2450
  }
2214
- function createRelationRef(targetTable, relationType, model, relationName, parentPath) {
2451
+ function createRelationRef(targetTable, relationType, model, relationName, parentPath, origin = {}) {
2215
2452
  const currentPath = relationName !== void 0 ? [...parentPath ?? [], relationName] : parentPath ?? [];
2216
2453
  const base = {
2217
2454
  [RELATION_META]: { target: targetTable, type: relationType },
2218
2455
  [BRAND]: "RelationRef",
2219
2456
  [RELATION_PATH]: currentPath,
2220
2457
  // Store path on RelationRef too
2458
+ [RELATION_REROOT]: (scope) => createRelationRef(targetTable, relationType, model, void 0, [], {
2459
+ ...scope !== void 0 && { scope }
2460
+ }),
2461
+ ...origin.fromTable !== void 0 && {
2462
+ [RELATION_FROM_TABLE]: origin.fromTable
2463
+ },
2221
2464
  _type: void 0
2222
2465
  // Phantom type placeholder
2223
2466
  };
2467
+ withCallbackScope(base, origin.scope);
2224
2468
  return new Proxy(base, {
2225
2469
  get(target, prop, receiver) {
2226
2470
  if (typeof prop === "symbol") {
@@ -2234,7 +2478,12 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2234
2478
  }
2235
2479
  const targetTableIR = model.getTable(targetTable);
2236
2480
  if (targetTableIR && hasColumn(targetTableIR.columns, prop)) {
2237
- return createColumnRef(targetTable, prop, currentPath);
2481
+ return createColumnRef(
2482
+ targetTable,
2483
+ prop,
2484
+ currentPath,
2485
+ origin.scope
2486
+ );
2238
2487
  }
2239
2488
  for (const rel of model.getRelationsFrom(targetTable)) {
2240
2489
  if (rel.name === prop) {
@@ -2243,7 +2492,8 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2243
2492
  mapRelationType(rel.type),
2244
2493
  model,
2245
2494
  prop,
2246
- currentPath
2495
+ currentPath,
2496
+ origin
2247
2497
  );
2248
2498
  }
2249
2499
  }
@@ -2254,7 +2504,8 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2254
2504
  "hasMany",
2255
2505
  model,
2256
2506
  prop,
2257
- currentPath
2507
+ currentPath,
2508
+ origin
2258
2509
  );
2259
2510
  }
2260
2511
  }
@@ -2339,7 +2590,9 @@ function createTableRef(tableName, model, suppress) {
2339
2590
  relation.target,
2340
2591
  relation.type,
2341
2592
  model,
2342
- propStr
2593
+ propStr,
2594
+ void 0,
2595
+ { fromTable: tableName }
2343
2596
  );
2344
2597
  }
2345
2598
  return void 0;
@@ -3618,7 +3871,7 @@ function pluralize(name) {
3618
3871
 
3619
3872
  // src/resolved-includes.ts
3620
3873
  import {
3621
- EXPRESSION_BRAND as EXPRESSION_BRAND4,
3874
+ EXPRESSION_BRAND as EXPRESSION_BRAND5,
3622
3875
  isParamIntent as isParamIntent4,
3623
3876
  RangeAllocator as RangeAllocator3,
3624
3877
  toColumnList
@@ -3653,6 +3906,163 @@ function relationJoinHops(relation, alias) {
3653
3906
  }
3654
3907
 
3655
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
+ }
3656
4066
  function assertSupportedIncludeWhere(includes, strategies, parent = "", intentParent = "", parentStrategy) {
3657
4067
  for (const [index, include] of (includes ?? []).entries()) {
3658
4068
  const path = `${parent}include[${index}](${include.relation})`;
@@ -3677,7 +4087,7 @@ function assertSupportedIncludeWhere(includes, strategies, parent = "", intentPa
3677
4087
  );
3678
4088
  }
3679
4089
  for (const [key, child] of Object.entries(record3)) {
3680
- const expressionValue = child !== null && typeof child === "object" && EXPRESSION_BRAND4 in child;
4090
+ const expressionValue = child !== null && typeof child === "object" && EXPRESSION_BRAND5 in child;
3681
4091
  if (key === "values" || key === "value" && record3.kind !== "namedArg" && (record3.kind === "literal" || !expressionValue))
3682
4092
  continue;
3683
4093
  visit(child);
@@ -4070,16 +4480,44 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4070
4480
  const alreadyApplied = intent.where === rootFilterIntent || intent.where?.kind === "and" && intent.where.conditions[0] === rootFilterIntent;
4071
4481
  if (rootDefaultFilter && !alreadyApplied)
4072
4482
  where = where ? { kind: "and", conditions: [rootDefaultFilter, where] } : rootDefaultFilter;
4483
+ const executable = copyRepeatedOccurrences(intent);
4073
4484
  const expressionConditions = [];
4074
4485
  const expressionSubqueries = [];
4075
4486
  const inspected = /* @__PURE__ */ new WeakSet();
4076
- const inspect = (value, intentPath) => {
4487
+ const expressionAliases = { count: 0 };
4488
+ const dottedField = (node) => [
4489
+ "comparison",
4490
+ "like",
4491
+ "in",
4492
+ "any",
4493
+ "null",
4494
+ "range",
4495
+ "jsonContains",
4496
+ "jsonExists"
4497
+ ].includes(String(node.kind)) && typeof node.field === "string" && node.field.includes(".");
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) => {
4077
4509
  if (!value || typeof value !== "object" || isParamIntent4(value)) return;
4078
4510
  if (inspected.has(value)) return;
4079
4511
  inspected.add(value);
4080
4512
  if (Array.isArray(value)) {
4081
4513
  value.forEach((child, index) => {
4082
- inspect(child, `${intentPath}[${index}]`);
4514
+ inspect(
4515
+ child,
4516
+ `${intentPath}[${index}]`,
4517
+ condition,
4518
+ inHaving,
4519
+ underHaving
4520
+ );
4083
4521
  });
4084
4522
  inspected.delete(value);
4085
4523
  return;
@@ -4118,53 +4556,82 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4118
4556
  inspected.delete(value);
4119
4557
  return;
4120
4558
  }
4121
- const predicate = [
4559
+ const relationSensitive = [
4122
4560
  "exists",
4123
4561
  "notExists",
4124
4562
  "relationFilter",
4125
4563
  "rawExists",
4126
4564
  "rawNotExists"
4127
- ].includes(String(node.kind)) || node.kind === "subquery" && node.subquery || node.kind === "in" && node.subquery || typeof node.field === "string" && node.field.includes(".");
4128
- if (predicate && model && (node.subquery && getRelationalReadPolicy(node.subquery) || findDefaultFilterScan(
4129
- { type: "select", from: rootRange.table, where: node },
4130
- model,
4131
- options.defaultFilters,
4132
- intentPath,
4133
- true
4134
- ))) {
4135
- const condition = resolveConditionContext(
4565
+ ].includes(String(node.kind)) || node.kind === "subquery" && node.subquery || node.kind === "in" && node.subquery || dottedField(node);
4566
+ if (condition && (relationSensitive && model || inHaving && namesAlias(node) || invisibleQualifier(node, inHaving))) {
4567
+ const resolved = resolveConditionContext(
4136
4568
  node,
4137
4569
  rootRange,
4138
4570
  visible,
4139
4571
  [],
4140
4572
  allocator,
4141
4573
  model,
4142
- 0,
4574
+ expressionAliases.count,
4143
4575
  [],
4144
- { defaultFilters: options.defaultFilters }
4576
+ {
4577
+ defaultFilters: options.defaultFilters,
4578
+ label: condition,
4579
+ aliasState: expressionAliases,
4580
+ ...inHaving && { havingAliases },
4581
+ ...underHaving && { fromHaving: true }
4582
+ }
4145
4583
  );
4146
- if (!condition)
4584
+ if (!resolved)
4147
4585
  throw new Error(`Missing resolved condition at ${intentPath}`);
4148
- expressionConditions.push({ intentPath, condition });
4586
+ expressionConditions.push({ intentPath, condition: resolved });
4587
+ inspected.delete(value);
4588
+ return;
4589
+ }
4590
+ if (absorbsBody(node)) {
4149
4591
  inspected.delete(value);
4150
4592
  return;
4151
4593
  }
4152
4594
  for (const [key, child] of Object.entries(node)) {
4153
4595
  if (isBoundPayload(node, key, child)) continue;
4154
- inspect(child, `${intentPath}.${key}`);
4596
+ if (node.kind === "case" && key === "when" && Array.isArray(child)) {
4597
+ child.forEach((branch, index) => {
4598
+ if (!branch || typeof branch !== "object") return;
4599
+ for (const [bkey, bchild] of Object.entries(branch)) {
4600
+ inspect(
4601
+ bchild,
4602
+ `${intentPath}.when[${index}].${bkey}`,
4603
+ bkey === "condition" ? "CASE WHEN" : condition,
4604
+ inHaving,
4605
+ underHaving
4606
+ );
4607
+ }
4608
+ });
4609
+ continue;
4610
+ }
4611
+ const filterRoot = key === "filter" && (node.kind === "customFn" || node.kind === "aggregate" || node.kind === void 0 && typeof node.function === "string");
4612
+ inspect(
4613
+ child,
4614
+ `${intentPath}.${key}`,
4615
+ filterRoot ? "FILTER" : condition,
4616
+ inHaving && !filterRoot,
4617
+ underHaving
4618
+ );
4155
4619
  }
4156
4620
  inspected.delete(value);
4157
4621
  };
4158
- inspect(intent.select, "select");
4159
- inspect(intent.orderBy, "orderBy");
4160
- inspect(intent.having, "having");
4622
+ inspect(executable.select, "select");
4623
+ inspect(executable.orderBy, "orderBy");
4624
+ inspect(executable.having, "having", "HAVING", true, true);
4161
4625
  return {
4162
- rootRange,
4163
- joins,
4164
- includes,
4165
- ...where && { where },
4166
- ...expressionSubqueries.length && { expressionSubqueries },
4167
- ...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
4168
4635
  };
4169
4636
  }
4170
4637
  function observeIncludeDecisions(decisions) {
@@ -4288,6 +4755,7 @@ function validateRecursiveShape(intent) {
4288
4755
  }
4289
4756
  }
4290
4757
  function plan(intent, model, options = {}) {
4758
+ assertNoPathRefInQueryBodies(intent);
4291
4759
  const startTime = performance.now();
4292
4760
  const state = {
4293
4761
  decisions: [],
@@ -4402,22 +4870,29 @@ function plan(intent, model, options = {}) {
4402
4870
  relationsAnalyzed: state.relationsAnalyzed,
4403
4871
  isAmbiguous: false
4404
4872
  });
4405
- const report = {
4406
- rootTable: intent.from,
4407
- execution: resolveReportIncludes(plannedIntent, state.decisions, model, {
4873
+ const resolution = resolveReportIncludes(
4874
+ plannedIntent,
4875
+ state.decisions,
4876
+ model,
4877
+ {
4408
4878
  whereReservedNames: opts.whereReservedNames,
4409
4879
  defaultFilters: opts.defaultFilters
4410
- }),
4880
+ }
4881
+ );
4882
+ const report = {
4883
+ rootTable: intent.from,
4884
+ execution: resolution.execution,
4411
4885
  decisions: Object.freeze(observeIncludeDecisions(state.decisions)),
4412
4886
  warnings: Object.freeze(state.warnings.slice()),
4413
4887
  ctes: Object.freeze(state.ctes.slice()),
4414
4888
  // intent is ALWAYS the original submitted intent (contract: observable via dump()).
4415
- // executableIntent carries the optimized WHERE (e.g. IN→EXISTS) when the
4416
- // optimizer rewrote it, so the adapter compiles the correct SQL from that field.
4417
- // When no optimization applies, executableIntent is left undefined and the
4418
- // 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.
4419
4892
  intent,
4420
- ...plannedIntent !== intent && { executableIntent: plannedIntent },
4893
+ ...resolution.intent !== intent && {
4894
+ executableIntent: resolution.intent
4895
+ },
4421
4896
  metadata
4422
4897
  };
4423
4898
  return markPlannedReport(report);
@@ -4434,7 +4909,6 @@ function planRecursive(intent, model, options = {}) {
4434
4909
  {
4435
4910
  type: "select",
4436
4911
  from: startFrom,
4437
- where: intent.start.where,
4438
4912
  select: intent.start.select,
4439
4913
  nodeIdExpr: intent.start.nodeIdExpr
4440
4914
  },
@@ -4499,6 +4973,18 @@ function planRecursive(intent, model, options = {}) {
4499
4973
  if (!startTable) {
4500
4974
  throw new Error(`Unknown table: ${startFrom}`);
4501
4975
  }
4976
+ assertNoPathRefInConditionBodies(intent.start.where);
4977
+ const startWhere = intent.start.where ? resolveConditionContext(
4978
+ intent.start.where,
4979
+ anchorRange,
4980
+ [anchorRange],
4981
+ [],
4982
+ allocator,
4983
+ model,
4984
+ 0,
4985
+ [],
4986
+ { defaultFilters: options.defaultFilters, label: "start.where" }
4987
+ ) : void 0;
4502
4988
  const traversalKind = intent.traversal.kind;
4503
4989
  const recursiveCteDecision = {
4504
4990
  id: generateDecisionId(state, "recursive-cte"),
@@ -4554,8 +5040,9 @@ function planRecursive(intent, model, options = {}) {
4554
5040
  const planningTimeMs = performance.now() - startTime;
4555
5041
  const dedupeStrategy = intent.dedupe ?? "none";
4556
5042
  const report = {
4557
- ...(anchorFilter || stepFilter) && {
5043
+ ...(anchorFilter || stepFilter || startWhere) && {
4558
5044
  recursiveFilters: {
5045
+ ...startWhere && { start: startWhere },
4559
5046
  ...anchorFilter && { anchor: anchorFilter },
4560
5047
  ...stepFilter && { step: stepFilter }
4561
5048
  }
@@ -5544,8 +6031,8 @@ function validateRecursiveSetOperation(intent, model, capabilities) {
5544
6031
  return;
5545
6032
  }
5546
6033
  const query = node;
5547
- const includes = (items, source, parent = "") => {
5548
- for (const [index, include] of items.entries()) {
6034
+ const includes = (items2, source, parent = "") => {
6035
+ for (const [index, include] of items2.entries()) {
5549
6036
  const relation = resolveIncludeRelationName2(
5550
6037
  model,
5551
6038
  source,
@@ -6029,7 +6516,7 @@ import { EXECUTION_CONTRACT_VERSION } from "@dbsp/types";
6029
6516
 
6030
6517
  // src/transition/minting.ts
6031
6518
  var minted = /* @__PURE__ */ new WeakSet();
6032
- function isObject(value) {
6519
+ function isObject2(value) {
6033
6520
  return typeof value === "object" && value !== null || typeof value === "function";
6034
6521
  }
6035
6522
  function childPath(parent, key) {
@@ -6084,7 +6571,7 @@ function assertPlainDataAndFreeze(value, path, seen) {
6084
6571
  if (typeof value === "bigint" || typeof value === "symbol") {
6085
6572
  throw plainDataError(typeof value, path);
6086
6573
  }
6087
- if (!isObject(value)) {
6574
+ if (!isObject2(value)) {
6088
6575
  return;
6089
6576
  }
6090
6577
  if (seen.has(value)) {
@@ -6155,7 +6642,7 @@ function mintInProcessPlan(shape) {
6155
6642
  return shape;
6156
6643
  }
6157
6644
  function isMintedInProcessPlan(plan2) {
6158
- return isObject(plan2) && minted.has(plan2);
6645
+ return isObject2(plan2) && minted.has(plan2);
6159
6646
  }
6160
6647
 
6161
6648
  // src/transition/execution-contract.ts
@@ -7956,11 +8443,11 @@ function resolvePhysicalSessionRevocationLatch(physicalSession) {
7956
8443
  function mintTransitionSessionRevocationPropagation() {
7957
8444
  return Object.freeze({
7958
8445
  compromise() {
7959
- if (!isObject2(this)) return;
8446
+ if (!isObject3(this)) return;
7960
8447
  resolvePhysicalSessionRevocationLatch(this).compromised = true;
7961
8448
  },
7962
8449
  isCompromised() {
7963
- return isObject2(this) && resolvePhysicalSessionRevocationLatch(this).compromised;
8450
+ return isObject3(this) && resolvePhysicalSessionRevocationLatch(this).compromised;
7964
8451
  }
7965
8452
  });
7966
8453
  }
@@ -8212,7 +8699,7 @@ function lessorBrand(target) {
8212
8699
  function isTransitionSessionRevocationCapability(value) {
8213
8700
  return value != null && typeof value === "object" && Object.isFrozen(value) && typeof value.compromise === "function" && typeof value.isCompromised === "function";
8214
8701
  }
8215
- function isObject2(value) {
8702
+ function isObject3(value) {
8216
8703
  return value != null && (typeof value === "object" || typeof value === "function");
8217
8704
  }
8218
8705
  var TransitionLeaseFailureError = class extends Error {
@@ -11656,13 +12143,13 @@ function logicalIdentityChanged(desired, current) {
11656
12143
  }
11657
12144
  return stableJson(logicalIdentityForComparison(desired.logicalIdentity)) !== stableJson(logicalIdentityForComparison(current.logicalIdentity));
11658
12145
  }
11659
- function normalizeNamedMap(items, normalize, kind) {
11660
- if (!items) {
12146
+ function normalizeNamedMap(items2, normalize, kind) {
12147
+ if (!items2) {
11661
12148
  return { items: void 0, conflicts: [] };
11662
12149
  }
11663
12150
  const normalizedItems = /* @__PURE__ */ new Map();
11664
12151
  const conflicts = [];
11665
- for (const item of items.values()) {
12152
+ for (const item of items2.values()) {
11666
12153
  const normalized = { ...item, name: normalize(item.name) };
11667
12154
  if (normalizedItems.has(normalized.name)) {
11668
12155
  conflicts.push(
@@ -11782,23 +12269,23 @@ function managedRelationsForComparison(relations, externalTables) {
11782
12269
  function modelRelations(model) {
11783
12270
  return model.relations;
11784
12271
  }
11785
- function managedMapPolicy(items) {
11786
- if (items === void 0) {
12272
+ function managedMapPolicy(items2) {
12273
+ if (items2 === void 0) {
11787
12274
  return { managed: false };
11788
12275
  }
11789
- if (items.size === 0) {
12276
+ if (items2.size === 0) {
11790
12277
  return { managed: true };
11791
12278
  }
11792
- return { managed: true, keys: new Set(items.keys()) };
12279
+ return { managed: true, keys: new Set(items2.keys()) };
11793
12280
  }
11794
- function managedListPolicy(items) {
11795
- if (items === void 0) {
12281
+ function managedListPolicy(items2) {
12282
+ if (items2 === void 0) {
11796
12283
  return { managed: false };
11797
12284
  }
11798
- if (items.length === 0) {
12285
+ if (items2.length === 0) {
11799
12286
  return { managed: true };
11800
12287
  }
11801
- return { managed: true, keys: new Set(items) };
12288
+ return { managed: true, keys: new Set(items2) };
11802
12289
  }
11803
12290
  function managedRelationPolicy(relations, externalTables) {
11804
12291
  if (relations === void 0) {
@@ -11825,11 +12312,11 @@ function managedModelCollections(desired, externalTables) {
11825
12312
  function isManagedCollectionKey(policy, key) {
11826
12313
  return policy.managed && (policy.keys === void 0 || policy.keys.has(key));
11827
12314
  }
11828
- function projectManagedMapEntries(items, policy, valueForEntry = (_name, value) => value) {
12315
+ function projectManagedMapEntries(items2, policy, valueForEntry = (_name, value) => value) {
11829
12316
  if (!policy.managed) {
11830
12317
  return [];
11831
12318
  }
11832
- return [...(items ?? /* @__PURE__ */ new Map()).entries()].filter(([name]) => isManagedCollectionKey(policy, name)).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => [name, valueForEntry(name, value)]);
12319
+ return [...(items2 ?? /* @__PURE__ */ new Map()).entries()].filter(([name]) => isManagedCollectionKey(policy, name)).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => [name, valueForEntry(name, value)]);
11833
12320
  }
11834
12321
  function extensionNamesForComparison(extensions, policy) {
11835
12322
  if (!policy.managed) {
@@ -17645,7 +18132,7 @@ function batchValues(data, columns, types, opts) {
17645
18132
  }
17646
18133
 
17647
18134
  // src/dx/window-functions.ts
17648
- import { brandValue as brandValue3, EXPRESSION_BRAND as EXPRESSION_BRAND5 } from "@dbsp/types";
18135
+ import { brandValue as brandValue3, EXPRESSION_BRAND as EXPRESSION_BRAND6 } from "@dbsp/types";
17649
18136
 
17650
18137
  // src/dx/column-utils.ts
17651
18138
  function getColumnName(field) {
@@ -17656,7 +18143,20 @@ function getColumnName(field) {
17656
18143
  if (colName === void 0) {
17657
18144
  throw new Error("Invalid ColumnRef: missing COLUMN_META");
17658
18145
  }
17659
- return colName;
18146
+ const relationPath = field[RELATION_PATH];
18147
+ if (relationPath !== void 0) {
18148
+ return relationPath.length === 0 ? colName : `${relationPath.join(".")}.${colName}`;
18149
+ }
18150
+ const tableName = field[TABLE_META];
18151
+ if (tableName === void 0) {
18152
+ throw new Error("Invalid ColumnRef: missing TABLE_META");
18153
+ }
18154
+ return `${tableName}.${colName}`;
18155
+ }
18156
+ function isRelationPathColumn(field) {
18157
+ if (typeof field === "string") return false;
18158
+ const relationPath = field[RELATION_PATH];
18159
+ return relationPath !== void 0 && relationPath.length > 0;
17660
18160
  }
17661
18161
 
17662
18162
  // src/dx/window-functions.ts
@@ -17752,7 +18252,7 @@ var WindowBuilder = class _WindowBuilder {
17752
18252
  {
17753
18253
  intent: this.toWindowIntent(alias)
17754
18254
  },
17755
- EXPRESSION_BRAND5,
18255
+ EXPRESSION_BRAND6,
17756
18256
  true
17757
18257
  );
17758
18258
  }
@@ -17829,7 +18329,7 @@ function lead(field) {
17829
18329
  }
17830
18330
 
17831
18331
  // src/dx/filters.ts
17832
- import { brandValue as brandValue4, EXPRESSION_BRAND as EXPRESSION_BRAND6 } from "@dbsp/types";
18332
+ import { brandValue as brandValue4, EXPRESSION_BRAND as EXPRESSION_BRAND7 } from "@dbsp/types";
17833
18333
  function distinct(field) {
17834
18334
  return { field, distinct: true };
17835
18335
  }
@@ -17837,12 +18337,16 @@ function isDistinctField(value) {
17837
18337
  return typeof value === "object" && value !== null && "field" in value && typeof value.field === "string" && "distinct" in value && value.distinct === true;
17838
18338
  }
17839
18339
  function createComparisonFilter(operator) {
17840
- return (field, value) => ({
17841
- kind: "comparison",
17842
- field: getColumnName(field),
17843
- operator,
17844
- value
17845
- });
18340
+ return (field, value) => scoped(
18341
+ {
18342
+ kind: "comparison",
18343
+ field: getColumnName(field),
18344
+ operator,
18345
+ value,
18346
+ ...isRelationPathColumn(field) && { pathRef: true }
18347
+ },
18348
+ field
18349
+ );
17846
18350
  }
17847
18351
  var eq = createComparisonFilter("eq");
17848
18352
  var neq = createComparisonFilter("neq");
@@ -17857,33 +18361,70 @@ function like(field, pattern, options) {
17857
18361
  const intent = {
17858
18362
  kind: "like",
17859
18363
  field: getColumnName(field),
17860
- pattern
18364
+ pattern,
18365
+ ...isRelationPathColumn(field) && { pathRef: true }
17861
18366
  };
17862
18367
  const withCi = caseInsensitive !== void 0 ? { ...intent, caseInsensitive } : intent;
17863
18368
  if (escapeChar !== void 0) {
17864
- return { ...withCi, escape: escapeChar };
18369
+ return scoped({ ...withCi, escape: escapeChar }, field);
17865
18370
  }
17866
- return withCi;
18371
+ return scoped(withCi, field);
17867
18372
  }
17868
18373
  function inArray(field, values) {
17869
- return { kind: "in", field: getColumnName(field), values };
18374
+ return scoped(
18375
+ {
18376
+ kind: "in",
18377
+ field: getColumnName(field),
18378
+ values,
18379
+ ...isRelationPathColumn(field) && { pathRef: true }
18380
+ },
18381
+ field
18382
+ );
17870
18383
  }
17871
18384
  function inSubquery(field, query) {
17872
18385
  const expr = "build" in query ? query.build() : query;
17873
- return {
17874
- kind: "in",
17875
- field: getColumnName(field),
17876
- subquery: expr.toIntent()
17877
- };
18386
+ return scoped(
18387
+ {
18388
+ kind: "in",
18389
+ field: getColumnName(field),
18390
+ subquery: expr.toIntent(),
18391
+ ...isRelationPathColumn(field) && { pathRef: true }
18392
+ },
18393
+ field
18394
+ );
17878
18395
  }
17879
18396
  function any(field, values) {
17880
- return { kind: "any", field: getColumnName(field), values };
18397
+ return scoped(
18398
+ {
18399
+ kind: "any",
18400
+ field: getColumnName(field),
18401
+ values,
18402
+ ...isRelationPathColumn(field) && { pathRef: true }
18403
+ },
18404
+ field
18405
+ );
17881
18406
  }
17882
18407
  function isNull(field) {
17883
- return { kind: "null", field: getColumnName(field), operator: "isNull" };
18408
+ return scoped(
18409
+ {
18410
+ kind: "null",
18411
+ field: getColumnName(field),
18412
+ operator: "isNull",
18413
+ ...isRelationPathColumn(field) && { pathRef: true }
18414
+ },
18415
+ field
18416
+ );
17884
18417
  }
17885
18418
  function isNotNull(field) {
17886
- return { kind: "null", field: getColumnName(field), operator: "isNotNull" };
18419
+ return scoped(
18420
+ {
18421
+ kind: "null",
18422
+ field: getColumnName(field),
18423
+ operator: "isNotNull",
18424
+ ...isRelationPathColumn(field) && { pathRef: true }
18425
+ },
18426
+ field
18427
+ );
17887
18428
  }
17888
18429
  function and(...conditions) {
17889
18430
  const flatConditions = conditions.length === 1 && Array.isArray(conditions[0]) ? conditions[0] : conditions;
@@ -17938,37 +18479,47 @@ function getRelationName(rel) {
17938
18479
  if (!meta) {
17939
18480
  throw new Error("Invalid RelationRef: missing RELATION_META");
17940
18481
  }
17941
- return meta.target;
18482
+ const path = rel[RELATION_PATH];
18483
+ return path !== void 0 && path.length > 0 ? path.join(".") : meta.target;
17942
18484
  }
17943
- function every(relation, filter) {
18485
+ function rerootRelation(rel, scope) {
18486
+ const reroot = rel[RELATION_REROOT];
18487
+ return reroot === void 0 ? rel : reroot(scope);
18488
+ }
18489
+ function quantify(mode, relation, filter) {
17944
18490
  const relationName = getRelationName(relation);
17945
- const where = filter(relation);
17946
- return {
17947
- kind: "relationFilter",
17948
- relation: relationName,
17949
- where,
17950
- mode: "every"
17951
- };
18491
+ const scope = {};
18492
+ const where = filter(rerootRelation(relation, scope));
18493
+ assertCallbackScope(where, CALLBACK_SCOPE, scope, mode);
18494
+ const origin = relation;
18495
+ return withCallbackScope(
18496
+ {
18497
+ kind: "relationFilter",
18498
+ relation: relationName,
18499
+ where,
18500
+ mode,
18501
+ ...typeof origin[RELATION_FROM_TABLE] === "string" && {
18502
+ pathRef: true,
18503
+ pathTable: origin[RELATION_FROM_TABLE]
18504
+ }
18505
+ },
18506
+ origin[CALLBACK_SCOPE]
18507
+ );
18508
+ }
18509
+ function scoped(intent, field) {
18510
+ return typeof field === "object" && field !== null ? withCallbackScope(
18511
+ intent,
18512
+ field[CALLBACK_SCOPE]
18513
+ ) : intent;
18514
+ }
18515
+ function every(relation, filter) {
18516
+ return quantify("every", relation, filter);
17952
18517
  }
17953
18518
  function none(relation, filter) {
17954
- const relationName = getRelationName(relation);
17955
- const where = filter(relation);
17956
- return {
17957
- kind: "relationFilter",
17958
- relation: relationName,
17959
- where,
17960
- mode: "none"
17961
- };
18519
+ return quantify("none", relation, filter);
17962
18520
  }
17963
18521
  function some(relation, filter) {
17964
- const relationName = getRelationName(relation);
17965
- const where = filter(relation);
17966
- return {
17967
- kind: "relationFilter",
17968
- relation: relationName,
17969
- where,
17970
- mode: "some"
17971
- };
18522
+ return quantify("some", relation, filter);
17972
18523
  }
17973
18524
  function coalesce(fields, as) {
17974
18525
  if (fields.length === 0) {
@@ -17985,7 +18536,7 @@ function coalesce(fields, as) {
17985
18536
  {
17986
18537
  intent: { kind: "coalesce", fields, as }
17987
18538
  },
17988
- EXPRESSION_BRAND6,
18539
+ EXPRESSION_BRAND7,
17989
18540
  true
17990
18541
  );
17991
18542
  }
@@ -18001,7 +18552,7 @@ function raw(sqlFragment, as) {
18001
18552
  {
18002
18553
  intent: { kind: "raw", sql: sqlFragment, as }
18003
18554
  },
18004
- EXPRESSION_BRAND6,
18555
+ EXPRESSION_BRAND7,
18005
18556
  true
18006
18557
  );
18007
18558
  }
@@ -18012,7 +18563,7 @@ function col(column, alias) {
18012
18563
  {
18013
18564
  intent: { kind: "columnAlias", column, alias }
18014
18565
  },
18015
- EXPRESSION_BRAND6,
18566
+ EXPRESSION_BRAND7,
18016
18567
  true
18017
18568
  );
18018
18569
  }
@@ -18031,7 +18582,7 @@ function relationColumn(relation, column, as) {
18031
18582
  {
18032
18583
  intent: { kind: "relationColumn", relation, column, as }
18033
18584
  },
18034
- EXPRESSION_BRAND6,
18585
+ EXPRESSION_BRAND7,
18035
18586
  true
18036
18587
  );
18037
18588
  }
@@ -18047,13 +18598,13 @@ function isSqlRaw(value) {
18047
18598
  }
18048
18599
 
18049
18600
  // src/dx/expressions.ts
18050
- import { brandValue as brandValue5, EXPRESSION_BRAND as EXPRESSION_BRAND7, PREDICATE_BRAND } from "@dbsp/types";
18601
+ import { brandValue as brandValue5, EXPRESSION_BRAND as EXPRESSION_BRAND8, PREDICATE_BRAND } from "@dbsp/types";
18051
18602
  var OPERATOR_PATTERN = /^[a-zA-Z_<>=!@#%^&|~*+\-/.]+$/;
18052
18603
  var FUNCTION_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/;
18053
18604
  var TYPE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_ ]*(\[\])?$/;
18054
18605
  function toExpressionIntent(input) {
18055
18606
  if (input instanceof ExpressionRef) return input.intent;
18056
- if (typeof input === "object" && input !== null && EXPRESSION_BRAND7 in input && input[EXPRESSION_BRAND7] === true && "intent" in input) {
18607
+ if (typeof input === "object" && input !== null && EXPRESSION_BRAND8 in input && input[EXPRESSION_BRAND8] === true && "intent" in input) {
18057
18608
  return input.intent;
18058
18609
  }
18059
18610
  if (typeof input === "string") {
@@ -18064,7 +18615,7 @@ function toExpressionIntent(input) {
18064
18615
  var ExpressionRef = class _ExpressionRef {
18065
18616
  intent;
18066
18617
  constructor(intent) {
18067
- brandValue5(this, EXPRESSION_BRAND7, true);
18618
+ brandValue5(this, EXPRESSION_BRAND8, true);
18068
18619
  this.intent = Object.freeze(intent);
18069
18620
  }
18070
18621
  /**
@@ -18165,7 +18716,7 @@ function hasPredicateRefDiscriminator(value) {
18165
18716
  return typeof value === "object" && value !== null && value[PREDICATE_BRAND] === PREDICATE_REF_DISCRIMINATOR;
18166
18717
  }
18167
18718
  function isExpressionPredicateRef(predicate) {
18168
- return EXPRESSION_BRAND7 in predicate && predicate[EXPRESSION_BRAND7] === true;
18719
+ return EXPRESSION_BRAND8 in predicate && predicate[EXPRESSION_BRAND8] === true;
18169
18720
  }
18170
18721
  function predicateWhereIntent(predicate) {
18171
18722
  return isExpressionPredicateRef(predicate) ? { kind: "expression", expr: predicate.intent } : predicate.intent;
@@ -18340,10 +18891,10 @@ function namedArg(name, value) {
18340
18891
  function star() {
18341
18892
  return new ExpressionRef({ kind: "star" });
18342
18893
  }
18343
- function array(...items) {
18894
+ function array(...items2) {
18344
18895
  return new ExpressionRef({
18345
18896
  kind: "array",
18346
- elements: items.map(toExpressionIntent)
18897
+ elements: items2.map(toExpressionIntent)
18347
18898
  });
18348
18899
  }
18349
18900
  function isDistinctField2(input) {
@@ -19119,12 +19670,6 @@ var MSSQL_CAPABILITIES = {
19119
19670
  booleanStyle: "numeric"
19120
19671
  };
19121
19672
 
19122
- // src/dx/types.ts
19123
- import { EXPRESSION_BRAND as EXPRESSION_BRAND8 } from "@dbsp/types";
19124
- function isExpressionSpec(spec) {
19125
- return typeof spec === "object" && spec !== null && EXPRESSION_BRAND8 in spec && spec[EXPRESSION_BRAND8] === true;
19126
- }
19127
-
19128
19673
  // src/mutation-rows.ts
19129
19674
  function inspectMutationRows(rows, options) {
19130
19675
  const rowKeys = rows.map((row) => new Set(Object.keys(row)));
@@ -20046,8 +20591,8 @@ function readPayload(value, shape) {
20046
20591
  }
20047
20592
  if (value === null || value === void 0) return shape.isToOne ? null : [];
20048
20593
  if (Array.isArray(value)) {
20049
- const items = value.map((item) => readPayload(item, shape));
20050
- return shape.isToOne ? items[0] ?? null : items;
20594
+ const items2 = value.map((item) => readPayload(item, shape));
20595
+ return shape.isToOne ? items2[0] ?? null : items2;
20051
20596
  }
20052
20597
  if (!record2(value)) return value;
20053
20598
  const converted = { ...value };
@@ -20781,7 +21326,7 @@ function createBindingTailIncludeDecisions(bindingName, include, firstHopRelatio
20781
21326
  { defaultIncludeStrategy: "json_agg" }
20782
21327
  );
20783
21328
  return tailPlan.decisions.filter((decision) => decision.type === "include-strategy").map((decision, tailIndex) => {
20784
- const nodes = (items) => items.flatMap((node2) => [node2, ...nodes(node2.children)]);
21329
+ const nodes = (items2) => items2.flatMap((node2) => [node2, ...nodes(node2.children)]);
20785
21330
  const node = nodes(tailPlan.execution?.includes ?? []).find(
20786
21331
  (node2) => node2.nodeId === decision.context.nodeId
20787
21332
  );
@@ -20886,18 +21431,22 @@ function createBindingFinalPlan(intent, bundle, model, dialectCapabilities, defa
20886
21431
  )
20887
21432
  ];
20888
21433
  });
21434
+ const resolution = resolveReportIncludes(intent, decisions, model, {
21435
+ ...defaultFilters && {
21436
+ defaultFilters: queryLocalDefaultFilters(bundle, defaultFilters)
21437
+ },
21438
+ skipRootDefaultFilter: true
21439
+ });
20889
21440
  return markPlannedReport2({
20890
21441
  rootTable: intent.from,
20891
- execution: resolveReportIncludes(intent, decisions, model, {
20892
- ...defaultFilters && {
20893
- defaultFilters: queryLocalDefaultFilters(bundle, defaultFilters)
20894
- },
20895
- skipRootDefaultFilter: true
20896
- }),
21442
+ execution: resolution.execution,
20897
21443
  decisions: observeIncludeDecisions(decisions),
20898
21444
  warnings: [],
20899
21445
  ctes: [],
20900
21446
  intent,
21447
+ ...resolution.intent !== intent && {
21448
+ executableIntent: resolution.intent
21449
+ },
20901
21450
  metadata: {
20902
21451
  planningTimeMs: 0,
20903
21452
  relationsAnalyzed: 0,
@@ -22127,6 +22676,12 @@ function extractPseudoColumnKeywords(model) {
22127
22676
  };
22128
22677
  }
22129
22678
 
22679
+ // src/dx/types.ts
22680
+ import { EXPRESSION_BRAND as EXPRESSION_BRAND9 } from "@dbsp/types";
22681
+ function isExpressionSpec(spec) {
22682
+ return typeof spec === "object" && spec !== null && EXPRESSION_BRAND9 in spec && spec[EXPRESSION_BRAND9] === true;
22683
+ }
22684
+
22130
22685
  // src/dx/raw-cte-builder.ts
22131
22686
  var RawCteQueryBuilder = class {
22132
22687
  cteName;
@@ -22681,7 +23236,7 @@ function applyHintToIncludeRecursive(inc, relationHints) {
22681
23236
  return result;
22682
23237
  }
22683
23238
 
22684
- // src/dx/intent-builder.ts
23239
+ // src/dx/include-intent.ts
22685
23240
  function isRecursiveIncludeOptions(options) {
22686
23241
  return options !== void 0 && "recursive" in options && options.recursive === true;
22687
23242
  }
@@ -24189,13 +24744,20 @@ var QueryBuilderImpl = class _QueryBuilderImpl {
24189
24744
  type: "select",
24190
24745
  from: this.from
24191
24746
  };
24747
+ if (this.aggregates.length > 0 && this.selectIntent?.type === "expressions") {
24748
+ throw new InvalidOperationError(
24749
+ "aggregate",
24750
+ "count(), sum(), avg(), min() and max() combine only with string columns(); with an expression projection from columns() or coalesce(), put the aggregate in columns(), e.g. columns([exprRef('a').as('x'), fn('count', star()).as('n')])"
24751
+ );
24752
+ }
24192
24753
  if (this.aggregates.length > 0) {
24193
24754
  const aggregateSelect = {
24194
24755
  type: "aggregate",
24195
24756
  aggregates: [...this.aggregates]
24196
24757
  };
24197
- if (this.groupByFields.length > 0) {
24198
- aggregateSelect.fields = [...this.groupByFields];
24758
+ const fields = this.selectIntent?.type === "fields" ? this.selectIntent.fields : this.groupByFields;
24759
+ if (fields.length > 0) {
24760
+ aggregateSelect.fields = [...fields];
24199
24761
  }
24200
24762
  intent.select = aggregateSelect;
24201
24763
  } else if (this.selectIntent !== void 0) {
@@ -26682,6 +27244,8 @@ export {
26682
27244
  intent_ast_exports,
26683
27245
  copyDefaultFilters,
26684
27246
  ModelIRImpl,
27247
+ refuseTableRootedQuantifier,
27248
+ assertNoPathRefInConditionBodies,
26685
27249
  getRelationalReadPlan,
26686
27250
  escapeDiagnosticText,
26687
27251
  resolveSelectWhere,
@@ -26865,7 +27429,6 @@ export {
26865
27429
  SQLITE_CAPABILITIES,
26866
27430
  DUCKDB_CAPABILITIES,
26867
27431
  MSSQL_CAPABILITIES,
26868
- isExpressionSpec,
26869
27432
  inspectMutationRows,
26870
27433
  InsertBuilder,
26871
27434
  UpdateBuilder,
@@ -26877,6 +27440,7 @@ export {
26877
27440
  compileNqlRead,
26878
27441
  nqlRaw,
26879
27442
  extractPseudoColumnKeywords,
27443
+ isExpressionSpec,
26880
27444
  RawCteQueryBuilder,
26881
27445
  createRawCteBuilder,
26882
27446
  createOrm,
@@ -26918,4 +27482,4 @@ export {
26918
27482
  runAssertions,
26919
27483
  isOverallSuccess
26920
27484
  };
26921
- //# sourceMappingURL=chunk-DUIL3IMF.js.map
27485
+ //# sourceMappingURL=chunk-64RIEJGN.js.map