@dbsp/core 6.1.0 → 6.1.2

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,12 +262,160 @@ ${errors.map((e) => ` - ${e}`).join("\n")}`
262
262
  }
263
263
  };
264
264
 
265
- // src/dx/default-filter-refusals.ts
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 (#1005).`
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 (#1005).`
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 (#1005).`
396
+ );
397
+ }
398
+ );
399
+ }
400
+
401
+ // src/relational-read-plans.ts
266
402
  import {
267
- EXPRESSION_BRAND,
268
- isParamIntent
403
+ isParamIntent as isParamIntent2
269
404
  } from "@dbsp/types";
405
+
406
+ // src/dx/default-filter-refusals.ts
407
+ import { isParamIntent } from "@dbsp/types";
270
408
  import { getTrustedNqlRelationFilterFields } from "@dbsp/types/internal";
409
+
410
+ // src/intent-payload.ts
411
+ import { EXPRESSION_BRAND as EXPRESSION_BRAND2 } from "@dbsp/types";
412
+ function isBoundPayload(node, key, child) {
413
+ if (key !== "value" && key !== "values") return false;
414
+ if (node.kind === "namedArg") return false;
415
+ return !child || typeof child !== "object" || !(EXPRESSION_BRAND2 in child);
416
+ }
417
+
418
+ // src/dx/default-filter-refusals.ts
271
419
  function findDefaultFilterScan(intent, model, filters, path, skipRoot = false, derivedRanges = /* @__PURE__ */ new Set()) {
272
420
  if (!filters || !Object.keys(filters).length) return;
273
421
  const root = intent;
@@ -325,8 +473,7 @@ function findDefaultFilterScan(intent, model, filters, path, skipRoot = false, d
325
473
  }
326
474
  }
327
475
  for (const [key, child] of Object.entries(node)) {
328
- if ((key === "value" || key === "values") && (!child || typeof child !== "object" || !(EXPRESSION_BRAND in child)))
329
- continue;
476
+ if (isBoundPayload(node, key, child)) continue;
330
477
  visit(child, source, `${location}.${key}`);
331
478
  }
332
479
  };
@@ -406,8 +553,7 @@ function assertUnsupportedNqlDefaultFilters(intent, model, filters, path) {
406
553
  }
407
554
  }
408
555
  for (const [key, child] of Object.entries(node)) {
409
- if ((key === "value" || key === "values") && (!child || typeof child !== "object" || !(EXPRESSION_BRAND in child)))
410
- continue;
556
+ if (isBoundPayload(node, key, child)) continue;
411
557
  visit(child, source, `${location}.${key}`);
412
558
  }
413
559
  };
@@ -441,6 +587,26 @@ function registerRelationalReadPolicy(intent, model, filters) {
441
587
  function getRelationalReadPolicy(intent) {
442
588
  return plans.get(intent);
443
589
  }
590
+ function containsRelationalReadPolicy(intent) {
591
+ const seen = /* @__PURE__ */ new Set();
592
+ const visit = (value) => {
593
+ if (!value || typeof value !== "object" || seen.has(value)) return false;
594
+ seen.add(value);
595
+ if (isParamIntent2(value)) return false;
596
+ const node = value;
597
+ if (node.kind === "param" || node.kind === "literal" || node.kind === "parameter")
598
+ return false;
599
+ if (typeof node.from === "string" && plans.has(value))
600
+ return true;
601
+ if (Array.isArray(value)) return value.some(visit);
602
+ for (const [key, child] of Object.entries(node)) {
603
+ if (isBoundPayload(node, key, child)) continue;
604
+ if (visit(child)) return true;
605
+ }
606
+ return false;
607
+ };
608
+ return visit(intent);
609
+ }
444
610
 
445
611
  // src/transition/diagnostic-text.ts
446
612
  function escapeDiagnosticText(value) {
@@ -462,8 +628,8 @@ function escapeDiagnosticText(value) {
462
628
 
463
629
  // src/resolved-conditions.ts
464
630
  import {
465
- EXPRESSION_BRAND as EXPRESSION_BRAND2,
466
- isParamIntent as isParamIntent2,
631
+ EXPRESSION_BRAND as EXPRESSION_BRAND3,
632
+ isParamIntent as isParamIntent3,
467
633
  RangeAllocator,
468
634
  REF_BRAND
469
635
  } from "@dbsp/types";
@@ -475,19 +641,20 @@ import {
475
641
  resolveDeclaredRelationPath
476
642
  } from "@dbsp/types/internal";
477
643
  function isExpression(value) {
478
- return value !== null && typeof value === "object" && EXPRESSION_BRAND2 in value;
644
+ return value !== null && typeof value === "object" && EXPRESSION_BRAND3 in value;
479
645
  }
480
646
  function isRef(value) {
481
647
  return value !== null && typeof value === "object" && REF_BRAND in value;
482
648
  }
483
649
  function containsOuterReference(value) {
484
- if (!value || typeof value !== "object" || isParamIntent2(value)) return false;
650
+ if (!value || typeof value !== "object" || isParamIntent3(value)) return false;
485
651
  if (isSubqueryRef(value) && value.outer === true) return true;
486
652
  return Object.values(value).some(
487
653
  (item) => Array.isArray(item) ? item.some(containsOuterReference) : containsOuterReference(item)
488
654
  );
489
655
  }
490
656
  function resolveSelectWhere(where, root, visible, allocator, model, initialAliasCount = 0, additionalOuterRanges = []) {
657
+ assertNoPathRefInConditionBodies(where);
491
658
  return resolveConditionContext(
492
659
  where,
493
660
  root,
@@ -500,6 +667,18 @@ function resolveSelectWhere(where, root, visible, allocator, model, initialAlias
500
667
  );
501
668
  }
502
669
  function resolveConditionContext(where, root, visible, enclosing, allocator, model, initialAliasCount = 0, additionalOuterRanges = [], mode) {
670
+ const label = mode?.label ?? "WHERE";
671
+ const entryDepth = enclosing.length;
672
+ const assertTableRootedQuantifier = (node, current, ranges, scopes) => {
673
+ const table = node.pathTable;
674
+ if (table === void 0) return;
675
+ if (mode?.unknownBody !== true && scopes.length <= entryDepth) return;
676
+ const sameTable = new Set(
677
+ [ranges, ...scopes].flat().filter((range) => range.table === table).map((range) => range.id)
678
+ );
679
+ if (mode?.unknownBody === true || current.table !== table || sameTable.size !== 1 || !sameTable.has(current.id))
680
+ refuseTableRootedQuantifier(node.relation);
681
+ };
503
682
  const subqueryRefusal = mode?.subqueryRefusal;
504
683
  let activeFilters = mode?.defaultFilters;
505
684
  const rootScope = [.../* @__PURE__ */ new Set([root, ...visible, ...additionalOuterRanges])];
@@ -525,19 +704,17 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
525
704
  const assertQualifierVisible = (qualifier, ranges) => {
526
705
  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))
527
706
  throw new Error(
528
- `WHERE qualifier '${qualifier}' is not visible in this query.`
707
+ `${label} qualifier '${qualifier}' is not visible in this query.`
529
708
  );
530
709
  };
531
710
  const matchQualifier = (qualifier, scope, outer) => {
532
711
  assertQualifierVisible(qualifier, scope);
533
712
  const candidates = scope.filter((r) => r.table === qualifier);
534
- const exact = writtenQualifiers.get(scope)?.get(qualifier) ?? scope.find(
535
- (r) => r.alias === qualifier && (r !== scope[0] || r.alias !== r.table || candidates.length < 2)
536
- );
713
+ const exact = writtenQualifiers.get(scope)?.get(qualifier) ?? scope.find((r) => r.alias === qualifier);
537
714
  if (exact) return exact;
538
715
  if (candidates.length > 1)
539
716
  throw new Error(
540
- `${outer ? "outerRef" : "WHERE"} qualifier '${qualifier}' is ambiguous between ${candidates.map((r) => `'${r.alias}'`).sort().join(", ")}${outer ? " in an enclosing query" : ""}.`
717
+ `${outer ? "outerRef" : label} qualifier '${qualifier}' is ambiguous between ${candidates.map((r) => `'${r.alias}'`).sort().join(", ")}${outer ? " in an enclosing query" : ""}.`
541
718
  );
542
719
  return candidates[0];
543
720
  };
@@ -569,7 +746,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
569
746
  else if (mode?.include) range = allocator.bind(qualifier, qualifier);
570
747
  else
571
748
  throw new Error(
572
- `WHERE qualifier '${qualifier}' is not visible in this query.`
749
+ `${label} qualifier '${qualifier}' is not visible in this query.`
573
750
  );
574
751
  }
575
752
  if (mode?.include && parts.join(".") !== "*" && model && !model.getTable(range.table)?.columns.some((c) => c.name === parts.join(".")))
@@ -604,7 +781,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
604
781
  );
605
782
  if (rel.type === "belongsToMany")
606
783
  throw new Error(
607
- `WHERE ${kind}('${segments.join(".")}'): many-to-many traversal is not supported yet (#787).`
784
+ `${label} ${kind}('${segments.join(".")}'): many-to-many traversal is not supported yet (#787).`
608
785
  );
609
786
  names.push(rel.name);
610
787
  table = rel.target;
@@ -673,6 +850,10 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
673
850
  };
