@aeye/query 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -714,6 +714,17 @@ var FieldType = class {
714
714
  if (TEMPORAL_KINDS.has(a) && TEMPORAL_KINDS.has(b)) return true;
715
715
  return false;
716
716
  }
717
+ /**
718
+ * The fraction of rows a non-indexed EQUALITY predicate on a column of this
719
+ * type is expected to keep, when the type itself knows better than the
720
+ * package-wide `EQ_SELECTIVITY` guess. A closed value set of `n` members
721
+ * answers `1/n`: a two-value flag keeps half the table, a fifty-value code
722
+ * keeps 2% — today both are costed at the same fixed third. `undefined`
723
+ * (the default) means "no better estimate; use the fixed one".
724
+ */
725
+ eqSelectivity() {
726
+ return void 0;
727
+ }
717
728
  /**
718
729
  * Whether TEXTUAL matching / comparison on a value of this type is
719
730
  * CASE-SENSITIVE. Default false (case-insensitive); only `text` fields
@@ -738,17 +749,54 @@ var FieldType = class {
738
749
  };
739
750
 
740
751
  // src/field-types/index.ts
741
- import { z as z11 } from "zod";
752
+ import { z as z12 } from "zod";
742
753
 
743
754
  // src/field-types/number.ts
755
+ import { z as z3 } from "zod";
756
+
757
+ // src/field-types/_values.ts
744
758
  import { z as z2 } from "zod";
759
+ function fieldValuesSchema() {
760
+ return z2.array(
761
+ z2.object({
762
+ value: z2.union([z2.string(), z2.number()]).describe("The stored value \u2014 one member of the closed set."),
763
+ label: z2.string().optional().describe("Human-facing name for this member (defaults to the value).")
764
+ })
765
+ ).optional().describe("Closed set of values this field may hold. Declare only a genuinely fixed set.");
766
+ }
767
+ function compactFieldValues(values) {
768
+ if (!values || values.length === 0) return void 0;
769
+ return values.map((v) => v.label === void 0 ? { value: v.value } : { value: v.value, label: v.label });
770
+ }
771
+ function closedSetValueSchema(values) {
772
+ if (!values || values.length === 0) return void 0;
773
+ const first = values[0];
774
+ if (values.length === 1) return z2.literal(first.value);
775
+ return z2.union(values.map((v) => z2.literal(v.value)));
776
+ }
777
+ function eqSelectivityOf(values) {
778
+ if (!values || values.length === 0) return void 0;
779
+ return 1 / values.length;
780
+ }
781
+ var MAX_DESCRIBED_VALUES = 12;
782
+ function describeValues(values) {
783
+ if (!values || values.length === 0) return "";
784
+ const shown = values.slice(0, MAX_DESCRIBED_VALUES).map(
785
+ (v) => v.label !== void 0 && v.label !== String(v.value) ? `${v.value} (${v.label})` : `${v.value}`
786
+ );
787
+ const more = values.length - shown.length;
788
+ return ` one of ${shown.join("|")}${more > 0 ? `|\u2026+${more} more` : ""}`;
789
+ }
790
+
791
+ // src/field-types/number.ts
745
792
  function numberOptionsSchema() {
746
- return z2.object({
747
- min: z2.number().optional().describe("Real lower bound only (e.g. age \u2192 0). Do not add 0 reflexively."),
748
- max: z2.number().optional().describe("Real upper bound only (e.g. percentage \u2192 100)."),
749
- whole: z2.boolean().optional().describe("True only when genuinely integral (counts, ids)."),
750
- minPlaces: z2.number().int().optional().describe("Decimal-place floor; omit unless required."),
751
- maxPlaces: z2.number().int().optional().describe("Decimal-place ceiling; omit unless required.")
793
+ return z3.object({
794
+ min: z3.number().optional().describe("Real lower bound only (e.g. age \u2192 0). Do not add 0 reflexively."),
795
+ max: z3.number().optional().describe("Real upper bound only (e.g. percentage \u2192 100)."),
796
+ whole: z3.boolean().optional().describe("True only when genuinely integral (counts, ids)."),
797
+ minPlaces: z3.number().int().optional().describe("Decimal-place floor; omit unless required."),
798
+ maxPlaces: z3.number().int().optional().describe("Decimal-place ceiling; omit unless required."),
799
+ values: fieldValuesSchema()
752
800
  });
753
801
  }
754
802
  function compactNumberOptions(o) {
@@ -758,10 +806,14 @@ function compactNumberOptions(o) {
758
806
  if (o.whole !== void 0) out.whole = o.whole;
759
807
  if (o.minPlaces !== void 0) out.minPlaces = o.minPlaces;
760
808
  if (o.maxPlaces !== void 0) out.maxPlaces = o.maxPlaces;
809
+ const values = compactFieldValues(o.values);
810
+ if (values) out.values = values;
761
811
  return out;
762
812
  }
763
813
  function numberValueSchema(o) {
764
- let s = o.whole ? z2.number().int() : z2.number();
814
+ const closed = closedSetValueSchema(o.values);
815
+ if (closed) return closed;
816
+ let s = o.whole ? z3.number().int() : z3.number();
765
817
  if (o.min !== void 0) s = s.min(o.min);
766
818
  if (o.max !== void 0) s = s.max(o.max);
767
819
  return s;
@@ -786,24 +838,29 @@ var NumberFieldType = class _NumberFieldType extends FieldType {
786
838
  message: `NumberFieldType.from: expected kind 'number', got '${json.kind}'`
787
839
  });
788
840
  }
789
- const { min: min2, max: max2, whole, minPlaces, maxPlaces } = json;
790
- return new _NumberFieldType(compactNumberOptions({ min: min2, max: max2, whole, minPlaces, maxPlaces }));
841
+ const { min: min2, max: max2, whole, minPlaces, maxPlaces, values } = json;
842
+ return new _NumberFieldType(compactNumberOptions({ min: min2, max: max2, whole, minPlaces, maxPlaces, values }));
791
843
  }
792
844
  /** The Zod schema for this field type's JSON def. */
