@dbsp/core 6.1.1 → 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,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 (#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
+
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,18 @@ 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 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
+ };
533
682
  const subqueryRefusal = mode?.subqueryRefusal;
534
683
  let activeFilters = mode?.defaultFilters;
535
684
  const rootScope = [.../* @__PURE__ */ new Set([root, ...visible, ...additionalOuterRanges])];
@@ -555,19 +704,17 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
555
704
  const assertQualifierVisible = (qualifier, ranges) => {
556
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))
557
706
  throw new Error(
558
- `WHERE qualifier '${qualifier}' is not visible in this query.`
707
+ `${label} qualifier '${qualifier}' is not visible in this query.`
559
708
  );
560
709
  };
561
710
  const matchQualifier = (qualifier, scope, outer) => {
562
711
  assertQualifierVisible(qualifier, scope);
563
712
  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
- );
713
+ const exact = writtenQualifiers.get(scope)?.get(qualifier) ?? scope.find((r) => r.alias === qualifier);
567
714
  if (exact) return exact;
568
715
  if (candidates.length > 1)
569
716
  throw new Error(
570
- `${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" : ""}.`
571
718
  );
572
719
  return candidates[0];
573
720
  };
@@ -599,7 +746,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
599
746
  else if (mode?.include) range = allocator.bind(qualifier, qualifier);
600
747
  else
601
748
  throw new Error(
602
- `WHERE qualifier '${qualifier}' is not visible in this query.`
749
+ `${label} qualifier '${qualifier}' is not visible in this query.`
603
750
  );
604
751
  }
605
752
  if (mode?.include && parts.join(".") !== "*" && model && !model.getTable(range.table)?.columns.some((c) => c.name === parts.join(".")))
@@ -634,7 +781,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
634
781
  );
635
782
  if (rel.type === "belongsToMany")
636
783
  throw new Error(
637
- `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).`
638
785
  );
639
786
  names.push(rel.name);
640
787
  table = rel.target;
@@ -775,7 +922,7 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
775
922
  const trusted = getTrustedNqlRelationFilterFields2(node);
776
923
  if ("recursive" in node && node.recursive !== void 0 || trusted?.recursive)
777
924
  throw new Error(
778
- `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}.`
779
926
  );
780
927
  const path = trusted ? {
781
928
  ok: true,
@@ -1039,12 +1186,16 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1039
1186
  );
1040
1187
  }
1041
1188
  };
1042
- const parameter = (value, cast2 = "none") => ({
1043
- kind: "parameter",
1044
- value: isParamIntent3(value) ? value.value : value,
1045
- cast: cast2,
1046
- bound: isParamIntent3(value)
1047
- });
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
+ };
1048
1199
  const rangeParameter = (value) => {
1049
1200
  const authored = parameter(value, "range");
1050
1201
  if (authored.bound) return authored;
@@ -1059,12 +1210,14 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1059
1210
  return authored;
1060
1211
  return { ...authored, cast: "range-element" };
1061
1212
  };
1062
- const normalizeList = (value) => {
1213
+ const normalizeList = (raw2) => {
1214
+ const value = authoredParam(raw2);
1063
1215
  if (isParamIntent3(value)) return value;
1064
1216
  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);
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);
1068
1221
  };
1069
1222
  const visit = (node, current, ranges, enclosing2, fieldOverride) => {
1070
1223
  if (current === root && node === getDefaultFilter(activeFilters, root.table) && mode?.rootDefaultFilter)
@@ -1082,6 +1235,8 @@ function resolveConditionContext(where, root, visible, enclosing, allocator, mod
1082
1235
  condition: visit(node.condition, current, ranges, enclosing2)
1083
1236
  };
1084
1237
  if (node.kind === "exists" || node.kind === "notExists" || node.kind === "relationFilter") {
1238
+ if (node.kind === "relationFilter")
1239
+ assertTableRootedQuantifier(node, current, ranges, enclosing2);
1085
1240
  const name = getTrustedNqlRelationFilterFields2(node)?.relation ?? node.relation;
1086
1241
  return relation(
1087
1242
  node,
@@ -1783,7 +1938,7 @@ var Errors = {
1783
1938
  };
1784
1939
 
1785
1940
  // src/dx/subquery-builder.ts
1786
- import { brandValue, EXPRESSION_BRAND as EXPRESSION_BRAND3 } from "@dbsp/types";
1941
+ import { brandValue, EXPRESSION_BRAND as EXPRESSION_BRAND4 } from "@dbsp/types";
1787
1942
  var SubqueryBuilder = class _SubqueryBuilder {
1788
1943
  _from;
1789
1944
  _select;
@@ -1961,7 +2116,7 @@ var SubqueryExpression = class {
1961
2116
  {
1962
2117
  intent: { kind: "subquery", query: this.intent, as: alias }
1963
2118
  },
1964
- EXPRESSION_BRAND3,
2119
+ EXPRESSION_BRAND4,
1965
2120
  true
1966
2121
  );
1967
2122
  }
@@ -2108,6 +2263,11 @@ var COLUMN_META = /* @__PURE__ */ Symbol.for("dbsp:column");
2108
2263
  var RELATION_META = /* @__PURE__ */ Symbol.for("dbsp:relation");
2109
2264
  var BRAND = /* @__PURE__ */ Symbol.for("dbsp:brand");
2110
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");
2111
2271
 
2112
2272
  // src/dx/table-ref-factory.ts
2113
2273
  var JS_RESERVED_WORDS = /* @__PURE__ */ new Set([
@@ -2160,7 +2320,7 @@ function warnReservedWord(tableName, columnName, suppress) {
2160
2320
  warnedReservedWords.add(dedupKey);
2161
2321
  }
2162
2322
  }
2163
- function createColumnRef(tableName, columnName, relationPath) {
2323
+ function createColumnRef(tableName, columnName, relationPath, scope) {
2164
2324
  const columnRef = {
2165
2325
  [TABLE_META]: tableName,
2166
2326
  [COLUMN_META]: columnName,
@@ -2173,16 +2333,24 @@ function createColumnRef(tableName, columnName, relationPath) {
2173
2333
  `Invalid alias "${alias}": must match /^[a-zA-Z_][a-zA-Z0-9_]*$/`
2174
2334
  );
2175
2335
  }
2176
- return {
2177
- ...this,
2178
- _alias: alias
2179
- };
2336
+ return withCallbackScope(
2337
+ { ...this, _alias: alias },
2338
+ this[CALLBACK_SCOPE]
2339
+ );
2180
2340
  }
2181
2341
  };
2182
- if (relationPath && relationPath.length > 0) {
2342
+ if (relationPath !== void 0) {
2183
2343
  columnRef[RELATION_PATH] = relationPath;
2184
2344
  }
2185
- 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;
2186
2354
  }
2187
2355
  function createAllColumns(tableName) {
2188
2356
  return {
@@ -2211,16 +2379,23 @@ function hasColumn(columns, columnName) {
2211
2379
  function getColumnNames(columns) {
2212
2380
  return columns.map((col2) => col2.name);
2213
2381
  }
2214
- function createRelationRef(targetTable, relationType, model, relationName, parentPath) {
2382
+ function createRelationRef(targetTable, relationType, model, relationName, parentPath, origin = {}) {
2215
2383
  const currentPath = relationName !== void 0 ? [...parentPath ?? [], relationName] : parentPath ?? [];
2216
2384
  const base = {
2217
2385
  [RELATION_META]: { target: targetTable, type: relationType },
2218
2386
  [BRAND]: "RelationRef",
2219
2387
  [RELATION_PATH]: currentPath,
2220
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
+ },
2221
2395
  _type: void 0
2222
2396
  // Phantom type placeholder
2223
2397
  };
2398
+ withCallbackScope(base, origin.scope);
2224
2399
  return new Proxy(base, {
2225
2400
  get(target, prop, receiver) {
2226
2401
  if (typeof prop === "symbol") {
@@ -2234,7 +2409,12 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2234
2409
  }
2235
2410
  const targetTableIR = model.getTable(targetTable);
2236
2411
  if (targetTableIR && hasColumn(targetTableIR.columns, prop)) {
2237
- return createColumnRef(targetTable, prop, currentPath);
2412
+ return createColumnRef(
2413
+ targetTable,
2414
+ prop,
2415
+ currentPath,
2416
+ origin.scope
2417
+ );
2238
2418
  }
2239
2419
  for (const rel of model.getRelationsFrom(targetTable)) {
2240
2420
  if (rel.name === prop) {
@@ -2243,7 +2423,8 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2243
2423
  mapRelationType(rel.type),
2244
2424
  model,
2245
2425
  prop,
2246
- currentPath
2426
+ currentPath,
2427
+ origin
2247
2428
  );
2248
2429
  }
2249
2430
  }
@@ -2254,7 +2435,8 @@ function createRelationRef(targetTable, relationType, model, relationName, paren
2254
2435
  "hasMany",
2255
2436
  model,
2256
2437
  prop,
2257
- currentPath
2438
+ currentPath,
2439
+ origin
2258
2440
  );
2259
2441
  }
2260
2442
  }
@@ -2339,7 +2521,9 @@ function createTableRef(tableName, model, suppress) {
2339
2521
  relation.target,
2340
2522
  relation.type,
2341
2523
  model,
2342
- propStr
2524
+ propStr,
2525
+ void 0,
2526
+ { fromTable: tableName }
2343
2527
  );
2344
2528
  }
2345
2529
  return void 0;
@@ -3618,7 +3802,7 @@ function pluralize(name) {
3618
3802
 
3619
3803
  // src/resolved-includes.ts
3620
3804
  import {
3621
- EXPRESSION_BRAND as EXPRESSION_BRAND4,
3805
+ EXPRESSION_BRAND as EXPRESSION_BRAND5,
3622
3806
  isParamIntent as isParamIntent4,
3623
3807
  RangeAllocator as RangeAllocator3,
3624
3808
  toColumnList
@@ -3677,7 +3861,7 @@ function assertSupportedIncludeWhere(includes, strategies, parent = "", intentPa
3677
3861
  );
3678
3862
  }
3679
3863
  for (const [key, child] of Object.entries(record3)) {
3680
- const expressionValue = child !== null && typeof child === "object" && EXPRESSION_BRAND4 in child;
3864
+ const expressionValue = child !== null && typeof child === "object" && EXPRESSION_BRAND5 in child;
3681
3865
  if (key === "values" || key === "value" && record3.kind !== "namedArg" && (record3.kind === "literal" || !expressionValue))
3682
3866
  continue;
3683
3867
  visit(child);
@@ -4073,13 +4257,50 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4073
4257
  const expressionConditions = [];
4074
4258
  const expressionSubqueries = [];
4075
4259
  const inspected = /* @__PURE__ */ new WeakSet();
4076
- const inspect = (value, intentPath) => {
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) => {
4077
4298
  if (!value || typeof value !== "object" || isParamIntent4(value)) return;
4078
4299
  if (inspected.has(value)) return;
4079
4300
  inspected.add(value);
4080
4301
  if (Array.isArray(value)) {
4081
4302
  value.forEach((child, index) => {
4082
- inspect(child, `${intentPath}[${index}]`);
4303
+ inspect(child, `${intentPath}[${index}]`, condition, belowBody);
4083
4304
  });
4084
4305
  inspected.delete(value);
4085
4306
  return;
@@ -4108,7 +4329,10 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4108
4329
  model,
4109
4330
  0,
4110
4331
  [],
4111
- { defaultFilters: options.defaultFilters }
4332
+ {
4333
+ defaultFilters: options.defaultFilters,
4334
+ ...belowBody && { unknownBody: true }
4335
+ }
4112
4336
  );
4113
4337
  if (resolved?.kind === "expression" && resolved.expression.kind === "subquery")
4114
4338
  expressionSubqueries.push({
@@ -4124,40 +4348,70 @@ function resolveReportIncludes(intent, decisions, model, options = {}) {
4124
4348
  "relationFilter",
4125
4349
  "rawExists",
4126
4350
  "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(
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(
4129
4354
  { type: "select", from: rootRange.table, where: node },
4130
4355
  model,
4131
4356
  options.defaultFilters,
4132
4357
  intentPath,
4133
4358
  true
4134
4359
  ))) {
4135
- const condition = resolveConditionContext(
4360
+ const resolved = resolveConditionContext(
4136
4361
  node,
4137
4362
  rootRange,
4138
4363
  visible,
4139
4364
  [],
4140
4365
  allocator,
4141
4366
  model,
4142
- 0,
4367
+ legacy ? 0 : expressionAliases.count,
4143
4368
  [],
4144
- { 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
+ }
4145
4377
  );
4146
- if (!condition)
4378
+ if (!resolved)
4147
4379
  throw new Error(`Missing resolved condition at ${intentPath}`);
4148
- expressionConditions.push({ intentPath, condition });
4380
+ expressionConditions.push({ intentPath, condition: resolved });
4149
4381
  inspected.delete(value);
4150
4382
  return;
4151
4383
  }
4152
4384
  for (const [key, child] of Object.entries(node)) {
4153
4385
  if (isBoundPayload(node, key, child)) continue;
4154
- inspect(child, `${intentPath}.${key}`);
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
+ });
4398
+ continue;
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
+ );
4155
4409
  }
4156
4410
  inspected.delete(value);
4157
4411
  };
4158
4412
  inspect(intent.select, "select");
4159
4413
  inspect(intent.orderBy, "orderBy");
4160
- inspect(intent.having, "having");
4414
+ inspect(intent.having, "having", "HAVING");
4161
4415
  return {
4162
4416
  rootRange,
4163
4417
  joins,
@@ -4288,6 +4542,7 @@ function validateRecursiveShape(intent) {
4288
4542
  }
4289
4543
  }
4290
4544
  function plan(intent, model, options = {}) {
4545
+ assertNoPathRefInQueryBodies(intent);
4291
4546
  const startTime = performance.now();
4292
4547
  const state = {
4293
4548
  decisions: [],
@@ -4434,7 +4689,6 @@ function planRecursive(intent, model, options = {}) {
4434
4689
  {
4435
4690
  type: "select",
4436
4691
  from: startFrom,
4437
- where: intent.start.where,
4438
4692
  select: intent.start.select,
4439
4693
  nodeIdExpr: intent.start.nodeIdExpr
4440
4694
  },
@@ -4499,6 +4753,18 @@ function planRecursive(intent, model, options = {}) {
4499
4753
  if (!startTable) {
4500
4754
  throw new Error(`Unknown table: ${startFrom}`);
4501
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;
4502
4768
  const traversalKind = intent.traversal.kind;
4503
4769
  const recursiveCteDecision = {
4504
4770
  id: generateDecisionId(state, "recursive-cte"),
@@ -4554,8 +4820,9 @@ function planRecursive(intent, model, options = {}) {
4554
4820
  const planningTimeMs = performance.now() - startTime;
4555
4821
  const dedupeStrategy = intent.dedupe ?? "none";
4556
4822
  const report = {
4557
- ...(anchorFilter || stepFilter) && {
4823
+ ...(anchorFilter || stepFilter || startWhere) && {
4558
4824
  recursiveFilters: {
4825
+ ...startWhere && { start: startWhere },
4559
4826
  ...anchorFilter && { anchor: anchorFilter },
4560
4827
  ...stepFilter && { step: stepFilter }
4561
4828
  }
@@ -5544,8 +5811,8 @@ function validateRecursiveSetOperation(intent, model, capabilities) {
5544
5811
  return;
5545
5812
  }
5546
5813
  const query = node;
5547
- const includes = (items, source, parent = "") => {
5548
- for (const [index, include] of items.entries()) {
5814
+ const includes = (items2, source, parent = "") => {
5815
+ for (const [index, include] of items2.entries()) {
5549
5816
  const relation = resolveIncludeRelationName2(
5550
5817
  model,
5551
5818
  source,
@@ -6029,7 +6296,7 @@ import { EXECUTION_CONTRACT_VERSION } from "@dbsp/types";
6029
6296
 
6030
6297
  // src/transition/minting.ts
6031
6298
  var minted = /* @__PURE__ */ new WeakSet();
6032
- function isObject(value) {
6299
+ function isObject2(value) {
6033
6300
  return typeof value === "object" && value !== null || typeof value === "function";
6034
6301
  }
6035
6302
  function childPath(parent, key) {
@@ -6084,7 +6351,7 @@ function assertPlainDataAndFreeze(value, path, seen) {
6084
6351
  if (typeof value === "bigint" || typeof value === "symbol") {
6085
6352
  throw plainDataError(typeof value, path);
6086
6353
  }
6087
- if (!isObject(value)) {
6354
+ if (!isObject2(value)) {
6088
6355
  return;
6089
6356
  }
6090
6357
  if (seen.has(value)) {
@@ -6155,7 +6422,7 @@ function mintInProcessPlan(shape) {
6155
6422
  return shape;
6156
6423
  }
6157
6424
  function isMintedInProcessPlan(plan2) {
6158
- return isObject(plan2) && minted.has(plan2);
6425
+ return isObject2(plan2) && minted.has(plan2);
6159
6426
  }
6160
6427
 
6161
6428
  // src/transition/execution-contract.ts
@@ -7956,11 +8223,11 @@ function resolvePhysicalSessionRevocationLatch(physicalSession) {
7956
8223
  function mintTransitionSessionRevocationPropagation() {
7957
8224
  return Object.freeze({
7958
8225
  compromise() {
7959
- if (!isObject2(this)) return;
8226
+ if (!isObject3(this)) return;
7960
8227
  resolvePhysicalSessionRevocationLatch(this).compromised = true;
7961
8228
  },
7962
8229
  isCompromised() {
7963
- return isObject2(this) && resolvePhysicalSessionRevocationLatch(this).compromised;
8230
+ return isObject3(this) && resolvePhysicalSessionRevocationLatch(this).compromised;
7964
8231
  }
7965
8232
  });
7966
8233
  }
@@ -8212,7 +8479,7 @@ function lessorBrand(target) {
8212
8479
  function isTransitionSessionRevocationCapability(value) {
8213
8480
  return value != null && typeof value === "object" && Object.isFrozen(value) && typeof value.compromise === "function" && typeof value.isCompromised === "function";
8214
8481
  }
8215
- function isObject2(value) {
8482
+ function isObject3(value) {
8216
8483
  return value != null && (typeof value === "object" || typeof value === "function");
8217
8484
  }
8218
8485
  var TransitionLeaseFailureError = class extends Error {
@@ -11656,13 +11923,13 @@ function logicalIdentityChanged(desired, current) {
11656
11923
  }
11657
11924
  return stableJson(logicalIdentityForComparison(desired.logicalIdentity)) !== stableJson(logicalIdentityForComparison(current.logicalIdentity));
11658
11925
  }
11659
- function normalizeNamedMap(items, normalize, kind) {
11660
- if (!items) {
11926
+ function normalizeNamedMap(items2, normalize, kind) {
11927
+ if (!items2) {
11661
11928
  return { items: void 0, conflicts: [] };
11662
11929
  }
11663
11930
  const normalizedItems = /* @__PURE__ */ new Map();
11664
11931
  const conflicts = [];
11665
- for (const item of items.values()) {
11932
+ for (const item of items2.values()) {
11666
11933
  const normalized = { ...item, name: normalize(item.name) };
11667
11934
  if (normalizedItems.has(normalized.name)) {
11668
11935
  conflicts.push(
@@ -11782,23 +12049,23 @@ function managedRelationsForComparison(relations, externalTables) {
11782
12049
  function modelRelations(model) {
11783
12050
  return model.relations;
11784
12051
  }
11785
- function managedMapPolicy(items) {
11786
- if (items === void 0) {
12052
+ function managedMapPolicy(items2) {
12053
+ if (items2 === void 0) {
11787
12054
  return { managed: false };
11788
12055
  }
11789
- if (items.size === 0) {
12056
+ if (items2.size === 0) {
11790
12057
  return { managed: true };
11791
12058
  }
11792
- return { managed: true, keys: new Set(items.keys()) };
12059
+ return { managed: true, keys: new Set(items2.keys()) };
11793
12060
  }
11794
- function managedListPolicy(items) {
11795
- if (items === void 0) {
12061
+ function managedListPolicy(items2) {
12062
+ if (items2 === void 0) {
11796
12063
  return { managed: false };
11797
12064
  }
11798
- if (items.length === 0) {
12065
+ if (items2.length === 0) {
11799
12066
  return { managed: true };
11800
12067
  }
11801
- return { managed: true, keys: new Set(items) };
12068
+ return { managed: true, keys: new Set(items2) };
11802
12069
  }
11803
12070
  function managedRelationPolicy(relations, externalTables) {
11804
12071
  if (relations === void 0) {
@@ -11825,11 +12092,11 @@ function managedModelCollections(desired, externalTables) {
11825
12092
  function isManagedCollectionKey(policy, key) {
11826
12093
  return policy.managed && (policy.keys === void 0 || policy.keys.has(key));
11827
12094
  }
11828
- function projectManagedMapEntries(items, policy, valueForEntry = (_name, value) => value) {
12095
+ function projectManagedMapEntries(items2, policy, valueForEntry = (_name, value) => value) {
11829
12096
  if (!policy.managed) {
11830
12097
  return [];
11831
12098
  }
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)]);
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)]);
11833
12100
  }
11834
12101
  function extensionNamesForComparison(extensions, policy) {
11835
12102
  if (!policy.managed) {
@@ -17645,7 +17912,7 @@ function batchValues(data, columns, types, opts) {
17645
17912
  }
17646
17913
 
17647
17914
  // src/dx/window-functions.ts
17648
- 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";
17649
17916
 
17650
17917
  // src/dx/column-utils.ts
17651
17918
  function getColumnName(field) {
@@ -17656,7 +17923,20 @@ function getColumnName(field) {
17656
17923
  if (colName === void 0) {
17657
17924
  throw new Error("Invalid ColumnRef: missing COLUMN_META");
17658
17925
  }
17659
- 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;
17660
17940
  }
17661
17941
 
17662
17942
  // src/dx/window-functions.ts
@@ -17752,7 +18032,7 @@ var WindowBuilder = class _WindowBuilder {
17752
18032
  {
17753
18033
  intent: this.toWindowIntent(alias)
17754
18034
  },
17755
- EXPRESSION_BRAND5,
18035
+ EXPRESSION_BRAND6,
17756
18036
  true
17757
18037
  );
17758
18038
  }
@@ -17829,7 +18109,7 @@ function lead(field) {
17829
18109
  }
17830
18110
 
17831
18111
  // src/dx/filters.ts
17832
- 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";
17833
18113
  function distinct(field) {
17834
18114
  return { field, distinct: true };
17835
18115
  }
@@ -17837,12 +18117,16 @@ function isDistinctField(value) {
17837
18117
  return typeof value === "object" && value !== null && "field" in value && typeof value.field === "string" && "distinct" in value && value.distinct === true;
17838
18118
  }
17839
18119
  function createComparisonFilter(operator) {
17840
- return (field, value) => ({
17841
- kind: "comparison",
17842
- field: getColumnName(field),
17843
- operator,
17844
- value
17845
- });
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
+ );
17846
18130
  }
17847
18131
  var eq = createComparisonFilter("eq");
17848
18132
  var neq = createComparisonFilter("neq");
@@ -17857,33 +18141,70 @@ function like(field, pattern, options) {
17857
18141
  const intent = {
17858
18142
  kind: "like",
17859
18143
  field: getColumnName(field),
17860
- pattern
18144
+ pattern,
18145
+ ...isRelationPathColumn(field) && { pathRef: true }
17861
18146
  };
17862
18147
  const withCi = caseInsensitive !== void 0 ? { ...intent, caseInsensitive } : intent;
17863
18148
  if (escapeChar !== void 0) {
17864
- return { ...withCi, escape: escapeChar };
18149
+ return scoped({ ...withCi, escape: escapeChar }, field);
17865
18150
  }
17866
- return withCi;
18151
+ return scoped(withCi, field);
17867
18152
  }
17868
18153
  function inArray(field, values) {
17869
- 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
+ );
17870
18163
  }
17871
18164
  function inSubquery(field, query) {
17872
18165
  const expr = "build" in query ? query.build() : query;
17873
- return {
17874
- kind: "in",
17875
- field: getColumnName(field),
17876
- subquery: expr.toIntent()
17877
- };
18166
+ return scoped(
18167
+ {
18168
+ kind: "in",
18169
+ field: getColumnName(field),
18170
+ subquery: expr.toIntent(),
18171
+ ...isRelationPathColumn(field) && { pathRef: true }
18172
+ },
18173
+ field
18174
+ );
17878
18175
  }
17879
18176
  function any(field, values) {
17880
- 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
+ );
17881
18186
  }
17882
18187
  function isNull(field) {
17883
- 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
+ );
17884
18197
  }
17885
18198
  function isNotNull(field) {
17886
- 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
+ );
17887
18208
  }
17888
18209
  function and(...conditions) {
17889
18210
  const flatConditions = conditions.length === 1 && Array.isArray(conditions[0]) ? conditions[0] : conditions;
@@ -17938,37 +18259,47 @@ function getRelationName(rel) {
17938
18259
  if (!meta) {
17939
18260
  throw new Error("Invalid RelationRef: missing RELATION_META");
17940
18261
  }
17941
- return meta.target;
18262
+ const path = rel[RELATION_PATH];
18263
+ return path !== void 0 && path.length > 0 ? path.join(".") : meta.target;
17942
18264
  }
17943
- 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) {
17944
18270
  const relationName = getRelationName(relation);
17945
- const where = filter(relation);
17946
- return {
17947
- kind: "relationFilter",
17948
- relation: relationName,
17949
- where,
17950
- mode: "every"
17951
- };
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);
17952
18297
  }
17953
18298
  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
- };
18299
+ return quantify("none", relation, filter);
17962
18300
  }
17963
18301
  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
- };
18302
+ return quantify("some", relation, filter);
17972
18303
  }
17973
18304
  function coalesce(fields, as) {
17974
18305
  if (fields.length === 0) {
@@ -17985,7 +18316,7 @@ function coalesce(fields, as) {
17985
18316
  {
17986
18317
  intent: { kind: "coalesce", fields, as }
17987
18318
  },
17988
- EXPRESSION_BRAND6,
18319
+ EXPRESSION_BRAND7,
17989
18320
  true
17990
18321
  );
17991
18322
  }
@@ -18001,7 +18332,7 @@ function raw(sqlFragment, as) {
18001
18332
  {
18002
18333
  intent: { kind: "raw", sql: sqlFragment, as }
18003
18334
  },
18004
- EXPRESSION_BRAND6,
18335
+ EXPRESSION_BRAND7,
18005
18336
  true
18006
18337
  );
18007
18338
  }
@@ -18012,7 +18343,7 @@ function col(column, alias) {
18012
18343
  {
18013
18344
  intent: { kind: "columnAlias", column, alias }
18014
18345
  },
18015
- EXPRESSION_BRAND6,
18346
+ EXPRESSION_BRAND7,
18016
18347
  true
18017
18348
  );
18018
18349
  }
@@ -18031,7 +18362,7 @@ function relationColumn(relation, column, as) {
18031
18362
  {
18032
18363
  intent: { kind: "relationColumn", relation, column, as }
18033
18364
  },
18034
- EXPRESSION_BRAND6,
18365
+ EXPRESSION_BRAND7,
18035
18366
  true
18036
18367
  );
18037
18368
  }
@@ -18047,13 +18378,13 @@ function isSqlRaw(value) {
18047
18378
  }
18048
18379
 
18049
18380
  // src/dx/expressions.ts
18050
- 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";
18051
18382
  var OPERATOR_PATTERN = /^[a-zA-Z_<>=!@#%^&|~*+\-/.]+$/;
18052
18383
  var FUNCTION_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/;
18053
18384
  var TYPE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_ ]*(\[\])?$/;
18054
18385
  function toExpressionIntent(input) {
18055
18386
  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) {
18387
+ if (typeof input === "object" && input !== null && EXPRESSION_BRAND8 in input && input[EXPRESSION_BRAND8] === true && "intent" in input) {
18057
18388
  return input.intent;
18058
18389
  }
18059
18390
  if (typeof input === "string") {
@@ -18064,7 +18395,7 @@ function toExpressionIntent(input) {
18064
18395
  var ExpressionRef = class _ExpressionRef {
18065
18396
  intent;
18066
18397
  constructor(intent) {
18067
- brandValue5(this, EXPRESSION_BRAND7, true);
18398
+ brandValue5(this, EXPRESSION_BRAND8, true);
18068
18399
  this.intent = Object.freeze(intent);
18069
18400
  }
18070
18401
  /**
@@ -18165,7 +18496,7 @@ function hasPredicateRefDiscriminator(value) {
18165
18496
  return typeof value === "object" && value !== null && value[PREDICATE_BRAND] === PREDICATE_REF_DISCRIMINATOR;
18166
18497
  }
18167
18498
  function isExpressionPredicateRef(predicate) {
18168
- return EXPRESSION_BRAND7 in predicate && predicate[EXPRESSION_BRAND7] === true;
18499
+ return EXPRESSION_BRAND8 in predicate && predicate[EXPRESSION_BRAND8] === true;
18169
18500
  }
18170
18501
  function predicateWhereIntent(predicate) {
18171
18502
  return isExpressionPredicateRef(predicate) ? { kind: "expression", expr: predicate.intent } : predicate.intent;
@@ -18340,10 +18671,10 @@ function namedArg(name, value) {
18340
18671
  function star() {
18341
18672
  return new ExpressionRef({ kind: "star" });
18342
18673
  }
18343
- function array(...items) {
18674
+ function array(...items2) {
18344
18675
  return new ExpressionRef({
18345
18676
  kind: "array",
18346
- elements: items.map(toExpressionIntent)
18677
+ elements: items2.map(toExpressionIntent)
18347
18678
  });
18348
18679
  }
18349
18680
  function isDistinctField2(input) {
@@ -19119,12 +19450,6 @@ var MSSQL_CAPABILITIES = {
19119
19450
  booleanStyle: "numeric"
19120
19451
  };
19121
19452
 
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
19453
  // src/mutation-rows.ts
19129
19454
  function inspectMutationRows(rows, options) {
19130
19455
  const rowKeys = rows.map((row) => new Set(Object.keys(row)));
@@ -20046,8 +20371,8 @@ function readPayload(value, shape) {
20046
20371
  }
20047
20372
  if (value === null || value === void 0) return shape.isToOne ? null : [];
20048
20373
  if (Array.isArray(value)) {
20049
- const items = value.map((item) => readPayload(item, shape));
20050
- return shape.isToOne ? items[0] ?? null : items;
20374
+ const items2 = value.map((item) => readPayload(item, shape));
20375
+ return shape.isToOne ? items2[0] ?? null : items2;
20051
20376
  }
20052
20377
  if (!record2(value)) return value;
20053
20378
  const converted = { ...value };
@@ -20781,7 +21106,7 @@ function createBindingTailIncludeDecisions(bindingName, include, firstHopRelatio
20781
21106
  { defaultIncludeStrategy: "json_agg" }
20782
21107
  );
20783
21108
  return tailPlan.decisions.filter((decision) => decision.type === "include-strategy").map((decision, tailIndex) => {
20784
- const nodes = (items) => items.flatMap((node2) => [node2, ...nodes(node2.children)]);
21109
+ const nodes = (items2) => items2.flatMap((node2) => [node2, ...nodes(node2.children)]);
20785
21110
  const node = nodes(tailPlan.execution?.includes ?? []).find(
20786
21111
  (node2) => node2.nodeId === decision.context.nodeId
20787
21112
  );
@@ -22127,6 +22452,12 @@ function extractPseudoColumnKeywords(model) {
22127
22452
  };
22128
22453
  }
22129
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
+
22130
22461
  // src/dx/raw-cte-builder.ts
22131
22462
  var RawCteQueryBuilder = class {
22132
22463
  cteName;
@@ -22681,7 +23012,7 @@ function applyHintToIncludeRecursive(inc, relationHints) {
22681
23012
  return result;
22682
23013
  }
22683
23014
 
22684
- // src/dx/intent-builder.ts
23015
+ // src/dx/include-intent.ts
22685
23016
  function isRecursiveIncludeOptions(options) {
22686
23017
  return options !== void 0 && "recursive" in options && options.recursive === true;
22687
23018
  }
@@ -24189,13 +24520,20 @@ var QueryBuilderImpl = class _QueryBuilderImpl {
24189
24520
  type: "select",
24190
24521
  from: this.from
24191
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
+ }
24192
24529
  if (this.aggregates.length > 0) {
24193
24530
  const aggregateSelect = {
24194
24531
  type: "aggregate",
24195
24532
  aggregates: [...this.aggregates]
24196
24533
  };
24197
- if (this.groupByFields.length > 0) {
24198
- 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];
24199
24537
  }
24200
24538
  intent.select = aggregateSelect;
24201
24539
  } else if (this.selectIntent !== void 0) {
@@ -26682,6 +27020,8 @@ export {
26682
27020
  intent_ast_exports,
26683
27021
  copyDefaultFilters,
26684
27022
  ModelIRImpl,
27023
+ refuseTableRootedQuantifier,
27024
+ assertNoPathRefInConditionBodies,
26685
27025
  getRelationalReadPlan,
26686
27026
  escapeDiagnosticText,
26687
27027
  resolveSelectWhere,
@@ -26865,7 +27205,6 @@ export {
26865
27205
  SQLITE_CAPABILITIES,
26866
27206
  DUCKDB_CAPABILITIES,
26867
27207
  MSSQL_CAPABILITIES,
26868
- isExpressionSpec,
26869
27208
  inspectMutationRows,
26870
27209
  InsertBuilder,
26871
27210
  UpdateBuilder,
@@ -26877,6 +27216,7 @@ export {
26877
27216
  compileNqlRead,
26878
27217
  nqlRaw,
26879
27218
  extractPseudoColumnKeywords,
27219
+ isExpressionSpec,
26880
27220
  RawCteQueryBuilder,
26881
27221
  createRawCteBuilder,
26882
27222
  createOrm,
@@ -26918,4 +27258,4 @@ export {
26918
27258
  runAssertions,
26919
27259
  isOverallSuccess
26920
27260
  };
26921
- //# sourceMappingURL=chunk-DUIL3IMF.js.map
27261
+ //# sourceMappingURL=chunk-RIQOPLZ5.js.map