674
851
  else if (select?.type === "aggregate" && select.aggregates[0]) {
675
852
  const agg = select.aggregates[0];
853
+ if (use === "scalar" && agg.filter !== void 0)
854
+ throw new Error(
855
+ "scalar subquery with an aggregate FILTER is not supported \u2014 it would silently change which rows match; restructure the query or use a CTE."
856
+ );
676
857
  projection = {
677
858
  kind: "aggregate",
678
859
  function: agg.function,
@@ -741,7 +922,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
741
922
  const trusted = getTrustedNqlRelationFilterFields2(node);
742
923
  if ("recursive" in node && node.recursive !== void 0 || trusted?.recursive)
743
924
  throw new Error(
744
- `WHERE ${node.kind}('${segments.join(".")}'): recursive relation predicates are not supported inside WHERE.`
925
+ `${label} ${node.kind}('${segments.join(".")}'): recursive relation predicates are not supported inside ${label}.`
745
926
  );
746
927
  const path = trusted ? {
747
928
  ok: true,
@@ -851,7 +1032,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
851
1032
  });
852
1033
  const expr = (value) => expression(value, current, ranges, enclosing2);
853
1034
  const arg = (value, stringsAreColumns = false) => {
854
- if (isParamIntent2(value))
1035
+ if (isParamIntent3(value))
855
1036
  return { kind: "parameter", value: value.value };
856
1037
  if (isExpression(value)) return expr(value.intent);
857
1038
  if (isRef(value)) return ref3(value.target);
@@ -1005,12 +1186,16 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1005
1186
  );
1006
1187
  }
1007
1188
  };
1008
- const parameter = (value, cast2 = "none") => ({
1009
- kind: "parameter",
1010
- value: isParamIntent2(value) ? value.value : value,
1011
- cast: cast2,
1012
- bound: isParamIntent2(value)
1013
- });
1189
+ const authoredParam = (value) => isExpression(value) && isParamIntent3(value.intent) ? value.intent : value;
1190
+ const parameter = (value, cast2 = "none") => {
1191
+ const authored = authoredParam(value);
1192
+ return {
1193
+ kind: "parameter",
1194
+ value: isParamIntent3(authored) ? authored.value : authored,
1195
+ cast: cast2,
1196
+ bound: isParamIntent3(authored)
1197
+ };
1198
+ };
1014
1199
  const rangeParameter = (value) => {
1015
1200
  const authored = parameter(value, "range");
1016
1201
  if (authored.bound) return authored;
@@ -1025,12 +1210,14 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1025
1210
  return authored;
1026
1211
  return { ...authored, cast: "range-element" };
1027
1212
  };
