@aeye/query 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/aeye-query.md CHANGED
@@ -130,7 +130,7 @@ The flat `TypeDef` the LLM sees can be arbitrarily richer behind the scenes. A `
130
130
  - **FLS** (`FieldBacking.access`) — a per-field gate emitting `CASE WHEN <pred> THEN <value> ELSE NULL END`; `false` ⇒ constant `NULL`.
131
131
  - **Named joins & LATERAL** (`TypeBacking.joins`, opted into by `FieldBacking.joins: [name]`) — hidden joins added once per query only when a referencing field is emitted, deduped by name. A `JoinSpec` is a `relation` (reuses relation-join machinery) or a `lateral` (a correlated sub-select; Postgres `LEFT JOIN LATERAL (…) ON true`, base degrades to `ON 1 = 1` and evaluates per outer row; a `lateral.pick` names the default column).
132
132
  - **Relation-join backing** (`FieldBacking.relation`, on a relation-typed field only) — drives a relation join's `ON` from explicit, LLM-HIDDEN physical foreign-key columns instead of the name convention (the JSON `FieldDef`/`TypeDef` are unchanged). `keys: [{ local, foreign? }]` are physical key-column pairs, ALL ANDed (composite FKs supported); `local` is the column on the side that DECLARES the relation, `foreign` the column on the TARGET (defaults to the target's identity). The backing lives on the OWNING **belongs-to** relation; a materialized inverse has-many REUSES the same FK (its forward relation's backing, orientation swapped). `on` is a fully custom, alias-correct predicate — `{ expr }` dual (SQL + runtime), with `sql` / `run` per-mode overrides; precedence like compute/access (`run`/`sql` override → `expr` → the `keys` mapping, else the convention). Every ON site (authored joins, `relation-path` value + runtime, fan-out aggregate grouping, the `TypeBacking.joins` relation spec, joined UPDATE/DELETE) honors it and references the BOUND ALIASES, so aliased / self-joins work; `JoinDef.and` still ANDs onto whatever ON is produced. Example (the belongs-to owner): `fields: { user: { relation: { keys: [{ local: 'user_id', foreign: 'id' }] } } }` ⇒ `ON src.user_id = tgt.id` (and its inverse has-many `ON one.id = many.user_id`).
133
- - **Search / semantic backing** — a `search`/`semantic`-flagged Type/field usually has a physical field hidden from the type system holding a precomputed `tsvector` / `pgvector`. `TypeBacking` and `FieldBacking` each take optional `search?: SearchBacking` / `semantic?: SemanticBacking` (field-level overrides type-level). Knobs (each factory takes the bound `alias` first): `vectorField` (the hidden physical field — a `SearchBacking.vectorField` emits `<alias>."f" @@ plainto_tsquery('<language>', $n)` without re-wrapping in `to_tsvector`; a `SemanticBacking.vectorField` is the left operand of the dialect's `similarity`, query vector bound as `$n::vector`), `language` (default `'english'`), `sql` (full override → boolean/numeric), `run` (runtime override), plus `SemanticBacking.vector` (row embedding source) and `embedder` (per-Type/field query embedder). Precedence (both modes): full `sql`/`run` override wins; else the hidden `vectorField`/`vector`; else the engine default. `toSQL` stays synchronous — the async embedder is never called there (the query vector is a bound param). The base dialect degrades (tsvector → `LIKE`, similarity → `0`) and never throws.
133
+ - **Search / semantic backing** — a `search`/`semantic`-flagged Type/field usually has a physical field hidden from the type system holding a precomputed `tsvector` / `pgvector`. `TypeBacking` and `FieldBacking` each take optional `search?: SearchBacking` / `semantic?: SemanticBacking` (field-level overrides type-level). Knobs (each factory takes the bound `alias` first): `vectorField` (the hidden physical field — a `SearchBacking.vectorField` emits `<alias>."f" @@ plainto_tsquery('<language>', $n)` without re-wrapping in `to_tsvector`; a `SemanticBacking.vectorField` is the left operand of the dialect's `similarity`, query vector bound as `$n::vector`), `language` (default `'english'`), `sql` (full override → boolean/numeric), `run` (runtime override), plus `SemanticBacking.vector` (row embedding source) and `embedder` (per-Type/field query embedder). Precedence (both modes): full `sql`/`run` override wins; else the hidden `vectorField`/`vector`; else the engine default. `toSQL` stays synchronous — the async embedder is never called there; a `vectorField`/`vector` query vector is a bound `$n::vector` param, and a `semantic(...)` TEXT-literal / text-param term is resolved to a pgvector-text literal from the caller's precomputed `embeddings` cache (see [SQL conversion](#sql-conversion): extract terms with `engine.semanticTexts`, embed, then `toSQL(query, dialect, { embeddings })`; a plain-text term with no/missing cache throws). The base dialect degrades (tsvector → `LIKE`, similarity → `0`) and never throws.
134
134
 
135
135
  ## Function library
136
136
 
@@ -187,6 +187,11 @@ const result = await engine.run(query, { params, filters, includeTotal });
187
187
 
188
188
  `engine.toSQL(query, dialect, options?)` emits `{ sql, params }` for any registered dialect. Base uses `?` placeholders; Postgres uses `$1, $2, …`. Relation joins synthesize their ON clause from the relation key. `toSQL` accepts the same `params` / `filters` / `includeTotal` options as `run`, so emitted SQL matches what would run.
189
189
 
190
+ - **Semantic text terms → vectors (extract → embed → sync build).** A `semantic(...)` term whose query is a TEXT literal (or a text `param` value) is TEXT, not an embedding, and cannot be bound as `'<text>'::vector`. Because SQL emission is SYNCHRONOUS, the caller embeds up front and passes the vectors in — `toSQL` (and `run`) stay sync for every caller:
191
+ 1. **Extract** — `engine.semanticTexts(query, opts?) → string[]` returns the DISTINCT plain-text semantic terms needing embedding, in a stable (first-seen) order. It reuses `toSQL`'s exact emit walk, so it finds terms at ANY depth (nested boolean AND/OR/NOT, a subquery WHERE, a computed-field expr, a function-call arg, a CASE/WHEN — anywhere an `Expr` sits) and never returns an already-`'[…]'` vector-text term. `opts` are the same `params` / `filters` a bind would see.
192
+ 2. **Embed** each returned term (the caller's model/network call) and fill a `text → vector` cache — a `ReadonlyMap<string, readonly number[]>` (a resolver function `(text) => readonly number[] | undefined` is accepted too; both are the `SemanticEmbeddings` type).
193
+ 3. **Build** — `engine.toSQL(query, dialect, { embeddings })` looks each term up, formats it with `toVectorText`, and binds `$n::vector` (all sync). A needed term MISSING from the cache **throws** (fail loud) rather than mis-binding; with NO cache a plain-text term likewise throws. A **pre-embedded `'[…]'` vector-text term / param is bound as-is** (never looked up), and a `vectorField` backing (query vector already a `$n::vector` param) is unchanged. The SAME `embeddings` cache is accepted by `engine.run(query, { embeddings })` for in-memory scoring (no embedder required). Helpers: `toVectorText(number[]) → '[…]'`, `parseVectorText('[…]') → number[]`, `isVectorText(string)`. (Replaces the former `convertSemanticText` seam + `toSQLAsync` — with vectors precomputed, nothing in `toSQL` is async.)
194
+
190
195
  ## The LLM tool
191
196
 
192
197
  The parse+validate pipeline is exposed **standalone**, so you can validate a query without building a `Tool` just to call `.parse` on it. All three entries share ONE implementation:
package/dist/index.d.ts CHANGED
@@ -1507,6 +1507,57 @@ declare class QueryScope {
1507
1507
  child(): QueryScope;
1508
1508
  }
1509
1509
 
1510
+ /**
1511
+ * pgvector TEXT helpers + the precomputed text→vector embedding cache.
1512
+ *
1513
+ * A `semantic(...)` term can be a plain-text LITERAL or a text PARAM value. Such
1514
+ * text is NOT an embedding — it must be turned into a vector before it can be
1515
+ * compared. Postgres has no array bind type, so a query vector travels as a
1516
+ * pgvector TEXT literal (`[a,b,c]`) and is cast `::vector` by the dialect. The
1517
+ * embedding itself is a model/network call the query layer does not own, so the
1518
+ * CALLER embeds up front (see `semanticTexts`) and passes the resulting
1519
+ * text→vector cache (see {@link SemanticEmbeddings}) into `engine.toSQL` /
1520
+ * `engine.run`; binding then stays fully SYNCHRONOUS.
1521
+ *
1522
+ * This module has NO runtime imports (pure string/number work), so it sits at
1523
+ * the bottom of the module graph and is safe to import from both the SQL and the
1524
+ * runtime paths.
1525
+ */
1526
+ /**
1527
+ * A caller-supplied SYNC converter turning a plain-text semantic term — a
1528
+ * `semantic(...)` TEXT LITERAL, or the runtime value of a text PARAM — into its
1529
+ * pgvector TEXT form (a bracketed literal such as `[0.0123,-0.045,…]`). It is the
1530
+ * INTERNAL seam the SQL emit path threads (built from a {@link SemanticEmbeddings}
1531
+ * cache by `engine.toSQL`); callers supply the {@link SemanticEmbeddings} cache,
1532
+ * not this converter directly.
1533
+ */
1534
+ type SemanticTextToVector = (text: string) => string;
1535
+ /**
1536
+ * The precomputed text→vector cache a caller fills after embedding the terms
1537
+ * `semanticTexts` extracted, and passes to `engine.toSQL` / `engine.run`
1538
+ * so a `semantic(...)` text term binds SYNCHRONOUSLY. The primary shape is a
1539
+ * `ReadonlyMap<string, readonly number[]>` (text → vector); a resolver function
1540
+ * is accepted as a superset. A term absent from the cache is a fail-loud error at
1541
+ * bind time (never a silently mis-bound `'<text>'::vector`).
1542
+ */
1543
+ type SemanticEmbeddings = ReadonlyMap<string, readonly number[]> | ((text: string) => readonly number[] | undefined);
1544
+ /**
1545
+ * Normalize a {@link SemanticEmbeddings} (map OR resolver) into a lookup
1546
+ * function `text → vector | undefined`. Pure — no runtime imports.
1547
+ */
1548
+ declare function embeddingResolver(embeddings: SemanticEmbeddings): (text: string) => readonly number[] | undefined;
1549
+ /** Whether `text` is already in pgvector TEXT form (a bracketed `[…]` literal). */
1550
+ declare function isVectorText(text: string): boolean;
1551
+ /** Format an embedding vector as pgvector TEXT (`[a,b,c]`, no spaces). */
1552
+ declare function toVectorText(vector: readonly number[]): string;
1553
+ /**
1554
+ * Parse a pgvector TEXT literal (`[a,b,c]`) back into numbers. Tolerates
1555
+ * surrounding whitespace and an empty vector (`[]` ⇒ `[]`). Throws on a value
1556
+ * that is not bracketed pgvector text (so a mis-supplied term fails loudly rather
1557
+ * than silently scoring against a garbage vector).
1558
+ */
1559
+ declare function parseVectorText(text: string): number[];
1560
+
1510
1561
  /**
1511
1562
  * Row-Level-Security injection.
1512
1563
  *
@@ -1718,6 +1769,16 @@ interface RuntimeOptions {
1718
1769
  includeTotal?: boolean;
1719
1770
  /** Embedder override (defaults to the engine's). */
1720
1771
  embedder?: Embedder;
1772
+ /**
1773
+ * Precomputed text→vector cache (see {@link SemanticEmbeddings}) for a
1774
+ * `semantic(...)` QUERY term (a text literal, or a text-param value), mirroring
1775
+ * the SQL path's `toSQL({ embeddings })`. The term's vector is looked up here
1776
+ * and cosine-scored in-memory (no embedder / network call); a pre-embedded
1777
+ * `[…]` value is used directly. Takes precedence over `embedder` for the query
1778
+ * term. A term MISSING from the cache throws (fail loud). With no cache, the
1779
+ * existing embedder path is used unchanged.
1780
+ */
1781
+ embeddings?: SemanticEmbeddings;
1721
1782
  /** Per-record embedding lookup for semantic scoring. */
1722
1783
  recordEmbedding?: (source: string, id: JsonValue) => Promise<number[] | null>;
1723
1784
  /** Cap on recursive-CTE iterations. */
@@ -1776,6 +1837,12 @@ declare class RuntimeContext {
1776
1837
  */
1777
1838
  private readonly sourceTypes;
1778
1839
  private readonly embedder?;
1840
+ /**
1841
+ * Precomputed text→vector cache for a semantic QUERY term (SQL parity), or
1842
+ * `undefined`. Normalized to a lookup function; `undefined` when no cache was
1843
+ * supplied.
1844
+ */
1845
+ readonly resolveEmbedding?: (text: string) => readonly number[] | undefined;
1779
1846
  private readonly recordEmbedding?;
1780
1847
  constructor(engine: QueryEngine, options?: RuntimeOptions);
1781
1848
  /** The bound value of `name`, or NULL when unbound. */
@@ -3333,9 +3400,13 @@ declare class SemanticExpr extends Expr {
3333
3400
  */
3334
3401
  scanRowPenalty(): number;
3335
3402
  /**
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.
3403
+ * Resolve the query side into a vector (null when unavailable). A caller-supplied
3404
+ * precomputed embeddings cache (`ctx.resolveEmbedding`, mirroring the SQL path's
3405
+ * `toSQL({ embeddings })`) takes precedence when present — the term's vector is
3406
+ * looked up synchronously; a pre-embedded `[…]` value short-circuits the lookup.
3407
+ * A term MISSING from the cache throws (fail loud). With no cache it falls back
3408
+ * to the `SemanticBacking`'s `embedder` override, else the run / engine embedder
3409
+ * (unchanged existing behavior).
3339
3410
  */
3340
3411
  private queryVector;
3341
3412
  /** Embed `text` via the backing's `embedder` override, else the run's embedder (cached). */
@@ -3398,8 +3469,25 @@ declare class SemanticExpr extends Expr {
3398
3469
  private sideVectorSQL;
3399
3470
  /** The `SemanticBacking` in effect for a bound `alias` (+ field), or `undefined`. */
3400
3471
  private backingForAlias;
3401
- /** The query side of the similarity, emitted for SQL (text / param only). */
3472
+ /**
3473
+ * The query side of the similarity, emitted for SQL (text / param only). A
3474
+ * `semantic(...)` term is TEXT — never a raw embedding — so a literal (and a
3475
+ * plain-text param VALUE) is EMBEDDED into a pgvector TEXT literal (`[…]`) via
3476
+ * the caller's `ctx.semanticText` converter before it is bound; the dialect
3477
+ * then casts it `::vector`. Two existing valid inputs are preserved untouched:
3478
+ * a PRE-EMBEDDED vector-text term / param (already `[…]`) is bound as-is, and a
3479
+ * `null` / absent param binds `null`. When a plain-text term is hit but NO
3480
+ * embeddings cache was supplied — or the term is missing from it — this THROWS
3481
+ * (rather than emitting the invalid `'<text>'::vector`).
3482
+ */
3402
3483
  private querySQL;
3484
+ /**
3485
+ * Resolve a plain-text semantic term to its pgvector TEXT literal via the
3486
+ * caller's precomputed embeddings (`ctx.semanticText`, built from
3487
+ * `toSQL({ embeddings })`), or THROW a directed error when no cache was
3488
+ * supplied. The converter itself throws when the cache lacks THIS term.
3489
+ */
3490
+ private vectorTextForSql;
3403
3491
  /** Serialize back to its JSON ExprDef. */
3404
3492
  toJSON(): SemanticExprDef;
3405
3493
  /** Deep-copy this expr. */
@@ -4163,6 +4251,17 @@ declare class SqlContext {
4163
4251
  * subquery may carry its own sorter), mirroring `filters`.
4164
4252
  */
4165
4253
  readonly sortSpec: readonly SortSelectionDef[];
4254
+ /**
4255
+ * INTERNAL SYNC converter turning a plain-text semantic term (a `semantic(...)`
4256
+ * literal, or a text-param value) into its pgvector TEXT literal (`[…]`) so it
4257
+ * can be bound + cast `::vector`. Built by `engine.toSQL` from its precomputed
4258
+ * `opts.embeddings` cache (looking each term up + formatting the vector);
4259
+ * throws when the cache lacks the term. Undefined when the caller supplied no
4260
+ * embeddings — a `SemanticExpr` that hits a plain-text term then throws
4261
+ * (rather than emitting the invalid `'<text>'::vector`). Propagated to every
4262
+ * nested level so a subquery's semantic terms resolve too.
4263
+ */
4264
+ readonly semanticText: SemanticTextToVector | undefined;
4166
4265
  constructor(
4167
4266
  /** The active dialect (identical to the `dialect` argument of `toSQL`). */
4168
4267
  dialect: Dialect,
@@ -4205,7 +4304,18 @@ declare class SqlContext {
4205
4304
  * it EXPANDS a sorter into concrete terms. Propagates to nested levels (a
4206
4305
  * subquery may carry its own sorter), mirroring `filters`.
4207
4306
  */
4208
- sortSpec?: readonly SortSelectionDef[]);
4307
+ sortSpec?: readonly SortSelectionDef[],
4308
+ /**
4309
+ * INTERNAL SYNC converter turning a plain-text semantic term (a `semantic(...)`
4310
+ * literal, or a text-param value) into its pgvector TEXT literal (`[…]`) so it
4311
+ * can be bound + cast `::vector`. Built by `engine.toSQL` from its precomputed
4312
+ * `opts.embeddings` cache (looking each term up + formatting the vector);
4313
+ * throws when the cache lacks the term. Undefined when the caller supplied no
4314
+ * embeddings — a `SemanticExpr` that hits a plain-text term then throws
4315
+ * (rather than emitting the invalid `'<text>'::vector`). Propagated to every
4316
+ * nested level so a subquery's semantic terms resolve too.
4317
+ */
4318
+ semanticText?: SemanticTextToVector | undefined);
4209
4319
  /** The execution-supplied filter expr bound to `source`, or `undefined`. */
4210
4320
  filtersFor(source: string): Expr | undefined;
4211
4321
  /** Same context with a different scope (same planner / level / root status). */
@@ -5466,6 +5576,31 @@ interface CostOptions {
5466
5576
  /** Execution-time param VALUES, so a param-bound LIMIT / OFFSET resolves in `outputCost`. */
5467
5577
  params?: Readonly<Record<string, JsonValue>>;
5468
5578
  }
5579
+ /** The dialect-agnostic SQL-emit options common to {@link QueryEngine.toSQL} / {@link QueryEngine.semanticTexts}. */
5580
+ interface BaseSqlOptions {
5581
+ /** Per-Type RLS predicate provider. */
5582
+ rls?: RlsProvider;
5583
+ /** Values for named bind parameters (name → scalar, or a relation `{ pk }` object). */
5584
+ params?: Readonly<Record<string, SqlParamValue>>;
5585
+ /** Execution-time filter predicates per source (authored `ExprDef` or parsed `Expr`). */
5586
+ filters?: Record<string, ExprDef | Expr | null>;
5587
+ /** Execution-time dynamic-sort selection, feeding a SELECT `order`'s `sorter`. */
5588
+ sort?: SortSelectionDef[];
5589
+ /** Emit `COUNT(*) OVER () AS "$total"` on the top-level SELECT. */
5590
+ includeTotal?: boolean;
5591
+ }
5592
+ /** Options for {@link QueryEngine.toSQL}. */
5593
+ interface ToSqlOptions extends BaseSqlOptions {
5594
+ /**
5595
+ * Precomputed text→vector cache (see {@link SemanticEmbeddings}) for every
5596
+ * `semantic(...)` text term — the vectors the caller obtained by embedding the
5597
+ * terms {@link QueryEngine.semanticTexts} returned. Each such term is
5598
+ * looked up here, formatted to pgvector TEXT, and bound (all SYNC). A needed
5599
+ * term ABSENT from the cache throws (never a silently mis-bound
5600
+ * `'<text>'::vector`); an already-`[…]` vector-text term needs no entry.
5601
+ */
5602
+ embeddings?: SemanticEmbeddings;
5603
+ }
5469
5604
  /**
5470
5605
  * The query engine: holds the {@link Registry}, exposes type / function lookup,
5471
5606
  * and is the entry point for resolve / validate / cost / run / toSQL.
@@ -5656,17 +5791,57 @@ declare class QueryEngine {
5656
5791
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
5657
5792
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
5658
5793
  * "$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
- }): {
5794
+ *
5795
+ * `opts.embeddings` is a precomputed text→vector cache (see {@link
5796
+ * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
5797
+ * `semantic(...)` text PARAM — is looked up there, formatted to a pgvector TEXT
5798
+ * literal (`[…]`), and bound (all synchronous). Obtain the terms to embed with
5799
+ * {@link semanticTexts}, embed them, fill the cache, then call this. A
5800
+ * plain-text semantic term with NO cache — or one MISSING from the cache —
5801
+ * THROWS (rather than emitting the invalid `'<text>'::vector`); a pre-embedded
5802
+ * `[…]` vector-text param is always bound as-is (never looked up).
5803
+ */
5804
+ toSQL(query: Query | QueryDef, dialect: string | Dialect, opts?: ToSqlOptions): {
5667
5805
  sql: string;
5668
5806
  params: SqlValue[];
5669
5807
  };
5808
+ /**
5809
+ * Extract the DISTINCT plain-text `semantic(...)` terms in `query` (+ the same
5810
+ * execution-time `opts` `toSQL` sees — `filters` / `params` can carry a semantic
5811
+ * text term) that need embedding, in a STABLE (first-seen) order. Give it a
5812
+ * query + params, get back the text to embed: embed each, fill a
5813
+ * {@link SemanticEmbeddings} cache, then pass that as `toSQL`'s `opts.embeddings`.
5814
+ *
5815
+ * Reuses `toSQL`'s exact emit walk (a discarded COLLECTING pass) rather than a
5816
+ * second walker, so it sees precisely the terms `toSQL` would bind. A term
5817
+ * already in pgvector TEXT form (`[…]`) needs no embedding and is NOT returned;
5818
+ * an absent / relation-`{ pk }` param value is not a semantic term and is
5819
+ * skipped.
5820
+ */
5821
+ semanticTexts(query: Query | QueryDef, opts?: BaseSqlOptions): string[];
5822
+ /**
5823
+ * A dialect for the discarded {@link semanticTexts} pass. The rendered
5824
+ * SQL is thrown away and every dialect drives the same semantic-term walk (a
5825
+ * `semantic(...)` term's query side is emitted — hence collected — regardless of
5826
+ * dialect), so any registered dialect serves; the first is used.
5827
+ */
5828
+ private collectDialect;
5829
+ /**
5830
+ * Build the INTERNAL sync `semanticText` seam (text → pgvector TEXT) the emit
5831
+ * path threads, from a precomputed {@link SemanticEmbeddings} cache: look the
5832
+ * term up and format its vector with {@link toVectorText}; a term MISSING from
5833
+ * the cache throws the same fail-loud error the emit path would (never a
5834
+ * silently mis-bound `'<text>'::vector`). Returns `undefined` when no cache was
5835
+ * supplied, so a plain-text term then hits the emit path's own "no embeddings"
5836
+ * throw.
5837
+ */
5838
+ private semanticConverter;
5839
+ /**
5840
+ * Shared SQL-emit core for {@link toSQL} / {@link semanticTexts}: resolve
5841
+ * the dialect, build the root {@link SqlContext} (threading params / filters /
5842
+ * sort / includeTotal + the SYNC `semanticText` converter), and render.
5843
+ */
5844
+ private emitSQL;
5670
5845
  /**
5671
5846
  * Parse an execution-time filter map (`source → ExprDef | Expr | null`) into a
5672
5847
  * map of bound `Expr`s, dropping `null` / absent entries. A `filters`
@@ -9529,4 +9704,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
9529
9704
  */
9530
9705
  declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
9531
9706
 
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 };
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 };
package/dist/index.js CHANGED
@@ -2990,7 +2990,7 @@ var raw = (text) => SqlText.raw(text);
2990
2990
  var concat = (parts) => SqlText.concat(parts);
2991
2991
  var join = (parts, sep) => SqlText.join(parts, sep);
2992
2992
  var SqlContext = class _SqlContext {
2993
- constructor(dialect, engine, scope, planner, rls, inAggregate = false, params = {}, filters2 = {}, includeTotal = false, isRoot = false, sortSpec = []) {
2993
+ constructor(dialect, engine, scope, planner, rls, inAggregate = false, params = {}, filters2 = {}, includeTotal = false, isRoot = false, sortSpec = [], semanticText2 = void 0) {
2994
2994
  this.dialect = dialect;
2995
2995
  this.engine = engine;
2996
2996
  this.scope = scope;
@@ -3002,6 +3002,7 @@ var SqlContext = class _SqlContext {
3002
3002
  this.includeTotal = includeTotal;
3003
3003
  this.isRoot = isRoot;
3004
3004
  this.sortSpec = sortSpec;
3005
+ this.semanticText = semanticText2;
3005
3006
  }
3006
3007
  dialect;
3007
3008
  engine;
@@ -3014,23 +3015,24 @@ var SqlContext = class _SqlContext {
3014
3015
  includeTotal;
3015
3016
  isRoot;
3016
3017
  sortSpec;
3018
+ semanticText;
3017
3019
  /** The execution-supplied filter expr bound to `source`, or `undefined`. */
3018
3020
  filtersFor(source) {
3019
3021
  return this.filters[source];
3020
3022
  }
3021
3023
  /** Same context with a different scope (same planner / level / root status). */
3022
3024
  withScope(scope) {
3023
- return new _SqlContext(this.dialect, this.engine, scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec);
3025
+ return new _SqlContext(this.dialect, this.engine, scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec, this.semanticText);
3024
3026
  }
3025
3027
  /** A nested level (subquery): fresh scope + fresh planner, not in-aggregate.
3026
3028
  * Neither the outer `$total` flag NOR root status propagates into a nested
3027
3029
  * level, so a subquery / FROM subquery emits as non-root. */
3028
3030
  withPlanner(scope, planner) {
3029
- return new _SqlContext(this.dialect, this.engine, scope, planner, this.rls, false, this.params, this.filters, false, false, this.sortSpec);
3031
+ return new _SqlContext(this.dialect, this.engine, scope, planner, this.rls, false, this.params, this.filters, false, false, this.sortSpec, this.semanticText);
3030
3032
  }
3031
3033
  /** Toggle the in-aggregate flag (set when emitting an aggregate argument). */
3032
3034
  asAggregate(on) {
3033
- return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, on, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec);
3035
+ return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, on, this.params, this.filters, this.includeTotal, this.isRoot, this.sortSpec, this.semanticText);
3034
3036
  }
3035
3037
  /**
3036
3038
  * Mark the NEXT emitted query as NON-root (same level otherwise). Used at the
@@ -3038,7 +3040,7 @@ var SqlContext = class _SqlContext {
3038
3040
  * branch — so those nested SELECTs never inherit the entry's root status.
3039
3041
  */
3040
3042
  nonRoot() {
3041
- return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, false, this.sortSpec);
3043
+ return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, false, this.sortSpec, this.semanticText);
3042
3044
  }
3043
3045
  };
3044
3046
 
@@ -7384,6 +7386,27 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7384
7386
  }
7385
7387
  };
7386
7388
 
7389
+ // src/vector-text.ts
7390
+ function embeddingResolver(embeddings) {
7391
+ return typeof embeddings === "function" ? embeddings : (text) => embeddings.get(text);
7392
+ }
7393
+ function isVectorText(text) {
7394
+ const t = text.trim();
7395
+ return t.startsWith("[") && t.endsWith("]");
7396
+ }
7397
+ function toVectorText(vector) {
7398
+ return `[${vector.join(",")}]`;
7399
+ }
7400
+ function parseVectorText(text) {
7401
+ const t = text.trim();
7402
+ if (!isVectorText(t)) {
7403
+ throw new Error(`parseVectorText: expected pgvector text '[\u2026]', got ${JSON.stringify(text)}.`);
7404
+ }
7405
+ const inner = t.slice(1, -1).trim();
7406
+ if (inner.length === 0) return [];
7407
+ return inner.split(",").map((part) => Number(part.trim()));
7408
+ }
7409
+
7387
7410
  // src/exprs/semantic.ts
7388
7411
  function cosine(a, b) {
7389
7412
  const n = Math.min(a.length, b.length);
@@ -7613,14 +7636,29 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7613
7636
  return SEMANTIC_ROW_PENALTY;
7614
7637
  }
7615
7638
  /**
7616
- * Embed the query side into a vector (null when unavailable), using the
7617
- * `SemanticBacking`'s `embedder` override when supplied, else the run / engine
7618
- * embedder.
7639
+ * Resolve the query side into a vector (null when unavailable). A caller-supplied
7640
+ * precomputed embeddings cache (`ctx.resolveEmbedding`, mirroring the SQL path's
7641
+ * `toSQL({ embeddings })`) takes precedence when present — the term's vector is
7642
+ * looked up synchronously; a pre-embedded `[…]` value short-circuits the lookup.
7643
+ * A term MISSING from the cache throws (fail loud). With no cache it falls back
7644
+ * to the `SemanticBacking`'s `embedder` override, else the run / engine embedder
7645
+ * (unchanged existing behavior).
7619
7646
  */
7620
7647
  async queryVector(ctx, q, embedder) {
7621
- if (q.kind === "text") return this.embedText(ctx, q.text, embedder);
7622
- const text = ctx.param(q.param.name).toText();
7623
- return text.length > 0 ? this.embedText(ctx, text, embedder) : null;
7648
+ const text = q.kind === "text" ? q.text : ctx.param(q.param.name).toText();
7649
+ if (text.length === 0) return null;
7650
+ const resolve = ctx.resolveEmbedding;
7651
+ if (resolve) {
7652
+ if (isVectorText(text)) return parseVectorText(text);
7653
+ const vector = resolve(text);
7654
+ if (vector === void 0) {
7655
+ throw new Error(
7656
+ `SemanticExpr.evaluate: no embedding supplied for the semantic term ${JSON.stringify(text)}. Collect the terms with 'engine.semanticTexts(query, opts)', embed each, and pass them via 'run({ embeddings })' (a text\u2192vector Map).`
7657
+ );
7658
+ }
7659
+ return [...vector];
7660
+ }
7661
+ return this.embedText(ctx, text, embedder);
7624
7662
  }
7625
7663
  /** Embed `text` via the backing's `embedder` override, else the run's embedder (cached). */
7626
7664
  async embedText(ctx, text, embedder) {
@@ -7648,7 +7686,7 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7648
7686
  const type = this.boundType(ctx);
7649
7687
  const backing = type ? ctx.engine.semanticBacking(type.name, this.field) : void 0;
7650
7688
  const embedder = backing?.embedder;
7651
- if (!embedder && !ctx.hasEmbedder()) return Value.of(0);
7689
+ if (!embedder && !ctx.hasEmbedder() && !ctx.resolveEmbedding) return Value.of(0);
7652
7690
  const queryVec = await this.queryVector(ctx, q, embedder);
7653
7691
  if (!queryVec) return Value.of(0);
7654
7692
  const rec = row[this.source] ?? ctx.correlation?.[this.source];
@@ -7781,11 +7819,44 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7781
7819
  if (!bound || bound.kind !== "type") return void 0;
7782
7820
  return ctx.engine.semanticBacking(bound.type.name, field);
7783
7821
  }
7784
- /** The query side of the similarity, emitted for SQL (text / param only). */
7785
- querySQL(dialect, ctx) {
7786
- if (this.query.kind === "text") return SqlText.param(this.query.text);
7787
- if (this.query.kind !== "param") return SqlText.raw("0");
7788
- return this.query.param.toSQL(dialect, ctx);
7822
+ /**
7823
+ * The query side of the similarity, emitted for SQL (text / param only). A
7824
+ * `semantic(...)` term is TEXT — never a raw embedding — so a literal (and a
7825
+ * plain-text param VALUE) is EMBEDDED into a pgvector TEXT literal (`[…]`) via
7826
+ * the caller's `ctx.semanticText` converter before it is bound; the dialect
7827
+ * then casts it `::vector`. Two existing valid inputs are preserved untouched:
7828
+ * a PRE-EMBEDDED vector-text term / param (already `[…]`) is bound as-is, and a
7829
+ * `null` / absent param binds `null`. When a plain-text term is hit but NO
7830
+ * embeddings cache was supplied — or the term is missing from it — this THROWS
7831
+ * (rather than emitting the invalid `'<text>'::vector`).
7832
+ */
7833
+ querySQL(_dialect, ctx) {
7834
+ const q = this.query;
7835
+ if (q.kind === "text") {
7836
+ if (isVectorText(q.text)) return SqlText.param(q.text);
7837
+ return SqlText.param(this.vectorTextForSql(ctx, q.text));
7838
+ }
7839
+ if (q.kind !== "param") return SqlText.raw("0");
7840
+ const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, q.param.name) ? ctx.params[q.param.name] : null;
7841
+ if (raw2 === null || typeof raw2 === "object") return SqlText.param(null);
7842
+ const text = String(raw2);
7843
+ if (isVectorText(text)) return SqlText.param(text);
7844
+ return SqlText.param(this.vectorTextForSql(ctx, text));
7845
+ }
7846
+ /**
7847
+ * Resolve a plain-text semantic term to its pgvector TEXT literal via the
7848
+ * caller's precomputed embeddings (`ctx.semanticText`, built from
7849
+ * `toSQL({ embeddings })`), or THROW a directed error when no cache was
7850
+ * supplied. The converter itself throws when the cache lacks THIS term.
7851
+ */
7852
+ vectorTextForSql(ctx, text) {
7853
+ const convert = ctx.semanticText;
7854
+ if (!convert) {
7855
+ throw new Error(
7856
+ `SemanticExpr.toSQL: the semantic term ${JSON.stringify(text)} is plain text, not a vector, and cannot be bound as-is (Postgres cannot cast '<text>'::vector). Collect the terms with 'engine.semanticTexts(query, opts)', embed each, and pass them via 'engine.toSQL(query, dialect, { embeddings })' \u2014 or pass the query vector as a pre-embedded '[\u2026]' vector-text param.`
7857
+ );
7858
+ }
7859
+ return convert(text);
7789
7860
  }
7790
7861
  /** Serialize back to its JSON ExprDef. */
7791
7862
  toJSON() {
@@ -11133,6 +11204,12 @@ var RuntimeContext = class {
11133
11204
  */
11134
11205
  sourceTypes = /* @__PURE__ */ new Map();
11135
11206
  embedder;
11207
+ /**
11208
+ * Precomputed text→vector cache for a semantic QUERY term (SQL parity), or
11209
+ * `undefined`. Normalized to a lookup function; `undefined` when no cache was
11210
+ * supplied.
11211
+ */
11212
+ resolveEmbedding;
11136
11213
  recordEmbedding;
11137
11214
  constructor(engine, options = {}) {
11138
11215
  this.engine = engine;
@@ -11142,6 +11219,7 @@ var RuntimeContext = class {
11142
11219
  this.sortSelection = options.sort ?? [];
11143
11220
  this.rlsProvider = options.rls;
11144
11221
  this.embedder = options.embedder ?? engine.embedder;
11222
+ this.resolveEmbedding = options.embeddings ? embeddingResolver(options.embeddings) : void 0;
11145
11223
  this.recordEmbedding = options.recordEmbedding;
11146
11224
  if (options.params) {
11147
11225
  for (const name of Object.keys(options.params)) {
@@ -15747,6 +15825,7 @@ function assertNever9(value2) {
15747
15825
  }
15748
15826
 
15749
15827
  // src/engine.ts
15828
+ var PLACEHOLDER_VECTOR_TEXT = "[0]";
15750
15829
  var QueryEngine = class {
15751
15830
  /** The registry of types, field types, exprs, queries, dialects, and functions. */
15752
15831
  registry;
@@ -16060,15 +16139,87 @@ var QueryEngine = class {
16060
16139
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
16061
16140
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
16062
16141
  * "$total"` column on the top-level SELECT.
16142
+ *
16143
+ * `opts.embeddings` is a precomputed text→vector cache (see {@link
16144
+ * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
16145
+ * `semantic(...)` text PARAM — is looked up there, formatted to a pgvector TEXT
16146
+ * literal (`[…]`), and bound (all synchronous). Obtain the terms to embed with
16147
+ * {@link semanticTexts}, embed them, fill the cache, then call this. A
16148
+ * plain-text semantic term with NO cache — or one MISSING from the cache —
16149
+ * THROWS (rather than emitting the invalid `'<text>'::vector`); a pre-embedded
16150
+ * `[…]` vector-text param is always bound as-is (never looked up).
16063
16151
  */
16064
16152
  toSQL(query, dialect, opts) {
16153
+ return this.emitSQL(query, dialect, opts, this.semanticConverter(opts?.embeddings));
16154
+ }
16155
+ /**
16156
+ * Extract the DISTINCT plain-text `semantic(...)` terms in `query` (+ the same
16157
+ * execution-time `opts` `toSQL` sees — `filters` / `params` can carry a semantic
16158
+ * text term) that need embedding, in a STABLE (first-seen) order. Give it a
16159
+ * query + params, get back the text to embed: embed each, fill a
16160
+ * {@link SemanticEmbeddings} cache, then pass that as `toSQL`'s `opts.embeddings`.
16161
+ *
16162
+ * Reuses `toSQL`'s exact emit walk (a discarded COLLECTING pass) rather than a
16163
+ * second walker, so it sees precisely the terms `toSQL` would bind. A term
16164
+ * already in pgvector TEXT form (`[…]`) needs no embedding and is NOT returned;
16165
+ * an absent / relation-`{ pk }` param value is not a semantic term and is
16166
+ * skipped.
16167
+ */
16168
+ semanticTexts(query, opts) {
16169
+ const terms = /* @__PURE__ */ new Set();
16170
+ const dialect = this.collectDialect();
16171
+ this.emitSQL(query, dialect, opts, (text) => {
16172
+ terms.add(text);
16173
+ return PLACEHOLDER_VECTOR_TEXT;
16174
+ });
16175
+ return [...terms];
16176
+ }
16177
+ /**
16178
+ * A dialect for the discarded {@link semanticTexts} pass. The rendered
16179
+ * SQL is thrown away and every dialect drives the same semantic-term walk (a
16180
+ * `semantic(...)` term's query side is emitted — hence collected — regardless of
16181
+ * dialect), so any registered dialect serves; the first is used.
16182
+ */
16183
+ collectDialect() {
16184
+ const d = this.registry.dialectList()[0];
16185
+ if (!d) throw new Error("QueryEngine.semanticTexts: no dialect registered.");
16186
+ return d;
16187
+ }
16188
+ /**
16189
+ * Build the INTERNAL sync `semanticText` seam (text → pgvector TEXT) the emit
16190
+ * path threads, from a precomputed {@link SemanticEmbeddings} cache: look the
16191
+ * term up and format its vector with {@link toVectorText}; a term MISSING from
16192
+ * the cache throws the same fail-loud error the emit path would (never a
16193
+ * silently mis-bound `'<text>'::vector`). Returns `undefined` when no cache was
16194
+ * supplied, so a plain-text term then hits the emit path's own "no embeddings"
16195
+ * throw.
16196
+ */
16197
+ semanticConverter(embeddings) {
16198
+ if (!embeddings) return void 0;
16199
+ const resolve = embeddingResolver(embeddings);
16200
+ return (text) => {
16201
+ const vector = resolve(text);
16202
+ if (vector === void 0) {
16203
+ throw new Error(
16204
+ `QueryEngine.toSQL: no embedding supplied for the semantic term ${JSON.stringify(text)}. Collect the terms with 'engine.semanticTexts(query, opts)', embed each, and pass them via 'opts.embeddings' (a text\u2192vector Map).`
16205
+ );
16206
+ }
16207
+ return toVectorText(vector);
16208
+ };
16209
+ }
16210
+ /**
16211
+ * Shared SQL-emit core for {@link toSQL} / {@link semanticTexts}: resolve
16212
+ * the dialect, build the root {@link SqlContext} (threading params / filters /
16213
+ * sort / includeTotal + the SYNC `semanticText` converter), and render.
16214
+ */
16215
+ emitSQL(query, dialect, opts, semanticText2) {
16065
16216
  const d = typeof dialect === "string" ? this.registry.dialect(dialect) : dialect;
16066
16217
  if (!d) throw new Error(`QueryEngine.toSQL: unknown dialect '${String(dialect)}'.`);
16067
16218
  const q = this.toQuery(query);
16068
16219
  const scope = this.globalScope();
16069
16220
  const params = opts?.params ?? {};
16070
16221
  const planner = new JoinCtePlanner(d, this, opts?.rls, params);
16071
- const ctx = new SqlContext(d, this, scope, planner, opts?.rls, false, params, this.parseFilters(opts?.filters), opts?.includeTotal ?? false, true, opts?.sort ?? []);
16222
+ const ctx = new SqlContext(d, this, scope, planner, opts?.rls, false, params, this.parseFilters(opts?.filters), opts?.includeTotal ?? false, true, opts?.sort ?? [], semanticText2);
16072
16223
  const rendered = q.toSQL(d, ctx).render(d);
16073
16224
  return { sql: rendered.sql, params: [...rendered.params] };
16074
16225
  }
@@ -17776,6 +17927,7 @@ export {
17776
17927
  drillDownInto,
17777
17928
  e,
17778
17929
  editDistance,
17930
+ embeddingResolver,
17779
17931
  epoch,
17780
17932
  eq,
17781
17933
  excluded,
@@ -17806,6 +17958,7 @@ export {
17806
17958
  isScalar,
17807
17959
  isScalarValue,
17808
17960
  isType,
17961
+ isVectorText,
17809
17962
  join,
17810
17963
  joinAlias,
17811
17964
  joinCode,
@@ -17843,6 +17996,7 @@ export {
17843
17996
  param2 as param,
17844
17997
  parseQueryRequest,
17845
17998
  parseQueryTool,
17999
+ parseVectorText,
17846
18000
  plain,
17847
18001
  pos,
17848
18002
  querySchema,
@@ -17891,6 +18045,7 @@ export {
17891
18045
  textSearch,
17892
18046
  timezoneSchema,
17893
18047
  toArrayRows,
18048
+ toVectorText,
17894
18049
  typeFromFields,
17895
18050
  typeMeta,
17896
18051
  value,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aeye/query",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Query - An LLM-friendly relational query language, runtime & SQL converter",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",