@aeye/query 0.3.10 → 0.5.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
@@ -1182,18 +1182,18 @@ async function resolveSemanticRun(semantic2, alias, row, queryVector, ctx) {
1182
1182
  function readFieldText(row, alias, field) {
1183
1183
  const rec = row[alias];
1184
1184
  if (!rec) return "";
1185
- const cell = rec[field];
1186
- if (typeof cell === "string") return cell;
1187
- if (Array.isArray(cell)) return cell.filter((x) => typeof x === "string").join(" ");
1185
+ const cell2 = rec[field];
1186
+ if (typeof cell2 === "string") return cell2;
1187
+ if (Array.isArray(cell2)) return cell2.filter((x) => typeof x === "string").join(" ");
1188
1188
  return "";
1189
1189
  }
1190
1190
  function readFieldVector(row, alias, field) {
1191
1191
  const rec = row[alias];
1192
1192
  if (!rec) return null;
1193
- const cell = rec[field];
1194
- if (!Array.isArray(cell)) return null;
1193
+ const cell2 = rec[field];
1194
+ if (!Array.isArray(cell2)) return null;
1195
1195
  const out = [];
1196
- for (const v of cell) {
1196
+ for (const v of cell2) {
1197
1197
  if (typeof v !== "number") return null;
1198
1198
  out.push(v);
1199
1199
  }
@@ -1295,6 +1295,32 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1295
1295
  foreignField: fk
1296
1296
  };
1297
1297
  }
1298
+ /**
1299
+ * The UNALIASED, ordered join-key column pairs for this relation — the
1300
+ * composite/backing-aware generalization of {@link resolveKey}. Each pair is
1301
+ * `{ local, foreign }`: `local` a column on THIS Type's side, `foreign` the
1302
+ * matching column on the TARGET (the target's PK field for a belongs-to). Uses
1303
+ * the field's `RelationBacking.keys` when declared, else the single
1304
+ * name-convention pair. Drives relation comparison lowering (`= <> in`).
1305
+ */
1306
+ resolveKeys(engine, relationFieldName, thisType, targetType) {
1307
+ const forward = this.count === 1;
1308
+ let backing;
1309
+ if (forward) {
1310
+ backing = engine.fieldBacking(thisType.name, relationFieldName)?.relation;
1311
+ } else if (this.inverseVia !== void 0) {
1312
+ backing = engine.fieldBacking(targetType.name, this.inverseVia)?.relation;
1313
+ }
1314
+ if (backing?.keys && backing.keys.length > 0) {
1315
+ const targetIdentity = backing.keys.some((k) => k.foreign === void 0) ? (
1316
+ /* v8 ignore next -- a forward=false (has-many) key omitting `foreign` is not reachable via the tested inverse backings */
1317
+ (forward ? targetType : thisType).identityField().name
1318
+ ) : "";
1319
+ return relationKeyColumns(backing.keys, forward, targetIdentity).map((p) => ({ local: p.localField, foreign: p.foreignField }));
1320
+ }
1321
+ const single = this.resolveKey(relationFieldName, thisType, targetType);
1322
+ return [{ local: single.localField, foreign: single.foreignField }];
1323
+ }
1298
1324
  /**
1299
1325
  * Resolve the full join `ON` for this relation hop, consulting the field's
1300
1326
  * DEV-SIDE `RelationBacking` (physical FK columns / custom predicate) and
@@ -1950,6 +1976,9 @@ var Index = class _Index {
1950
1976
 
1951
1977
  // src/type.ts
1952
1978
  import { z as z12 } from "zod";
1979
+ function noKeyMessage(typeName) {
1980
+ return `Type '${typeName}' needs a primary key (a unique index or an 'id' field) to participate in relations.`;
1981
+ }
1953
1982
  var Type = class _Type {
1954
1983
  /** Type name (unique within the registry). */
1955
1984
  name;
@@ -2012,6 +2041,31 @@ var Type = class _Type {
2012
2041
  * a clear error. Relations resolve their keys through this.
2013
2042
  */
2014
2043
  identityField() {
2044
+ const single = this.singleIdentity();
2045
+ if (single) return single;
2046
+ throw new QueryTypeError({ path: [], code: "type.no-identity", severity: "error", message: noKeyMessage(this.name) });
2047
+ }
2048
+ /**
2049
+ * 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.
2055
+ */
2056
+ primaryKey() {
2057
+ const single = this.singleIdentity();
2058
+ if (single) return [single];
2059
+ for (const idx of this.indexes) {
2060
+ const last = idx.parts[idx.parts.length - 1];
2061
+ if (!last || last.count !== 1) continue;
2062
+ const fields = idx.parts.map((p) => p.expr.kind === "field-ref" ? this.field(p.expr.field) : void 0);
2063
+ if (fields.every((f) => f !== void 0)) return fields;
2064
+ }
2065
+ throw new QueryTypeError({ path: [], code: "type.no-identity", severity: "error", message: noKeyMessage(this.name) });
2066
+ }
2067
+ /** The single identity field: the first single-part unique index's field, else `id`, else undefined. */
2068
+ singleIdentity() {
2015
2069
  for (const idx of this.indexes) {
2016
2070
  if (idx.parts.length !== 1) continue;
2017
2071
  const part = idx.parts[0];
@@ -2020,14 +2074,7 @@ var Type = class _Type {
2020
2074
  const field = this.field(part.expr.field);
2021
2075
  if (field) return field;
2022
2076
  }
2023
- const byName = this.field("id");
2024
- if (byName) return byName;
2025
- throw new QueryTypeError({
2026
- path: [],
2027
- code: "type.no-identity",
2028
- severity: "error",
2029
- message: `Type '${this.name}' needs an identity field (a unique single-field index or an 'id' field) to participate in relations.`
2030
- });
2077
+ return this.field("id");
2031
2078
  }
2032
2079
  /**
2033
2080
  * Fields eligible for semantic-aware querying: text fields flagged
@@ -2943,7 +2990,7 @@ var raw = (text) => SqlText.raw(text);
2943
2990
  var concat = (parts) => SqlText.concat(parts);
2944
2991
  var join = (parts, sep) => SqlText.join(parts, sep);
2945
2992
  var SqlContext = class _SqlContext {
2946
- constructor(dialect, engine, scope, planner, rls, inAggregate = false, params = {}, filters2 = {}, includeTotal = false, isRoot = false, sortSpec = []) {
2993
+ constructor(dialect, engine, scope, planner, rls, inAggregate = false, params = {}, filters2 = {}, includeTotal = false, isRoot = false, sortSpec = [], semanticText2 = void 0) {
2947
2994
  this.dialect = dialect;
2948
2995
  this.engine = engine;
2949
2996
  this.scope = scope;
@@ -2955,6 +3002,7 @@ var SqlContext = class _SqlContext {
2955
3002
  this.includeTotal = includeTotal;
2956
3003
  this.isRoot = isRoot;
2957
3004
  this.sortSpec = sortSpec;
3005
+ this.semanticText = semanticText2;
2958
3006
  }
2959
3007
  dialect;
2960
3008
  engine;
@@ -2967,23 +3015,24 @@ var SqlContext = class _SqlContext {
2967
3015
  includeTotal;
2968
3016
  isRoot;
2969
3017
  sortSpec;
3018
+ semanticText;
2970
3019
  /** The execution-supplied filter expr bound to `source`, or `undefined`. */
2971
3020
  filtersFor(source) {
2972
3021
  return this.filters[source];
2973
3022
  }
2974
3023
  /** Same context with a different scope (same planner / level / root status). */
2975
3024
  withScope(scope) {
2976
- return new _SqlContext(this.dialect, this.engine, scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec);
3025
+ 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);
2977
3026
  }
2978
3027
  /** A nested level (subquery): fresh scope + fresh planner, not in-aggregate.
2979
3028
  * Neither the outer `$total` flag NOR root status propagates into a nested
2980
3029
  * level, so a subquery / FROM subquery emits as non-root. */
2981
3030
  withPlanner(scope, planner) {
2982
- return new _SqlContext(this.dialect, this.engine, scope, planner, this.rls, false, this.params, this.filters, false, false, this.sortSpec);
3031
+ return new _SqlContext(this.dialect, this.engine, scope, planner, this.rls, false, this.params, this.filters, false, false, this.sortSpec, this.semanticText);
2983
3032
  }
2984
3033
  /** Toggle the in-aggregate flag (set when emitting an aggregate argument). */
2985
3034
  asAggregate(on) {
2986
- return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, on, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec);
3035
+ 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);
2987
3036
  }