1028
- const normalizeList = (value) => {
1029
- if (isParamIntent2(value)) return value;
1213
+ const normalizeList = (raw2) => {
1214
+ const value = authoredParam(raw2);
1215
+ if (isParamIntent3(value)) return value;
1030
1216
  if (!Array.isArray(value)) return value;
1031
- if (value.length === 1 && isParamIntent2(value[0]) && Array.isArray(value[0].value))
1032
- return value[0];
1033
- return value.map((v) => isParamIntent2(v) ? v.value : v);
1217
+ const items2 = value.map(authoredParam);
1218
+ if (items2.length === 1 && isParamIntent3(items2[0]) && Array.isArray(items2[0].value))
1219
+ return items2[0];
1220
+ return items2.map((v) => isParamIntent3(v) ? v.value : v);
1034
1221
  };
1035
1222
  const visit = (node, current, ranges, enclosing2, fieldOverride) => {
1036
1223
  if (current === root && node === getDefaultFilter(activeFilters, root.table) && mode?.rootDefaultFilter)
@@ -1048,6 +1235,8 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1048
1235
  condition: visit(node.condition, current, ranges, enclosing2)
1049
1236
  };
1050
1237
  if (node.kind === "exists" || node.kind === "notExists" || node.kind === "relationFilter") {
1238
+ if (node.kind === "relationFilter")
1239
+ assertTableRootedQuantifier(node, current, ranges, enclosing2);
1051
1240
  const name = getTrustedNqlRelationFilterFields2(node)?.relation ?? node.relation;
1052
1241
  return relation(
1053
1242
  node,
@@ -1082,7 +1271,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1082
1271
  return column(fieldOverride ?? node.field, current, ranges, enclosing2);
1083
1272
  };
1084
1273
  const rhs = (value, cast2) => {
1085
- if (isParamIntent2(value)) return parameter(value, cast2);
1274
+ if (isParamIntent3(value)) return parameter(value, cast2);
1086
1275
  if (isFieldRef(value))
1087
1276
  return column(
1088
1277
  value.alias ? `${value.alias}.${value.column}` : value.column,
@@ -1749,7 +1938,7 @@ var Errors = {
1749
1938
  };
1750
1939
 
1751
1940
  // src/dx/subquery-builder.ts
1752
- import { brandValue, EXPRESSION_BRAND as EXPRESSION_BRAND3 } from "@dbsp/types";
1941
+ import { brandValue, EXPRESSION_BRAND as EXPRESSION_BRAND4 } from "@dbsp/types";
1753
1942
  var SubqueryBuilder = class _SubqueryBuilder {
1754
1943
  _from;
1755
1944
  _select;
@@ -1927,7 +2116,7 @@ var SubqueryExpression = class {
1927
2116
  {
1928
2117
  intent: { kind: "subquery", query: this.intent, as: alias }
1929
2118
  },
1930
- EXPRESSION_BRAND3,
2119
+ EXPRESSION_BRAND4,
1931
2120
  true
1932
2121
  );
1933
2122
  }
@@ -2074,6 +2263,11 @@ var COLUMN_META = /* @__PURE__ */ Symbol.for("dbsp:column");
2074
2263
  var RELATION_META = /* @__PURE__ */ Symbol.for("dbsp:relation");
2075
2264
  var BRAND = /* @__PURE__ */ Symbol.for("dbsp:brand");
2076
2265
  var RELATION_PATH = /* @__PURE__ */ Symbol.for("dbsp:relationPath");
2266
+ var RELATION_REROOT = /* @__PURE__ */ Symbol("dbsp:relationReroot");
2267
+ var RELATION_FROM_TABLE = /* @__PURE__ */ Symbol.for(
2268
+ "dbsp:relationFromTable"
2269
+ );
2270
+ var CALLBACK_SCOPE = /* @__PURE__ */ Symbol.for("dbsp:callbackScope");
2077
2271
 
2078
2272
  // src/dx/table-ref-factory.ts
2079
2273
  var JS_RESERVED_WORDS = /* @__PURE__ */ new Set([
@@ -2126,7 +2320,7 @@ function warnReservedWord(tableName, columnName, suppress) {
2126
2320
  warnedReservedWords.add(dedupKey);
2127
2321
  }
2128
2322
  }
2129
- function createColumnRef(tableName, columnName, relationPath) {
2323
+ function createColumnRef(tableName, columnName, relationPath, scope) {
2130
2324
  const columnRef = {
2131
2325
  [TABLE_META]: tableName,
2132
2326
  [COLUMN_META]: columnName,
@@ -2139,16 +2333,24 @@ function createColumnRef(tableName, columnName, relationPath) {
2139
2333
  `Invalid alias "${alias}": must match /^[a-zA-Z_][a-zA-Z0-9_]*$/`
2140
2334
  );
2141
2335
  }
2142
- return {
2143
- ...this,
2144
- _alias: alias
2145
- };
2336
+ return withCallbackScope(
2337
+ { ...this, _alias: alias },
2338
+ this[CALLBACK_SCOPE]
2339
+ );
2146
2340
  }
2147
2341
  };
2148
- if (relationPath && relationPath.length > 0) {
2342
+ if (relationPath !== void 0) {
2149
2343
  columnRef[RELATION_PATH] = relationPath;
2150
2344
  }
2151
- return columnRef;
2345
+ return withCallbackScope(columnRef, scope);
2346
+ }
2347
+ function withCallbackScope(target, scope) {
2348
+ if (scope !== void 0)
2349
+ Object.defineProperty(target, CALLBACK_SCOPE, {
2350
+ value: scope,
2351
+ enumerable: false
2352
+ });
2353
+ return target;
2152
2354
  }
2153
2355
  function createAllColumns(tableName) {
2154
2356
  return {
@@ -2177,16 +2379,23 @@ function hasColumn(columns, columnName) {
2177
2379
  function getColumnNames(columns) {
2178
2380
  return columns.map((col2) => col2.name);
2179
2381
  }
2180
- function createRelationRef(targetTable, relationType, model, relationName, parentPath) {
2382
+ function createRelationRef(targetTable, relationType, model, relationName, parentPath, origin = {}) {
2181
2383
  const currentPath = relationName !== void 0 ? [...parentPath ?? [], relationName] : parentPath ?? [];
2182
2384
  const base = {
2183
2385
  [RELATION_META]: { target: targetTable, type: relationType },
2184
2386
  [BRAND]: "RelationRef",
2185
2387
  [RELATION_PATH]: currentPath,
2186
2388
  // Store path on RelationRef too
2389
+ [RELATION_REROOT]: (scope) => createRelationRef(targetTable, relationType, model, void 0, [], {
2390
+ ...scope !== void 0 && { scope }
2391
+ }),
2392
+ ...origin.fromTable !== void 0 && {
2393
+ [RELATION_FROM_TABLE]: origin.fromTable
2394
+ },
2187
2395
  _type: void 0
2188
2396
  // Phantom type placeholder
2189
2397
  };
2398
+ withCallbackScope(base, origin.scope);
2190
2399
  return new Proxy(base, {
2191
2400
  get(target, prop, receiver) {
2192
2401
  if (typeof prop === "symbol") {
@@ -2200,7 +2409,12 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2200
2409
  }
2201
2410
  const targetTableIR = model.getTable(targetTable);
2202
2411
  if (targetTableIR && hasColumn(targetTableIR.columns, prop)) {
2203
- return createColumnRef(targetTable, prop, currentPath);
2412
+ return createColumnRef(
2413
+ targetTable,
2414
+ prop,
2415
+ currentPath,
2416
+ origin.scope
2417
+ );
2204
2418
  }
2205
2419
  for (const rel of model.getRelationsFrom(targetTable)) {
2206
2420
  if (rel.name === prop) {
@@ -2209,7 +2423,8 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2209
2423
  mapRelationType(rel.type),
2210
2424
  model,
2211
2425
  prop,
2212
- currentPath
2426
+ currentPath,
2427
+ origin
2213
2428
  );
2214
2429
  }
2215
2430
  }
@@ -2220,7 +2435,8 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2220
2435
  "hasMany",
2221
2436
  model,
2222
2437
  prop,
2223
- currentPath
2438
+ currentPath,
2439
+ origin
2224
2440
  );
2225
2441
  }
2226
2442
  }
@@ -2305,7 +2521,9 @@ function createTableRef(tableName, model, suppress) {
2305
2521
  relation.target,
2306
2522
  relation.type,
2307
2523
  model,
2308
- propStr
2524
+ propStr,
2525
+ void 0,
2526
+ { fromTable: tableName }
2309
2527
  );
2310
2528
  }
2311
2529
  return void 0;
@@ -3584,8 +3802,8 @@ function pluralize(name) {
3584
3802
 
3585
3803
  // src/resolved-includes.ts
3586
3804
  import {
3587
- EXPRESSION_BRAND as EXPRESSION_BRAND4,
3588
- isParamIntent as isParamIntent3,
3805
+ EXPRESSION_BRAND as EXPRESSION_BRAND5,
3806
+ isParamIntent as isParamIntent4,
3589
3807
  RangeAllocator as RangeAllocator3,
3590
3808
  toColumnList
3591
3809
  } from "@dbsp/types";
@@ -3631,7 +3849,7 @@ function assertSupportedIncludeWhere(includes, strategies, parent = "", intentPa
3631
3849
  }
3632
3850
  if (include.where) {
3633
3851
  const visit = (node) => {
3634
- if (!node || typeof node !== "object" || isParamIntent3(node)) return;
3852
+ if (!node || typeof node !== "object" || isParamIntent4(node)) return;
3635
3853
  if (Array.isArray(node)) {
3636
3854
  for (const child of node) visit(child);
3637
3855
  return;
@@ -3643,7 +3861,7 @@ function assertSupportedIncludeWhere(includes, strategies, parent = "", intentPa
3643
3861
  );
3644
3862
  }
3645
3863
  for (const [key, child] of Object.entries(record3)) {
3646
- const expressionValue = child !== null && typeof child === "object" && EXPRESSION_BRAND4 in child;
3864
+ const expressionValue = child !== null && typeof child === "object" && EXPRESSION_BRAND5 in child;
3647
3865
  if (key === "values" || key === "value" && record3.kind !== "namedArg" && (record3.kind === "literal" || !expressionValue))
3648
3866
  continue;
3649
3867
  visit(child);
@@ -4039,13 +4257,50 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4039
4257
  const expressionConditions = [];
4040
4258
  const expressionSubqueries = [];
4041
4259
  const inspected = /* @__PURE__ */ new WeakSet();
4042
- const inspect = (value, intentPath) => {
4043
- if (!value || typeof value !== "object" || isParamIntent3(value)) return;
4260
+ const expressionAliases = { count: 0 };
4261
+ const dottedField = (node) => [
4262
+ "comparison",
4263
+ "like",
4264
+ "in",
4265
+ "any",
4266
+ "null",
4267
+ "range",
4268
+ "jsonContains",
4269
+ "jsonExists"
4270
+ ].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) => {
4298
+ if (!value || typeof value !== "object" || isParamIntent4(value)) return;
4044
4299
  if (inspected.has(value)) return;
4045
4300
  inspected.add(value);
4046
4301
  if (Array.isArray(value)) {
4047
4302
  value.forEach((child, index) => {
4048
- inspect(child, `${intentPath}[${index}]`);
4303
+ inspect(child, `${intentPath}[${index}]`, condition, belowBody);
4049
4304
  });
4050
4305
  inspected.delete(value);
4051
4306
  return;
@@ -4058,7 +4313,7 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4058
4313
  );
4059
4314
  if (node.kind === "subquery" && node.query) {
4060
4315
  const query = node.query;
4061
- if (!model || !getRelationalReadPolicy(query) && !findDefaultFilterScan(
4316
+ if (!model || !containsRelationalReadPolicy(query) && !findDefaultFilterScan(
4062
4317
  query,
4063
4318
  model,
4064
4319
  options.defaultFilters,
@@ -4074,7 +4329,10 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4074
4329
  model,
4075
4330
  0,
4076
4331
  [],
4077
- { defaultFilters: options.defaultFilters }
4332
+ {
4333
+ defaultFilters: options.defaultFilters,
4334
+ ...belowBody && { unknownBody: true }
4335
+ }
4078
4336
  );
4079
4337
  if (resolved?.kind === "expression" && resolved.expression.kind === "subquery")
4080
4338
  expressionSubqueries.push({
@@ -4090,41 +4348,70 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4090
4348
  "relationFilter",
4091
4349
  "rawExists",
4092
4350
  "rawNotExists"
4093
- ].includes(String(node.kind)) || node.kind === "subquery" && node.subquery || node.kind === "in" && node.subquery || typeof node.field === "string" && node.field.includes(".");
4094
- if (predicate && model && (node.subquery && getRelationalReadPolicy(node.subquery) || findDefaultFilterScan(
4351
+ ].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(
4095
4354
  { type: "select", from: rootRange.table, where: node },
4096
4355
  model,
4097
4356
  options.defaultFilters,
4098
4357
  intentPath,
4099
4358
  true
4100
4359
  ))) {
4101
- const condition = resolveConditionContext(
4360
+ const resolved = resolveConditionContext(
4102
4361
  node,
4103
4362
  rootRange,
4104
4363
  visible,
4105
4364
  [],
4106
4365
  allocator,
4107
4366
  model,
4108
- 0,
4367
+ legacy ? 0 : expressionAliases.count,
4109
4368
  [],
4110
- { defaultFilters: options.defaultFilters }
4369
+ {
4370
+ ...legacy ? { defaultFilters: options.defaultFilters } : {
4371
+ defaultFilters: options.defaultFilters,
4372
+ label: condition,
4373
+ aliasState: expressionAliases
4374
+ },
4375
+ ...belowBody && { unknownBody: true }
4376
+ }
4111
4377
  );
4112
- if (!condition)
4378
+ if (!resolved)
4113
4379
  throw new Error(`Missing resolved condition at ${intentPath}`);
4114
- expressionConditions.push({ intentPath, condition });
4380
+ expressionConditions.push({ intentPath, condition: resolved });
4115
4381
  inspected.delete(value);
4116
4382
  return;
4117
4383
  }
4118
4384
  for (const [key, child] of Object.entries(node)) {
4119
- if ((key === "value" || key === "values") && (!child || typeof child !== "object" || !(EXPRESSION_BRAND4 in child)))
4385
+ if (isBoundPayload(node, key, child)) continue;
4386
+ if (node.kind === "case" && key === "when" && Array.isArray(child)) {
4387
+ child.forEach((branch, index) => {
4388
+ if (!branch || typeof branch !== "object") return;
4389
+ for (const [bkey, bchild] of Object.entries(branch)) {
4390
+ inspect(
4391
+ bchild,
4392
+ `${intentPath}.when[${index}].${bkey}`,
4393
+ bkey === "condition" ? "CASE WHEN" : condition,
4394
+ belowBody
4395
+ );
4396
+ }
4397
+ });
4120
4398
  continue;
4121
- inspect(child, `${intentPath}.${key}`);
4399
+ }
4400
+ const filterRoot = key === "filter" && (node.kind === "customFn" || node.kind === "aggregate" || node.kind === void 0 && typeof node.function === "string");
4401
+ inspect(
4402
+ child,
4403
+ `${intentPath}.${key}`,
4404
+ filterRoot ? "FILTER" : condition,
4405
+ belowBody || key === "subquery" || key === "query" || key === "where" && ["exists", "notExists", "relationFilter"].includes(
4406
+ String(node.kind)
4407
+ )
4408
+ );
4122
4409
  }
4123
4410
  inspected.delete(value);
4124
4411
  };
4125
4412
  inspect(intent.select, "select");
4126
4413
  inspect(intent.orderBy, "orderBy");
4127
- inspect(intent.having, "having");
4414
+ inspect(intent.having, "having", "HAVING");
4128
4415
  return {
4129
4416
  rootRange,
4130
4417
  joins,
@@ -4255,6 +4542,7 @@ function validateRecursiveShape(intent) {
4255
4542
  }
4256
4543
  }
4257
4544
  function plan(intent, model, options = {}) {
4545
+ assertNoPathRefInQueryBodies(intent);
4258
4546
  const startTime = performance.now();
4259
4547
  const state = {
4260
4548
  decisions: [],
@@ -4401,7 +4689,6 @@ function planRecursive(intent, model, options = {}) {
4401
4689
  {
4402
4690
  type: "select",
4403
4691
  from: startFrom,
4404
- where: intent.start.where,
4405
4692
  select: intent.start.select,
4406
4693
  nodeIdExpr: intent.start.nodeIdExpr
4407
4694
  },
@@ -4466,6 +4753,18 @@ function planRecursive(intent, model, options = {}) {
4466
4753
  if (!startTable) {
4467
4754
  throw new Error(`Unknown table: ${startFrom}`);
4468
4755
  }
4756
+ assertNoPathRefInConditionBodies(intent.start.where);
4757
+ const startWhere = intent.start.where ? resolveConditionContext(
4758
+ intent.start.where,
4759
+ anchorRange,
4760
+ [anchorRange],
4761
+ [],
4762
+ allocator,
4763
+ model,
4764
+ 0,
4765
+ [],
4766
+ { defaultFilters: options.defaultFilters, label: "start.where" }
4767
+ ) : void 0;
4469
4768
  const traversalKind = intent.traversal.kind;
4470
4769
  const recursiveCteDecision = {
4471
4770
  id: generateDecisionId(state, "recursive-cte"),
@@ -4521,8 +4820,9 @@ function planRecursive(intent, model, options = {}) {
4521
4820
  const planningTimeMs = performance.now() - startTime;
4522
4821
  const dedupeStrategy = intent.dedupe ?? "none";
4523
4822
  const report = {
4524
- ...(anchorFilter || stepFilter) && {
4823
+ ...(anchorFilter || stepFilter || startWhere) && {
4525
4824
  recursiveFilters: {
4825
+ ...startWhere && { start: startWhere },
4526
4826
  ...anchorFilter && { anchor: anchorFilter },
4527
4827
  ...stepFilter && { step: stepFilter }
4528
4828
  }
@@ -4588,7 +4888,7 @@ function optimizeInToExists(where, sourceTable, model, negated = false) {
4588
4888
  const inWhere = where;
4589
4889
  if (!inWhere.subquery) return where;
4590
4890
  const sq = inWhere.subquery;
4591
- if (sq.limit != null || sq.orderBy?.length || sq.offset != null || sq.groupBy?.length || sq.having != null || sq.distinct || sq.distinctOn?.length || sq.joins?.length || sq.include?.length || sq.batchValuesSource != null || sq.existsWrap || sq.lock != null || sq.select != null && sq.select.type !== "fields") {
4891
+ if (getRelationalReadPolicy(sq) !== void 0 || sq.limit != null || sq.orderBy?.length || sq.offset != null || sq.groupBy?.length || sq.having != null || sq.distinct || sq.distinctOn?.length || sq.joins?.length || sq.include?.length || sq.batchValuesSource != null || sq.existsWrap || sq.lock != null || sq.select != null && sq.select.type !== "fields") {
4592
4892
  return where;
4593
4893
  }
4594
4894
  const subSelect = inWhere.subquery.select;
@@ -5511,8 +5811,8 @@ function validateRecursiveSetOperation(intent, model, capabilities) {
5511
5811
  return;
5512
5812
  }
5513
5813
  const query = node;
5514
- const includes = (items, source, parent = "") => {
5515
- for (const [index, include] of items.entries()) {
5814
+ const includes = (items2, source, parent = "") => {
5815
+ for (const [index, include] of items2.entries()) {
5516
5816
  const relation = resolveIncludeRelationName2(
5517
5817
  model,
5518
5818
  source,
@@ -5996,7 +6296,7 @@ import { EXECUTION_CONTRACT_VERSION } from "@dbsp/types";
5996
6296
 
5997
6297
  // src/transition/minting.ts
5998
6298
  var minted = /* @__PURE__ */ new WeakSet();
5999
- function isObject(value) {
6299
+ function isObject2(value) {
6000
6300
  return typeof value === "object" && value !== null || typeof value === "function";
6001
6301
  }
6002
6302
  function childPath(parent, key) {
@@ -6051,7 +6351,7 @@ function assertPlainDataAndFreeze(value, path, seen) {
6051
6351
  if (typeof value === "bigint" || typeof value === "symbol") {
6052
6352
  throw plainDataError(typeof value, path);
6053
6353
  }
6054
- if (!isObject(value)) {
6354
+ if (!isObject2(value)) {
6055
6355
  return;
6056
6356
  }
6057
6357
  if (seen.has(value)) {
@@ -6122,7 +6422,7 @@ function mintInProcessPlan(shape) {
6122
6422
  return shape;
6123
6423
  }
6124
6424
  function isMintedInProcessPlan(plan2) {
6125
- return isObject(plan2) && minted.has(plan2);
6425
+ return isObject2(plan2) && minted.has(plan2);
6126
6426
  }
6127
6427
 
6128
6428
  // src/transition/execution-contract.ts
@@ -7923,11 +8223,11 @@ function resolvePhysicalSessionRevocationLatch(physicalSession) {
7923
8223
  function mintTransitionSessionRevocationPropagation() {
7924
8224
  return Object.freeze({
7925
8225
  compromise() {
7926
- if (!isObject2(this)) return;
8226
+ if (!isObject3(this)) return;
7927
8227
  resolvePhysicalSessionRevocationLatch(this).compromised = true;
7928
8228
  },
7929
8229
  isCompromised() {
7930
- return isObject2(this) && resolvePhysicalSessionRevocationLatch(this).compromised;
8230
+ return isObject3(this) && resolvePhysicalSessionRevocationLatch(this).compromised;
7931
8231
  }
7932
8232
  });
7933
8233
  }
@@ -8179,7 +8479,7 @@ function lessorBrand(target) {
8179
8479
  function isTransitionSessionRevocationCapability(value) {
8180
8480
  return value != null && typeof value === "object" && Object.isFrozen(value) && typeof value.compromise === "function" && typeof value.isCompromised === "function";
8181
8481
  }
8182
- function isObject2(value) {
8482
+ function isObject3(value) {
8183
8483
  return value != null && (typeof value === "object" || typeof value === "function");
8184
8484
  }
8185
8485
  var TransitionLeaseFailureError = class extends Error {
@@ -11623,13 +11923,13 @@ function logicalIdentityChanged(desired, current) {
11623
11923
  }
11624
11924
  return stableJson(logicalIdentityForComparison(desired.logicalIdentity)) !== stableJson(logicalIdentityForComparison(current.logicalIdentity));
11625
11925
  }
11626
- function normalizeNamedMap(items, normalize, kind) {
11627
- if (!items) {
11926
+ function normalizeNamedMap(items2, normalize, kind) {
11927
+ if (!items2) {
11628
11928
  return { items: void 0, conflicts: [] };
11629
11929
  }
11630
11930
  const normalizedItems = /* @__PURE__ */ new Map();
11631
11931
  const conflicts = [];
11632
- for (const item of items.values()) {
11932
+ for (const item of items2.values()) {
11633
11933
  const normalized = { ...item, name: normalize(item.name) };
11634
11934
  if (normalizedItems.has(normalized.name)) {
11635
11935
  conflicts.push(
@@ -11749,23 +12049,23 @@ function managedRelationsForComparison(relations, externalTables) {
11749
12049
  function modelRelations(model) {
11750
12050
  return model.relations;
11751
12051
  }
11752
- function managedMapPolicy(items) {
11753
- if (items === void 0) {
12052
+ function managedMapPolicy(items2) {
12053
+ if (items2 === void 0) {
11754
12054
  return { managed: false };
11755
12055
  }
11756
- if (items.size === 0) {
12056
+ if (items2.size === 0) {
11757
12057
  return { managed: true };
11758
12058
  }
11759
- return { managed: true, keys: new Set(items.keys()) };
12059
+ return { managed: true, keys: new Set(items2.keys()) };
11760
12060
  }
11761
- function managedListPolicy(items) {
11762
- if (items === void 0) {
12061
+ function managedListPolicy(items2) {
12062
+ if (items2 === void 0) {
11763
12063
  return { managed: false };
11764
12064
  }
11765
- if (items.length === 0) {
12065
+ if (items2.length === 0) {
11766
12066
  return { managed: true };
11767
12067
  }
11768
- return { managed: true, keys: new Set(items) };
12068
+ return { managed: true, keys: new Set(items2) };
11769
12069
  }
11770
12070
  function managedRelationPolicy(relations, externalTables) {
11771
12071
  if (relations === void 0) {
@@ -11792,11 +12092,11 @@ function managedModelCollections(desired, externalTables) {
11792
12092
  function isManagedCollectionKey(policy, key) {
11793
12093
  return policy.managed && (policy.keys === void 0 || policy.keys.has(key));
11794
12094
  }
11795
- function projectManagedMapEntries(items, policy, valueForEntry = (_name, value) => value) {
12095
+ function projectManagedMapEntries(items2, policy, valueForEntry = (_name, value) => value) {
11796
12096
  if (!policy.managed) {
11797
12097
  return [];
11798
12098
  }
11799
- return [...(items ?? /* @__PURE__ */ new Map()).entries()].filter(([name]) => isManagedCollectionKey(policy, name)).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => [name, valueForEntry(name, value)]);
12099
+ return [...(items2 ?? /* @__PURE__ */ new Map()).entries()].filter(([name]) => isManagedCollectionKey(policy, name)).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => [name, valueForEntry(name, value)]);
11800
12100
  }
11801
12101
  function extensionNamesForComparison(extensions, policy) {
11802
12102
  if (!policy.managed) {
@@ -17612,7 +17912,7 @@ function batchValues(data, columns, types, opts) {
17612
17912
  }
17613
17913
 
17614
17914
  // src/dx/window-functions.ts
17615
- import { brandValue as brandValue3, EXPRESSION_BRAND as EXPRESSION_BRAND5 } from "@dbsp/types";
17915
+ import { brandValue as brandValue3, EXPRESSION_BRAND as EXPRESSION_BRAND6 } from "@dbsp/types";
17616
17916
 
17617
17917
  // src/dx/column-utils.ts
17618
17918
  function getColumnName(field) {
@@ -17623,7 +17923,20 @@ function getColumnName(field) {
17623
17923
  if (colName === void 0) {
17624
17924
  throw new Error("Invalid ColumnRef: missing COLUMN_META");
17625
17925
  }
17626
- return colName;
17926
+ const relationPath = field[RELATION_PATH];
17927
+ if (relationPath !== void 0) {
17928
+ return relationPath.length === 0 ? colName : `${relationPath.join(".")}.${colName}`;
17929
+ }
17930
+ const tableName = field[TABLE_META];
17931
+ if (tableName === void 0) {
17932
+ throw new Error("Invalid ColumnRef: missing TABLE_META");
17933
+ }
17934
+ return `${tableName}.${colName}`;
17935
+ }
17936
+ function isRelationPathColumn(field) {
17937
+ if (typeof field === "string") return false;
17938
+ const relationPath = field[RELATION_PATH];
17939
+ return relationPath !== void 0 && relationPath.length > 0;
17627
17940
  }
17628
17941
 
17629
17942
  // src/dx/window-functions.ts
@@ -17719,7 +18032,7 @@ var WindowBuilder = class _WindowBuilder {
17719
18032
  {
17720
18033
  intent: this.toWindowIntent(alias)
17721
18034
  },
17722
- EXPRESSION_BRAND5,
18035
+ EXPRESSION_BRAND6,
17723
18036
  true
17724
18037
  );
17725
18038
  }
@@ -17796,7 +18109,7 @@ function lead(field) {
17796
18109
  }
17797
18110
 
17798
18111
  // src/dx/filters.ts
17799
- import { brandValue as brandValue4, EXPRESSION_BRAND as EXPRESSION_BRAND6 } from "@dbsp/types";
18112
+ import { brandValue as brandValue4, EXPRESSION_BRAND as EXPRESSION_BRAND7 } from "@dbsp/types";
17800
18113
  function distinct(field) {
17801
18114
  return { field, distinct: true };
17802
18115
  }
@@ -17804,12 +18117,16 @@ function isDistinctField(value) {
17804
18117
  return typeof value === "object" && value !== null && "field" in value && typeof value.field === "string" && "distinct" in value && value.distinct === true;
17805
18118
  }
17806
18119
  function createComparisonFilter(operator) {
17807
- return (field, value) => ({
17808
- kind: "comparison",
17809
- field: getColumnName(field),
17810
- operator,
17811
- value
17812
- });
18120
+ return (field, value) => scoped(
18121
+ {
18122
+ kind: "comparison",
18123
+ field: getColumnName(field),
18124
+ operator,
18125
+ value,
18126
+ ...isRelationPathColumn(field) && { pathRef: true }
18127
+ },
18128
+ field
18129
+ );
17813
18130
  }
17814
18131
  var eq = createComparisonFilter("eq");
17815
18132
  var neq = createComparisonFilter("neq");
@@ -17824,33 +18141,70 @@ function like(field, pattern, options) {
17824
18141
  const intent = {
17825
18142
  kind: "like",
17826
18143
  field: getColumnName(field),
17827
- pattern
18144
+ pattern,
18145
+ ...isRelationPathColumn(field) && { pathRef: true }
17828
18146
  };
17829
18147
  const withCi = caseInsensitive !== void 0 ? { ...intent, caseInsensitive } : intent;
17830
18148
  if (escapeChar !== void 0) {
17831
- return { ...withCi, escape: escapeChar };
18149
+ return scoped({ ...withCi, escape: escapeChar }, field);
17832
18150
  }
17833
- return withCi;
18151
+ return scoped(withCi, field);
17834
18152
  }
17835
18153
  function inArray(field, values) {
17836
- return { kind: "in", field: getColumnName(field), values };
18154
+ return scoped(
18155
+ {
18156
+ kind: "in",
18157
+ field: getColumnName(field),
18158
+ values,
18159
+ ...isRelationPathColumn(field) && { pathRef: true }
18160
+ },
18161
+ field
18162
+ );
17837
18163
  }
17838
18164
  function inSubquery(field, query) {
17839
18165
  const expr = "build" in query ? query.build() : query;
17840
- return {
17841
- kind: "in",
17842
- field: getColumnName(field),
17843
- subquery: expr.toIntent()
17844
- };
18166
+ return scoped(
18167
+ {
18168
+ kind: "in",
18169
+ field: getColumnName(field),
18170
+ subquery: expr.toIntent(),
18171
+ ...isRelationPathColumn(field) && { pathRef: true }
18172
+ },
18173
+ field
18174
+ );
17845
18175
  }
17846
18176
  function any(field, values) {
17847
- return { kind: "any", field: getColumnName(field), values };
18177
+ return scoped(
18178
+ {
18179
+ kind: "any",
18180
+ field: getColumnName(field),
18181
+ values,
18182
+ ...isRelationPathColumn(field) && { pathRef: true }
18183
+ },
18184
+ field
18185
+ );
17848
18186
  }
17849
18187
  function isNull(field) {
17850
- return { kind: "null", field: getColumnName(field), operator: "isNull" };
18188
+ return scoped(
18189
+ {
18190
+ kind: "null",
18191
+ field: getColumnName(field),
18192
+ operator: "isNull",
18193
+ ...isRelationPathColumn(field) && { pathRef: true }
18194
+ },
18195
+ field
18196
+ );
17851
18197
  }
17852
18198
  function isNotNull(field) {
17853
- return { kind: "null", field: getColumnName(field), operator: "isNotNull" };
18199
+ return scoped(
18200
+ {
18201
+ kind: "null",
18202
+ field: getColumnName(field),
18203
+ operator: "isNotNull",
18204
+ ...isRelationPathColumn(field) && { pathRef: true }
18205
+ },
18206
+ field
18207
+ );
17854
18208
  }
17855
18209
  function and(...conditions) {
17856
18210
  const flatConditions = conditions.length === 1 && Array.isArray(conditions[0]) ? conditions[0] : conditions;
@@ -17905,37 +18259,47 @@ function getRelationName(rel) {
17905
18259
  if (!meta) {
17906
18260
  throw new Error("Invalid RelationRef: missing RELATION_META");
17907
18261
  }
17908
- return meta.target;
18262
+ const path = rel[RELATION_PATH];
18263
+ return path !== void 0 && path.length > 0 ? path.join(".") : meta.target;
17909
18264
  }
17910
- function every(relation, filter) {
18265
+ function rerootRelation(rel, scope) {
18266
+ const reroot = rel[RELATION_REROOT];
18267
+ return reroot === void 0 ? rel : reroot(scope);
18268
+ }
18269
+ function quantify(mode, relation, filter) {
17911
18270
  const relationName = getRelationName(relation);
17912
- const where = filter(relation);
17913
- return {
17914
- kind: "relationFilter",
17915
- relation: relationName,
17916
- where,
17917
- mode: "every"
17918
- };
18271
+ const scope = {};
18272
+ const where = filter(rerootRelation(relation, scope));
18273
+ assertCallbackScope(where, CALLBACK_SCOPE, scope, mode);
18274
+ const origin = relation;
18275
+ return withCallbackScope(
18276
+ {
18277
+ kind: "relationFilter",
18278
+ relation: relationName,
18279
+ where,
18280
+ mode,
18281
+ ...typeof origin[RELATION_FROM_TABLE] === "string" && {
18282
+ pathRef: true,
18283
+ pathTable: origin[RELATION_FROM_TABLE]
18284
+ }
18285
+ },
18286
+ origin[CALLBACK_SCOPE]
18287
+ );
18288
+ }
18289
+ function scoped(intent, field) {
18290
+ return typeof field === "object" && field !== null ? withCallbackScope(
18291
+ intent,
18292
+ field[CALLBACK_SCOPE]
18293
+ ) : intent;
18294
+ }
18295
+ function every(relation, filter) {
18296
+ return quantify("every", relation, filter);
17919
18297
  }
17920
18298
  function none(relation, filter) {
17921
- const relationName = getRelationName(relation);
17922
- const where = filter(relation);
17923
- return {
17924
- kind: "relationFilter",
17925
- relation: relationName,
17926
- where,
17927
- mode: "none"
17928
- };
18299
+ return quantify("none", relation, filter);
17929
18300
  }
17930
18301
  function some(relation, filter) {
17931
- const relationName = getRelationName(relation);
17932
- const where = filter(relation);
17933
- return {
17934
- kind: "relationFilter",
17935
- relation: relationName,
17936
- where,
17937
- mode: "some"
17938
- };
18302
+ return quantify("some", relation, filter);
17939
18303
  }
17940
18304
  function coalesce(fields, as) {
17941
18305
  if (fields.length === 0) {
@@ -17952,7 +18316,7 @@ function coalesce(fields, as) {
17952
18316
  {
17953
18317
  intent: { kind: "coalesce", fields, as }
17954
18318
  },
17955
- EXPRESSION_BRAND6,
18319
+ EXPRESSION_BRAND7,
17956
18320
  true
17957
18321
  );
17958
18322
  }
@@ -17968,7 +18332,7 @@ function raw(sqlFragment, as) {
17968
18332
  {
17969
18333
  intent: { kind: "raw", sql: sqlFragment, as }
17970
18334
  },
17971
- EXPRESSION_BRAND6,
18335
+ EXPRESSION_BRAND7,
17972
18336
  true
17973
18337
  );
17974
18338
  }
@@ -17979,7 +18343,7 @@ function col(column, alias) {
17979
18343
  {
17980
18344
  intent: { kind: "columnAlias", column, alias }
17981
18345
  },
17982
- EXPRESSION_BRAND6,
18346
+ EXPRESSION_BRAND7,
17983
18347
  true
17984
18348
  );
17985
18349
  }
@@ -17998,7 +18362,7 @@ function relationColumn(relation, column, as) {
17998
18362
  {
17999
18363
  intent: { kind: "relationColumn", relation, column, as }
18000
18364
  },
18001
- EXPRESSION_BRAND6,
18365
+ EXPRESSION_BRAND7,
18002
18366
  true
18003
18367
  );
18004
18368
  }
@@ -18014,13 +18378,13 @@ function isSqlRaw(value) {
18014
18378
  }
18015
18379
 
18016
18380
  // src/dx/expressions.ts
18017
- import { brandValue as brandValue5, EXPRESSION_BRAND as EXPRESSION_BRAND7, PREDICATE_BRAND } from "@dbsp/types";
18381
+ import { brandValue as brandValue5, EXPRESSION_BRAND as EXPRESSION_BRAND8, PREDICATE_BRAND } from "@dbsp/types";
18018
18382
  var OPERATOR_PATTERN = /^[a-zA-Z_<>=!@#%^&|~*+\-/.]+$/;
18019
18383
  var FUNCTION_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/;
18020
18384
  var TYPE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_ ]*(\[\])?$/;
18021
18385
  function toExpressionIntent(input) {
18022
18386
  if (input instanceof ExpressionRef) return input.intent;
18023
- if (typeof input === "object" && input !== null && EXPRESSION_BRAND7 in input && input[EXPRESSION_BRAND7] === true && "intent" in input) {
18387
+ if (typeof input === "object" && input !== null && EXPRESSION_BRAND8 in input && input[EXPRESSION_BRAND8] === true && "intent" in input) {
18024
18388
  return input.intent;
18025
18389
  }
18026
18390
  if (typeof input === "string") {
@@ -18031,7 +18395,7 @@ function toExpressionIntent(input) {
18031
18395
  var ExpressionRef = class _ExpressionRef {
18032
18396
  intent;
18033
18397
  constructor(intent) {
18034
- brandValue5(this, EXPRESSION_BRAND7, true);
18398
+ brandValue5(this, EXPRESSION_BRAND8, true);
18035
18399
  this.intent = Object.freeze(intent);
18036
18400
  }
18037
18401
  /**
@@ -18132,7 +18496,7 @@ function hasPredicateRefDiscriminator(value) {
18132
18496
  return typeof value === "object" && value !== null && value[PREDICATE_BRAND] === PREDICATE_REF_DISCRIMINATOR;
18133
18497
  }
18134
18498
  function isExpressionPredicateRef(predicate) {
18135
- return EXPRESSION_BRAND7 in predicate && predicate[EXPRESSION_BRAND7] === true;
18499
+ return EXPRESSION_BRAND8 in predicate && predicate[EXPRESSION_BRAND8] === true;
18136
18500
  }
18137
18501
  function predicateWhereIntent(predicate) {
18138
18502
  return isExpressionPredicateRef(predicate) ? { kind: "expression", expr: predicate.intent } : predicate.intent;
@@ -18307,10 +18671,10 @@ function namedArg(name, value) {
18307
18671
  function star() {
18308
18672
  return new ExpressionRef({ kind: "star" });
18309
18673
  }
18310
- function array(...items) {
18674
+ function array(...items2) {
18311
18675
  return new ExpressionRef({
18312
18676
  kind: "array",
18313
- elements: items.map(toExpressionIntent)
18677
+ elements: items2.map(toExpressionIntent)
18314
18678
  });
18315
18679
  }
18316
18680
  function isDistinctField2(input) {
@@ -19086,12 +19450,6 @@ var MSSQL_CAPABILITIES = {
19086
19450
  booleanStyle: "numeric"
19087
19451
  };
19088
19452
 
19089
- // src/dx/types.ts
19090
- import { EXPRESSION_BRAND as EXPRESSION_BRAND8 } from "@dbsp/types";
19091
- function isExpressionSpec(spec) {
19092
- return typeof spec === "object" && spec !== null && EXPRESSION_BRAND8 in spec && spec[EXPRESSION_BRAND8] === true;
19093
- }
19094
-
19095
19453
  // src/mutation-rows.ts
19096
19454
  function inspectMutationRows(rows, options) {
19097
19455
  const rowKeys = rows.map((row) => new Set(Object.keys(row)));
@@ -20013,8 +20371,8 @@ function readPayload(value, shape) {
20013
20371
  }
20014
20372
  if (value === null || value === void 0) return shape.isToOne ? null : [];
20015
20373
  if (Array.isArray(value)) {
20016
- const items = value.map((item) => readPayload(item, shape));
20017
- return shape.isToOne ? items[0] ?? null : items;
20374
+ const items2 = value.map((item) => readPayload(item, shape));
20375
+ return shape.isToOne ? items2[0] ?? null : items2;
20018
20376
  }
20019
20377
  if (!record2(value)) return value;
20020
20378
  const converted = { ...value };
@@ -20748,7 +21106,7 @@ function createBindingTailIncludeDecisions(bindingName, include, firstHopRelatio
20748
21106
  { defaultIncludeStrategy: "json_agg" }
20749
21107
  );
20750
21108
  return tailPlan.decisions.filter((decision) => decision.type === "include-strategy").map((decision, tailIndex) => {
20751
- const nodes = (items) => items.flatMap((node2) => [node2, ...nodes(node2.children)]);
21109
+ const nodes = (items2) => items2.flatMap((node2) => [node2, ...nodes(node2.children)]);
20752
21110
  const node = nodes(tailPlan.execution?.includes ?? []).find(
20753
21111
  (node2) => node2.nodeId === decision.context.nodeId
20754
21112
  );
@@ -22094,6 +22452,12 @@ function extractPseudoColumnKeywords(model) {
22094
22452
  };
22095
22453
  }
22096
22454
 
22455
+ // src/dx/types.ts
22456
+ import { EXPRESSION_BRAND as EXPRESSION_BRAND9 } from "@dbsp/types";
22457
+ function isExpressionSpec(spec) {
22458
+ return typeof spec === "object" && spec !== null && EXPRESSION_BRAND9 in spec && spec[EXPRESSION_BRAND9] === true;
22459
+ }
22460
+
22097
22461
  // src/dx/raw-cte-builder.ts
22098
22462
  var RawCteQueryBuilder = class {
22099
22463
  cteName;
@@ -22648,7 +23012,7 @@ function applyHintToIncludeRecursive(inc, relationHints) {
22648
23012
  return result;
22649
23013
  }
22650
23014
 
22651
- // src/dx/intent-builder.ts
23015
+ // src/dx/include-intent.ts
22652
23016
  function isRecursiveIncludeOptions(options) {
22653
23017
  return options !== void 0 && "recursive" in options && options.recursive === true;
22654
23018
  }
@@ -24156,13 +24520,20 @@ var QueryBuilderImpl = class _QueryBuilderImpl {
24156
24520
  type: "select",
24157
24521
  from: this.from
24158
24522
  };
24523
+ if (this.aggregates.length > 0 && this.selectIntent?.type === "expressions") {
24524
+ throw new InvalidOperationError(
24525
+ "aggregate",
24526
+ "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')])"
24527
+ );
24528
+ }
24159
24529
  if (this.aggregates.length > 0) {
24160
24530
  const aggregateSelect = {
24161
24531
  type: "aggregate",
24162
24532
  aggregates: [...this.aggregates]
24163
24533
  };
24164
- if (this.groupByFields.length > 0) {
24165
- aggregateSelect.fields = [...this.groupByFields];
24534
+ const fields = this.selectIntent?.type === "fields" ? this.selectIntent.fields : this.groupByFields;
24535
+ if (fields.length > 0) {
24536
+ aggregateSelect.fields = [...fields];
24166
24537
  }
24167
24538
  intent.select = aggregateSelect;
24168
24539
  } else if (this.selectIntent !== void 0) {
@@ -25399,7 +25770,10 @@ function createOrmInstance(model, strictMode, relationHints, adapter, schemaName
25399
25770
  "selectExpression() requires an adapter. Pass an adapter when creating the ORM."
25400
25771
  );
25401
25772
  }
25402
- const compiled = adapter.compileSelectExpression(expr.intent, { model });
25773
+ const compiled = adapter.compileSelectExpression(expr.intent, {
25774
+ model,
25775
+ ...defaultFilters !== void 0 && { defaultFilters }
25776
+ });
25403
25777
  return {
25404
25778
  sql: compiled.sql,
25405
25779
  parameters: compiled.parameters,
@@ -26646,6 +27020,8 @@ export {
26646
27020
  intent_ast_exports,
26647
27021
  copyDefaultFilters,
26648
27022
  ModelIRImpl,
27023
+ refuseTableRootedQuantifier,
27024
+ assertNoPathRefInConditionBodies,
26649
27025
  getRelationalReadPlan,
26650
27026
  escapeDiagnosticText,
26651
27027
  resolveSelectWhere,
@@ -26829,7 +27205,6 @@ export {
26829
27205
  SQLITE_CAPABILITIES,
26830
27206
  DUCKDB_CAPABILITIES,
26831
27207
  MSSQL_CAPABILITIES,
26832
- isExpressionSpec,
26833
27208
  inspectMutationRows,
26834
27209
  InsertBuilder,
26835
27210
  UpdateBuilder,
@@ -26841,6 +27216,7 @@ export {
26841
27216
  compileNqlRead,
26842
27217
  nqlRaw,
26843
27218
  extractPseudoColumnKeywords,
27219
+ isExpressionSpec,
26844
27220
  RawCteQueryBuilder,
26845
27221
  createRawCteBuilder,
26846
27222
  createOrm,
@@ -26882,4 +27258,4 @@ export {
26882
27258
  runAssertions,
26883
27259
  isOverallSuccess
26884
27260
  };
26885
- //# sourceMappingURL=chunk-SDUWYSS7.js.map
27261
+ //# sourceMappingURL=chunk-RIQOPLZ5.js.map