@aeye/query 0.5.0 → 0.6.1

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.d.ts CHANGED
@@ -30,11 +30,27 @@ type JsonValue = string | number | boolean | null | JsonValue[] | {
30
30
  /** A scalar (leaf) JSON value — the payload of a literal expression and of
31
31
  * filter values. */
32
32
  type ScalarValue = string | number | boolean | null;
33
+ /**
34
+ * One member of a field's CLOSED VALUE SET (see `NumberOptions.values` /
35
+ * `TextFieldTypeDef.values`) — the stored value plus an optional human label.
36
+ *
37
+ * The label rides along with the value deliberately: `FieldDef` already carries
38
+ * a `label` that `describeField` renders, so naming is not foreign to this
39
+ * package, and splitting membership from presentation would put ONE closed set
40
+ * in two places that can drift.
41
+ */
42
+ interface FieldValueDef {
43
+ /** The stored value — one member of the closed set. */
44
+ value: string | number;
45
+ /** Human-facing name for this member (defaults to the value itself). */
46
+ label?: string;
47
+ }
33
48
  /**
34
49
  * Numeric option bag, shared by the `number` field type and by `money`'s
35
50
  * inner numeric configuration.
36
51
  * - `whole` — integral values only.
37
52
  * - `minPlaces` / `maxPlaces` — decimal-place bounds (display / precision).
53
+ * - `values` — a CLOSED SET this column may hold (see below).
38
54
  */
39
55
  interface NumberOptions {
40
56
  min?: number;
@@ -42,6 +58,17 @@ interface NumberOptions {
42
58
  whole?: boolean;
43
59
  minPlaces?: number;
44
60
  maxPlaces?: number;
61
+ /**
62
+ * The closed set of values this column may hold — an enum expressed as a
63
+ * CONSTRAINT ON the underlying scalar rather than as a separate field-type
64
+ * `kind` (which would fork every comparison / SQL-type / value-schema path
65
+ * for what is one extra fact). Three things depend on it and none of them are
66
+ * reachable from outside the library: equality SELECTIVITY becomes a
67
+ * defensible `1/n` instead of the fixed guess, the model-facing description
68
+ * can say `one of a|b|c`, and `toValueSchema()` narrows to the members
69
+ * instead of answering "any number". Composes with `min`/`max`.
70
+ */
71
+ values?: FieldValueDef[];
45
72
  }
46
73
  /** The `number` field type — a numeric value with the shared `NumberOptions`. */
47
74
  interface NumberFieldTypeDef extends NumberOptions {
@@ -63,6 +90,13 @@ interface TextFieldTypeDef {
63
90
  * Default false ⇒ case-insensitive (text operators lower-case both operands).
64
91
  */
65
92
  sensitive?: boolean;
93
+ /**
94
+ * The closed set of values this column may hold — see `NumberOptions.values`
95
+ * for why membership is a query fact. Composes with `pattern`: a regex
96
+ * expresses a SHAPE, a value set expresses MEMBERSHIP, and they are different
97
+ * facts, so both may be declared.
98
+ */
99
+ values?: FieldValueDef[];
66
100
  }
67
101
  /** The `money` field type — a monetary amount plus optional currency. */
68
102
  interface MoneyFieldTypeDef {
@@ -89,6 +123,11 @@ interface RelationFieldTypeDef {
89
123
  * The relation field's NAME is the key for ALL purposes — there are no
90
124
  * exposed foreign-key fields. `owns` (the FK living on THIS type) is
91
125
  * INFERRED as `count === 1`; `count > 1` means the FK lives on the target.
126
+ * NOTE this holds for a DECLARED def only: the runtime discriminator is
127
+ * `RelationFieldType.isBelongsTo()` (`count === 1` AND no internal
128
+ * `inverseVia`), because a registry-materialized inverse is a has-many
129
+ * whatever its estimated `count` came out as. `inverseVia` is internal and
130
+ * never appears in this def.
92
131
  */
93
132
  count: number;
94
133
  /**
@@ -207,6 +246,19 @@ interface TypeDef {
207
246
  description?: string;
208
247
  fields: FieldDef[];
209
248
  indexes?: IndexDef[];
249
+ /**
250
+ * The field (or ordered fields) that IDENTIFY a row. When present it is THE
251
+ * answer for `Type.identityField()` / `Type.primaryKey()`: index ORDER becomes
252
+ * irrelevant, and a unique index on any other column is just a unique index.
253
+ *
254
+ * Without it identity is INFERRED as "the first single-part unique index, else
255
+ * the field named `id`" — which makes the identity of a Type depend on the
256
+ * order its indexes happen to be listed in. A Type declaring both `id` and a
257
+ * unique `email`, with the email index listed first, silently identifies by
258
+ * `email`, and every relation into it then joins a stored id against an email.
259
+ * Declaring it removes that whole class of failure.
260
+ */
261
+ identity?: string | string[];
210
262
  /** Estimated total row count — drives cost estimation. */
211
263
  count: number;
212
264
  /** Estimated average bytes per row (else derived as the sum of the fields' bytes). */
@@ -264,10 +316,19 @@ type UnaryOp = '-' | '+';
264
316
  type ComparisonOp = '=' | '<>' | '<' | '<=' | '>' | '>=' | 'like' | 'notLike' | 'ilike';
265
317
  /** Boolean connectives. `not` takes exactly one operand. */
266
318
  type LogicalOp = 'and' | 'or' | 'not';
267
- /** A literal scalar value. */
319
+ /**
320
+ * A literal constant VALUE — a scalar, or a whole JSON document (an object /
321
+ * array) for a `json` / `array` field.
322
+ *
323
+ * The non-scalar half exists because a WRITE CELL had no way to carry one: a
324
+ * `json` column could not be inserted or updated at all (a raw document was
325
+ * refused by the write parser, no expression could carry one, and the `param`
326
+ * route bound SQL `NULL` — see 0.6.1's A9). A non-scalar literal is bound as a
327
+ * single parameter through `Dialect.jsonValue`, never string-interpolated.
328
+ */
268
329
  interface LiteralExprDef {
269
330
  kind: 'literal';
270
- value: ScalarValue;
331
+ value: JsonValue;
271
332
  }
272
333
  /**
273
334
  * A direct field reference: `<source>.<field>`. Reuses `SourceFieldRef` — the
@@ -1063,6 +1124,15 @@ declare abstract class FieldType implements Node {
1063
1124
  * stricter or looser rules.
1064
1125
  */
1065
1126
  comparableWith(other: FieldType): boolean;
1127
+ /**
1128
+ * The fraction of rows a non-indexed EQUALITY predicate on a column of this
1129
+ * type is expected to keep, when the type itself knows better than the
1130
+ * package-wide `EQ_SELECTIVITY` guess. A closed value set of `n` members
1131
+ * answers `1/n`: a two-value flag keeps half the table, a fifty-value code
1132
+ * keeps 2% — today both are costed at the same fixed third. `undefined`
1133
+ * (the default) means "no better estimate; use the fixed one".
1134
+ */
1135
+ eqSelectivity(): number | undefined;
1066
1136
  /**
1067
1137
  * Whether TEXTUAL matching / comparison on a value of this type is
1068
1138
  * CASE-SENSITIVE. Default false (case-insensitive); only `text` fields
@@ -1105,7 +1175,6 @@ declare abstract class FieldType implements Node {
1105
1175
  * getter so a dialect INSTANCE can be registered directly.
1106
1176
  */
1107
1177
 
1108
- /** The abstract SQL-dialect contract; concrete dialects override the engine-specific points. */
1109
1178
  declare abstract class Dialect implements DialectEntry {
1110
1179
  /** The dialect's canonical name (e.g. `'base'`, `'postgres'`). */
1111
1180
  abstract readonly name: string;
@@ -1210,7 +1279,41 @@ declare abstract class Dialect implements DialectEntry {
1210
1279
  /** Shared lateral-join assembly; `on` is the raw ON-condition literal. */
1211
1280
  protected lateralJoinWith(subquery: SqlText, alias: string, joinType: 'left' | 'inner', on: string): SqlText;
1212
1281
  /** The SQL field type for a field type in this dialect. */
1282
+ /**
1283
+ * Build a JSON OBJECT from ordered `key → value` pairs — how a relation's
1284
+ * IDENTITY reaches the result boundary (`{ id: 5 }`, `{ tenantId: 3, userId: 1 }`).
1285
+ *
1286
+ * `json_build_object` is not ANSI, but neither is `json_array_length` which
1287
+ * this base dialect already emits for `arrayLength`: the portable dialect is
1288
+ * portable-ISH, and degrading a structured value to a concatenated string
1289
+ * would be worse than depending on the same JSON support that is already
1290
+ * assumed. Dialects with a richer JSON type override this.
1291
+ */
1292
+ jsonObject(entries: readonly {
1293
+ key: string;
1294
+ value: SqlText;
1295
+ }[]): SqlText;
1213
1296
  abstract sqlTypeFor(fieldType: FieldType): string;
1297
+ /**
1298
+ * Bind a whole JSON DOCUMENT (an object / array) as ONE parameter, cast to the
1299
+ * column type it is destined for. The single binding path for a non-scalar
1300
+ * VALUE — a `json` cell, an `array` cell, a document literal in a predicate.
1301
+ *
1302
+ * WHY A CAST, AND WHY THE FIELD TYPE. The document travels as its JSON TEXT in
1303
+ * a normal parameter slot (so `SqlValue` stays scalar and nothing is ever
1304
+ * string-interpolated), which means the server must be told what to parse it
1305
+ * AS. Left to inference, the same text is a `jsonb` in one column and a syntax
1306
+ * error in another. `fieldType` — supplied by the WRITE path, which knows the
1307
+ * column — makes that explicit; without it (a bare literal in a `where`, which
1308
+ * knows only its own shape) the dialect's own JSON type is the default.
1309
+ *
1310
+ * The base dialect casts to whatever `sqlTypeFor` names, which is the portable
1311
+ * answer for a JSON-typed column. A dialect with a NATIVE array type (Postgres
1312
+ * `text[]`) must override — an array literal there is not JSON text.
1313
+ */
1314
+ jsonValue(value: JsonValue, fieldType?: FieldType): SqlText;
1315
+ /** This dialect's JSON column type — the default cast target for a document. */
1316
+ jsonSqlType(): string;
1214
1317
  /**
1215
1318
  * Length (element count) of array expression `arg`. Postgres `cardinality`;
1216
1319
  * the base dialect degrades to `COALESCE(json_array_length(arg), 0)`.
@@ -1294,8 +1397,16 @@ interface RelationResolved {
1294
1397
  readonly keyType: FieldType;
1295
1398
  /** The relation's target Type name (its `to`). */
1296
1399
  readonly to: string;
1297
- /** Cardinality: `1` = belongs-to (single target row), `>1` = has-many (a set). */
1400
+ /** Declared cardinality of the related rows (`1` = one-to-one / belongs-to shaped). */
1298
1401
  readonly count: number;
1402
+ /**
1403
+ * Which side the FOREIGN KEY is on: true = belongs-to, so this row holds the
1404
+ * target's identity locally; false = has-many, a SET keyed on the target.
1405
+ * Read this rather than `count` — a MATERIALIZED INVERSE can carry an
1406
+ * estimated `count` of 1 and is still a has-many (see
1407
+ * `RelationFieldType.isBelongsTo`).
1408
+ */
1409
+ readonly belongsTo: boolean;
1299
1410
  /** The ORDERED join-key pairs (composite-capable) driving relation comparison lowering. */
1300
1411
  readonly keys: readonly RelationKeyPair[];
1301
1412
  }
@@ -1357,6 +1468,20 @@ declare function sourcesOf(rt: ResolvedType): readonly FieldResolved[];
1357
1468
  declare function widenNullable(rt: ResolvedType, nullable?: boolean): ResolvedType;
1358
1469
  /** Type guard: a resolved type. */
1359
1470
  declare function isType(rt: ResolvedType): rt is TypeResolved;
1471
+ /**
1472
+ * The relation info when `rt` is a Type resolved from a relation FIELD-REF
1473
+ * (a belongs-to / has-many field), else `undefined`. Used by the scalar
1474
+ * operators to reject a relation used as a value and to allow (and key-compare)
1475
+ * a relation-vs-relation comparison.
1476
+ */
1477
+ declare function relationOf(rt: ResolvedType): RelationResolved | undefined;
1478
+ /**
1479
+ * The comparable-VALUE field type of a resolved value: its scalar field type,
1480
+ * else — for a relation Type — the relation's key value type. Used to type a
1481
+ * bind param compared against the operand (a relation compares by its FK key).
1482
+ * A non-relation whole Type has none.
1483
+ */
1484
+ declare function valueFieldType(rt: ResolvedType): FieldType | undefined;
1360
1485
  /** Type guard: a resolved scalar (field or computed value, never a type). */
1361
1486
  declare function isScalar(rt: ResolvedType): rt is FieldResolved | ComputedResolved;
1362
1487
 
@@ -1960,8 +2085,8 @@ interface ResolvedRelationOn {
1960
2085
  *
1961
2086
  * CONVENTION: a relation field's NAME is the key for all purposes. There are
1962
2087
  * no exposed foreign-key fields — `owns` (FK on THIS type, "belongs-to") is
1963
- * INFERRED as `count === 1`; `count > 1` ⇒ has-many (FK on the target). See
1964
- * `resolveKey`.
2088
+ * INFERRED as `count === 1` AND no `inverseVia` (see `isBelongsTo`); otherwise
2089
+ * has-many (FK on the target). See `resolveKey`.
1965
2090
  *
1966
2091
  * `inverseRelation`, when set on a belongs-to relation, asks the registry to
1967
2092
  * materialize a one-to-many relation of that name back on the TARGET Type.
@@ -1995,14 +2120,29 @@ declare class RelationFieldType extends FieldType {
1995
2120
  static from(json: FieldTypeDef): RelationFieldType;
1996
2121
  /** The Zod schema for this field type's JSON def. */
1997
2122
  static toSchema(): z.ZodTypeAny;
2123
+ /**
2124
+ * True when the FOREIGN KEY lives on THIS Type — a declared belongs-to. The
2125
+ * cardinality alone is NOT the discriminator: a MATERIALIZED INVERSE (one
2126
+ * carrying {@link inverseVia}) is never belongs-to however its estimated
2127
+ * `count` came out, because `Registry.finalize()` derives that count from a
2128
+ * ROW RATIO (`round(source.count / target.count)`) — so a 1:1 pair, or two
2129
+ * unmeasured Types sharing one declared row estimate, legitimately yields 1.
2130
+ *
2131
+ * Reading `count === 1` alone made such an inverse resolve its join as
2132
+ * `order.invoice = invoice.id`, where `order.invoice` is the SYNTHETIC
2133
+ * relation field the registry just added rather than a column — every
2134
+ * traversal then matched zero rows, silently. The FK side is knowable from
2135
+ * `inverseVia`; this is where that knowledge is applied.
2136
+ */
2137
+ isBelongsTo(): boolean;
1998
2138
  /**
1999
2139
  * Resolve the join key for this relation, given the relation field's NAME and
2000
2140
  * the two Types it relates. The relation field's NAME is the key:
2001
- * - belongs-to (`count === 1`): `this.<relName> = target.<identity>` —
2141
+ * - belongs-to ({@link isBelongsTo}): `this.<relName> = target.<identity>` —
2002
2142
  * the local relation field holds the target's identity value.
2003
- * - has-many (`count > 1`): `this.<identity> = target.<fk>` — where the
2004
- * FK on the target is `inverseVia` (for a materialized inverse) else the
2005
- * declaring Type's name in camelCase.
2143
+ * - has-many: `this.<identity> = target.<fk>` — where the FK on the target
2144
+ * is `inverseVia` (for a materialized inverse) else the declaring Type's
2145
+ * name in camelCase.
2006
2146
  */
2007
2147
  resolveKey(relationFieldName: string, thisType: Type, targetType: Type): RelationKey;
2008
2148
  /**
@@ -2025,7 +2165,7 @@ declare class RelationFieldType extends FieldType {
2025
2165
  * source, `targetAlias` = the target), so aliased / self-joins resolve.
2026
2166
  *
2027
2167
  * The backing lives on the OWNING (belongs-to) relation. A materialized
2028
- * inverse has-many (`count > 1` with an `inverseVia`) REUSES the SAME FK: its
2168
+ * inverse has-many (one carrying an `inverseVia`) REUSES the SAME FK: its
2029
2169
  * forward relation's `relation` backing on the target Type, with the key
2030
2170
  * orientation SWAPPED (the declaring side is now the join's target). A
2031
2171
  * directly-declared has-many (no `inverseVia`) has no forward relation to
@@ -2054,7 +2194,7 @@ declare class FieldRefExpr extends Expr {
2054
2194
  readonly field: string;
2055
2195
  static readonly KIND: "field-ref";
2056
2196
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
2057
- static readonly 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.";
2197
+ static readonly INSTRUCTIONS: "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a BELONGS-TO RELATION field IS a value: it projects the relation's IDENTITY \u2014 the target's key read off THIS row's own key column(s), as an object keyed by the target's identity field names (`{id:'u1'}`, `{tenantId:3,userId:1}`), NULL when unset \u2014 planning NO join and applying no target scope. Legal in `fields` / `RETURNING`, `order`, `groupBy`, `is null`, and an identity `=` / `<>` / `in`. To read any OTHER field of the target, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. A HAS-MANY ref is REFUSED (`ref.relation-has-many`) \u2014 it has no key on this row and its value is a SET: join it, or test membership against a target key. A relation is still NOT a value as an arithmetic operand / `case` arm / function argument / aggregate; and to CORRELATE a subquery, join the relation and compare the joined key \u2014 never a relation field-ref against an id/scalar.";
2058
2198
  readonly kind: "field-ref";
2059
2199
  /** Wrap a `<source>.<field>` reference by its source alias and field name. */
2060
2200
  constructor(source: string, field: string);
@@ -2080,12 +2220,42 @@ declare class FieldRefExpr extends Expr {
2080
2220
  private resolveRelation;
2081
2221
  /** Validate the source resolves to a type and has the named field; report problems. */
2082
2222
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): ResolvedType;
2223
+ /**
2224
+ * Report the relation-as-value problem for this position, if any. Split into
2225
+ * three distinct outcomes because they have three different fixes:
2226
+ * - an identity-value position + a BELONGS-TO ⇒ fine, it has a local key;
2227
+ * - an identity-value position + a HAS-MANY ⇒ there is no key on this row at
2228
+ * all and its "value" is a set, so say that instead of the join-it hint;
2229
+ * - inside an AGGREGATE ⇒ an identity is not summable/averageable/max-able
2230
+ * under any representation, so say that;
2231
+ * - anywhere else ⇒ the long-standing "join it" hint.
2232
+ */
2233
+ private checkRelationUse;
2083
2234
  /** Zero rows; cost is just the resolved field's byte size. */
2084
2235
  cost(ctx: CostContext, scope: QueryScope): Cost;
2085
2236
  /** A field-ref IS a plain column reference (drives GROUP BY / index-key costing). */
2086
2237
  fieldRef(): FieldRefExpr;
2087
2238
  /** Read the field's runtime value, honoring backing (joins/compute/access security). */
2088
2239
  evaluate(ctx: RuntimeContext, row: SourceRow | null): Promise<Value>;
2240
+ /**
2241
+ * Read this ref as a plain COLUMN, skipping the relation-identity projection.
2242
+ *
2243
+ * Needed because a belongs-to's local key column and the relation FIELD share
2244
+ * a name under the package's name convention (`order.userId` is both the
2245
+ * relation and the column holding its key). Every internal reader of a key
2246
+ * column — relation comparison lowering, ORDER BY / GROUP BY expansion, an
2247
+ * `IN` against a scalar subquery — wants the COLUMN; going through
2248
+ * {@link evaluate} would resolve the relation again and hand back the identity
2249
+ * object. Backing (compute / lateral / stored-name remap / access) still
2250
+ * applies exactly as it does for any other column.
2251
+ */
2252
+ columnValue(ctx: RuntimeContext, row: SourceRow | null): Promise<Value>;
2253
+ /**
2254
+ * Apply this field's `access` backing (FLS) to an already-computed value: a
2255
+ * denied field reads NULL. Shared by the relation-identity path, which
2256
+ * bypasses the stored/compute/lateral resolution but must not bypass security.
2257
+ */
2258
+ private securedRun;
2089
2259
  /** Read a stored field off the bound record, attaching the conceptual field's metadata. */
2090
2260
  private storedValue;
2091
2261
  /**
@@ -2102,6 +2272,18 @@ declare class FieldRefExpr extends Expr {
2102
2272
  private attachRelationRun;
2103
2273
  /** Emit as a SqlText column ref, lowering backing (joins/compute/access) when present. */
2104
2274
  toSQL(dialect: Dialect, ctx: SqlContext): SqlText;
2275
+ /**
2276
+ * Emit this ref as a plain COLUMN, skipping the relation-identity projection —
2277
+ * the SQL twin of {@link columnValue}, and needed for the same reason (a
2278
+ * belongs-to's key column shares the relation field's name).
2279
+ */
2280
+ columnSQL(dialect: Dialect, ctx: SqlContext): SqlText;
2281
+ /**
2282
+ * Apply this field's `access` backing (FLS) to an already-emitted fragment —
2283
+ * the SQL twin of {@link securedRun}, so a relation identity is secured by the
2284
+ * same rule as any other column.
2285
+ */
2286
+ private securedSql;
2105
2287
  /**
2106
2288
  * Register every named join this field opts into with the planner (SQL),
2107
2289
  * deduped on the join's deterministic alias so N fields sharing a join emit
@@ -2253,15 +2435,15 @@ declare function bytesOfResolved(rt: ResolvedType): number;
2253
2435
  */
2254
2436
  declare function reportCostProblems(cost: Cost, constraints: CostConstraints, p: Problems): void;
2255
2437
 
2256
- /** A constant scalar value (`string | number | boolean | null`). */
2438
+ /** A constant value: a scalar, or a whole JSON document (object / array). */
2257
2439
  declare class LiteralExpr extends Expr {
2258
- readonly value: ScalarValue;
2440
+ readonly value: JsonValue;
2259
2441
  static readonly KIND: "literal";
2260
2442
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
2261
- static readonly INSTRUCTIONS: "A constant scalar value.";
2443
+ static readonly INSTRUCTIONS: "A constant value: a scalar (string / number / boolean / null), or a whole JSON DOCUMENT (object / array) for a `json` / `array` field \u2014 which is how a write cell carries one. A document is bound as ONE parameter, never interpolated.";
2262
2444
  readonly kind: "literal";
2263
- /** Wrap a constant scalar value (`string | number | boolean | null`). */
2264
- constructor(value: ScalarValue);
2445
+ /** Wrap a constant value: a scalar, or a whole JSON document. */
2446
+ constructor(value: JsonValue);
2265
2447
  /** Reconstruct a LiteralExpr from its JSON def (validates the `kind` discriminant). */
2266
2448
  static from(json: ExprDef, _registry: Registry): LiteralExpr;
2267
2449
  /**
@@ -2282,8 +2464,17 @@ declare class LiteralExpr extends Expr {
2282
2464
  cost(ctx: CostContext, scope: QueryScope): Cost;
2283
2465
  /** Evaluate to the wrapped constant value. */
2284
2466
  evaluate(): Promise<Value>;
2285
- /** Emit as a SqlText fragment — `NULL` keyword or a bound param. */
2286
- toSQL(_dialect: Dialect, _ctx: SqlContext): SqlText;
2467
+ /**
2468
+ * Emit as a SqlText fragment — `NULL` keyword, a bound scalar param, or a
2469
+ * bound DOCUMENT.
2470
+ *
2471
+ * A document has no target field type HERE (a bare literal in a WHERE knows
2472
+ * only its own shape), so it binds through the dialect's default json type.
2473
+ * The WRITE path emits its cells through `writeCellSql`, which supplies the
2474
+ * target COLUMN's field type — the difference between a Postgres `jsonb` cast
2475
+ * and the `ARRAY[…]::text[]` a native array column actually needs.
2476
+ */
2477
+ toSQL(dialect: Dialect, _ctx: SqlContext): SqlText;
2287
2478
  /** Serialize back to its JSON ExprDef. */
2288
2479
  toJSON(): LiteralExprDef;
2289
2480
  /** Deep-copy this expr. */
@@ -2543,8 +2734,23 @@ declare class ParamExpr extends Expr {
2543
2734
  cost(ctx: CostContext, scope: QueryScope): Cost;
2544
2735
  /** Evaluate to the runtime-bound value for this param name. */
2545
2736
  evaluate(ctx: RuntimeContext): Promise<Value>;
2546
- /** Emit as a bound SqlText param slot (null until a value is supplied). */
2547
- toSQL(_dialect: Dialect, ctx: SqlContext): SqlText;
2737
+ /**
2738
+ * Emit as a bound SqlText param slot (NULL until a value is supplied).
2739
+ *
2740
+ * A NON-SCALAR bound value — a JSON document, or a relation `{ pk }` object
2741
+ * that reached here undecomposed — binds through `Dialect.jsonValue`, NOT as
2742
+ * NULL. Binding NULL was the worst outcome available (A9): the statement
2743
+ * SUCCEEDED and the supplied value was silently dropped, so an INSERT of a
2744
+ * `json` column through a param appeared to work and lost the data. A
2745
+ * relation comparison still decomposes its `{ pk }` object into per-column
2746
+ * binds before reaching here, so that path is unchanged; anything that DOES
2747
+ * get here is a value the caller supplied, and is bound as one.
2748
+ *
2749
+ * A write CELL routes through `writeCellSql` first, which also knows the
2750
+ * target column's field type; this is the fallback for every other position,
2751
+ * which knows only the value's own shape.
2752
+ */
2753
+ toSQL(dialect: Dialect, ctx: SqlContext): SqlText;
2548
2754
  /** Serialize back to its JSON ExprDef. */
2549
2755
  toJSON(): ParamExprDef;
2550
2756
  /** Deep-copy this expr. */
@@ -2661,8 +2867,20 @@ declare class ComparisonExpr extends BoolExpr {
2661
2867
  * equality and the equality-like ops (`= <> like notLike ilike`) keep ~a third.
2662
2868
  * An index-covered `=` is discounted separately by the cost model (via
2663
2869
  * {@link indexProbe}); this is the non-indexed fallback.
2870
+ *
2871
+ * An `=` against a column whose field type declares a CLOSED VALUE SET uses
2872
+ * that type's own `1/n` instead of the fixed third — the one case where the
2873
+ * schema knows the real answer (`FieldType.eqSelectivity`).
2664
2874
  */
2665
- selectivity(): number;
2875
+ selectivity(ctx: CostContext, scope: QueryScope): number;
2876
+ /**
2877
+ * The `1/n` an operand's declared closed value set implies, or `undefined`
2878
+ * when neither side declares one. Both operands are consulted so
2879
+ * `:param = order.status` costs the same as `order.status = :param`; when both
2880
+ * declare a set the TIGHTER (smaller) estimate wins, since satisfying both
2881
+ * memberships can only narrow further.
2882
+ */
2883
+ private closedSetSelectivity;
2666
2884
  /** An `=` against a column is an index point-probe (arity 1); other ops are not. */
2667
2885
  indexProbe(): IndexProbe | undefined;
2668
2886
  /** Evaluate under 3VL: a NULL operand yields UNKNOWN; text compares case-insensitively unless a `sensitive` field is involved. */
@@ -2772,7 +2990,7 @@ declare class InExpr extends BoolExpr {
2772
2990
  readonly not: boolean;
2773
2991
  static readonly KIND: "in";
2774
2992
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
2775
- static readonly 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.";
2993
+ static readonly 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. A COMPOSITE-key relation may NOT use the subquery form (`in.relation-composite`) \u2014 one projected field cannot match a multi-column key, so list its `{ pk }` values instead. Inside the SUBQUERY, cross a relation with a `relation` join and field-ref the joined alias: projecting the relation field-ref itself yields its IDENTITY OBJECT, not a scalar id, and is refused here (`compare.relation-vs-value`). To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
2776
2994
  /**
2777
2995
  * Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
2778
2996
  * value LIST, and a single-field SUBQUERY that crosses a relation via a
@@ -2872,7 +3090,7 @@ declare class IsNullExpr extends BoolExpr {
2872
3090
  readonly not: boolean;
2873
3091
  static readonly KIND: "is-null";
2874
3092
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
2875
- static readonly INSTRUCTIONS: "`value IS [NOT] NULL`.";
3093
+ static readonly INSTRUCTIONS: "`value IS [NOT] NULL`. On a BELONGS-TO relation field-ref it tests whether the relation is UNSET \u2014 the KEY COLUMNS, so it stays index-usable; a HAS-MANY there is refused (`ref.relation-has-many`) \u2014 use `[NOT] EXISTS` over the related rows instead.";
2876
3094
  readonly kind: "is-null";
2877
3095
  /** Wrap `value IS [NOT] NULL` as a null test. */
2878
3096
  constructor(value: Expr, not: boolean);
@@ -2896,7 +3114,17 @@ declare class IsNullExpr extends BoolExpr {
2896
3114
  selectivity(): number;
2897
3115
  /** Evaluate the operand and return whether it is (not) null. */
2898
3116
  evaluateBool(ctx: RuntimeContext, row: SourceRow, group?: readonly SourceRow[]): Promise<boolean>;
2899
- /** Emit as a SqlText fragment (`value IS [NOT] NULL`). */
3117
+ /**
3118
+ * Emit as a SqlText fragment (`value IS [NOT] NULL`).
3119
+ *
3120
+ * A RELATION operand tests its KEY COLUMNS, not the assembled identity
3121
+ * object: the object is a constructed value and is never SQL NULL, so
3122
+ * `json_build_object(...) IS NULL` would be a constant false. Unset means any
3123
+ * key column is null (a partial composite key cannot join), so `IS NULL` is
3124
+ * the OR over them and `IS NOT NULL` the AND of their negations — which also
3125
+ * keeps the predicate index-usable. Matches the runtime, where a relation
3126
+ * ref with any null key evaluates to NULL.
3127
+ */
2900
3128
  toSQL(dialect: Dialect, ctx: SqlContext): SqlText;
2901
3129
  /** Serialize back to its JSON ExprDef. */
2902
3130
  toJSON(): IsNullExprDef;
@@ -3079,7 +3307,7 @@ declare class AggregateExpr extends Expr {
3079
3307
  readonly distinct: boolean;
3080
3308
  static readonly KIND: "aggregate";
3081
3309
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3082
- static readonly INSTRUCTIONS: "An aggregate function over a group (`count(*)` = empty args); optional `distinct`.";
3310
+ static readonly INSTRUCTIONS: "An aggregate function over a group (`count(*)` = empty args); optional `distinct`. A RELATION field-ref is NOT aggregable (`ref.relation-aggregate`) \u2014 its value is an IDENTITY: group by it, or aggregate a scalar off a `relation`-joined alias.";
3083
3311
  readonly kind: "aggregate";
3084
3312
  /** Wrap a registered aggregate `fn` with its named `args` and a DISTINCT flag. */
3085
3313
  constructor(fn: string,
@@ -3522,7 +3750,7 @@ declare class TextSearchExpr extends BoolExpr {
3522
3750
  readonly query: TextSearchQuery;
3523
3751
  static readonly KIND: "text-search";
3524
3752
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3525
- static readonly INSTRUCTIONS: "Full-text predicate over a source (optionally one field) \u2192 boolean.";
3753
+ static readonly INSTRUCTIONS: "Full-text predicate over a source (optionally one field) \u2192 boolean. NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source search is REFUSED (`text-search.unbacked`) rather than guessing a column.";
3526
3754
  readonly kind: "text-search";
3527
3755
  /** Wrap the bound `source` (optional `field`) and the search query text. */
3528
3756
  constructor(source: string, field: string | undefined, query: TextSearchQuery);
@@ -3578,7 +3806,7 @@ declare class TextScoreExpr extends Expr {
3578
3806
  readonly query: TextSearchQuery;
3579
3807
  static readonly KIND: "text-score";
3580
3808
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3581
- static readonly INSTRUCTIONS: "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`).";
3809
+ static readonly INSTRUCTIONS: "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`). NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source score is REFUSED (`text-score.unbacked`) rather than guessing a column.";
3582
3810
  readonly kind: "text-score";
3583
3811
  /** Wrap the bound `source` (optional `field`) and the query text to rank against. */
3584
3812
  constructor(source: string, field: string | undefined, query: TextSearchQuery);
@@ -4143,12 +4371,19 @@ declare class JoinCtePlanner {
4143
4371
  /** A value that may be bound as a SQL parameter. */
4144
4372
  type SqlValue = string | number | boolean | null;
4145
4373
  /**
4146
- * A supplied param value: a bindable scalar, OR a RELATION KEY object (`{ pk }`
4147
- * keyed by the target's PK field names) used on the RHS of a relation
4148
- * comparison (`assignedUser = { id: 5 }`). A relation comparison decomposes the
4149
- * object into per-column binds; a scalar binds directly.
4374
+ * A supplied param value:
4375
+ * - a bindable SCALAR, bound directly;
4376
+ * - a RELATION KEY object (`{ pk }`, keyed by the target's PK field names) on
4377
+ * the RHS of a relation comparison (`assignedUser = { id: 5 }`), which the
4378
+ * comparison decomposes into per-column binds;
4379
+ * - or a whole JSON DOCUMENT for a `json` / `array` cell, bound as ONE
4380
+ * parameter through `Dialect.jsonValue` (0.6.1's A9 — such a value used to
4381
+ * bind SQL `NULL`, so the write succeeded and the data was dropped).
4382
+ *
4383
+ * `JsonValue` subsumes the relation-key object; the three cases are spelled out
4384
+ * because they are read very differently at the point of use.
4150
4385
  */
4151
- type SqlParamValue = SqlValue | Readonly<Record<string, SqlValue>>;
4386
+ type SqlParamValue = JsonValue;
4152
4387
  /** A rendered SQL string plus its ordered bind parameters. */
4153
4388
  interface RenderedSql {
4154
4389
  /** The flat SQL string with dialect-numbered placeholders. */
@@ -4645,6 +4880,18 @@ interface RelationBacking {
4645
4880
  /** A dynamic, alias-correct custom `ON` (overrides `keys`). See {@link RelationOn}. */
4646
4881
  on?: RelationOn;
4647
4882
  }
4883
+ /**
4884
+ * Map a `RelationBacking`'s declared `keys` to ON column pairs ORIENTED to a
4885
+ * join's source (left) + target aliases. `forward` = the join goes the
4886
+ * belongs-to direction (the source alias is the declaring side); when `false`
4887
+ * (a has-many inverse reusing the forward FK) the orientation is swapped.
4888
+ * `targetIdentity` supplies the default column for any pair that omits `foreign`
4889
+ * (the belongs-to TARGET's identity field).
4890
+ */
4891
+ declare function relationKeyColumns(keys: ReadonlyArray<{
4892
+ local: string;
4893
+ foreign?: string;
4894
+ }>, forward: boolean, targetIdentity: string): RelationOnPair[];
4648
4895
  /**
4649
4896
  * The dev-side backing for a whole Type. All members are optional:
4650
4897
  * - `name` is the real underlying source name (default = the Type name); SQL
@@ -4891,6 +5138,13 @@ interface DefaultOrder {
4891
5138
  /** Which SELECTs receive this order (default `'result'`). */
4892
5139
  applyTo?: DefaultOrderScope;
4893
5140
  }
5141
+ /** The direction + NULLs placement of a resolved default-order term. */
5142
+ interface DefaultOrderDir {
5143
+ /** Sort direction (a term's `dir`, defaulted to `'asc'`). */
5144
+ readonly dir: 'asc' | 'desc';
5145
+ /** Explicit NULLs placement, or `undefined` for the direction-based default. */
5146
+ readonly nulls: 'first' | 'last' | undefined;
5147
+ }
4894
5148
  /** The SQL-mode resolution of a `JoinBacking` (`sql` raw fragment, else a `JoinSpec`). */
4895
5149
  type JoinSqlPlan = {
4896
5150
  readonly kind: 'none';
@@ -5087,6 +5341,25 @@ declare class Field implements Node {
5087
5341
  * to `JsonValue` by the annotation.
5088
5342
  */
5089
5343
  declare function exprDigest(expr: ExprDef): string;
5344
+ /**
5345
+ * Rewrite every `field-ref` whose `source` is `from` to `to`, leaving every
5346
+ * other node untouched. Round-trips through JSON (so the result is a plain,
5347
+ * independently-owned def) — the same `JSON.parse`-annotated idiom
5348
+ * {@link exprDigest} uses, no casts.
5349
+ */
5350
+ declare function renameSource(expr: ExprDef, from: string, to: string): ExprDef;
5351
+ /**
5352
+ * The digest an ALIASED usage of `expr` matches an index part on.
5353
+ *
5354
+ * An index part is a TYPE-level fact, so it is necessarily written against the
5355
+ * Type NAME (`IndexPartDef.expr` is an `ExprDef`, and a `field-ref` requires a
5356
+ * `source`). A QUERY may bind that same Type under an alias — `FROM user AS u`,
5357
+ * or either side of a self-join — and then its refs read `u.email`, whose raw
5358
+ * digest can never equal the part's `user.email`. Normalizing the USAGE back to
5359
+ * the Type name is what lets a declared index actually apply; the stored part
5360
+ * digest ({@link IndexPart.digest}) is deliberately left exactly as it is.
5361
+ */
5362
+ declare function aliasedDigest(expr: ExprDef, alias: string, typeName: string): string;
5090
5363
  /** One ordered part of a composite index: an expr + its prefix cardinality. */
5091
5364
  declare class IndexPart {
5092
5365
  /** The indexed expression, stored as raw JSON this phase. */
@@ -5137,10 +5410,19 @@ declare class Index {
5137
5410
  * Because part counts are non-increasing, a longer matched prefix always
5138
5411
  * yields a smaller (or equal) estimate — so this returns the tightest bound
5139
5412
  * the supplied predicates can achieve via this index.
5413
+ *
5414
+ * `alias` names the SOURCE the supplied usages are bound under together with
5415
+ * the TYPE this index belongs to; when they differ, each usage is normalized
5416
+ * back to the type name before matching (see {@link aliasedDigest}). Omitting
5417
+ * it keeps the literal, un-normalized match — the identity case, and what
5418
+ * every pre-existing caller gets.
5140
5419
  */
5141
5420
  prefixReduction(used: ReadonlyArray<{
5142
5421
  toJSON(): ExprDef;
5143
- }>): number | undefined;
5422
+ }>, alias?: {
5423
+ source: string;
5424
+ typeName: string;
5425
+ }): number | undefined;
5144
5426
  /** Build an Index from its `IndexDef` JSON. */
5145
5427
  static from(json: IndexDef): Index;
5146
5428
  /** Serialize to its `IndexDef` JSON shape (emitting `bytes` only when authored explicitly). */
@@ -5168,6 +5450,12 @@ interface TypeSpec {
5168
5450
  fields: Field[];
5169
5451
  /** The (composite) indexes declared on this Type. */
5170
5452
  indexes: Index[];
5453
+ /**
5454
+ * The field (or ordered fields) that IDENTIFY a row. When set it is THE
5455
+ * answer for {@link Type.identityField} / {@link Type.primaryKey} and index
5456
+ * order stops mattering. Omit to fall back to the inferred rule.
5457
+ */
5458
+ identity?: string | string[];
5171
5459
  /** Estimated row count. */
5172
5460
  count: number;
5173
5461
  /**
@@ -5206,6 +5494,12 @@ declare class Type implements Node {
5206
5494
  readonly fields: Field[];
5207
5495
  /** The (composite) indexes declared on this Type. */
5208
5496
  readonly indexes: Index[];
5497
+ /**
5498
+ * The DECLARED identity field names, in key order — normalized from the spec's
5499
+ * `string | string[]`. `undefined` means identity is INFERRED (first
5500
+ * single-part unique index, else `id`), which is index-order dependent.
5501
+ */
5502
+ readonly identity?: readonly string[];
5209
5503
  /** Estimated total row count (drives cost estimation). */
5210
5504
  readonly count: number;
5211
5505
  /** Estimated average bytes per row (drives byte-cost estimation). */
@@ -5232,31 +5526,76 @@ declare class Type implements Node {
5232
5526
  textFields(): Field[];
5233
5527
  /**
5234
5528
  * The IDENTITY field used as the join key on this Type's side of a relation:
5235
- * the field referenced by the first single-part UNIQUE index (one part,
5236
- * `count === 1`, whose expr is a field-ref), else the field named `id`, else
5237
- * a clear error. Relations resolve their keys through this.
5529
+ * the DECLARED `identity` when it names exactly one field, else the field
5530
+ * referenced by the first single-part UNIQUE index (one part, `count === 1`,
5531
+ * whose expr is a field-ref), else the field named `id`, else a clear error.
5532
+ * Relations resolve their keys through this.
5238
5533
  */
5239
5534
  identityField(): Field;
5240
5535
  /**
5241
5536
  * The ordered PRIMARY KEY fields of this Type — generalizing {@link
5242
- * identityField} to COMPOSITE keys: the single identity field (a single-part
5243
- * unique index's field, else `id`) when present, else the fields of the first
5244
- * multi-part UNIQUE index (last part `count === 1`) whose every part is a
5245
- * field-ref. Relations map their key columns to these; a relation VALUE is
5246
- * keyed by these field names. Throws when none exists.
5537
+ * identityField} to COMPOSITE keys: the DECLARED `identity` when set, else the
5538
+ * single identity field (a single-part unique index's field, else `id`), else
5539
+ * the fields of the first multi-part UNIQUE index (last part `count === 1`)
5540
+ * whose every part is a field-ref. Relations map their key columns to these; a
5541
+ * relation VALUE is keyed by these field names. Throws when none exists.
5247
5542
  */
5248
5543
  primaryKey(): Field[];
5249
- /** The single identity field: the first single-part unique index's field, else `id`, else undefined. */
5544
+ /**
5545
+ * The fields named by an explicit `identity` declaration, in key order, or
5546
+ * `undefined` when none is declared. A declared name that is not a field on
5547
+ * this Type is an ERROR rather than a silent fall-back to the inferred rule —
5548
+ * falling back would reintroduce exactly the index-order dependence the
5549
+ * declaration exists to remove, and would do it invisibly.
5550
+ */
5551
+ private declaredIdentity;
5552
+ /**
5553
+ * The single identity field: the DECLARED `identity` when it is exactly one
5554
+ * field, else the first single-part unique index's field, else `id`, else
5555
+ * undefined. A declared COMPOSITE identity has no single field, so it yields
5556
+ * `undefined` here and is answered by {@link primaryKey}.
5557
+ */
5250
5558
  private singleIdentity;
5251
5559
  /**
5252
- * Fields eligible for semantic-aware querying: text fields flagged
5253
- * `semantic` or `search`, plus all relation fields (which can drive
5254
- * cross-entity semantic joins).
5560
+ * Fields eligible for semantic-aware querying: text fields flagged `semantic`
5561
+ * or `search`.
5562
+ *
5563
+ * Relation fields are NOT included. They used to be — on the theory that they
5564
+ * could drive cross-entity semantic joins — which made almost every Type
5565
+ * report itself semantic-eligible on the strength of having a foreign key, and
5566
+ * a whole-source semantic score then silently ran over a Type nobody had
5567
+ * declared semantic. A relation is a join, not an embedding.
5255
5568
  */
5256
5569
  semanticFields(): Field[];
5257
- /** Whether this Type is eligible for embedding-based semantic similarity. */
5570
+ /**
5571
+ * Whether ONE field is declared semantic-eligible: a text field flagged
5572
+ * `semantic` (or `search`, whose index is the same kind of derived artifact).
5573
+ */
5574
+ isFieldSemantic(field: Field): boolean;
5575
+ /**
5576
+ * Whether semantic scoring is possible ANYWHERE on this Type — the whole type
5577
+ * is flagged, or at least one field is. This is the ELIGIBILITY question
5578
+ * (does the `semantic` expr apply to this Type at all), which is what schema
5579
+ * gating and the capability description ask.
5580
+ *
5581
+ * What an UNNARROWED score reads is the row's embedding over
5582
+ * {@link semanticFields}, which no longer counts relation fields — so a Type
5583
+ * whose only "evidence" was owning a foreign key is no longer eligible at
5584
+ * all. See {@link isFieldSemantic} for the per-field question.
5585
+ */
5258
5586
  isSemantic(): boolean;
5259
- /** Whether this Type is eligible for full-text search. */
5587
+ /** Whether ONE field is declared full-text searchable. */
5588
+ isFieldSearchable(field: Field): boolean;
5589
+ /**
5590
+ * Whether full-text search is possible ANYWHERE on this Type — the whole type
5591
+ * is flagged, or at least one field is. The ELIGIBILITY question, used for
5592
+ * schema gating and the capability description.
5593
+ *
5594
+ * It is NOT the answer to "can this type be searched WITHOUT naming a field":
5595
+ * that needs a `SearchBacking` (the searchable document), whose absence is now
5596
+ * refused as `text-search.unbacked` rather than guessed at. See
5597
+ * {@link isFieldSearchable} for the per-field question.
5598
+ */
5260
5599
  isSearchable(): boolean;
5261
5600
  /** Build a Type from its JSON, parsing fields/indexes via `registry`. */
5262
5601
  static from(json: TypeDef, registry: Registry): Type;
@@ -6503,16 +6842,30 @@ interface ValidateContext {
6503
6842
  */
6504
6843
  readonly fieldExprKind?: ExprKind;
6505
6844
  /**
6506
- * Set by the FK-comparison operators (`comparison` / `in` / `between` /
6507
- * `binary`) when validating an operand, to permit a RELATION field-ref there
6508
- * (those operators compare two relations by FK key / reject relation-vs-scalar
6509
- * themselves). Everywhere else it is unset, so a bare relation field-ref used
6510
- * as a scalar VALUE (a select field, aggregate/window value, `partitionBy`,
6511
- * `orderBy`, group-by key, function arg) is a `ref.relation-not-value` error —
6512
- * a relation is a whole related row (possibly composite-keyed), never a value.
6845
+ * How a RELATION field-ref is allowed to be used at this position, if at all:
6846
+ *
6847
+ * - `'compare'` — set by the FK-comparison operators (`comparison` / `in` /
6848
+ * `between` / `binary`), which handle the relation THEMSELVES: a belongs-to
6849
+ * compares by key columns, a has-many by membership, and a
6850
+ * relation-vs-scalar is rejected by the operator.
6851
+ * - `'value'` — set where a relation's IDENTITY is a well-defined value: a
6852
+ * select field / RETURNING, an ORDER BY term, a GROUP BY key, a null test.
6853
+ * Only a BELONGS-TO has one (the key lives on this row); a has-many is a
6854
+ * SET and is refused with a message that says so.
6855
+ * - unset — a relation is not a value here at all (a function argument, a
6856
+ * `case` arm, an arithmetic operand, an aggregate), and a bare relation
6857
+ * field-ref is an error.
6858
+ *
6859
+ * Set ONLY for a DIRECT field-ref operand (see `_field-guard.ts`), so it never
6860
+ * leaks down into a nested expression that would not have earned it.
6513
6861
  */
6514
- readonly relationValueOk?: boolean;
6862
+ readonly relationUse?: RelationUse;
6515
6863
  }
6864
+ /**
6865
+ * How a RELATION field-ref may be used at a given validation position — see
6866
+ * `ValidateContext.relationUse`.
6867
+ */
6868
+ type RelationUse = 'compare' | 'value';
6516
6869
  /** The default top-level context: a bare expression may aggregate freely. */
6517
6870
  declare const ROOT_VALIDATE_CONTEXT: ValidateContext;
6518
6871
  /**
@@ -7365,6 +7718,8 @@ declare class NumberFieldType extends FieldType {
7365
7718
  static toSchema(): z.ZodTypeAny;
7366
7719
  /** Resolve to the `number` scalar comparison category. */
7367
7720
  resolve(): ScalarKind;
7721
+ /** A declared closed set of `n` members makes `= x` a `1/n` predicate. */
7722
+ eqSelectivity(): number | undefined;
7368
7723
  /** Estimated average stored byte size. */
7369
7724
  avgBytes(): number;
7370
7725
  /** SQL column type (`integer` when whole, else `numeric`). */
@@ -7373,7 +7728,7 @@ declare class NumberFieldType extends FieldType {
7373
7728
  toValueSchema(_opts?: ValueSchemaOptions): z.ZodTypeAny;
7374
7729
  /** Serialize to its JSON def (flattening the compacted options). */
7375
7730
  toJSON(): NumberFieldTypeDef;
7376
- /** A copy of this field type (cloning the options bag). */
7731
+ /** A copy of this field type (deep-cloning the options bag's value set). */
7377
7732
  clone(): NumberFieldType;
7378
7733
  }
7379
7734
 
@@ -7391,6 +7746,8 @@ interface TextOptions {
7391
7746
  search?: boolean;
7392
7747
  /** When true, text matching is case-sensitive (default: case-insensitive). */
7393
7748
  sensitive?: boolean;
7749
+ /** The closed set of values this column may hold (see `NumberOptions.values`). */
7750
+ values?: FieldValueDef[];
7394
7751
  }
7395
7752
  /**
7396
7753
  * TextFieldType — a string field with optional length / pattern constraints,
@@ -7421,15 +7778,17 @@ declare class TextFieldType extends FieldType {
7421
7778
  static toSchema(): z.ZodTypeAny;
7422
7779
  /** Resolve to the `text` scalar comparison category. */
7423
7780
  resolve(): ScalarKind;
7781
+ /** A declared closed set of `n` members makes `= x` a `1/n` predicate. */
7782
+ eqSelectivity(): number | undefined;
7424
7783
  /** Estimated average stored byte size (half the max length, else 32). */
7425
7784
  avgBytes(): number;
7426
7785
  /** SQL column type (`varchar(n)` when bounded, else `text`). */
7427
7786
  toSQLType(): string;
7428
- /** Zod schema validating a string, honoring length / pattern options. */
7787
+ /** Zod schema validating a string, honoring the closed value set else length / pattern options. */
7429
7788
  toValueSchema(_opts?: ValueSchemaOptions): z.ZodTypeAny;
7430
7789
  /** Serialize to its JSON def (flattening the compacted options). */
7431
7790
  toJSON(): TextFieldTypeDef;
7432
- /** A copy of this field type (cloning the options bag). */
7791
+ /** A copy of this field type (deep-cloning the options bag's value set). */
7433
7792
  clone(): TextFieldType;
7434
7793
  }
7435
7794
 
@@ -8340,7 +8699,12 @@ declare class SelectQuery extends Query {
8340
8699
  private fromSQL;
8341
8700
  /** One ORDER BY clause `<key> ASC|DESC [NULLS FIRST|LAST]` from a resolved key + dir/nulls. */
8342
8701
  private orderClauseSQL;
8343
- /** One ORDER BY term: `<expr> ASC|DESC [NULLS FIRST|LAST]`. */
8702
+ /**
8703
+ * One ORDER BY term: `<expr> ASC|DESC [NULLS FIRST|LAST]`. A RELATION term
8704
+ * expands to ONE clause per key column (each inheriting the term's direction
8705
+ * and NULLs placement) — lexicographic over the declared key order, and
8706
+ * index-usable, where sorting the assembled JSON object would be neither.
8707
+ */
8344
8708
  private orderTermSQL;
8345
8709
  /**
8346
8710
  * Emit the SELECT. A SELECT never prepends its own `WITH` (relation crossings
@@ -9038,6 +9402,37 @@ declare class PostgresDialect extends BaseDialect {
9038
9402
  * text-search config defaulting to `'english'`.
9039
9403
  */
9040
9404
  tsvectorSearch(tsv: SqlText, query: SqlText, language?: string): SqlText;
9405
+ /**
9406
+ * `jsonb_build_object` rather than the base `json_build_object`: `jsonb` has
9407
+ * equality and ordering operators, so a projected identity can also be
9408
+ * DISTINCTed or compared, where a `json` value cannot be (Postgres has no
9409
+ * equality operator for `json` at all).
9410
+ */
9411
+ jsonObject(entries: readonly {
9412
+ key: string;
9413
+ value: SqlText;
9414
+ }[]): SqlText;
9415
+ /** Postgres stores JSON as `jsonb` (it has the equality / ordering operators `json` lacks). */
9416
+ jsonSqlType(): string;
9417
+ /**
9418
+ * Bind a JSON DOCUMENT — with the one Postgres wrinkle that makes the base
9419
+ * implementation wrong here: a NATIVE array column (`text[]`, `integer[]`, …)
9420
+ * does NOT accept JSON text. `CAST('["a","b"]' AS text[])` is a syntax error,
9421
+ * because a Postgres array literal is `{a,b}`.
9422
+ *
9423
+ * So a document destined for a native array is CONSTRUCTED instead —
9424
+ * `ARRAY[$1, $2]::text[]` — with each element bound in its own slot. That
9425
+ * reuses the element-binding pattern the array containment operators already
9426
+ * use, needs no array-literal encoder (whose quoting / escaping / NULL rules
9427
+ * would be their own defect surface), and handles the empty array
9428
+ * (`ARRAY[]::text[]`, which Postgres accepts precisely because the cast names
9429
+ * the type). Elements recurse, so a `jsonb[]` column takes documents.
9430
+ *
9431
+ * Everything else — a `json` / `jsonb` column, a heterogeneous array (which
9432
+ * `sqlTypeFor` already stores as `jsonb`), or a bare document with no declared
9433
+ * target — casts the JSON text to `jsonb`.
9434
+ */
9435
+ jsonValue(value: JsonValue, fieldType?: FieldType): SqlText;
9041
9436
  /** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
9042
9437
  queryVectorParam(param: SqlText): SqlText;
9043
9438
  /**
@@ -9230,17 +9625,30 @@ interface DrillDownFailure {
9230
9625
  type DrillDownResult = DrillDownSuccess | DrillDownFailure;
9231
9626
  /**
9232
9627
  * A successful `drillDownInto`: the rebuilt query plus the EXTRACTED param
9233
- * VALUE map (each drill param's name → the scalar pulled from the group row),
9628
+ * VALUE map (each drill param's name → the value pulled from the group row),
9234
9629
  * ready for `engine.run(query, { params })`.
9235
9630
  */
9236
9631
  interface DrillDownIntoSuccess {
9237
9632
  /** The un-ravelled SELECT returning the underlying rows. */
9238
9633
  query: SelectQuery;
9239
- /** Bind-param values pulled from the group row (param name → scalar). */
9240
- params: Record<string, ScalarValue>;
9634
+ /**
9635
+ * Bind-param values pulled from the group row (param name → value). Usually a
9636
+ * scalar; a group key that is a RELATION carries that relation's IDENTITY
9637
+ * object (`{ id: 5 }`), which is exactly the shape the rebuilt query's
9638
+ * relation comparison binds.
9639
+ */
9640
+ params: Record<string, DrillValue>;
9241
9641
  /** Non-fatal notes carried over from `drillDown`. */
9242
9642
  warnings: Problems;
9243
9643
  }
9644
+ /**
9645
+ * A value a drill param can carry: a scalar, or the IDENTITY OBJECT of a
9646
+ * relation group key (keyed by the target's identity field names — see the
9647
+ * relation comparison lowering, which accepts exactly this shape).
9648
+ */
9649
+ type DrillValue = ScalarValue | {
9650
+ [key: string]: ScalarValue;
9651
+ };
9244
9652
  /**
9245
9653
  * Un-ravel an aggregating SELECT into a reusable query over the underlying
9246
9654
  * rows: pin each group key to a fresh bind param, replace each aggregate with
@@ -9553,7 +9961,7 @@ declare function describeEngine(engine: QueryEngine | Registry, options?: Descri
9553
9961
  * so every Type / Field surfaces a human- / LLM-facing doc even when the dev
9554
9962
  * authored none. Values are derived from what the meta-model already knows — a
9555
9963
  * Field from its `FieldType` (kind, bounds, `sensitive` / `semantic` / `search`
9556
- * flags, array item / bounds, a relation's `to` + `count`, nullability) and a
9964
+ * flags, array item / bounds, a relation's `to` + DIRECTION + `count`, nullability) and a
9557
9965
  * Type from its name plus a field / relation / index summary.
9558
9966
  *
9559
9967
  * NOTHING here mutates the stored `TypeDef` / `FieldDef`: each string is
@@ -9704,4 +10112,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
9704
10112
  */
9705
10113
  declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
9706
10114
 
9707
- export { AID_REGISTRY, type Access, type AccessRun, type AccessSql, AggregateExpr, type AggregateExprDef, type AggregateRun, type AidInfo, type AidOptions, type AliasedSourceDef, type ArgExprDef, ArrayFieldType, type ArrayFieldTypeDef, type ArrayOp, ArrayOpExpr, type ArrayOpExprDef, type AutoPaginateOptions, BUILTIN_EXPRS, BUILTIN_FIELD_TYPES, BUILTIN_LIBRARY, BUILTIN_QUERIES, Backing, BaseDialect, BetweenExpr, type BetweenExprDef, BinaryExpr, type BinaryExprDef, type BinaryOp, BoolExpr, BoolFieldType, type BoolFieldTypeDef, type BuildQueryToolOptions, type BuildSchemasOptions, type BuiltinFunction, type CTEDef, type CTERecursiveDef, type CTEStatementDef, CTEStatementQuery, type CaseBranchDef, type CaseBranchSpec, CaseExpr, type CaseExprDef, Code, type CodeLine, type CodeOptions, ComparisonExpr, type ComparisonExprDef, type ComparisonOp, type ComputeRun, type ComputeSql, type Computed, type ComputedResolved, type Cost, type CostConstraints, DEFAULT_MAX_CTE_ITERATIONS, DEFAULT_MAX_EXAMPLES, DEFAULT_MAX_QUERY_SCHEMA_TYPES, DateFieldType, type DateFieldTypeDef, type DefaultCondition, type DefaultConditionOp, type DeleteDef, DeleteQuery, type DescribeEngineOptions, type DescribeOverrides, Dialect, type DialectEntry, type DrillDownFailure, type DrillDownIntoSuccess, type DrillDownResult, type DrillDownSuccess, type DrillParam, EQ_SELECTIVITY, type Embedder, ExcludedExpr, type ExcludedExprDef, type ExecutorContext, ExistsExpr, type ExistsExprDef, Expr, type ExprClass, type ExprClassEntry, type ExprDef, type ExprKind, ExprQuery, type ExprQueryDef, Field, type FieldBacking, type FieldDef, type FieldExprRestriction, FieldRefExpr, type FieldRefExprDef, type FieldResolved, type FieldSpec, FieldType, type FieldTypeClass, type FieldTypeDef, type FieldTypeKind, type FilterDepth, FiltersExpr, type FiltersExprDef, type FnDepth, type FormatOptions, type FormatProblemsOptions, FunctionCallExpr, type FunctionCallExprDef, type FunctionDef, type FunctionParamDef, type FunctionRun, type FunctionSelector, type FunctionShape, type FunctionSourceDef, IN_SELECTIVITY, InExpr, type InExprDef, Index, type IndexDef, type IndexPartDef, type InferOptions, type InsertDef, InsertQuery, type InsertRowDef, IsNullExpr, type IsNullExprDef, type JSONEntry, type JoinBacking, JoinCtePlanner, type JoinDef, type JoinHop, type JoinOnDef, type JoinRequest, type JoinRunPlan, type JoinSpec, type JoinSqlPlan, type JoinType, JsonFieldType, type JsonFieldTypeDef, type JsonValue, type LateralJoinSpec, LiteralExpr, type LiteralExprDef, LogicalExpr, type LogicalExprDef, type LogicalOp, type MaybePromise, type Meta, MoneyFieldType, type MoneyFieldTypeDef, type MoneyOptions, type NameDepth, type NamedArgs, type Node, NumberFieldType, type NumberFieldTypeDef, type NumberOptions, type OnConflictDef, type OrderDef, type OrderEntry, OutputRefExpr, type OutputRefExprDef, type ParamDef, ParamExpr, type ParamExprDef, ParamSet, PostgresDialect, type Problem, Problems, Query, type QueryClass, type QueryClassEntry, type QueryDef, QueryEngine, type QueryEngineOptions, type QueryField, QueryFunction, QueryJoin, type QueryKind, QueryOrder, type QueryResult, type QueryResultArray, type QuerySchemaOptions, type QuerySchemas, QueryScope, QuerySource, QueryToolError, type QueryToolInput, QueryTypeError, type QueryValidator, RANGE_SELECTIVITY, ROOT_VALIDATE_CONTEXT, type RefDepth, Registry, RelationFieldType, type RelationFieldTypeDef, type RelationJoinOnDef, type RelationJoinSpec, type RelationKey, type RenderedSql, type ResolvedSchemaDepth, type ResolvedType, type RlsProvider, RuntimeContext, type RuntimeJoin, type RuntimeOptions, SEMANTIC_ROW_PENALTY, type ScalarKind, type ScalarRun, type ScalarValue, type SchemaDepth, type SchemaOptions, type SelectDef, type SelectFieldDef, SelectQuery, type SelectTypesOptions, type SelectedFunctions, type SemanticEmbeddings, SemanticExpr, type SemanticExprDef, type SemanticQueryDef, type SemanticTextToVector, type SetDef, type SetOperationDef, SetOperationQuery, type SortEntryDef, type SortSelectionDef, type SorterDef, SorterExpr, type SourceDef, type SourceFieldOptionalRef, type SourceFieldRef, type SourceFieldsRef, type SourceRecord, type SourceRow, type Span, type SpanMeta, SqlContext, SqlText, type SqlValue, SubqueryExpr, type SubqueryExprDef, type SubquerySourceDef, TEXT_SEARCH_ROW_PENALTY, TabularFunctionCallExpr, type TabularFunctionCallExprDef, type TabularRun, TextFieldType, type TextFieldTypeDef, type TextOptions, TextScoreExpr, type TextScoreExprDef, TextSearchExpr, type TextSearchExprDef, TimestampFieldType, type TimestampFieldTypeDef, type TimezonePolicy, type ToSqlOptions, Type, type TypeBacking, type TypeDef, type TypeExecutor, type TypeFieldRef, type TypeResolved, type TypeSourceDef, type TypeSpec, type TypeState, UnaryExpr, type UnaryExprDef, type UnaryOp, type UpdateDef, UpdateQuery, type ValidateContext, Value, type ValueCategory, type ValueSchemaOptions, WINDOW_ORDER_ARG, WindowExpr, type WindowExprDef, type WindowOrderSpec, type WindowRun, type WriteValueDef, ZERO_COST, add, addCost, age, agg, aidInfo, and, arrayAgg, arrayAppend, arrayConcat, arrayContains, arrayDistinct, arrayExecutor, arrayIndexOf, arrayPrepend, arrayRemove, arraySlice, arrayToString, asFieldType, autoPaginate, avg, between, boolAnd, boolOr, buildQueryTool, buildSchemas, builtinDialects, bytesOfResolved, canonicalize, caseExpr, cloneRecord, code, concat, contains, containsAll, containsAny, count, countIf, countStar, createRegistry, currentTime, currentTimestamp, dateAdd, dateDiff, dateFormat, datePart, dateTrunc, day, dayOfWeek, dayOfYear, defaultConditionOps, defaultConditionWithout, depthInstructions, describeDialects, describeEngine, describeExprs, describeFunctions, describeInput, describeQueryExamples, describeType, describeTypes, didYouMean, directedMessage, div, drillDown, drillDownInto, e, editDistance, embeddingResolver, epoch, eq, excluded, exists, exprDefSchema, exprDigest, fieldMeta, fieldNameOf, fieldTypeDefSchema, filters, firstField, fn, fromEpoch, generatedFieldDescription, generatedFieldLabel, generatedTypeDescription, generatedTypeLabel, gt, gte, hour, humanize, ilike, inList, inSubquery, inferType, isEmpty, isNull, isScalar, isScalarValue, isType, isVectorText, join, joinAlias, joinCode, joinLines, jsonValueSchema, like, lit, lt, lte, makeDate, makeField, makeResult, max, maxCost, mergeRows, min, minute, mod, month, mul, nearest, nearestKind, neg, neq, not, notBetween, notEmpty, notExists, notInList, notInSubquery, notLike, notNull, or, output, param, parseQueryRequest, parseQueryTool, parseVectorText, plain, pos, querySchema, raw, recordKey, recordSignature, ref, relJoin, reportCostProblems, resolveAccessRun, resolveAccessSql, resolveComputeRun, resolveComputeSql, resolveDefaultConditionRun, resolveDefaultConditionSql, resolveFields, resolveJoinRun, resolveJoinSql, resolveSchemaDepth, rlsPredicate, rowsCost, runAggregateFunction, runScalarFunction, runTabularFunction, runWindowFunction, scaleRows, second, selectFunctions, selectTypes, semantic, shouldUseStringSchema, singleRow, sortEntries, sourcesOf, span, stddev, stringAgg, stringToArray, sub, subquery, suggestionBudget, sum, syntheticType, tableFn, textScore, textSearch, timezoneSchema, toArrayRows, toVectorText, typeFromFields, typeMeta, value, variance, week, when, widenNullable, window, withAid, year };
10115
+ export { AID_REGISTRY, type Access, type AccessRun, type AccessSql, AggregateExpr, type AggregateExprDef, type AggregateRun, type AidInfo, type AidOptions, type AliasedSourceDef, type ArgExprDef, ArrayFieldType, type ArrayFieldTypeDef, type ArrayOp, ArrayOpExpr, type ArrayOpExprDef, type AutoPaginateOptions, BUILTIN_EXPRS, BUILTIN_FIELD_TYPES, BUILTIN_LIBRARY, BUILTIN_QUERIES, Backing, BaseDialect, BetweenExpr, type BetweenExprDef, BinaryExpr, type BinaryExprDef, type BinaryOp, BoolExpr, BoolFieldType, type BoolFieldTypeDef, type BuildQueryToolOptions, type BuildSchemasOptions, type BuiltinFunction, type CTEDef, type CTERecursiveDef, type CTEStatementDef, CTEStatementQuery, type CaseBranchDef, type CaseBranchSpec, CaseExpr, type CaseExprDef, Code, type CodeLine, type CodeOptions, ComparisonExpr, type ComparisonExprDef, type ComparisonOp, type ComputeRun, type ComputeSql, type Computed, type ComputedResolved, type Cost, type CostConstraints, DEFAULT_MAX_CTE_ITERATIONS, DEFAULT_MAX_EXAMPLES, DEFAULT_MAX_QUERY_SCHEMA_TYPES, DateFieldType, type DateFieldTypeDef, type DefaultCondition, type DefaultConditionOp, type DefaultOrder, type DefaultOrderDir, type DefaultOrderScope, type DefaultOrderTerm, type DeleteDef, DeleteQuery, type DescribeEngineOptions, type DescribeOverrides, Dialect, type DialectEntry, type DrillDownFailure, type DrillDownIntoSuccess, type DrillDownResult, type DrillDownSuccess, type DrillParam, type DrillValue, EQ_SELECTIVITY, type Embedder, ExcludedExpr, type ExcludedExprDef, type ExecutorContext, ExistsExpr, type ExistsExprDef, Expr, type ExprClass, type ExprClassEntry, type ExprDef, type ExprKind, ExprQuery, type ExprQueryDef, Field, type FieldBacking, type FieldDef, type FieldExprRestriction, FieldRefExpr, type FieldRefExprDef, type FieldResolved, type FieldSpec, FieldType, type FieldTypeClass, type FieldTypeDef, type FieldTypeKind, type FieldValueDef, type FilterDepth, FiltersExpr, type FiltersExprDef, type FnDepth, type FormatOptions, type FormatProblemsOptions, FunctionCallExpr, type FunctionCallExprDef, type FunctionDef, type FunctionParamDef, type FunctionRun, type FunctionSelector, type FunctionShape, type FunctionSourceDef, IN_SELECTIVITY, InExpr, type InExprDef, Index, type IndexDef, IndexPart, type IndexPartDef, type InferOptions, type InsertDef, InsertQuery, type InsertRowDef, IsNullExpr, type IsNullExprDef, type JSONEntry, type JoinBacking, JoinCtePlanner, type JoinDef, type JoinHop, type JoinOnDef, type JoinRequest, type JoinRunPlan, type JoinSpec, type JoinSqlPlan, type JoinType, JsonFieldType, type JsonFieldTypeDef, type JsonValue, type LateralJoinSpec, LiteralExpr, type LiteralExprDef, LogicalExpr, type LogicalExprDef, type LogicalOp, type MaybePromise, type Meta, MoneyFieldType, type MoneyFieldTypeDef, type MoneyOptions, type NameDepth, type NamedArgs, type Node, NumberFieldType, type NumberFieldTypeDef, type NumberOptions, type OnConflictDef, type OrderDef, type OrderEntry, OutputRefExpr, type OutputRefExprDef, type ParamDef, ParamExpr, type ParamExprDef, ParamSet, PostgresDialect, type Problem, Problems, Query, type QueryClass, type QueryClassEntry, type QueryDef, QueryEngine, type QueryEngineOptions, type QueryField, QueryFunction, QueryJoin, type QueryKind, QueryOrder, type QueryResult, type QueryResultArray, type QuerySchemaOptions, type QuerySchemas, QueryScope, QuerySource, QueryToolError, type QueryToolInput, QueryTypeError, type QueryValidator, RANGE_SELECTIVITY, ROOT_VALIDATE_CONTEXT, type RefDepth, Registry, type RelationBacking, RelationFieldType, type RelationFieldTypeDef, type RelationJoinOnDef, type RelationJoinSpec, type RelationKey, type RelationKeyPair, type RelationOn, type RelationOnPair, type RelationResolved, type RenderedSql, type ResolvedSchemaDepth, type ResolvedType, type RlsProvider, RuntimeContext, type RuntimeJoin, type RuntimeOptions, SEMANTIC_ROW_PENALTY, type ScalarKind, type ScalarRun, type ScalarValue, type SchemaDepth, type SchemaOptions, type SearchBacking, type SelectDef, type SelectFieldDef, SelectQuery, type SelectTypesOptions, type SelectedFunctions, type SemanticBacking, type SemanticEmbeddings, SemanticExpr, type SemanticExprDef, type SemanticQueryDef, type SemanticTextToVector, type SetDef, type SetOperationDef, SetOperationQuery, type SortEntryDef, type SortSelectionDef, type SorterDef, SorterExpr, type SourceDef, type SourceFieldOptionalRef, type SourceFieldRef, type SourceFieldsRef, type SourceRecord, type SourceRow, type Span, type SpanMeta, SqlContext, type SqlParamValue, SqlText, type SqlValue, SubqueryExpr, type SubqueryExprDef, type SubquerySourceDef, TEXT_SEARCH_ROW_PENALTY, TabularFunctionCallExpr, type TabularFunctionCallExprDef, type TabularRun, TextFieldType, type TextFieldTypeDef, type TextOptions, TextScoreExpr, type TextScoreExprDef, TextSearchExpr, type TextSearchExprDef, TimestampFieldType, type TimestampFieldTypeDef, type TimezonePolicy, type ToSqlOptions, Type, type TypeBacking, type TypeDef, type TypeExecutor, type TypeFieldRef, type TypeResolved, type TypeSourceDef, type TypeSpec, type TypeState, UnaryExpr, type UnaryExprDef, type UnaryOp, type UpdateDef, UpdateQuery, type ValidateContext, Value, type ValueCategory, type ValueSchemaOptions, WINDOW_ORDER_ARG, WindowExpr, type WindowExprDef, type WindowOrderSpec, type WindowRun, type WriteValueDef, ZERO_COST, add, addCost, age, agg, aidInfo, aliasedDigest, and, arrayAgg, arrayAppend, arrayConcat, arrayContains, arrayDistinct, arrayExecutor, arrayIndexOf, arrayPrepend, arrayRemove, arraySlice, arrayToString, asFieldType, autoPaginate, avg, between, boolAnd, boolOr, buildQueryTool, buildSchemas, builtinDialects, bytesOfResolved, canonicalize, caseExpr, cloneRecord, code, concat, contains, containsAll, containsAny, count, countIf, countStar, createRegistry, currentTime, currentTimestamp, dateAdd, dateDiff, dateFormat, datePart, dateTrunc, day, dayOfWeek, dayOfYear, defaultConditionOps, defaultConditionWithout, depthInstructions, describeDialects, describeEngine, describeExprs, describeFunctions, describeInput, describeQueryExamples, describeType, describeTypes, didYouMean, directedMessage, div, drillDown, drillDownInto, e, editDistance, embeddingResolver, epoch, eq, excluded, exists, exprDefSchema, exprDigest, fieldMeta, fieldNameOf, fieldTypeDefSchema, filters, firstField, fn, fromEpoch, generatedFieldDescription, generatedFieldLabel, generatedTypeDescription, generatedTypeLabel, gt, gte, hour, humanize, ilike, inList, inSubquery, inferType, isEmpty, isNull, isScalar, isScalarValue, isType, isVectorText, join, joinAlias, joinCode, joinLines, jsonValueSchema, like, lit, lt, lte, makeDate, makeField, makeResult, max, maxCost, mergeRows, min, minute, mod, month, mul, nearest, nearestKind, neg, neq, not, notBetween, notEmpty, notExists, notInList, notInSubquery, notLike, notNull, or, output, param, parseQueryRequest, parseQueryTool, parseVectorText, plain, pos, querySchema, raw, recordKey, recordSignature, ref, relJoin, relationKeyColumns, relationOf, renameSource, reportCostProblems, resolveAccessRun, resolveAccessSql, resolveComputeRun, resolveComputeSql, resolveDefaultConditionRun, resolveDefaultConditionSql, resolveFields, resolveJoinRun, resolveJoinSql, resolveSchemaDepth, rlsPredicate, rowsCost, runAggregateFunction, runScalarFunction, runTabularFunction, runWindowFunction, scaleRows, second, selectFunctions, selectTypes, semantic, shouldUseStringSchema, singleRow, sortEntries, sourcesOf, span, stddev, stringAgg, stringToArray, sub, subquery, suggestionBudget, sum, syntheticType, tableFn, textScore, textSearch, timezoneSchema, toArrayRows, toVectorText, typeFromFields, typeMeta, value, valueFieldType, variance, week, when, widenNullable, window, withAid, year };