2988
3037
  /**
2989
3038
  * Mark the NEXT emitted query as NON-root (same level otherwise). Used at the
@@ -2991,7 +3040,7 @@ var SqlContext = class _SqlContext {
2991
3040
  * branch — so those nested SELECTs never inherit the entry's root status.
2992
3041
  */
2993
3042
  nonRoot() {
2994
- return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, false, this.sortSpec);
3043
+ 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);
2995
3044
  }
2996
3045
  };
2997
3046
 
@@ -4039,9 +4088,25 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
4039
4088
  );
4040
4089
  return textResult([], true);
4041
4090
  }
4042
- const keyField = ft.resolveKey(this.field, ownerType, target).localField;
4043
- const keyType = (ft.count === 1 ? target : ownerType).identityField().fieldType;
4044
- const relation = { source: this.source, field: this.field, keyField, keyType, to: ft.to };
4091
+ const keys = ft.resolveKeys(engine, this.field, ownerType, target).map((kp) => {
4092
+ const tf = target.field(kp.foreign);
4093
+ let keyType;
4094
+ if (tf && !(tf.fieldType instanceof RelationFieldType)) {
4095
+ keyType = tf.fieldType;
4096
+ } else {
4097
+ keyType = (ft.count === 1 ? target : ownerType).identityField().fieldType;
4098
+ }
4099
+ return { local: kp.local, foreign: kp.foreign, keyType };
4100
+ });
4101
+ const relation = {
4102
+ source: this.source,
4103
+ field: this.field,
4104
+ keyField: keys[0].local,
4105
+ keyType: keys[0].keyType,
4106
+ to: ft.to,
4107
+ count: ft.count,
4108
+ keys
4109
+ };
4045
4110
  const resolved = {
4046
4111
  kind: "type",
4047
4112
  type: target,
@@ -4409,7 +4474,8 @@ var ParamExpr = class _ParamExpr extends Expr {
4409
4474
  }
4410
4475
  /** Emit as a bound SqlText param slot (null until a value is supplied). */
4411
4476
  toSQL(_dialect, ctx) {
4412
- const value2 = Object.prototype.hasOwnProperty.call(ctx.params, this.name) ? ctx.params[this.name] : null;
4477
+ const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, this.name) ? ctx.params[this.name] : null;
4478
+ const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
4413
4479
  return SqlText.param(value2);
4414
4480
  }