793
845
  static toSchema() {
794
- return z2.object({
795
- kind: z2.literal("number"),
796
- min: z2.number().optional().describe("Real lower bound only (e.g. age \u2192 0). Do not add 0 reflexively."),
797
- max: z2.number().optional().describe("Real upper bound only (e.g. percentage \u2192 100)."),
798
- whole: z2.boolean().optional().describe("True only when genuinely integral (counts, ids)."),
799
- minPlaces: z2.number().int().optional().describe("Decimal-place floor; omit unless required."),
800
- maxPlaces: z2.number().int().optional().describe("Decimal-place ceiling; omit unless required.")
846
+ return z3.object({
847
+ kind: z3.literal("number"),
848
+ min: z3.number().optional().describe("Real lower bound only (e.g. age \u2192 0). Do not add 0 reflexively."),
849
+ max: z3.number().optional().describe("Real upper bound only (e.g. percentage \u2192 100)."),
850
+ whole: z3.boolean().optional().describe("True only when genuinely integral (counts, ids)."),
851
+ minPlaces: z3.number().int().optional().describe("Decimal-place floor; omit unless required."),
852
+ maxPlaces: z3.number().int().optional().describe("Decimal-place ceiling; omit unless required."),
853
+ values: fieldValuesSchema()
801
854
  }).meta({ aid: "FieldType_number" }).describe("Numeric field type.");
802
855
  }
803
856
  /** Resolve to the `number` scalar comparison category. */
804
857
  resolve() {
805
858
  return "number";
806
859
  }
860
+ /** A declared closed set of `n` members makes `= x` a `1/n` predicate. */
861
+ eqSelectivity() {
862
+ return eqSelectivityOf(this.options.values);
863
+ }
807
864
  /** Estimated average stored byte size. */
808
865
  avgBytes() {
809
866
  return 8;
@@ -820,14 +877,14 @@ var NumberFieldType = class _NumberFieldType extends FieldType {
820
877
  toJSON() {
821
878
  return { kind: _NumberFieldType.NAME, ...compactNumberOptions(this.options) };
822
879
  }
823
- /** A copy of this field type (cloning the options bag). */
880
+ /** A copy of this field type (deep-cloning the options bag's value set). */
824
881
  clone() {
825
- return new _NumberFieldType({ ...this.options });
882
+ return new _NumberFieldType({ ...this.options, values: this.options.values?.map((v) => ({ ...v })) });
826
883
  }
827
884
  };
828
885
 
829
886
  // src/field-types/text.ts
830
- import { z as z3 } from "zod";
887
+ import { z as z4 } from "zod";
831
888
  function compact(o) {
832
889
  const out = {};
833
890
  if (o.minLength !== void 0) out.minLength = o.minLength;
@@ -836,6 +893,8 @@ function compact(o) {
836
893
  if (o.semantic !== void 0) out.semantic = o.semantic;
837
894
  if (o.search !== void 0) out.search = o.search;
838
895
  if (o.sensitive !== void 0) out.sensitive = o.sensitive;
896
+ const values = compactFieldValues(o.values);
897
+ if (values) out.values = values;
839
898
  return out;
840
899
  }
841
900
  var TextFieldType = class _TextFieldType extends FieldType {
@@ -862,25 +921,30 @@ var TextFieldType = class _TextFieldType extends FieldType {
862
921
  message: `TextFieldType.from: expected kind 'text', got '${json.kind}'`
863
922
  });
864
923
  }
865
- const { minLength, maxLength, pattern, semantic: semantic2, search, sensitive } = json;
866
- return new _TextFieldType(compact({ minLength, maxLength, pattern, semantic: semantic2, search, sensitive }));
924
+ const { minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values } = json;
925
+ return new _TextFieldType(compact({ minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values }));
867
926
  }
868
927
  /** The Zod schema for this field type's JSON def. */
869
928
  static toSchema() {
870
- return z3.object({
871
- kind: z3.literal("text"),
872
- minLength: z3.number().int().optional().describe("Real lower bound (e.g. non-empty \u2192 1)."),
873
- maxLength: z3.number().int().optional().describe("Real upper bound (field width / API limit)."),
874
- pattern: z3.string().optional().describe("Format regex (UUID, slug, \u2026); not accept-anything."),
875
- semantic: z3.boolean().optional().describe("Eligible for embedding-based semantic similarity."),
876
- search: z3.boolean().optional().describe("Eligible for full-text search."),
877
- sensitive: z3.boolean().optional().describe("When true, text matching is CASE-SENSITIVE (default: case-insensitive).")
929
+ return z4.object({
930
+ kind: z4.literal("text"),
931
+ minLength: z4.number().int().optional().describe("Real lower bound (e.g. non-empty \u2192 1)."),
932
+ maxLength: z4.number().int().optional().describe("Real upper bound (field width / API limit)."),
933
+ pattern: z4.string().optional().describe("Format regex (UUID, slug, \u2026); not accept-anything."),
934
+ semantic: z4.boolean().optional().describe("Eligible for embedding-based semantic similarity."),
935
+ search: z4.boolean().optional().describe("Eligible for full-text search."),
936
+ sensitive: z4.boolean().optional().describe("When true, text matching is CASE-SENSITIVE (default: case-insensitive)."),
937
+ values: fieldValuesSchema()
878
938
  }).meta({ aid: "FieldType_text" }).describe("String field type.");
879
939
  }
880
940
  /** Resolve to the `text` scalar comparison category. */
881
941
  resolve() {
882
942
  return "text";
883
943
  }
944
+ /** A declared closed set of `n` members makes `= x` a `1/n` predicate. */
945
+ eqSelectivity() {
946
+ return eqSelectivityOf(this.options.values);
947
+ }
884
948
  /** Estimated average stored byte size (half the max length, else 32). */
885
949
  avgBytes() {
886
950
  if (this.options.maxLength !== void 0) {
@@ -892,9 +956,11 @@ var TextFieldType = class _TextFieldType extends FieldType {
892
956
  toSQLType() {
893
957
  return this.options.maxLength !== void 0 ? `varchar(${this.options.maxLength})` : "text";
894
958
  }
895
- /** Zod schema validating a string, honoring length / pattern options. */
959
+ /** Zod schema validating a string, honoring the closed value set else length / pattern options. */
896
960
  toValueSchema(_opts) {
897
- let s = z3.string();
961
+ const closed = closedSetValueSchema(this.options.values);
962
+ if (closed) return closed;
963
+ let s = z4.string();
898
964
  if (this.options.minLength !== void 0) s = s.min(this.options.minLength);
899
965
  if (this.options.maxLength !== void 0) s = s.max(this.options.maxLength);
900
966
  if (this.options.pattern !== void 0) s = s.regex(new RegExp(this.options.pattern));
@@ -904,14 +970,14 @@ var TextFieldType = class _TextFieldType extends FieldType {
904
970
  toJSON() {
905
971
  return { kind: _TextFieldType.NAME, ...compact(this.options) };
906
972
  }
907
- /** A copy of this field type (cloning the options bag). */
973
+ /** A copy of this field type (deep-cloning the options bag's value set). */
908
974
  clone() {
909
- return new _TextFieldType({ ...this.options });
975
+ return new _TextFieldType({ ...this.options, values: this.options.values?.map((v) => ({ ...v })) });
910
976
  }
911
977
  };
912
978
 
913
979
  // src/field-types/money.ts
914
- import { z as z4 } from "zod";
980
+ import { z as z5 } from "zod";
915
981
  function compact2(o) {
916
982
  const out = {};
917
983
  const num2 = o.number ? compactNumberOptions(o.number) : void 0;
@@ -943,10 +1009,10 @@ var MoneyFieldType = class _MoneyFieldType extends FieldType {
943
1009
  }
944
1010
  /** The Zod schema for this field type's JSON def. */
945
1011
  static toSchema() {
946
- return z4.object({
947
- kind: z4.literal("money"),
1012
+ return z5.object({
1013
+ kind: z5.literal("money"),
948
1014
  number: numberOptionsSchema().optional().describe("Numeric constraints on the amount."),
949
- currency: z4.string().optional().describe('ISO 4217 currency code (e.g. "USD").')
1015
+ currency: z5.string().optional().describe('ISO 4217 currency code (e.g. "USD").')
950
1016
  }).meta({ aid: "FieldType_money" }).describe("Monetary amount field type.");
951
1017
  }
952
1018
  /** Resolve to the `money` scalar comparison category. */
@@ -979,7 +1045,7 @@ var MoneyFieldType = class _MoneyFieldType extends FieldType {
979
1045
  };
980
1046
 
981
1047
  // src/field-types/bool.ts
982
- import { z as z5 } from "zod";
1048
+ import { z as z6 } from "zod";
983
1049
  var BoolFieldType = class _BoolFieldType extends FieldType {
984
1050
  /** Discriminant kind tag (`'bool'`) shared by all instances. */
985
1051
  static NAME = "bool";
@@ -999,7 +1065,7 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
999
1065
  }
1000
1066
  /** The Zod schema for this field type's JSON def. */
1001
1067
  static toSchema() {
1002
- return z5.object({ kind: z5.literal("bool") }).meta({ aid: "FieldType_bool" }).describe("Boolean field type.");
1068
+ return z6.object({ kind: z6.literal("bool") }).meta({ aid: "FieldType_bool" }).describe("Boolean field type.");
1003
1069
  }
1004
1070
  /** Resolve to the `bool` scalar comparison category. */
1005
1071
  resolve() {
@@ -1015,7 +1081,7 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
1015
1081
  }
1016
1082
  /** Zod schema validating a boolean value. */
1017
1083
  toValueSchema(_opts) {
1018
- return z5.boolean();
1084
+ return z6.boolean();
1019
1085
  }
1020
1086
  /** Serialize to its JSON def. */
1021
1087
  toJSON() {
@@ -1028,7 +1094,7 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
1028
1094
  };
1029
1095
 
1030
1096
  // src/field-types/relation.ts
1031
- import { z as z6 } from "zod";
1097
+ import { z as z7 } from "zod";
1032
1098
 
1033
1099
  // src/backing.ts
1034
1100
  function joinAlias(sourceAlias, name) {
@@ -1266,24 +1332,41 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1266
1332
  }
1267
1333
  /** The Zod schema for this field type's JSON def. */
1268
1334
  static toSchema() {
1269
- return z6.object({
1270
- kind: z6.literal("relation"),
1271
- to: z6.string().describe("Name of the target Type this relation points to."),
1272
- count: z6.number().describe("Expected related-row cardinality; 1 = belongs-to, >1 = has-many."),
1273
- inverseRelation: z6.string().optional().describe("If set, the target Type gains a one-to-many relation of this name pointing back.")
1335
+ return z7.object({
1336
+ kind: z7.literal("relation"),
1337
+ to: z7.string().describe("Name of the target Type this relation points to."),
1338
+ count: z7.number().describe("Expected related-row cardinality; 1 = belongs-to, >1 = has-many."),
1339
+ inverseRelation: z7.string().optional().describe("If set, the target Type gains a one-to-many relation of this name pointing back.")
1274
1340
  }).meta({ aid: "FieldType_relation" }).describe("Relation (foreign-key) field type.");
1275
1341
  }
1342
+ /**
1343
+ * True when the FOREIGN KEY lives on THIS Type — a declared belongs-to. The
1344
+ * cardinality alone is NOT the discriminator: a MATERIALIZED INVERSE (one
1345
+ * carrying {@link inverseVia}) is never belongs-to however its estimated
1346
+ * `count` came out, because `Registry.finalize()` derives that count from a
1347
+ * ROW RATIO (`round(source.count / target.count)`) — so a 1:1 pair, or two
1348
+ * unmeasured Types sharing one declared row estimate, legitimately yields 1.
1349
+ *
1350
+ * Reading `count === 1` alone made such an inverse resolve its join as
1351
+ * `order.invoice = invoice.id`, where `order.invoice` is the SYNTHETIC
1352
+ * relation field the registry just added rather than a column — every
1353
+ * traversal then matched zero rows, silently. The FK side is knowable from
1354
+ * `inverseVia`; this is where that knowledge is applied.
1355
+ */
1356
+ isBelongsTo() {
1357
+ return this.count === 1 && this.inverseVia === void 0;
1358
+ }
1276
1359
  /**
1277
1360
  * Resolve the join key for this relation, given the relation field's NAME and
1278
1361
  * the two Types it relates. The relation field's NAME is the key:
1279
- * - belongs-to (`count === 1`): `this.<relName> = target.<identity>` —
1362
+ * - belongs-to ({@link isBelongsTo}): `this.<relName> = target.<identity>` —
1280
1363
  * the local relation field holds the target's identity value.
1281
- * - has-many (`count > 1`): `this.<identity> = target.<fk>` — where the
1282
- * FK on the target is `inverseVia` (for a materialized inverse) else the
1283
- * declaring Type's name in camelCase.
1364
+ * - has-many: `this.<identity> = target.<fk>` — where the FK on the target
1365
+ * is `inverseVia` (for a materialized inverse) else the declaring Type's
1366
+ * name in camelCase.
1284
1367
  */
1285
1368
  resolveKey(relationFieldName, thisType, targetType) {
1286
- if (this.count === 1) {
1369
+ if (this.isBelongsTo()) {
1287
1370
  return {
1288
1371
  localField: relationFieldName,
1289
1372
  foreignField: targetType.identityField().name
@@ -1304,7 +1387,7 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1304
1387
  * name-convention pair. Drives relation comparison lowering (`= <> in`).
1305
1388
  */
1306
1389
  resolveKeys(engine, relationFieldName, thisType, targetType) {
1307
- const forward = this.count === 1;
1390
+ const forward = this.isBelongsTo();
1308
1391
  let backing;
1309
1392
  if (forward) {
1310
1393
  backing = engine.fieldBacking(thisType.name, relationFieldName)?.relation;
@@ -1329,7 +1412,7 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1329
1412
  * source, `targetAlias` = the target), so aliased / self-joins resolve.
1330
1413
  *
1331
1414
  * The backing lives on the OWNING (belongs-to) relation. A materialized
1332
- * inverse has-many (`count > 1` with an `inverseVia`) REUSES the SAME FK: its
1415
+ * inverse has-many (one carrying an `inverseVia`) REUSES the SAME FK: its
1333
1416
  * forward relation's `relation` backing on the target Type, with the key
1334
1417
  * orientation SWAPPED (the declaring side is now the join's target). A
1335
1418
  * directly-declared has-many (no `inverseVia`) has no forward relation to
@@ -1341,7 +1424,7 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1341
1424
  let targetIdentity;
1342
1425
  let declarerAlias;
1343
1426
  let joinedAlias;
1344
- if (this.count === 1) {
1427
+ if (this.isBelongsTo()) {
1345
1428
  backing = engine.fieldBacking(thisType.name, relationFieldName)?.relation;
1346
1429
  forward = true;
1347
1430
  targetIdentity = targetType.identityField().name;
@@ -1378,7 +1461,7 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1378
1461
  }
1379
1462
  /** Zod schema validating a relation value (the related row's identifier). */
1380
1463
  toValueSchema(_opts) {
1381
- return z6.string();
1464
+ return z7.string();
1382
1465
  }
1383
1466
  /** Serialize to its JSON def (`inverseVia` is internal, never emitted). */
1384
1467
  toJSON() {
@@ -1393,15 +1476,15 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1393
1476
  };
1394
1477
 
1395
1478
  // src/field-types/date.ts
1396
- import { z as z8 } from "zod";
1479
+ import { z as z9 } from "zod";
1397
1480
 
1398
1481
  // src/field-types/timestamp.ts
1399
- import { z as z7 } from "zod";
1482
+ import { z as z8 } from "zod";
1400
1483
  var ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
1401
1484
  function timezoneSchema() {
1402
- return z7.union([
1403
- z7.string().describe('Fixed IANA timezone name (e.g. "America/New_York").'),
1404
- z7.boolean().describe("true = tz-aware, false = naive/local.")
1485
+ return z8.union([
1486
+ z8.string().describe('Fixed IANA timezone name (e.g. "America/New_York").'),
1487
+ z8.boolean().describe("true = tz-aware, false = naive/local.")
1405
1488
  ]).describe("Timezone policy.");
1406
1489
  }
1407
1490
  var TimestampFieldType = class _TimestampFieldType extends FieldType {
@@ -1428,8 +1511,8 @@ var TimestampFieldType = class _TimestampFieldType extends FieldType {
1428
1511
  }
1429
1512
  /** The Zod schema for this field type's JSON def. */
1430
1513
  static toSchema() {
1431
- return z7.object({
1432
- kind: z7.literal("timestamp"),
1514
+ return z8.object({
1515
+ kind: z8.literal("timestamp"),
1433
1516
  timezone: timezoneSchema().optional()
1434
1517
  }).meta({ aid: "FieldType_timestamp" }).describe("Timestamp (date + time) field type.");
1435
1518
  }
@@ -1447,7 +1530,7 @@ var TimestampFieldType = class _TimestampFieldType extends FieldType {
1447
1530
  }
1448
1531
  /** Zod schema validating an ISO timestamp (`YYYY-MM-DD HH:MM`) value. */
1449
1532
  toValueSchema(_opts) {
1450
- return z7.string().regex(ISO_TIMESTAMP, "expected ISO timestamp (YYYY-MM-DD HH:MM)");
1533
+ return z8.string().regex(ISO_TIMESTAMP, "expected ISO timestamp (YYYY-MM-DD HH:MM)");
1451
1534
  }
1452
1535
  /** Serialize to its JSON def (omitting `timezone` when unset). */
1453
1536
  toJSON() {
@@ -1485,8 +1568,8 @@ var DateFieldType = class _DateFieldType extends FieldType {
1485
1568
  }
1486
1569
  /** The Zod schema for this field type's JSON def. */
1487
1570
  static toSchema() {
1488
- return z8.object({
1489
- kind: z8.literal("date"),
1571
+ return z9.object({
1572
+ kind: z9.literal("date"),
1490
1573
  timezone: timezoneSchema().optional()
1491
1574
  }).meta({ aid: "FieldType_date" }).describe("Calendar-date field type.");
1492
1575
  }
@@ -1504,7 +1587,7 @@ var DateFieldType = class _DateFieldType extends FieldType {
1504
1587
  }
1505
1588
  /** Zod schema validating an ISO date (`YYYY-MM-DD`) value. */
1506
1589
  toValueSchema(_opts) {
1507
- return z8.string().regex(ISO_DATE, "expected ISO date (YYYY-MM-DD)");
1590
+ return z9.string().regex(ISO_DATE, "expected ISO date (YYYY-MM-DD)");
1508
1591
  }
1509
1592
  /** Serialize to its JSON def (omitting `timezone` when unset). */
1510
1593
  toJSON() {
@@ -1517,16 +1600,16 @@ var DateFieldType = class _DateFieldType extends FieldType {
1517
1600
  };
1518
1601
 
1519
1602
  // src/field-types/json.ts
1520
- import { z as z9 } from "zod";
1603
+ import { z as z10 } from "zod";
1521
1604
  function jsonValueSchema() {
1522
- const schema = z9.lazy(
1523
- () => z9.union([
1524
- z9.string(),
1525
- z9.number(),
1526
- z9.boolean(),
1527
- z9.null(),
1528
- z9.array(schema),
1529
- z9.record(z9.string(), schema)
1605
+ const schema = z10.lazy(
1606
+ () => z10.union([
1607
+ z10.string(),
1608
+ z10.number(),
1609
+ z10.boolean(),
1610
+ z10.null(),
1611
+ z10.array(schema),
1612
+ z10.record(z10.string(), schema)
1530
1613
  ])
1531
1614
  );
1532
1615
  return schema;
@@ -1555,8 +1638,8 @@ var JsonFieldType = class _JsonFieldType extends FieldType {
1555
1638
  }
1556
1639
  /** The Zod schema for this field type's JSON def. */
1557
1640
  static toSchema() {
1558
- return z9.object({
1559
- kind: z9.literal("json"),
1641
+ return z10.object({
1642
+ kind: z10.literal("json"),
1560
1643
  schema: jsonValueSchema().optional().describe("Optional JSON-Schema-shaped constraint.")
1561
1644
  }).meta({ aid: "FieldType_json" }).describe("JSON-document field type.");
1562
1645
  }
@@ -1592,7 +1675,7 @@ var JsonFieldType = class _JsonFieldType extends FieldType {
1592
1675
  };
1593
1676
 
1594
1677
  // src/field-types/array.ts
1595
- import { z as z10 } from "zod";
1678
+ import { z as z11 } from "zod";
1596
1679
  var DEFAULT_AVG_ITEMS = 4;
1597
1680
  var UNKNOWN_ITEM_BYTES = 16;
1598
1681
  var ArrayFieldType = class _ArrayFieldType extends FieldType {
@@ -1624,11 +1707,11 @@ var ArrayFieldType = class _ArrayFieldType extends FieldType {
1624
1707
  }
1625
1708
  /** The Zod schema for this field type's JSON def. */
1626
1709
  static toSchema() {
1627
- const item = z10.lazy(() => fieldTypeDefSchema());
1628
- return z10.object({
1629
- kind: z10.literal("array"),
1630
- minItems: z10.number().int().optional().describe("Minimum element count (e.g. non-empty \u2192 1)."),
1631
- maxItems: z10.number().int().optional().describe("Maximum element count; omit when unbounded."),
1710
+ const item = z11.lazy(() => fieldTypeDefSchema());
1711
+ return z11.object({
1712
+ kind: z11.literal("array"),
1713
+ minItems: z11.number().int().optional().describe("Minimum element count (e.g. non-empty \u2192 1)."),
1714
+ maxItems: z11.number().int().optional().describe("Maximum element count; omit when unbounded."),
1632
1715
  item: item.optional().describe("Element field type; omit for heterogeneous / unknown elements.")
1633
1716
  }).meta({ aid: "FieldType_array" }).describe("Ordered collection (array) field type.");
1634
1717
  }
@@ -1660,7 +1743,7 @@ var ArrayFieldType = class _ArrayFieldType extends FieldType {
1660
1743
  }
1661
1744
  /** Zod schema validating an array value, honoring element type and bounds. */
1662
1745
  toValueSchema(opts) {
1663
- let s = z10.array(this.item ? this.item.toValueSchema(opts) : jsonValueSchema());
1746
+ let s = z11.array(this.item ? this.item.toValueSchema(opts) : jsonValueSchema());
1664
1747
  if (this.minItems !== void 0) s = s.min(this.minItems);
1665
1748
  if (this.maxItems !== void 0) s = s.max(this.maxItems);
1666
1749
  return s;
@@ -1698,7 +1781,7 @@ var BUILTIN_FIELD_TYPES = [
1698
1781
  function fieldTypeDefSchema() {
1699
1782
  const branches = BUILTIN_FIELD_TYPES.map((c) => c.toSchema());
1700
1783
  const first = branches[0];
1701
- if (!first) return z11.never();
1784
+ if (!first) return z12.never();
1702
1785
  return branches.slice(1).reduce((acc, s) => acc.or(s), first).describe("Field type definition (one of the 8 built-in kinds).");
1703
1786
  }
1704
1787
 
@@ -1886,6 +1969,22 @@ function exprDigest(expr) {
1886
1969
  const json = JSON.parse(JSON.stringify(expr));
1887
1970
  return stableStringify(json);
1888
1971
  }
1972
+ function renameJson(node, from, to) {
1973
+ if (Array.isArray(node)) return node.map((n) => renameJson(n, from, to));
1974
+ if (node === null || typeof node !== "object") return node;
1975
+ const out = {};
1976
+ for (const key of Object.keys(node)) out[key] = renameJson(node[key], from, to);
1977
+ if (out["kind"] === "field-ref" && out["source"] === from) out["source"] = to;
1978
+ return out;
1979
+ }
1980
+ function renameSource(expr, from, to) {
1981
+ const renamed = JSON.parse(JSON.stringify(renameJson(JSON.parse(JSON.stringify(expr)), from, to)));
1982
+ return renamed;
1983
+ }
1984
+ function aliasedDigest(expr, alias, typeName) {
1985
+ if (alias === typeName) return exprDigest(expr);
1986
+ return stableStringify(renameJson(JSON.parse(JSON.stringify(expr)), alias, typeName));
1987
+ }
1889
1988
  var IndexPart = class {
1890
1989
  constructor(expr, count2) {
1891
1990
  this.expr = expr;
@@ -1948,9 +2047,17 @@ var Index = class _Index {
1948
2047
  * Because part counts are non-increasing, a longer matched prefix always
1949
2048
  * yields a smaller (or equal) estimate — so this returns the tightest bound
1950
2049
  * the supplied predicates can achieve via this index.
1951
- */
1952
- prefixReduction(used) {
1953
- const digests = used.map((u) => exprDigest(u.toJSON()));
2050
+ *
2051
+ * `alias` names the SOURCE the supplied usages are bound under together with
2052
+ * the TYPE this index belongs to; when they differ, each usage is normalized
2053
+ * back to the type name before matching (see {@link aliasedDigest}). Omitting
2054
+ * it keeps the literal, un-normalized match — the identity case, and what
2055
+ * every pre-existing caller gets.
2056
+ */
2057
+ prefixReduction(used, alias) {
2058
+ const digests = used.map(
2059
+ (u) => alias ? aliasedDigest(u.toJSON(), alias.source, alias.typeName) : exprDigest(u.toJSON())
2060
+ );
1954
2061
  let reduction;
1955
2062
  for (const part of this.parts) {
1956
2063
  if (!digests.includes(part.digest)) break;
@@ -1975,9 +2082,13 @@ var Index = class _Index {
1975
2082
  };
1976
2083
 
1977
2084
  // src/type.ts
1978
- import { z as z12 } from "zod";
2085
+ import { z as z13 } from "zod";
1979
2086
  function noKeyMessage(typeName) {
1980
- return `Type '${typeName}' needs a primary key (a unique index or an 'id' field) to participate in relations.`;
2087
+ return `Type '${typeName}' needs a primary key (a declared 'identity', a unique index, or an 'id' field) to participate in relations.`;
2088
+ }
2089
+ function identityNames(identity) {
2090
+ if (identity === void 0) return void 0;
2091
+ return typeof identity === "string" ? [identity] : identity;
1981
2092
  }
1982
2093
  var Type = class _Type {
1983
2094
  /** Type name (unique within the registry). */
@@ -1990,6 +2101,12 @@ var Type = class _Type {
1990
2101
  fields;
1991
2102
  /** The (composite) indexes declared on this Type. */
1992
2103
  indexes;
2104
+ /**
2105
+ * The DECLARED identity field names, in key order — normalized from the spec's
2106
+ * `string | string[]`. `undefined` means identity is INFERRED (first
2107
+ * single-part unique index, else `id`), which is index-order dependent.
2108
+ */
2109
+ identity;
1993
2110
  /** Estimated total row count (drives cost estimation). */
1994
2111
  count;
1995
2112
  /** Estimated average bytes per row (drives byte-cost estimation). */
@@ -2013,6 +2130,7 @@ var Type = class _Type {
2013
2130
  this.description = spec.description;
2014
2131
  this.fields = spec.fields;
2015
2132
  this.indexes = spec.indexes;
2133
+ this.identity = identityNames(spec.identity);
2016
2134
  this.count = spec.count;
2017
2135
  this.bytes = spec.bytes ?? this.fields.reduce((sum2, f) => sum2 + f.bytes(), 0);
2018
2136
  this.changes = spec.changes ?? 0;
@@ -2036,9 +2154,10 @@ var Type = class _Type {
2036
2154
  }
2037
2155
  /**
2038
2156
  * The IDENTITY field used as the join key on this Type's side of a relation:
2039
- * the field referenced by the first single-part UNIQUE index (one part,
2040
- * `count === 1`, whose expr is a field-ref), else the field named `id`, else
2041
- * a clear error. Relations resolve their keys through this.
2157
+ * the DECLARED `identity` when it names exactly one field, else the field
2158
+ * referenced by the first single-part UNIQUE index (one part, `count === 1`,
2159
+ * whose expr is a field-ref), else the field named `id`, else a clear error.
2160
+ * Relations resolve their keys through this.
2042
2161
  */
2043
2162
  identityField() {
2044
2163
  const single = this.singleIdentity();
@@ -2047,13 +2166,15 @@ var Type = class _Type {
2047
2166
  }
2048
2167
  /**
2049
2168
  * The ordered PRIMARY KEY fields of this Type — generalizing {@link
2050
- * identityField} to COMPOSITE keys: the single identity field (a single-part
2051
- * unique index's field, else `id`) when present, else the fields of the first
2052
- * multi-part UNIQUE index (last part `count === 1`) whose every part is a
2053
- * field-ref. Relations map their key columns to these; a relation VALUE is
2054
- * keyed by these field names. Throws when none exists.
2169
+ * identityField} to COMPOSITE keys: the DECLARED `identity` when set, else the
2170
+ * single identity field (a single-part unique index's field, else `id`), else
2171
+ * the fields of the first multi-part UNIQUE index (last part `count === 1`)
2172
+ * whose every part is a field-ref. Relations map their key columns to these; a
2173
+ * relation VALUE is keyed by these field names. Throws when none exists.
2055
2174
  */
2056
2175
  primaryKey() {
2176
+ const declared = this.declaredIdentity();
2177
+ if (declared) return declared;
2057
2178
  const single = this.singleIdentity();
2058
2179
  if (single) return [single];
2059
2180
  for (const idx of this.indexes) {
@@ -2064,8 +2185,36 @@ var Type = class _Type {
2064
2185
  }
2065
2186
  throw new QueryTypeError({ path: [], code: "type.no-identity", severity: "error", message: noKeyMessage(this.name) });
2066
2187
  }
2067
- /** The single identity field: the first single-part unique index's field, else `id`, else undefined. */
2188
+ /**
2189
+ * The fields named by an explicit `identity` declaration, in key order, or
2190
+ * `undefined` when none is declared. A declared name that is not a field on
2191
+ * this Type is an ERROR rather than a silent fall-back to the inferred rule —
2192
+ * falling back would reintroduce exactly the index-order dependence the
2193
+ * declaration exists to remove, and would do it invisibly.
2194
+ */
2195
+ declaredIdentity() {
2196
+ if (this.identity === void 0) return void 0;
2197
+ const found = this.identity.map((name) => this.field(name));
2198
+ const missing = this.identity.filter((_, i) => found[i] === void 0);
2199
+ if (missing.length > 0) {
2200
+ throw new QueryTypeError({
2201
+ path: [],
2202
+ code: "type.identity-unknown-field",
2203
+ severity: "error",
2204
+ message: `Type '${this.name}' declares identity field(s) ${missing.map((m) => `'${m}'`).join(", ")} that it does not have. Declared identity: ${this.identity.join(", ")}.`
2205
+ });
2206
+ }
2207
+ return found.filter((f) => f !== void 0);
2208
+ }
2209
+ /**
2210
+ * The single identity field: the DECLARED `identity` when it is exactly one
2211
+ * field, else the first single-part unique index's field, else `id`, else
2212
+ * undefined. A declared COMPOSITE identity has no single field, so it yields
2213
+ * `undefined` here and is answered by {@link primaryKey}.
2214
+ */
2068
2215
  singleIdentity() {
2216
+ const declared = this.declaredIdentity();
2217
+ if (declared) return declared.length === 1 ? declared[0] : void 0;
2069
2218
  for (const idx of this.indexes) {
2070
2219
  if (idx.parts.length !== 1) continue;
2071
2220
  const part = idx.parts[0];
@@ -2077,27 +2226,57 @@ var Type = class _Type {
2077
2226
  return this.field("id");
2078
2227
  }
2079
2228
  /**
2080
- * Fields eligible for semantic-aware querying: text fields flagged
2081
- * `semantic` or `search`, plus all relation fields (which can drive
2082
- * cross-entity semantic joins).
2229
+ * Fields eligible for semantic-aware querying: text fields flagged `semantic`
2230
+ * or `search`.
2231
+ *
2232
+ * Relation fields are NOT included. They used to be — on the theory that they
2233
+ * could drive cross-entity semantic joins — which made almost every Type
2234
+ * report itself semantic-eligible on the strength of having a foreign key, and
2235
+ * a whole-source semantic score then silently ran over a Type nobody had
2236
+ * declared semantic. A relation is a join, not an embedding.
2083
2237
  */
2084
2238
  semanticFields() {
2085
- return this.fields.filter((f) => {
2086
- const ft = f.fieldType;
2087
- if (ft instanceof TextFieldType) return ft.options.semantic === true || ft.options.search === true;
2088
- return ft instanceof RelationFieldType;
2089
- });
2239
+ return this.fields.filter((f) => this.isFieldSemantic(f));
2240
+ }
2241
+ /**
2242
+ * Whether ONE field is declared semantic-eligible: a text field flagged
2243
+ * `semantic` (or `search`, whose index is the same kind of derived artifact).
2244
+ */
2245
+ isFieldSemantic(field) {
2246
+ const ft = field.fieldType;
2247
+ return ft instanceof TextFieldType && (ft.options.semantic === true || ft.options.search === true);
2090
2248
  }
2091
- /** Whether this Type is eligible for embedding-based semantic similarity. */
2249
+ /**
2250
+ * Whether semantic scoring is possible ANYWHERE on this Type — the whole type
2251
+ * is flagged, or at least one field is. This is the ELIGIBILITY question
2252
+ * (does the `semantic` expr apply to this Type at all), which is what schema
2253
+ * gating and the capability description ask.
2254
+ *
2255
+ * What an UNNARROWED score reads is the row's embedding over
2256
+ * {@link semanticFields}, which no longer counts relation fields — so a Type
2257
+ * whose only "evidence" was owning a foreign key is no longer eligible at
2258
+ * all. See {@link isFieldSemantic} for the per-field question.
2259
+ */
2092
2260
  isSemantic() {
2093
2261
  return this.semantic || this.semanticFields().length > 0;
2094
2262
  }
2095
- /** Whether this Type is eligible for full-text search. */
2263
+ /** Whether ONE field is declared full-text searchable. */
2264
+ isFieldSearchable(field) {
2265
+ const ft = field.fieldType;
2266
+ return ft instanceof TextFieldType && ft.options.search === true;
2267
+ }
2268
+ /**
2269
+ * Whether full-text search is possible ANYWHERE on this Type — the whole type
2270
+ * is flagged, or at least one field is. The ELIGIBILITY question, used for
2271
+ * schema gating and the capability description.
2272
+ *
2273
+ * It is NOT the answer to "can this type be searched WITHOUT naming a field":
2274
+ * that needs a `SearchBacking` (the searchable document), whose absence is now
2275
+ * refused as `text-search.unbacked` rather than guessed at. See
2276
+ * {@link isFieldSearchable} for the per-field question.
2277
+ */
2096
2278
  isSearchable() {
2097
- if (this.search) return true;
2098
- return this.fields.some(
2099
- (f) => f.fieldType instanceof TextFieldType && f.fieldType.options.search === true
2100
- );
2279
+ return this.search || this.fields.some((f) => this.isFieldSearchable(f));
2101
2280
  }
2102
2281
  /** Build a Type from its JSON, parsing fields/indexes via `registry`. */
2103
2282
  static from(json, registry) {
@@ -2109,6 +2288,7 @@ var Type = class _Type {
2109
2288
  description: json.description,
2110
2289
  fields,
2111
2290
  indexes,
2291
+ identity: json.identity,
2112
2292
  count: json.count,
2113
2293
  bytes: json.bytes,
2114
2294
  changes: json.changes,
@@ -2121,46 +2301,49 @@ var Type = class _Type {
2121
2301
  }
2122
2302
  /** Zod schema for the `TypeDef` JSON shape. */
2123
2303
  static toSchema(opts) {
2124
- const exprKindSchema = z12.string().describe("An expression kind (e.g. `comparison`, `array-op`).");
2125
- const fieldExprsSchema = z12.union([
2126
- z12.object({ not: z12.array(exprKindSchema).describe("Expr kinds to EXCLUDE for this field.") }),
2127
- z12.object({ only: z12.array(exprKindSchema).describe("The ONLY expr kinds allowed for this field.") })
2304
+ const exprKindSchema = z13.string().describe("An expression kind (e.g. `comparison`, `array-op`).");
2305
+ const fieldExprsSchema = z13.union([
2306
+ z13.object({ not: z13.array(exprKindSchema).describe("Expr kinds to EXCLUDE for this field.") }),
2307
+ z13.object({ only: z13.array(exprKindSchema).describe("The ONLY expr kinds allowed for this field.") })
2128
2308
  ]).describe("Restrict which expr kinds may target this field (narrows the type's set).");
2129
- const fieldDefSchema = z12.object({
2130
- name: z12.string(),
2131
- label: z12.string().optional(),
2132
- description: z12.string().optional(),
2309
+ const fieldDefSchema = z13.object({
2310
+ name: z13.string(),
2311
+ label: z13.string().optional(),
2312
+ description: z13.string().optional(),
2133
2313
  type: fieldTypeDefSchema(),
2134
- bytes: z12.number().optional().describe("Estimated average stored bytes for this field (overrides the field type default)."),
2135
- changes: z12.number().optional().describe("Ms between changes to this field (overrides the Type; 0 = always, -1 = never)."),
2136
- nullable: z12.boolean().optional(),
2137
- insertable: z12.boolean().optional().describe("Whether the field may be supplied on INSERT (default true)."),
2138
- updatable: z12.boolean().optional().describe("Whether the field may be assigned on UPDATE (default true)."),
2314
+ bytes: z13.number().optional().describe("Estimated average stored bytes for this field (overrides the field type default)."),
2315
+ changes: z13.number().optional().describe("Ms between changes to this field (overrides the Type; 0 = always, -1 = never)."),
2316
+ nullable: z13.boolean().optional(),
2317
+ insertable: z13.boolean().optional().describe("Whether the field may be supplied on INSERT (default true)."),
2318
+ updatable: z13.boolean().optional().describe("Whether the field may be assigned on UPDATE (default true)."),
2139
2319
  exprs: fieldExprsSchema.optional()
2140
2320
  }).meta({ aid: "FieldDef" }).describe("A field (field) definition.");
2141
- const exprSchema = opts?.Expr ?? z12.object({ kind: z12.string() }).loose();
2142
- const indexPartDefSchema = z12.object({
2321
+ const exprSchema = opts?.Expr ?? z13.object({ kind: z13.string() }).loose();
2322
+ const indexPartDefSchema = z13.object({
2143
2323
  expr: exprSchema,
2144
- count: z12.number().describe("Prefix distinct rows up to & including this part; last part 1 \u21D2 unique.")
2324
+ count: z13.number().describe("Prefix distinct rows up to & including this part; last part 1 \u21D2 unique.")
2145
2325
  }).meta({ aid: "IndexPartDef" }).describe("One ordered part of a composite index.");
2146
- const indexDefSchema = z12.object({
2147
- exprs: z12.array(indexPartDefSchema).describe("Ordered composite-index parts."),
2148
- bytes: z12.number().optional().describe("Estimated average bytes per index entry (else derived from the parts).")
2326
+ const indexDefSchema = z13.object({
2327
+ exprs: z13.array(indexPartDefSchema).describe("Ordered composite-index parts."),
2328
+ bytes: z13.number().optional().describe("Estimated average bytes per index entry (else derived from the parts).")
2149
2329
  }).meta({ aid: "IndexDef" }).describe("A composite index definition.");
2150
- return z12.object({
2151
- name: z12.string(),
2152
- label: z12.string().optional(),
2153
- description: z12.string().optional(),
2154
- fields: z12.array(fieldDefSchema),
2155
- indexes: z12.array(indexDefSchema).optional(),
2156
- count: z12.number().describe("Estimated total row count."),
2157
- bytes: z12.number().optional().describe("Estimated average bytes per row (else derived as the sum of the fields' bytes)."),
2158
- changes: z12.number().optional().describe("Ms between changes to this Type's data (0 = always changing, -1 = never)."),
2159
- semantic: z12.boolean().optional().describe("Eligible for semantic similarity across the type."),
2160
- search: z12.boolean().optional().describe("Eligible for full-text search across the type."),
2161
- insertable: z12.boolean().optional().describe("Whether rows may be INSERTed (default true)."),
2162
- updatable: z12.boolean().optional().describe("Whether rows may be UPDATEd (default true)."),
2163
- deletable: z12.boolean().optional().describe("Whether rows may be DELETEd (default true).")
2330
+ return z13.object({
2331
+ name: z13.string(),
2332
+ label: z13.string().optional(),
2333
+ description: z13.string().optional(),
2334
+ fields: z13.array(fieldDefSchema),
2335
+ indexes: z13.array(indexDefSchema).optional(),
2336
+ identity: z13.union([z13.string(), z13.array(z13.string())]).optional().describe(
2337
+ "The field (or ordered fields) that IDENTIFY a row. Declare it and index order stops deciding identity."
2338
+ ),
2339
+ count: z13.number().describe("Estimated total row count."),
2340
+ bytes: z13.number().optional().describe("Estimated average bytes per row (else derived as the sum of the fields' bytes)."),
2341
+ changes: z13.number().optional().describe("Ms between changes to this Type's data (0 = always changing, -1 = never)."),
2342
+ semantic: z13.boolean().optional().describe("Eligible for semantic similarity across the type."),
2343
+ search: z13.boolean().optional().describe("Eligible for full-text search across the type."),
2344
+ insertable: z13.boolean().optional().describe("Whether rows may be INSERTed (default true)."),
2345
+ updatable: z13.boolean().optional().describe("Whether rows may be UPDATEd (default true)."),
2346
+ deletable: z13.boolean().optional().describe("Whether rows may be DELETEd (default true).")
2164
2347
  }).meta({ aid: "TypeDef" }).describe("A type-like Type definition.");
2165
2348
  }
2166
2349
  /** Serialize to its `TypeDef` JSON shape (omits synthetic fields and false flags). */
@@ -2173,6 +2356,9 @@ var Type = class _Type {
2173
2356
  description: this.description,
2174
2357
  fields,
2175
2358
  indexes: indexes.length > 0 ? indexes : void 0,
2359
+ // Emitted in its NORMALIZED form: a single declared field round-trips as a
2360
+ // bare name whether it was authored as `'id'` or `['id']`.
2361
+ identity: this.identity === void 0 ? void 0 : this.identity.length === 1 ? this.identity[0] : [...this.identity],
2176
2362
  count: this.count,
2177
2363
  bytes: this.bytes,
2178
2364
  // Emit `changes` only when set away from the default (0 = always changing).
@@ -2193,6 +2379,7 @@ var Type = class _Type {
2193
2379
  description: this.description,
2194
2380
  fields: this.fields.map((f) => f.clone()),
2195
2381
  indexes: this.indexes.map((i) => i.clone()),
2382
+ identity: this.identity === void 0 ? void 0 : [...this.identity],
2196
2383
  count: this.count,
2197
2384
  bytes: this.bytes,
2198
2385
  changes: this.changes,
@@ -2312,6 +2499,8 @@ function rowsCost(rows, perRowBytes) {
2312
2499
  }
2313
2500
  function bytesOfResolved(rt) {
2314
2501
  if (rt.kind === "field") return rt.field.bytes();
2502
+ const rel = relationOf(rt);
2503
+ if (rel) return rel.keys.reduce((sum2, k) => sum2 + k.keyType.avgBytes(), 0);
2315
2504
  return asFieldType(rt)?.avgBytes() ?? 0;
2316
2505
  }
2317
2506
  function reportCostProblems(cost, constraints, p) {
@@ -2853,13 +3042,13 @@ function obj(fields, build, opts = {}) {
2853
3042
  }
2854
3043
 
2855
3044
  // src/exprs/index.ts
2856
- import { z as z35 } from "zod";
3045
+ import { z as z36 } from "zod";
2857
3046
 
2858
3047
  // src/exprs/literal.ts
2859
- import { z as z14 } from "zod";
3048
+ import { z as z15 } from "zod";
2860
3049
 
2861
3050
  // src/exprs/_shared.ts
2862
- import { z as z13 } from "zod";
3051
+ import { z as z14 } from "zod";
2863
3052
  function computed(fieldType, sources, nullable, aggregate2) {
2864
3053
  return { kind: "computed", fieldType, sources, nullable, aggregate: aggregate2 };
2865
3054
  }
@@ -2895,6 +3084,12 @@ function relationHint(rel, tail) {
2895
3084
  function relationAsValueMessage(rel) {
2896
3085
  return relationHint(rel, "or compare it to another relation of the same target.");
2897
3086
  }
3087
+ function hasManyValueMessage(rel) {
3088
+ return `'${rel.source}.${rel.field}' is a HAS-MANY relation: it has no key on this row (the foreign key lives on '${rel.to}'), and its value is a SET, not an identity. Join it (\`{on:{kind:'relation',source:'${rel.source}',field:'${rel.field}',as:'\u2026'}}\`) and read / aggregate the joined source, or test membership with '=' / 'in' against a target key.`;
3089
+ }
3090
+ function relationAggregateMessage(rel) {
3091
+ return `'${rel.source}.${rel.field}' is a relation: its value is an IDENTITY, which cannot be aggregated. Group BY it (or order by it) instead, aggregate one of the joined target's scalar fields, or count rows.`;
3092
+ }
2898
3093
  function relationValueProblem(a, b) {
2899
3094
  const ra = relationOf(a);
2900
3095
  const rb = relationOf(b);
@@ -2911,7 +3106,7 @@ function relationValueProblem(a, b) {
2911
3106
  return relationAsValueMessage(rel);
2912
3107
  }
2913
3108
  function looseExprSchema() {
2914
- return z13.looseObject({ kind: z13.string() });
3109
+ return z14.looseObject({ kind: z14.string() });
2915
3110
  }
2916
3111
  function childExprSchema(Expr9) {
2917
3112
  return Expr9 ?? looseExprSchema();
@@ -3079,9 +3274,9 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3079
3274
  /** Zod schema for this expr kind's JSON shape. */
3080
3275
  static toSchema(_opts) {
3081
3276
  return withAid(
3082
- z14.object({
3083
- kind: z14.literal("literal"),
3084
- value: withAid(z14.union([z14.string(), z14.number(), z14.boolean(), z14.null()]), "ScalarValue")
3277
+ z15.object({
3278
+ kind: z15.literal("literal"),
3279
+ value: withAid(z15.union([z15.string(), z15.number(), z15.boolean(), z15.null()]), "ScalarValue")
3085
3280
  }),
3086
3281
  "Expr_literal"
3087
3282
  ).describe("A constant scalar value.");
@@ -3136,7 +3331,7 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3136
3331
  };
3137
3332
 
3138
3333
  // src/exprs/output-ref.ts
3139
- import { z as z15 } from "zod";
3334
+ import { z as z16 } from "zod";
3140
3335
  var OutputRefExpr = class _OutputRefExpr extends Expr {
3141
3336
  /** Wrap the referenced output field name. */
3142
3337
  constructor(name) {
@@ -3172,9 +3367,9 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
3172
3367
  /** Zod schema for this expr kind's JSON shape (name is query-local ⇒ a plain string). */
3173
3368
  static toSchema(_opts) {
3174
3369
  return withAid(
3175
- z15.object({
3176
- kind: z15.literal("output"),
3177
- name: z15.string().describe("A SELECT output field name (its `as`, or the natural derived name).")
3370
+ z16.object({
3371
+ kind: z16.literal("output"),
3372
+ name: z16.string().describe("A SELECT output field name (its `as`, or the natural derived name).")
3178
3373
  }),
3179
3374
  "Expr_output"
3180
3375
  ).describe("A reference to a SELECT output field by name (valid in groupBy / orderBy / having).");
@@ -3251,7 +3446,7 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
3251
3446
  };
3252
3447
 
3253
3448
  // src/schema-build.ts
3254
- import { z as z16 } from "zod";
3449
+ import { z as z17 } from "zod";
3255
3450
 
3256
3451
  // src/write-model.ts
3257
3452
  function requiredOnInsert(field, fb) {
@@ -3277,16 +3472,16 @@ function checkFieldExpr(kind, field, source, p) {
3277
3472
  function enumOf2(values) {
3278
3473
  const unique = Array.from(new Set(values));
3279
3474
  const first = unique[0];
3280
- if (first === void 0) return z16.never();
3281
- return unique.slice(1).reduce((acc, v) => acc.or(z16.literal(v)), z16.literal(first));
3475
+ if (first === void 0) return z17.never();
3476
+ return unique.slice(1).reduce((acc, v) => acc.or(z17.literal(v)), z17.literal(first));
3282
3477
  }
3283
3478
  function orFold(branches) {
3284
3479
  const first = branches[0];
3285
- if (!first) return z16.never();
3480
+ if (!first) return z17.never();
3286
3481
  return branches.slice(1).reduce((acc, s) => acc.or(s), first);
3287
3482
  }
3288
3483
  function paramSchema() {
3289
- return z16.object({ kind: z16.literal("param"), name: z16.string() }).describe("A named bind parameter.");
3484
+ return z17.object({ kind: z17.literal("param"), name: z17.string() }).describe("A named bind parameter.");
3290
3485
  }
3291
3486
  var cacheGeneration = 0;
3292
3487
  var SchemaCache = class {
@@ -3335,7 +3530,7 @@ var SchemaCache = class {
3335
3530
  "param",
3336
3531
  "param",
3337
3532
  (id) => withSharedId(
3338
- z16.object({ kind: z16.literal("param"), name: z16.string() }).describe("A named bind parameter."),
3533
+ z17.object({ kind: z17.literal("param"), name: z17.string() }).describe("A named bind parameter."),
3339
3534
  id
3340
3535
  )
3341
3536
  );
@@ -3355,7 +3550,7 @@ var SchemaCache = class {
3355
3550
  const shape = {};
3356
3551
  for (const param3 of fn2.params) shape[param3.name] = param3.optional ? child.optional() : child;
3357
3552
  const named = params.length ? params.join(", ") : "none";
3358
- return withSharedId(z16.strictObject(shape).describe(`Named arguments: ${named}.`), id);
3553
+ return withSharedId(z17.strictObject(shape).describe(`Named arguments: ${named}.`), id);
3359
3554
  });
3360
3555
  }
3361
3556
  };
@@ -3380,7 +3575,7 @@ function fieldProperty(mode, fieldValue) {
3380
3575
  case "optional":
3381
3576
  return { field: fieldValue.optional().describe("A field to narrow to (omit for the whole source).") };
3382
3577
  case "list":
3383
- return { fields: z16.array(fieldValue).optional().describe("Optional allowlist of fields the reference may touch.") };
3578
+ return { fields: z17.array(fieldValue).optional().describe("Optional allowlist of fields the reference may touch.") };
3384
3579
  /* v8 ignore next 2 -- unreachable: `mode` exhaustively covers RefFieldMode (compile-time guard) */
3385
3580
  default:
3386
3581
  return assertNeverFieldMode(mode);
@@ -3388,7 +3583,7 @@ function fieldProperty(mode, fieldValue) {
3388
3583
  }
3389
3584
  function refObject(keyName, keyValue, fieldProps, extras, aid, describe) {
3390
3585
  const shape = { [keyName]: keyValue, ...fieldProps, ...extras };
3391
- const obj2 = z16.object(shape);
3586
+ const obj2 = z17.object(shape);
3392
3587
  return (aid ? withAid(obj2, aid) : obj2).describe(describe);
3393
3588
  }
3394
3589
  function refSchema(types, depth, opts, cache) {
@@ -3397,8 +3592,8 @@ function refSchema(types, depth, opts, cache) {
3397
3592
  if (depth === "paired") {
3398
3593
  const branches = types.map((t) => {
3399
3594
  const names = opts.eligible(t).map((f) => f.name);
3400
- const fieldValue2 = names.length ? fieldEnum(names, t.name) : z16.string();
3401
- const keyValue2 = z16.literal(t.name).describe(`The \`${t.name}\` ${opts.keyName} (its Type name).`);
3595
+ const fieldValue2 = names.length ? fieldEnum(names, t.name) : z17.string();
3596
+ const keyValue2 = z17.literal(t.name).describe(`The \`${t.name}\` ${opts.keyName} (its Type name).`);
3402
3597
  const fieldProps2 = fieldProperty(opts.fieldMode, fieldValue2);
3403
3598
  return refObject(
3404
3599
  opts.keyName,
@@ -3413,13 +3608,13 @@ function refSchema(types, depth, opts, cache) {
3413
3608
  }
3414
3609
  const enumKey = depth === "types" || depth === "both";
3415
3610
  const enumField = depth === "fields" || depth === "both";
3416
- const keyBase = enumKey ? enumOf2(types.map((t) => t.name)) : z16.string();
3611
+ const keyBase = enumKey ? enumOf2(types.map((t) => t.name)) : z17.string();
3417
3612
  const keyTagged = enumKey && opts.keyName === "type" ? withAid(keyBase, "TypeName") : keyBase;
3418
3613
  const keyValue = keyTagged.describe(
3419
3614
  enumKey ? `${keyNoun[0].toUpperCase()}${keyNoun.slice(1)}.` : `A ${opts.keyName} name.`
3420
3615
  );
3421
3616
  const fieldNames = eligibleFieldNames(types, opts.eligible);
3422
- const fieldValue = enumField && fieldNames.length ? fieldEnum(fieldNames, "any") : z16.string();
3617
+ const fieldValue = enumField && fieldNames.length ? fieldEnum(fieldNames, "any") : z17.string();
3423
3618
  const fieldProps = fieldProperty(opts.fieldMode, fieldValue);
3424
3619
  return refObject(opts.keyName, keyValue, fieldProps, opts.extras, opts.aid, opts.describe);
3425
3620
  }
@@ -3428,7 +3623,7 @@ function fieldRefSchema(types, depth, cache) {
3428
3623
  keyName: "source",
3429
3624
  fieldMode: "one",
3430
3625
  eligible: allowingExpr(allFields, "field-ref"),
3431
- extras: { kind: z16.literal("field-ref") },
3626
+ extras: { kind: z17.literal("field-ref") },
3432
3627
  aid: "Expr_field-ref",
3433
3628
  describe: "A direct field reference."
3434
3629
  }, cache);
@@ -3450,7 +3645,7 @@ function semanticQuerySchema(types, depth, cache) {
3450
3645
  describe: "A semantic Type + field, resolved to that Type's single bound source, whose embedding is the query vector."
3451
3646
  }, cache);
3452
3647
  return orFold([
3453
- z16.string().describe("A literal natural-language query."),
3648
+ z17.string().describe("A literal natural-language query."),
3454
3649
  paramFragment(cache),
3455
3650
  sourceField,
3456
3651
  typeField
@@ -3461,7 +3656,7 @@ function semanticSchema(types, depth, cache) {
3461
3656
  keyName: "source",
3462
3657
  fieldMode: "optional",
3463
3658
  eligible: allowingExpr(semanticFieldsOf, "semantic"),
3464
- extras: { kind: z16.literal("semantic"), query: semanticQuerySchema(types, depth, cache) },
3659
+ extras: { kind: z17.literal("semantic"), query: semanticQuerySchema(types, depth, cache) },
3465
3660
  aid: "Expr_semantic",
3466
3661
  describe: "Semantic-similarity score (requires an embedder)."
3467
3662
  }, cache);
@@ -3472,8 +3667,8 @@ function textSearchSchema(types, depth, cache) {
3472
3667
  fieldMode: "optional",
3473
3668
  eligible: allowingExpr(textFieldsOf, "text-search"),
3474
3669
  extras: {
3475
- kind: z16.literal("text-search"),
3476
- query: z16.string().or(paramFragment(cache)).describe("Search query: a literal string or a param.")
3670
+ kind: z17.literal("text-search"),
3671
+ query: z17.string().or(paramFragment(cache)).describe("Search query: a literal string or a param.")
3477
3672
  },
3478
3673
  aid: "Expr_text-search",
3479
3674
  describe: "Full-text search predicate."
@@ -3485,8 +3680,8 @@ function textScoreSchema(types, depth, cache) {
3485
3680
  fieldMode: "optional",
3486
3681
  eligible: allowingExpr(textFieldsOf, "text-score"),
3487
3682
  extras: {
3488
- kind: z16.literal("text-score"),
3489
- query: z16.string().or(paramFragment(cache)).describe("Search query: a literal string or a param.")
3683
+ kind: z17.literal("text-score"),
3684
+ query: z17.string().or(paramFragment(cache)).describe("Search query: a literal string or a param.")
3490
3685
  },
3491
3686
  aid: "Expr_text-score",
3492
3687
  describe: "Numeric full-text relevance score (usable in SELECT / ORDER BY)."
@@ -3497,21 +3692,21 @@ function filtersSchema(types, depth, cache) {
3497
3692
  keyName: "source",
3498
3693
  fieldMode: "list",
3499
3694
  eligible: allowingExpr(allFields, "filters"),
3500
- extras: { kind: z16.literal("filters") },
3695
+ extras: { kind: z17.literal("filters") },
3501
3696
  aid: "Expr_filters",
3502
3697
  describe: "A structured filter placeholder; clauses are supplied at execution time."
3503
3698
  }, cache);
3504
3699
  }
3505
3700
  function sorterSchema(childExpr) {
3506
- const entry = z16.object({
3507
- sort: z16.string().describe("A declared sort name (a key of `sorts`)."),
3701
+ const entry = z17.object({
3702
+ sort: z17.string().describe("A declared sort name (a key of `sorts`)."),
3508
3703
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir")
3509
3704
  });
3510
3705
  return withAid(
3511
- z16.object({
3512
- kind: z16.literal("sorter"),
3513
- sorts: z16.record(z16.string(), childExpr).describe("Named sortable expressions (sort name \u2192 expr); the caller selects by name at run time."),
3514
- defaultSort: z16.array(entry).optional().describe("Default multi-key sort (each `{ sort, dir }`) applied when the caller selects none.")
3706
+ z17.object({
3707
+ kind: z17.literal("sorter"),
3708
+ sorts: z17.record(z17.string(), childExpr).describe("Named sortable expressions (sort name \u2192 expr); the caller selects by name at run time."),
3709
+ defaultSort: z17.array(entry).optional().describe("Default multi-key sort (each `{ sort, dir }`) applied when the caller selects none.")
3515
3710
  }),
3516
3711
  "Expr_sorter"
3517
3712
  ).describe("A dynamic-sort catalog (valid only in a SELECT `order`); the selection is supplied at execution time.");
@@ -3531,7 +3726,7 @@ function insertRowSchema(type, fbOf, writes, Expr9) {
3531
3726
  const required = writes === "typed" && requiredOnInsert(f, fb);
3532
3727
  shape[f.name] = required ? value2 : value2.optional();
3533
3728
  }
3534
- return z16.strictObject(shape).describe(`A row to insert into ${type.name} (field \u2192 value).`);
3729
+ return z17.strictObject(shape).describe(`A row to insert into ${type.name} (field \u2192 value).`);
3535
3730
  }
3536
3731
  function updateSetSchema(type, fbOf, writes, Expr9) {
3537
3732
  const shape = {};
@@ -3540,7 +3735,7 @@ function updateSetSchema(type, fbOf, writes, Expr9) {
3540
3735
  if (!f.updatableFor(fb)) continue;
3541
3736
  shape[f.name] = writeValueSchema(f, writes, Expr9).optional();
3542
3737
  }
3543
- return z16.strictObject(shape).describe(`Fields to set on ${type.name} (field \u2192 value).`);
3738
+ return z17.strictObject(shape).describe(`Fields to set on ${type.name} (field \u2192 value).`);
3544
3739
  }
3545
3740
  function pickByNames(available, sel) {
3546
3741
  if (sel === "none") return [];
@@ -3603,11 +3798,11 @@ function shapeForKind(kind) {
3603
3798
  }
3604
3799
  }
3605
3800
  function windowOrderSchema(child) {
3606
- return z16.array(
3607
- z16.object({
3801
+ return z17.array(
3802
+ z17.object({
3608
3803
  expr: child,
3609
- dir: z16.enum(["asc", "desc"]),
3610
- nulls: z16.enum(["first", "last"]).optional()
3804
+ dir: z17.enum(["asc", "desc"]),
3805
+ nulls: z17.enum(["first", "last"]).optional()
3611
3806
  })
3612
3807
  );
3613
3808
  }
@@ -3615,31 +3810,31 @@ function functionObject(kind, functionField, argsField, child) {
3615
3810
  switch (kind) {
3616
3811
  case "function-call":
3617
3812
  return withAid(
3618
- z16.object({ kind: z16.literal("function-call"), function: functionField, args: argsField }),
3813
+ z17.object({ kind: z17.literal("function-call"), function: functionField, args: argsField }),
3619
3814
  "Expr_function-call"
3620
3815
  ).describe("A scalar function call with named arguments.");
3621
3816
  case "tabular-function-call":
3622
3817
  return withAid(
3623
- z16.object({ kind: z16.literal("tabular-function-call"), function: functionField, args: argsField }),
3818
+ z17.object({ kind: z17.literal("tabular-function-call"), function: functionField, args: argsField }),
3624
3819
  "Expr_tabular-function-call"
3625
3820
  ).describe("A type-valued function call (produces rows).");
3626
3821
  case "aggregate":
3627
3822
  return withAid(
3628
- z16.object({
3629
- kind: z16.literal("aggregate"),
3823
+ z17.object({
3824
+ kind: z17.literal("aggregate"),
3630
3825
  function: functionField,
3631
3826
  args: argsField,
3632
- distinct: z16.boolean().optional()
3827
+ distinct: z17.boolean().optional()
3633
3828
  }),
3634
3829
  "Expr_aggregate"
3635
3830
  ).describe("Aggregate function over named args (count with empty args = count(*)).");
3636
3831
  case "window":
3637
3832
  return withAid(
3638
- z16.object({
3639
- kind: z16.literal("window"),
3833
+ z17.object({
3834
+ kind: z17.literal("window"),
3640
3835
  function: functionField,
3641
3836
  args: argsField,
3642
- partitionBy: z16.array(child).optional(),
3837
+ partitionBy: z17.array(child).optional(),
3643
3838
  orderBy: windowOrderSchema(child).optional()
3644
3839
  }),
3645
3840
  "Expr_window"
@@ -3655,7 +3850,7 @@ function typedArgsSchema(fn2, child, cache) {
3655
3850
  for (const param3 of fn2.params) {
3656
3851
  shape[param3.name] = param3.optional ? child.optional() : child;
3657
3852
  }
3658
- return z16.strictObject(shape).describe(`Named arguments for \`${fn2.name}\`.`);
3853
+ return z17.strictObject(shape).describe(`Named arguments for \`${fn2.name}\`.`);
3659
3854
  }
3660
3855
  function functionExprSchema(kind, openSchema, selected, depth, child, cache) {
3661
3856
  if (depth === "open" || !selected) return openSchema;
@@ -3664,7 +3859,7 @@ function functionExprSchema(kind, openSchema, selected, depth, child, cache) {
3664
3859
  const functionField = withAid(enumOf2(fns.map((f) => f.name)), "FunctionName").describe(
3665
3860
  "A selected function name."
3666
3861
  );
3667
- const argsField = withAid(z16.record(z16.string(), child), "FunctionArgs").describe(
3862
+ const argsField = withAid(z17.record(z17.string(), child), "FunctionArgs").describe(
3668
3863
  "Arguments keyed by declared parameter name."
3669
3864
  );
3670
3865
  return functionObject(kind, functionField, argsField, child);
@@ -3674,12 +3869,12 @@ function functionExprSchema(kind, openSchema, selected, depth, child, cache) {
3674
3869
  const argsObj = typedArgsSchema(fn2, child, cache);
3675
3870
  return functionObject(
3676
3871
  kind,
3677
- z16.literal(fn2.name).describe(`The \`${fn2.name}\` function.`),
3872
+ z17.literal(fn2.name).describe(`The \`${fn2.name}\` function.`),
3678
3873
  hasRequired ? argsObj : argsObj.optional(),
3679
3874
  child
3680
3875
  );
3681
3876
  });
3682
- return branches.length > 0 ? orFold(branches) : z16.never();
3877
+ return branches.length > 0 ? orFold(branches) : z17.never();
3683
3878
  }
3684
3879
  function exprKindApplicable(kind, types, selected) {
3685
3880
  switch (kind) {
@@ -3721,336 +3916,44 @@ function assertNeverFieldMode(value2) {
3721
3916
  throw new Error(`schema-build: unhandled ref field mode ${JSON.stringify(value2)}`);
3722
3917
  }
3723
3918
 
3724
- // src/queries/order.ts
3725
- var QueryOrder = class _QueryOrder {
3726
- /** Construct an ORDER BY term from its expr, direction, and optional nulls placement. */
3727
- constructor(expr, dir, nulls) {
3728
- this.expr = expr;
3729
- this.dir = dir;
3730
- this.nulls = nulls;
3731
- }
3732
- expr;
3733
- dir;
3734
- nulls;
3735
- /** Build a `QueryOrder` from its authored `OrderDef`. */
3736
- static from(def, registry) {
3737
- return new _QueryOrder(registry.parseExpr(def.expr), def.dir, def.nulls);
3738
- }
3739
- /**
3740
- * Owned structural {@link Shape} for an `OrderDef` (`{ expr, dir, nulls? }`) —
3741
- * the zod-free parallel to {@link from}. Never throws; accumulates. See
3742
- * `shape/`.
3743
- */
3744
- static SHAPE = obj(
3745
- {
3746
- expr: exprRef(),
3747
- dir: enumOf(["asc", "desc"], "OrderDir"),
3748
- nulls: enumOf(["first", "last"], "OrderNulls")
3749
- },
3750
- (v) => new _QueryOrder(v.expr, v.dir, v.nulls),
3751
- { optional: ["nulls"], aid: "Order" }
3752
- );
3753
- /**
3754
- * The per-row cost of this ORDER BY term — just its sort expression's cost.
3755
- * Mirrors {@link SorterExpr.cost} so a SELECT can cost every `order` entry
3756
- * uniformly (concrete term or dynamic sorter) without a type check.
3757
- */
3758
- cost(ctx, scope) {
3759
- return this.expr.cost(ctx, scope);
3760
- }
3761
- /** The exprs this term reads for `references` — a concrete term is just its own expr. */
3762
- referenceExprs(_spec) {
3763
- return [this.expr];
3764
- }
3765
- /** Serialize back to an `OrderDef`, omitting `nulls` when unset. */
3766
- toJSON() {
3767
- const def = { expr: this.expr.toJSON(), dir: this.dir };
3768
- if (this.nulls) def.nulls = this.nulls;
3769
- return def;
3770
- }
3771
- /** Deep-clone this term (cloning its expr). */
3772
- clone() {
3773
- return new _QueryOrder(this.expr.clone(), this.dir, this.nulls);
3774
- }
3775
- };
3776
- function sortByKeys(entries, terms) {
3777
- const decorated = [...entries];
3778
- decorated.sort((a, b) => {
3779
- for (let i = 0; i < terms.length; i++) {
3780
- const cmp = compareWithNulls(a.keys[i], b.keys[i], terms[i]);
3781
- if (cmp !== 0) return cmp;
3782
- }
3783
- return 0;
3784
- });
3785
- return decorated.map((d) => d.item);
3786
- }
3787
- async function sortEntries(entries, terms, ctx) {
3788
- const decorated = await Promise.all(
3789
- entries.map(async (e2) => {
3790
- const keys = [];
3791
- for (const t of terms) keys.push(await t.expr.evaluate(ctx, e2.row, e2.group));
3792
- return { item: e2.item, keys };
3793
- })
3794
- );
3795
- return sortByKeys(decorated, terms);
3796
- }
3797
- function compareWithNulls(a, b, term) {
3798
- const aNull = a.isNull();
3799
- const bNull = b.isNull();
3800
- if (aNull || bNull) {
3801
- if (aNull && bNull) return 0;
3802
- const nullsFirst = term.nulls ? term.nulls === "first" : term.dir === "asc";
3803
- const nullIsA = aNull ? -1 : 1;
3804
- return nullsFirst ? nullIsA : -nullIsA;
3805
- }
3806
- const cmp = a.compareTo(b);
3807
- return term.dir === "desc" ? -cmp : cmp;
3808
- }
3809
-
3810
- // src/exprs/sorter.ts
3811
- var sortEntryShape = obj(
3812
- {
3813
- sort: str("SortName"),
3814
- dir: enumOf(["asc", "desc"], "OrderDir")
3815
- },
3816
- (v) => ({ sort: v.sort, dir: v.dir }),
3817
- { aid: "SortEntry" }
3818
- );
3819
- var SorterExpr = class _SorterExpr extends Expr {
3820
- /** Wrap the catalog (`sorts`) and its optional multi-key `defaultSort`. */
3821
- constructor(sorts, defaultSort) {
3919
+ // src/exprs/field-ref.ts
3920
+ var FieldRefExpr = class _FieldRefExpr extends Expr {
3921
+ /** Wrap a `<source>.<field>` reference by its source alias and field name. */
3922
+ constructor(source, field) {
3822
3923
  super();
3823
- this.sorts = sorts;
3824
- this.defaultSort = defaultSort;
3924
+ this.source = source;
3925
+ this.field = field;
3825
3926
  }
3826
- sorts;
3827
- defaultSort;
3828
- static KIND = "sorter";
3927
+ source;
3928
+ field;
3929
+ static KIND = "field-ref";
3829
3930
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3830
- static INSTRUCTIONS = "A dynamic-sort catalog for a SELECT `order`: declare named `sorts` (+ optional `defaultSort`); the caller picks the sort at execution time.";
3831
- kind = _SorterExpr.KIND;
3832
- /** Reconstruct a SorterExpr from its JSON def (validates the `kind` discriminant). */
3833
- static from(json, registry) {
3834
- if (json.kind !== "sorter") {
3835
- throw new Error(`SorterExpr.from: expected 'sorter', got '${json.kind}'`);
3836
- }
3837
- const sorts = /* @__PURE__ */ new Map();
3838
- for (const name of Object.keys(json.sorts)) {
3839
- sorts.set(name, registry.parseExpr(json.sorts[name]));
3931
+ static INSTRUCTIONS = "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a RELATION field resolves to the whole related row, NOT a scalar: to READ a related scalar, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. To CORRELATE a subquery, join the relation and compare the joined key \u2014 do NOT compare a relation field-ref to an id/scalar. A relation field-ref may only be compared to ANOTHER relation of the same target.";
3932
+ kind = _FieldRefExpr.KIND;
3933
+ /** Reconstruct a FieldRefExpr from its JSON def (validates the `kind` discriminant). */
3934
+ static from(json, _registry) {
3935
+ if (json.kind !== "field-ref") {
3936
+ throw new Error(`FieldRefExpr.from: expected 'field-ref', got '${json.kind}'`);
3840
3937
  }
3841
- const defaultSort = json.defaultSort ? json.defaultSort.map((d) => ({ ...d })) : void 0;
3842
- return new _SorterExpr(sorts, defaultSort);
3938
+ return new _FieldRefExpr(json.source, json.field);
3843
3939
  }
3844
3940
  /**
3845
3941
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
3846
- * `SorterExpr` equal to `from`'s output on a valid def (`{ sorts, defaultSort? }`);
3847
- * accumulates on a bad def (never throws). The SELECTION is supplied at
3848
- * execution time — never authored here. See `shape/`.
3942
+ * `FieldRefExpr` equal to `from`'s output on a valid def; accumulates
3943
+ * problems on a bad def (never throws). See `shape/`.
3849
3944
  */
3850
3945
  static SHAPE = obj(
3851
3946
  {
3852
- kind: lit("sorter"),
3853
- sorts: record(exprRef(), "Sorts"),
3854
- defaultSort: list(sortEntryShape)
3947
+ kind: lit("field-ref"),
3948
+ source: str("Source"),
3949
+ field: str("FieldName")
3855
3950
  },
3856
- (v) => new _SorterExpr(v.sorts, v.defaultSort),
3857
- { optional: ["defaultSort"], aid: "Expr_sorter" }
3951
+ (v) => new _FieldRefExpr(v.source, v.field),
3952
+ { aid: "Expr_field-ref" }
3858
3953
  );
3859
- /** Zod schema for this expr kind's JSON shape (its `sorts` values are child exprs). */
3954
+ /** Depth-aware Zod schema for this expr kind's JSON shape (per `opts.depth.refs`). */
3860
3955
  static toSchema(opts) {
3861
- return sorterSchema(childExprSchema(opts.Expr));
3862
- }
3863
- // ─── Resolution / validation ─────────────────────────────────────────────
3864
- /**
3865
- * A sorter is never a VALUE, so this is only reached when one is (invalidly)
3866
- * nested in a value position — already rejected by {@link validateWalk}. It
3867
- * resolves to a nullable text placeholder so a surrounding resolve never throws.
3868
- */
3869
- resolve(_engine, _scope) {
3870
- return textResult([], true);
3871
- }
3872
- /**
3873
- * A sorter reached as a general expression is MISPLACED — it is valid only in a
3874
- * select's `order` list (where the SELECT validates it via {@link validateInOrder}).
3875
- * Anywhere else (WHERE, a select field, a function arg, a `sorts` value, …) is
3876
- * a `sorter.misplaced` error.
3877
- */
3878
- validateWalk(_engine, _scope, p, _ctx) {
3879
- p.error("sorter.misplaced", "A `sorter` is only valid inside a SELECT's `order` list; it cannot be used here.");
3880
- return textResult([], true);
3881
- }
3882
- /**
3883
- * Validate a WELL-PLACED sorter (called by the SELECT for each `order` sorter):
3884
- * - `sorts` must be NON-EMPTY (`sorter.empty`);
3885
- * - each `sorts` value is validated EXACTLY like an order-by term's expr —
3886
- * against the SELECT's order scope + the same `ValidateContext` — so an
3887
- * `output` ref resolves and any non-orderable / relation-as-value expr is
3888
- * rejected there;
3889
- * - each `defaultSort[*].sort` must name a declared sort (`sorter.unknown-default`).
3890
- * The SQL-92 GROUP BY rule is applied to the `sorts` exprs by the SELECT itself
3891
- * (it owns the group-key set), mirroring how it treats an ordinary order term.
3892
- */
3893
- validateInOrder(engine, scope, p, ctx) {
3894
- if (this.sorts.size === 0) {
3895
- p.error("sorter.empty", "A `sorter` must declare at least one entry in `sorts`.");
3896
- }
3897
- p.at("sorts", () => {
3898
- for (const [name, expr] of this.sorts) {
3899
- p.at(name, () => expr.validateWalk(engine, scope, p, ctx));
3900
- }
3901
- });
3902
- if (this.defaultSort) {
3903
- p.at("defaultSort", () => {
3904
- this.defaultSort.forEach((d, i) => {
3905
- if (!this.sorts.has(d.sort)) {
3906
- p.at(
3907
- [i, "sort"],
3908
- () => p.error(
3909
- "sorter.unknown-default",
3910
- `defaultSort references '${d.sort}', which is not a declared sort.${didYouMean(d.sort, [...this.sorts.keys()])}`
3911
- )
3912
- );
3913
- }
3914
- });
3915
- });
3916
- }
3917
- }
3918
- // ─── Expansion (the order-by consumer's entry point) ──────────────────────
3919
- /**
3920
- * Expand this sorter against the runtime sort `spec` into concrete
3921
- * {@link QueryOrder} terms. A non-empty `spec` drives the terms (each `dir`
3922
- * defaults to `'asc'`); an empty / absent `spec` falls back to `defaultSort`;
3923
- * neither yields no terms. A selected `sort` name absent from `sorts` throws a
3924
- * loud `sort.unknown-name` runtime error (never silently dropped).
3925
- */
3926
- expand(spec) {
3927
- const chosen = spec && spec.length > 0 ? spec.map((s) => ({ sort: s.sort, dir: s.dir ?? "asc" })) : this.defaultSort ?? [];
3928
- return chosen.map(({ sort, dir }) => {
3929
- const expr = this.sorts.get(sort);
3930
- if (!expr) {
3931
- throw new Error(
3932
- `sort.unknown-name: unknown sort '${sort}'. Declared sorts: ${[...this.sorts.keys()].join(", ")}.`
3933
- );
3934
- }
3935
- return new QueryOrder(expr, dir, void 0);
3936
- });
3937
- }
3938
- // ─── Evaluation / cost / SQL (never reached for a well-placed sorter) ──────
3939
- //
3940
- // A sorter is NOT a value — it never evaluates / emits ITSELF. The real runtime
3941
- // + SQL sorting lives in `SelectQuery`: it calls `SorterExpr.expand(spec)` (via
3942
- // `SelectQuery.expandOrder(ctx.sortSpec)` — see select.ts, the ORDER BY phase of
3943
- // both `run` and `toSQL`) to turn the execution-time sort spec into concrete
3944
- // `QueryOrder[]`, then runs those through the SAME order-by comparator /
3945
- // ORDER BY emission an explicit `order` uses. The methods below are reachable
3946
- // ONLY for a MISPLACED sorter, which `validateWalk` has already rejected
3947
- // (`sorter.misplaced`); they just degrade harmlessly.
3948
- /** Dead path (see the note above): a well-placed sorter is expanded by `SelectQuery`; a misplaced one is rejected by validation — so this only NULLs defensively. */
3949
- async evaluate(_ctx, _row, _group) {
3950
- return Value.null();
3951
- }
3952
- /**
3953
- * A sorter's cost is the cost of the catalog entries it could sort BY: the
3954
- * caller's runtime selection ({@link CostContext.sort}) when supplied, else its
3955
- * `defaultSort`, else — as a worst case — its WHOLE catalog (any entry could be
3956
- * chosen at execution time). Each contributes its expr's own cost, so a sort
3957
- * key that is a SUBQUERY makes the sorter expensive (evaluated per sorted row
3958
- * by the SELECT), while sorting by a plain column stays cheap.
3959
- */
3960
- cost(ctx, scope) {
3961
- let c = ZERO_COST;
3962
- for (const expr of this.chosenSortExprs(ctx)) c = addCost(c, expr.cost(ctx, scope));
3963
- return c;
3964
- }
3965
- /**
3966
- * The catalog exprs a cost estimate should charge for: the caller's selected
3967
- * sorts (when a runtime `sort` is supplied), else the `defaultSort`'s sorts,
3968
- * else every catalog entry (worst case). Selected names absent from the catalog
3969
- * are skipped (they cost nothing here; a real run reports them loudly).
3970
- */
3971
- chosenSortExprs(ctx) {
3972
- return this.referenceExprs(ctx.sort);
3973
- }
3974
- /**
3975
- * The catalog exprs a caller's `sort` selection reads (for cost / references):
3976
- * the selected sorts when a `spec` is supplied, else the `defaultSort`'s sorts,
3977
- * else every catalog entry (worst case). Selected names absent from the catalog
3978
- * are skipped.
3979
- */
3980
- referenceExprs(spec) {
3981
- const pick = (entries) => entries.map((s) => this.sorts.get(s.sort)).filter((e2) => e2 !== void 0);
3982
- if (spec && spec.length > 0) return pick(spec);
3983
- if (this.defaultSort && this.defaultSort.length > 0) return pick(this.defaultSort);
3984
- return [...this.sorts.values()];
3985
- }
3986
- /** Dead path (see the note above): the ORDER BY SQL is emitted by `SelectQuery` from the expanded terms; a misplaced sorter is rejected by validation — so this only NULLs defensively. */
3987
- toSQL(_dialect, _ctx) {
3988
- return SqlText.raw("NULL");
3989
- }
3990
- // ─── Traversal ─────────────────────────────────────────────────────────────
3991
- /** Visit each catalog (`sorts`) value expr. */
3992
- forEachChild(visit) {
3993
- for (const expr of this.sorts.values()) visit(expr);
3994
- }
3995
- // ─── Serialization ─────────────────────────────────────────────────────────
3996
- /** Serialize back to its JSON ExprDef. */
3997
- toJSON() {
3998
- const sorts = {};
3999
- for (const [name, expr] of this.sorts) sorts[name] = expr.toJSON();
4000
- const def = { kind: "sorter", sorts };
4001
- if (this.defaultSort) def.defaultSort = this.defaultSort.map((d) => ({ ...d }));
4002
- return def;
4003
- }
4004
- /** Deep-copy this expr (cloning each catalog expr). */
4005
- clone() {
4006
- const sorts = /* @__PURE__ */ new Map();
4007
- for (const [name, expr] of this.sorts) sorts.set(name, expr.clone());
4008
- return new _SorterExpr(sorts, this.defaultSort ? this.defaultSort.map((d) => ({ ...d })) : void 0);
4009
- }
4010
- /** Render as the readable `sorter(name1, name2, …)` DSL form. */
4011
- toCode() {
4012
- return `sorter(${[...this.sorts.keys()].join(", ")})`;
4013
- }
4014
- };
4015
-
4016
- // src/exprs/field-ref.ts
4017
- var FieldRefExpr = class _FieldRefExpr extends Expr {
4018
- /** Wrap a `<source>.<field>` reference by its source alias and field name. */
4019
- constructor(source, field) {
4020
- super();
4021
- this.source = source;
4022
- this.field = field;
4023
- }
4024
- source;
4025
- field;
4026
- static KIND = "field-ref";
4027
- /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4028
- static INSTRUCTIONS = "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a RELATION field resolves to the whole related row, NOT a scalar: to READ a related scalar, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. To CORRELATE a subquery, join the relation and compare the joined key \u2014 do NOT compare a relation field-ref to an id/scalar. A relation field-ref may only be compared to ANOTHER relation of the same target.";
4029
- kind = _FieldRefExpr.KIND;
4030
- /** Reconstruct a FieldRefExpr from its JSON def (validates the `kind` discriminant). */
4031
- static from(json, _registry) {
4032
- if (json.kind !== "field-ref") {
4033
- throw new Error(`FieldRefExpr.from: expected 'field-ref', got '${json.kind}'`);
4034
- }
4035
- return new _FieldRefExpr(json.source, json.field);
4036
- }
4037
- /**
4038
- * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
4039
- * `FieldRefExpr` equal to `from`'s output on a valid def; accumulates
4040
- * problems on a bad def (never throws). See `shape/`.
4041
- */
4042
- static SHAPE = obj(
4043
- {
4044
- kind: lit("field-ref"),
4045
- source: str("Source"),
4046
- field: str("FieldName")
4047
- },
4048
- (v) => new _FieldRefExpr(v.source, v.field),
4049
- { aid: "Expr_field-ref" }
4050
- );
4051
- /** Depth-aware Zod schema for this expr kind's JSON shape (per `opts.depth.refs`). */
4052
- static toSchema(opts) {
4053
- return fieldRefSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
3956
+ return fieldRefSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
4054
3957
  }
4055
3958
  /** Resolve to the named field on the bound source, widening nullability by the source's. */
4056
3959
  resolve(engine, scope) {
@@ -4094,7 +3997,7 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4094
3997
  if (tf && !(tf.fieldType instanceof RelationFieldType)) {
4095
3998
  keyType = tf.fieldType;
4096
3999
  } else {
4097
- keyType = (ft.count === 1 ? target : ownerType).identityField().fieldType;
4000
+ keyType = (ft.isBelongsTo() ? target : ownerType).identityField().fieldType;
4098
4001
  }
4099
4002
  return { local: kp.local, foreign: kp.foreign, keyType };
4100
4003
  });
@@ -4105,6 +4008,7 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4105
4008
  keyType: keys[0].keyType,
4106
4009
  to: ft.to,
4107
4010
  count: ft.count,
4011
+ belongsTo: ft.isBelongsTo(),
4108
4012
  keys
4109
4013
  };
4110
4014
  const resolved = {
@@ -4144,10 +4048,8 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4144
4048
  checkFieldExpr(ctx.fieldExprKind ?? "field-ref", field, this.source, p);
4145
4049
  if (field.fieldType instanceof RelationFieldType) {
4146
4050
  const resolved2 = this.resolveRelation(engine, bound.type, field.fieldType, p);
4147
- if (!ctx.relationValueOk) {
4148
- const rel = relationOf(resolved2);
4149
- if (rel) p.error("ref.relation-not-value", relationAsValueMessage(rel));
4150
- }
4051
+ const rel = relationOf(resolved2);
4052
+ if (rel) this.checkRelationUse(rel, p, ctx);
4151
4053
  return resolved2;
4152
4054
  }
4153
4055
  const resolved = {
@@ -4159,6 +4061,29 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4159
4061
  };
4160
4062
  return resolved;
4161
4063
  }
4064
+ /**
4065
+ * Report the relation-as-value problem for this position, if any. Split into
4066
+ * three distinct outcomes because they have three different fixes:
4067
+ * - an identity-value position + a BELONGS-TO ⇒ fine, it has a local key;
4068
+ * - an identity-value position + a HAS-MANY ⇒ there is no key on this row at
4069
+ * all and its "value" is a set, so say that instead of the join-it hint;
4070
+ * - inside an AGGREGATE ⇒ an identity is not summable/averageable/max-able
4071
+ * under any representation, so say that;
4072
+ * - anywhere else ⇒ the long-standing "join it" hint.
4073
+ */
4074
+ checkRelationUse(rel, p, ctx) {
4075
+ if (ctx.relationUse === "compare") return;
4076
+ if (ctx.relationUse === "value") {
4077
+ if (rel.belongsTo) return;
4078
+ p.error("ref.relation-has-many", hasManyValueMessage(rel));
4079
+ return;
4080
+ }
4081
+ if (ctx.inAggregate) {
4082
+ p.error("ref.relation-aggregate", relationAggregateMessage(rel));
4083
+ return;
4084
+ }
4085
+ p.error("ref.relation-not-value", relationAsValueMessage(rel));
4086
+ }
4162
4087
  /** Zero rows; cost is just the resolved field's byte size. */
4163
4088
  cost(ctx, scope) {
4164
4089
  return { rows: 0, bytes: bytesOfResolved(this.resolve(ctx.engine, scope)) };
@@ -4169,6 +4094,24 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4169
4094
  }
4170
4095
  /** Read the field's runtime value, honoring backing (joins/compute/access security). */
4171
4096
  async evaluate(ctx, row) {
4097
+ if (!row) return Value.null();
4098
+ const identity = relationIdentityValue(this, ctx, row);
4099
+ if (identity) return this.securedRun(identity, ctx, row);
4100
+ return this.columnValue(ctx, row);
4101
+ }
4102
+ /**
4103
+ * Read this ref as a plain COLUMN, skipping the relation-identity projection.
4104
+ *
4105
+ * Needed because a belongs-to's local key column and the relation FIELD share
4106
+ * a name under the package's name convention (`order.userId` is both the
4107
+ * relation and the column holding its key). Every internal reader of a key
4108
+ * column — relation comparison lowering, ORDER BY / GROUP BY expansion, an
4109
+ * `IN` against a scalar subquery — wants the COLUMN; going through
4110
+ * {@link evaluate} would resolve the relation again and hand back the identity
4111
+ * object. Backing (compute / lateral / stored-name remap / access) still
4112
+ * applies exactly as it does for any other column.
4113
+ */
4114
+ async columnValue(ctx, row) {
4172
4115
  if (!row) return Value.null();
4173
4116
  const rec = row[this.source] ?? ctx.correlation?.[this.source];
4174
4117
  const type = ctx.sourceType(this.source) ?? ctx.engine.type(this.source);
@@ -4191,6 +4134,18 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4191
4134
  }
4192
4135
  return value2;
4193
4136
  }
4137
+ /**
4138
+ * Apply this field's `access` backing (FLS) to an already-computed value: a
4139
+ * denied field reads NULL. Shared by the relation-identity path, which
4140
+ * bypasses the stored/compute/lateral resolution but must not bypass security.
4141
+ */
4142
+ async securedRun(value2, ctx, row) {
4143
+ const type = ctx.sourceType(this.source) ?? ctx.engine.type(this.source);
4144
+ const access = type ? ctx.engine.fieldBacking(type.name, this.field)?.access : void 0;
4145
+ if (!access) return value2;
4146
+ const ar = await resolveAccessRun(access, this.source, row, ctx);
4147
+ return ar.kind === "visible" && !ar.visible ? Value.null() : value2;
4148
+ }
4194
4149
  /** Read a stored field off the bound record, attaching the conceptual field's metadata. */
4195
4150
  storedValue(rec, name, type) {
4196
4151
  if (!rec) return Value.null();
@@ -4281,6 +4236,20 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4281
4236
  }
4282
4237
  /** Emit as a SqlText column ref, lowering backing (joins/compute/access) when present. */
4283
4238
  toSQL(dialect, ctx) {
4239
+ const identity = relationIdentitySql(this, dialect, ctx);
4240
+ if (identity) {
4241
+ const rel = ctx.scope.lookup(this.source);
4242
+ const owner = rel && rel.kind === "type" ? rel.type.name : void 0;
4243
+ return this.securedSql(identity, dialect, ctx, owner);
4244
+ }
4245
+ return this.columnSQL(dialect, ctx);
4246
+ }
4247
+ /**
4248
+ * Emit this ref as a plain COLUMN, skipping the relation-identity projection —
4249
+ * the SQL twin of {@link columnValue}, and needed for the same reason (a
4250
+ * belongs-to's key column shares the relation field's name).
4251
+ */
4252
+ columnSQL(dialect, ctx) {
4284
4253
  const bound = ctx.scope.lookup(this.source);
4285
4254
  const typeName = bound && bound.kind === "type" ? bound.type.name : void 0;
4286
4255
  const fb = typeName === void 0 ? void 0 : ctx.engine.fieldBacking(typeName, this.field);
@@ -4314,6 +4283,31 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4314
4283
  return assertNeverAccess(acc);
4315
4284
  }
4316
4285
  }
4286
+ /**
4287
+ * Apply this field's `access` backing (FLS) to an already-emitted fragment —
4288
+ * the SQL twin of {@link securedRun}, so a relation identity is secured by the
4289
+ * same rule as any other column.
4290
+ */
4291
+ securedSql(value2, dialect, ctx, typeName) {
4292
+ const access = typeName === void 0 ? void 0 : ctx.engine.fieldBacking(typeName, this.field)?.access;
4293
+ if (!access) return value2;
4294
+ const acc = resolveAccessSql(access, this.source, ctx);
4295
+ switch (acc.kind) {
4296
+ case "noop":
4297
+ case "allow":
4298
+ return value2;
4299
+ case "deny":
4300
+ return SqlText.raw("NULL");
4301
+ case "predicate":
4302
+ return SqlText.join(
4303
+ [SqlText.raw("CASE WHEN"), acc.sql, SqlText.raw("THEN"), value2, SqlText.raw("ELSE NULL END")],
4304
+ " "
4305
+ );
4306
+ /* v8 ignore next 2 -- unreachable: AccessSql union is exhaustively handled above */
4307
+ default:
4308
+ return assertNeverAccess(acc);
4309
+ }
4310
+ }
4317
4311
  /**
4318
4312
  * Register every named join this field opts into with the planner (SQL),
4319
4313
  * deduped on the join's deterministic alias so N fields sharing a join emit
@@ -4408,7 +4402,7 @@ function assertNeverJoinSpec(value2) {
4408
4402
  }
4409
4403
 
4410
4404
  // src/exprs/param.ts
4411
- import { z as z17 } from "zod";
4405
+ import { z as z18 } from "zod";
4412
4406
  var ParamExpr = class _ParamExpr extends Expr {
4413
4407
  /** Wrap a named bind parameter (its type is inferred from usage). */
4414
4408
  constructor(name) {
@@ -4443,9 +4437,9 @@ var ParamExpr = class _ParamExpr extends Expr {
4443
4437
  /** Zod schema for this expr kind's JSON shape. */
4444
4438
  static toSchema(_opts) {
4445
4439
  return withAid(
4446
- z17.object({
4447
- kind: z17.literal("param"),
4448
- name: z17.string().describe("Parameter name; its type is inferred from usage.")
4440
+ z18.object({
4441
+ kind: z18.literal("param"),
4442
+ name: z18.string().describe("Parameter name; its type is inferred from usage.")
4449
4443
  }),
4450
4444
  "Expr_param"
4451
4445
  ).describe("A named bind parameter (contextually typed).");
@@ -4492,36 +4486,537 @@ var ParamExpr = class _ParamExpr extends Expr {
4492
4486
  }
4493
4487
  };
4494
4488
 
4495
- // src/exprs/binary.ts
4496
- import { z as z18 } from "zod";
4497
- var NUMERIC = /* @__PURE__ */ new Set(["number", "money"]);
4498
- var BINARY_OPS = ["+", "-", "*", "/", "%"];
4499
- function exempt(e2) {
4500
- return e2 instanceof LiteralExpr && e2.isNullLiteral() || e2 instanceof ParamExpr;
4489
+ // src/runtime/tri.ts
4490
+ function not3(a) {
4491
+ return a === void 0 ? void 0 : !a;
4501
4492
  }
4502
- var BinaryExpr = class _BinaryExpr extends Expr {
4503
- /** Wrap an arithmetic operation over its operator and left/right operand exprs. */
4504
- constructor(op, left, right) {
4505
- super();
4506
- this.op = op;
4507
- this.left = left;
4508
- this.right = right;
4509
- }
4510
- op;
4511
- left;
4512
- right;
4513
- static KIND = "binary";
4514
- /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4515
- static INSTRUCTIONS = "Arithmetic `left <op> right` (`+ - * / %`).";
4516
- kind = _BinaryExpr.KIND;
4517
- /** Reconstruct a BinaryExpr from its JSON def (validates the `kind` discriminant). */
4518
- static from(json, registry) {
4519
- if (json.kind !== "binary") {
4520
- throw new Error(`BinaryExpr.from: expected 'binary', got '${json.kind}'`);
4521
- }
4522
- return new _BinaryExpr(
4523
- json.op,
4524
- registry.parseExpr(json.left),
4493
+ function and3(a, b) {
4494
+ if (a === false || b === false) return false;
4495
+ if (a === void 0 || b === void 0) return void 0;
4496
+ return true;
4497
+ }
4498
+ function or3(a, b) {
4499
+ if (a === true || b === true) return true;
4500
+ if (a === void 0 || b === void 0) return void 0;
4501
+ return false;
4502
+ }
4503
+ function triOf(v) {
4504
+ return v.isNull() ? void 0 : v.toBoolean();
4505
+ }
4506
+
4507
+ // src/exprs/_relation-compare.ts
4508
+ var HAS_MANY_ALIAS = "__rel";
4509
+ function relationCompare(operand, engine, typeOf) {
4510
+ const ref3 = operand.fieldRef();
4511
+ if (!ref3) return void 0;
4512
+ const owner = typeOf(ref3.source);
4513
+ if (!owner) return void 0;
4514
+ const field = owner.field(ref3.field);
4515
+ if (!field || !(field.fieldType instanceof RelationFieldType)) return void 0;
4516
+ const ft = field.fieldType;
4517
+ const target = engine.type(ft.to);
4518
+ if (!target) return void 0;
4519
+ return {
4520
+ source: ref3.source,
4521
+ keys: ft.resolveKeys(engine, ref3.field, owner, target),
4522
+ belongsTo: ft.isBelongsTo(),
4523
+ target
4524
+ };
4525
+ }
4526
+ function runtimeTypeOf(ctx) {
4527
+ return (s) => ctx.sourceType(s) ?? ctx.engine.type(s);
4528
+ }
4529
+ function sqlTypeOf(ctx) {
4530
+ return (s) => {
4531
+ const b = ctx.scope.lookup(s);
4532
+ return b && b.kind === "type" ? b.type : void 0;
4533
+ };
4534
+ }
4535
+ function column(row, source, name, ctx) {
4536
+ const rec = row[source] ?? ctx.correlation?.[source];
4537
+ if (!rec) return Value.null();
4538
+ return cell(rec, name);
4539
+ }
4540
+ async function tuple(operand, rel, keys, row, ctx, group) {
4541
+ if (rel) return rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4542
+ const v = await operand.evaluate(ctx, row, group);
4543
+ if (v.isNull()) return keys.map(() => Value.null());
4544
+ const raw2 = v.raw;
4545
+ if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4546
+ const obj2 = raw2;
4547
+ return keys.map((k) => Value.of(obj2[k.foreign] ?? null));
4548
+ }
4549
+ return [v];
4550
+ }
4551
+ function eq3(a, b) {
4552
+ if (a.isNull() || b.isNull()) return void 0;
4553
+ return a.compareTo(b) === 0;
4554
+ }
4555
+ function cell(rec, name) {
4556
+ return Value.of(rec[name] ?? null);
4557
+ }
4558
+ async function evaluateRelationCompare(op, left, right, leftRel, rightRel, row, ctx, group) {
4559
+ const keys = (leftRel ?? rightRel).keys;
4560
+ const lt2 = await tuple(left, leftRel, keys, row, ctx, group);
4561
+ const rt = await tuple(right, rightRel, keys, row, ctx, group);
4562
+ let acc = true;
4563
+ for (let i = 0; i < keys.length; i++) acc = and3(acc, eq3(lt2[i], rt[i]));
4564
+ return op === "=" ? acc : not3(acc);
4565
+ }
4566
+ async function valueTuple(value2, pkFields, row, ctx, group) {
4567
+ const v = await value2.evaluate(ctx, row, group);
4568
+ if (v.isNull()) return pkFields.map(() => Value.null());
4569
+ const raw2 = v.raw;
4570
+ if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4571
+ const obj2 = raw2;
4572
+ return pkFields.map((f) => Value.of(obj2[f] ?? null));
4573
+ }
4574
+ return [v];
4575
+ }
4576
+ async function evaluateHasMany(op, rel, value2, row, ctx, group) {
4577
+ const pkFields = rel.target.primaryKey().map((f) => f.name);
4578
+ const outer = rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4579
+ const pkVals = await valueTuple(value2, pkFields, row, ctx, group);
4580
+ if (outer.some((v) => v.isNull()) || pkVals.some((v) => v.isNull())) return op !== "=";
4581
+ const rows = (await ctx.typeState(rel.target)).current;
4582
+ const found = rows.some(
4583
+ (tr) => rel.keys.every((k, i) => eq3(cell(tr, k.foreign), outer[i]) === true) && pkFields.every((f, i) => eq3(cell(tr, f), pkVals[i]) === true)
4584
+ );
4585
+ return op === "=" ? found : !found;
4586
+ }
4587
+ function tupleSql(operand, rel, keys, dialect, ctx) {
4588
+ if (rel) return rel.keys.map((k) => new FieldRefExpr(rel.source, k.local).columnSQL(dialect, ctx));
4589
+ if (operand instanceof ParamExpr) {
4590
+ const pv = ctx.params[operand.name];
4591
+ if (pv !== null && pv !== void 0 && typeof pv === "object") {
4592
+ const obj2 = pv;
4593
+ return keys.map((k) => SqlText.param(obj2[k.foreign] ?? null));
4594
+ }
4595
+ return [SqlText.param(pv ?? null)];
4596
+ }
4597
+ return [operand.toSQL(dialect, ctx)];
4598
+ }
4599
+ function emitRelationCompare(op, left, right, leftRel, rightRel, dialect, ctx) {
4600
+ const keys = (leftRel ?? rightRel).keys;
4601
+ const ls = tupleSql(left, leftRel, keys, dialect, ctx);
4602
+ const rs = tupleSql(right, rightRel, keys, dialect, ctx);
4603
+ const eqs = keys.map((_, i) => SqlText.join([ls[i], SqlText.raw("="), rs[i]], " "));
4604
+ const anded = SqlText.join(eqs, " AND ").parens();
4605
+ return op === "=" ? anded : SqlText.concat([SqlText.raw("NOT "), anded]);
4606
+ }
4607
+ function valueComponentsSql(value2, pkFields, ctx) {
4608
+ if (!(value2 instanceof ParamExpr)) return pkFields.map(() => null);
4609
+ const pv = ctx.params[value2.name];
4610
+ if (pv !== null && pv !== void 0 && typeof pv === "object") {
4611
+ const obj2 = pv;
4612
+ return pkFields.map((f) => obj2[f] ?? null);
4613
+ }
4614
+ return [pv ?? null];
4615
+ }
4616
+ function emitHasMany(op, rel, value2, dialect, ctx) {
4617
+ const pkFields = rel.target.primaryKey().map((f) => f.name);
4618
+ const comps = valueComponentsSql(value2, pkFields, ctx);
4619
+ const eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
4620
+ const col = (source, field) => ({ kind: "field-ref", source, field });
4621
+ const where = [
4622
+ // Correlation: each has-many key joins the target's FK-back column to this row's identity.
4623
+ ...rel.keys.map((k) => eq2(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
4624
+ // Membership: the target's PK equals the value's components.
4625
+ ...pkFields.map((pk, i) => eq2(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
4626
+ ];
4627
+ const def = {
4628
+ kind: "select",
4629
+ // Project the target's PK column (a bare ref, no bound param) — EXISTS
4630
+ // ignores the projected value, and `SELECT 1` would bind a stray literal.
4631
+ fields: [{ expr: col(HAS_MANY_ALIAS, pkFields[0]) }],
4632
+ from: { kind: "aliased", type: rel.target.name, as: HAS_MANY_ALIAS },
4633
+ where
4634
+ };
4635
+ const sub2 = emitSubquerySQL(dialect, ctx, def);
4636
+ return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub2]);
4637
+ }
4638
+
4639
+ // src/exprs/_relation-value.ts
4640
+ function relationIdentity(expr, engine, typeOf) {
4641
+ const rel = relationCompare(expr, engine, typeOf);
4642
+ return rel && rel.belongsTo ? rel : void 0;
4643
+ }
4644
+ function relationIdentityValue(expr, ctx, row) {
4645
+ const rel = relationIdentity(expr, ctx.engine, runtimeTypeOf(ctx));
4646
+ if (!rel) return void 0;
4647
+ const rec = row[rel.source] ?? ctx.correlation?.[rel.source];
4648
+ if (!rec) return Value.null();
4649
+ const out = {};
4650
+ for (const k of rel.keys) {
4651
+ const raw2 = rec[k.local] ?? null;
4652
+ if (raw2 === null) return Value.null();
4653
+ out[k.foreign] = raw2;
4654
+ }
4655
+ return Value.of(out);
4656
+ }
4657
+ function relationIdentitySql(expr, dialect, ctx) {
4658
+ const rel = relationIdentity(expr, ctx.engine, sqlTypeOf(ctx));
4659
+ if (!rel) return void 0;
4660
+ const object = dialect.jsonObject(rel.keys.map((k) => ({ key: k.foreign, value: dialect.field(rel.source, k.local) })));
4661
+ const anyNull = SqlText.join(
4662
+ rel.keys.map((k) => SqlText.concat([dialect.field(rel.source, k.local), SqlText.raw(" IS NULL")])),
4663
+ " OR "
4664
+ );
4665
+ return SqlText.join([SqlText.raw("CASE WHEN"), anyNull, SqlText.raw("THEN NULL ELSE"), object, SqlText.raw("END")], " ");
4666
+ }
4667
+ function relationKeyRefs(expr, engine, typeOf) {
4668
+ const rel = relationIdentity(expr, engine, typeOf);
4669
+ if (!rel) return void 0;
4670
+ return rel.keys.map((k) => new FieldRefExpr(rel.source, k.local));
4671
+ }
4672
+ function throughOutput(expr, resolve) {
4673
+ return expr instanceof OutputRefExpr ? resolve(expr.name) ?? expr : expr;
4674
+ }
4675
+ function relationKeySqls(expr, dialect, ctx) {
4676
+ const target = throughOutput(expr, (n) => ctx.scope.output(n));
4677
+ return relationKeyRefs(target, ctx.engine, sqlTypeOf(ctx))?.map((r) => r.columnSQL(dialect, ctx));
4678
+ }
4679
+ function relationKeyRefsRun(expr, ctx) {
4680
+ const target = throughOutput(expr, (n) => ctx.outputExpr(n));
4681
+ return relationKeyRefs(target, ctx.engine, runtimeTypeOf(ctx));
4682
+ }
4683
+
4684
+ // src/queries/order.ts
4685
+ var QueryOrder = class _QueryOrder {
4686
+ /** Construct an ORDER BY term from its expr, direction, and optional nulls placement. */
4687
+ constructor(expr, dir, nulls) {
4688
+ this.expr = expr;
4689
+ this.dir = dir;
4690
+ this.nulls = nulls;
4691
+ }
4692
+ expr;
4693
+ dir;
4694
+ nulls;
4695
+ /** Build a `QueryOrder` from its authored `OrderDef`. */
4696
+ static from(def, registry) {
4697
+ return new _QueryOrder(registry.parseExpr(def.expr), def.dir, def.nulls);
4698
+ }
4699
+ /**
4700
+ * Owned structural {@link Shape} for an `OrderDef` (`{ expr, dir, nulls? }`) —
4701
+ * the zod-free parallel to {@link from}. Never throws; accumulates. See
4702
+ * `shape/`.
4703
+ */
4704
+ static SHAPE = obj(
4705
+ {
4706
+ expr: exprRef(),
4707
+ dir: enumOf(["asc", "desc"], "OrderDir"),
4708
+ nulls: enumOf(["first", "last"], "OrderNulls")
4709
+ },
4710
+ (v) => new _QueryOrder(v.expr, v.dir, v.nulls),
4711
+ { optional: ["nulls"], aid: "Order" }
4712
+ );
4713
+ /**
4714
+ * The per-row cost of this ORDER BY term — just its sort expression's cost.
4715
+ * Mirrors {@link SorterExpr.cost} so a SELECT can cost every `order` entry
4716
+ * uniformly (concrete term or dynamic sorter) without a type check.
4717
+ */
4718
+ cost(ctx, scope) {
4719
+ return this.expr.cost(ctx, scope);
4720
+ }
4721
+ /** The exprs this term reads for `references` — a concrete term is just its own expr. */
4722
+ referenceExprs(_spec) {
4723
+ return [this.expr];
4724
+ }
4725
+ /** Serialize back to an `OrderDef`, omitting `nulls` when unset. */
4726
+ toJSON() {
4727
+ const def = { expr: this.expr.toJSON(), dir: this.dir };
4728
+ if (this.nulls) def.nulls = this.nulls;
4729
+ return def;
4730
+ }
4731
+ /** Deep-clone this term (cloning its expr). */
4732
+ clone() {
4733
+ return new _QueryOrder(this.expr.clone(), this.dir, this.nulls);
4734
+ }
4735
+ };
4736
+ function sortByKeys(entries, terms) {
4737
+ const decorated = [...entries];
4738
+ decorated.sort((a, b) => {
4739
+ for (let i = 0; i < terms.length; i++) {
4740
+ const cmp = compareWithNulls(a.keys[i], b.keys[i], terms[i]);
4741
+ if (cmp !== 0) return cmp;
4742
+ }
4743
+ return 0;
4744
+ });
4745
+ return decorated.map((d) => d.item);
4746
+ }
4747
+ function expandSortTerms(terms, ctx) {
4748
+ const out = [];
4749
+ for (const t of terms) {
4750
+ const keys = relationKeyRefsRun(t.expr, ctx);
4751
+ if (keys) {
4752
+ for (const k of keys) out.push({ read: (c, row) => k.columnValue(c, row), dir: t.dir, nulls: t.nulls });
4753
+ } else {
4754
+ const expr = t.expr;
4755
+ out.push({ read: (c, row, group) => expr.evaluate(c, row, group), dir: t.dir, nulls: t.nulls });
4756
+ }
4757
+ }
4758
+ return out;
4759
+ }
4760
+ async function sortEntries(entries, terms, ctx) {
4761
+ const expanded = expandSortTerms(terms, ctx);
4762
+ const decorated = await Promise.all(
4763
+ entries.map(async (e2) => {
4764
+ const keys = [];
4765
+ for (const t of expanded) keys.push(await t.read(ctx, e2.row, e2.group));
4766
+ return { item: e2.item, keys };
4767
+ })
4768
+ );
4769
+ return sortByKeys(decorated, expanded);
4770
+ }
4771
+ function compareWithNulls(a, b, term) {
4772
+ const aNull = a.isNull();
4773
+ const bNull = b.isNull();
4774
+ if (aNull || bNull) {
4775
+ if (aNull && bNull) return 0;
4776
+ const nullsFirst = term.nulls ? term.nulls === "first" : term.dir === "asc";
4777
+ const nullIsA = aNull ? -1 : 1;
4778
+ return nullsFirst ? nullIsA : -nullIsA;
4779
+ }
4780
+ const cmp = a.compareTo(b);
4781
+ return term.dir === "desc" ? -cmp : cmp;
4782
+ }
4783
+
4784
+ // src/exprs/sorter.ts
4785
+ var sortEntryShape = obj(
4786
+ {
4787
+ sort: str("SortName"),
4788
+ dir: enumOf(["asc", "desc"], "OrderDir")
4789
+ },
4790
+ (v) => ({ sort: v.sort, dir: v.dir }),
4791
+ { aid: "SortEntry" }
4792
+ );
4793
+ var SorterExpr = class _SorterExpr extends Expr {
4794
+ /** Wrap the catalog (`sorts`) and its optional multi-key `defaultSort`. */
4795
+ constructor(sorts, defaultSort) {
4796
+ super();
4797
+ this.sorts = sorts;
4798
+ this.defaultSort = defaultSort;
4799
+ }
4800
+ sorts;
4801
+ defaultSort;
4802
+ static KIND = "sorter";
4803
+ /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4804
+ static INSTRUCTIONS = "A dynamic-sort catalog for a SELECT `order`: declare named `sorts` (+ optional `defaultSort`); the caller picks the sort at execution time.";
4805
+ kind = _SorterExpr.KIND;
4806
+ /** Reconstruct a SorterExpr from its JSON def (validates the `kind` discriminant). */
4807
+ static from(json, registry) {
4808
+ if (json.kind !== "sorter") {
4809
+ throw new Error(`SorterExpr.from: expected 'sorter', got '${json.kind}'`);
4810
+ }
4811
+ const sorts = /* @__PURE__ */ new Map();
4812
+ for (const name of Object.keys(json.sorts)) {
4813
+ sorts.set(name, registry.parseExpr(json.sorts[name]));
4814
+ }
4815
+ const defaultSort = json.defaultSort ? json.defaultSort.map((d) => ({ ...d })) : void 0;
4816
+ return new _SorterExpr(sorts, defaultSort);
4817
+ }
4818
+ /**
4819
+ * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
4820
+ * `SorterExpr` equal to `from`'s output on a valid def (`{ sorts, defaultSort? }`);
4821
+ * accumulates on a bad def (never throws). The SELECTION is supplied at
4822
+ * execution time — never authored here. See `shape/`.
4823
+ */
4824
+ static SHAPE = obj(
4825
+ {
4826
+ kind: lit("sorter"),
4827
+ sorts: record(exprRef(), "Sorts"),
4828
+ defaultSort: list(sortEntryShape)
4829
+ },
4830
+ (v) => new _SorterExpr(v.sorts, v.defaultSort),
4831
+ { optional: ["defaultSort"], aid: "Expr_sorter" }
4832
+ );
4833
+ /** Zod schema for this expr kind's JSON shape (its `sorts` values are child exprs). */
4834
+ static toSchema(opts) {
4835
+ return sorterSchema(childExprSchema(opts.Expr));
4836
+ }
4837
+ // ─── Resolution / validation ─────────────────────────────────────────────
4838
+ /**
4839
+ * A sorter is never a VALUE, so this is only reached when one is (invalidly)
4840
+ * nested in a value position — already rejected by {@link validateWalk}. It
4841
+ * resolves to a nullable text placeholder so a surrounding resolve never throws.
4842
+ */
4843
+ resolve(_engine, _scope) {
4844
+ return textResult([], true);
4845
+ }
4846
+ /**
4847
+ * A sorter reached as a general expression is MISPLACED — it is valid only in a
4848
+ * select's `order` list (where the SELECT validates it via {@link validateInOrder}).
4849
+ * Anywhere else (WHERE, a select field, a function arg, a `sorts` value, …) is
4850
+ * a `sorter.misplaced` error.
4851
+ */
4852
+ validateWalk(_engine, _scope, p, _ctx) {
4853
+ p.error("sorter.misplaced", "A `sorter` is only valid inside a SELECT's `order` list; it cannot be used here.");
4854
+ return textResult([], true);
4855
+ }
4856
+ /**
4857
+ * Validate a WELL-PLACED sorter (called by the SELECT for each `order` sorter):
4858
+ * - `sorts` must be NON-EMPTY (`sorter.empty`);
4859
+ * - each `sorts` value is validated EXACTLY like an order-by term's expr —
4860
+ * against the SELECT's order scope + the same `ValidateContext` — so an
4861
+ * `output` ref resolves and any non-orderable / relation-as-value expr is
4862
+ * rejected there;
4863
+ * - each `defaultSort[*].sort` must name a declared sort (`sorter.unknown-default`).
4864
+ * The SQL-92 GROUP BY rule is applied to the `sorts` exprs by the SELECT itself
4865
+ * (it owns the group-key set), mirroring how it treats an ordinary order term.
4866
+ */
4867
+ validateInOrder(engine, scope, p, ctx) {
4868
+ if (this.sorts.size === 0) {
4869
+ p.error("sorter.empty", "A `sorter` must declare at least one entry in `sorts`.");
4870
+ }
4871
+ p.at("sorts", () => {
4872
+ for (const [name, expr] of this.sorts) {
4873
+ p.at(name, () => expr.validateWalk(engine, scope, p, ctx));
4874
+ }
4875
+ });
4876
+ if (this.defaultSort) {
4877
+ p.at("defaultSort", () => {
4878
+ this.defaultSort.forEach((d, i) => {
4879
+ if (!this.sorts.has(d.sort)) {
4880
+ p.at(
4881
+ [i, "sort"],
4882
+ () => p.error(
4883
+ "sorter.unknown-default",
4884
+ `defaultSort references '${d.sort}', which is not a declared sort.${didYouMean(d.sort, [...this.sorts.keys()])}`
4885
+ )
4886
+ );
4887
+ }
4888
+ });
4889
+ });
4890
+ }
4891
+ }
4892
+ // ─── Expansion (the order-by consumer's entry point) ──────────────────────
4893
+ /**
4894
+ * Expand this sorter against the runtime sort `spec` into concrete
4895
+ * {@link QueryOrder} terms. A non-empty `spec` drives the terms (each `dir`
4896
+ * defaults to `'asc'`); an empty / absent `spec` falls back to `defaultSort`;
4897
+ * neither yields no terms. A selected `sort` name absent from `sorts` throws a
4898
+ * loud `sort.unknown-name` runtime error (never silently dropped).
4899
+ */
4900
+ expand(spec) {
4901
+ const chosen = spec && spec.length > 0 ? spec.map((s) => ({ sort: s.sort, dir: s.dir ?? "asc" })) : this.defaultSort ?? [];
4902
+ return chosen.map(({ sort, dir }) => {
4903
+ const expr = this.sorts.get(sort);
4904
+ if (!expr) {
4905
+ throw new Error(
4906
+ `sort.unknown-name: unknown sort '${sort}'. Declared sorts: ${[...this.sorts.keys()].join(", ")}.`
4907
+ );
4908
+ }
4909
+ return new QueryOrder(expr, dir, void 0);
4910
+ });
4911
+ }
4912
+ // ─── Evaluation / cost / SQL (never reached for a well-placed sorter) ──────
4913
+ //
4914
+ // A sorter is NOT a value — it never evaluates / emits ITSELF. The real runtime
4915
+ // + SQL sorting lives in `SelectQuery`: it calls `SorterExpr.expand(spec)` (via
4916
+ // `SelectQuery.expandOrder(ctx.sortSpec)` — see select.ts, the ORDER BY phase of
4917
+ // both `run` and `toSQL`) to turn the execution-time sort spec into concrete
4918
+ // `QueryOrder[]`, then runs those through the SAME order-by comparator /
4919
+ // ORDER BY emission an explicit `order` uses. The methods below are reachable
4920
+ // ONLY for a MISPLACED sorter, which `validateWalk` has already rejected
4921
+ // (`sorter.misplaced`); they just degrade harmlessly.
4922
+ /** Dead path (see the note above): a well-placed sorter is expanded by `SelectQuery`; a misplaced one is rejected by validation — so this only NULLs defensively. */
4923
+ async evaluate(_ctx, _row, _group) {
4924
+ return Value.null();
4925
+ }
4926
+ /**
4927
+ * A sorter's cost is the cost of the catalog entries it could sort BY: the
4928
+ * caller's runtime selection ({@link CostContext.sort}) when supplied, else its
4929
+ * `defaultSort`, else — as a worst case — its WHOLE catalog (any entry could be
4930
+ * chosen at execution time). Each contributes its expr's own cost, so a sort
4931
+ * key that is a SUBQUERY makes the sorter expensive (evaluated per sorted row
4932
+ * by the SELECT), while sorting by a plain column stays cheap.
4933
+ */
4934
+ cost(ctx, scope) {
4935
+ let c = ZERO_COST;
4936
+ for (const expr of this.chosenSortExprs(ctx)) c = addCost(c, expr.cost(ctx, scope));
4937
+ return c;
4938
+ }
4939
+ /**
4940
+ * The catalog exprs a cost estimate should charge for: the caller's selected
4941
+ * sorts (when a runtime `sort` is supplied), else the `defaultSort`'s sorts,
4942
+ * else every catalog entry (worst case). Selected names absent from the catalog
4943
+ * are skipped (they cost nothing here; a real run reports them loudly).
4944
+ */
4945
+ chosenSortExprs(ctx) {
4946
+ return this.referenceExprs(ctx.sort);
4947
+ }
4948
+ /**
4949
+ * The catalog exprs a caller's `sort` selection reads (for cost / references):
4950
+ * the selected sorts when a `spec` is supplied, else the `defaultSort`'s sorts,
4951
+ * else every catalog entry (worst case). Selected names absent from the catalog
4952
+ * are skipped.
4953
+ */
4954
+ referenceExprs(spec) {
4955
+ const pick = (entries) => entries.map((s) => this.sorts.get(s.sort)).filter((e2) => e2 !== void 0);
4956
+ if (spec && spec.length > 0) return pick(spec);
4957
+ if (this.defaultSort && this.defaultSort.length > 0) return pick(this.defaultSort);
4958
+ return [...this.sorts.values()];
4959
+ }
4960
+ /** Dead path (see the note above): the ORDER BY SQL is emitted by `SelectQuery` from the expanded terms; a misplaced sorter is rejected by validation — so this only NULLs defensively. */
4961
+ toSQL(_dialect, _ctx) {
4962
+ return SqlText.raw("NULL");
4963
+ }
4964
+ // ─── Traversal ─────────────────────────────────────────────────────────────
4965
+ /** Visit each catalog (`sorts`) value expr. */
4966
+ forEachChild(visit) {
4967
+ for (const expr of this.sorts.values()) visit(expr);
4968
+ }
4969
+ // ─── Serialization ─────────────────────────────────────────────────────────
4970
+ /** Serialize back to its JSON ExprDef. */
4971
+ toJSON() {
4972
+ const sorts = {};
4973
+ for (const [name, expr] of this.sorts) sorts[name] = expr.toJSON();
4974
+ const def = { kind: "sorter", sorts };
4975
+ if (this.defaultSort) def.defaultSort = this.defaultSort.map((d) => ({ ...d }));
4976
+ return def;
4977
+ }
4978
+ /** Deep-copy this expr (cloning each catalog expr). */
4979
+ clone() {
4980
+ const sorts = /* @__PURE__ */ new Map();
4981
+ for (const [name, expr] of this.sorts) sorts.set(name, expr.clone());
4982
+ return new _SorterExpr(sorts, this.defaultSort ? this.defaultSort.map((d) => ({ ...d })) : void 0);
4983
+ }
4984
+ /** Render as the readable `sorter(name1, name2, …)` DSL form. */
4985
+ toCode() {
4986
+ return `sorter(${[...this.sorts.keys()].join(", ")})`;
4987
+ }
4988
+ };
4989
+
4990
+ // src/exprs/binary.ts
4991
+ import { z as z19 } from "zod";
4992
+ var NUMERIC = /* @__PURE__ */ new Set(["number", "money"]);
4993
+ var BINARY_OPS = ["+", "-", "*", "/", "%"];
4994
+ function exempt(e2) {
4995
+ return e2 instanceof LiteralExpr && e2.isNullLiteral() || e2 instanceof ParamExpr;
4996
+ }
4997
+ var BinaryExpr = class _BinaryExpr extends Expr {
4998
+ /** Wrap an arithmetic operation over its operator and left/right operand exprs. */
4999
+ constructor(op, left, right) {
5000
+ super();
5001
+ this.op = op;
5002
+ this.left = left;
5003
+ this.right = right;
5004
+ }
5005
+ op;
5006
+ left;
5007
+ right;
5008
+ static KIND = "binary";
5009
+ /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
5010
+ static INSTRUCTIONS = "Arithmetic `left <op> right` (`+ - * / %`).";
5011
+ kind = _BinaryExpr.KIND;
5012
+ /** Reconstruct a BinaryExpr from its JSON def (validates the `kind` discriminant). */
5013
+ static from(json, registry) {
5014
+ if (json.kind !== "binary") {
5015
+ throw new Error(`BinaryExpr.from: expected 'binary', got '${json.kind}'`);
5016
+ }
5017
+ return new _BinaryExpr(
5018
+ json.op,
5019
+ registry.parseExpr(json.left),
4525
5020
  registry.parseExpr(json.right)
4526
5021
  );
4527
5022
  }
@@ -4544,9 +5039,9 @@ var BinaryExpr = class _BinaryExpr extends Expr {
4544
5039
  static toSchema(opts) {
4545
5040
  const child = childExprSchema(opts.Expr);
4546
5041
  return withAid(
4547
- z18.object({
4548
- kind: z18.literal("binary"),
4549
- op: withAid(z18.enum(["+", "-", "*", "/", "%"]), "BinaryOp"),
5042
+ z19.object({
5043
+ kind: z19.literal("binary"),
5044
+ op: withAid(z19.enum(["+", "-", "*", "/", "%"]), "BinaryOp"),
4550
5045
  left: child,
4551
5046
  right: child
4552
5047
  }),
@@ -4575,7 +5070,7 @@ var BinaryExpr = class _BinaryExpr extends Expr {
4575
5070
  /** Validate both operands are numeric (text ok for `+`), infer param types, then resolve. */
4576
5071
  validateWalk(engine, scope, p, ctx) {
4577
5072
  const here = p.here;
4578
- const opCtx = { ...ctx, relationValueOk: true };
5073
+ const opCtx = { ...ctx, relationUse: "compare" };
4579
5074
  const l = p.at("left", () => this.left.validateWalk(engine, scope, p, opCtx));
4580
5075
  const r = p.at("right", () => this.right.validateWalk(engine, scope, p, opCtx));
4581
5076
  const checkNumeric = (operand, rt, key) => {
@@ -4667,7 +5162,7 @@ function assertNeverOp(op) {
4667
5162
  }
4668
5163
 
4669
5164
  // src/exprs/unary.ts
4670
- import { z as z19 } from "zod";
5165
+ import { z as z20 } from "zod";
4671
5166
  var UNARY_OPS = ["-", "+"];
4672
5167
  var UnaryExpr = class _UnaryExpr extends Expr {
4673
5168
  /** Wrap a unary operation over its operator and operand expr. */
@@ -4684,247 +5179,105 @@ var UnaryExpr = class _UnaryExpr extends Expr {
4684
5179
  kind = _UnaryExpr.KIND;
4685
5180
  /** Reconstruct a UnaryExpr from its JSON def (validates the `kind` discriminant). */
4686
5181
  static from(json, registry) {
4687
- if (json.kind !== "unary") {
4688
- throw new Error(`UnaryExpr.from: expected 'unary', got '${json.kind}'`);
4689
- }
4690
- return new _UnaryExpr(json.op, registry.parseExpr(json.operand));
4691
- }
4692
- /**
4693
- * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
4694
- * `UnaryExpr` equal to `from`'s output on a valid def; accumulates problems on
4695
- * a bad def (never throws). See `shape/`.
4696
- */
4697
- static SHAPE = obj(
4698
- {
4699
- kind: lit("unary"),
4700
- op: enumOf(UNARY_OPS, "UnaryOp"),
4701
- operand: exprRef()
4702
- },
4703
- (v) => new _UnaryExpr(v.op, v.operand),
4704
- { aid: "Expr_unary" }
4705
- );
4706
- /** Zod schema for this expr kind's JSON shape (operand uses the shared child Expr schema). */
4707
- static toSchema(opts) {
4708
- return withAid(
4709
- z19.object({
4710
- kind: z19.literal("unary"),
4711
- op: withAid(z19.enum(["-", "+"]), "UnaryOp"),
4712
- operand: childExprSchema(opts.Expr)
4713
- }),
4714
- "Expr_unary"
4715
- ).describe("Unary arithmetic operation.");
4716
- }
4717
- forEachChild(visit) {
4718
- visit(this.operand);
4719
- }
4720
- /** Resolve to numeric/money mirroring the operand's category, propagating nullability/aggregate. */
4721
- resolve(engine, scope) {
4722
- const o = this.operand.resolve(engine, scope);
4723
- const sources = gatherSources([o]);
4724
- const nullable = o.kind !== "type" && o.nullable;
4725
- const aggregate2 = o.kind === "computed" && o.aggregate;
4726
- const fieldType = categoryOf(o) === "money" ? new MoneyFieldType() : new NumberFieldType();
4727
- return computed(fieldType, sources, nullable, aggregate2);
4728
- }
4729
- /** Validate the operand is numeric (NULL/param exempt), infer param type, then resolve. */
4730
- validateWalk(engine, scope, p, ctx) {
4731
- const o = p.at("operand", () => this.operand.validateWalk(engine, scope, p, ctx));
4732
- const exempt3 = this.operand instanceof LiteralExpr && this.operand.isNullLiteral() || this.operand instanceof ParamExpr;
4733
- if (!exempt3) {
4734
- const cat = categoryOf(o);
4735
- if (cat !== "number" && cat !== "money") {
4736
- p.at("operand", () => {
4737
- p.error("unary.type", `Unary '${this.op}' requires a numeric operand; got ${cat ?? "a type"}.`);
4738
- });
4739
- }
4740
- }
4741
- if (this.operand instanceof ParamExpr) {
4742
- scope.params.observe(this.operand.name, new NumberFieldType(), [...p.here, "operand"]);
4743
- }
4744
- return this.resolve(engine, scope);
4745
- }
4746
- /** Cost is the operand's cost. */
4747
- cost(ctx, scope) {
4748
- return this.childCost(ctx, scope);
4749
- }
4750
- /** Evaluate the operand and apply the sign (NULL/non-numeric → NULL). */
4751
- async evaluate(ctx, row, group) {
4752
- const v = await this.operand.evaluate(ctx, row, group);
4753
- if (v.isNull()) return Value.null();
4754
- const n = v.toNumber();
4755
- if (Number.isNaN(n)) return Value.null();
4756
- return Value.of(this.op === "-" ? -n : n);
4757
- }
4758
- /** Emit as a parenthesized `(op operand)` SqlText fragment. */
4759
- toSQL(dialect, ctx) {
4760
- return SqlText.concat([SqlText.raw(`(${this.op}`), this.operand.toSQL(dialect, ctx), SqlText.raw(")")]);
4761
- }
4762
- /** Serialize back to its JSON ExprDef. */
4763
- toJSON() {
4764
- return { kind: "unary", op: this.op, operand: this.operand.toJSON() };
4765
- }
4766
- /** Deep-copy this expr and its operand. */
4767
- clone() {
4768
- return new _UnaryExpr(this.op, this.operand.clone());
4769
- }
4770
- /** Render as source-like code (`-operand` / `+operand`). */
4771
- toCode() {
4772
- return `${this.op}${this.operand.toCode()}`;
4773
- }
4774
- };
4775
-
4776
- // src/exprs/comparison.ts
4777
- import { z as z20 } from "zod";
4778
-
4779
- // src/runtime/tri.ts
4780
- function not3(a) {
4781
- return a === void 0 ? void 0 : !a;
4782
- }
4783
- function and3(a, b) {
4784
- if (a === false || b === false) return false;
4785
- if (a === void 0 || b === void 0) return void 0;
4786
- return true;
4787
- }
4788
- function or3(a, b) {
4789
- if (a === true || b === true) return true;
4790
- if (a === void 0 || b === void 0) return void 0;
4791
- return false;
4792
- }
4793
- function triOf(v) {
4794
- return v.isNull() ? void 0 : v.toBoolean();
4795
- }
4796
-
4797
- // src/exprs/_relation-compare.ts
4798
- var HAS_MANY_ALIAS = "__rel";
4799
- function relationCompare(operand, engine, typeOf) {
4800
- const ref3 = operand.fieldRef();
4801
- if (!ref3) return void 0;
4802
- const owner = typeOf(ref3.source);
4803
- if (!owner) return void 0;
4804
- const field = owner.field(ref3.field);
4805
- if (!field || !(field.fieldType instanceof RelationFieldType)) return void 0;
4806
- const ft = field.fieldType;
4807
- const target = engine.type(ft.to);
4808
- if (!target) return void 0;
4809
- return { source: ref3.source, keys: ft.resolveKeys(engine, ref3.field, owner, target), count: ft.count, target };
4810
- }
4811
- function runtimeTypeOf(ctx) {
4812
- return (s) => ctx.sourceType(s) ?? ctx.engine.type(s);
4813
- }
4814
- function sqlTypeOf(ctx) {
4815
- return (s) => {
4816
- const b = ctx.scope.lookup(s);
4817
- return b && b.kind === "type" ? b.type : void 0;
4818
- };
4819
- }
4820
- function column(row, source, name, ctx) {
4821
- const rec = row[source] ?? ctx.correlation?.[source];
4822
- if (!rec) return Value.null();
4823
- return cell(rec, name);
4824
- }
4825
- async function tuple(operand, rel, keys, row, ctx, group) {
4826
- if (rel) return rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4827
- const v = await operand.evaluate(ctx, row, group);
4828
- if (v.isNull()) return keys.map(() => Value.null());
4829
- const raw2 = v.raw;
4830
- if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4831
- const obj2 = raw2;
4832
- return keys.map((k) => Value.of(obj2[k.foreign] ?? null));
4833
- }
4834
- return [v];
4835
- }
4836
- function eq3(a, b) {
4837
- if (a.isNull() || b.isNull()) return void 0;
4838
- return a.compareTo(b) === 0;
4839
- }
4840
- function cell(rec, name) {
4841
- return Value.of(rec[name] ?? null);
4842
- }
4843
- async function evaluateRelationCompare(op, left, right, leftRel, rightRel, row, ctx, group) {
4844
- const keys = (leftRel ?? rightRel).keys;
4845
- const lt2 = await tuple(left, leftRel, keys, row, ctx, group);
4846
- const rt = await tuple(right, rightRel, keys, row, ctx, group);
4847
- let acc = true;
4848
- for (let i = 0; i < keys.length; i++) acc = and3(acc, eq3(lt2[i], rt[i]));
4849
- return op === "=" ? acc : not3(acc);
4850
- }
4851
- async function valueTuple(value2, pkFields, row, ctx, group) {
4852
- const v = await value2.evaluate(ctx, row, group);
4853
- if (v.isNull()) return pkFields.map(() => Value.null());
4854
- const raw2 = v.raw;
4855
- if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4856
- const obj2 = raw2;
4857
- return pkFields.map((f) => Value.of(obj2[f] ?? null));
5182
+ if (json.kind !== "unary") {
5183
+ throw new Error(`UnaryExpr.from: expected 'unary', got '${json.kind}'`);
5184
+ }
5185
+ return new _UnaryExpr(json.op, registry.parseExpr(json.operand));
4858
5186
  }
4859
- return [v];
4860
- }
4861
- async function evaluateHasMany(op, rel, value2, row, ctx, group) {
4862
- const pkFields = rel.target.primaryKey().map((f) => f.name);
4863
- const outer = rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4864
- const pkVals = await valueTuple(value2, pkFields, row, ctx, group);
4865
- if (outer.some((v) => v.isNull()) || pkVals.some((v) => v.isNull())) return op !== "=";
4866
- const rows = (await ctx.typeState(rel.target)).current;
4867
- const found = rows.some(
4868
- (tr) => rel.keys.every((k, i) => eq3(cell(tr, k.foreign), outer[i]) === true) && pkFields.every((f, i) => eq3(cell(tr, f), pkVals[i]) === true)
5187
+ /**
5188
+ * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
5189
+ * `UnaryExpr` equal to `from`'s output on a valid def; accumulates problems on
5190
+ * a bad def (never throws). See `shape/`.
5191
+ */
5192
+ static SHAPE = obj(
5193
+ {
5194
+ kind: lit("unary"),
5195
+ op: enumOf(UNARY_OPS, "UnaryOp"),
5196
+ operand: exprRef()
5197
+ },
5198
+ (v) => new _UnaryExpr(v.op, v.operand),
5199
+ { aid: "Expr_unary" }
4869
5200
  );
4870
- return op === "=" ? found : !found;
4871
- }
4872
- function tupleSql(operand, rel, keys, dialect, ctx) {
4873
- if (rel) return rel.keys.map((k) => new FieldRefExpr(rel.source, k.local).toSQL(dialect, ctx));
4874
- if (operand instanceof ParamExpr) {
4875
- const pv = ctx.params[operand.name];
4876
- if (pv !== null && pv !== void 0 && typeof pv === "object") {
4877
- const obj2 = pv;
4878
- return keys.map((k) => SqlText.param(obj2[k.foreign] ?? null));
5201
+ /** Zod schema for this expr kind's JSON shape (operand uses the shared child Expr schema). */
5202
+ static toSchema(opts) {
5203
+ return withAid(
5204
+ z20.object({
5205
+ kind: z20.literal("unary"),
5206
+ op: withAid(z20.enum(["-", "+"]), "UnaryOp"),
5207
+ operand: childExprSchema(opts.Expr)
5208
+ }),
5209
+ "Expr_unary"
5210
+ ).describe("Unary arithmetic operation.");
5211
+ }
5212
+ forEachChild(visit) {
5213
+ visit(this.operand);
5214
+ }
5215
+ /** Resolve to numeric/money mirroring the operand's category, propagating nullability/aggregate. */
5216
+ resolve(engine, scope) {
5217
+ const o = this.operand.resolve(engine, scope);
5218
+ const sources = gatherSources([o]);
5219
+ const nullable = o.kind !== "type" && o.nullable;
5220
+ const aggregate2 = o.kind === "computed" && o.aggregate;
5221
+ const fieldType = categoryOf(o) === "money" ? new MoneyFieldType() : new NumberFieldType();
5222
+ return computed(fieldType, sources, nullable, aggregate2);
5223
+ }
5224
+ /** Validate the operand is numeric (NULL/param exempt), infer param type, then resolve. */
5225
+ validateWalk(engine, scope, p, ctx) {
5226
+ const o = p.at("operand", () => this.operand.validateWalk(engine, scope, p, ctx));
5227
+ const exempt3 = this.operand instanceof LiteralExpr && this.operand.isNullLiteral() || this.operand instanceof ParamExpr;
5228
+ if (!exempt3) {
5229
+ const cat = categoryOf(o);
5230
+ if (cat !== "number" && cat !== "money") {
5231
+ p.at("operand", () => {
5232
+ p.error("unary.type", `Unary '${this.op}' requires a numeric operand; got ${cat ?? "a type"}.`);
5233
+ });
5234
+ }
4879
5235
  }
4880
- return [SqlText.param(pv ?? null)];
5236
+ if (this.operand instanceof ParamExpr) {
5237
+ scope.params.observe(this.operand.name, new NumberFieldType(), [...p.here, "operand"]);
5238
+ }
5239
+ return this.resolve(engine, scope);
4881
5240
  }
4882
- return [operand.toSQL(dialect, ctx)];
4883
- }
4884
- function emitRelationCompare(op, left, right, leftRel, rightRel, dialect, ctx) {
4885
- const keys = (leftRel ?? rightRel).keys;
4886
- const ls = tupleSql(left, leftRel, keys, dialect, ctx);
4887
- const rs = tupleSql(right, rightRel, keys, dialect, ctx);
4888
- const eqs = keys.map((_, i) => SqlText.join([ls[i], SqlText.raw("="), rs[i]], " "));
4889
- const anded = SqlText.join(eqs, " AND ").parens();
4890
- return op === "=" ? anded : SqlText.concat([SqlText.raw("NOT "), anded]);
4891
- }
4892
- function valueComponentsSql(value2, pkFields, ctx) {
4893
- if (!(value2 instanceof ParamExpr)) return pkFields.map(() => null);
4894
- const pv = ctx.params[value2.name];
4895
- if (pv !== null && pv !== void 0 && typeof pv === "object") {
4896
- const obj2 = pv;
4897
- return pkFields.map((f) => obj2[f] ?? null);
5241
+ /** Cost is the operand's cost. */
5242
+ cost(ctx, scope) {
5243
+ return this.childCost(ctx, scope);
4898
5244
  }
4899
- return [pv ?? null];
4900
- }
4901
- function emitHasMany(op, rel, value2, dialect, ctx) {
4902
- const pkFields = rel.target.primaryKey().map((f) => f.name);
4903
- const comps = valueComponentsSql(value2, pkFields, ctx);
4904
- const eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
4905
- const col = (source, field) => ({ kind: "field-ref", source, field });
4906
- const where = [
4907
- // Correlation: each has-many key joins the target's FK-back column to this row's identity.
4908
- ...rel.keys.map((k) => eq2(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
4909
- // Membership: the target's PK equals the value's components.
4910
- ...pkFields.map((pk, i) => eq2(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
4911
- ];
4912
- const def = {
4913
- kind: "select",
4914
- // Project the target's PK column (a bare ref, no bound param) — EXISTS
4915
- // ignores the projected value, and `SELECT 1` would bind a stray literal.
4916
- fields: [{ expr: col(HAS_MANY_ALIAS, pkFields[0]) }],
4917
- from: { kind: "aliased", type: rel.target.name, as: HAS_MANY_ALIAS },
4918
- where
4919
- };
4920
- const sub2 = emitSubquerySQL(dialect, ctx, def);
4921
- return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub2]);
4922
- }
5245
+ /** Evaluate the operand and apply the sign (NULL/non-numeric → NULL). */
5246
+ async evaluate(ctx, row, group) {
5247
+ const v = await this.operand.evaluate(ctx, row, group);
5248
+ if (v.isNull()) return Value.null();
5249
+ const n = v.toNumber();
5250
+ if (Number.isNaN(n)) return Value.null();
5251
+ return Value.of(this.op === "-" ? -n : n);
5252
+ }
5253
+ /** Emit as a parenthesized `(op operand)` SqlText fragment. */
5254
+ toSQL(dialect, ctx) {
5255
+ return SqlText.concat([SqlText.raw(`(${this.op}`), this.operand.toSQL(dialect, ctx), SqlText.raw(")")]);
5256
+ }
5257
+ /** Serialize back to its JSON ExprDef. */
5258
+ toJSON() {
5259
+ return { kind: "unary", op: this.op, operand: this.operand.toJSON() };
5260
+ }
5261
+ /** Deep-copy this expr and its operand. */
5262
+ clone() {
5263
+ return new _UnaryExpr(this.op, this.operand.clone());
5264
+ }
5265
+ /** Render as source-like code (`-operand` / `+operand`). */
5266
+ toCode() {
5267
+ return `${this.op}${this.operand.toCode()}`;
5268
+ }
5269
+ };
5270
+
5271
+ // src/exprs/comparison.ts
5272
+ import { z as z21 } from "zod";
4923
5273
 
4924
5274
  // src/exprs/_field-guard.ts
4925
- function operandCtx(operand, kind, ctx, relationOk = false) {
5275
+ function operandCtx(operand, kind, ctx, relationUse) {
4926
5276
  if (!(operand instanceof FieldRefExpr)) return ctx;
4927
- return relationOk ? { ...ctx, fieldExprKind: kind, relationValueOk: true } : { ...ctx, fieldExprKind: kind };
5277
+ return relationUse ? { ...ctx, fieldExprKind: kind, relationUse } : { ...ctx, fieldExprKind: kind };
5278
+ }
5279
+ function identityValueCtx(expr, ctx) {
5280
+ return expr instanceof FieldRefExpr ? { ...ctx, relationUse: "value" } : ctx;
4928
5281
  }
4929
5282
 
4930
5283
  // src/exprs/comparison.ts
@@ -5022,9 +5375,9 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5022
5375
  static toSchema(opts) {
5023
5376
  const child = childExprSchema(opts.Expr);
5024
5377
  return withAid(
5025
- z20.object({
5026
- kind: z20.literal("comparison"),
5027
- op: withAid(z20.enum(["=", "<>", "<", "<=", ">", ">=", "like", "notLike", "ilike"]), "ComparisonOp"),
5378
+ z21.object({
5379
+ kind: z21.literal("comparison"),
5380
+ op: withAid(z21.enum(["=", "<>", "<", "<=", ">", ">=", "like", "notLike", "ilike"]), "ComparisonOp"),
5028
5381
  left: child,
5029
5382
  right: child
5030
5383
  }),
@@ -5038,8 +5391,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5038
5391
  /** Validate operands (comparability, or text for the LIKE family), infer any bind param from the other operand, and resolve to bool. */
5039
5392
  validateWalk(engine, scope, p, ctx) {
5040
5393
  const here = p.here;
5041
- const l = p.at("left", () => this.left.validateWalk(engine, scope, p, operandCtx(this.left, "comparison", ctx, true)));
5042
- const r = p.at("right", () => this.right.validateWalk(engine, scope, p, operandCtx(this.right, "comparison", ctx, true)));
5394
+ const l = p.at("left", () => this.left.validateWalk(engine, scope, p, operandCtx(this.left, "comparison", ctx, "compare")));
5395
+ const r = p.at("right", () => this.right.validateWalk(engine, scope, p, operandCtx(this.right, "comparison", ctx, "compare")));
5043
5396
  const lft = asFieldType(l);
5044
5397
  const rft = asFieldType(r);
5045
5398
  if (this.op !== "=" && this.op !== "<>" && (relationOf(l) || relationOf(r))) {
@@ -5047,8 +5400,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5047
5400
  }
5048
5401
  const lRel = relationOf(l);
5049
5402
  const rRel = relationOf(r);
5050
- if (lRel && rRel && (lRel.count > 1 || rRel.count > 1)) {
5051
- const set = lRel.count > 1 ? lRel : rRel;
5403
+ if (lRel && rRel && (!lRel.belongsTo || !rRel.belongsTo)) {
5404
+ const set = !lRel.belongsTo ? lRel : rRel;
5052
5405
  p.error(
5053
5406
  "comparison.relation-set",
5054
5407
  `Has-many relation '${set.source}.${set.field}' compares against a value (its members' key), not another relation ('${(set === lRel ? rRel : lRel).source}.${(set === lRel ? rRel : lRel).field}').`
@@ -5093,18 +5446,38 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5093
5446
  * equality and the equality-like ops (`= <> like notLike ilike`) keep ~a third.
5094
5447
  * An index-covered `=` is discounted separately by the cost model (via
5095
5448
  * {@link indexProbe}); this is the non-indexed fallback.
5449
+ *
5450
+ * An `=` against a column whose field type declares a CLOSED VALUE SET uses
5451
+ * that type's own `1/n` instead of the fixed third — the one case where the
5452
+ * schema knows the real answer (`FieldType.eqSelectivity`).
5096
5453
  */
5097
- selectivity() {
5454
+ selectivity(ctx, scope) {
5098
5455
  switch (this.op) {
5099
5456
  case "<":
5100
5457
  case "<=":
5101
5458
  case ">":
5102
5459
  case ">=":
5103
5460
  return RANGE_SELECTIVITY;
5461
+ case "=":
5462
+ return this.closedSetSelectivity(ctx, scope) ?? EQ_SELECTIVITY;
5104
5463
  default:
5105
5464
  return EQ_SELECTIVITY;
5106
5465
  }
5107
5466
  }
5467
+ /**
5468
+ * The `1/n` an operand's declared closed value set implies, or `undefined`
5469
+ * when neither side declares one. Both operands are consulted so
5470
+ * `:param = order.status` costs the same as `order.status = :param`; when both
5471
+ * declare a set the TIGHTER (smaller) estimate wins, since satisfying both
5472
+ * memberships can only narrow further.
5473
+ */
5474
+ closedSetSelectivity(ctx, scope) {
5475
+ const l = asFieldType(this.left.resolve(ctx.engine, scope))?.eqSelectivity();
5476
+ const r = asFieldType(this.right.resolve(ctx.engine, scope))?.eqSelectivity();
5477
+ if (l === void 0) return r;
5478
+ if (r === void 0) return l;
5479
+ return Math.min(l, r);
5480
+ }
5108
5481
  /** An `=` against a column is an index point-probe (arity 1); other ops are not. */
5109
5482
  indexProbe() {
5110
5483
  if (this.op !== "=") return void 0;
@@ -5117,8 +5490,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5117
5490
  const typeOf = runtimeTypeOf(ctx);
5118
5491
  const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5119
5492
  const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5120
- if (leftRel && leftRel.count > 1) return evaluateHasMany(this.op, leftRel, this.right, row, ctx, group);
5121
- if (rightRel && rightRel.count > 1) return evaluateHasMany(this.op, rightRel, this.left, row, ctx, group);
5493
+ if (leftRel && !leftRel.belongsTo) return evaluateHasMany(this.op, leftRel, this.right, row, ctx, group);
5494
+ if (rightRel && !rightRel.belongsTo) return evaluateHasMany(this.op, rightRel, this.left, row, ctx, group);
5122
5495
  if (leftRel || rightRel) {
5123
5496
  return evaluateRelationCompare(this.op, this.left, this.right, leftRel, rightRel, row, ctx, group);
5124
5497
  }
@@ -5164,8 +5537,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5164
5537
  const typeOf = sqlTypeOf(ctx);
5165
5538
  const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5166
5539
  const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5167
- if (leftRel && leftRel.count > 1) return emitHasMany(this.op, leftRel, this.right, dialect, ctx);
5168
- if (rightRel && rightRel.count > 1) return emitHasMany(this.op, rightRel, this.left, dialect, ctx);
5540
+ if (leftRel && !leftRel.belongsTo) return emitHasMany(this.op, leftRel, this.right, dialect, ctx);
5541
+ if (rightRel && !rightRel.belongsTo) return emitHasMany(this.op, rightRel, this.left, dialect, ctx);
5169
5542
  if (leftRel || rightRel) {
5170
5543
  return emitRelationCompare(this.op, this.left, this.right, leftRel, rightRel, dialect, ctx);
5171
5544
  }
@@ -5203,7 +5576,7 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5203
5576
  };
5204
5577
 
5205
5578
  // src/exprs/logical.ts
5206
- import { z as z21 } from "zod";
5579
+ import { z as z22 } from "zod";
5207
5580
  var LOGICAL_OPS = ["and", "or", "not"];
5208
5581
  var LogicalExpr = class _LogicalExpr extends BoolExpr {
5209
5582
  /** Wrap a boolean connective (`and` / `or` / `not`) over its operands. */
@@ -5261,10 +5634,10 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
5261
5634
  /** Zod schema for this expr kind's JSON shape (operands are child Expr slots). */
5262
5635
  static toSchema(opts) {
5263
5636
  return withAid(
5264
- z21.object({
5265
- kind: z21.literal("logical"),
5266
- op: withAid(z21.enum(["and", "or", "not"]), "LogicalOp"),
5267
- operands: z21.array(childExprSchema(opts.Expr))
5637
+ z22.object({
5638
+ kind: z22.literal("logical"),
5639
+ op: withAid(z22.enum(["and", "or", "not"]), "LogicalOp"),
5640
+ operands: z22.array(childExprSchema(opts.Expr))
5268
5641
  }),
5269
5642
  "Expr_logical"
5270
5643
  ).describe("Boolean connective (and / or / not).");
@@ -5368,7 +5741,7 @@ function assertNeverOp3(op) {
5368
5741
  }
5369
5742
 
5370
5743
  // src/exprs/in.ts
5371
- import { z as z22 } from "zod";
5744
+ import { z as z23 } from "zod";
5372
5745
 
5373
5746
  // src/exprs/_subquery.ts
5374
5747
  function inferSubqueryOutput(engine, scope, def) {
@@ -5507,11 +5880,11 @@ var InExpr = class _InExpr extends BoolExpr {
5507
5880
  /** Zod schema for this expr kind's JSON shape (`in` is a child Expr list or a child Query slot). */
5508
5881
  static toSchema(opts) {
5509
5882
  return withAid(
5510
- z22.object({
5511
- kind: z22.literal("in"),
5883
+ z23.object({
5884
+ kind: z23.literal("in"),
5512
5885
  value: childExprSchema(opts.Expr),
5513
- in: z22.union([z22.array(childExprSchema(opts.Expr)), childQuerySchema(opts.Query)]),
5514
- not: z22.boolean().optional()
5886
+ in: z23.union([z23.array(childExprSchema(opts.Expr)), childQuerySchema(opts.Query)]),
5887
+ not: z23.boolean().optional()
5515
5888
  }),
5516
5889
  "Expr_in"
5517
5890
  ).describe("Membership predicate (value IN list / subquery).");
@@ -5523,12 +5896,12 @@ var InExpr = class _InExpr extends BoolExpr {
5523
5896
  /** Validate that each list element / subquery output field is comparable with the value, infer params on either side, and resolve to bool. */
5524
5897
  validateWalk(engine, scope, p, ctx) {
5525
5898
  const here = p.here;
5526
- const v = p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "in", ctx, true)));
5899
+ const v = p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "in", ctx, "compare")));
5527
5900
  const vft = asFieldType(v);
5528
5901
  if (this.list) {
5529
5902
  p.at("in", () => {
5530
5903
  this.list.forEach((el, i) => {
5531
- const rt = p.at(i, () => el.validateWalk(engine, scope, p, operandCtx(el, "in", ctx, true)));
5904
+ const rt = p.at(i, () => el.validateWalk(engine, scope, p, operandCtx(el, "in", ctx, "compare")));
5532
5905
  const eft = asFieldType(rt);
5533
5906
  const skip = el instanceof ParamExpr || this.value instanceof ParamExpr;
5534
5907
  const relProblem = skip ? void 0 : relationValueProblem(v, rt);
@@ -5549,6 +5922,13 @@ var InExpr = class _InExpr extends BoolExpr {
5549
5922
  });
5550
5923
  });
5551
5924
  } else if (this.subquery) {
5925
+ const vRel = relationOf(v);
5926
+ if (vRel && vRel.keys.length > 1) {
5927
+ p.error(
5928
+ "in.relation-composite",
5929
+ `Relation '${vRel.source}.${vRel.field}' has a COMPOSITE key (${vRel.keys.map((k) => k.foreign).join(", ")}), so a subquery projecting one field cannot match it. Use an explicit list of { pk } identity values, or join the relation and compare the joined columns.`
5930
+ );
5931
+ }
5552
5932
  const out = p.at("in", () => validateSubqueryOutput(engine, scope, p, ctx, this.subquery));
5553
5933
  const oft = asFieldType(out);
5554
5934
  if (!(this.value instanceof ParamExpr)) {
@@ -5596,7 +5976,7 @@ var InExpr = class _InExpr extends BoolExpr {
5596
5976
  const typeOf = runtimeTypeOf(ctx);
5597
5977
  const rel = relationCompare(this.value, ctx.engine, typeOf);
5598
5978
  if (rel && this.list) {
5599
- if (rel.count > 1) {
5979
+ if (!rel.belongsTo) {
5600
5980
  let found = false;
5601
5981
  for (const el of this.list) {
5602
5982
  if (await evaluateHasMany("=", rel, el, row, ctx, group)) {
@@ -5613,7 +5993,8 @@ var InExpr = class _InExpr extends BoolExpr {
5613
5993
  }
5614
5994
  return this.not ? not3(acc) : acc;
5615
5995
  }
5616
- const v = await this.value.evaluate(ctx, row, group);
5996
+ const keyRef = rel && this.subquery ? new FieldRefExpr(rel.source, rel.keys[0].local) : void 0;
5997
+ const v = keyRef ? await keyRef.columnValue(ctx, row) : await this.value.evaluate(ctx, row, group);
5617
5998
  let matched = false;
5618
5999
  let anyNull = v.isNull();
5619
6000
  if (this.list) {
@@ -5645,17 +6026,16 @@ var InExpr = class _InExpr extends BoolExpr {
5645
6026
  const typeOf = sqlTypeOf(ctx);
5646
6027
  const rel = relationCompare(this.value, ctx.engine, typeOf);
5647
6028
  if (rel && this.list) {
5648
- const ors = rel.count > 1 ? this.list.map((el) => emitHasMany("=", rel, el, dialect, ctx)) : this.list.map(
6029
+ const ors = !rel.belongsTo ? this.list.map((el) => emitHasMany("=", rel, el, dialect, ctx)) : this.list.map(
5649
6030
  (el) => emitRelationCompare("=", this.value, el, rel, relationCompare(el, ctx.engine, typeOf), dialect, ctx)
5650
6031
  );
5651
6032
  const anded = SqlText.join(ors, " OR ").parens();
5652
6033
  return this.not ? SqlText.concat([SqlText.raw("NOT "), anded]) : anded;
5653
6034
  }
5654
6035
  const rhs = this.list ? SqlText.join(this.list.map((e2) => e2.toSQL(dialect, ctx)), ", ").parens() : this.subquery ? emitSubquerySQL(dialect, ctx, this.subquery) : SqlText.raw("()");
5655
- return SqlText.join(
5656
- [this.value.toSQL(dialect, ctx), SqlText.raw(this.not ? "NOT IN" : "IN"), rhs],
5657
- " "
5658
- );
6036
+ const keyRef = rel && this.subquery ? new FieldRefExpr(rel.source, rel.keys[0].local) : void 0;
6037
+ const lhs = keyRef ? keyRef.columnSQL(dialect, ctx) : this.value.toSQL(dialect, ctx);
6038
+ return SqlText.join([lhs, SqlText.raw(this.not ? "NOT IN" : "IN"), rhs], " ");
5659
6039
  }
5660
6040
  /** Serialize back to its JSON ExprDef. */
5661
6041
  toJSON() {
@@ -5681,7 +6061,7 @@ var InExpr = class _InExpr extends BoolExpr {
5681
6061
  };
5682
6062
 
5683
6063
  // src/exprs/between.ts
5684
- import { z as z23 } from "zod";
6064
+ import { z as z24 } from "zod";
5685
6065
  var BetweenExpr = class _BetweenExpr extends BoolExpr {
5686
6066
  /** Wrap `value [NOT] BETWEEN lower AND upper` as a range predicate. */
5687
6067
  constructor(value2, lower2, upper, not2) {
@@ -5732,12 +6112,12 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
5732
6112
  static toSchema(opts) {
5733
6113
  const child = childExprSchema(opts.Expr);
5734
6114
  return withAid(
5735
- z23.object({
5736
- kind: z23.literal("between"),
6115
+ z24.object({
6116
+ kind: z24.literal("between"),
5737
6117
  value: child,
5738
6118
  lower: child,
5739
6119
  upper: child,
5740
- not: z23.boolean().optional()
6120
+ not: z24.boolean().optional()
5741
6121
  }),
5742
6122
  "Expr_between"
5743
6123
  ).describe("Range predicate (value BETWEEN lower AND upper).");
@@ -5750,9 +6130,9 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
5750
6130
  /** Validate that both bounds are comparable with the value, infer any bound/value param, and resolve to bool. */
5751
6131
  validateWalk(engine, scope, p, ctx) {
5752
6132
  const here = p.here;
5753
- const v = p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "between", ctx, true)));
5754
- const lo = p.at("lower", () => this.lower.validateWalk(engine, scope, p, operandCtx(this.lower, "between", ctx, true)));
5755
- const hi = p.at("upper", () => this.upper.validateWalk(engine, scope, p, operandCtx(this.upper, "between", ctx, true)));
6133
+ const v = p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "between", ctx, "compare")));
6134
+ const lo = p.at("lower", () => this.lower.validateWalk(engine, scope, p, operandCtx(this.lower, "between", ctx, "compare")));
6135
+ const hi = p.at("upper", () => this.upper.validateWalk(engine, scope, p, operandCtx(this.upper, "between", ctx, "compare")));
5756
6136
  const vft = asFieldType(v);
5757
6137
  const check = (operand, rt, key) => {
5758
6138
  const ft = asFieldType(rt);
@@ -5837,7 +6217,7 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
5837
6217
  };
5838
6218
 
5839
6219
  // src/exprs/is-null.ts
5840
- import { z as z24 } from "zod";
6220
+ import { z as z25 } from "zod";
5841
6221
  var IsNullExpr = class _IsNullExpr extends BoolExpr {
5842
6222
  /** Wrap `value IS [NOT] NULL` as a null test. */
5843
6223
  constructor(value2, not2) {
@@ -5876,10 +6256,10 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5876
6256
  /** Zod schema for this expr kind's JSON shape (value is a child Expr slot). */
5877
6257
  static toSchema(opts) {
5878
6258
  return withAid(
5879
- z24.object({
5880
- kind: z24.literal("is-null"),
6259
+ z25.object({
6260
+ kind: z25.literal("is-null"),
5881
6261
  value: childExprSchema(opts.Expr),
5882
- not: z24.boolean().optional()
6262
+ not: z25.boolean().optional()
5883
6263
  }),
5884
6264
  "Expr_is-null"
5885
6265
  ).describe("Null test (value IS [NOT] NULL).");
@@ -5894,7 +6274,7 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5894
6274
  }
5895
6275
  /** Validate the operand and resolve to a non-nullable bool. */
5896
6276
  validateWalk(engine, scope, p, ctx) {
5897
- p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "is-null", ctx)));
6277
+ p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "is-null", ctx, "value")));
5898
6278
  return this.resolve(engine, scope);
5899
6279
  }
5900
6280
  /** A null test keeps ~a third of the rows (equality-like selectivity). */
@@ -5906,8 +6286,23 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5906
6286
  const v = await this.value.evaluate(ctx, row, group);
5907
6287
  return this.not ? !v.isNull() : v.isNull();
5908
6288
  }
5909
- /** Emit as a SqlText fragment (`value IS [NOT] NULL`). */
6289
+ /**
6290
+ * Emit as a SqlText fragment (`value IS [NOT] NULL`).
6291
+ *
6292
+ * A RELATION operand tests its KEY COLUMNS, not the assembled identity
6293
+ * object: the object is a constructed value and is never SQL NULL, so
6294
+ * `json_build_object(...) IS NULL` would be a constant false. Unset means any
6295
+ * key column is null (a partial composite key cannot join), so `IS NULL` is
6296
+ * the OR over them and `IS NOT NULL` the AND of their negations — which also
6297
+ * keeps the predicate index-usable. Matches the runtime, where a relation
6298
+ * ref with any null key evaluates to NULL.
6299
+ */
5910
6300
  toSQL(dialect, ctx) {
6301
+ const keys = relationKeySqls(this.value, dialect, ctx);
6302
+ if (keys) {
6303
+ const tests = keys.map((k) => SqlText.concat([k, SqlText.raw(this.not ? " IS NOT NULL" : " IS NULL")]));
6304
+ return SqlText.join(tests, this.not ? " AND " : " OR ").parens();
6305
+ }
5911
6306
  return SqlText.concat([
5912
6307
  this.value.toSQL(dialect, ctx),
5913
6308
  SqlText.raw(this.not ? " IS NOT NULL" : " IS NULL")
@@ -5930,7 +6325,7 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5930
6325
  };
5931
6326
 
5932
6327
  // src/exprs/exists.ts
5933
- import { z as z25 } from "zod";
6328
+ import { z as z26 } from "zod";
5934
6329
  var ExistsExpr = class _ExistsExpr extends BoolExpr {
5935
6330
  /** Wrap `[NOT] EXISTS (query)` as an existence predicate over a subquery. */
5936
6331
  constructor(query, not2) {
@@ -6030,10 +6425,10 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
6030
6425
  /** Zod schema for this expr kind's JSON shape (uses a child Query slot for the subquery). */
6031
6426
  static toSchema(opts) {
6032
6427
  return withAid(
6033
- z25.object({
6034
- kind: z25.literal("exists"),
6428
+ z26.object({
6429
+ kind: z26.literal("exists"),
6035
6430
  query: childQuerySchema(opts.Query),
6036
- not: z25.boolean().optional()
6431
+ not: z26.boolean().optional()
6037
6432
  }),
6038
6433
  "Expr_exists"
6039
6434
  ).describe("Existence predicate over a subquery.");
@@ -6083,7 +6478,7 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
6083
6478
  };
6084
6479
 
6085
6480
  // src/exprs/array-op.ts
6086
- import { z as z26 } from "zod";
6481
+ import { z as z27 } from "zod";
6087
6482
  var NO_VALUE_OPS = /* @__PURE__ */ new Set(["isEmpty", "notEmpty"]);
6088
6483
  var SINGLE_VALUE_OPS = /* @__PURE__ */ new Set(["contains"]);
6089
6484
  var LIST_VALUE_OPS = /* @__PURE__ */ new Set(["containsAny", "containsAll"]);
@@ -6146,9 +6541,9 @@ var ArrayOpExpr = class _ArrayOpExpr extends BoolExpr {
6146
6541
  static toSchema(opts) {
6147
6542
  const child = childExprSchema(opts.Expr);
6148
6543
  return withAid(
6149
- z26.object({
6150
- kind: z26.literal("array-op"),
6151
- op: withAid(z26.enum(["contains", "containsAny", "containsAll", "isEmpty", "notEmpty"]), "ArrayOp").describe(
6544
+ z27.object({
6545
+ kind: z27.literal("array-op"),
6546
+ op: withAid(z27.enum(["contains", "containsAny", "containsAll", "isEmpty", "notEmpty"]), "ArrayOp").describe(
6152
6547
  "Array predicate: element membership / overlap / emptiness."
6153
6548
  ),
6154
6549
  // The target is the recursive `Expr` union (`opts.Expr` is a shared
@@ -6161,7 +6556,7 @@ var ArrayOpExpr = class _ArrayOpExpr extends BoolExpr {
6161
6556
  // expr class threads `childExprSchema(opts.Expr)` in bare — see #array-op
6162
6557
  // overflow.) The wrapping object's own `.describe` still documents the kind.
6163
6558
  target: child,
6164
- value: z26.union([child, z26.array(child)]).optional().describe("Single element (contains), element list (containsAny/All), or omitted (isEmpty/notEmpty).")
6559
+ value: z27.union([child, z27.array(child)]).optional().describe("Single element (contains), element list (containsAny/All), or omitted (isEmpty/notEmpty).")
6165
6560
  }),
6166
6561
  "Expr_array-op"
6167
6562
  ).describe("Array containment / emptiness predicate.");
@@ -6318,7 +6713,7 @@ function assertNever2(value2) {
6318
6713
  }
6319
6714
 
6320
6715
  // src/exprs/case.ts
6321
- import { z as z27 } from "zod";
6716
+ import { z as z28 } from "zod";
6322
6717
  var BRANCH_SHAPE = obj(
6323
6718
  { when: exprRef(), then: exprRef() },
6324
6719
  (v) => ({ when: v.when, then: v.then }),
@@ -6368,9 +6763,9 @@ var CaseExpr = class _CaseExpr extends Expr {
6368
6763
  static toSchema(opts) {
6369
6764
  const child = childExprSchema(opts.Expr);
6370
6765
  return withAid(
6371
- z27.object({
6372
- kind: z27.literal("case"),
6373
- branches: z27.array(z27.object({ when: child, then: child })),
6766
+ z28.object({
6767
+ kind: z28.literal("case"),
6768
+ branches: z28.array(z28.object({ when: child, then: child })),
6374
6769
  else: child.optional()
6375
6770
  }),
6376
6771
  "Expr_case"
@@ -6485,17 +6880,17 @@ var CaseExpr = class _CaseExpr extends Expr {
6485
6880
  };
6486
6881
 
6487
6882
  // src/exprs/aggregate.ts
6488
- import { z as z29 } from "zod";
6883
+ import { z as z30 } from "zod";
6489
6884
 
6490
6885
  // src/exprs/_function-args.ts
6491
- import { z as z28 } from "zod";
6886
+ import { z as z29 } from "zod";
6492
6887
  function parseNamedArgs(json, registry) {
6493
6888
  const out = /* @__PURE__ */ new Map();
6494
6889
  for (const [name, def] of Object.entries(json)) out.set(name, registry.parseExpr(def));
6495
6890
  return out;
6496
6891
  }
6497
6892
  function namedArgSchema(child) {
6498
- return withAid(z28.record(z28.string(), child), "FunctionArgs").describe(
6893
+ return withAid(z29.record(z29.string(), child), "FunctionArgs").describe(
6499
6894
  "Arguments keyed by declared parameter name."
6500
6895
  );
6501
6896
  }
@@ -6680,11 +7075,11 @@ var AggregateExpr = class _AggregateExpr extends Expr {
6680
7075
  static toSchema(opts) {
6681
7076
  const child = childExprSchema(opts.Expr);
6682
7077
  const open = withAid(
6683
- z29.object({
6684
- kind: z29.literal("aggregate"),
6685
- function: z29.string().describe("Registered aggregate function name (count for count(*))."),
7078
+ z30.object({
7079
+ kind: z30.literal("aggregate"),
7080
+ function: z30.string().describe("Registered aggregate function name (count for count(*))."),
6686
7081
  args: namedArgSchema(child),
6687
- distinct: z29.boolean().optional()
7082
+ distinct: z30.boolean().optional()
6688
7083
  }),
6689
7084
  "Expr_aggregate"
6690
7085
  ).describe("Aggregate function over named args (count with empty args = count(*)).");
@@ -6831,7 +7226,7 @@ function substituteArgs(template, args) {
6831
7226
  }
6832
7227
 
6833
7228
  // src/exprs/window.ts
6834
- import { z as z30 } from "zod";
7229
+ import { z as z31 } from "zod";
6835
7230
  var ORDER_SHAPE = obj(
6836
7231
  {
6837
7232
  expr: exprRef(),
@@ -6916,16 +7311,16 @@ var WindowExpr = class _WindowExpr extends Expr {
6916
7311
  static toSchema(opts) {
6917
7312
  const child = childExprSchema(opts.Expr);
6918
7313
  const open = withAid(
6919
- z30.object({
6920
- kind: z30.literal("window"),
6921
- function: z30.string().describe("Registered window (or aggregate) function name."),
7314
+ z31.object({
7315
+ kind: z31.literal("window"),
7316
+ function: z31.string().describe("Registered window (or aggregate) function name."),
6922
7317
  args: namedArgSchema(child),
6923
- partitionBy: z30.array(child).optional(),
6924
- orderBy: z30.array(
6925
- z30.object({
7318
+ partitionBy: z31.array(child).optional(),
7319
+ orderBy: z31.array(
7320
+ z31.object({
6926
7321
  expr: child,
6927
- dir: withAid(z30.enum(["asc", "desc"]), "OrderDir"),
6928
- nulls: withAid(z30.enum(["first", "last"]), "OrderNulls").optional()
7322
+ dir: withAid(z31.enum(["asc", "desc"]), "OrderDir"),
7323
+ nulls: withAid(z31.enum(["first", "last"]), "OrderNulls").optional()
6929
7324
  })
6930
7325
  ).optional()
6931
7326
  }),
@@ -7112,7 +7507,7 @@ var WindowExpr = class _WindowExpr extends Expr {
7112
7507
  };
7113
7508
 
7114
7509
  // src/exprs/function-call.ts
7115
- import { z as z31 } from "zod";
7510
+ import { z as z32 } from "zod";
7116
7511
  var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7117
7512
  /** Wrap a registered scalar `fn` with its named `args`. */
7118
7513
  constructor(fn2, args) {
@@ -7163,9 +7558,9 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7163
7558
  static toSchema(opts) {
7164
7559
  const child = childExprSchema(opts.Expr);
7165
7560
  const open = withAid(
7166
- z31.object({
7167
- kind: z31.literal("function-call"),
7168
- function: z31.string().describe("Registered scalar function name."),
7561
+ z32.object({
7562
+ kind: z32.literal("function-call"),
7563
+ function: z32.string().describe("Registered scalar function name."),
7169
7564
  args: namedArgSchema(child)
7170
7565
  }),
7171
7566
  "Expr_function-call"
@@ -7252,7 +7647,7 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7252
7647
  };
7253
7648
 
7254
7649
  // src/exprs/tabular-function-call.ts
7255
- import { z as z32 } from "zod";
7650
+ import { z as z33 } from "zod";
7256
7651
  var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7257
7652
  /** Wrap a registered tabular `fn` with its named `args`. */
7258
7653
  constructor(fn2, args) {
@@ -7292,9 +7687,9 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7292
7687
  static toSchema(opts) {
7293
7688
  const child = childExprSchema(opts.Expr);
7294
7689
  const open = withAid(
7295
- z32.object({
7296
- kind: z32.literal("tabular-function-call"),
7297
- function: z32.string().describe("Registered tabular function name."),
7690
+ z33.object({
7691
+ kind: z33.literal("tabular-function-call"),
7692
+ function: z33.string().describe("Registered tabular function name."),
7298
7693
  args: namedArgSchema(child)
7299
7694
  }),
7300
7695
  "Expr_tabular-function-call"
@@ -7925,15 +8320,13 @@ function boundTypeOf(ctx, source) {
7925
8320
  function searchColumn(dialect, ctx, source, field) {
7926
8321
  if (field !== void 0) return dialect.field(source, field);
7927
8322
  const bound = ctx.scope.lookup(source);
7928
- if (bound && bound.kind === "type") {
7929
- const searchable = bound.type.fields.find(
7930
- (f) => f.fieldType instanceof TextFieldType && f.fieldType.options.search === true
7931
- );
7932
- if (searchable) return dialect.field(source, searchable.name);
7933
- const text = bound.type.fields.find((f) => f.fieldType.resolve() === "text");
7934
- if (text) return dialect.field(source, text.name);
7935
- }
7936
- return dialect.field(source, "search");
8323
+ const typeName = bound && bound.kind === "type" ? bound.type.name : source;
8324
+ throw new QueryTypeError({
8325
+ path: [],
8326
+ code: "text-search.unbacked",
8327
+ severity: "error",
8328
+ message: `Whole-source text search / score on '${source}' (type '${typeName}') has no SQL-emitting search backing (a 'vectorField' or a 'sql' override), so there is no column to search. Narrow it to a text field, or complete the Type's SearchBacking.`
8329
+ });
7937
8330
  }
7938
8331
  function searchBackingOf(ctx, source, field) {
7939
8332
  const bound = ctx.scope.lookup(source);
@@ -8037,6 +8430,11 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
8037
8430
  } else if (this.field === void 0) {
8038
8431
  if (!bound.type.isSearchable()) {
8039
8432
  p.error("text-search.not-searchable", `Type '${bound.type.name}' is not full-text-search-eligible.`);
8433
+ } else if (engine.searchBacking(bound.type.name, void 0) === void 0) {
8434
+ p.error(
8435
+ "text-search.unbacked",
8436
+ `Type '${bound.type.name}' is declared searchable but has no search backing, so it has no whole-record document to search. Narrow the search to a text field, or declare a SearchBacking for the Type.`
8437
+ );
8040
8438
  }
8041
8439
  } else {
8042
8440
  const fieldName = this.field;
@@ -8191,6 +8589,11 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
8191
8589
  } else if (this.field === void 0) {
8192
8590
  if (!bound.type.isSearchable()) {
8193
8591
  p.error("text-score.not-searchable", `Type '${bound.type.name}' is not full-text-search-eligible.`);
8592
+ } else if (engine.searchBacking(bound.type.name, void 0) === void 0) {
8593
+ p.error(
8594
+ "text-score.unbacked",
8595
+ `Type '${bound.type.name}' is declared searchable but has no search backing, so it has no whole-record document to rank. Narrow the score to a text field, or declare a SearchBacking for the Type.`
8596
+ );
8194
8597
  }
8195
8598
  } else {
8196
8599
  const fieldName = this.field;
@@ -8417,7 +8820,7 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
8417
8820
  };
8418
8821
 
8419
8822
  // src/exprs/subquery.ts
8420
- import { z as z33 } from "zod";
8823
+ import { z as z34 } from "zod";
8421
8824
  var SubqueryExpr = class _SubqueryExpr extends Expr {
8422
8825
  /** Wrap the inner query def evaluated in value position. */
8423
8826
  constructor(query) {
@@ -8505,8 +8908,8 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
8505
8908
  /** Zod schema for this expr kind's JSON shape. */
8506
8909
  static toSchema(opts) {
8507
8910
  return withAid(
8508
- z33.object({
8509
- kind: z33.literal("subquery"),
8911
+ z34.object({
8912
+ kind: z34.literal("subquery"),
8510
8913
  query: childQuerySchema(opts.Query)
8511
8914
  }),
8512
8915
  "Expr_subquery"
@@ -8552,7 +8955,7 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
8552
8955
  };
8553
8956
 
8554
8957
  // src/exprs/excluded.ts
8555
- import { z as z34 } from "zod";
8958
+ import { z as z35 } from "zod";
8556
8959
  var EXCLUDED_SOURCE = "excluded";
8557
8960
  var ExcludedExpr = class _ExcludedExpr extends Expr {
8558
8961
  /** Wrap the proposed-row column name this reference reads. */
@@ -8589,9 +8992,9 @@ var ExcludedExpr = class _ExcludedExpr extends Expr {
8589
8992
  /** Zod schema for this expr kind's JSON shape. */
8590
8993
  static toSchema(_opts) {
8591
8994
  return withAid(
8592
- z34.object({
8593
- kind: z34.literal("excluded"),
8594
- field: z34.string().describe("A column of the proposed (excluded) row.")
8995
+ z35.object({
8996
+ kind: z35.literal("excluded"),
8997
+ field: z35.string().describe("A column of the proposed (excluded) row.")
8595
8998
  }),
8596
8999
  "Expr_excluded"
8597
9000
  ).describe("The proposed row inside an INSERT ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
@@ -8683,7 +9086,7 @@ var BUILTIN_EXPRS = [
8683
9086
  function exprDefSchema(opts = {}) {
8684
9087
  const branches = BUILTIN_EXPRS.map((c) => c.toSchema(opts));
8685
9088
  const first = branches[0];
8686
- if (!first) return z35.never();
9089
+ if (!first) return z36.never();
8687
9090
  return branches.slice(1).reduce((acc, s) => acc.or(s), first).describe("Expression definition (one of the built-in expression kinds).");
8688
9091
  }
8689
9092
 
@@ -8944,6 +9347,7 @@ var Query = class {
8944
9347
  };
8945
9348
  function makeField(name, type) {
8946
9349
  const ft = asFieldType(type);
9350
+ if (relationOf(type)?.belongsTo) return { name, type, nullable: true, fieldType: "json" };
8947
9351
  const fieldType = ft ? ft.resolve() : "type";
8948
9352
  const nullable = type.kind !== "type" && type.nullable;
8949
9353
  return { name, type, nullable, fieldType };
@@ -8953,8 +9357,8 @@ function toArrayRows(fields, rows) {
8953
9357
  }
8954
9358
  function syntheticType(name, fields) {
8955
9359
  const built = fields.map((c) => {
8956
- const ft = asFieldType(c.type) ?? new TextFieldType();
8957
- const nullable = c.type.kind !== "type" && c.type.nullable;
9360
+ const ft = asFieldType(c.type) ?? (relationOf(c.type)?.belongsTo ? new JsonFieldType() : new TextFieldType());
9361
+ const nullable = c.type.kind !== "type" ? c.type.nullable : relationOf(c.type)?.belongsTo === true;
8958
9362
  return new Field({ name: c.name, fieldType: ft, nullable });
8959
9363
  });
8960
9364
  return new Type({ name, fields: built, indexes: [], count: 0, bytes: 0 });
@@ -9589,6 +9993,12 @@ function boundShape() {
9589
9993
  }
9590
9994
 
9591
9995
  // src/queries/_cost.ts
9996
+ function selfBinding(type) {
9997
+ return { source: type.name, type };
9998
+ }
9999
+ function boundDigest(ref3, at) {
10000
+ return aliasedDigest(ref3.toJSON(), at.source, at.type.name);
10001
+ }
9592
10002
  function scanCost(type) {
9593
10003
  return { rows: type.count, bytes: type.count * type.bytes };
9594
10004
  }
@@ -9606,76 +10016,82 @@ function probesOf(conjuncts) {
9606
10016
  }
9607
10017
  return probes;
9608
10018
  }
9609
- function indexPartDigests(type) {
10019
+ function indexPartDigests(at) {
9610
10020
  const digests = /* @__PURE__ */ new Set();
9611
- for (const idx of type.indexes) for (const part of idx.parts) digests.add(part.digest);
10021
+ for (const idx of at.type.indexes) for (const part of idx.parts) digests.add(part.digest);
9612
10022
  return digests;
9613
10023
  }
9614
- function bestPrefixReduction(type, refs) {
9615
- if (refs.length === 0) return void 0;
10024
+ function probesAt(probes, at) {
10025
+ return probes.filter((p) => p.ref.source === at.source);
10026
+ }
10027
+ function bestPrefixReduction(at, refs) {
10028
+ const bound = refs.filter((r) => r.source === at.source);
10029
+ if (bound.length === 0) return void 0;
9616
10030
  let best;
9617
- for (const idx of type.indexes) {
9618
- const r = idx.prefixReduction(refs);
10031
+ for (const idx of at.type.indexes) {
10032
+ const r = idx.prefixReduction(bound, { source: at.source, typeName: at.type.name });
9619
10033
  if (r === void 0) continue;
9620
10034
  best = best === void 0 ? r : Math.min(best, r);
9621
10035
  }
9622
10036
  return best;
9623
10037
  }
9624
- function indexArityFactor(partDigests, probes) {
10038
+ function indexArityFactor(partDigests, probes, at) {
9625
10039
  let factor = 1;
9626
- for (const pr of probes) {
9627
- if (pr.arity > 1 && partDigests.has(exprDigest(pr.ref.toJSON()))) factor *= pr.arity;
10040
+ for (const pr of probesAt(probes, at)) {
10041
+ if (pr.arity > 1 && partDigests.has(boundDigest(pr.ref, at))) factor *= pr.arity;
9628
10042
  }
9629
10043
  return factor;
9630
10044
  }
9631
- function applyWhere(ctx, scope, base, type, where, perRowBytes) {
10045
+ function applyWhere(ctx, scope, base, at, where, perRowBytes) {
9632
10046
  const conjuncts = conjunctsOf(ctx, scope, where);
9633
- const rows = reduceRows(ctx, scope, type, base.rows, conjuncts);
10047
+ const rows = reduceRows(ctx, scope, at, base.rows, conjuncts);
9634
10048
  const penalty = conjuncts.reduce((sum2, c) => sum2 + c.totalScanRowPenalty(), 0) * base.rows;
9635
10049
  return { rows, bytes: rows * perRowBytes + penalty };
9636
10050
  }
9637
- function reduceRows(ctx, scope, type, baseRows, conjuncts) {
10051
+ function reduceRows(ctx, scope, at, baseRows, conjuncts) {
9638
10052
  const probes = probesOf(conjuncts);
9639
- const partDigests = indexPartDigests(type);
9640
- const reduction = bestPrefixReduction(type, probes.map((p) => p.ref));
10053
+ const partDigests = indexPartDigests(at);
10054
+ const reduction = bestPrefixReduction(at, probes.map((p) => p.ref));
9641
10055
  let rows = baseRows;
9642
10056
  for (const c of conjuncts) {
9643
10057
  const probe = c.indexProbe();
9644
- if (reduction !== void 0 && probe && partDigests.has(exprDigest(probe.ref.toJSON()))) continue;
10058
+ if (reduction !== void 0 && probe && probe.ref.source === at.source && partDigests.has(boundDigest(probe.ref, at))) {
10059
+ continue;
10060
+ }
9645
10061
  rows = floor1(rows * c.selectivity(ctx, scope));
9646
10062
  }
9647
- if (reduction !== void 0) rows = Math.min(rows, floor1(reduction * indexArityFactor(partDigests, probes)));
10063
+ if (reduction !== void 0) rows = Math.min(rows, floor1(reduction * indexArityFactor(partDigests, probes, at)));
9648
10064
  return rows;
9649
10065
  }
9650
- function matchedRows(ctx, scope, type, where) {
9651
- return andMatch(ctx, scope, type, type.count, conjunctsOf(ctx, scope, where));
10066
+ function matchedRows(ctx, scope, at, where) {
10067
+ return andMatch(ctx, scope, at, at.type.count, conjunctsOf(ctx, scope, where));
9652
10068
  }
9653
- function andMatch(ctx, scope, type, base, conjuncts) {
10069
+ function andMatch(ctx, scope, at, base, conjuncts) {
9654
10070
  const ors = conjuncts.filter((c) => c.orOperands() !== void 0);
9655
10071
  const rest = conjuncts.filter((c) => c.orOperands() === void 0);
9656
- let rows = reduceRows(ctx, scope, type, base, rest);
9657
- for (const or2 of ors) rows = floor1(rows * orFraction(ctx, scope, type, or2));
10072
+ let rows = reduceRows(ctx, scope, at, base, rest);
10073
+ for (const or2 of ors) rows = floor1(rows * orFraction(ctx, scope, at, or2));
9658
10074
  return rows;
9659
10075
  }
9660
- function orFraction(ctx, scope, type, orExpr) {
10076
+ function orFraction(ctx, scope, at, orExpr) {
9661
10077
  let none = 1;
9662
10078
  for (const operand of orExpr.orOperands()) {
9663
- const branch = andMatch(ctx, scope, type, type.count, operand.conjuncts(ctx, scope));
9664
- none *= 1 - branch / type.count;
10079
+ const branch = andMatch(ctx, scope, at, at.type.count, operand.conjuncts(ctx, scope));
10080
+ none *= 1 - branch / at.type.count;
9665
10081
  }
9666
10082
  return 1 - none;
9667
10083
  }
9668
- function distinctEstimate(type, groupBy, scannedRows) {
10084
+ function distinctEstimate(at, groupBy, scannedRows) {
9669
10085
  if (groupBy.length === 1) {
9670
10086
  const ref3 = groupBy[0].fieldRef();
9671
10087
  if (ref3) {
9672
- const reduction = bestPrefixReduction(type, [ref3]);
10088
+ const reduction = bestPrefixReduction(at, [ref3]);
9673
10089
  if (reduction !== void 0) return Math.max(1, reduction);
9674
10090
  }
9675
10091
  }
9676
10092
  return Math.max(1, Math.ceil(Math.sqrt(Math.max(1, scannedRows))));
9677
10093
  }
9678
- function coveredScanBytes(ctx, scope, fromType, fromAlias, fields, where) {
10094
+ function coveredScanBytes(ctx, scope, at, fields, where) {
9679
10095
  const refs = [];
9680
10096
  let simple = true;
9681
10097
  const collect = (e2) => {
@@ -9683,21 +10099,21 @@ function coveredScanBytes(ctx, scope, fromType, fromAlias, fields, where) {
9683
10099
  if (n.cost(ctx, scope).rows > 0) simple = false;
9684
10100
  const r = n.fieldRef();
9685
10101
  if (!r) return;
9686
- if (r.source !== fromAlias) simple = false;
10102
+ if (r.source !== at.source) simple = false;
9687
10103
  else refs.push(r);
9688
10104
  });
9689
10105
  };
9690
10106
  for (const e2 of fields) collect(e2);
9691
10107
  for (const w of where) collect(w);
9692
10108
  if (!simple || refs.length === 0) return void 0;
9693
- const refDigests = new Set(refs.map((r) => exprDigest(r.toJSON())));
9694
- const probes = probesOf(conjunctsOf(ctx, scope, where));
10109
+ const refDigests = new Set(refs.map((r) => boundDigest(r, at)));
10110
+ const probes = probesAt(probesOf(conjunctsOf(ctx, scope, where)), at);
9695
10111
  if (probes.length === 0) return void 0;
9696
- for (const idx of fromType.indexes) {
10112
+ for (const idx of at.type.indexes) {
9697
10113
  const partDigests = indexPartDigestsOf(idx.parts);
9698
10114
  const allColumnsIndexed = [...refDigests].every((d) => partDigests.has(d));
9699
- const whereProbesIndex = probes.some((p) => partDigests.has(exprDigest(p.ref.toJSON())));
9700
- if (allColumnsIndexed && whereProbesIndex) return idx.bytes(fromType);
10115
+ const whereProbesIndex = probes.some((p) => partDigests.has(boundDigest(p.ref, at)));
10116
+ if (allColumnsIndexed && whereProbesIndex) return idx.bytes(at.type);
9701
10117
  }
9702
10118
  return void 0;
9703
10119
  }
@@ -10548,7 +10964,9 @@ var SelectQuery = class _SelectQuery extends Query {
10548
10964
  const groupCtx = { ...predCtx, inGroupBy: true };
10549
10965
  const outScope = this.outputScope(inner);
10550
10966
  p.at("fields", () => {
10551
- this.fields.forEach((c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, colCtx)));
10967
+ this.fields.forEach(
10968
+ (c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, identityValueCtx(c.expr, colCtx)))
10969
+ );
10552
10970
  });
10553
10971
  p.at("where", () => {
10554
10972
  this.where.forEach((w, i) => p.at(i, () => {
@@ -10557,7 +10975,7 @@ var SelectQuery = class _SelectQuery extends Query {
10557
10975
  }));
10558
10976
  });
10559
10977
  p.at("groupBy", () => {
10560
- this.groupBy.forEach((g, i) => p.at(i, () => g.validateWalk(engine, outScope, p, groupCtx)));
10978
+ this.groupBy.forEach((g, i) => p.at(i, () => g.validateWalk(engine, outScope, p, identityValueCtx(g, groupCtx))));
10561
10979
  });
10562
10980
  p.at("having", () => {
10563
10981
  this.having.forEach((h, i) => p.at(i, () => {
@@ -10567,7 +10985,7 @@ var SelectQuery = class _SelectQuery extends Query {
10567
10985
  });
10568
10986
  p.at("order", () => {
10569
10987
  this.order.forEach(
10570
- (o, i) => o instanceof SorterExpr ? p.at(i, () => o.validateInOrder(engine, outScope, p, colCtx)) : p.at([i, "expr"], () => o.expr.validateWalk(engine, outScope, p, colCtx))
10988
+ (o, i) => o instanceof SorterExpr ? p.at(i, () => o.validateInOrder(engine, outScope, p, colCtx)) : p.at([i, "expr"], () => o.expr.validateWalk(engine, outScope, p, identityValueCtx(o.expr, colCtx)))
10571
10989
  );
10572
10990
  });
10573
10991
  if (this.groupBy.length > 0) {
@@ -10821,6 +11239,7 @@ var SelectQuery = class _SelectQuery extends Query {
10821
11239
  const engine = ctx.engine;
10822
11240
  const { scope: inner, aliasTypes } = this.bind(engine, scope);
10823
11241
  const fromType = this.from.resolvedType(engine, inner).type;
11242
+ const at = { source: this.from.alias, type: fromType };
10824
11243
  let rows = fromType.count;
10825
11244
  let perRowBytes = fromType.bytes;
10826
11245
  for (const join2 of this.joins) {
@@ -10829,20 +11248,20 @@ var SelectQuery = class _SelectQuery extends Query {
10829
11248
  if (plan) for (const hop of plan) perRowBytes += hop.targetType.bytes;
10830
11249
  }
10831
11250
  if (!this.joins.length && !this.groupBy.length && !this.distinct && !this.fields.some((c) => c.expr.containsAggregate())) {
10832
- const covered = coveredScanBytes(ctx, inner, fromType, this.from.alias, this.fields.map((c) => c.expr), this.where);
11251
+ const covered = coveredScanBytes(ctx, inner, at, this.fields.map((c) => c.expr), this.where);
10833
11252
  if (covered !== void 0) perRowBytes = covered;
10834
11253
  }
10835
11254
  const baseScan = scanCost(fromType);
10836
11255
  baseScan.rows = rows;
10837
11256
  baseScan.bytes = rows * perRowBytes;
10838
- let cost = applyWhere(ctx, inner, baseScan, fromType, this.where, perRowBytes);
11257
+ let cost = applyWhere(ctx, inner, baseScan, at, this.where, perRowBytes);
10839
11258
  if (this.groupBy.length) {
10840
- const distinct = distinctEstimate(fromType, this.groupBy, cost.rows);
11259
+ const distinct = distinctEstimate(at, this.groupBy, cost.rows);
10841
11260
  cost = { rows: distinct, bytes: distinct * perRowBytes };
10842
11261
  } else if (this.fields.some((c) => c.expr.containsAggregate())) {
10843
11262
  cost = { rows: 1, bytes: perRowBytes };
10844
11263
  } else if (this.distinct) {
10845
- const distinct = distinctEstimate(fromType, this.fields.map((c) => c.expr), cost.rows);
11264
+ const distinct = distinctEstimate(at, this.fields.map((c) => c.expr), cost.rows);
10846
11265
  cost = { rows: distinct, bytes: distinct * perRowBytes };
10847
11266
  }
10848
11267
  return { inner, fromType, perRowBytes, matchedRows: cost.rows };
@@ -11028,9 +11447,16 @@ var SelectQuery = class _SelectQuery extends Query {
11028
11447
  nulls ? SqlText.raw(` NULLS ${nulls.toUpperCase()}`) : SqlText.empty()
11029
11448
  ]);
11030
11449
  }
11031
- /** One ORDER BY term: `<expr> ASC|DESC [NULLS FIRST|LAST]`. */
11450
+ /**
11451
+ * One ORDER BY term: `<expr> ASC|DESC [NULLS FIRST|LAST]`. A RELATION term
11452
+ * expands to ONE clause per key column (each inheriting the term's direction
11453
+ * and NULLs placement) — lexicographic over the declared key order, and
11454
+ * index-usable, where sorting the assembled JSON object would be neither.
11455
+ */
11032
11456
  orderTermSQL(dialect, ctx, o) {
11033
- return this.orderClauseSQL(o.expr.toSQL(dialect, ctx), o.dir, o.nulls);
11457
+ const keys = relationKeySqls(o.expr, dialect, ctx);
11458
+ const sqls = keys ?? [o.expr.toSQL(dialect, ctx)];
11459
+ return sqls.map((s) => this.orderClauseSQL(s, o.dir, o.nulls));
11034
11460
  }
11035
11461
  /**
11036
11462
  * Emit the SELECT. A SELECT never prepends its own `WITH` (relation crossings
@@ -11058,9 +11484,9 @@ var SelectQuery = class _SelectQuery extends Query {
11058
11484
  }
11059
11485
  wherePreds.push(...defaultConditionPredicatesSql(this.activeDefaults(engine, aliasTypes), selCtx));
11060
11486
  const outCtx = selCtx.withScope(this.outputScope(inner));
11061
- const groupSqls = this.groupBy.map((g) => g.toSQL(dialect, outCtx));
11487
+ const groupSqls = this.groupBy.flatMap((g) => relationKeySqls(g, dialect, outCtx) ?? [g.toSQL(dialect, outCtx)]);
11062
11488
  const havingSqls = this.having.map((h) => h.toSQL(dialect, outCtx));
11063
- let orderSqls = this.expandOrder(ctx.sortSpec).map((o) => this.orderTermSQL(dialect, outCtx, o));
11489
+ let orderSqls = this.expandOrder(ctx.sortSpec).flatMap((o) => this.orderTermSQL(dialect, outCtx, o));
11064
11490
  const def = this.effectiveDefaultOrder(engine, isRoot);
11065
11491
  if (def) {
11066
11492
  orderSqls = resolveDefaultOrderSql(def, this.from.alias, outCtx).map(
@@ -11597,7 +12023,9 @@ var InsertQuery = class _InsertQuery extends Query {
11597
12023
  const inner = this.targetScope(engine, scope);
11598
12024
  const ctx = { inAggregate: false, inWindow: false, allowAggregate: true, groupKeys: [], inGroupBy: false };
11599
12025
  p.at("returning", () => {
11600
- this.returning.forEach((c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, ctx)));
12026
+ this.returning.forEach(
12027
+ (c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, identityValueCtx(c.expr, ctx)))
12028
+ );
11601
12029
  });
11602
12030
  if (this.onConflict && this.onConflict.update.length) {
11603
12031
  const conflictScope = this.conflictScope(engine, scope);
@@ -11964,7 +12392,9 @@ var UpdateQuery = class _UpdateQuery extends Query {
11964
12392
  checkBoolCondition(w, rt, p);
11965
12393
  })));
11966
12394
  const colCtx = { ...ctx, allowAggregate: true };
11967
- p.at("returning", () => this.returning.forEach((c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, colCtx))));
12395
+ p.at("returning", () => this.returning.forEach(
12396
+ (c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, identityValueCtx(c.expr, colCtx)))
12397
+ ));
11968
12398
  }
11969
12399
  /** The single target Type name this update writes. */
11970
12400
  referencedTypes() {
@@ -11986,13 +12416,13 @@ var UpdateQuery = class _UpdateQuery extends Query {
11986
12416
  const baseScan = scanCost(type);
11987
12417
  baseScan.rows = rows;
11988
12418
  baseScan.bytes = rows * perRowBytes;
11989
- return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
12419
+ return applyWhere(ctx, scope, baseScan, selfBinding(type), this.where, perRowBytes);
11990
12420
  }
11991
12421
  /** Rows this UPDATE mutates: the target type's rows matching WHERE (index / selectivity / OR-aware). */
11992
12422
  affected(ctx, scope) {
11993
12423
  const type = ctx.engine.type(this.type);
11994
12424
  if (!type) return AFFECTED_NONE;
11995
- return affectedOne(this.type, matchedRows(ctx, scope, type, this.where));
12425
+ return affectedOne(this.type, matchedRows(ctx, scope, selfBinding(type), this.where));
11996
12426
  }
11997
12427
  /** Expand joins, filter by WHERE, apply SET to each matched target row, then project RETURNING. */
11998
12428
  async execute(ctx) {
@@ -12252,7 +12682,9 @@ var DeleteQuery = class _DeleteQuery extends Query {
12252
12682
  checkBoolCondition(w, rt, p);
12253
12683
  })));
12254
12684
  const colCtx = { ...ctx, allowAggregate: true };
12255
- p.at("returning", () => this.returning.forEach((c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, colCtx))));
12685
+ p.at("returning", () => this.returning.forEach(
12686
+ (c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, identityValueCtx(c.expr, colCtx)))
12687
+ ));
12256
12688
  }
12257
12689
  /** The single target Type name this delete writes. */
12258
12690
  referencedTypes() {
@@ -12274,13 +12706,13 @@ var DeleteQuery = class _DeleteQuery extends Query {
12274
12706
  const baseScan = scanCost(type);
12275
12707
  baseScan.rows = rows;
12276
12708
  baseScan.bytes = rows * perRowBytes;
12277
- return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
12709
+ return applyWhere(ctx, scope, baseScan, selfBinding(type), this.where, perRowBytes);
12278
12710
  }
12279
12711
  /** Rows this DELETE removes: the target type's rows matching WHERE (index / selectivity / OR-aware). */
12280
12712
  affected(ctx, scope) {
12281
12713
  const type = ctx.engine.type(this.from);
12282
12714
  if (!type) return AFFECTED_NONE;
12283
- return affectedOne(this.from, matchedRows(ctx, scope, type, this.where));
12715
+ return affectedOne(this.from, matchedRows(ctx, scope, selfBinding(type), this.where));
12284
12716
  }
12285
12717
  /** Expand joins, filter by WHERE, project RETURNING (pre-removal), then delete the matched rows. */
12286
12718
  async execute(ctx) {
@@ -13142,6 +13574,14 @@ var BUILTIN_QUERIES = [
13142
13574
  ];
13143
13575
 
13144
13576
  // src/sql/dialect.ts
13577
+ function jsonObjectArgs(entries) {
13578
+ const args = [];
13579
+ for (const e2 of entries) {
13580
+ args.push(SqlText.raw(`'${e2.key.replace(/'/g, "''")}'`));
13581
+ args.push(e2.value);
13582
+ }
13583
+ return args;
13584
+ }
13145
13585
  var Dialect = class {
13146
13586
  /** Registry key (mirrors `name`) so an instance satisfies `DialectEntry`. */
13147
13587
  get NAME() {
@@ -13232,6 +13672,24 @@ var Dialect = class {
13232
13672
  SqlText.raw(` ON ${on}`)
13233
13673
  ]);
13234
13674
  }
13675
+ /** The SQL field type for a field type in this dialect. */
13676
+ /**
13677
+ * Build a JSON OBJECT from ordered `key → value` pairs — how a relation's
13678
+ * IDENTITY reaches the result boundary (`{ id: 5 }`, `{ tenantId: 3, userId: 1 }`).
13679
+ *
13680
+ * `json_build_object` is not ANSI, but neither is `json_array_length` which
13681
+ * this base dialect already emits for `arrayLength`: the portable dialect is
13682
+ * portable-ISH, and degrading a structured value to a concatenated string
13683
+ * would be worse than depending on the same JSON support that is already
13684
+ * assumed. Dialects with a richer JSON type override this.
13685
+ */
13686
+ jsonObject(entries) {
13687
+ return SqlText.concat([
13688
+ SqlText.raw("json_build_object("),
13689
+ SqlText.join(jsonObjectArgs(entries), ", "),
13690
+ SqlText.raw(")")
13691
+ ]);
13692
+ }
13235
13693
  /**
13236
13694
  * Render a builtin's INLINE-LITERAL argument (a `rawArgs` position — see
13237
13695
  * {@link import('../schema').FunctionDef.rawArgs}) as a dialect-appropriate SQL
@@ -13498,6 +13956,19 @@ var PostgresDialect = class extends BaseDialect {
13498
13956
  " "
13499
13957
  );
13500
13958
  }
13959
+ /**
13960
+ * `jsonb_build_object` rather than the base `json_build_object`: `jsonb` has
13961
+ * equality and ordering operators, so a projected identity can also be
13962
+ * DISTINCTed or compared, where a `json` value cannot be (Postgres has no
13963
+ * equality operator for `json` at all).
13964
+ */
13965
+ jsonObject(entries) {
13966
+ return SqlText.concat([
13967
+ SqlText.raw("jsonb_build_object("),
13968
+ SqlText.join(jsonObjectArgs(entries), ", "),
13969
+ SqlText.raw(")")
13970
+ ]);
13971
+ }
13501
13972
  /** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
13502
13973
  queryVectorParam(param3) {
13503
13974
  return SqlText.concat([param3, SqlText.raw("::vector")]);
@@ -16748,6 +17219,11 @@ function assertNeverExprKind(value2) {
16748
17219
  function isScalar2(value2) {
16749
17220
  return value2 === null || value2 !== void 0 && typeof value2 !== "object";
16750
17221
  }
17222
+ function isDrillValue(value2) {
17223
+ if (isScalar2(value2)) return true;
17224
+ if (value2 === void 0 || Array.isArray(value2)) return false;
17225
+ return Object.values(value2).every((v) => isScalar2(v));
17226
+ }
16751
17227
  function referencesField(expr) {
16752
17228
  let found = false;
16753
17229
  expr.walk((e2) => {
@@ -16935,12 +17411,12 @@ function drillDownInto(select, groupRow, engine) {
16935
17411
  drilled.params.forEach((dp, i) => {
16936
17412
  const present = Object.prototype.hasOwnProperty.call(groupRow, dp.field);
16937
17413
  const value2 = present ? groupRow[dp.field] : void 0;
16938
- if (!present || !isScalar2(value2)) {
17414
+ if (!present || !isDrillValue(value2)) {
16939
17415
  errors.at(
16940
17416
  ["groupBy", i],
16941
17417
  () => errors.error(
16942
17418
  "drill.missing-group-value",
16943
- `Group key '${engine.parse(dp.key).toCode()}' has no scalar value under field '${dp.field}' in the supplied group row.`
17419
+ `Group key '${engine.parse(dp.key).toCode()}' has no bindable value under field '${dp.field}' in the supplied group row.`
16944
17420
  )
16945
17421
  );
16946
17422
  return;
@@ -16952,7 +17428,7 @@ function drillDownInto(select, groupRow, engine) {
16952
17428
  }
16953
17429
 
16954
17430
  // src/llm/schemas.ts
16955
- import { z as z36 } from "zod";
17431
+ import { z as z37 } from "zod";
16956
17432
  var DEFAULT_MAX_QUERY_SCHEMA_TYPES = 5;
16957
17433
  function toRegistry(engineOrRegistry) {
16958
17434
  return "registry" in engineOrRegistry ? engineOrRegistry.registry : engineOrRegistry;
@@ -17030,8 +17506,8 @@ function relationOnSchema(types, depth, cache) {
17030
17506
  fieldMode: "one",
17031
17507
  eligible: relationFieldsOf,
17032
17508
  extras: {
17033
- kind: z36.literal("relation"),
17034
- as: z36.string().describe("Required alias the joined target binds under.")
17509
+ kind: z37.literal("relation"),
17510
+ as: z37.string().describe("Required alias the joined target binds under.")
17035
17511
  },
17036
17512
  aid: "JoinOn",
17037
17513
  describe: "Cross a relation field of a bound source (key synthesized from the relation)."
@@ -17061,37 +17537,37 @@ function buildSchemas(engineOrRegistry, options = {}) {
17061
17537
  functions: selected,
17062
17538
  includeDocs: options.includeDocs,
17063
17539
  cache,
17064
- Expr: z36.never(),
17065
- Query: z36.never()
17540
+ Expr: z37.never(),
17541
+ Query: z37.never()
17066
17542
  };
17067
- inner.Expr = z36.lazy(() => buildExprUnion(registry, inner, types, selected));
17068
- const typeRef = depth.typeNames === "enum" ? withAid(enumOf2(typeNames), "TypeName").describe("A registered Type name.") : z36.string().describe("A Type name.");
17543
+ inner.Expr = z37.lazy(() => buildExprUnion(registry, inner, types, selected));
17544
+ const typeRef = depth.typeNames === "enum" ? withAid(enumOf2(typeNames), "TypeName").describe("A registered Type name.") : z37.string().describe("A Type name.");
17069
17545
  const Expr9 = inner.Expr;
17070
- const Query2 = z36.lazy(() => QueryUnion);
17546
+ const Query2 = z37.lazy(() => QueryUnion);
17071
17547
  inner.Query = Query2;
17072
17548
  const sourceBranches = [
17073
- z36.object({ kind: z36.literal("type"), type: typeRef }).describe("A type source, bound under (and referenced by) its type name."),
17074
- z36.object({
17075
- kind: z36.literal("aliased"),
17549
+ z37.object({ kind: z37.literal("type"), type: typeRef }).describe("A type source, bound under (and referenced by) its type name."),
17550
+ z37.object({
17551
+ kind: z37.literal("aliased"),
17076
17552
  type: typeRef,
17077
- as: z36.string().describe("Custom source name (self-join / collision break).")
17553
+ as: z37.string().describe("Custom source name (self-join / collision break).")
17078
17554
  }).describe("An explicitly-aliased type source (the discouraged escape hatch)."),
17079
- z36.object({
17080
- kind: z36.literal("subquery"),
17555
+ z37.object({
17556
+ kind: z37.literal("subquery"),
17081
17557
  query: Query2,
17082
- as: z36.string().describe("Required alias for the derived source.")
17558
+ as: z37.string().describe("Required alias for the derived source.")
17083
17559
  }).describe("A derived (subquery) source.")
17084
17560
  ];
17085
17561
  if (selected.tabular.length > 0) {
17086
- const fnName = depth.functions === "open" ? z36.string().describe("A registered tabular function name.") : withAid(enumOf2(selected.tabular.map((f) => f.name)), "FunctionName").describe(
17562
+ const fnName = depth.functions === "open" ? z37.string().describe("A registered tabular function name.") : withAid(enumOf2(selected.tabular.map((f) => f.name)), "FunctionName").describe(
17087
17563
  "A registered tabular function name."
17088
17564
  );
17089
17565
  sourceBranches.push(
17090
- z36.object({
17091
- kind: z36.literal("function"),
17566
+ z37.object({
17567
+ kind: z37.literal("function"),
17092
17568
  function: fnName,
17093
- args: z36.record(z36.string(), Expr9).describe("Arguments keyed by declared parameter name."),
17094
- as: z36.string().describe("Required alias the produced rows bind under.")
17569
+ args: z37.record(z37.string(), Expr9).describe("Arguments keyed by declared parameter name."),
17570
+ as: z37.string().describe("Required alias the produced rows bind under.")
17095
17571
  }).describe("A table-valued function source: FROM fn(args) AS alias.")
17096
17572
  );
17097
17573
  }
@@ -17109,22 +17585,22 @@ function buildSchemas(engineOrRegistry, options = {}) {
17109
17585
  { kinds: ["relation", ...sourceKinds] }
17110
17586
  ).describe("A join target: a relation crossing or a manually-joined source.");
17111
17587
  const Join = withAid(
17112
- z36.object({
17588
+ z37.object({
17113
17589
  on: JoinOn,
17114
17590
  and: Expr9.optional(),
17115
17591
  joinType: withAid(enumOf2(["inner", "left", "right", "full"]), "JoinType").optional()
17116
17592
  }),
17117
17593
  "Join"
17118
17594
  ).describe("A JOIN: a relation crossing (key synthesized) or a manual source-def join with `and` as its ON.");
17119
- const joinsField = hasRelations ? z36.array(Join).optional() : z36.array(z36.never()).optional();
17120
- const Order = z36.object({
17595
+ const joinsField = hasRelations ? z37.array(Join).optional() : z37.array(z37.never()).optional();
17596
+ const Order = z37.object({
17121
17597
  expr: Expr9,
17122
17598
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
17123
17599
  nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
17124
17600
  }).describe("An ORDER BY entry.");
17125
- const OutputRef = z36.object({ kind: z36.literal("output"), name: z36.string() }).describe("A reference to a SELECT output field by name (its `as`, or the natural derived name).");
17601
+ const OutputRef = z37.object({ kind: z37.literal("output"), name: z37.string() }).describe("A reference to a SELECT output field by name (its `as`, or the natural derived name).");
17126
17602
  const GroupExpr = Expr9.or(OutputRef);
17127
- const SelectOrder = z36.object({
17603
+ const SelectOrder = z37.object({
17128
17604
  expr: GroupExpr,
17129
17605
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
17130
17606
  nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
@@ -17133,19 +17609,19 @@ function buildSchemas(engineOrRegistry, options = {}) {
17133
17609
  const SelectOrderEntry = SelectOrder.or(Sorter).describe(
17134
17610
  "A SELECT ORDER BY entry: a term, or a dynamic-sort `sorter` catalog (selection supplied at run time)."
17135
17611
  );
17136
- const SelectField = z36.object({ expr: Expr9, as: z36.string().optional() }).describe("A selected output field.");
17137
- const limitOffset = withAid(z36.number().or(cache.param()), "Limit", { id: cache.defId("Limit") });
17612
+ const SelectField = z37.object({ expr: Expr9, as: z37.string().optional() }).describe("A selected output field.");
17613
+ const limitOffset = withAid(z37.number().or(cache.param()), "Limit", { id: cache.defId("Limit") });
17138
17614
  const Select = withAid(
17139
- z36.object({
17140
- kind: z36.literal("select"),
17141
- distinct: z36.boolean().optional(),
17142
- fields: z36.array(SelectField),
17615
+ z37.object({
17616
+ kind: z37.literal("select"),
17617
+ distinct: z37.boolean().optional(),
17618
+ fields: z37.array(SelectField),
17143
17619
  from: Source,
17144
17620
  joins: joinsField,
17145
- where: z36.array(Expr9).optional(),
17146
- groupBy: z36.array(GroupExpr).optional(),
17147
- having: z36.array(GroupExpr).optional(),
17148
- order: z36.array(SelectOrderEntry).optional(),
17621
+ where: z37.array(Expr9).optional(),
17622
+ groupBy: z37.array(GroupExpr).optional(),
17623
+ having: z37.array(GroupExpr).optional(),
17624
+ order: z37.array(SelectOrderEntry).optional(),
17149
17625
  limit: limitOffset.optional(),
17150
17626
  offset: limitOffset.optional()
17151
17627
  // `includeTotal` is an EXECUTION-time option (engine.run / engine.toSQL),
@@ -17157,103 +17633,103 @@ function buildSchemas(engineOrRegistry, options = {}) {
17157
17633
  const updatableTypes = types.filter((t) => t.updatable);
17158
17634
  const deletableTypes = types.filter((t) => t.deletable);
17159
17635
  const fbOf = (typeName, field) => registry.backing(typeName)?.fields?.[field];
17160
- const dmlTypeRef = (subset) => depth.typeNames === "enum" ? enumOf2(subset.map((t) => t.name)).describe("A permitted target Type name.") : z36.string().describe("A Type name.");
17161
- const ExcludedExprSchema = z36.object({ kind: z36.literal("excluded"), field: z36.string() }).describe("The proposed row inside ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
17636
+ const dmlTypeRef = (subset) => depth.typeNames === "enum" ? enumOf2(subset.map((t) => t.name)).describe("A permitted target Type name.") : z37.string().describe("A Type name.");
17637
+ const ExcludedExprSchema = z37.object({ kind: z37.literal("excluded"), field: z37.string() }).describe("The proposed row inside ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
17162
17638
  const ConflictExpr = Expr9.or(ExcludedExprSchema);
17163
17639
  const onConflictSchema = (t) => {
17164
- const update = depth.writes !== "open" && t ? updateSetSchema(t, fbOf, depth.writes, ConflictExpr) : z36.record(z36.string(), ConflictExpr).describe("DO UPDATE SET assignments (field \u2192 value).");
17165
- return z36.object({
17166
- fields: z36.array(z36.string()),
17167
- doNothing: z36.boolean().optional(),
17640
+ const update = depth.writes !== "open" && t ? updateSetSchema(t, fbOf, depth.writes, ConflictExpr) : z37.record(z37.string(), ConflictExpr).describe("DO UPDATE SET assignments (field \u2192 value).");
17641
+ return z37.object({
17642
+ fields: z37.array(z37.string()),
17643
+ doNothing: z37.boolean().optional(),
17168
17644
  update: update.optional()
17169
17645
  });
17170
17646
  };
17171
17647
  const openInsert = () => withAid(
17172
- z36.object({
17173
- kind: z36.literal("insert"),
17648
+ z37.object({
17649
+ kind: z37.literal("insert"),
17174
17650
  into: dmlTypeRef(insertableTypes),
17175
- rows: z36.array(z36.record(z36.string(), Expr9)).optional().describe("Rows to insert (each a field \u2192 value map)."),
17651
+ rows: z37.array(z37.record(z37.string(), Expr9)).optional().describe("Rows to insert (each a field \u2192 value map)."),
17176
17652
  select: Query2.optional(),
17177
- returning: z36.array(SelectField).optional(),
17653
+ returning: z37.array(SelectField).optional(),
17178
17654
  onConflict: onConflictSchema().optional()
17179
17655
  }),
17180
17656
  "Query_insert"
17181
17657
  ).describe("An INSERT statement.");
17182
17658
  const namedInsert = (writes) => orFold(
17183
17659
  insertableTypes.map(
17184
- (t) => z36.object({
17185
- kind: z36.literal("insert"),
17186
- into: z36.literal(t.name),
17187
- rows: z36.array(insertRowSchema(t, fbOf, writes, Expr9)).optional(),
17660
+ (t) => z37.object({
17661
+ kind: z37.literal("insert"),
17662
+ into: z37.literal(t.name),
17663
+ rows: z37.array(insertRowSchema(t, fbOf, writes, Expr9)).optional(),
17188
17664
  select: Query2.optional(),
17189
- returning: z36.array(SelectField).optional(),
17665
+ returning: z37.array(SelectField).optional(),
17190
17666
  onConflict: onConflictSchema(t).optional()
17191
17667
  }).describe(`An INSERT into ${t.name}.`)
17192
17668
  )
17193
17669
  ).describe("An INSERT statement.");
17194
17670
  const Insert = depth.writes === "open" ? openInsert() : namedInsert(depth.writes);
17195
17671
  const openUpdate = () => withAid(
17196
- z36.object({
17197
- kind: z36.literal("update"),
17672
+ z37.object({
17673
+ kind: z37.literal("update"),
17198
17674
  type: dmlTypeRef(updatableTypes),
17199
- set: z36.record(z36.string(), Expr9).describe("Fields to set (field \u2192 value)."),
17675
+ set: z37.record(z37.string(), Expr9).describe("Fields to set (field \u2192 value)."),
17200
17676
  joins: joinsField,
17201
- where: z36.array(Expr9).optional(),
17202
- returning: z36.array(SelectField).optional()
17677
+ where: z37.array(Expr9).optional(),
17678
+ returning: z37.array(SelectField).optional()
17203
17679
  }),
17204
17680
  "Query_update"
17205
17681
  ).describe("An UPDATE statement.");
17206
17682
  const namedUpdate = (writes) => orFold(
17207
17683
  updatableTypes.map(
17208
- (t) => z36.object({
17209
- kind: z36.literal("update"),
17210
- type: z36.literal(t.name),
17684
+ (t) => z37.object({
17685
+ kind: z37.literal("update"),
17686
+ type: z37.literal(t.name),
17211
17687
  set: updateSetSchema(t, fbOf, writes, Expr9),
17212
17688
  joins: joinsField,
17213
- where: z36.array(Expr9).optional(),
17214
- returning: z36.array(SelectField).optional()
17689
+ where: z37.array(Expr9).optional(),
17690
+ returning: z37.array(SelectField).optional()
17215
17691
  }).describe(`An UPDATE of ${t.name}.`)
17216
17692
  )
17217
17693
  ).describe("An UPDATE statement.");
17218
17694
  const Update = depth.writes === "open" ? openUpdate() : namedUpdate(depth.writes);
17219
17695
  const Delete = withAid(
17220
- z36.object({
17221
- kind: z36.literal("delete"),
17696
+ z37.object({
17697
+ kind: z37.literal("delete"),
17222
17698
  from: dmlTypeRef(deletableTypes),
17223
17699
  joins: joinsField,
17224
- where: z36.array(Expr9).optional(),
17225
- returning: z36.array(SelectField).optional()
17700
+ where: z37.array(Expr9).optional(),
17701
+ returning: z37.array(SelectField).optional()
17226
17702
  }),
17227
17703
  "Query_delete"
17228
17704
  ).describe("A DELETE statement.");
17229
17705
  const SetOperation = withAid(
17230
- z36.object({
17706
+ z37.object({
17231
17707
  kind: withAid(enumOf2(["union", "intersect", "except"]), "SetOpKind"),
17232
17708
  left: Query2,
17233
17709
  right: Query2,
17234
- all: z36.boolean().optional(),
17710
+ all: z37.boolean().optional(),
17235
17711
  // SET-LEVEL ordering / pagination applied AFTER the set op; ORDER BY terms
17236
17712
  // reference OUTPUT COLUMN names (a set op has no table to qualify).
17237
- order: z36.array(Order).optional(),
17713
+ order: z37.array(Order).optional(),
17238
17714
  limit: limitOffset.optional(),
17239
17715
  offset: limitOffset.optional()
17240
17716
  }),
17241
17717
  "Query_set-operation"
17242
17718
  ).describe("A UNION / INTERSECT / EXCEPT set operation.");
17243
17719
  const CteEntry = orFold([
17244
- z36.object({ name: z36.string(), query: Query2 }).describe("A non-recursive CTE."),
17245
- z36.object({ name: z36.string(), base: Query2, recursive: Query2 }).describe("A recursive CTE: a base seed UNION-ed with a recursive arm.")
17720
+ z37.object({ name: z37.string(), query: Query2 }).describe("A non-recursive CTE."),
17721
+ z37.object({ name: z37.string(), base: Query2, recursive: Query2 }).describe("A recursive CTE: a base seed UNION-ed with a recursive arm.")
17246
17722
  ]);
17247
17723
  const CTE = withAid(
17248
- z36.object({
17249
- kind: z36.literal("cte"),
17250
- ctes: z36.array(CteEntry),
17724
+ z37.object({
17725
+ kind: z37.literal("cte"),
17726
+ ctes: z37.array(CteEntry),
17251
17727
  final: Query2
17252
17728
  }),
17253
17729
  "Query_cte"
17254
17730
  ).describe("A WITH (CTE) statement.");
17255
17731
  const ExprQuery2 = withAid(
17256
- z36.object({ kind: z36.literal("expr"), expr: Expr9 }),
17732
+ z37.object({ kind: z37.literal("expr"), expr: Expr9 }),
17257
17733
  "Query_expr"
17258
17734
  ).describe("A single-expression query.");
17259
17735
  const queryBranches = [Select];
@@ -17300,14 +17776,14 @@ function querySchema(engine, options = {}) {
17300
17776
  const types = options.types ?? registry.typeList();
17301
17777
  const max2 = options.max ?? DEFAULT_MAX_QUERY_SCHEMA_TYPES;
17302
17778
  if (shouldUseStringSchema(types, max2)) {
17303
- return z36.object({
17304
- query: z36.string().describe(
17779
+ return z37.object({
17780
+ query: z37.string().describe(
17305
17781
  "A detailed natural-language description of the query: which Types are involved, filter conditions, known record IDs, and the precise outcome desired. Do not emit a structured query \u2014 there are too many Types to enumerate."
17306
17782
  )
17307
17783
  });
17308
17784
  }
17309
17785
  const schemas = buildSchemas(registry, options);
17310
- return z36.object({
17786
+ return z37.object({
17311
17787
  query: schemas.Query.describe("The query to execute as a structured Query object.")
17312
17788
  });
17313
17789
  }
@@ -17490,7 +17966,11 @@ function fieldTypeTag(field) {
17490
17966
  const flags = [];
17491
17967
  if (ft.options.search) flags.push("search");
17492
17968
  if (ft.options.semantic) flags.push("semantic");
17493
- return flags.length ? `text(${flags.join(",")})` : "text";
17969
+ const base = flags.length ? `text(${flags.join(",")})` : "text";
17970
+ return base + describeValues(ft.options.values);
17971
+ }
17972
+ if (ft instanceof NumberFieldType) {
17973
+ return "number" + describeValues(ft.options.values);
17494
17974
  }
17495
17975
  return ft.kind;
17496
17976
  }
@@ -17812,6 +18292,7 @@ export {
17812
18292
  IN_SELECTIVITY,
17813
18293
  InExpr,
17814
18294
  Index,
18295
+ IndexPart,
17815
18296
  InsertQuery,
17816
18297
  IsNullExpr,
17817
18298
  JoinCtePlanner,
@@ -17865,6 +18346,7 @@ export {
17865
18346
  age,
17866
18347
  agg,
17867
18348
  aidInfo,
18349
+ aliasedDigest,
17868
18350
  and,
17869
18351
  arrayAgg,
17870
18352
  arrayAppend,
@@ -18005,6 +18487,9 @@ export {
18005
18487
  recordSignature,
18006
18488
  ref2 as ref,
18007
18489
  relJoin,
18490
+ relationKeyColumns,
18491
+ relationOf,
18492
+ renameSource,
18008
18493
  reportCostProblems,
18009
18494
  resolveAccessRun,
18010
18495
  resolveAccessSql,
@@ -18049,6 +18534,7 @@ export {
18049
18534
  typeFromFields,
18050
18535
  typeMeta,
18051
18536
  value,
18537
+ valueFieldType,
18052
18538
  variance,
18053
18539
  week,
18054
18540
  when,