@aeye/query 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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 {
@@ -207,6 +241,19 @@ interface TypeDef {
207
241
  description?: string;
208
242
  fields: FieldDef[];
209
243
  indexes?: IndexDef[];
244
+ /**
245
+ * The field (or ordered fields) that IDENTIFY a row. When present it is THE
246
+ * answer for `Type.identityField()` / `Type.primaryKey()`: index ORDER becomes
247
+ * irrelevant, and a unique index on any other column is just a unique index.
248
+ *
249
+ * Without it identity is INFERRED as "the first single-part unique index, else
250
+ * the field named `id`" — which makes the identity of a Type depend on the
251
+ * order its indexes happen to be listed in. A Type declaring both `id` and a
252
+ * unique `email`, with the email index listed first, silently identifies by
253
+ * `email`, and every relation into it then joins a stored id against an email.
254
+ * Declaring it removes that whole class of failure.
255
+ */
256
+ identity?: string | string[];
210
257
  /** Estimated total row count — drives cost estimation. */
211
258
  count: number;
212
259
  /** Estimated average bytes per row (else derived as the sum of the fields' bytes). */
@@ -1063,6 +1110,15 @@ declare abstract class FieldType implements Node {
1063
1110
  * stricter or looser rules.
1064
1111
  */
1065
1112
  comparableWith(other: FieldType): boolean;
1113
+ /**
1114
+ * The fraction of rows a non-indexed EQUALITY predicate on a column of this
1115
+ * type is expected to keep, when the type itself knows better than the
1116
+ * package-wide `EQ_SELECTIVITY` guess. A closed value set of `n` members
1117
+ * answers `1/n`: a two-value flag keeps half the table, a fifty-value code
1118
+ * keeps 2% — today both are costed at the same fixed third. `undefined`
1119
+ * (the default) means "no better estimate; use the fixed one".
1120
+ */
1121
+ eqSelectivity(): number | undefined;
1066
1122
  /**
1067
1123
  * Whether TEXTUAL matching / comparison on a value of this type is
1068
1124
  * CASE-SENSITIVE. Default false (case-insensitive); only `text` fields
@@ -1105,7 +1161,6 @@ declare abstract class FieldType implements Node {
1105
1161
  * getter so a dialect INSTANCE can be registered directly.
1106
1162
  */
1107
1163
 
1108
- /** The abstract SQL-dialect contract; concrete dialects override the engine-specific points. */
1109
1164
  declare abstract class Dialect implements DialectEntry {
1110
1165
  /** The dialect's canonical name (e.g. `'base'`, `'postgres'`). */
1111
1166
  abstract readonly name: string;
@@ -1210,6 +1265,20 @@ declare abstract class Dialect implements DialectEntry {
1210
1265
  /** Shared lateral-join assembly; `on` is the raw ON-condition literal. */
1211
1266
  protected lateralJoinWith(subquery: SqlText, alias: string, joinType: 'left' | 'inner', on: string): SqlText;
1212
1267
  /** The SQL field type for a field type in this dialect. */
1268
+ /**
1269
+ * Build a JSON OBJECT from ordered `key → value` pairs — how a relation's
1270
+ * IDENTITY reaches the result boundary (`{ id: 5 }`, `{ tenantId: 3, userId: 1 }`).
1271
+ *
1272
+ * `json_build_object` is not ANSI, but neither is `json_array_length` which
1273
+ * this base dialect already emits for `arrayLength`: the portable dialect is
1274
+ * portable-ISH, and degrading a structured value to a concatenated string
1275
+ * would be worse than depending on the same JSON support that is already
1276
+ * assumed. Dialects with a richer JSON type override this.
1277
+ */
1278
+ jsonObject(entries: readonly {
1279
+ key: string;
1280
+ value: SqlText;
1281
+ }[]): SqlText;
1213
1282
  abstract sqlTypeFor(fieldType: FieldType): string;
1214
1283
  /**
1215
1284
  * Length (element count) of array expression `arg`. Postgres `cardinality`;
@@ -1294,8 +1363,16 @@ interface RelationResolved {
1294
1363
  readonly keyType: FieldType;
1295
1364
  /** The relation's target Type name (its `to`). */
1296
1365
  readonly to: string;
1297
- /** Cardinality: `1` = belongs-to (single target row), `>1` = has-many (a set). */
1366
+ /** Declared cardinality of the related rows (`1` = one-to-one / belongs-to shaped). */
1298
1367
  readonly count: number;
1368
+ /**
1369
+ * Which side the FOREIGN KEY is on: true = belongs-to, so this row holds the
1370
+ * target's identity locally; false = has-many, a SET keyed on the target.
1371
+ * Read this rather than `count` — a MATERIALIZED INVERSE can carry an
1372
+ * estimated `count` of 1 and is still a has-many (see
1373
+ * `RelationFieldType.isBelongsTo`).
1374
+ */
1375
+ readonly belongsTo: boolean;
1299
1376
  /** The ORDERED join-key pairs (composite-capable) driving relation comparison lowering. */
1300
1377
  readonly keys: readonly RelationKeyPair[];
1301
1378
  }
@@ -1357,6 +1434,20 @@ declare function sourcesOf(rt: ResolvedType): readonly FieldResolved[];
1357
1434
  declare function widenNullable(rt: ResolvedType, nullable?: boolean): ResolvedType;
1358
1435
  /** Type guard: a resolved type. */
1359
1436
  declare function isType(rt: ResolvedType): rt is TypeResolved;
1437
+ /**
1438
+ * The relation info when `rt` is a Type resolved from a relation FIELD-REF
1439
+ * (a belongs-to / has-many field), else `undefined`. Used by the scalar
1440
+ * operators to reject a relation used as a value and to allow (and key-compare)
1441
+ * a relation-vs-relation comparison.
1442
+ */
1443
+ declare function relationOf(rt: ResolvedType): RelationResolved | undefined;
1444
+ /**
1445
+ * The comparable-VALUE field type of a resolved value: its scalar field type,
1446
+ * else — for a relation Type — the relation's key value type. Used to type a
1447
+ * bind param compared against the operand (a relation compares by its FK key).
1448
+ * A non-relation whole Type has none.
1449
+ */
1450
+ declare function valueFieldType(rt: ResolvedType): FieldType | undefined;
1360
1451
  /** Type guard: a resolved scalar (field or computed value, never a type). */
1361
1452
  declare function isScalar(rt: ResolvedType): rt is FieldResolved | ComputedResolved;
1362
1453
 
@@ -1507,6 +1598,57 @@ declare class QueryScope {
1507
1598
  child(): QueryScope;
1508
1599
  }
1509
1600
 
1601
+ /**
1602
+ * pgvector TEXT helpers + the precomputed text→vector embedding cache.
1603
+ *
1604
+ * A `semantic(...)` term can be a plain-text LITERAL or a text PARAM value. Such
1605
+ * text is NOT an embedding — it must be turned into a vector before it can be
1606
+ * compared. Postgres has no array bind type, so a query vector travels as a
1607
+ * pgvector TEXT literal (`[a,b,c]`) and is cast `::vector` by the dialect. The
1608
+ * embedding itself is a model/network call the query layer does not own, so the
1609
+ * CALLER embeds up front (see `semanticTexts`) and passes the resulting
1610
+ * text→vector cache (see {@link SemanticEmbeddings}) into `engine.toSQL` /
1611
+ * `engine.run`; binding then stays fully SYNCHRONOUS.
1612
+ *
1613
+ * This module has NO runtime imports (pure string/number work), so it sits at
1614
+ * the bottom of the module graph and is safe to import from both the SQL and the
1615
+ * runtime paths.
1616
+ */
1617
+ /**
1618
+ * A caller-supplied SYNC converter turning a plain-text semantic term — a
1619
+ * `semantic(...)` TEXT LITERAL, or the runtime value of a text PARAM — into its
1620
+ * pgvector TEXT form (a bracketed literal such as `[0.0123,-0.045,…]`). It is the
1621
+ * INTERNAL seam the SQL emit path threads (built from a {@link SemanticEmbeddings}
1622
+ * cache by `engine.toSQL`); callers supply the {@link SemanticEmbeddings} cache,
1623
+ * not this converter directly.
1624
+ */
1625
+ type SemanticTextToVector = (text: string) => string;
1626
+ /**
1627
+ * The precomputed text→vector cache a caller fills after embedding the terms
1628
+ * `semanticTexts` extracted, and passes to `engine.toSQL` / `engine.run`
1629
+ * so a `semantic(...)` text term binds SYNCHRONOUSLY. The primary shape is a
1630
+ * `ReadonlyMap<string, readonly number[]>` (text → vector); a resolver function
1631
+ * is accepted as a superset. A term absent from the cache is a fail-loud error at
1632
+ * bind time (never a silently mis-bound `'<text>'::vector`).
1633
+ */
1634
+ type SemanticEmbeddings = ReadonlyMap<string, readonly number[]> | ((text: string) => readonly number[] | undefined);
1635
+ /**
1636
+ * Normalize a {@link SemanticEmbeddings} (map OR resolver) into a lookup
1637
+ * function `text → vector | undefined`. Pure — no runtime imports.
1638
+ */
1639
+ declare function embeddingResolver(embeddings: SemanticEmbeddings): (text: string) => readonly number[] | undefined;
1640
+ /** Whether `text` is already in pgvector TEXT form (a bracketed `[…]` literal). */
1641
+ declare function isVectorText(text: string): boolean;
1642
+ /** Format an embedding vector as pgvector TEXT (`[a,b,c]`, no spaces). */
1643
+ declare function toVectorText(vector: readonly number[]): string;
1644
+ /**
1645
+ * Parse a pgvector TEXT literal (`[a,b,c]`) back into numbers. Tolerates
1646
+ * surrounding whitespace and an empty vector (`[]` ⇒ `[]`). Throws on a value
1647
+ * that is not bracketed pgvector text (so a mis-supplied term fails loudly rather
1648
+ * than silently scoring against a garbage vector).
1649
+ */
1650
+ declare function parseVectorText(text: string): number[];
1651
+
1510
1652
  /**
1511
1653
  * Row-Level-Security injection.
1512
1654
  *
@@ -1718,6 +1860,16 @@ interface RuntimeOptions {
1718
1860
  includeTotal?: boolean;
1719
1861
  /** Embedder override (defaults to the engine's). */
1720
1862
  embedder?: Embedder;
1863
+ /**
1864
+ * Precomputed text→vector cache (see {@link SemanticEmbeddings}) for a
1865
+ * `semantic(...)` QUERY term (a text literal, or a text-param value), mirroring
1866
+ * the SQL path's `toSQL({ embeddings })`. The term's vector is looked up here
1867
+ * and cosine-scored in-memory (no embedder / network call); a pre-embedded
1868
+ * `[…]` value is used directly. Takes precedence over `embedder` for the query
1869
+ * term. A term MISSING from the cache throws (fail loud). With no cache, the
1870
+ * existing embedder path is used unchanged.
1871
+ */
1872
+ embeddings?: SemanticEmbeddings;
1721
1873
  /** Per-record embedding lookup for semantic scoring. */
1722
1874
  recordEmbedding?: (source: string, id: JsonValue) => Promise<number[] | null>;
1723
1875
  /** Cap on recursive-CTE iterations. */
@@ -1776,6 +1928,12 @@ declare class RuntimeContext {
1776
1928
  */
1777
1929
  private readonly sourceTypes;
1778
1930
  private readonly embedder?;
1931
+ /**
1932
+ * Precomputed text→vector cache for a semantic QUERY term (SQL parity), or
1933
+ * `undefined`. Normalized to a lookup function; `undefined` when no cache was
1934
+ * supplied.
1935
+ */
1936
+ readonly resolveEmbedding?: (text: string) => readonly number[] | undefined;
1779
1937
  private readonly recordEmbedding?;
1780
1938
  constructor(engine: QueryEngine, options?: RuntimeOptions);
1781
1939
  /** The bound value of `name`, or NULL when unbound. */
@@ -1893,8 +2051,8 @@ interface ResolvedRelationOn {
1893
2051
  *
1894
2052
  * CONVENTION: a relation field's NAME is the key for all purposes. There are
1895
2053
  * no exposed foreign-key fields — `owns` (FK on THIS type, "belongs-to") is
1896
- * INFERRED as `count === 1`; `count > 1` ⇒ has-many (FK on the target). See
1897
- * `resolveKey`.
2054
+ * INFERRED as `count === 1` AND no `inverseVia` (see `isBelongsTo`); otherwise
2055
+ * has-many (FK on the target). See `resolveKey`.
1898
2056
  *
1899
2057
  * `inverseRelation`, when set on a belongs-to relation, asks the registry to
1900
2058
  * materialize a one-to-many relation of that name back on the TARGET Type.
@@ -1928,14 +2086,29 @@ declare class RelationFieldType extends FieldType {
1928
2086
  static from(json: FieldTypeDef): RelationFieldType;
1929
2087
  /** The Zod schema for this field type's JSON def. */
1930
2088
  static toSchema(): z.ZodTypeAny;
2089
+ /**
2090
+ * True when the FOREIGN KEY lives on THIS Type — a declared belongs-to. The
2091
+ * cardinality alone is NOT the discriminator: a MATERIALIZED INVERSE (one
2092
+ * carrying {@link inverseVia}) is never belongs-to however its estimated
2093
+ * `count` came out, because `Registry.finalize()` derives that count from a
2094
+ * ROW RATIO (`round(source.count / target.count)`) — so a 1:1 pair, or two
2095
+ * unmeasured Types sharing one declared row estimate, legitimately yields 1.
2096
+ *
2097
+ * Reading `count === 1` alone made such an inverse resolve its join as
2098
+ * `order.invoice = invoice.id`, where `order.invoice` is the SYNTHETIC
2099
+ * relation field the registry just added rather than a column — every
2100
+ * traversal then matched zero rows, silently. The FK side is knowable from
2101
+ * `inverseVia`; this is where that knowledge is applied.
2102
+ */
2103
+ isBelongsTo(): boolean;
1931
2104
  /**
1932
2105
  * Resolve the join key for this relation, given the relation field's NAME and
1933
2106
  * the two Types it relates. The relation field's NAME is the key:
1934
- * - belongs-to (`count === 1`): `this.<relName> = target.<identity>` —
2107
+ * - belongs-to ({@link isBelongsTo}): `this.<relName> = target.<identity>` —
1935
2108
  * the local relation field holds the target's identity value.
1936
- * - has-many (`count > 1`): `this.<identity> = target.<fk>` — where the
1937
- * FK on the target is `inverseVia` (for a materialized inverse) else the
1938
- * declaring Type's name in camelCase.
2109
+ * - has-many: `this.<identity> = target.<fk>` — where the FK on the target
2110
+ * is `inverseVia` (for a materialized inverse) else the declaring Type's
2111
+ * name in camelCase.
1939
2112
  */
1940
2113
  resolveKey(relationFieldName: string, thisType: Type, targetType: Type): RelationKey;
1941
2114
  /**
@@ -1958,7 +2131,7 @@ declare class RelationFieldType extends FieldType {
1958
2131
  * source, `targetAlias` = the target), so aliased / self-joins resolve.
1959
2132
  *
1960
2133
  * The backing lives on the OWNING (belongs-to) relation. A materialized
1961
- * inverse has-many (`count > 1` with an `inverseVia`) REUSES the SAME FK: its
2134
+ * inverse has-many (one carrying an `inverseVia`) REUSES the SAME FK: its
1962
2135
  * forward relation's `relation` backing on the target Type, with the key
1963
2136
  * orientation SWAPPED (the declaring side is now the join's target). A
1964
2137
  * directly-declared has-many (no `inverseVia`) has no forward relation to
@@ -2013,12 +2186,42 @@ declare class FieldRefExpr extends Expr {
2013
2186
  private resolveRelation;
2014
2187
  /** Validate the source resolves to a type and has the named field; report problems. */
2015
2188
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): ResolvedType;
2189
+ /**
2190
+ * Report the relation-as-value problem for this position, if any. Split into
2191
+ * three distinct outcomes because they have three different fixes:
2192
+ * - an identity-value position + a BELONGS-TO ⇒ fine, it has a local key;
2193
+ * - an identity-value position + a HAS-MANY ⇒ there is no key on this row at
2194
+ * all and its "value" is a set, so say that instead of the join-it hint;
2195
+ * - inside an AGGREGATE ⇒ an identity is not summable/averageable/max-able
2196
+ * under any representation, so say that;
2197
+ * - anywhere else ⇒ the long-standing "join it" hint.
2198
+ */
2199
+ private checkRelationUse;
2016
2200
  /** Zero rows; cost is just the resolved field's byte size. */
2017
2201
  cost(ctx: CostContext, scope: QueryScope): Cost;
2018
2202
  /** A field-ref IS a plain column reference (drives GROUP BY / index-key costing). */
2019
2203
  fieldRef(): FieldRefExpr;
2020
2204
  /** Read the field's runtime value, honoring backing (joins/compute/access security). */
2021
2205
  evaluate(ctx: RuntimeContext, row: SourceRow | null): Promise<Value>;
2206
+ /**
2207
+ * Read this ref as a plain COLUMN, skipping the relation-identity projection.
2208
+ *
2209
+ * Needed because a belongs-to's local key column and the relation FIELD share
2210
+ * a name under the package's name convention (`order.userId` is both the
2211
+ * relation and the column holding its key). Every internal reader of a key
2212
+ * column — relation comparison lowering, ORDER BY / GROUP BY expansion, an
2213
+ * `IN` against a scalar subquery — wants the COLUMN; going through
2214
+ * {@link evaluate} would resolve the relation again and hand back the identity
2215
+ * object. Backing (compute / lateral / stored-name remap / access) still
2216
+ * applies exactly as it does for any other column.
2217
+ */
2218
+ columnValue(ctx: RuntimeContext, row: SourceRow | null): Promise<Value>;
2219
+ /**
2220
+ * Apply this field's `access` backing (FLS) to an already-computed value: a
2221
+ * denied field reads NULL. Shared by the relation-identity path, which
2222
+ * bypasses the stored/compute/lateral resolution but must not bypass security.
2223
+ */
2224
+ private securedRun;
2022
2225
  /** Read a stored field off the bound record, attaching the conceptual field's metadata. */
2023
2226
  private storedValue;
2024
2227
  /**
@@ -2035,6 +2238,18 @@ declare class FieldRefExpr extends Expr {
2035
2238
  private attachRelationRun;
2036
2239
  /** Emit as a SqlText column ref, lowering backing (joins/compute/access) when present. */
2037
2240
  toSQL(dialect: Dialect, ctx: SqlContext): SqlText;
2241
+ /**
2242
+ * Emit this ref as a plain COLUMN, skipping the relation-identity projection —
2243
+ * the SQL twin of {@link columnValue}, and needed for the same reason (a
2244
+ * belongs-to's key column shares the relation field's name).
2245
+ */
2246
+ columnSQL(dialect: Dialect, ctx: SqlContext): SqlText;
2247
+ /**
2248
+ * Apply this field's `access` backing (FLS) to an already-emitted fragment —
2249
+ * the SQL twin of {@link securedRun}, so a relation identity is secured by the
2250
+ * same rule as any other column.
2251
+ */
2252
+ private securedSql;
2038
2253
  /**
2039
2254
  * Register every named join this field opts into with the planner (SQL),
2040
2255
  * deduped on the join's deterministic alias so N fields sharing a join emit
@@ -2594,8 +2809,20 @@ declare class ComparisonExpr extends BoolExpr {
2594
2809
  * equality and the equality-like ops (`= <> like notLike ilike`) keep ~a third.
2595
2810
  * An index-covered `=` is discounted separately by the cost model (via
2596
2811
  * {@link indexProbe}); this is the non-indexed fallback.
2812
+ *
2813
+ * An `=` against a column whose field type declares a CLOSED VALUE SET uses
2814
+ * that type's own `1/n` instead of the fixed third — the one case where the
2815
+ * schema knows the real answer (`FieldType.eqSelectivity`).
2597
2816
  */
2598
- selectivity(): number;
2817
+ selectivity(ctx: CostContext, scope: QueryScope): number;
2818
+ /**
2819
+ * The `1/n` an operand's declared closed value set implies, or `undefined`
2820
+ * when neither side declares one. Both operands are consulted so
2821
+ * `:param = order.status` costs the same as `order.status = :param`; when both
2822
+ * declare a set the TIGHTER (smaller) estimate wins, since satisfying both
2823
+ * memberships can only narrow further.
2824
+ */
2825
+ private closedSetSelectivity;
2599
2826
  /** An `=` against a column is an index point-probe (arity 1); other ops are not. */
2600
2827
  indexProbe(): IndexProbe | undefined;
2601
2828
  /** Evaluate under 3VL: a NULL operand yields UNKNOWN; text compares case-insensitively unless a `sensitive` field is involved. */
@@ -2829,7 +3056,17 @@ declare class IsNullExpr extends BoolExpr {
2829
3056
  selectivity(): number;
2830
3057
  /** Evaluate the operand and return whether it is (not) null. */
2831
3058
  evaluateBool(ctx: RuntimeContext, row: SourceRow, group?: readonly SourceRow[]): Promise<boolean>;
2832
- /** Emit as a SqlText fragment (`value IS [NOT] NULL`). */
3059
+ /**
3060
+ * Emit as a SqlText fragment (`value IS [NOT] NULL`).
3061
+ *
3062
+ * A RELATION operand tests its KEY COLUMNS, not the assembled identity
3063
+ * object: the object is a constructed value and is never SQL NULL, so
3064
+ * `json_build_object(...) IS NULL` would be a constant false. Unset means any
3065
+ * key column is null (a partial composite key cannot join), so `IS NULL` is
3066
+ * the OR over them and `IS NOT NULL` the AND of their negations — which also
3067
+ * keeps the predicate index-usable. Matches the runtime, where a relation
3068
+ * ref with any null key evaluates to NULL.
3069
+ */
2833
3070
  toSQL(dialect: Dialect, ctx: SqlContext): SqlText;
2834
3071
  /** Serialize back to its JSON ExprDef. */
2835
3072
  toJSON(): IsNullExprDef;
@@ -3333,9 +3570,13 @@ declare class SemanticExpr extends Expr {
3333
3570
  */
3334
3571
  scanRowPenalty(): number;
3335
3572
  /**
3336
- * Embed the query side into a vector (null when unavailable), using the
3337
- * `SemanticBacking`'s `embedder` override when supplied, else the run / engine
3338
- * embedder.
3573
+ * Resolve the query side into a vector (null when unavailable). A caller-supplied
3574
+ * precomputed embeddings cache (`ctx.resolveEmbedding`, mirroring the SQL path's
3575
+ * `toSQL({ embeddings })`) takes precedence when present — the term's vector is
3576
+ * looked up synchronously; a pre-embedded `[…]` value short-circuits the lookup.
3577
+ * A term MISSING from the cache throws (fail loud). With no cache it falls back
3578
+ * to the `SemanticBacking`'s `embedder` override, else the run / engine embedder
3579
+ * (unchanged existing behavior).
3339
3580
  */
3340
3581
  private queryVector;
3341
3582
  /** Embed `text` via the backing's `embedder` override, else the run's embedder (cached). */
@@ -3398,8 +3639,25 @@ declare class SemanticExpr extends Expr {
3398
3639
  private sideVectorSQL;
3399
3640
  /** The `SemanticBacking` in effect for a bound `alias` (+ field), or `undefined`. */
3400
3641
  private backingForAlias;
3401
- /** The query side of the similarity, emitted for SQL (text / param only). */
3642
+ /**
3643
+ * The query side of the similarity, emitted for SQL (text / param only). A
3644
+ * `semantic(...)` term is TEXT — never a raw embedding — so a literal (and a
3645
+ * plain-text param VALUE) is EMBEDDED into a pgvector TEXT literal (`[…]`) via
3646
+ * the caller's `ctx.semanticText` converter before it is bound; the dialect
3647
+ * then casts it `::vector`. Two existing valid inputs are preserved untouched:
3648
+ * a PRE-EMBEDDED vector-text term / param (already `[…]`) is bound as-is, and a
3649
+ * `null` / absent param binds `null`. When a plain-text term is hit but NO
3650
+ * embeddings cache was supplied — or the term is missing from it — this THROWS
3651
+ * (rather than emitting the invalid `'<text>'::vector`).
3652
+ */
3402
3653
  private querySQL;
3654
+ /**
3655
+ * Resolve a plain-text semantic term to its pgvector TEXT literal via the
3656
+ * caller's precomputed embeddings (`ctx.semanticText`, built from
3657
+ * `toSQL({ embeddings })`), or THROW a directed error when no cache was
3658
+ * supplied. The converter itself throws when the cache lacks THIS term.
3659
+ */
3660
+ private vectorTextForSql;
3403
3661
  /** Serialize back to its JSON ExprDef. */
3404
3662
  toJSON(): SemanticExprDef;
3405
3663
  /** Deep-copy this expr. */
@@ -4163,6 +4421,17 @@ declare class SqlContext {
4163
4421
  * subquery may carry its own sorter), mirroring `filters`.
4164
4422
  */
4165
4423
  readonly sortSpec: readonly SortSelectionDef[];
4424
+ /**
4425
+ * INTERNAL SYNC converter turning a plain-text semantic term (a `semantic(...)`
4426
+ * literal, or a text-param value) into its pgvector TEXT literal (`[…]`) so it
4427
+ * can be bound + cast `::vector`. Built by `engine.toSQL` from its precomputed
4428
+ * `opts.embeddings` cache (looking each term up + formatting the vector);
4429
+ * throws when the cache lacks the term. Undefined when the caller supplied no
4430
+ * embeddings — a `SemanticExpr` that hits a plain-text term then throws
4431
+ * (rather than emitting the invalid `'<text>'::vector`). Propagated to every
4432
+ * nested level so a subquery's semantic terms resolve too.
4433
+ */
4434
+ readonly semanticText: SemanticTextToVector | undefined;
4166
4435
  constructor(
4167
4436
  /** The active dialect (identical to the `dialect` argument of `toSQL`). */
4168
4437
  dialect: Dialect,
@@ -4205,7 +4474,18 @@ declare class SqlContext {
4205
4474
  * it EXPANDS a sorter into concrete terms. Propagates to nested levels (a
4206
4475
  * subquery may carry its own sorter), mirroring `filters`.
4207
4476
  */
4208
- sortSpec?: readonly SortSelectionDef[]);
4477
+ sortSpec?: readonly SortSelectionDef[],
4478
+ /**
4479
+ * INTERNAL SYNC converter turning a plain-text semantic term (a `semantic(...)`
4480
+ * literal, or a text-param value) into its pgvector TEXT literal (`[…]`) so it
4481
+ * can be bound + cast `::vector`. Built by `engine.toSQL` from its precomputed
4482
+ * `opts.embeddings` cache (looking each term up + formatting the vector);
4483
+ * throws when the cache lacks the term. Undefined when the caller supplied no
4484
+ * embeddings — a `SemanticExpr` that hits a plain-text term then throws
4485
+ * (rather than emitting the invalid `'<text>'::vector`). Propagated to every
4486
+ * nested level so a subquery's semantic terms resolve too.
4487
+ */
4488
+ semanticText?: SemanticTextToVector | undefined);
4209
4489
  /** The execution-supplied filter expr bound to `source`, or `undefined`. */
4210
4490
  filtersFor(source: string): Expr | undefined;
4211
4491
  /** Same context with a different scope (same planner / level / root status). */
@@ -4535,6 +4815,18 @@ interface RelationBacking {
4535
4815
  /** A dynamic, alias-correct custom `ON` (overrides `keys`). See {@link RelationOn}. */
4536
4816
  on?: RelationOn;
4537
4817
  }
4818
+ /**
4819
+ * Map a `RelationBacking`'s declared `keys` to ON column pairs ORIENTED to a
4820
+ * join's source (left) + target aliases. `forward` = the join goes the
4821
+ * belongs-to direction (the source alias is the declaring side); when `false`
4822
+ * (a has-many inverse reusing the forward FK) the orientation is swapped.
4823
+ * `targetIdentity` supplies the default column for any pair that omits `foreign`
4824
+ * (the belongs-to TARGET's identity field).
4825
+ */
4826
+ declare function relationKeyColumns(keys: ReadonlyArray<{
4827
+ local: string;
4828
+ foreign?: string;
4829
+ }>, forward: boolean, targetIdentity: string): RelationOnPair[];
4538
4830
  /**
4539
4831
  * The dev-side backing for a whole Type. All members are optional:
4540
4832
  * - `name` is the real underlying source name (default = the Type name); SQL
@@ -4781,6 +5073,13 @@ interface DefaultOrder {
4781
5073
  /** Which SELECTs receive this order (default `'result'`). */
4782
5074
  applyTo?: DefaultOrderScope;
4783
5075
  }
5076
+ /** The direction + NULLs placement of a resolved default-order term. */
5077
+ interface DefaultOrderDir {
5078
+ /** Sort direction (a term's `dir`, defaulted to `'asc'`). */
5079
+ readonly dir: 'asc' | 'desc';
5080
+ /** Explicit NULLs placement, or `undefined` for the direction-based default. */
5081
+ readonly nulls: 'first' | 'last' | undefined;
5082
+ }
4784
5083
  /** The SQL-mode resolution of a `JoinBacking` (`sql` raw fragment, else a `JoinSpec`). */
4785
5084
  type JoinSqlPlan = {
4786
5085
  readonly kind: 'none';
@@ -4977,6 +5276,25 @@ declare class Field implements Node {
4977
5276
  * to `JsonValue` by the annotation.
4978
5277
  */
4979
5278
  declare function exprDigest(expr: ExprDef): string;
5279
+ /**
5280
+ * Rewrite every `field-ref` whose `source` is `from` to `to`, leaving every
5281
+ * other node untouched. Round-trips through JSON (so the result is a plain,
5282
+ * independently-owned def) — the same `JSON.parse`-annotated idiom
5283
+ * {@link exprDigest} uses, no casts.
5284
+ */
5285
+ declare function renameSource(expr: ExprDef, from: string, to: string): ExprDef;
5286
+ /**
5287
+ * The digest an ALIASED usage of `expr` matches an index part on.
5288
+ *
5289
+ * An index part is a TYPE-level fact, so it is necessarily written against the
5290
+ * Type NAME (`IndexPartDef.expr` is an `ExprDef`, and a `field-ref` requires a
5291
+ * `source`). A QUERY may bind that same Type under an alias — `FROM user AS u`,
5292
+ * or either side of a self-join — and then its refs read `u.email`, whose raw
5293
+ * digest can never equal the part's `user.email`. Normalizing the USAGE back to
5294
+ * the Type name is what lets a declared index actually apply; the stored part
5295
+ * digest ({@link IndexPart.digest}) is deliberately left exactly as it is.
5296
+ */
5297
+ declare function aliasedDigest(expr: ExprDef, alias: string, typeName: string): string;
4980
5298
  /** One ordered part of a composite index: an expr + its prefix cardinality. */
4981
5299
  declare class IndexPart {
4982
5300
  /** The indexed expression, stored as raw JSON this phase. */
@@ -5027,10 +5345,19 @@ declare class Index {
5027
5345
  * Because part counts are non-increasing, a longer matched prefix always
5028
5346
  * yields a smaller (or equal) estimate — so this returns the tightest bound
5029
5347
  * the supplied predicates can achieve via this index.
5348
+ *
5349
+ * `alias` names the SOURCE the supplied usages are bound under together with
5350
+ * the TYPE this index belongs to; when they differ, each usage is normalized
5351
+ * back to the type name before matching (see {@link aliasedDigest}). Omitting
5352
+ * it keeps the literal, un-normalized match — the identity case, and what
5353
+ * every pre-existing caller gets.
5030
5354
  */
5031
5355
  prefixReduction(used: ReadonlyArray<{
5032
5356
  toJSON(): ExprDef;
5033
- }>): number | undefined;
5357
+ }>, alias?: {
5358
+ source: string;
5359
+ typeName: string;
5360
+ }): number | undefined;
5034
5361
  /** Build an Index from its `IndexDef` JSON. */
5035
5362
  static from(json: IndexDef): Index;
5036
5363
  /** Serialize to its `IndexDef` JSON shape (emitting `bytes` only when authored explicitly). */
@@ -5058,6 +5385,12 @@ interface TypeSpec {
5058
5385
  fields: Field[];
5059
5386
  /** The (composite) indexes declared on this Type. */
5060
5387
  indexes: Index[];
5388
+ /**
5389
+ * The field (or ordered fields) that IDENTIFY a row. When set it is THE
5390
+ * answer for {@link Type.identityField} / {@link Type.primaryKey} and index
5391
+ * order stops mattering. Omit to fall back to the inferred rule.
5392
+ */
5393
+ identity?: string | string[];
5061
5394
  /** Estimated row count. */
5062
5395
  count: number;
5063
5396
  /**
@@ -5096,6 +5429,12 @@ declare class Type implements Node {
5096
5429
  readonly fields: Field[];
5097
5430
  /** The (composite) indexes declared on this Type. */
5098
5431
  readonly indexes: Index[];
5432
+ /**
5433
+ * The DECLARED identity field names, in key order — normalized from the spec's
5434
+ * `string | string[]`. `undefined` means identity is INFERRED (first
5435
+ * single-part unique index, else `id`), which is index-order dependent.
5436
+ */
5437
+ readonly identity?: readonly string[];
5099
5438
  /** Estimated total row count (drives cost estimation). */
5100
5439
  readonly count: number;
5101
5440
  /** Estimated average bytes per row (drives byte-cost estimation). */
@@ -5122,31 +5461,76 @@ declare class Type implements Node {
5122
5461
  textFields(): Field[];
5123
5462
  /**
5124
5463
  * The IDENTITY field used as the join key on this Type's side of a relation:
5125
- * the field referenced by the first single-part UNIQUE index (one part,
5126
- * `count === 1`, whose expr is a field-ref), else the field named `id`, else
5127
- * a clear error. Relations resolve their keys through this.
5464
+ * the DECLARED `identity` when it names exactly one field, else the field
5465
+ * referenced by the first single-part UNIQUE index (one part, `count === 1`,
5466
+ * whose expr is a field-ref), else the field named `id`, else a clear error.
5467
+ * Relations resolve their keys through this.
5128
5468
  */
5129
5469
  identityField(): Field;
5130
5470
  /**
5131
5471
  * The ordered PRIMARY KEY fields of this Type — generalizing {@link
5132
- * identityField} to COMPOSITE keys: the single identity field (a single-part
5133
- * unique index's field, else `id`) when present, else the fields of the first
5134
- * multi-part UNIQUE index (last part `count === 1`) whose every part is a
5135
- * field-ref. Relations map their key columns to these; a relation VALUE is
5136
- * keyed by these field names. Throws when none exists.
5472
+ * identityField} to COMPOSITE keys: the DECLARED `identity` when set, else the
5473
+ * single identity field (a single-part unique index's field, else `id`), else
5474
+ * the fields of the first multi-part UNIQUE index (last part `count === 1`)
5475
+ * whose every part is a field-ref. Relations map their key columns to these; a
5476
+ * relation VALUE is keyed by these field names. Throws when none exists.
5137
5477
  */
5138
5478
  primaryKey(): Field[];
5139
- /** The single identity field: the first single-part unique index's field, else `id`, else undefined. */
5479
+ /**
5480
+ * The fields named by an explicit `identity` declaration, in key order, or
5481
+ * `undefined` when none is declared. A declared name that is not a field on
5482
+ * this Type is an ERROR rather than a silent fall-back to the inferred rule —
5483
+ * falling back would reintroduce exactly the index-order dependence the
5484
+ * declaration exists to remove, and would do it invisibly.
5485
+ */
5486
+ private declaredIdentity;
5487
+ /**
5488
+ * The single identity field: the DECLARED `identity` when it is exactly one
5489
+ * field, else the first single-part unique index's field, else `id`, else
5490
+ * undefined. A declared COMPOSITE identity has no single field, so it yields
5491
+ * `undefined` here and is answered by {@link primaryKey}.
5492
+ */
5140
5493
  private singleIdentity;
5141
5494
  /**
5142
- * Fields eligible for semantic-aware querying: text fields flagged
5143
- * `semantic` or `search`, plus all relation fields (which can drive
5144
- * cross-entity semantic joins).
5495
+ * Fields eligible for semantic-aware querying: text fields flagged `semantic`
5496
+ * or `search`.
5497
+ *
5498
+ * Relation fields are NOT included. They used to be — on the theory that they
5499
+ * could drive cross-entity semantic joins — which made almost every Type
5500
+ * report itself semantic-eligible on the strength of having a foreign key, and
5501
+ * a whole-source semantic score then silently ran over a Type nobody had
5502
+ * declared semantic. A relation is a join, not an embedding.
5145
5503
  */
5146
5504
  semanticFields(): Field[];
5147
- /** Whether this Type is eligible for embedding-based semantic similarity. */
5505
+ /**
5506
+ * Whether ONE field is declared semantic-eligible: a text field flagged
5507
+ * `semantic` (or `search`, whose index is the same kind of derived artifact).
5508
+ */
5509
+ isFieldSemantic(field: Field): boolean;
5510
+ /**
5511
+ * Whether semantic scoring is possible ANYWHERE on this Type — the whole type
5512
+ * is flagged, or at least one field is. This is the ELIGIBILITY question
5513
+ * (does the `semantic` expr apply to this Type at all), which is what schema
5514
+ * gating and the capability description ask.
5515
+ *
5516
+ * What an UNNARROWED score reads is the row's embedding over
5517
+ * {@link semanticFields}, which no longer counts relation fields — so a Type
5518
+ * whose only "evidence" was owning a foreign key is no longer eligible at
5519
+ * all. See {@link isFieldSemantic} for the per-field question.
5520
+ */
5148
5521
  isSemantic(): boolean;
5149
- /** Whether this Type is eligible for full-text search. */
5522
+ /** Whether ONE field is declared full-text searchable. */
5523
+ isFieldSearchable(field: Field): boolean;
5524
+ /**
5525
+ * Whether full-text search is possible ANYWHERE on this Type — the whole type
5526
+ * is flagged, or at least one field is. The ELIGIBILITY question, used for
5527
+ * schema gating and the capability description.
5528
+ *
5529
+ * It is NOT the answer to "can this type be searched WITHOUT naming a field":
5530
+ * that needs a `SearchBacking` (the searchable document), whose absence is now
5531
+ * refused as `text-search.unbacked` rather than guessed at. See
5532
+ * {@link isFieldSearchable} for the per-field question.
5533
+ */
5150
5534
  isSearchable(): boolean;
5151
5535
  /** Build a Type from its JSON, parsing fields/indexes via `registry`. */
5152
5536
  static from(json: TypeDef, registry: Registry): Type;
@@ -5466,6 +5850,31 @@ interface CostOptions {
5466
5850
  /** Execution-time param VALUES, so a param-bound LIMIT / OFFSET resolves in `outputCost`. */
5467
5851
  params?: Readonly<Record<string, JsonValue>>;
5468
5852
  }
5853
+ /** The dialect-agnostic SQL-emit options common to {@link QueryEngine.toSQL} / {@link QueryEngine.semanticTexts}. */
5854
+ interface BaseSqlOptions {
5855
+ /** Per-Type RLS predicate provider. */
5856
+ rls?: RlsProvider;
5857
+ /** Values for named bind parameters (name → scalar, or a relation `{ pk }` object). */
5858
+ params?: Readonly<Record<string, SqlParamValue>>;
5859
+ /** Execution-time filter predicates per source (authored `ExprDef` or parsed `Expr`). */
5860
+ filters?: Record<string, ExprDef | Expr | null>;
5861
+ /** Execution-time dynamic-sort selection, feeding a SELECT `order`'s `sorter`. */
5862
+ sort?: SortSelectionDef[];
5863
+ /** Emit `COUNT(*) OVER () AS "$total"` on the top-level SELECT. */
5864
+ includeTotal?: boolean;
5865
+ }
5866
+ /** Options for {@link QueryEngine.toSQL}. */
5867
+ interface ToSqlOptions extends BaseSqlOptions {
5868
+ /**
5869
+ * Precomputed text→vector cache (see {@link SemanticEmbeddings}) for every
5870
+ * `semantic(...)` text term — the vectors the caller obtained by embedding the
5871
+ * terms {@link QueryEngine.semanticTexts} returned. Each such term is
5872
+ * looked up here, formatted to pgvector TEXT, and bound (all SYNC). A needed
5873
+ * term ABSENT from the cache throws (never a silently mis-bound
5874
+ * `'<text>'::vector`); an already-`[…]` vector-text term needs no entry.
5875
+ */
5876
+ embeddings?: SemanticEmbeddings;
5877
+ }
5469
5878
  /**
5470
5879
  * The query engine: holds the {@link Registry}, exposes type / function lookup,
5471
5880
  * and is the entry point for resolve / validate / cost / run / toSQL.
@@ -5656,17 +6065,57 @@ declare class QueryEngine {
5656
6065
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
5657
6066
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
5658
6067
  * "$total"` column on the top-level SELECT.
5659
- */
5660
- toSQL(query: Query | QueryDef, dialect: string | Dialect, opts?: {
5661
- rls?: RlsProvider;
5662
- params?: Readonly<Record<string, SqlParamValue>>;
5663
- filters?: Record<string, ExprDef | Expr | null>;
5664
- sort?: SortSelectionDef[];
5665
- includeTotal?: boolean;
5666
- }): {
6068
+ *
6069
+ * `opts.embeddings` is a precomputed text→vector cache (see {@link
6070
+ * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
6071
+ * `semantic(...)` text PARAM — is looked up there, formatted to a pgvector TEXT
6072
+ * literal (`[…]`), and bound (all synchronous). Obtain the terms to embed with
6073
+ * {@link semanticTexts}, embed them, fill the cache, then call this. A
6074
+ * plain-text semantic term with NO cache — or one MISSING from the cache —
6075
+ * THROWS (rather than emitting the invalid `'<text>'::vector`); a pre-embedded
6076
+ * `[…]` vector-text param is always bound as-is (never looked up).
6077
+ */
6078
+ toSQL(query: Query | QueryDef, dialect: string | Dialect, opts?: ToSqlOptions): {
5667
6079
  sql: string;
5668
6080
  params: SqlValue[];
5669
6081
  };
6082
+ /**
6083
+ * Extract the DISTINCT plain-text `semantic(...)` terms in `query` (+ the same
6084
+ * execution-time `opts` `toSQL` sees — `filters` / `params` can carry a semantic
6085
+ * text term) that need embedding, in a STABLE (first-seen) order. Give it a
6086
+ * query + params, get back the text to embed: embed each, fill a
6087
+ * {@link SemanticEmbeddings} cache, then pass that as `toSQL`'s `opts.embeddings`.
6088
+ *
6089
+ * Reuses `toSQL`'s exact emit walk (a discarded COLLECTING pass) rather than a
6090
+ * second walker, so it sees precisely the terms `toSQL` would bind. A term
6091
+ * already in pgvector TEXT form (`[…]`) needs no embedding and is NOT returned;
6092
+ * an absent / relation-`{ pk }` param value is not a semantic term and is
6093
+ * skipped.
6094
+ */
6095
+ semanticTexts(query: Query | QueryDef, opts?: BaseSqlOptions): string[];
6096
+ /**
6097
+ * A dialect for the discarded {@link semanticTexts} pass. The rendered
6098
+ * SQL is thrown away and every dialect drives the same semantic-term walk (a
6099
+ * `semantic(...)` term's query side is emitted — hence collected — regardless of
6100
+ * dialect), so any registered dialect serves; the first is used.
6101
+ */
6102
+ private collectDialect;
6103
+ /**
6104
+ * Build the INTERNAL sync `semanticText` seam (text → pgvector TEXT) the emit
6105
+ * path threads, from a precomputed {@link SemanticEmbeddings} cache: look the
6106
+ * term up and format its vector with {@link toVectorText}; a term MISSING from
6107
+ * the cache throws the same fail-loud error the emit path would (never a
6108
+ * silently mis-bound `'<text>'::vector`). Returns `undefined` when no cache was
6109
+ * supplied, so a plain-text term then hits the emit path's own "no embeddings"
6110
+ * throw.
6111
+ */
6112
+ private semanticConverter;
6113
+ /**
6114
+ * Shared SQL-emit core for {@link toSQL} / {@link semanticTexts}: resolve
6115
+ * the dialect, build the root {@link SqlContext} (threading params / filters /
6116
+ * sort / includeTotal + the SYNC `semanticText` converter), and render.
6117
+ */
6118
+ private emitSQL;
5670
6119
  /**
5671
6120
  * Parse an execution-time filter map (`source → ExprDef | Expr | null`) into a
5672
6121
  * map of bound `Expr`s, dropping `null` / absent entries. A `filters`
@@ -6328,16 +6777,30 @@ interface ValidateContext {
6328
6777
  */
6329
6778
  readonly fieldExprKind?: ExprKind;
6330
6779
  /**
6331
- * Set by the FK-comparison operators (`comparison` / `in` / `between` /
6332
- * `binary`) when validating an operand, to permit a RELATION field-ref there
6333
- * (those operators compare two relations by FK key / reject relation-vs-scalar
6334
- * themselves). Everywhere else it is unset, so a bare relation field-ref used
6335
- * as a scalar VALUE (a select field, aggregate/window value, `partitionBy`,
6336
- * `orderBy`, group-by key, function arg) is a `ref.relation-not-value` error —
6337
- * a relation is a whole related row (possibly composite-keyed), never a value.
6780
+ * How a RELATION field-ref is allowed to be used at this position, if at all:
6781
+ *
6782
+ * - `'compare'` — set by the FK-comparison operators (`comparison` / `in` /
6783
+ * `between` / `binary`), which handle the relation THEMSELVES: a belongs-to
6784
+ * compares by key columns, a has-many by membership, and a
6785
+ * relation-vs-scalar is rejected by the operator.
6786
+ * - `'value'` — set where a relation's IDENTITY is a well-defined value: a
6787
+ * select field / RETURNING, an ORDER BY term, a GROUP BY key, a null test.
6788
+ * Only a BELONGS-TO has one (the key lives on this row); a has-many is a
6789
+ * SET and is refused with a message that says so.
6790
+ * - unset — a relation is not a value here at all (a function argument, a
6791
+ * `case` arm, an arithmetic operand, an aggregate), and a bare relation
6792
+ * field-ref is an error.
6793
+ *
6794
+ * Set ONLY for a DIRECT field-ref operand (see `_field-guard.ts`), so it never
6795
+ * leaks down into a nested expression that would not have earned it.
6338
6796
  */
6339
- readonly relationValueOk?: boolean;
6797
+ readonly relationUse?: RelationUse;
6340
6798
  }
6799
+ /**
6800
+ * How a RELATION field-ref may be used at a given validation position — see
6801
+ * `ValidateContext.relationUse`.
6802
+ */
6803
+ type RelationUse = 'compare' | 'value';
6341
6804
  /** The default top-level context: a bare expression may aggregate freely. */
6342
6805
  declare const ROOT_VALIDATE_CONTEXT: ValidateContext;
6343
6806
  /**
@@ -7190,6 +7653,8 @@ declare class NumberFieldType extends FieldType {
7190
7653
  static toSchema(): z.ZodTypeAny;
7191
7654
  /** Resolve to the `number` scalar comparison category. */
7192
7655
  resolve(): ScalarKind;
7656
+ /** A declared closed set of `n` members makes `= x` a `1/n` predicate. */
7657
+ eqSelectivity(): number | undefined;
7193
7658
  /** Estimated average stored byte size. */
7194
7659
  avgBytes(): number;
7195
7660
  /** SQL column type (`integer` when whole, else `numeric`). */
@@ -7198,7 +7663,7 @@ declare class NumberFieldType extends FieldType {
7198
7663
  toValueSchema(_opts?: ValueSchemaOptions): z.ZodTypeAny;
7199
7664
  /** Serialize to its JSON def (flattening the compacted options). */
7200
7665
  toJSON(): NumberFieldTypeDef;
7201
- /** A copy of this field type (cloning the options bag). */
7666
+ /** A copy of this field type (deep-cloning the options bag's value set). */
7202
7667
  clone(): NumberFieldType;
7203
7668
  }
7204
7669
 
@@ -7216,6 +7681,8 @@ interface TextOptions {
7216
7681
  search?: boolean;
7217
7682
  /** When true, text matching is case-sensitive (default: case-insensitive). */
7218
7683
  sensitive?: boolean;
7684
+ /** The closed set of values this column may hold (see `NumberOptions.values`). */
7685
+ values?: FieldValueDef[];
7219
7686
  }
7220
7687
  /**
7221
7688
  * TextFieldType — a string field with optional length / pattern constraints,
@@ -7246,15 +7713,17 @@ declare class TextFieldType extends FieldType {
7246
7713
  static toSchema(): z.ZodTypeAny;
7247
7714
  /** Resolve to the `text` scalar comparison category. */
7248
7715
  resolve(): ScalarKind;
7716
+ /** A declared closed set of `n` members makes `= x` a `1/n` predicate. */
7717
+ eqSelectivity(): number | undefined;
7249
7718
  /** Estimated average stored byte size (half the max length, else 32). */
7250
7719
  avgBytes(): number;
7251
7720
  /** SQL column type (`varchar(n)` when bounded, else `text`). */
7252
7721
  toSQLType(): string;
7253
- /** Zod schema validating a string, honoring length / pattern options. */
7722
+ /** Zod schema validating a string, honoring the closed value set else length / pattern options. */
7254
7723
  toValueSchema(_opts?: ValueSchemaOptions): z.ZodTypeAny;
7255
7724
  /** Serialize to its JSON def (flattening the compacted options). */
7256
7725
  toJSON(): TextFieldTypeDef;
7257
- /** A copy of this field type (cloning the options bag). */
7726
+ /** A copy of this field type (deep-cloning the options bag's value set). */
7258
7727
  clone(): TextFieldType;
7259
7728
  }
7260
7729
 
@@ -8165,7 +8634,12 @@ declare class SelectQuery extends Query {
8165
8634
  private fromSQL;
8166
8635
  /** One ORDER BY clause `<key> ASC|DESC [NULLS FIRST|LAST]` from a resolved key + dir/nulls. */
8167
8636
  private orderClauseSQL;
8168
- /** One ORDER BY term: `<expr> ASC|DESC [NULLS FIRST|LAST]`. */
8637
+ /**
8638
+ * One ORDER BY term: `<expr> ASC|DESC [NULLS FIRST|LAST]`. A RELATION term
8639
+ * expands to ONE clause per key column (each inheriting the term's direction
8640
+ * and NULLs placement) — lexicographic over the declared key order, and
8641
+ * index-usable, where sorting the assembled JSON object would be neither.
8642
+ */
8169
8643
  private orderTermSQL;
8170
8644
  /**
8171
8645
  * Emit the SELECT. A SELECT never prepends its own `WITH` (relation crossings
@@ -8863,6 +9337,16 @@ declare class PostgresDialect extends BaseDialect {
8863
9337
  * text-search config defaulting to `'english'`.
8864
9338
  */
8865
9339
  tsvectorSearch(tsv: SqlText, query: SqlText, language?: string): SqlText;
9340
+ /**
9341
+ * `jsonb_build_object` rather than the base `json_build_object`: `jsonb` has
9342
+ * equality and ordering operators, so a projected identity can also be
9343
+ * DISTINCTed or compared, where a `json` value cannot be (Postgres has no
9344
+ * equality operator for `json` at all).
9345
+ */
9346
+ jsonObject(entries: readonly {
9347
+ key: string;
9348
+ value: SqlText;
9349
+ }[]): SqlText;
8866
9350
  /** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
8867
9351
  queryVectorParam(param: SqlText): SqlText;
8868
9352
  /**
@@ -9055,17 +9539,30 @@ interface DrillDownFailure {
9055
9539
  type DrillDownResult = DrillDownSuccess | DrillDownFailure;
9056
9540
  /**
9057
9541
  * A successful `drillDownInto`: the rebuilt query plus the EXTRACTED param
9058
- * VALUE map (each drill param's name → the scalar pulled from the group row),
9542
+ * VALUE map (each drill param's name → the value pulled from the group row),
9059
9543
  * ready for `engine.run(query, { params })`.
9060
9544
  */
9061
9545
  interface DrillDownIntoSuccess {
9062
9546
  /** The un-ravelled SELECT returning the underlying rows. */
9063
9547
  query: SelectQuery;
9064
- /** Bind-param values pulled from the group row (param name → scalar). */
9065
- params: Record<string, ScalarValue>;
9548
+ /**
9549
+ * Bind-param values pulled from the group row (param name → value). Usually a
9550
+ * scalar; a group key that is a RELATION carries that relation's IDENTITY
9551
+ * object (`{ id: 5 }`), which is exactly the shape the rebuilt query's
9552
+ * relation comparison binds.
9553
+ */
9554
+ params: Record<string, DrillValue>;
9066
9555
  /** Non-fatal notes carried over from `drillDown`. */
9067
9556
  warnings: Problems;
9068
9557
  }
9558
+ /**
9559
+ * A value a drill param can carry: a scalar, or the IDENTITY OBJECT of a
9560
+ * relation group key (keyed by the target's identity field names — see the
9561
+ * relation comparison lowering, which accepts exactly this shape).
9562
+ */
9563
+ type DrillValue = ScalarValue | {
9564
+ [key: string]: ScalarValue;
9565
+ };
9069
9566
  /**
9070
9567
  * Un-ravel an aggregating SELECT into a reusable query over the underlying
9071
9568
  * rows: pin each group key to a fresh bind param, replace each aggregate with
@@ -9529,4 +10026,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
9529
10026
  */
9530
10027
  declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
9531
10028
 
9532
- 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, SemanticExpr, type SemanticExprDef, type SemanticQueryDef, 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, 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, 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, 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, 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, typeFromFields, typeMeta, value, variance, week, when, widenNullable, window, withAid, year };
10029
+ 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, 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, 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 };