4415
4481
  /** Serialize back to its JSON ExprDef. */
@@ -4710,6 +4776,151 @@ var UnaryExpr = class _UnaryExpr extends Expr {
4710
4776
  // src/exprs/comparison.ts
4711
4777
  import { z as z20 } from "zod";
4712
4778
 
4779
+ // src/runtime/tri.ts
4780
+ function not3(a) {
4781
+ return a === void 0 ? void 0 : !a;
4782
+ }
4783
+ function and3(a, b) {
4784
+ if (a === false || b === false) return false;
4785
+ if (a === void 0 || b === void 0) return void 0;
4786
+ return true;
4787
+ }
4788
+ function or3(a, b) {
4789
+ if (a === true || b === true) return true;
4790
+ if (a === void 0 || b === void 0) return void 0;
4791
+ return false;
4792
+ }
4793
+ function triOf(v) {
4794
+ return v.isNull() ? void 0 : v.toBoolean();
4795
+ }
4796
+
4797
+ // src/exprs/_relation-compare.ts
4798
+ var HAS_MANY_ALIAS = "__rel";
4799
+ function relationCompare(operand, engine, typeOf) {
4800
+ const ref3 = operand.fieldRef();
4801
+ if (!ref3) return void 0;
4802
+ const owner = typeOf(ref3.source);
4803
+ if (!owner) return void 0;
4804
+ const field = owner.field(ref3.field);
4805
+ if (!field || !(field.fieldType instanceof RelationFieldType)) return void 0;
4806
+ const ft = field.fieldType;
4807
+ const target = engine.type(ft.to);
4808
+ if (!target) return void 0;
4809
+ return { source: ref3.source, keys: ft.resolveKeys(engine, ref3.field, owner, target), count: ft.count, target };
4810
+ }
4811
+ function runtimeTypeOf(ctx) {
4812
+ return (s) => ctx.sourceType(s) ?? ctx.engine.type(s);
4813
+ }
4814
+ function sqlTypeOf(ctx) {
4815
+ return (s) => {
4816
+ const b = ctx.scope.lookup(s);
4817
+ return b && b.kind === "type" ? b.type : void 0;
4818
+ };
4819
+ }
4820
+ function column(row, source, name, ctx) {
4821
+ const rec = row[source] ?? ctx.correlation?.[source];
4822
+ if (!rec) return Value.null();
4823
+ return cell(rec, name);
4824
+ }
4825
+ async function tuple(operand, rel, keys, row, ctx, group) {
4826
+ if (rel) return rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4827
+ const v = await operand.evaluate(ctx, row, group);
4828
+ if (v.isNull()) return keys.map(() => Value.null());
4829
+ const raw2 = v.raw;
4830
+ if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4831
+ const obj2 = raw2;
4832
+ return keys.map((k) => Value.of(obj2[k.foreign] ?? null));
4833
+ }
4834
+ return [v];
4835
+ }
4836
+ function eq3(a, b) {
4837
+ if (a.isNull() || b.isNull()) return void 0;
4838
+ return a.compareTo(b) === 0;
4839
+ }
4840
+ function cell(rec, name) {
4841
+ return Value.of(rec[name] ?? null);
4842
+ }
4843
+ async function evaluateRelationCompare(op, left, right, leftRel, rightRel, row, ctx, group) {
4844
+ const keys = (leftRel ?? rightRel).keys;
4845
+ const lt2 = await tuple(left, leftRel, keys, row, ctx, group);
4846
+ const rt = await tuple(right, rightRel, keys, row, ctx, group);
4847
+ let acc = true;
4848
+ for (let i = 0; i < keys.length; i++) acc = and3(acc, eq3(lt2[i], rt[i]));
4849
+ return op === "=" ? acc : not3(acc);
4850
+ }
4851
+ async function valueTuple(value2, pkFields, row, ctx, group) {
4852
+ const v = await value2.evaluate(ctx, row, group);
4853
+ if (v.isNull()) return pkFields.map(() => Value.null());
4854
+ const raw2 = v.raw;
4855
+ if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4856
+ const obj2 = raw2;
4857
+ return pkFields.map((f) => Value.of(obj2[f] ?? null));
4858
+ }
4859
+ return [v];
4860
+ }
4861
+ async function evaluateHasMany(op, rel, value2, row, ctx, group) {
4862
+ const pkFields = rel.target.primaryKey().map((f) => f.name);
4863
+ const outer = rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4864
+ const pkVals = await valueTuple(value2, pkFields, row, ctx, group);
4865
+ if (outer.some((v) => v.isNull()) || pkVals.some((v) => v.isNull())) return op !== "=";
4866
+ const rows = (await ctx.typeState(rel.target)).current;
4867
+ const found = rows.some(
4868
+ (tr) => rel.keys.every((k, i) => eq3(cell(tr, k.foreign), outer[i]) === true) && pkFields.every((f, i) => eq3(cell(tr, f), pkVals[i]) === true)
4869
+ );
4870
+ return op === "=" ? found : !found;
4871
+ }
4872
+ function tupleSql(operand, rel, keys, dialect, ctx) {
4873
+ if (rel) return rel.keys.map((k) => new FieldRefExpr(rel.source, k.local).toSQL(dialect, ctx));
4874
+ if (operand instanceof ParamExpr) {
4875
+ const pv = ctx.params[operand.name];
4876
+ if (pv !== null && pv !== void 0 && typeof pv === "object") {
4877
+ const obj2 = pv;
4878
+ return keys.map((k) => SqlText.param(obj2[k.foreign] ?? null));
4879
+ }
4880
+ return [SqlText.param(pv ?? null)];
4881
+ }
4882
+ return [operand.toSQL(dialect, ctx)];
4883
+ }
4884
+ function emitRelationCompare(op, left, right, leftRel, rightRel, dialect, ctx) {
4885
+ const keys = (leftRel ?? rightRel).keys;
4886
+ const ls = tupleSql(left, leftRel, keys, dialect, ctx);
4887
+ const rs = tupleSql(right, rightRel, keys, dialect, ctx);
4888
+ const eqs = keys.map((_, i) => SqlText.join([ls[i], SqlText.raw("="), rs[i]], " "));
4889
+ const anded = SqlText.join(eqs, " AND ").parens();
4890
+ return op === "=" ? anded : SqlText.concat([SqlText.raw("NOT "), anded]);
4891
+ }
4892
+ function valueComponentsSql(value2, pkFields, ctx) {
4893
+ if (!(value2 instanceof ParamExpr)) return pkFields.map(() => null);
4894
+ const pv = ctx.params[value2.name];
4895
+ if (pv !== null && pv !== void 0 && typeof pv === "object") {
4896
+ const obj2 = pv;
4897
+ return pkFields.map((f) => obj2[f] ?? null);
4898
+ }
4899
+ return [pv ?? null];
4900
+ }
4901
+ function emitHasMany(op, rel, value2, dialect, ctx) {
4902
+ const pkFields = rel.target.primaryKey().map((f) => f.name);
4903
+ const comps = valueComponentsSql(value2, pkFields, ctx);
4904
+ const eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
4905
+ const col = (source, field) => ({ kind: "field-ref", source, field });
4906
+ const where = [
4907
+ // Correlation: each has-many key joins the target's FK-back column to this row's identity.
4908
+ ...rel.keys.map((k) => eq2(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
4909
+ // Membership: the target's PK equals the value's components.
4910
+ ...pkFields.map((pk, i) => eq2(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
4911
+ ];
4912
+ const def = {
4913
+ kind: "select",
4914
+ // Project the target's PK column (a bare ref, no bound param) — EXISTS
4915
+ // ignores the projected value, and `SELECT 1` would bind a stray literal.
4916
+ fields: [{ expr: col(HAS_MANY_ALIAS, pkFields[0]) }],
4917
+ from: { kind: "aliased", type: rel.target.name, as: HAS_MANY_ALIAS },
4918
+ where
4919
+ };
4920
+ const sub2 = emitSubquerySQL(dialect, ctx, def);
4921
+ return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub2]);
4922
+ }
4923
+
4713
4924
  // src/exprs/_field-guard.ts
4714
4925
  function operandCtx(operand, kind, ctx, relationOk = false) {
4715
4926
  if (!(operand instanceof FieldRefExpr)) return ctx;
@@ -4779,7 +4990,7 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4779
4990
  right;
4780
4991
  static KIND = "comparison";
4781
4992
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4782
- static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). Do NOT compare a RELATION field-ref to an id/scalar (e.g. `salesOrder.customer = customer.id`) \u2014 that is rejected: to correlate, JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key. Comparing two relations of the SAME target IS allowed (compared by FK key).";
4993
+ static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION field-ref compares by IDENTITY with `=`/`<>` ONLY (ordering / LIKE on a relation is rejected). Its RHS may be (a) another relation of the SAME target \u2014 compared by FK key (`order.customer = invoice.customer`); or (b) a `{ pk }` VALUE param keyed by the target's primary-key fields (`assignedUser = :u` with `:u = {id:5}`); a single-key relation also accepts a bare scalar param. A BELONGS-TO compares the FK columns; a HAS-MANY compares by MEMBERSHIP \u2014 `= value` is TRUE when the value's key is in the related set (correlated EXISTS), `<>` is NOT EXISTS; a has-many may not be compared to another relation. Do NOT compare a relation to a scalar id COLUMN/field-ref (the correlation bug) \u2014 JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key.";
4783
4994
  kind = _ComparisonExpr.KIND;
4784
4995
  /** Reconstruct a ComparisonExpr from its JSON def (validates `kind`, recurses into operands via `registry.parseExpr`). */
4785
4996
  static from(json, registry) {
@@ -4831,6 +5042,18 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4831
5042
  const r = p.at("right", () => this.right.validateWalk(engine, scope, p, operandCtx(this.right, "comparison", ctx, true)));
4832
5043
  const lft = asFieldType(l);
4833
5044
  const rft = asFieldType(r);
5045
+ if (this.op !== "=" && this.op !== "<>" && (relationOf(l) || relationOf(r))) {
5046
+ p.error("comparison.relation-order", `A relation compares by identity \u2014 use '=' or '<>', not '${this.op}'.`);
5047
+ }
5048
+ const lRel = relationOf(l);
5049
+ const rRel = relationOf(r);
5050
+ if (lRel && rRel && (lRel.count > 1 || rRel.count > 1)) {
5051
+ const set = lRel.count > 1 ? lRel : rRel;
5052
+ p.error(
5053
+ "comparison.relation-set",
5054
+ `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}').`
5055
+ );
5056
+ }
4834
5057
  if (LIKE_OPS.has(this.op)) {
4835
5058
  if (!exempt2(this.left) && categoryOf(l) !== "text") {
4836
5059
  p.at(
@@ -4890,6 +5113,16 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4890
5113
  }
4891
5114
  /** Evaluate under 3VL: a NULL operand yields UNKNOWN; text compares case-insensitively unless a `sensitive` field is involved. */
4892
5115
  async evaluateBool(ctx, row, group) {
5116
+ if (this.op === "=" || this.op === "<>") {
5117
+ const typeOf = runtimeTypeOf(ctx);
5118
+ const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5119
+ const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5120
+ if (leftRel && leftRel.count > 1) return evaluateHasMany(this.op, leftRel, this.right, row, ctx, group);
5121
+ if (rightRel && rightRel.count > 1) return evaluateHasMany(this.op, rightRel, this.left, row, ctx, group);
5122
+ if (leftRel || rightRel) {
5123
+ return evaluateRelationCompare(this.op, this.left, this.right, leftRel, rightRel, row, ctx, group);
5124
+ }
5125
+ }
4893
5126
  const l = await this.left.evaluate(ctx, row, group);
4894
5127
  const r = await this.right.evaluate(ctx, row, group);
4895
5128
  if (l.isNull() || r.isNull()) return void 0;
@@ -4927,6 +5160,16 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4927
5160
  }
4928
5161
  /** Emit as a SqlText fragment (ILIKE delegates to the dialect; case-insensitive text wraps both operands in `LOWER(...)`). */
4929
5162
  toSQL(dialect, ctx) {
5163
+ if (this.op === "=" || this.op === "<>") {
5164
+ const typeOf = sqlTypeOf(ctx);
5165
+ const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5166
+ const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5167
+ if (leftRel && leftRel.count > 1) return emitHasMany(this.op, leftRel, this.right, dialect, ctx);
5168
+ if (rightRel && rightRel.count > 1) return emitHasMany(this.op, rightRel, this.left, dialect, ctx);
5169
+ if (leftRel || rightRel) {
5170
+ return emitRelationCompare(this.op, this.left, this.right, leftRel, rightRel, dialect, ctx);
5171
+ }
5172
+ }
4930
5173
  let left = this.left.toSQL(dialect, ctx);
4931
5174
  let right = this.right.toSQL(dialect, ctx);
4932
5175
  if (this.op === "ilike") return dialect.ilike(left, right);
@@ -4961,26 +5204,6 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4961
5204
 
4962
5205
  // src/exprs/logical.ts
4963
5206
  import { z as z21 } from "zod";
4964
-
4965
- // src/runtime/tri.ts
4966
- function not3(a) {
4967
- return a === void 0 ? void 0 : !a;
4968
- }
4969
- function and3(a, b) {
4970
- if (a === false || b === false) return false;
4971
- if (a === void 0 || b === void 0) return void 0;
4972
- return true;
4973
- }
4974
- function or3(a, b) {
4975
- if (a === true || b === true) return true;
4976
- if (a === void 0 || b === void 0) return void 0;
4977
- return false;
4978
- }
4979
- function triOf(v) {
4980
- return v.isNull() ? void 0 : v.toBoolean();
4981
- }
4982
-
4983
- // src/exprs/logical.ts
4984
5207
  var LOGICAL_OPS = ["and", "or", "not"];
4985
5208
  var LogicalExpr = class _LogicalExpr extends BoolExpr {
4986
5209
  /** Wrap a boolean connective (`and` / `or` / `not`) over its operands. */
@@ -5184,7 +5407,7 @@ var InExpr = class _InExpr extends BoolExpr {
5184
5407
  not;
5185
5408
  static KIND = "in";
5186
5409
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
5187
- static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). To project a value across a relation, add a `relation` join in the subquery and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
5410
+ static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. To project a value across a relation in the SUBQUERY form, add a `relation` join and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
5188
5411
  /**
5189
5412
  * Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
5190
5413
  * value LIST, and a single-field SUBQUERY that crosses a relation via a
@@ -5370,6 +5593,26 @@ var InExpr = class _InExpr extends BoolExpr {
5370
5593
  }
5371
5594
  /** Evaluate under 3VL: TRUE if any element equals the value; else UNKNOWN if the value or any element is NULL; else FALSE (negated for `NOT IN`). */
5372
5595
  async evaluateBool(ctx, row, group) {
5596
+ const typeOf = runtimeTypeOf(ctx);
5597
+ const rel = relationCompare(this.value, ctx.engine, typeOf);
5598
+ if (rel && this.list) {
5599
+ if (rel.count > 1) {
5600
+ let found = false;
5601
+ for (const el of this.list) {
5602
+ if (await evaluateHasMany("=", rel, el, row, ctx, group)) {
5603
+ found = true;
5604
+ break;
5605
+ }
5606
+ }
5607
+ return this.not ? !found : found;
5608
+ }
5609
+ let acc = false;
5610
+ for (const el of this.list) {
5611
+ const elRel = relationCompare(el, ctx.engine, typeOf);
5612
+ acc = or3(acc, await evaluateRelationCompare("=", this.value, el, rel, elRel, row, ctx, group));
5613
+ }
5614
+ return this.not ? not3(acc) : acc;
5615
+ }
5373
5616
  const v = await this.value.evaluate(ctx, row, group);
5374
5617
  let matched = false;
5375
5618
  let anyNull = v.isNull();
@@ -5399,6 +5642,15 @@ var InExpr = class _InExpr extends BoolExpr {
5399
5642
  }
5400
5643
  /** Emit as a SqlText fragment (`value [NOT] IN (...)` over a list or an emitted subquery). */
5401
5644
  toSQL(dialect, ctx) {
5645
+ const typeOf = sqlTypeOf(ctx);
5646
+ const rel = relationCompare(this.value, ctx.engine, typeOf);
5647
+ if (rel && this.list) {
5648
+ const ors = rel.count > 1 ? this.list.map((el) => emitHasMany("=", rel, el, dialect, ctx)) : this.list.map(
5649
+ (el) => emitRelationCompare("=", this.value, el, rel, relationCompare(el, ctx.engine, typeOf), dialect, ctx)
5650
+ );
5651
+ const anded = SqlText.join(ors, " OR ").parens();
5652
+ return this.not ? SqlText.concat([SqlText.raw("NOT "), anded]) : anded;
5653
+ }
5402
5654
  const rhs = this.list ? SqlText.join(this.list.map((e2) => e2.toSQL(dialect, ctx)), ", ").parens() : this.subquery ? emitSubquerySQL(dialect, ctx, this.subquery) : SqlText.raw("()");
5403
5655
  return SqlText.join(
5404
5656
  [this.value.toSQL(dialect, ctx), SqlText.raw(this.not ? "NOT IN" : "IN"), rhs],
@@ -7134,6 +7386,27 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7134
7386
  }
7135
7387
  };
7136
7388
 
7389
+ // src/vector-text.ts
7390
+ function embeddingResolver(embeddings) {
7391
+ return typeof embeddings === "function" ? embeddings : (text) => embeddings.get(text);
7392
+ }
7393
+ function isVectorText(text) {
7394
+ const t = text.trim();
7395
+ return t.startsWith("[") && t.endsWith("]");
7396
+ }
7397
+ function toVectorText(vector) {
7398
+ return `[${vector.join(",")}]`;
7399
+ }
7400
+ function parseVectorText(text) {
7401
+ const t = text.trim();
7402
+ if (!isVectorText(t)) {
7403
+ throw new Error(`parseVectorText: expected pgvector text '[\u2026]', got ${JSON.stringify(text)}.`);
7404
+ }
7405
+ const inner = t.slice(1, -1).trim();
7406
+ if (inner.length === 0) return [];
7407
+ return inner.split(",").map((part) => Number(part.trim()));
7408
+ }
7409
+
7137
7410
  // src/exprs/semantic.ts
7138
7411
  function cosine(a, b) {
7139
7412
  const n = Math.min(a.length, b.length);
@@ -7363,14 +7636,29 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7363
7636
  return SEMANTIC_ROW_PENALTY;
7364
7637
  }
7365
7638
  /**
7366
- * Embed the query side into a vector (null when unavailable), using the
7367
- * `SemanticBacking`'s `embedder` override when supplied, else the run / engine
7368
- * embedder.
7639
+ * Resolve the query side into a vector (null when unavailable). A caller-supplied
7640
+ * precomputed embeddings cache (`ctx.resolveEmbedding`, mirroring the SQL path's
7641
+ * `toSQL({ embeddings })`) takes precedence when present — the term's vector is
7642
+ * looked up synchronously; a pre-embedded `[…]` value short-circuits the lookup.
7643
+ * A term MISSING from the cache throws (fail loud). With no cache it falls back
7644
+ * to the `SemanticBacking`'s `embedder` override, else the run / engine embedder
7645
+ * (unchanged existing behavior).
7369
7646
  */
7370
7647
  async queryVector(ctx, q, embedder) {
7371
- if (q.kind === "text") return this.embedText(ctx, q.text, embedder);
7372
- const text = ctx.param(q.param.name).toText();
7373
- return text.length > 0 ? this.embedText(ctx, text, embedder) : null;
7648
+ const text = q.kind === "text" ? q.text : ctx.param(q.param.name).toText();
7649
+ if (text.length === 0) return null;
7650
+ const resolve = ctx.resolveEmbedding;
7651
+ if (resolve) {
7652
+ if (isVectorText(text)) return parseVectorText(text);
7653
+ const vector = resolve(text);
7654
+ if (vector === void 0) {
7655
+ throw new Error(
7656
+ `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).`
7657
+ );
7658
+ }
7659
+ return [...vector];
7660
+ }
7661
+ return this.embedText(ctx, text, embedder);
7374
7662
  }
7375
7663
  /** Embed `text` via the backing's `embedder` override, else the run's embedder (cached). */
7376
7664
  async embedText(ctx, text, embedder) {
@@ -7398,7 +7686,7 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7398
7686
  const type = this.boundType(ctx);
7399
7687
  const backing = type ? ctx.engine.semanticBacking(type.name, this.field) : void 0;
7400
7688
  const embedder = backing?.embedder;
7401
- if (!embedder && !ctx.hasEmbedder()) return Value.of(0);
7689
+ if (!embedder && !ctx.hasEmbedder() && !ctx.resolveEmbedding) return Value.of(0);
7402
7690
  const queryVec = await this.queryVector(ctx, q, embedder);
7403
7691
  if (!queryVec) return Value.of(0);
7404
7692
  const rec = row[this.source] ?? ctx.correlation?.[this.source];
@@ -7531,11 +7819,44 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7531
7819
  if (!bound || bound.kind !== "type") return void 0;
7532
7820
  return ctx.engine.semanticBacking(bound.type.name, field);
7533
7821
  }
7534
- /** The query side of the similarity, emitted for SQL (text / param only). */
7535
- querySQL(dialect, ctx) {
7536
- if (this.query.kind === "text") return SqlText.param(this.query.text);
7537
- if (this.query.kind !== "param") return SqlText.raw("0");
7538
- return this.query.param.toSQL(dialect, ctx);
7822
+ /**
7823
+ * The query side of the similarity, emitted for SQL (text / param only). A
7824
+ * `semantic(...)` term is TEXT — never a raw embedding — so a literal (and a
7825
+ * plain-text param VALUE) is EMBEDDED into a pgvector TEXT literal (`[…]`) via
7826
+ * the caller's `ctx.semanticText` converter before it is bound; the dialect
7827
+ * then casts it `::vector`. Two existing valid inputs are preserved untouched:
7828
+ * a PRE-EMBEDDED vector-text term / param (already `[…]`) is bound as-is, and a
7829
+ * `null` / absent param binds `null`. When a plain-text term is hit but NO
7830
+ * embeddings cache was supplied — or the term is missing from it — this THROWS
7831
+ * (rather than emitting the invalid `'<text>'::vector`).
7832
+ */
7833
+ querySQL(_dialect, ctx) {
7834
+ const q = this.query;
7835
+ if (q.kind === "text") {
7836
+ if (isVectorText(q.text)) return SqlText.param(q.text);
7837
+ return SqlText.param(this.vectorTextForSql(ctx, q.text));
7838
+ }
7839
+ if (q.kind !== "param") return SqlText.raw("0");
7840
+ const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, q.param.name) ? ctx.params[q.param.name] : null;
7841
+ if (raw2 === null || typeof raw2 === "object") return SqlText.param(null);
7842
+ const text = String(raw2);
7843
+ if (isVectorText(text)) return SqlText.param(text);
7844
+ return SqlText.param(this.vectorTextForSql(ctx, text));
7845
+ }
7846
+ /**
7847
+ * Resolve a plain-text semantic term to its pgvector TEXT literal via the
7848
+ * caller's precomputed embeddings (`ctx.semanticText`, built from
7849
+ * `toSQL({ embeddings })`), or THROW a directed error when no cache was
7850
+ * supplied. The converter itself throws when the cache lacks THIS term.
7851
+ */
7852
+ vectorTextForSql(ctx, text) {
7853
+ const convert = ctx.semanticText;
7854
+ if (!convert) {
7855
+ throw new Error(
7856
+ `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.`
7857
+ );
7858
+ }
7859
+ return convert(text);
7539
7860
  }
7540
7861
  /** Serialize back to its JSON ExprDef. */
7541
7862
  toJSON() {
@@ -9860,7 +10181,8 @@ function fieldReadonly(op, typeName, field) {
9860
10181
  function boundSQL(v, ctx) {
9861
10182
  if (v === void 0) return void 0;
9862
10183
  if (typeof v === "number") return SqlText.raw(String(v));
9863
- const value2 = Object.prototype.hasOwnProperty.call(ctx.params, v.name) ? ctx.params[v.name] : null;
10184
+ const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, v.name) ? ctx.params[v.name] : null;
10185
+ const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
9864
10186
  return SqlText.param(value2);
9865
10187
  }
9866
10188
 
@@ -10882,6 +11204,12 @@ var RuntimeContext = class {
10882
11204
  */
10883
11205
  sourceTypes = /* @__PURE__ */ new Map();
10884
11206
  embedder;
11207
+ /**
11208
+ * Precomputed text→vector cache for a semantic QUERY term (SQL parity), or
11209
+ * `undefined`. Normalized to a lookup function; `undefined` when no cache was
11210
+ * supplied.
11211
+ */
11212
+ resolveEmbedding;
10885
11213
  recordEmbedding;
10886
11214
  constructor(engine, options = {}) {
10887
11215
  this.engine = engine;
@@ -10891,6 +11219,7 @@ var RuntimeContext = class {
10891
11219
  this.sortSelection = options.sort ?? [];
10892
11220
  this.rlsProvider = options.rls;
10893
11221
  this.embedder = options.embedder ?? engine.embedder;
11222
+ this.resolveEmbedding = options.embeddings ? embeddingResolver(options.embeddings) : void 0;
10894
11223
  this.recordEmbedding = options.recordEmbedding;
10895
11224
  if (options.params) {
10896
11225
  for (const name of Object.keys(options.params)) {
@@ -15496,6 +15825,7 @@ function assertNever9(value2) {
15496
15825
  }
15497
15826
 
15498
15827
  // src/engine.ts
15828
+ var PLACEHOLDER_VECTOR_TEXT = "[0]";
15499
15829
  var QueryEngine = class {
15500
15830
  /** The registry of types, field types, exprs, queries, dialects, and functions. */
15501
15831
  registry;
@@ -15809,15 +16139,87 @@ var QueryEngine = class {
15809
16139
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
15810
16140
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
15811
16141
  * "$total"` column on the top-level SELECT.
16142
+ *
16143
+ * `opts.embeddings` is a precomputed text→vector cache (see {@link
16144
+ * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
16145
+ * `semantic(...)` text PARAM — is looked up there, formatted to a pgvector TEXT
16146
+ * literal (`[…]`), and bound (all synchronous). Obtain the terms to embed with
16147
+ * {@link semanticTexts}, embed them, fill the cache, then call this. A
16148
+ * plain-text semantic term with NO cache — or one MISSING from the cache —
16149
+ * THROWS (rather than emitting the invalid `'<text>'::vector`); a pre-embedded
16150
+ * `[…]` vector-text param is always bound as-is (never looked up).
15812
16151
  */
15813
16152
  toSQL(query, dialect, opts) {
16153
+ return this.emitSQL(query, dialect, opts, this.semanticConverter(opts?.embeddings));
16154
+ }
16155
+ /**
16156
+ * Extract the DISTINCT plain-text `semantic(...)` terms in `query` (+ the same
16157
+ * execution-time `opts` `toSQL` sees — `filters` / `params` can carry a semantic
16158
+ * text term) that need embedding, in a STABLE (first-seen) order. Give it a
16159
+ * query + params, get back the text to embed: embed each, fill a
16160
+ * {@link SemanticEmbeddings} cache, then pass that as `toSQL`'s `opts.embeddings`.
16161
+ *
16162
+ * Reuses `toSQL`'s exact emit walk (a discarded COLLECTING pass) rather than a
16163
+ * second walker, so it sees precisely the terms `toSQL` would bind. A term
16164
+ * already in pgvector TEXT form (`[…]`) needs no embedding and is NOT returned;
16165
+ * an absent / relation-`{ pk }` param value is not a semantic term and is
16166
+ * skipped.
16167
+ */
16168
+ semanticTexts(query, opts) {
16169
+ const terms = /* @__PURE__ */ new Set();
16170
+ const dialect = this.collectDialect();
16171
+ this.emitSQL(query, dialect, opts, (text) => {
16172
+ terms.add(text);
16173
+ return PLACEHOLDER_VECTOR_TEXT;
16174
+ });
16175
+ return [...terms];
16176
+ }
16177
+ /**
16178
+ * A dialect for the discarded {@link semanticTexts} pass. The rendered
16179
+ * SQL is thrown away and every dialect drives the same semantic-term walk (a
16180
+ * `semantic(...)` term's query side is emitted — hence collected — regardless of
16181
+ * dialect), so any registered dialect serves; the first is used.
16182
+ */
16183
+ collectDialect() {
16184
+ const d = this.registry.dialectList()[0];
16185
+ if (!d) throw new Error("QueryEngine.semanticTexts: no dialect registered.");
16186
+ return d;
16187
+ }
16188
+ /**
16189
+ * Build the INTERNAL sync `semanticText` seam (text → pgvector TEXT) the emit
16190
+ * path threads, from a precomputed {@link SemanticEmbeddings} cache: look the
16191
+ * term up and format its vector with {@link toVectorText}; a term MISSING from
16192
+ * the cache throws the same fail-loud error the emit path would (never a
16193
+ * silently mis-bound `'<text>'::vector`). Returns `undefined` when no cache was
16194
+ * supplied, so a plain-text term then hits the emit path's own "no embeddings"
16195
+ * throw.
16196
+ */
16197
+ semanticConverter(embeddings) {
16198
+ if (!embeddings) return void 0;
16199
+ const resolve = embeddingResolver(embeddings);
16200
+ return (text) => {
16201
+ const vector = resolve(text);
16202
+ if (vector === void 0) {
16203
+ throw new Error(
16204
+ `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).`
16205
+ );
16206
+ }
16207
+ return toVectorText(vector);
16208
+ };
16209
+ }
16210
+ /**
16211
+ * Shared SQL-emit core for {@link toSQL} / {@link semanticTexts}: resolve
16212
+ * the dialect, build the root {@link SqlContext} (threading params / filters /
16213
+ * sort / includeTotal + the SYNC `semanticText` converter), and render.
16214
+ */
16215
+ emitSQL(query, dialect, opts, semanticText2) {
15814
16216
  const d = typeof dialect === "string" ? this.registry.dialect(dialect) : dialect;
15815
16217
  if (!d) throw new Error(`QueryEngine.toSQL: unknown dialect '${String(dialect)}'.`);
15816
16218
  const q = this.toQuery(query);
15817
16219
  const scope = this.globalScope();
15818
16220
  const params = opts?.params ?? {};
15819
16221
  const planner = new JoinCtePlanner(d, this, opts?.rls, params);
15820
- const ctx = new SqlContext(d, this, scope, planner, opts?.rls, false, params, this.parseFilters(opts?.filters), opts?.includeTotal ?? false, true, opts?.sort ?? []);
16222
+ const ctx = new SqlContext(d, this, scope, planner, opts?.rls, false, params, this.parseFilters(opts?.filters), opts?.includeTotal ?? false, true, opts?.sort ?? [], semanticText2);
15821
16223
  const rendered = q.toSQL(d, ctx).render(d);
15822
16224
  return { sql: rendered.sql, params: [...rendered.params] };
15823
16225
  }
@@ -17525,6 +17927,7 @@ export {
17525
17927
  drillDownInto,
17526
17928
  e,
17527
17929
  editDistance,
17930
+ embeddingResolver,
17528
17931
  epoch,
17529
17932
  eq,
17530
17933
  excluded,
@@ -17555,6 +17958,7 @@ export {
17555
17958
  isScalar,
17556
17959
  isScalarValue,
17557
17960
  isType,
17961
+ isVectorText,
17558
17962
  join,
17559
17963
  joinAlias,
17560
17964
  joinCode,
@@ -17592,6 +17996,7 @@ export {
17592
17996
  param2 as param,
17593
17997
  parseQueryRequest,
17594
17998
  parseQueryTool,
17999
+ parseVectorText,
17595
18000
  plain,
17596
18001
  pos,
17597
18002
  querySchema,
@@ -17640,6 +18045,7 @@ export {
17640
18045
  textSearch,
17641
18046
  timezoneSchema,
17642
18047
  toArrayRows,
18048
+ toVectorText,
17643
18049
  typeFromFields,
17644
18050
  typeMeta,
17645
18051
  value,