@aeye/query 0.4.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();
@@ -2990,7 +3185,7 @@ var raw = (text) => SqlText.raw(text);
2990
3185
  var concat = (parts) => SqlText.concat(parts);
2991
3186
  var join = (parts, sep) => SqlText.join(parts, sep);
2992
3187
  var SqlContext = class _SqlContext {
2993
- constructor(dialect, engine, scope, planner, rls, inAggregate = false, params = {}, filters2 = {}, includeTotal = false, isRoot = false, sortSpec = []) {
3188
+ constructor(dialect, engine, scope, planner, rls, inAggregate = false, params = {}, filters2 = {}, includeTotal = false, isRoot = false, sortSpec = [], semanticText2 = void 0) {
2994
3189
  this.dialect = dialect;
2995
3190
  this.engine = engine;
2996
3191
  this.scope = scope;
@@ -3002,6 +3197,7 @@ var SqlContext = class _SqlContext {
3002
3197
  this.includeTotal = includeTotal;
3003
3198
  this.isRoot = isRoot;
3004
3199
  this.sortSpec = sortSpec;
3200
+ this.semanticText = semanticText2;
3005
3201
  }
3006
3202
  dialect;
3007
3203
  engine;
@@ -3014,23 +3210,24 @@ var SqlContext = class _SqlContext {
3014
3210
  includeTotal;
3015
3211
  isRoot;
3016
3212
  sortSpec;
3213
+ semanticText;
3017
3214
  /** The execution-supplied filter expr bound to `source`, or `undefined`. */
3018
3215
  filtersFor(source) {
3019
3216
  return this.filters[source];
3020
3217
  }
3021
3218
  /** Same context with a different scope (same planner / level / root status). */
3022
3219
  withScope(scope) {
3023
- return new _SqlContext(this.dialect, this.engine, scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec);
3220
+ return new _SqlContext(this.dialect, this.engine, scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec, this.semanticText);
3024
3221
  }
3025
3222
  /** A nested level (subquery): fresh scope + fresh planner, not in-aggregate.
3026
3223
  * Neither the outer `$total` flag NOR root status propagates into a nested
3027
3224
  * level, so a subquery / FROM subquery emits as non-root. */
3028
3225
  withPlanner(scope, planner) {
3029
- return new _SqlContext(this.dialect, this.engine, scope, planner, this.rls, false, this.params, this.filters, false, false, this.sortSpec);
3226
+ return new _SqlContext(this.dialect, this.engine, scope, planner, this.rls, false, this.params, this.filters, false, false, this.sortSpec, this.semanticText);
3030
3227
  }
3031
3228
  /** Toggle the in-aggregate flag (set when emitting an aggregate argument). */
3032
3229
  asAggregate(on) {
3033
- return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, on, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec);
3230
+ return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, on, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec, this.semanticText);
3034
3231
  }
3035
3232
  /**
3036
3233
  * Mark the NEXT emitted query as NON-root (same level otherwise). Used at the
@@ -3038,7 +3235,7 @@ var SqlContext = class _SqlContext {
3038
3235
  * branch — so those nested SELECTs never inherit the entry's root status.
3039
3236
  */
3040
3237
  nonRoot() {
3041
- return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, false, this.sortSpec);
3238
+ return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, false, this.sortSpec, this.semanticText);
3042
3239
  }
3043
3240
  };
3044
3241
 
@@ -3077,9 +3274,9 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3077
3274
  /** Zod schema for this expr kind's JSON shape. */
3078
3275
  static toSchema(_opts) {
3079
3276
  return withAid(
3080
- z14.object({
3081
- kind: z14.literal("literal"),
3082
- 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")
3083
3280
  }),
3084
3281
  "Expr_literal"
3085
3282
  ).describe("A constant scalar value.");
@@ -3134,7 +3331,7 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3134
3331
  };
3135
3332
 
3136
3333
  // src/exprs/output-ref.ts
3137
- import { z as z15 } from "zod";
3334
+ import { z as z16 } from "zod";
3138
3335
  var OutputRefExpr = class _OutputRefExpr extends Expr {
3139
3336
  /** Wrap the referenced output field name. */
3140
3337
  constructor(name) {
@@ -3170,9 +3367,9 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
3170
3367
  /** Zod schema for this expr kind's JSON shape (name is query-local ⇒ a plain string). */
3171
3368
  static toSchema(_opts) {
3172
3369
  return withAid(
3173
- z15.object({
3174
- kind: z15.literal("output"),
3175
- 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).")
3176
3373
  }),
3177
3374
  "Expr_output"
3178
3375
  ).describe("A reference to a SELECT output field by name (valid in groupBy / orderBy / having).");
@@ -3249,7 +3446,7 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
3249
3446
  };
3250
3447
 
3251
3448
  // src/schema-build.ts
3252
- import { z as z16 } from "zod";
3449
+ import { z as z17 } from "zod";
3253
3450
 
3254
3451
  // src/write-model.ts
3255
3452
  function requiredOnInsert(field, fb) {
@@ -3275,16 +3472,16 @@ function checkFieldExpr(kind, field, source, p) {
3275
3472
  function enumOf2(values) {
3276
3473
  const unique = Array.from(new Set(values));
3277
3474
  const first = unique[0];
3278
- if (first === void 0) return z16.never();
3279
- 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));
3280
3477
  }
3281
3478
  function orFold(branches) {
3282
3479
  const first = branches[0];
3283
- if (!first) return z16.never();
3480
+ if (!first) return z17.never();
3284
3481
  return branches.slice(1).reduce((acc, s) => acc.or(s), first);
3285
3482
  }
3286
3483
  function paramSchema() {
3287
- 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.");
3288
3485
  }
3289
3486
  var cacheGeneration = 0;
3290
3487
  var SchemaCache = class {
@@ -3333,7 +3530,7 @@ var SchemaCache = class {
3333
3530
  "param",
3334
3531
  "param",
3335
3532
  (id) => withSharedId(
3336
- 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."),
3337
3534
  id
3338
3535
  )
3339
3536
  );
@@ -3353,7 +3550,7 @@ var SchemaCache = class {
3353
3550
  const shape = {};
3354
3551
  for (const param3 of fn2.params) shape[param3.name] = param3.optional ? child.optional() : child;
3355
3552
  const named = params.length ? params.join(", ") : "none";
3356
- return withSharedId(z16.strictObject(shape).describe(`Named arguments: ${named}.`), id);
3553
+ return withSharedId(z17.strictObject(shape).describe(`Named arguments: ${named}.`), id);
3357
3554
  });
3358
3555
  }
3359
3556
  };
@@ -3378,7 +3575,7 @@ function fieldProperty(mode, fieldValue) {
3378
3575
  case "optional":
3379
3576
  return { field: fieldValue.optional().describe("A field to narrow to (omit for the whole source).") };
3380
3577
  case "list":
3381
- 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.") };
3382
3579
  /* v8 ignore next 2 -- unreachable: `mode` exhaustively covers RefFieldMode (compile-time guard) */
3383
3580
  default:
3384
3581
  return assertNeverFieldMode(mode);
@@ -3386,7 +3583,7 @@ function fieldProperty(mode, fieldValue) {
3386
3583
  }
3387
3584
  function refObject(keyName, keyValue, fieldProps, extras, aid, describe) {
3388
3585
  const shape = { [keyName]: keyValue, ...fieldProps, ...extras };
3389
- const obj2 = z16.object(shape);
3586
+ const obj2 = z17.object(shape);
3390
3587
  return (aid ? withAid(obj2, aid) : obj2).describe(describe);
3391
3588
  }
3392
3589
  function refSchema(types, depth, opts, cache) {
@@ -3395,8 +3592,8 @@ function refSchema(types, depth, opts, cache) {
3395
3592
  if (depth === "paired") {
3396
3593
  const branches = types.map((t) => {
3397
3594
  const names = opts.eligible(t).map((f) => f.name);
3398
- const fieldValue2 = names.length ? fieldEnum(names, t.name) : z16.string();
3399
- 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).`);
3400
3597
  const fieldProps2 = fieldProperty(opts.fieldMode, fieldValue2);
3401
3598
  return refObject(
3402
3599
  opts.keyName,
@@ -3411,13 +3608,13 @@ function refSchema(types, depth, opts, cache) {
3411
3608
  }
3412
3609
  const enumKey = depth === "types" || depth === "both";
3413
3610
  const enumField = depth === "fields" || depth === "both";
3414
- const keyBase = enumKey ? enumOf2(types.map((t) => t.name)) : z16.string();
3611
+ const keyBase = enumKey ? enumOf2(types.map((t) => t.name)) : z17.string();
3415
3612
  const keyTagged = enumKey && opts.keyName === "type" ? withAid(keyBase, "TypeName") : keyBase;
3416
3613
  const keyValue = keyTagged.describe(
3417
3614
  enumKey ? `${keyNoun[0].toUpperCase()}${keyNoun.slice(1)}.` : `A ${opts.keyName} name.`
3418
3615
  );
3419
3616
  const fieldNames = eligibleFieldNames(types, opts.eligible);
3420
- const fieldValue = enumField && fieldNames.length ? fieldEnum(fieldNames, "any") : z16.string();
3617
+ const fieldValue = enumField && fieldNames.length ? fieldEnum(fieldNames, "any") : z17.string();
3421
3618
  const fieldProps = fieldProperty(opts.fieldMode, fieldValue);
3422
3619
  return refObject(opts.keyName, keyValue, fieldProps, opts.extras, opts.aid, opts.describe);
3423
3620
  }
@@ -3426,7 +3623,7 @@ function fieldRefSchema(types, depth, cache) {
3426
3623
  keyName: "source",
3427
3624
  fieldMode: "one",
3428
3625
  eligible: allowingExpr(allFields, "field-ref"),
3429
- extras: { kind: z16.literal("field-ref") },
3626
+ extras: { kind: z17.literal("field-ref") },
3430
3627
  aid: "Expr_field-ref",
3431
3628
  describe: "A direct field reference."
3432
3629
  }, cache);
@@ -3448,7 +3645,7 @@ function semanticQuerySchema(types, depth, cache) {
3448
3645
  describe: "A semantic Type + field, resolved to that Type's single bound source, whose embedding is the query vector."
3449
3646
  }, cache);
3450
3647
  return orFold([
3451
- z16.string().describe("A literal natural-language query."),
3648
+ z17.string().describe("A literal natural-language query."),
3452
3649
  paramFragment(cache),
3453
3650
  sourceField,
3454
3651
  typeField
@@ -3459,7 +3656,7 @@ function semanticSchema(types, depth, cache) {
3459
3656
  keyName: "source",
3460
3657
  fieldMode: "optional",
3461
3658
  eligible: allowingExpr(semanticFieldsOf, "semantic"),
3462
- extras: { kind: z16.literal("semantic"), query: semanticQuerySchema(types, depth, cache) },
3659
+ extras: { kind: z17.literal("semantic"), query: semanticQuerySchema(types, depth, cache) },
3463
3660
  aid: "Expr_semantic",
3464
3661
  describe: "Semantic-similarity score (requires an embedder)."
3465
3662
  }, cache);
@@ -3470,8 +3667,8 @@ function textSearchSchema(types, depth, cache) {
3470
3667
  fieldMode: "optional",
3471
3668
  eligible: allowingExpr(textFieldsOf, "text-search"),
3472
3669
  extras: {
3473
- kind: z16.literal("text-search"),
3474
- 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.")
3475
3672
  },
3476
3673
  aid: "Expr_text-search",
3477
3674
  describe: "Full-text search predicate."
@@ -3483,8 +3680,8 @@ function textScoreSchema(types, depth, cache) {
3483
3680
  fieldMode: "optional",
3484
3681
  eligible: allowingExpr(textFieldsOf, "text-score"),
3485
3682
  extras: {
3486
- kind: z16.literal("text-score"),
3487
- 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.")
3488
3685
  },
3489
3686
  aid: "Expr_text-score",
3490
3687
  describe: "Numeric full-text relevance score (usable in SELECT / ORDER BY)."
@@ -3495,21 +3692,21 @@ function filtersSchema(types, depth, cache) {
3495
3692
  keyName: "source",
3496
3693
  fieldMode: "list",
3497
3694
  eligible: allowingExpr(allFields, "filters"),
3498
- extras: { kind: z16.literal("filters") },
3695
+ extras: { kind: z17.literal("filters") },
3499
3696
  aid: "Expr_filters",
3500
3697
  describe: "A structured filter placeholder; clauses are supplied at execution time."
3501
3698
  }, cache);
3502
3699
  }
3503
3700
  function sorterSchema(childExpr) {
3504
- const entry = z16.object({
3505
- 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`)."),
3506
3703
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir")
3507
3704
  });
3508
3705
  return withAid(
3509
- z16.object({
3510
- kind: z16.literal("sorter"),
3511
- sorts: z16.record(z16.string(), childExpr).describe("Named sortable expressions (sort name \u2192 expr); the caller selects by name at run time."),
3512
- 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.")
3513
3710
  }),
3514
3711
  "Expr_sorter"
3515
3712
  ).describe("A dynamic-sort catalog (valid only in a SELECT `order`); the selection is supplied at execution time.");
@@ -3529,7 +3726,7 @@ function insertRowSchema(type, fbOf, writes, Expr9) {
3529
3726
  const required = writes === "typed" && requiredOnInsert(f, fb);
3530
3727
  shape[f.name] = required ? value2 : value2.optional();
3531
3728
  }
3532
- 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).`);
3533
3730
  }
3534
3731
  function updateSetSchema(type, fbOf, writes, Expr9) {
3535
3732
  const shape = {};
@@ -3538,7 +3735,7 @@ function updateSetSchema(type, fbOf, writes, Expr9) {
3538
3735
  if (!f.updatableFor(fb)) continue;
3539
3736
  shape[f.name] = writeValueSchema(f, writes, Expr9).optional();
3540
3737
  }
3541
- 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).`);
3542
3739
  }
3543
3740
  function pickByNames(available, sel) {
3544
3741
  if (sel === "none") return [];
@@ -3601,11 +3798,11 @@ function shapeForKind(kind) {
3601
3798
  }
3602
3799
  }
3603
3800
  function windowOrderSchema(child) {
3604
- return z16.array(
3605
- z16.object({
3801
+ return z17.array(
3802
+ z17.object({
3606
3803
  expr: child,
3607
- dir: z16.enum(["asc", "desc"]),
3608
- nulls: z16.enum(["first", "last"]).optional()
3804
+ dir: z17.enum(["asc", "desc"]),
3805
+ nulls: z17.enum(["first", "last"]).optional()
3609
3806
  })
3610
3807
  );
3611
3808
  }
@@ -3613,31 +3810,31 @@ function functionObject(kind, functionField, argsField, child) {
3613
3810
  switch (kind) {
3614
3811
  case "function-call":
3615
3812
  return withAid(
3616
- z16.object({ kind: z16.literal("function-call"), function: functionField, args: argsField }),
3813
+ z17.object({ kind: z17.literal("function-call"), function: functionField, args: argsField }),
3617
3814
  "Expr_function-call"
3618
3815
  ).describe("A scalar function call with named arguments.");
3619
3816
  case "tabular-function-call":
3620
3817
  return withAid(
3621
- 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 }),
3622
3819
  "Expr_tabular-function-call"
3623
3820
  ).describe("A type-valued function call (produces rows).");
3624
3821
  case "aggregate":
3625
3822
  return withAid(
3626
- z16.object({
3627
- kind: z16.literal("aggregate"),
3823
+ z17.object({
3824
+ kind: z17.literal("aggregate"),
3628
3825
  function: functionField,
3629
3826
  args: argsField,
3630
- distinct: z16.boolean().optional()
3827
+ distinct: z17.boolean().optional()
3631
3828
  }),
3632
3829
  "Expr_aggregate"
3633
3830
  ).describe("Aggregate function over named args (count with empty args = count(*)).");
3634
3831
  case "window":
3635
3832
  return withAid(
3636
- z16.object({
3637
- kind: z16.literal("window"),
3833
+ z17.object({
3834
+ kind: z17.literal("window"),
3638
3835
  function: functionField,
3639
3836
  args: argsField,
3640
- partitionBy: z16.array(child).optional(),
3837
+ partitionBy: z17.array(child).optional(),
3641
3838
  orderBy: windowOrderSchema(child).optional()
3642
3839
  }),
3643
3840
  "Expr_window"
@@ -3653,7 +3850,7 @@ function typedArgsSchema(fn2, child, cache) {
3653
3850
  for (const param3 of fn2.params) {
3654
3851
  shape[param3.name] = param3.optional ? child.optional() : child;
3655
3852
  }
3656
- return z16.strictObject(shape).describe(`Named arguments for \`${fn2.name}\`.`);
3853
+ return z17.strictObject(shape).describe(`Named arguments for \`${fn2.name}\`.`);
3657
3854
  }
3658
3855
  function functionExprSchema(kind, openSchema, selected, depth, child, cache) {
3659
3856
  if (depth === "open" || !selected) return openSchema;
@@ -3662,7 +3859,7 @@ function functionExprSchema(kind, openSchema, selected, depth, child, cache) {
3662
3859
  const functionField = withAid(enumOf2(fns.map((f) => f.name)), "FunctionName").describe(
3663
3860
  "A selected function name."
3664
3861
  );
3665
- const argsField = withAid(z16.record(z16.string(), child), "FunctionArgs").describe(
3862
+ const argsField = withAid(z17.record(z17.string(), child), "FunctionArgs").describe(
3666
3863
  "Arguments keyed by declared parameter name."
3667
3864
  );
3668
3865
  return functionObject(kind, functionField, argsField, child);
@@ -3672,12 +3869,12 @@ function functionExprSchema(kind, openSchema, selected, depth, child, cache) {
3672
3869
  const argsObj = typedArgsSchema(fn2, child, cache);
3673
3870
  return functionObject(
3674
3871
  kind,
3675
- z16.literal(fn2.name).describe(`The \`${fn2.name}\` function.`),
3872
+ z17.literal(fn2.name).describe(`The \`${fn2.name}\` function.`),
3676
3873
  hasRequired ? argsObj : argsObj.optional(),
3677
3874
  child
3678
3875
  );
3679
3876
  });
3680
- return branches.length > 0 ? orFold(branches) : z16.never();
3877
+ return branches.length > 0 ? orFold(branches) : z17.never();
3681
3878
  }
3682
3879
  function exprKindApplicable(kind, types, selected) {
3683
3880
  switch (kind) {
@@ -3719,336 +3916,44 @@ function assertNeverFieldMode(value2) {
3719
3916
  throw new Error(`schema-build: unhandled ref field mode ${JSON.stringify(value2)}`);
3720
3917
  }
3721
3918
 
3722
- // src/queries/order.ts
3723
- var QueryOrder = class _QueryOrder {
3724
- /** Construct an ORDER BY term from its expr, direction, and optional nulls placement. */
3725
- constructor(expr, dir, nulls) {
3726
- this.expr = expr;
3727
- this.dir = dir;
3728
- this.nulls = nulls;
3729
- }
3730
- expr;
3731
- dir;
3732
- nulls;
3733
- /** Build a `QueryOrder` from its authored `OrderDef`. */
3734
- static from(def, registry) {
3735
- return new _QueryOrder(registry.parseExpr(def.expr), def.dir, def.nulls);
3736
- }
3737
- /**
3738
- * Owned structural {@link Shape} for an `OrderDef` (`{ expr, dir, nulls? }`) —
3739
- * the zod-free parallel to {@link from}. Never throws; accumulates. See
3740
- * `shape/`.
3741
- */
3742
- static SHAPE = obj(
3743
- {
3744
- expr: exprRef(),
3745
- dir: enumOf(["asc", "desc"], "OrderDir"),
3746
- nulls: enumOf(["first", "last"], "OrderNulls")
3747
- },
3748
- (v) => new _QueryOrder(v.expr, v.dir, v.nulls),
3749
- { optional: ["nulls"], aid: "Order" }
3750
- );
3751
- /**
3752
- * The per-row cost of this ORDER BY term — just its sort expression's cost.
3753
- * Mirrors {@link SorterExpr.cost} so a SELECT can cost every `order` entry
3754
- * uniformly (concrete term or dynamic sorter) without a type check.
3755
- */
3756
- cost(ctx, scope) {
3757
- return this.expr.cost(ctx, scope);
3758
- }
3759
- /** The exprs this term reads for `references` — a concrete term is just its own expr. */
3760
- referenceExprs(_spec) {
3761
- return [this.expr];
3762
- }
3763
- /** Serialize back to an `OrderDef`, omitting `nulls` when unset. */
3764
- toJSON() {
3765
- const def = { expr: this.expr.toJSON(), dir: this.dir };
3766
- if (this.nulls) def.nulls = this.nulls;
3767
- return def;
3768
- }
3769
- /** Deep-clone this term (cloning its expr). */
3770
- clone() {
3771
- return new _QueryOrder(this.expr.clone(), this.dir, this.nulls);
3772
- }
3773
- };
3774
- function sortByKeys(entries, terms) {
3775
- const decorated = [...entries];
3776
- decorated.sort((a, b) => {
3777
- for (let i = 0; i < terms.length; i++) {
3778
- const cmp = compareWithNulls(a.keys[i], b.keys[i], terms[i]);
3779
- if (cmp !== 0) return cmp;
3780
- }
3781
- return 0;
3782
- });
3783
- return decorated.map((d) => d.item);
3784
- }
3785
- async function sortEntries(entries, terms, ctx) {
3786
- const decorated = await Promise.all(
3787
- entries.map(async (e2) => {
3788
- const keys = [];
3789
- for (const t of terms) keys.push(await t.expr.evaluate(ctx, e2.row, e2.group));
3790
- return { item: e2.item, keys };
3791
- })
3792
- );
3793
- return sortByKeys(decorated, terms);
3794
- }
3795
- function compareWithNulls(a, b, term) {
3796
- const aNull = a.isNull();
3797
- const bNull = b.isNull();
3798
- if (aNull || bNull) {
3799
- if (aNull && bNull) return 0;
3800
- const nullsFirst = term.nulls ? term.nulls === "first" : term.dir === "asc";
3801
- const nullIsA = aNull ? -1 : 1;
3802
- return nullsFirst ? nullIsA : -nullIsA;
3803
- }
3804
- const cmp = a.compareTo(b);
3805
- return term.dir === "desc" ? -cmp : cmp;
3806
- }
3807
-
3808
- // src/exprs/sorter.ts
3809
- var sortEntryShape = obj(
3810
- {
3811
- sort: str("SortName"),
3812
- dir: enumOf(["asc", "desc"], "OrderDir")
3813
- },
3814
- (v) => ({ sort: v.sort, dir: v.dir }),
3815
- { aid: "SortEntry" }
3816
- );
3817
- var SorterExpr = class _SorterExpr extends Expr {
3818
- /** Wrap the catalog (`sorts`) and its optional multi-key `defaultSort`. */
3819
- 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) {
3820
3923
  super();
3821
- this.sorts = sorts;
3822
- this.defaultSort = defaultSort;
3924
+ this.source = source;
3925
+ this.field = field;
3823
3926
  }
3824
- sorts;
3825
- defaultSort;
3826
- static KIND = "sorter";
3927
+ source;
3928
+ field;
3929
+ static KIND = "field-ref";
3827
3930
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3828
- static INSTRUCTIONS = "A dynamic-sort catalog for a SELECT `order`: declare named `sorts` (+ optional `defaultSort`); the caller picks the sort at execution time.";
3829
- kind = _SorterExpr.KIND;
3830
- /** Reconstruct a SorterExpr from its JSON def (validates the `kind` discriminant). */
3831
- static from(json, registry) {
3832
- if (json.kind !== "sorter") {
3833
- throw new Error(`SorterExpr.from: expected 'sorter', got '${json.kind}'`);
3834
- }
3835
- const sorts = /* @__PURE__ */ new Map();
3836
- for (const name of Object.keys(json.sorts)) {
3837
- 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}'`);
3838
3937
  }
3839
- const defaultSort = json.defaultSort ? json.defaultSort.map((d) => ({ ...d })) : void 0;
3840
- return new _SorterExpr(sorts, defaultSort);
3938
+ return new _FieldRefExpr(json.source, json.field);
3841
3939
  }
3842
3940
  /**
3843
3941
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
3844
- * `SorterExpr` equal to `from`'s output on a valid def (`{ sorts, defaultSort? }`);
3845
- * accumulates on a bad def (never throws). The SELECTION is supplied at
3846
- * 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/`.
3847
3944
  */
3848
3945
  static SHAPE = obj(
3849
3946
  {
3850
- kind: lit("sorter"),
3851
- sorts: record(exprRef(), "Sorts"),
3852
- defaultSort: list(sortEntryShape)
3947
+ kind: lit("field-ref"),
3948
+ source: str("Source"),
3949
+ field: str("FieldName")
3853
3950
  },
3854
- (v) => new _SorterExpr(v.sorts, v.defaultSort),
3855
- { optional: ["defaultSort"], aid: "Expr_sorter" }
3951
+ (v) => new _FieldRefExpr(v.source, v.field),
3952
+ { aid: "Expr_field-ref" }
3856
3953
  );
3857
- /** 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`). */
3858
3955
  static toSchema(opts) {
3859
- return sorterSchema(childExprSchema(opts.Expr));
3860
- }
3861
- // ─── Resolution / validation ─────────────────────────────────────────────
3862
- /**
3863
- * A sorter is never a VALUE, so this is only reached when one is (invalidly)
3864
- * nested in a value position — already rejected by {@link validateWalk}. It
3865
- * resolves to a nullable text placeholder so a surrounding resolve never throws.
3866
- */
3867
- resolve(_engine, _scope) {
3868
- return textResult([], true);
3869
- }
3870
- /**
3871
- * A sorter reached as a general expression is MISPLACED — it is valid only in a
3872
- * select's `order` list (where the SELECT validates it via {@link validateInOrder}).
3873
- * Anywhere else (WHERE, a select field, a function arg, a `sorts` value, …) is
3874
- * a `sorter.misplaced` error.
3875
- */
3876
- validateWalk(_engine, _scope, p, _ctx) {
3877
- p.error("sorter.misplaced", "A `sorter` is only valid inside a SELECT's `order` list; it cannot be used here.");
3878
- return textResult([], true);
3879
- }
3880
- /**
3881
- * Validate a WELL-PLACED sorter (called by the SELECT for each `order` sorter):
3882
- * - `sorts` must be NON-EMPTY (`sorter.empty`);
3883
- * - each `sorts` value is validated EXACTLY like an order-by term's expr —
3884
- * against the SELECT's order scope + the same `ValidateContext` — so an
3885
- * `output` ref resolves and any non-orderable / relation-as-value expr is
3886
- * rejected there;
3887
- * - each `defaultSort[*].sort` must name a declared sort (`sorter.unknown-default`).
3888
- * The SQL-92 GROUP BY rule is applied to the `sorts` exprs by the SELECT itself
3889
- * (it owns the group-key set), mirroring how it treats an ordinary order term.
3890
- */
3891
- validateInOrder(engine, scope, p, ctx) {
3892
- if (this.sorts.size === 0) {
3893
- p.error("sorter.empty", "A `sorter` must declare at least one entry in `sorts`.");
3894
- }
3895
- p.at("sorts", () => {
3896
- for (const [name, expr] of this.sorts) {
3897
- p.at(name, () => expr.validateWalk(engine, scope, p, ctx));
3898
- }
3899
- });
3900
- if (this.defaultSort) {
3901
- p.at("defaultSort", () => {
3902
- this.defaultSort.forEach((d, i) => {
3903
- if (!this.sorts.has(d.sort)) {
3904
- p.at(
3905
- [i, "sort"],
3906
- () => p.error(
3907
- "sorter.unknown-default",
3908
- `defaultSort references '${d.sort}', which is not a declared sort.${didYouMean(d.sort, [...this.sorts.keys()])}`
3909
- )
3910
- );
3911
- }
3912
- });
3913
- });
3914
- }
3915
- }
3916
- // ─── Expansion (the order-by consumer's entry point) ──────────────────────
3917
- /**
3918
- * Expand this sorter against the runtime sort `spec` into concrete
3919
- * {@link QueryOrder} terms. A non-empty `spec` drives the terms (each `dir`
3920
- * defaults to `'asc'`); an empty / absent `spec` falls back to `defaultSort`;
3921
- * neither yields no terms. A selected `sort` name absent from `sorts` throws a
3922
- * loud `sort.unknown-name` runtime error (never silently dropped).
3923
- */
3924
- expand(spec) {
3925
- const chosen = spec && spec.length > 0 ? spec.map((s) => ({ sort: s.sort, dir: s.dir ?? "asc" })) : this.defaultSort ?? [];
3926
- return chosen.map(({ sort, dir }) => {
3927
- const expr = this.sorts.get(sort);
3928
- if (!expr) {
3929
- throw new Error(
3930
- `sort.unknown-name: unknown sort '${sort}'. Declared sorts: ${[...this.sorts.keys()].join(", ")}.`
3931
- );
3932
- }
3933
- return new QueryOrder(expr, dir, void 0);
3934
- });
3935
- }
3936
- // ─── Evaluation / cost / SQL (never reached for a well-placed sorter) ──────
3937
- //
3938
- // A sorter is NOT a value — it never evaluates / emits ITSELF. The real runtime
3939
- // + SQL sorting lives in `SelectQuery`: it calls `SorterExpr.expand(spec)` (via
3940
- // `SelectQuery.expandOrder(ctx.sortSpec)` — see select.ts, the ORDER BY phase of
3941
- // both `run` and `toSQL`) to turn the execution-time sort spec into concrete
3942
- // `QueryOrder[]`, then runs those through the SAME order-by comparator /
3943
- // ORDER BY emission an explicit `order` uses. The methods below are reachable
3944
- // ONLY for a MISPLACED sorter, which `validateWalk` has already rejected
3945
- // (`sorter.misplaced`); they just degrade harmlessly.
3946
- /** 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. */
3947
- async evaluate(_ctx, _row, _group) {
3948
- return Value.null();
3949
- }
3950
- /**
3951
- * A sorter's cost is the cost of the catalog entries it could sort BY: the
3952
- * caller's runtime selection ({@link CostContext.sort}) when supplied, else its
3953
- * `defaultSort`, else — as a worst case — its WHOLE catalog (any entry could be
3954
- * chosen at execution time). Each contributes its expr's own cost, so a sort
3955
- * key that is a SUBQUERY makes the sorter expensive (evaluated per sorted row
3956
- * by the SELECT), while sorting by a plain column stays cheap.
3957
- */
3958
- cost(ctx, scope) {
3959
- let c = ZERO_COST;
3960
- for (const expr of this.chosenSortExprs(ctx)) c = addCost(c, expr.cost(ctx, scope));
3961
- return c;
3962
- }
3963
- /**
3964
- * The catalog exprs a cost estimate should charge for: the caller's selected
3965
- * sorts (when a runtime `sort` is supplied), else the `defaultSort`'s sorts,
3966
- * else every catalog entry (worst case). Selected names absent from the catalog
3967
- * are skipped (they cost nothing here; a real run reports them loudly).
3968
- */
3969
- chosenSortExprs(ctx) {
3970
- return this.referenceExprs(ctx.sort);
3971
- }
3972
- /**
3973
- * The catalog exprs a caller's `sort` selection reads (for cost / references):
3974
- * the selected sorts when a `spec` is supplied, else the `defaultSort`'s sorts,
3975
- * else every catalog entry (worst case). Selected names absent from the catalog
3976
- * are skipped.
3977
- */
3978
- referenceExprs(spec) {
3979
- const pick = (entries) => entries.map((s) => this.sorts.get(s.sort)).filter((e2) => e2 !== void 0);
3980
- if (spec && spec.length > 0) return pick(spec);
3981
- if (this.defaultSort && this.defaultSort.length > 0) return pick(this.defaultSort);
3982
- return [...this.sorts.values()];
3983
- }
3984
- /** 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. */
3985
- toSQL(_dialect, _ctx) {
3986
- return SqlText.raw("NULL");
3987
- }
3988
- // ─── Traversal ─────────────────────────────────────────────────────────────
3989
- /** Visit each catalog (`sorts`) value expr. */
3990
- forEachChild(visit) {
3991
- for (const expr of this.sorts.values()) visit(expr);
3992
- }
3993
- // ─── Serialization ─────────────────────────────────────────────────────────
3994
- /** Serialize back to its JSON ExprDef. */
3995
- toJSON() {
3996
- const sorts = {};
3997
- for (const [name, expr] of this.sorts) sorts[name] = expr.toJSON();
3998
- const def = { kind: "sorter", sorts };
3999
- if (this.defaultSort) def.defaultSort = this.defaultSort.map((d) => ({ ...d }));
4000
- return def;
4001
- }
4002
- /** Deep-copy this expr (cloning each catalog expr). */
4003
- clone() {
4004
- const sorts = /* @__PURE__ */ new Map();
4005
- for (const [name, expr] of this.sorts) sorts.set(name, expr.clone());
4006
- return new _SorterExpr(sorts, this.defaultSort ? this.defaultSort.map((d) => ({ ...d })) : void 0);
4007
- }
4008
- /** Render as the readable `sorter(name1, name2, …)` DSL form. */
4009
- toCode() {
4010
- return `sorter(${[...this.sorts.keys()].join(", ")})`;
4011
- }
4012
- };
4013
-
4014
- // src/exprs/field-ref.ts
4015
- var FieldRefExpr = class _FieldRefExpr extends Expr {
4016
- /** Wrap a `<source>.<field>` reference by its source alias and field name. */
4017
- constructor(source, field) {
4018
- super();
4019
- this.source = source;
4020
- this.field = field;
4021
- }
4022
- source;
4023
- field;
4024
- static KIND = "field-ref";
4025
- /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4026
- 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.";
4027
- kind = _FieldRefExpr.KIND;
4028
- /** Reconstruct a FieldRefExpr from its JSON def (validates the `kind` discriminant). */
4029
- static from(json, _registry) {
4030
- if (json.kind !== "field-ref") {
4031
- throw new Error(`FieldRefExpr.from: expected 'field-ref', got '${json.kind}'`);
4032
- }
4033
- return new _FieldRefExpr(json.source, json.field);
4034
- }
4035
- /**
4036
- * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
4037
- * `FieldRefExpr` equal to `from`'s output on a valid def; accumulates
4038
- * problems on a bad def (never throws). See `shape/`.
4039
- */
4040
- static SHAPE = obj(
4041
- {
4042
- kind: lit("field-ref"),
4043
- source: str("Source"),
4044
- field: str("FieldName")
4045
- },
4046
- (v) => new _FieldRefExpr(v.source, v.field),
4047
- { aid: "Expr_field-ref" }
4048
- );
4049
- /** Depth-aware Zod schema for this expr kind's JSON shape (per `opts.depth.refs`). */
4050
- static toSchema(opts) {
4051
- return fieldRefSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
3956
+ return fieldRefSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
4052
3957
  }
4053
3958
  /** Resolve to the named field on the bound source, widening nullability by the source's. */
4054
3959
  resolve(engine, scope) {
@@ -4092,7 +3997,7 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4092
3997
  if (tf && !(tf.fieldType instanceof RelationFieldType)) {
4093
3998
  keyType = tf.fieldType;
4094
3999
  } else {
4095
- keyType = (ft.count === 1 ? target : ownerType).identityField().fieldType;
4000
+ keyType = (ft.isBelongsTo() ? target : ownerType).identityField().fieldType;
4096
4001
  }
4097
4002
  return { local: kp.local, foreign: kp.foreign, keyType };
4098
4003
  });
@@ -4103,6 +4008,7 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4103
4008
  keyType: keys[0].keyType,
4104
4009
  to: ft.to,
4105
4010
  count: ft.count,
4011
+ belongsTo: ft.isBelongsTo(),
4106
4012
  keys
4107
4013
  };
4108
4014
  const resolved = {
@@ -4142,10 +4048,8 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4142
4048
  checkFieldExpr(ctx.fieldExprKind ?? "field-ref", field, this.source, p);
4143
4049
  if (field.fieldType instanceof RelationFieldType) {
4144
4050
  const resolved2 = this.resolveRelation(engine, bound.type, field.fieldType, p);
4145
- if (!ctx.relationValueOk) {
4146
- const rel = relationOf(resolved2);
4147
- if (rel) p.error("ref.relation-not-value", relationAsValueMessage(rel));
4148
- }
4051
+ const rel = relationOf(resolved2);
4052
+ if (rel) this.checkRelationUse(rel, p, ctx);
4149
4053
  return resolved2;
4150
4054
  }
4151
4055
  const resolved = {
@@ -4157,6 +4061,29 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4157
4061
  };
4158
4062
  return resolved;
4159
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
+ }
4160
4087
  /** Zero rows; cost is just the resolved field's byte size. */
4161
4088
  cost(ctx, scope) {
4162
4089
  return { rows: 0, bytes: bytesOfResolved(this.resolve(ctx.engine, scope)) };
@@ -4167,6 +4094,24 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4167
4094
  }
4168
4095
  /** Read the field's runtime value, honoring backing (joins/compute/access security). */
4169
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) {
4170
4115
  if (!row) return Value.null();
4171
4116
  const rec = row[this.source] ?? ctx.correlation?.[this.source];
4172
4117
  const type = ctx.sourceType(this.source) ?? ctx.engine.type(this.source);
@@ -4189,6 +4134,18 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4189
4134
  }
4190
4135
  return value2;
4191
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
+ }
4192
4149
  /** Read a stored field off the bound record, attaching the conceptual field's metadata. */
4193
4150
  storedValue(rec, name, type) {
4194
4151
  if (!rec) return Value.null();
@@ -4279,6 +4236,20 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4279
4236
  }
4280
4237
  /** Emit as a SqlText column ref, lowering backing (joins/compute/access) when present. */
4281
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) {
4282
4253
  const bound = ctx.scope.lookup(this.source);
4283
4254
  const typeName = bound && bound.kind === "type" ? bound.type.name : void 0;
4284
4255
  const fb = typeName === void 0 ? void 0 : ctx.engine.fieldBacking(typeName, this.field);
@@ -4312,6 +4283,31 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4312
4283
  return assertNeverAccess(acc);
4313
4284
  }
4314
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
+ }
4315
4311
  /**
4316
4312
  * Register every named join this field opts into with the planner (SQL),
4317
4313
  * deduped on the join's deterministic alias so N fields sharing a join emit
@@ -4406,7 +4402,7 @@ function assertNeverJoinSpec(value2) {
4406
4402
  }
4407
4403
 
4408
4404
  // src/exprs/param.ts
4409
- import { z as z17 } from "zod";
4405
+ import { z as z18 } from "zod";
4410
4406
  var ParamExpr = class _ParamExpr extends Expr {
4411
4407
  /** Wrap a named bind parameter (its type is inferred from usage). */
4412
4408
  constructor(name) {
@@ -4441,9 +4437,9 @@ var ParamExpr = class _ParamExpr extends Expr {
4441
4437
  /** Zod schema for this expr kind's JSON shape. */
4442
4438
  static toSchema(_opts) {
4443
4439
  return withAid(
4444
- z17.object({
4445
- kind: z17.literal("param"),
4446
- 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.")
4447
4443
  }),
4448
4444
  "Expr_param"
4449
4445
  ).describe("A named bind parameter (contextually typed).");
@@ -4490,36 +4486,537 @@ var ParamExpr = class _ParamExpr extends Expr {
4490
4486
  }
4491
4487
  };
4492
4488
 
4493
- // src/exprs/binary.ts
4494
- import { z as z18 } from "zod";
4495
- var NUMERIC = /* @__PURE__ */ new Set(["number", "money"]);
4496
- var BINARY_OPS = ["+", "-", "*", "/", "%"];
4497
- function exempt(e2) {
4498
- 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;
4499
4492
  }
4500
- var BinaryExpr = class _BinaryExpr extends Expr {
4501
- /** Wrap an arithmetic operation over its operator and left/right operand exprs. */
4502
- constructor(op, left, right) {
4503
- super();
4504
- this.op = op;
4505
- this.left = left;
4506
- this.right = right;
4507
- }
4508
- op;
4509
- left;
4510
- right;
4511
- static KIND = "binary";
4512
- /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4513
- static INSTRUCTIONS = "Arithmetic `left <op> right` (`+ - * / %`).";
4514
- kind = _BinaryExpr.KIND;
4515
- /** Reconstruct a BinaryExpr from its JSON def (validates the `kind` discriminant). */
4516
- static from(json, registry) {
4517
- if (json.kind !== "binary") {
4518
- throw new Error(`BinaryExpr.from: expected 'binary', got '${json.kind}'`);
4519
- }
4520
- return new _BinaryExpr(
4521
- json.op,
4522
- 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),
4523
5020
  registry.parseExpr(json.right)
4524
5021
  );
4525
5022
  }
@@ -4542,9 +5039,9 @@ var BinaryExpr = class _BinaryExpr extends Expr {
4542
5039
  static toSchema(opts) {
4543
5040
  const child = childExprSchema(opts.Expr);
4544
5041
  return withAid(
4545
- z18.object({
4546
- kind: z18.literal("binary"),
4547
- op: withAid(z18.enum(["+", "-", "*", "/", "%"]), "BinaryOp"),
5042
+ z19.object({
5043
+ kind: z19.literal("binary"),
5044
+ op: withAid(z19.enum(["+", "-", "*", "/", "%"]), "BinaryOp"),
4548
5045
  left: child,
4549
5046
  right: child
4550
5047
  }),
@@ -4573,7 +5070,7 @@ var BinaryExpr = class _BinaryExpr extends Expr {
4573
5070
  /** Validate both operands are numeric (text ok for `+`), infer param types, then resolve. */
4574
5071
  validateWalk(engine, scope, p, ctx) {
4575
5072
  const here = p.here;
4576
- const opCtx = { ...ctx, relationValueOk: true };
5073
+ const opCtx = { ...ctx, relationUse: "compare" };
4577
5074
  const l = p.at("left", () => this.left.validateWalk(engine, scope, p, opCtx));
4578
5075
  const r = p.at("right", () => this.right.validateWalk(engine, scope, p, opCtx));
4579
5076
  const checkNumeric = (operand, rt, key) => {
@@ -4665,7 +5162,7 @@ function assertNeverOp(op) {
4665
5162
  }
4666
5163
 
4667
5164
  // src/exprs/unary.ts
4668
- import { z as z19 } from "zod";
5165
+ import { z as z20 } from "zod";
4669
5166
  var UNARY_OPS = ["-", "+"];
4670
5167
  var UnaryExpr = class _UnaryExpr extends Expr {
4671
5168
  /** Wrap a unary operation over its operator and operand expr. */
@@ -4704,9 +5201,9 @@ var UnaryExpr = class _UnaryExpr extends Expr {
4704
5201
  /** Zod schema for this expr kind's JSON shape (operand uses the shared child Expr schema). */
4705
5202
  static toSchema(opts) {
4706
5203
  return withAid(
4707
- z19.object({
4708
- kind: z19.literal("unary"),
4709
- op: withAid(z19.enum(["-", "+"]), "UnaryOp"),
5204
+ z20.object({
5205
+ kind: z20.literal("unary"),
5206
+ op: withAid(z20.enum(["-", "+"]), "UnaryOp"),
4710
5207
  operand: childExprSchema(opts.Expr)
4711
5208
  }),
4712
5209
  "Expr_unary"
@@ -4718,211 +5215,69 @@ var UnaryExpr = class _UnaryExpr extends Expr {
4718
5215
  /** Resolve to numeric/money mirroring the operand's category, propagating nullability/aggregate. */
4719
5216
  resolve(engine, scope) {
4720
5217
  const o = this.operand.resolve(engine, scope);
4721
- const sources = gatherSources([o]);
4722
- const nullable = o.kind !== "type" && o.nullable;
4723
- const aggregate2 = o.kind === "computed" && o.aggregate;
4724
- const fieldType = categoryOf(o) === "money" ? new MoneyFieldType() : new NumberFieldType();
4725
- return computed(fieldType, sources, nullable, aggregate2);
4726
- }
4727
- /** Validate the operand is numeric (NULL/param exempt), infer param type, then resolve. */
4728
- validateWalk(engine, scope, p, ctx) {
4729
- const o = p.at("operand", () => this.operand.validateWalk(engine, scope, p, ctx));
4730
- const exempt3 = this.operand instanceof LiteralExpr && this.operand.isNullLiteral() || this.operand instanceof ParamExpr;
4731
- if (!exempt3) {
4732
- const cat = categoryOf(o);
4733
- if (cat !== "number" && cat !== "money") {
4734
- p.at("operand", () => {
4735
- p.error("unary.type", `Unary '${this.op}' requires a numeric operand; got ${cat ?? "a type"}.`);
4736
- });
4737
- }
4738
- }
4739
- if (this.operand instanceof ParamExpr) {
4740
- scope.params.observe(this.operand.name, new NumberFieldType(), [...p.here, "operand"]);
4741
- }
4742
- return this.resolve(engine, scope);
4743
- }
4744
- /** Cost is the operand's cost. */
4745
- cost(ctx, scope) {
4746
- return this.childCost(ctx, scope);
4747
- }
4748
- /** Evaluate the operand and apply the sign (NULL/non-numeric → NULL). */
4749
- async evaluate(ctx, row, group) {
4750
- const v = await this.operand.evaluate(ctx, row, group);
4751
- if (v.isNull()) return Value.null();
4752
- const n = v.toNumber();
4753
- if (Number.isNaN(n)) return Value.null();
4754
- return Value.of(this.op === "-" ? -n : n);
4755
- }
4756
- /** Emit as a parenthesized `(op operand)` SqlText fragment. */
4757
- toSQL(dialect, ctx) {
4758
- return SqlText.concat([SqlText.raw(`(${this.op}`), this.operand.toSQL(dialect, ctx), SqlText.raw(")")]);
4759
- }
4760
- /** Serialize back to its JSON ExprDef. */
4761
- toJSON() {
4762
- return { kind: "unary", op: this.op, operand: this.operand.toJSON() };
4763
- }
4764
- /** Deep-copy this expr and its operand. */
4765
- clone() {
4766
- return new _UnaryExpr(this.op, this.operand.clone());
4767
- }
4768
- /** Render as source-like code (`-operand` / `+operand`). */
4769
- toCode() {
4770
- return `${this.op}${this.operand.toCode()}`;
4771
- }
4772
- };
4773
-
4774
- // src/exprs/comparison.ts
4775
- import { z as z20 } from "zod";
4776
-
4777
- // src/runtime/tri.ts
4778
- function not3(a) {
4779
- return a === void 0 ? void 0 : !a;
4780
- }
4781
- function and3(a, b) {
4782
- if (a === false || b === false) return false;
4783
- if (a === void 0 || b === void 0) return void 0;
4784
- return true;
4785
- }
4786
- function or3(a, b) {
4787
- if (a === true || b === true) return true;
4788
- if (a === void 0 || b === void 0) return void 0;
4789
- return false;
4790
- }
4791
- function triOf(v) {
4792
- return v.isNull() ? void 0 : v.toBoolean();
4793
- }
4794
-
4795
- // src/exprs/_relation-compare.ts
4796
- var HAS_MANY_ALIAS = "__rel";
4797
- function relationCompare(operand, engine, typeOf) {
4798
- const ref3 = operand.fieldRef();
4799
- if (!ref3) return void 0;
4800
- const owner = typeOf(ref3.source);
4801
- if (!owner) return void 0;
4802
- const field = owner.field(ref3.field);
4803
- if (!field || !(field.fieldType instanceof RelationFieldType)) return void 0;
4804
- const ft = field.fieldType;
4805
- const target = engine.type(ft.to);
4806
- if (!target) return void 0;
4807
- return { source: ref3.source, keys: ft.resolveKeys(engine, ref3.field, owner, target), count: ft.count, target };
4808
- }
4809
- function runtimeTypeOf(ctx) {
4810
- return (s) => ctx.sourceType(s) ?? ctx.engine.type(s);
4811
- }
4812
- function sqlTypeOf(ctx) {
4813
- return (s) => {
4814
- const b = ctx.scope.lookup(s);
4815
- return b && b.kind === "type" ? b.type : void 0;
4816
- };
4817
- }
4818
- function column(row, source, name, ctx) {
4819
- const rec = row[source] ?? ctx.correlation?.[source];
4820
- if (!rec) return Value.null();
4821
- return cell(rec, name);
4822
- }
4823
- async function tuple(operand, rel, keys, row, ctx, group) {
4824
- if (rel) return rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4825
- const v = await operand.evaluate(ctx, row, group);
4826
- if (v.isNull()) return keys.map(() => Value.null());
4827
- const raw2 = v.raw;
4828
- if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4829
- const obj2 = raw2;
4830
- return keys.map((k) => Value.of(obj2[k.foreign] ?? null));
4831
- }
4832
- return [v];
4833
- }
4834
- function eq3(a, b) {
4835
- if (a.isNull() || b.isNull()) return void 0;
4836
- return a.compareTo(b) === 0;
4837
- }
4838
- function cell(rec, name) {
4839
- return Value.of(rec[name] ?? null);
4840
- }
4841
- async function evaluateRelationCompare(op, left, right, leftRel, rightRel, row, ctx, group) {
4842
- const keys = (leftRel ?? rightRel).keys;
4843
- const lt2 = await tuple(left, leftRel, keys, row, ctx, group);
4844
- const rt = await tuple(right, rightRel, keys, row, ctx, group);
4845
- let acc = true;
4846
- for (let i = 0; i < keys.length; i++) acc = and3(acc, eq3(lt2[i], rt[i]));
4847
- return op === "=" ? acc : not3(acc);
4848
- }
4849
- async function valueTuple(value2, pkFields, row, ctx, group) {
4850
- const v = await value2.evaluate(ctx, row, group);
4851
- if (v.isNull()) return pkFields.map(() => Value.null());
4852
- const raw2 = v.raw;
4853
- if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4854
- const obj2 = raw2;
4855
- return pkFields.map((f) => Value.of(obj2[f] ?? null));
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);
4856
5223
  }
4857
- return [v];
4858
- }
4859
- async function evaluateHasMany(op, rel, value2, row, ctx, group) {
4860
- const pkFields = rel.target.primaryKey().map((f) => f.name);
4861
- const outer = rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4862
- const pkVals = await valueTuple(value2, pkFields, row, ctx, group);
4863
- if (outer.some((v) => v.isNull()) || pkVals.some((v) => v.isNull())) return op !== "=";
4864
- const rows = (await ctx.typeState(rel.target)).current;
4865
- const found = rows.some(
4866
- (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)
4867
- );
4868
- return op === "=" ? found : !found;
4869
- }
4870
- function tupleSql(operand, rel, keys, dialect, ctx) {
4871
- if (rel) return rel.keys.map((k) => new FieldRefExpr(rel.source, k.local).toSQL(dialect, ctx));
4872
- if (operand instanceof ParamExpr) {
4873
- const pv = ctx.params[operand.name];
4874
- if (pv !== null && pv !== void 0 && typeof pv === "object") {
4875
- const obj2 = pv;
4876
- return keys.map((k) => SqlText.param(obj2[k.foreign] ?? null));
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
+ }
4877
5235
  }
4878
- 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);
4879
5240
  }
4880
- return [operand.toSQL(dialect, ctx)];
4881
- }
4882
- function emitRelationCompare(op, left, right, leftRel, rightRel, dialect, ctx) {
4883
- const keys = (leftRel ?? rightRel).keys;
4884
- const ls = tupleSql(left, leftRel, keys, dialect, ctx);
4885
- const rs = tupleSql(right, rightRel, keys, dialect, ctx);
4886
- const eqs = keys.map((_, i) => SqlText.join([ls[i], SqlText.raw("="), rs[i]], " "));
4887
- const anded = SqlText.join(eqs, " AND ").parens();
4888
- return op === "=" ? anded : SqlText.concat([SqlText.raw("NOT "), anded]);
4889
- }
4890
- function valueComponentsSql(value2, pkFields, ctx) {
4891
- if (!(value2 instanceof ParamExpr)) return pkFields.map(() => null);
4892
- const pv = ctx.params[value2.name];
4893
- if (pv !== null && pv !== void 0 && typeof pv === "object") {
4894
- const obj2 = pv;
4895
- return pkFields.map((f) => obj2[f] ?? null);
5241
+ /** Cost is the operand's cost. */
5242
+ cost(ctx, scope) {
5243
+ return this.childCost(ctx, scope);
4896
5244
  }
4897
- return [pv ?? null];
4898
- }
4899
- function emitHasMany(op, rel, value2, dialect, ctx) {
4900
- const pkFields = rel.target.primaryKey().map((f) => f.name);
4901
- const comps = valueComponentsSql(value2, pkFields, ctx);
4902
- const eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
4903
- const col = (source, field) => ({ kind: "field-ref", source, field });
4904
- const where = [
4905
- // Correlation: each has-many key joins the target's FK-back column to this row's identity.
4906
- ...rel.keys.map((k) => eq2(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
4907
- // Membership: the target's PK equals the value's components.
4908
- ...pkFields.map((pk, i) => eq2(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
4909
- ];
4910
- const def = {
4911
- kind: "select",
4912
- // Project the target's PK column (a bare ref, no bound param) — EXISTS
4913
- // ignores the projected value, and `SELECT 1` would bind a stray literal.
4914
- fields: [{ expr: col(HAS_MANY_ALIAS, pkFields[0]) }],
4915
- from: { kind: "aliased", type: rel.target.name, as: HAS_MANY_ALIAS },
4916
- where
4917
- };
4918
- const sub2 = emitSubquerySQL(dialect, ctx, def);
4919
- return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub2]);
4920
- }
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";
4921
5273
 
4922
5274
  // src/exprs/_field-guard.ts
4923
- function operandCtx(operand, kind, ctx, relationOk = false) {
5275
+ function operandCtx(operand, kind, ctx, relationUse) {
4924
5276
  if (!(operand instanceof FieldRefExpr)) return ctx;
4925
- 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;
4926
5281
  }
4927
5282
 
4928
5283
  // src/exprs/comparison.ts
@@ -5020,9 +5375,9 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5020
5375
  static toSchema(opts) {
5021
5376
  const child = childExprSchema(opts.Expr);
5022
5377
  return withAid(
5023
- z20.object({
5024
- kind: z20.literal("comparison"),
5025
- 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"),
5026
5381
  left: child,
5027
5382
  right: child
5028
5383
  }),
@@ -5036,8 +5391,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5036
5391
  /** Validate operands (comparability, or text for the LIKE family), infer any bind param from the other operand, and resolve to bool. */
5037
5392
  validateWalk(engine, scope, p, ctx) {
5038
5393
  const here = p.here;
5039
- const l = p.at("left", () => this.left.validateWalk(engine, scope, p, operandCtx(this.left, "comparison", ctx, true)));
5040
- 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")));
5041
5396
  const lft = asFieldType(l);
5042
5397
  const rft = asFieldType(r);
5043
5398
  if (this.op !== "=" && this.op !== "<>" && (relationOf(l) || relationOf(r))) {
@@ -5045,8 +5400,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5045
5400
  }
5046
5401
  const lRel = relationOf(l);
5047
5402
  const rRel = relationOf(r);
5048
- if (lRel && rRel && (lRel.count > 1 || rRel.count > 1)) {
5049
- const set = lRel.count > 1 ? lRel : rRel;
5403
+ if (lRel && rRel && (!lRel.belongsTo || !rRel.belongsTo)) {
5404
+ const set = !lRel.belongsTo ? lRel : rRel;
5050
5405
  p.error(
5051
5406
  "comparison.relation-set",
5052
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}').`
@@ -5091,18 +5446,38 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5091
5446
  * equality and the equality-like ops (`= <> like notLike ilike`) keep ~a third.
5092
5447
  * An index-covered `=` is discounted separately by the cost model (via
5093
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`).
5094
5453
  */
5095
- selectivity() {
5454
+ selectivity(ctx, scope) {
5096
5455
  switch (this.op) {
5097
5456
  case "<":
5098
5457
  case "<=":
5099
5458
  case ">":
5100
5459
  case ">=":
5101
5460
  return RANGE_SELECTIVITY;
5461
+ case "=":
5462
+ return this.closedSetSelectivity(ctx, scope) ?? EQ_SELECTIVITY;
5102
5463
  default:
5103
5464
  return EQ_SELECTIVITY;
5104
5465
  }
5105
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
+ }
5106
5481
  /** An `=` against a column is an index point-probe (arity 1); other ops are not. */
5107
5482
  indexProbe() {
5108
5483
  if (this.op !== "=") return void 0;
@@ -5115,8 +5490,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5115
5490
  const typeOf = runtimeTypeOf(ctx);
5116
5491
  const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5117
5492
  const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5118
- if (leftRel && leftRel.count > 1) return evaluateHasMany(this.op, leftRel, this.right, row, ctx, group);
5119
- 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);
5120
5495
  if (leftRel || rightRel) {
5121
5496
  return evaluateRelationCompare(this.op, this.left, this.right, leftRel, rightRel, row, ctx, group);
5122
5497
  }
@@ -5162,8 +5537,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5162
5537
  const typeOf = sqlTypeOf(ctx);
5163
5538
  const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5164
5539
  const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5165
- if (leftRel && leftRel.count > 1) return emitHasMany(this.op, leftRel, this.right, dialect, ctx);
5166
- 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);
5167
5542
  if (leftRel || rightRel) {
5168
5543
  return emitRelationCompare(this.op, this.left, this.right, leftRel, rightRel, dialect, ctx);
5169
5544
  }
@@ -5201,7 +5576,7 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5201
5576
  };
5202
5577
 
5203
5578
  // src/exprs/logical.ts
5204
- import { z as z21 } from "zod";
5579
+ import { z as z22 } from "zod";
5205
5580
  var LOGICAL_OPS = ["and", "or", "not"];
5206
5581
  var LogicalExpr = class _LogicalExpr extends BoolExpr {
5207
5582
  /** Wrap a boolean connective (`and` / `or` / `not`) over its operands. */
@@ -5259,10 +5634,10 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
5259
5634
  /** Zod schema for this expr kind's JSON shape (operands are child Expr slots). */
5260
5635
  static toSchema(opts) {
5261
5636
  return withAid(
5262
- z21.object({
5263
- kind: z21.literal("logical"),
5264
- op: withAid(z21.enum(["and", "or", "not"]), "LogicalOp"),
5265
- 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))
5266
5641
  }),
5267
5642
  "Expr_logical"
5268
5643
  ).describe("Boolean connective (and / or / not).");
@@ -5366,7 +5741,7 @@ function assertNeverOp3(op) {
5366
5741
  }
5367
5742
 
5368
5743
  // src/exprs/in.ts
5369
- import { z as z22 } from "zod";
5744
+ import { z as z23 } from "zod";
5370
5745
 
5371
5746
  // src/exprs/_subquery.ts
5372
5747
  function inferSubqueryOutput(engine, scope, def) {
@@ -5505,11 +5880,11 @@ var InExpr = class _InExpr extends BoolExpr {
5505
5880
  /** Zod schema for this expr kind's JSON shape (`in` is a child Expr list or a child Query slot). */
5506
5881
  static toSchema(opts) {
5507
5882
  return withAid(
5508
- z22.object({
5509
- kind: z22.literal("in"),
5883
+ z23.object({
5884
+ kind: z23.literal("in"),
5510
5885
  value: childExprSchema(opts.Expr),
5511
- in: z22.union([z22.array(childExprSchema(opts.Expr)), childQuerySchema(opts.Query)]),
5512
- not: z22.boolean().optional()
5886
+ in: z23.union([z23.array(childExprSchema(opts.Expr)), childQuerySchema(opts.Query)]),
5887
+ not: z23.boolean().optional()
5513
5888
  }),
5514
5889
  "Expr_in"
5515
5890
  ).describe("Membership predicate (value IN list / subquery).");
@@ -5521,12 +5896,12 @@ var InExpr = class _InExpr extends BoolExpr {
5521
5896
  /** Validate that each list element / subquery output field is comparable with the value, infer params on either side, and resolve to bool. */
5522
5897
  validateWalk(engine, scope, p, ctx) {
5523
5898
  const here = p.here;
5524
- 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")));
5525
5900
  const vft = asFieldType(v);
5526
5901
  if (this.list) {
5527
5902
  p.at("in", () => {
5528
5903
  this.list.forEach((el, i) => {
5529
- 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")));
5530
5905
  const eft = asFieldType(rt);
5531
5906
  const skip = el instanceof ParamExpr || this.value instanceof ParamExpr;
5532
5907
  const relProblem = skip ? void 0 : relationValueProblem(v, rt);
@@ -5547,6 +5922,13 @@ var InExpr = class _InExpr extends BoolExpr {
5547
5922
  });
5548
5923
  });
5549
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
+ }
5550
5932
  const out = p.at("in", () => validateSubqueryOutput(engine, scope, p, ctx, this.subquery));
5551
5933
  const oft = asFieldType(out);
5552
5934
  if (!(this.value instanceof ParamExpr)) {
@@ -5594,7 +5976,7 @@ var InExpr = class _InExpr extends BoolExpr {
5594
5976
  const typeOf = runtimeTypeOf(ctx);
5595
5977
  const rel = relationCompare(this.value, ctx.engine, typeOf);
5596
5978
  if (rel && this.list) {
5597
- if (rel.count > 1) {
5979
+ if (!rel.belongsTo) {
5598
5980
  let found = false;
5599
5981
  for (const el of this.list) {
5600
5982
  if (await evaluateHasMany("=", rel, el, row, ctx, group)) {
@@ -5611,7 +5993,8 @@ var InExpr = class _InExpr extends BoolExpr {
5611
5993
  }
5612
5994
  return this.not ? not3(acc) : acc;
5613
5995
  }
5614
- 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);
5615
5998
  let matched = false;
5616
5999
  let anyNull = v.isNull();
5617
6000
  if (this.list) {
@@ -5643,17 +6026,16 @@ var InExpr = class _InExpr extends BoolExpr {
5643
6026
  const typeOf = sqlTypeOf(ctx);
5644
6027
  const rel = relationCompare(this.value, ctx.engine, typeOf);
5645
6028
  if (rel && this.list) {
5646
- 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(
5647
6030
  (el) => emitRelationCompare("=", this.value, el, rel, relationCompare(el, ctx.engine, typeOf), dialect, ctx)
5648
6031
  );
5649
6032
  const anded = SqlText.join(ors, " OR ").parens();
5650
6033
  return this.not ? SqlText.concat([SqlText.raw("NOT "), anded]) : anded;
5651
6034
  }
5652
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("()");
5653
- return SqlText.join(
5654
- [this.value.toSQL(dialect, ctx), SqlText.raw(this.not ? "NOT IN" : "IN"), rhs],
5655
- " "
5656
- );
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], " ");
5657
6039
  }
5658
6040
  /** Serialize back to its JSON ExprDef. */
5659
6041
  toJSON() {
@@ -5679,7 +6061,7 @@ var InExpr = class _InExpr extends BoolExpr {
5679
6061
  };
5680
6062
 
5681
6063
  // src/exprs/between.ts
5682
- import { z as z23 } from "zod";
6064
+ import { z as z24 } from "zod";
5683
6065
  var BetweenExpr = class _BetweenExpr extends BoolExpr {
5684
6066
  /** Wrap `value [NOT] BETWEEN lower AND upper` as a range predicate. */
5685
6067
  constructor(value2, lower2, upper, not2) {
@@ -5730,12 +6112,12 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
5730
6112
  static toSchema(opts) {
5731
6113
  const child = childExprSchema(opts.Expr);
5732
6114
  return withAid(
5733
- z23.object({
5734
- kind: z23.literal("between"),
6115
+ z24.object({
6116
+ kind: z24.literal("between"),
5735
6117
  value: child,
5736
6118
  lower: child,
5737
6119
  upper: child,
5738
- not: z23.boolean().optional()
6120
+ not: z24.boolean().optional()
5739
6121
  }),
5740
6122
  "Expr_between"
5741
6123
  ).describe("Range predicate (value BETWEEN lower AND upper).");
@@ -5748,9 +6130,9 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
5748
6130
  /** Validate that both bounds are comparable with the value, infer any bound/value param, and resolve to bool. */
5749
6131
  validateWalk(engine, scope, p, ctx) {
5750
6132
  const here = p.here;
5751
- const v = p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "between", ctx, true)));
5752
- const lo = p.at("lower", () => this.lower.validateWalk(engine, scope, p, operandCtx(this.lower, "between", ctx, true)));
5753
- 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")));
5754
6136
  const vft = asFieldType(v);
5755
6137
  const check = (operand, rt, key) => {
5756
6138
  const ft = asFieldType(rt);
@@ -5835,7 +6217,7 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
5835
6217
  };
5836
6218
 
5837
6219
  // src/exprs/is-null.ts
5838
- import { z as z24 } from "zod";
6220
+ import { z as z25 } from "zod";
5839
6221
  var IsNullExpr = class _IsNullExpr extends BoolExpr {
5840
6222
  /** Wrap `value IS [NOT] NULL` as a null test. */
5841
6223
  constructor(value2, not2) {
@@ -5874,10 +6256,10 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5874
6256
  /** Zod schema for this expr kind's JSON shape (value is a child Expr slot). */
5875
6257
  static toSchema(opts) {
5876
6258
  return withAid(
5877
- z24.object({
5878
- kind: z24.literal("is-null"),
6259
+ z25.object({
6260
+ kind: z25.literal("is-null"),
5879
6261
  value: childExprSchema(opts.Expr),
5880
- not: z24.boolean().optional()
6262
+ not: z25.boolean().optional()
5881
6263
  }),
5882
6264
  "Expr_is-null"
5883
6265
  ).describe("Null test (value IS [NOT] NULL).");
@@ -5892,7 +6274,7 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5892
6274
  }
5893
6275
  /** Validate the operand and resolve to a non-nullable bool. */
5894
6276
  validateWalk(engine, scope, p, ctx) {
5895
- 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")));
5896
6278
  return this.resolve(engine, scope);
5897
6279
  }
5898
6280
  /** A null test keeps ~a third of the rows (equality-like selectivity). */
@@ -5904,8 +6286,23 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5904
6286
  const v = await this.value.evaluate(ctx, row, group);
5905
6287
  return this.not ? !v.isNull() : v.isNull();
5906
6288
  }
5907
- /** 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
+ */
5908
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
+ }
5909
6306
  return SqlText.concat([
5910
6307
  this.value.toSQL(dialect, ctx),
5911
6308
  SqlText.raw(this.not ? " IS NOT NULL" : " IS NULL")
@@ -5928,7 +6325,7 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5928
6325
  };
5929
6326
 
5930
6327
  // src/exprs/exists.ts
5931
- import { z as z25 } from "zod";
6328
+ import { z as z26 } from "zod";
5932
6329
  var ExistsExpr = class _ExistsExpr extends BoolExpr {
5933
6330
  /** Wrap `[NOT] EXISTS (query)` as an existence predicate over a subquery. */
5934
6331
  constructor(query, not2) {
@@ -6028,10 +6425,10 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
6028
6425
  /** Zod schema for this expr kind's JSON shape (uses a child Query slot for the subquery). */
6029
6426
  static toSchema(opts) {
6030
6427
  return withAid(
6031
- z25.object({
6032
- kind: z25.literal("exists"),
6428
+ z26.object({
6429
+ kind: z26.literal("exists"),
6033
6430
  query: childQuerySchema(opts.Query),
6034
- not: z25.boolean().optional()
6431
+ not: z26.boolean().optional()
6035
6432
  }),
6036
6433
  "Expr_exists"
6037
6434
  ).describe("Existence predicate over a subquery.");
@@ -6081,7 +6478,7 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
6081
6478
  };
6082
6479
 
6083
6480
  // src/exprs/array-op.ts
6084
- import { z as z26 } from "zod";
6481
+ import { z as z27 } from "zod";
6085
6482
  var NO_VALUE_OPS = /* @__PURE__ */ new Set(["isEmpty", "notEmpty"]);
6086
6483
  var SINGLE_VALUE_OPS = /* @__PURE__ */ new Set(["contains"]);
6087
6484
  var LIST_VALUE_OPS = /* @__PURE__ */ new Set(["containsAny", "containsAll"]);
@@ -6144,9 +6541,9 @@ var ArrayOpExpr = class _ArrayOpExpr extends BoolExpr {
6144
6541
  static toSchema(opts) {
6145
6542
  const child = childExprSchema(opts.Expr);
6146
6543
  return withAid(
6147
- z26.object({
6148
- kind: z26.literal("array-op"),
6149
- 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(
6150
6547
  "Array predicate: element membership / overlap / emptiness."
6151
6548
  ),
6152
6549
  // The target is the recursive `Expr` union (`opts.Expr` is a shared
@@ -6159,7 +6556,7 @@ var ArrayOpExpr = class _ArrayOpExpr extends BoolExpr {
6159
6556
  // expr class threads `childExprSchema(opts.Expr)` in bare — see #array-op
6160
6557
  // overflow.) The wrapping object's own `.describe` still documents the kind.
6161
6558
  target: child,
6162
- 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).")
6163
6560
  }),
6164
6561
  "Expr_array-op"
6165
6562
  ).describe("Array containment / emptiness predicate.");
@@ -6316,7 +6713,7 @@ function assertNever2(value2) {
6316
6713
  }
6317
6714
 
6318
6715
  // src/exprs/case.ts
6319
- import { z as z27 } from "zod";
6716
+ import { z as z28 } from "zod";
6320
6717
  var BRANCH_SHAPE = obj(
6321
6718
  { when: exprRef(), then: exprRef() },
6322
6719
  (v) => ({ when: v.when, then: v.then }),
@@ -6366,9 +6763,9 @@ var CaseExpr = class _CaseExpr extends Expr {
6366
6763
  static toSchema(opts) {
6367
6764
  const child = childExprSchema(opts.Expr);
6368
6765
  return withAid(
6369
- z27.object({
6370
- kind: z27.literal("case"),
6371
- 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 })),
6372
6769
  else: child.optional()
6373
6770
  }),
6374
6771
  "Expr_case"
@@ -6483,17 +6880,17 @@ var CaseExpr = class _CaseExpr extends Expr {
6483
6880
  };
6484
6881
 
6485
6882
  // src/exprs/aggregate.ts
6486
- import { z as z29 } from "zod";
6883
+ import { z as z30 } from "zod";
6487
6884
 
6488
6885
  // src/exprs/_function-args.ts
6489
- import { z as z28 } from "zod";
6886
+ import { z as z29 } from "zod";
6490
6887
  function parseNamedArgs(json, registry) {
6491
6888
  const out = /* @__PURE__ */ new Map();
6492
6889
  for (const [name, def] of Object.entries(json)) out.set(name, registry.parseExpr(def));
6493
6890
  return out;
6494
6891
  }
6495
6892
  function namedArgSchema(child) {
6496
- return withAid(z28.record(z28.string(), child), "FunctionArgs").describe(
6893
+ return withAid(z29.record(z29.string(), child), "FunctionArgs").describe(
6497
6894
  "Arguments keyed by declared parameter name."
6498
6895
  );
6499
6896
  }
@@ -6678,11 +7075,11 @@ var AggregateExpr = class _AggregateExpr extends Expr {
6678
7075
  static toSchema(opts) {
6679
7076
  const child = childExprSchema(opts.Expr);
6680
7077
  const open = withAid(
6681
- z29.object({
6682
- kind: z29.literal("aggregate"),
6683
- 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(*))."),
6684
7081
  args: namedArgSchema(child),
6685
- distinct: z29.boolean().optional()
7082
+ distinct: z30.boolean().optional()
6686
7083
  }),
6687
7084
  "Expr_aggregate"
6688
7085
  ).describe("Aggregate function over named args (count with empty args = count(*)).");
@@ -6829,7 +7226,7 @@ function substituteArgs(template, args) {
6829
7226
  }
6830
7227
 
6831
7228
  // src/exprs/window.ts
6832
- import { z as z30 } from "zod";
7229
+ import { z as z31 } from "zod";
6833
7230
  var ORDER_SHAPE = obj(
6834
7231
  {
6835
7232
  expr: exprRef(),
@@ -6914,16 +7311,16 @@ var WindowExpr = class _WindowExpr extends Expr {
6914
7311
  static toSchema(opts) {
6915
7312
  const child = childExprSchema(opts.Expr);
6916
7313
  const open = withAid(
6917
- z30.object({
6918
- kind: z30.literal("window"),
6919
- 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."),
6920
7317
  args: namedArgSchema(child),
6921
- partitionBy: z30.array(child).optional(),
6922
- orderBy: z30.array(
6923
- z30.object({
7318
+ partitionBy: z31.array(child).optional(),
7319
+ orderBy: z31.array(
7320
+ z31.object({
6924
7321
  expr: child,
6925
- dir: withAid(z30.enum(["asc", "desc"]), "OrderDir"),
6926
- 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()
6927
7324
  })
6928
7325
  ).optional()
6929
7326
  }),
@@ -7110,7 +7507,7 @@ var WindowExpr = class _WindowExpr extends Expr {
7110
7507
  };
7111
7508
 
7112
7509
  // src/exprs/function-call.ts
7113
- import { z as z31 } from "zod";
7510
+ import { z as z32 } from "zod";
7114
7511
  var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7115
7512
  /** Wrap a registered scalar `fn` with its named `args`. */
7116
7513
  constructor(fn2, args) {
@@ -7161,9 +7558,9 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7161
7558
  static toSchema(opts) {
7162
7559
  const child = childExprSchema(opts.Expr);
7163
7560
  const open = withAid(
7164
- z31.object({
7165
- kind: z31.literal("function-call"),
7166
- 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."),
7167
7564
  args: namedArgSchema(child)
7168
7565
  }),
7169
7566
  "Expr_function-call"
@@ -7250,7 +7647,7 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7250
7647
  };
7251
7648
 
7252
7649
  // src/exprs/tabular-function-call.ts
7253
- import { z as z32 } from "zod";
7650
+ import { z as z33 } from "zod";
7254
7651
  var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7255
7652
  /** Wrap a registered tabular `fn` with its named `args`. */
7256
7653
  constructor(fn2, args) {
@@ -7290,9 +7687,9 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7290
7687
  static toSchema(opts) {
7291
7688
  const child = childExprSchema(opts.Expr);
7292
7689
  const open = withAid(
7293
- z32.object({
7294
- kind: z32.literal("tabular-function-call"),
7295
- 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."),
7296
7693
  args: namedArgSchema(child)
7297
7694
  }),
7298
7695
  "Expr_tabular-function-call"
@@ -7384,6 +7781,27 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7384
7781
  }
7385
7782
  };
7386
7783
 
7784
+ // src/vector-text.ts
7785
+ function embeddingResolver(embeddings) {
7786
+ return typeof embeddings === "function" ? embeddings : (text) => embeddings.get(text);
7787
+ }
7788
+ function isVectorText(text) {
7789
+ const t = text.trim();
7790
+ return t.startsWith("[") && t.endsWith("]");
7791
+ }
7792
+ function toVectorText(vector) {
7793
+ return `[${vector.join(",")}]`;
7794
+ }
7795
+ function parseVectorText(text) {
7796
+ const t = text.trim();
7797
+ if (!isVectorText(t)) {
7798
+ throw new Error(`parseVectorText: expected pgvector text '[\u2026]', got ${JSON.stringify(text)}.`);
7799
+ }
7800
+ const inner = t.slice(1, -1).trim();
7801
+ if (inner.length === 0) return [];
7802
+ return inner.split(",").map((part) => Number(part.trim()));
7803
+ }
7804
+
7387
7805
  // src/exprs/semantic.ts
7388
7806
  function cosine(a, b) {
7389
7807
  const n = Math.min(a.length, b.length);
@@ -7613,14 +8031,29 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7613
8031
  return SEMANTIC_ROW_PENALTY;
7614
8032
  }
7615
8033
  /**
7616
- * Embed the query side into a vector (null when unavailable), using the
7617
- * `SemanticBacking`'s `embedder` override when supplied, else the run / engine
7618
- * embedder.
8034
+ * Resolve the query side into a vector (null when unavailable). A caller-supplied
8035
+ * precomputed embeddings cache (`ctx.resolveEmbedding`, mirroring the SQL path's
8036
+ * `toSQL({ embeddings })`) takes precedence when present — the term's vector is
8037
+ * looked up synchronously; a pre-embedded `[…]` value short-circuits the lookup.
8038
+ * A term MISSING from the cache throws (fail loud). With no cache it falls back
8039
+ * to the `SemanticBacking`'s `embedder` override, else the run / engine embedder
8040
+ * (unchanged existing behavior).
7619
8041
  */
7620
8042
  async queryVector(ctx, q, embedder) {
7621
- if (q.kind === "text") return this.embedText(ctx, q.text, embedder);
7622
- const text = ctx.param(q.param.name).toText();
7623
- return text.length > 0 ? this.embedText(ctx, text, embedder) : null;
8043
+ const text = q.kind === "text" ? q.text : ctx.param(q.param.name).toText();
8044
+ if (text.length === 0) return null;
8045
+ const resolve = ctx.resolveEmbedding;
8046
+ if (resolve) {
8047
+ if (isVectorText(text)) return parseVectorText(text);
8048
+ const vector = resolve(text);
8049
+ if (vector === void 0) {
8050
+ throw new Error(
8051
+ `SemanticExpr.evaluate: no embedding supplied for the semantic term ${JSON.stringify(text)}. Collect the terms with 'engine.semanticTexts(query, opts)', embed each, and pass them via 'run({ embeddings })' (a text\u2192vector Map).`
8052
+ );
8053
+ }
8054
+ return [...vector];
8055
+ }
8056
+ return this.embedText(ctx, text, embedder);
7624
8057
  }
7625
8058
  /** Embed `text` via the backing's `embedder` override, else the run's embedder (cached). */
7626
8059
  async embedText(ctx, text, embedder) {
@@ -7648,7 +8081,7 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7648
8081
  const type = this.boundType(ctx);
7649
8082
  const backing = type ? ctx.engine.semanticBacking(type.name, this.field) : void 0;
7650
8083
  const embedder = backing?.embedder;
7651
- if (!embedder && !ctx.hasEmbedder()) return Value.of(0);
8084
+ if (!embedder && !ctx.hasEmbedder() && !ctx.resolveEmbedding) return Value.of(0);
7652
8085
  const queryVec = await this.queryVector(ctx, q, embedder);
7653
8086
  if (!queryVec) return Value.of(0);
7654
8087
  const rec = row[this.source] ?? ctx.correlation?.[this.source];
@@ -7781,11 +8214,44 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7781
8214
  if (!bound || bound.kind !== "type") return void 0;
7782
8215
  return ctx.engine.semanticBacking(bound.type.name, field);
7783
8216
  }
7784
- /** The query side of the similarity, emitted for SQL (text / param only). */
7785
- querySQL(dialect, ctx) {
7786
- if (this.query.kind === "text") return SqlText.param(this.query.text);
7787
- if (this.query.kind !== "param") return SqlText.raw("0");
7788
- return this.query.param.toSQL(dialect, ctx);
8217
+ /**
8218
+ * The query side of the similarity, emitted for SQL (text / param only). A
8219
+ * `semantic(...)` term is TEXT — never a raw embedding — so a literal (and a
8220
+ * plain-text param VALUE) is EMBEDDED into a pgvector TEXT literal (`[…]`) via
8221
+ * the caller's `ctx.semanticText` converter before it is bound; the dialect
8222
+ * then casts it `::vector`. Two existing valid inputs are preserved untouched:
8223
+ * a PRE-EMBEDDED vector-text term / param (already `[…]`) is bound as-is, and a
8224
+ * `null` / absent param binds `null`. When a plain-text term is hit but NO
8225
+ * embeddings cache was supplied — or the term is missing from it — this THROWS
8226
+ * (rather than emitting the invalid `'<text>'::vector`).
8227
+ */
8228
+ querySQL(_dialect, ctx) {
8229
+ const q = this.query;
8230
+ if (q.kind === "text") {
8231
+ if (isVectorText(q.text)) return SqlText.param(q.text);
8232
+ return SqlText.param(this.vectorTextForSql(ctx, q.text));
8233
+ }
8234
+ if (q.kind !== "param") return SqlText.raw("0");
8235
+ const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, q.param.name) ? ctx.params[q.param.name] : null;
8236
+ if (raw2 === null || typeof raw2 === "object") return SqlText.param(null);
8237
+ const text = String(raw2);
8238
+ if (isVectorText(text)) return SqlText.param(text);
8239
+ return SqlText.param(this.vectorTextForSql(ctx, text));
8240
+ }
8241
+ /**
8242
+ * Resolve a plain-text semantic term to its pgvector TEXT literal via the
8243
+ * caller's precomputed embeddings (`ctx.semanticText`, built from
8244
+ * `toSQL({ embeddings })`), or THROW a directed error when no cache was
8245
+ * supplied. The converter itself throws when the cache lacks THIS term.
8246
+ */
8247
+ vectorTextForSql(ctx, text) {
8248
+ const convert = ctx.semanticText;
8249
+ if (!convert) {
8250
+ throw new Error(
8251
+ `SemanticExpr.toSQL: the semantic term ${JSON.stringify(text)} is plain text, not a vector, and cannot be bound as-is (Postgres cannot cast '<text>'::vector). Collect the terms with 'engine.semanticTexts(query, opts)', embed each, and pass them via 'engine.toSQL(query, dialect, { embeddings })' \u2014 or pass the query vector as a pre-embedded '[\u2026]' vector-text param.`
8252
+ );
8253
+ }
8254
+ return convert(text);
7789
8255
  }
7790
8256
  /** Serialize back to its JSON ExprDef. */
7791
8257
  toJSON() {
@@ -7854,15 +8320,13 @@ function boundTypeOf(ctx, source) {
7854
8320
  function searchColumn(dialect, ctx, source, field) {
7855
8321
  if (field !== void 0) return dialect.field(source, field);
7856
8322
  const bound = ctx.scope.lookup(source);
7857
- if (bound && bound.kind === "type") {
7858
- const searchable = bound.type.fields.find(
7859
- (f) => f.fieldType instanceof TextFieldType && f.fieldType.options.search === true
7860
- );
7861
- if (searchable) return dialect.field(source, searchable.name);
7862
- const text = bound.type.fields.find((f) => f.fieldType.resolve() === "text");
7863
- if (text) return dialect.field(source, text.name);
7864
- }
7865
- 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
+ });
7866
8330
  }
7867
8331
  function searchBackingOf(ctx, source, field) {
7868
8332
  const bound = ctx.scope.lookup(source);
@@ -7966,6 +8430,11 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
7966
8430
  } else if (this.field === void 0) {
7967
8431
  if (!bound.type.isSearchable()) {
7968
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
+ );
7969
8438
  }
7970
8439
  } else {
7971
8440
  const fieldName = this.field;
@@ -8120,6 +8589,11 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
8120
8589
  } else if (this.field === void 0) {
8121
8590
  if (!bound.type.isSearchable()) {
8122
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
+ );
8123
8597
  }
8124
8598
  } else {
8125
8599
  const fieldName = this.field;
@@ -8346,7 +8820,7 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
8346
8820
  };
8347
8821
 
8348
8822
  // src/exprs/subquery.ts
8349
- import { z as z33 } from "zod";
8823
+ import { z as z34 } from "zod";
8350
8824
  var SubqueryExpr = class _SubqueryExpr extends Expr {
8351
8825
  /** Wrap the inner query def evaluated in value position. */
8352
8826
  constructor(query) {
@@ -8434,8 +8908,8 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
8434
8908
  /** Zod schema for this expr kind's JSON shape. */
8435
8909
  static toSchema(opts) {
8436
8910
  return withAid(
8437
- z33.object({
8438
- kind: z33.literal("subquery"),
8911
+ z34.object({
8912
+ kind: z34.literal("subquery"),
8439
8913
  query: childQuerySchema(opts.Query)
8440
8914
  }),
8441
8915
  "Expr_subquery"
@@ -8481,7 +8955,7 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
8481
8955
  };
8482
8956
 
8483
8957
  // src/exprs/excluded.ts
8484
- import { z as z34 } from "zod";
8958
+ import { z as z35 } from "zod";
8485
8959
  var EXCLUDED_SOURCE = "excluded";
8486
8960
  var ExcludedExpr = class _ExcludedExpr extends Expr {
8487
8961
  /** Wrap the proposed-row column name this reference reads. */
@@ -8518,9 +8992,9 @@ var ExcludedExpr = class _ExcludedExpr extends Expr {
8518
8992
  /** Zod schema for this expr kind's JSON shape. */
8519
8993
  static toSchema(_opts) {
8520
8994
  return withAid(
8521
- z34.object({
8522
- kind: z34.literal("excluded"),
8523
- 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.")
8524
8998
  }),
8525
8999
  "Expr_excluded"
8526
9000
  ).describe("The proposed row inside an INSERT ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
@@ -8612,7 +9086,7 @@ var BUILTIN_EXPRS = [
8612
9086
  function exprDefSchema(opts = {}) {
8613
9087
  const branches = BUILTIN_EXPRS.map((c) => c.toSchema(opts));
8614
9088
  const first = branches[0];
8615
- if (!first) return z35.never();
9089
+ if (!first) return z36.never();
8616
9090
  return branches.slice(1).reduce((acc, s) => acc.or(s), first).describe("Expression definition (one of the built-in expression kinds).");
8617
9091
  }
8618
9092
 
@@ -8873,6 +9347,7 @@ var Query = class {
8873
9347
  };
8874
9348
  function makeField(name, type) {
8875
9349
  const ft = asFieldType(type);
9350
+ if (relationOf(type)?.belongsTo) return { name, type, nullable: true, fieldType: "json" };
8876
9351
  const fieldType = ft ? ft.resolve() : "type";
8877
9352
  const nullable = type.kind !== "type" && type.nullable;
8878
9353
  return { name, type, nullable, fieldType };
@@ -8882,8 +9357,8 @@ function toArrayRows(fields, rows) {
8882
9357
  }
8883
9358
  function syntheticType(name, fields) {
8884
9359
  const built = fields.map((c) => {
8885
- const ft = asFieldType(c.type) ?? new TextFieldType();
8886
- 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;
8887
9362
  return new Field({ name: c.name, fieldType: ft, nullable });
8888
9363
  });
8889
9364
  return new Type({ name, fields: built, indexes: [], count: 0, bytes: 0 });
@@ -9518,6 +9993,12 @@ function boundShape() {
9518
9993
  }
9519
9994
 
9520
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
+ }
9521
10002
  function scanCost(type) {
9522
10003
  return { rows: type.count, bytes: type.count * type.bytes };
9523
10004
  }
@@ -9535,76 +10016,82 @@ function probesOf(conjuncts) {
9535
10016
  }
9536
10017
  return probes;
9537
10018
  }
9538
- function indexPartDigests(type) {
10019
+ function indexPartDigests(at) {
9539
10020
  const digests = /* @__PURE__ */ new Set();
9540
- 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);
9541
10022
  return digests;
9542
10023
  }
9543
- function bestPrefixReduction(type, refs) {
9544
- 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;
9545
10030
  let best;
9546
- for (const idx of type.indexes) {
9547
- 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 });
9548
10033
  if (r === void 0) continue;
9549
10034
  best = best === void 0 ? r : Math.min(best, r);
9550
10035
  }
9551
10036
  return best;
9552
10037
  }
9553
- function indexArityFactor(partDigests, probes) {
10038
+ function indexArityFactor(partDigests, probes, at) {
9554
10039
  let factor = 1;
9555
- for (const pr of probes) {
9556
- 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;
9557
10042
  }
9558
10043
  return factor;
9559
10044
  }
9560
- function applyWhere(ctx, scope, base, type, where, perRowBytes) {
10045
+ function applyWhere(ctx, scope, base, at, where, perRowBytes) {
9561
10046
  const conjuncts = conjunctsOf(ctx, scope, where);
9562
- const rows = reduceRows(ctx, scope, type, base.rows, conjuncts);
10047
+ const rows = reduceRows(ctx, scope, at, base.rows, conjuncts);
9563
10048
  const penalty = conjuncts.reduce((sum2, c) => sum2 + c.totalScanRowPenalty(), 0) * base.rows;
9564
10049
  return { rows, bytes: rows * perRowBytes + penalty };
9565
10050
  }
9566
- function reduceRows(ctx, scope, type, baseRows, conjuncts) {
10051
+ function reduceRows(ctx, scope, at, baseRows, conjuncts) {
9567
10052
  const probes = probesOf(conjuncts);
9568
- const partDigests = indexPartDigests(type);
9569
- const reduction = bestPrefixReduction(type, probes.map((p) => p.ref));
10053
+ const partDigests = indexPartDigests(at);
10054
+ const reduction = bestPrefixReduction(at, probes.map((p) => p.ref));
9570
10055
  let rows = baseRows;
9571
10056
  for (const c of conjuncts) {
9572
10057
  const probe = c.indexProbe();
9573
- 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
+ }
9574
10061
  rows = floor1(rows * c.selectivity(ctx, scope));
9575
10062
  }
9576
- 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)));
9577
10064
  return rows;
9578
10065
  }
9579
- function matchedRows(ctx, scope, type, where) {
9580
- 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));
9581
10068
  }
9582
- function andMatch(ctx, scope, type, base, conjuncts) {
10069
+ function andMatch(ctx, scope, at, base, conjuncts) {
9583
10070
  const ors = conjuncts.filter((c) => c.orOperands() !== void 0);
9584
10071
  const rest = conjuncts.filter((c) => c.orOperands() === void 0);
9585
- let rows = reduceRows(ctx, scope, type, base, rest);
9586
- 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));
9587
10074
  return rows;
9588
10075
  }
9589
- function orFraction(ctx, scope, type, orExpr) {
10076
+ function orFraction(ctx, scope, at, orExpr) {
9590
10077
  let none = 1;
9591
10078
  for (const operand of orExpr.orOperands()) {
9592
- const branch = andMatch(ctx, scope, type, type.count, operand.conjuncts(ctx, scope));
9593
- 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;
9594
10081
  }
9595
10082
  return 1 - none;
9596
10083
  }
9597
- function distinctEstimate(type, groupBy, scannedRows) {
10084
+ function distinctEstimate(at, groupBy, scannedRows) {
9598
10085
  if (groupBy.length === 1) {
9599
10086
  const ref3 = groupBy[0].fieldRef();
9600
10087
  if (ref3) {
9601
- const reduction = bestPrefixReduction(type, [ref3]);
10088
+ const reduction = bestPrefixReduction(at, [ref3]);
9602
10089
  if (reduction !== void 0) return Math.max(1, reduction);
9603
10090
  }
9604
10091
  }
9605
10092
  return Math.max(1, Math.ceil(Math.sqrt(Math.max(1, scannedRows))));
9606
10093
  }
9607
- function coveredScanBytes(ctx, scope, fromType, fromAlias, fields, where) {
10094
+ function coveredScanBytes(ctx, scope, at, fields, where) {
9608
10095
  const refs = [];
9609
10096
  let simple = true;
9610
10097
  const collect = (e2) => {
@@ -9612,21 +10099,21 @@ function coveredScanBytes(ctx, scope, fromType, fromAlias, fields, where) {
9612
10099
  if (n.cost(ctx, scope).rows > 0) simple = false;
9613
10100
  const r = n.fieldRef();
9614
10101
  if (!r) return;
9615
- if (r.source !== fromAlias) simple = false;
10102
+ if (r.source !== at.source) simple = false;
9616
10103
  else refs.push(r);
9617
10104
  });
9618
10105
  };
9619
10106
  for (const e2 of fields) collect(e2);
9620
10107
  for (const w of where) collect(w);
9621
10108
  if (!simple || refs.length === 0) return void 0;
9622
- const refDigests = new Set(refs.map((r) => exprDigest(r.toJSON())));
9623
- 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);
9624
10111
  if (probes.length === 0) return void 0;
9625
- for (const idx of fromType.indexes) {
10112
+ for (const idx of at.type.indexes) {
9626
10113
  const partDigests = indexPartDigestsOf(idx.parts);
9627
10114
  const allColumnsIndexed = [...refDigests].every((d) => partDigests.has(d));
9628
- const whereProbesIndex = probes.some((p) => partDigests.has(exprDigest(p.ref.toJSON())));
9629
- 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);
9630
10117
  }
9631
10118
  return void 0;
9632
10119
  }
@@ -10477,7 +10964,9 @@ var SelectQuery = class _SelectQuery extends Query {
10477
10964
  const groupCtx = { ...predCtx, inGroupBy: true };
10478
10965
  const outScope = this.outputScope(inner);
10479
10966
  p.at("fields", () => {
10480
- 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
+ );
10481
10970
  });
10482
10971
  p.at("where", () => {
10483
10972
  this.where.forEach((w, i) => p.at(i, () => {
@@ -10486,7 +10975,7 @@ var SelectQuery = class _SelectQuery extends Query {
10486
10975
  }));
10487
10976
  });
10488
10977
  p.at("groupBy", () => {
10489
- 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))));
10490
10979
  });
10491
10980
  p.at("having", () => {
10492
10981
  this.having.forEach((h, i) => p.at(i, () => {
@@ -10496,7 +10985,7 @@ var SelectQuery = class _SelectQuery extends Query {
10496
10985
  });
10497
10986
  p.at("order", () => {
10498
10987
  this.order.forEach(
10499
- (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)))
10500
10989
  );
10501
10990
  });
10502
10991
  if (this.groupBy.length > 0) {
@@ -10750,6 +11239,7 @@ var SelectQuery = class _SelectQuery extends Query {
10750
11239
  const engine = ctx.engine;
10751
11240
  const { scope: inner, aliasTypes } = this.bind(engine, scope);
10752
11241
  const fromType = this.from.resolvedType(engine, inner).type;
11242
+ const at = { source: this.from.alias, type: fromType };
10753
11243
  let rows = fromType.count;
10754
11244
  let perRowBytes = fromType.bytes;
10755
11245
  for (const join2 of this.joins) {
@@ -10758,20 +11248,20 @@ var SelectQuery = class _SelectQuery extends Query {
10758
11248
  if (plan) for (const hop of plan) perRowBytes += hop.targetType.bytes;
10759
11249
  }
10760
11250
  if (!this.joins.length && !this.groupBy.length && !this.distinct && !this.fields.some((c) => c.expr.containsAggregate())) {
10761
- 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);
10762
11252
  if (covered !== void 0) perRowBytes = covered;
10763
11253
  }
10764
11254
  const baseScan = scanCost(fromType);
10765
11255
  baseScan.rows = rows;
10766
11256
  baseScan.bytes = rows * perRowBytes;
10767
- let cost = applyWhere(ctx, inner, baseScan, fromType, this.where, perRowBytes);
11257
+ let cost = applyWhere(ctx, inner, baseScan, at, this.where, perRowBytes);
10768
11258
  if (this.groupBy.length) {
10769
- const distinct = distinctEstimate(fromType, this.groupBy, cost.rows);
11259
+ const distinct = distinctEstimate(at, this.groupBy, cost.rows);
10770
11260
  cost = { rows: distinct, bytes: distinct * perRowBytes };
10771
11261
  } else if (this.fields.some((c) => c.expr.containsAggregate())) {
10772
11262
  cost = { rows: 1, bytes: perRowBytes };
10773
11263
  } else if (this.distinct) {
10774
- 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);
10775
11265
  cost = { rows: distinct, bytes: distinct * perRowBytes };
10776
11266
  }
10777
11267
  return { inner, fromType, perRowBytes, matchedRows: cost.rows };
@@ -10957,9 +11447,16 @@ var SelectQuery = class _SelectQuery extends Query {
10957
11447
  nulls ? SqlText.raw(` NULLS ${nulls.toUpperCase()}`) : SqlText.empty()
10958
11448
  ]);
10959
11449
  }
10960
- /** 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
+ */
10961
11456
  orderTermSQL(dialect, ctx, o) {
10962
- 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));
10963
11460
  }
10964
11461
  /**
10965
11462
  * Emit the SELECT. A SELECT never prepends its own `WITH` (relation crossings
@@ -10987,9 +11484,9 @@ var SelectQuery = class _SelectQuery extends Query {
10987
11484
  }
10988
11485
  wherePreds.push(...defaultConditionPredicatesSql(this.activeDefaults(engine, aliasTypes), selCtx));
10989
11486
  const outCtx = selCtx.withScope(this.outputScope(inner));
10990
- 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)]);
10991
11488
  const havingSqls = this.having.map((h) => h.toSQL(dialect, outCtx));
10992
- 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));
10993
11490
  const def = this.effectiveDefaultOrder(engine, isRoot);
10994
11491
  if (def) {
10995
11492
  orderSqls = resolveDefaultOrderSql(def, this.from.alias, outCtx).map(
@@ -11133,6 +11630,12 @@ var RuntimeContext = class {
11133
11630
  */
11134
11631
  sourceTypes = /* @__PURE__ */ new Map();
11135
11632
  embedder;
11633
+ /**
11634
+ * Precomputed text→vector cache for a semantic QUERY term (SQL parity), or
11635
+ * `undefined`. Normalized to a lookup function; `undefined` when no cache was
11636
+ * supplied.
11637
+ */
11638
+ resolveEmbedding;
11136
11639
  recordEmbedding;
11137
11640
  constructor(engine, options = {}) {
11138
11641
  this.engine = engine;
@@ -11142,6 +11645,7 @@ var RuntimeContext = class {
11142
11645
  this.sortSelection = options.sort ?? [];
11143
11646
  this.rlsProvider = options.rls;
11144
11647
  this.embedder = options.embedder ?? engine.embedder;
11648
+ this.resolveEmbedding = options.embeddings ? embeddingResolver(options.embeddings) : void 0;
11145
11649
  this.recordEmbedding = options.recordEmbedding;
11146
11650
  if (options.params) {
11147
11651
  for (const name of Object.keys(options.params)) {
@@ -11519,7 +12023,9 @@ var InsertQuery = class _InsertQuery extends Query {
11519
12023
  const inner = this.targetScope(engine, scope);
11520
12024
  const ctx = { inAggregate: false, inWindow: false, allowAggregate: true, groupKeys: [], inGroupBy: false };
11521
12025
  p.at("returning", () => {
11522
- 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
+ );
11523
12029
  });
11524
12030
  if (this.onConflict && this.onConflict.update.length) {
11525
12031
  const conflictScope = this.conflictScope(engine, scope);
@@ -11886,7 +12392,9 @@ var UpdateQuery = class _UpdateQuery extends Query {
11886
12392
  checkBoolCondition(w, rt, p);
11887
12393
  })));
11888
12394
  const colCtx = { ...ctx, allowAggregate: true };
11889
- 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
+ ));
11890
12398
  }
11891
12399
  /** The single target Type name this update writes. */
11892
12400
  referencedTypes() {
@@ -11908,13 +12416,13 @@ var UpdateQuery = class _UpdateQuery extends Query {
11908
12416
  const baseScan = scanCost(type);
11909
12417
  baseScan.rows = rows;
11910
12418
  baseScan.bytes = rows * perRowBytes;
11911
- return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
12419
+ return applyWhere(ctx, scope, baseScan, selfBinding(type), this.where, perRowBytes);
11912
12420
  }
11913
12421
  /** Rows this UPDATE mutates: the target type's rows matching WHERE (index / selectivity / OR-aware). */
11914
12422
  affected(ctx, scope) {
11915
12423
  const type = ctx.engine.type(this.type);
11916
12424
  if (!type) return AFFECTED_NONE;
11917
- return affectedOne(this.type, matchedRows(ctx, scope, type, this.where));
12425
+ return affectedOne(this.type, matchedRows(ctx, scope, selfBinding(type), this.where));
11918
12426
  }
11919
12427
  /** Expand joins, filter by WHERE, apply SET to each matched target row, then project RETURNING. */
11920
12428
  async execute(ctx) {
@@ -12174,7 +12682,9 @@ var DeleteQuery = class _DeleteQuery extends Query {
12174
12682
  checkBoolCondition(w, rt, p);
12175
12683
  })));
12176
12684
  const colCtx = { ...ctx, allowAggregate: true };
12177
- 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
+ ));
12178
12688
  }
12179
12689
  /** The single target Type name this delete writes. */
12180
12690
  referencedTypes() {
@@ -12196,13 +12706,13 @@ var DeleteQuery = class _DeleteQuery extends Query {
12196
12706
  const baseScan = scanCost(type);
12197
12707
  baseScan.rows = rows;
12198
12708
  baseScan.bytes = rows * perRowBytes;
12199
- return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
12709
+ return applyWhere(ctx, scope, baseScan, selfBinding(type), this.where, perRowBytes);
12200
12710
  }
12201
12711
  /** Rows this DELETE removes: the target type's rows matching WHERE (index / selectivity / OR-aware). */
12202
12712
  affected(ctx, scope) {
12203
12713
  const type = ctx.engine.type(this.from);
12204
12714
  if (!type) return AFFECTED_NONE;
12205
- return affectedOne(this.from, matchedRows(ctx, scope, type, this.where));
12715
+ return affectedOne(this.from, matchedRows(ctx, scope, selfBinding(type), this.where));
12206
12716
  }
12207
12717
  /** Expand joins, filter by WHERE, project RETURNING (pre-removal), then delete the matched rows. */
12208
12718
  async execute(ctx) {
@@ -13064,6 +13574,14 @@ var BUILTIN_QUERIES = [
13064
13574
  ];
13065
13575
 
13066
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
+ }
13067
13585
  var Dialect = class {
13068
13586
  /** Registry key (mirrors `name`) so an instance satisfies `DialectEntry`. */
13069
13587
  get NAME() {
@@ -13154,6 +13672,24 @@ var Dialect = class {
13154
13672
  SqlText.raw(` ON ${on}`)
13155
13673
  ]);
13156
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
+ }
13157
13693
  /**
13158
13694
  * Render a builtin's INLINE-LITERAL argument (a `rawArgs` position — see
13159
13695
  * {@link import('../schema').FunctionDef.rawArgs}) as a dialect-appropriate SQL
@@ -13420,6 +13956,19 @@ var PostgresDialect = class extends BaseDialect {
13420
13956
  " "
13421
13957
  );
13422
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
+ }
13423
13972
  /** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
13424
13973
  queryVectorParam(param3) {
13425
13974
  return SqlText.concat([param3, SqlText.raw("::vector")]);
@@ -15747,6 +16296,7 @@ function assertNever9(value2) {
15747
16296
  }
15748
16297
 
15749
16298
  // src/engine.ts
16299
+ var PLACEHOLDER_VECTOR_TEXT = "[0]";
15750
16300
  var QueryEngine = class {
15751
16301
  /** The registry of types, field types, exprs, queries, dialects, and functions. */
15752
16302
  registry;
@@ -16060,15 +16610,87 @@ var QueryEngine = class {
16060
16610
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
16061
16611
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
16062
16612
  * "$total"` column on the top-level SELECT.
16613
+ *
16614
+ * `opts.embeddings` is a precomputed text→vector cache (see {@link
16615
+ * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
16616
+ * `semantic(...)` text PARAM — is looked up there, formatted to a pgvector TEXT
16617
+ * literal (`[…]`), and bound (all synchronous). Obtain the terms to embed with
16618
+ * {@link semanticTexts}, embed them, fill the cache, then call this. A
16619
+ * plain-text semantic term with NO cache — or one MISSING from the cache —
16620
+ * THROWS (rather than emitting the invalid `'<text>'::vector`); a pre-embedded
16621
+ * `[…]` vector-text param is always bound as-is (never looked up).
16063
16622
  */
16064
16623
  toSQL(query, dialect, opts) {
16624
+ return this.emitSQL(query, dialect, opts, this.semanticConverter(opts?.embeddings));
16625
+ }
16626
+ /**
16627
+ * Extract the DISTINCT plain-text `semantic(...)` terms in `query` (+ the same
16628
+ * execution-time `opts` `toSQL` sees — `filters` / `params` can carry a semantic
16629
+ * text term) that need embedding, in a STABLE (first-seen) order. Give it a
16630
+ * query + params, get back the text to embed: embed each, fill a
16631
+ * {@link SemanticEmbeddings} cache, then pass that as `toSQL`'s `opts.embeddings`.
16632
+ *
16633
+ * Reuses `toSQL`'s exact emit walk (a discarded COLLECTING pass) rather than a
16634
+ * second walker, so it sees precisely the terms `toSQL` would bind. A term
16635
+ * already in pgvector TEXT form (`[…]`) needs no embedding and is NOT returned;
16636
+ * an absent / relation-`{ pk }` param value is not a semantic term and is
16637
+ * skipped.
16638
+ */
16639
+ semanticTexts(query, opts) {
16640
+ const terms = /* @__PURE__ */ new Set();
16641
+ const dialect = this.collectDialect();
16642
+ this.emitSQL(query, dialect, opts, (text) => {
16643
+ terms.add(text);
16644
+ return PLACEHOLDER_VECTOR_TEXT;
16645
+ });
16646
+ return [...terms];
16647
+ }
16648
+ /**
16649
+ * A dialect for the discarded {@link semanticTexts} pass. The rendered
16650
+ * SQL is thrown away and every dialect drives the same semantic-term walk (a
16651
+ * `semantic(...)` term's query side is emitted — hence collected — regardless of
16652
+ * dialect), so any registered dialect serves; the first is used.
16653
+ */
16654
+ collectDialect() {
16655
+ const d = this.registry.dialectList()[0];
16656
+ if (!d) throw new Error("QueryEngine.semanticTexts: no dialect registered.");
16657
+ return d;
16658
+ }
16659
+ /**
16660
+ * Build the INTERNAL sync `semanticText` seam (text → pgvector TEXT) the emit
16661
+ * path threads, from a precomputed {@link SemanticEmbeddings} cache: look the
16662
+ * term up and format its vector with {@link toVectorText}; a term MISSING from
16663
+ * the cache throws the same fail-loud error the emit path would (never a
16664
+ * silently mis-bound `'<text>'::vector`). Returns `undefined` when no cache was
16665
+ * supplied, so a plain-text term then hits the emit path's own "no embeddings"
16666
+ * throw.
16667
+ */
16668
+ semanticConverter(embeddings) {
16669
+ if (!embeddings) return void 0;
16670
+ const resolve = embeddingResolver(embeddings);
16671
+ return (text) => {
16672
+ const vector = resolve(text);
16673
+ if (vector === void 0) {
16674
+ throw new Error(
16675
+ `QueryEngine.toSQL: no embedding supplied for the semantic term ${JSON.stringify(text)}. Collect the terms with 'engine.semanticTexts(query, opts)', embed each, and pass them via 'opts.embeddings' (a text\u2192vector Map).`
16676
+ );
16677
+ }
16678
+ return toVectorText(vector);
16679
+ };
16680
+ }
16681
+ /**
16682
+ * Shared SQL-emit core for {@link toSQL} / {@link semanticTexts}: resolve
16683
+ * the dialect, build the root {@link SqlContext} (threading params / filters /
16684
+ * sort / includeTotal + the SYNC `semanticText` converter), and render.
16685
+ */
16686
+ emitSQL(query, dialect, opts, semanticText2) {
16065
16687
  const d = typeof dialect === "string" ? this.registry.dialect(dialect) : dialect;
16066
16688
  if (!d) throw new Error(`QueryEngine.toSQL: unknown dialect '${String(dialect)}'.`);
16067
16689
  const q = this.toQuery(query);
16068
16690
  const scope = this.globalScope();
16069
16691
  const params = opts?.params ?? {};
16070
16692
  const planner = new JoinCtePlanner(d, this, opts?.rls, params);
16071
- const ctx = new SqlContext(d, this, scope, planner, opts?.rls, false, params, this.parseFilters(opts?.filters), opts?.includeTotal ?? false, true, opts?.sort ?? []);
16693
+ const ctx = new SqlContext(d, this, scope, planner, opts?.rls, false, params, this.parseFilters(opts?.filters), opts?.includeTotal ?? false, true, opts?.sort ?? [], semanticText2);
16072
16694
  const rendered = q.toSQL(d, ctx).render(d);
16073
16695
  return { sql: rendered.sql, params: [...rendered.params] };
16074
16696
  }
@@ -16597,6 +17219,11 @@ function assertNeverExprKind(value2) {
16597
17219
  function isScalar2(value2) {
16598
17220
  return value2 === null || value2 !== void 0 && typeof value2 !== "object";
16599
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
+ }
16600
17227
  function referencesField(expr) {
16601
17228
  let found = false;
16602
17229
  expr.walk((e2) => {
@@ -16784,12 +17411,12 @@ function drillDownInto(select, groupRow, engine) {
16784
17411
  drilled.params.forEach((dp, i) => {
16785
17412
  const present = Object.prototype.hasOwnProperty.call(groupRow, dp.field);
16786
17413
  const value2 = present ? groupRow[dp.field] : void 0;
16787
- if (!present || !isScalar2(value2)) {
17414
+ if (!present || !isDrillValue(value2)) {
16788
17415
  errors.at(
16789
17416
  ["groupBy", i],
16790
17417
  () => errors.error(
16791
17418
  "drill.missing-group-value",
16792
- `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.`
16793
17420
  )
16794
17421
  );
16795
17422
  return;
@@ -16801,7 +17428,7 @@ function drillDownInto(select, groupRow, engine) {
16801
17428
  }
16802
17429
 
16803
17430
  // src/llm/schemas.ts
16804
- import { z as z36 } from "zod";
17431
+ import { z as z37 } from "zod";
16805
17432
  var DEFAULT_MAX_QUERY_SCHEMA_TYPES = 5;
16806
17433
  function toRegistry(engineOrRegistry) {
16807
17434
  return "registry" in engineOrRegistry ? engineOrRegistry.registry : engineOrRegistry;
@@ -16879,8 +17506,8 @@ function relationOnSchema(types, depth, cache) {
16879
17506
  fieldMode: "one",
16880
17507
  eligible: relationFieldsOf,
16881
17508
  extras: {
16882
- kind: z36.literal("relation"),
16883
- 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.")
16884
17511
  },
16885
17512
  aid: "JoinOn",
16886
17513
  describe: "Cross a relation field of a bound source (key synthesized from the relation)."
@@ -16910,37 +17537,37 @@ function buildSchemas(engineOrRegistry, options = {}) {
16910
17537
  functions: selected,
16911
17538
  includeDocs: options.includeDocs,
16912
17539
  cache,
16913
- Expr: z36.never(),
16914
- Query: z36.never()
17540
+ Expr: z37.never(),
17541
+ Query: z37.never()
16915
17542
  };
16916
- inner.Expr = z36.lazy(() => buildExprUnion(registry, inner, types, selected));
16917
- 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.");
16918
17545
  const Expr9 = inner.Expr;
16919
- const Query2 = z36.lazy(() => QueryUnion);
17546
+ const Query2 = z37.lazy(() => QueryUnion);
16920
17547
  inner.Query = Query2;
16921
17548
  const sourceBranches = [
16922
- z36.object({ kind: z36.literal("type"), type: typeRef }).describe("A type source, bound under (and referenced by) its type name."),
16923
- z36.object({
16924
- 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"),
16925
17552
  type: typeRef,
16926
- as: z36.string().describe("Custom source name (self-join / collision break).")
17553
+ as: z37.string().describe("Custom source name (self-join / collision break).")
16927
17554
  }).describe("An explicitly-aliased type source (the discouraged escape hatch)."),
16928
- z36.object({
16929
- kind: z36.literal("subquery"),
17555
+ z37.object({
17556
+ kind: z37.literal("subquery"),
16930
17557
  query: Query2,
16931
- as: z36.string().describe("Required alias for the derived source.")
17558
+ as: z37.string().describe("Required alias for the derived source.")
16932
17559
  }).describe("A derived (subquery) source.")
16933
17560
  ];
16934
17561
  if (selected.tabular.length > 0) {
16935
- 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(
16936
17563
  "A registered tabular function name."
16937
17564
  );
16938
17565
  sourceBranches.push(
16939
- z36.object({
16940
- kind: z36.literal("function"),
17566
+ z37.object({
17567
+ kind: z37.literal("function"),
16941
17568
  function: fnName,
16942
- args: z36.record(z36.string(), Expr9).describe("Arguments keyed by declared parameter name."),
16943
- 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.")
16944
17571
  }).describe("A table-valued function source: FROM fn(args) AS alias.")
16945
17572
  );
16946
17573
  }
@@ -16958,22 +17585,22 @@ function buildSchemas(engineOrRegistry, options = {}) {
16958
17585
  { kinds: ["relation", ...sourceKinds] }
16959
17586
  ).describe("A join target: a relation crossing or a manually-joined source.");
16960
17587
  const Join = withAid(
16961
- z36.object({
17588
+ z37.object({
16962
17589
  on: JoinOn,
16963
17590
  and: Expr9.optional(),
16964
17591
  joinType: withAid(enumOf2(["inner", "left", "right", "full"]), "JoinType").optional()
16965
17592
  }),
16966
17593
  "Join"
16967
17594
  ).describe("A JOIN: a relation crossing (key synthesized) or a manual source-def join with `and` as its ON.");
16968
- const joinsField = hasRelations ? z36.array(Join).optional() : z36.array(z36.never()).optional();
16969
- const Order = z36.object({
17595
+ const joinsField = hasRelations ? z37.array(Join).optional() : z37.array(z37.never()).optional();
17596
+ const Order = z37.object({
16970
17597
  expr: Expr9,
16971
17598
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
16972
17599
  nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
16973
17600
  }).describe("An ORDER BY entry.");
16974
- 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).");
16975
17602
  const GroupExpr = Expr9.or(OutputRef);
16976
- const SelectOrder = z36.object({
17603
+ const SelectOrder = z37.object({
16977
17604
  expr: GroupExpr,
16978
17605
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
16979
17606
  nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
@@ -16982,19 +17609,19 @@ function buildSchemas(engineOrRegistry, options = {}) {
16982
17609
  const SelectOrderEntry = SelectOrder.or(Sorter).describe(
16983
17610
  "A SELECT ORDER BY entry: a term, or a dynamic-sort `sorter` catalog (selection supplied at run time)."
16984
17611
  );
16985
- const SelectField = z36.object({ expr: Expr9, as: z36.string().optional() }).describe("A selected output field.");
16986
- 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") });
16987
17614
  const Select = withAid(
16988
- z36.object({
16989
- kind: z36.literal("select"),
16990
- distinct: z36.boolean().optional(),
16991
- fields: z36.array(SelectField),
17615
+ z37.object({
17616
+ kind: z37.literal("select"),
17617
+ distinct: z37.boolean().optional(),
17618
+ fields: z37.array(SelectField),
16992
17619
  from: Source,
16993
17620
  joins: joinsField,
16994
- where: z36.array(Expr9).optional(),
16995
- groupBy: z36.array(GroupExpr).optional(),
16996
- having: z36.array(GroupExpr).optional(),
16997
- 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(),
16998
17625
  limit: limitOffset.optional(),
16999
17626
  offset: limitOffset.optional()
17000
17627
  // `includeTotal` is an EXECUTION-time option (engine.run / engine.toSQL),
@@ -17006,103 +17633,103 @@ function buildSchemas(engineOrRegistry, options = {}) {
17006
17633
  const updatableTypes = types.filter((t) => t.updatable);
17007
17634
  const deletableTypes = types.filter((t) => t.deletable);
17008
17635
  const fbOf = (typeName, field) => registry.backing(typeName)?.fields?.[field];
17009
- const dmlTypeRef = (subset) => depth.typeNames === "enum" ? enumOf2(subset.map((t) => t.name)).describe("A permitted target Type name.") : z36.string().describe("A Type name.");
17010
- 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>).");
17011
17638
  const ConflictExpr = Expr9.or(ExcludedExprSchema);
17012
17639
  const onConflictSchema = (t) => {
17013
- 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).");
17014
- return z36.object({
17015
- fields: z36.array(z36.string()),
17016
- 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(),
17017
17644
  update: update.optional()
17018
17645
  });
17019
17646
  };
17020
17647
  const openInsert = () => withAid(
17021
- z36.object({
17022
- kind: z36.literal("insert"),
17648
+ z37.object({
17649
+ kind: z37.literal("insert"),
17023
17650
  into: dmlTypeRef(insertableTypes),
17024
- 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)."),
17025
17652
  select: Query2.optional(),
17026
- returning: z36.array(SelectField).optional(),
17653
+ returning: z37.array(SelectField).optional(),
17027
17654
  onConflict: onConflictSchema().optional()
17028
17655
  }),
17029
17656
  "Query_insert"
17030
17657
  ).describe("An INSERT statement.");
17031
17658
  const namedInsert = (writes) => orFold(
17032
17659
  insertableTypes.map(
17033
- (t) => z36.object({
17034
- kind: z36.literal("insert"),
17035
- into: z36.literal(t.name),
17036
- 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(),
17037
17664
  select: Query2.optional(),
17038
- returning: z36.array(SelectField).optional(),
17665
+ returning: z37.array(SelectField).optional(),
17039
17666
  onConflict: onConflictSchema(t).optional()
17040
17667
  }).describe(`An INSERT into ${t.name}.`)
17041
17668
  )
17042
17669
  ).describe("An INSERT statement.");
17043
17670
  const Insert = depth.writes === "open" ? openInsert() : namedInsert(depth.writes);
17044
17671
  const openUpdate = () => withAid(
17045
- z36.object({
17046
- kind: z36.literal("update"),
17672
+ z37.object({
17673
+ kind: z37.literal("update"),
17047
17674
  type: dmlTypeRef(updatableTypes),
17048
- 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)."),
17049
17676
  joins: joinsField,
17050
- where: z36.array(Expr9).optional(),
17051
- returning: z36.array(SelectField).optional()
17677
+ where: z37.array(Expr9).optional(),
17678
+ returning: z37.array(SelectField).optional()
17052
17679
  }),
17053
17680
  "Query_update"
17054
17681
  ).describe("An UPDATE statement.");
17055
17682
  const namedUpdate = (writes) => orFold(
17056
17683
  updatableTypes.map(
17057
- (t) => z36.object({
17058
- kind: z36.literal("update"),
17059
- type: z36.literal(t.name),
17684
+ (t) => z37.object({
17685
+ kind: z37.literal("update"),
17686
+ type: z37.literal(t.name),
17060
17687
  set: updateSetSchema(t, fbOf, writes, Expr9),
17061
17688
  joins: joinsField,
17062
- where: z36.array(Expr9).optional(),
17063
- returning: z36.array(SelectField).optional()
17689
+ where: z37.array(Expr9).optional(),
17690
+ returning: z37.array(SelectField).optional()
17064
17691
  }).describe(`An UPDATE of ${t.name}.`)
17065
17692
  )
17066
17693
  ).describe("An UPDATE statement.");
17067
17694
  const Update = depth.writes === "open" ? openUpdate() : namedUpdate(depth.writes);
17068
17695
  const Delete = withAid(
17069
- z36.object({
17070
- kind: z36.literal("delete"),
17696
+ z37.object({
17697
+ kind: z37.literal("delete"),
17071
17698
  from: dmlTypeRef(deletableTypes),
17072
17699
  joins: joinsField,
17073
- where: z36.array(Expr9).optional(),
17074
- returning: z36.array(SelectField).optional()
17700
+ where: z37.array(Expr9).optional(),
17701
+ returning: z37.array(SelectField).optional()
17075
17702
  }),
17076
17703
  "Query_delete"
17077
17704
  ).describe("A DELETE statement.");
17078
17705
  const SetOperation = withAid(
17079
- z36.object({
17706
+ z37.object({
17080
17707
  kind: withAid(enumOf2(["union", "intersect", "except"]), "SetOpKind"),
17081
17708
  left: Query2,
17082
17709
  right: Query2,
17083
- all: z36.boolean().optional(),
17710
+ all: z37.boolean().optional(),
17084
17711
  // SET-LEVEL ordering / pagination applied AFTER the set op; ORDER BY terms
17085
17712
  // reference OUTPUT COLUMN names (a set op has no table to qualify).
17086
- order: z36.array(Order).optional(),
17713
+ order: z37.array(Order).optional(),
17087
17714
  limit: limitOffset.optional(),
17088
17715
  offset: limitOffset.optional()
17089
17716
  }),
17090
17717
  "Query_set-operation"
17091
17718
  ).describe("A UNION / INTERSECT / EXCEPT set operation.");
17092
17719
  const CteEntry = orFold([
17093
- z36.object({ name: z36.string(), query: Query2 }).describe("A non-recursive CTE."),
17094
- 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.")
17095
17722
  ]);
17096
17723
  const CTE = withAid(
17097
- z36.object({
17098
- kind: z36.literal("cte"),
17099
- ctes: z36.array(CteEntry),
17724
+ z37.object({
17725
+ kind: z37.literal("cte"),
17726
+ ctes: z37.array(CteEntry),
17100
17727
  final: Query2
17101
17728
  }),
17102
17729
  "Query_cte"
17103
17730
  ).describe("A WITH (CTE) statement.");
17104
17731
  const ExprQuery2 = withAid(
17105
- z36.object({ kind: z36.literal("expr"), expr: Expr9 }),
17732
+ z37.object({ kind: z37.literal("expr"), expr: Expr9 }),
17106
17733
  "Query_expr"
17107
17734
  ).describe("A single-expression query.");
17108
17735
  const queryBranches = [Select];
@@ -17149,14 +17776,14 @@ function querySchema(engine, options = {}) {
17149
17776
  const types = options.types ?? registry.typeList();
17150
17777
  const max2 = options.max ?? DEFAULT_MAX_QUERY_SCHEMA_TYPES;
17151
17778
  if (shouldUseStringSchema(types, max2)) {
17152
- return z36.object({
17153
- query: z36.string().describe(
17779
+ return z37.object({
17780
+ query: z37.string().describe(
17154
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."
17155
17782
  )
17156
17783
  });
17157
17784
  }
17158
17785
  const schemas = buildSchemas(registry, options);
17159
- return z36.object({
17786
+ return z37.object({
17160
17787
  query: schemas.Query.describe("The query to execute as a structured Query object.")
17161
17788
  });
17162
17789
  }
@@ -17339,7 +17966,11 @@ function fieldTypeTag(field) {
17339
17966
  const flags = [];
17340
17967
  if (ft.options.search) flags.push("search");
17341
17968
  if (ft.options.semantic) flags.push("semantic");
17342
- 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);
17343
17974
  }
17344
17975
  return ft.kind;
17345
17976
  }
@@ -17661,6 +18292,7 @@ export {
17661
18292
  IN_SELECTIVITY,
17662
18293
  InExpr,
17663
18294
  Index,
18295
+ IndexPart,
17664
18296
  InsertQuery,
17665
18297
  IsNullExpr,
17666
18298
  JoinCtePlanner,
@@ -17714,6 +18346,7 @@ export {
17714
18346
  age,
17715
18347
  agg,
17716
18348
  aidInfo,
18349
+ aliasedDigest,
17717
18350
  and,
17718
18351
  arrayAgg,
17719
18352
  arrayAppend,
@@ -17776,6 +18409,7 @@ export {
17776
18409
  drillDownInto,
17777
18410
  e,
17778
18411
  editDistance,
18412
+ embeddingResolver,
17779
18413
  epoch,
17780
18414
  eq,
17781
18415
  excluded,
@@ -17806,6 +18440,7 @@ export {
17806
18440
  isScalar,
17807
18441
  isScalarValue,
17808
18442
  isType,
18443
+ isVectorText,
17809
18444
  join,
17810
18445
  joinAlias,
17811
18446
  joinCode,
@@ -17843,6 +18478,7 @@ export {
17843
18478
  param2 as param,
17844
18479
  parseQueryRequest,
17845
18480
  parseQueryTool,
18481
+ parseVectorText,
17846
18482
  plain,
17847
18483
  pos,
17848
18484
  querySchema,
@@ -17851,6 +18487,9 @@ export {
17851
18487
  recordSignature,
17852
18488
  ref2 as ref,
17853
18489
  relJoin,
18490
+ relationKeyColumns,
18491
+ relationOf,
18492
+ renameSource,
17854
18493
  reportCostProblems,
17855
18494
  resolveAccessRun,
17856
18495
  resolveAccessSql,
@@ -17891,9 +18530,11 @@ export {
17891
18530
  textSearch,
17892
18531
  timezoneSchema,
17893
18532
  toArrayRows,
18533
+ toVectorText,
17894
18534
  typeFromFields,
17895
18535
  typeMeta,
17896
18536
  value,
18537
+ valueFieldType,
17897
18538
  variance,
17898
18539
  week,
17899
18540
  when,