@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/aeye-query.md CHANGED
@@ -29,8 +29,10 @@ Builders, by group: leaves (`value`/`lit`, `param`, `ref`, `path`, `output`, `ex
29
29
  A `Type` is a named collection of `Field`s plus index + cardinality estimates (`count` rows, `bytes`/row for cost). Each field has a `FieldType` — one of `number`, `text`, `money`, `bool`, `relation`, `date`, `timestamp`, `json`, `array` (nine kinds). Nullability lives on the field, not the type.
30
30
 
31
31
  - **Text** is case-insensitive by default; set `sensitive: true` for case-sensitive matching. Fields may be flagged `semantic` (embedding-eligible) and/or `search` (full-text-eligible); a whole Type may carry the same `semantic` / `search` flags.
32
- - **Relations** carry a target `to` Type and cardinality `count`: the relation field's **name IS the join key** (there are no explicit FK fields). `count === 1` is belongs-to; `count > 1` is has-many. A belongs-to may set `inverseRelation` so its target auto-gains the matching has-many. Join keys resolve through each Type's identity field (first unique single-field index, else `id`).
33
- - **Indexes** are composite (ordered parts, each with a non-increasing prefix distinct-row `count`); unique iff the last part's `count === 1`. They drive cost estimation.
32
+ - **Closed value sets** — `text` and `number` fields take `values?: { value, label? }[]`, an enum expressed as a CONSTRAINT ON the scalar rather than a separate field-type kind. Membership is a QUERY fact: it makes `= x` a `1/n` predicate instead of the fixed `EQ_SELECTIVITY` guess, narrows `toValueSchema()` to the members, and is rendered to the model as `status: text one of applied|screening (In screening)|hired`. The per-member `label` rides along so one closed set has ONE home. Composes with `min`/`max` / `pattern` (a regex is a SHAPE, a value set is MEMBERSHIP — different facts, both allowed).
33
+ - **Relations** carry a target `to` Type and cardinality `count`: the relation field's **name IS the join key** (there are no explicit FK fields). A belongs-to may set `inverseRelation` so its target auto-gains the matching has-many. **Which side the FK is on is `RelationFieldType.isBelongsTo()`, not `count` alone**: a MATERIALIZED INVERSE is never belongs-to however its estimated `count` came out, because the registry derives that count from a row RATIO — so a 1:1 pair (or two types sharing one declared row estimate) legitimately yields `1`.
34
+ - **Identity** — a Type may declare `identity?: string | string[]`, the field (or ordered fields) that IDENTIFY a row. When present it is THE answer for `identityField()` / `primaryKey()` and index ORDER stops mattering. Without it, identity is INFERRED as "the first single-part unique index, else the field named `id`" — so a Type declaring both `id` and a unique `email`, with the email index listed first, silently identifies by `email`, and every relation into it joins a stored id against an email address. Declaring a name the Type does not have is an ERROR, not a silent fall-back to the inferred rule.
35
+ - **Indexes** are composite (ordered parts, each with a non-increasing prefix distinct-row `count`); unique iff the last part's `count === 1`. They drive cost estimation. An index part is a TYPE-level fact, so it is written against the Type NAME; a query binding that Type under an ALIAS (`{kind:'aliased'}`, either side of a self-join) has its probes NORMALIZED back to the type name before matching (`renameSource` / `aliasedDigest` / `Index.prefixReduction(used, alias?)`), and matching is SOURCE-SCOPED so a join alias equal to another Type's name cannot match the scanned Type's parts.
34
36
  - **Arrays** are ordered collections with optional `minItems`/`maxItems` and an optional `item` element field type (omit `item` for heterogeneous); they nest (`array<array<number>>`).
35
37
 
36
38
  `createRegistry()` bootstraps the Type/expr/function catalog; `registry.parseType(def)` + `registerType` add Types. `inferType(name, rows)` derives a `TypeDef` (field types + nullability, array detection) straight from sampled JSON rows.
@@ -67,6 +69,12 @@ Every kind is one branch of the `ExprDef` union. Availability in the LLM schema
67
69
  | `output` | References a projected SELECT output field by name (valid ONLY in `groupBy`/`orderBy`/`having`); expands to that item's expr. |
68
70
  | `tabular-function-call` | A row-producing (table-valued) function call, usable as a source. |
69
71
 
72
+ **A relation's VALUE is its IDENTITY.** A `field-ref` to a **belongs-to** relation is a legal VALUE, reading the key off the caller's OWN row — no join, no scope. It yields a JSON object keyed by the TARGET's identity field names (`{ id: 'userB' }`, `{ tenantId: 3, userId: 1 }`), or SQL `NULL` when ANY key column is null (a partial composite key cannot join, so the relation is unset). A keyed object, not a positional tuple: a tuple's meaning would depend on element order, and that order derives from index order.
73
+
74
+ - **Projectable without a join** — legal in `fields` / `RETURNING`, emitting `CASE WHEN <keys IS NULL> THEN NULL ELSE <json object> END` over the local columns. This is what lets an audit column (`createdBy`) report a value: reading the target through an RLS-scoped join nulls its id along with the rest of the hidden row, making UNSET indistinguishable from HIDDEN. Reading the local column discloses nothing — it is data the reader's own row already holds. The projected field reports `fieldType: 'json'` and is nullable.
75
+ - **Comparable, orderable, groupable** — `=` / `<>` / `in` compare per key column (a bare scalar is accepted iff the key is single-column); `is null` / `is not null` test the KEY COLUMNS (`json_build_object(…) IS NULL` would be a constant false), so they stay index-usable; `order by` expands to one clause per key column (lexicographic over the declared key order) and `group by` to the key columns (structural).
76
+ - **Refusals are STATEABLE** — a **has-many** has no key on this row and its value is a SET, so it is `ref.relation-has-many` (join it, or test membership); an AGGREGATE over an identity is undefined, so it is `ref.relation-aggregate` (group by it instead); anywhere a relation is not a value at all — an arithmetic operand, a `case` arm, a function argument — it stays `ref.relation-not-value` / `compare.relation-vs-value` with the join-it hint.
77
+
70
78
  ## Sources & aliasing
71
79
 
72
80
  Everything is referenced by its **Type name** — there is no alias to invent or keep in sync.
@@ -103,7 +111,9 @@ Types and fields declare **what write operations are possible**, and the model f
103
111
 
104
112
  ## Semantic & text search + scoring / ranking
105
113
 
106
- All three search exprs bind to a **source** with an OPTIONAL `field` (omit ⇒ whole source); eligibility requires a `semantic`/`search`-flagged Type or field.
114
+ All three search exprs bind to a **source** with an OPTIONAL `field` (omit ⇒ whole source); eligibility requires a `semantic`/`search`-flagged Type or field (`Type.isSearchable()` / `isSemantic()` answer "anywhere on this Type"; `isFieldSearchable(f)` / `isFieldSemantic(f)` answer per field).
115
+
116
+ **An unnarrowed `text-search` / `text-score` needs a `SearchBacking` and does NOT guess.** A whole-source search wants the Type's searchable DOCUMENT, which only a backing supplies (a precomputed `vectorField`, or a `sql` override). Without one it is refused — `text-search.unbacked` / `text-score.unbacked` in validation, and a `QueryTypeError` on emission — rather than resolving to the first `search`-flagged field, then the first text field of any kind, then a column literally named `search`. Those three fallbacks meant a query asking for a multi-field document silently searched ONE column, and which column depended on field ORDER. Narrowing to a field needs no backing and is unaffected. Relation fields are no longer counted as semantic-eligible (a foreign key is a join, not an embedding).
107
117
 
108
118
  - **`text-search`** — full-text **predicate** (boolean). `query` is a literal string or a `param`.
109
119
  - **`text-score`** — the **numeric** relevance counterpart (same eligibility): usable in SELECT + ORDER BY, so "top N by text relevance" works. Postgres emits `ts_rank(to_tsvector(col), plainto_tsquery(query))`; base (ANSI) degrades to `CASE WHEN <LIKE> THEN 1 ELSE 0 END`; in-memory is a deterministic token-overlap fraction. Build with `e.textScore(source, query, field?)`.
@@ -130,7 +140,7 @@ The flat `TypeDef` the LLM sees can be arbitrarily richer behind the scenes. A `
130
140
  - **FLS** (`FieldBacking.access`) — a per-field gate emitting `CASE WHEN <pred> THEN <value> ELSE NULL END`; `false` ⇒ constant `NULL`.
131
141
  - **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
142
  - **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.
143
+ - **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
144
 
135
145
  ## Function library
136
146
 
@@ -187,6 +197,11 @@ const result = await engine.run(query, { params, filters, includeTotal });
187
197
 
188
198
  `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
199
 
200
+ - **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:
201
+ 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.
202
+ 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).
203
+ 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.)
204
+
190
205
  ## The LLM tool
191
206
 
192
207
  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: