@aeye/query 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/aeye-query.md +31 -20
- package/dist/index.d.ts +473 -65
- package/dist/index.js +2019 -1358
- package/package.json +1 -1
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
|
-
- **
|
|
33
|
-
- **
|
|
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.
|
|
@@ -41,38 +43,43 @@ Every kind is one branch of the `ExprDef` union. Availability in the LLM schema
|
|
|
41
43
|
|
|
42
44
|
| kind | one-line meaning |
|
|
43
45
|
| ---- | ---------------- |
|
|
44
|
-
| `literal` | A constant scalar
|
|
46
|
+
| `literal` | A constant value: a scalar, or a whole JSON DOCUMENT (object / array) for a `json` / `array` field — bound as ONE parameter, never interpolated. |
|
|
45
47
|
| `param` | A named bind parameter; type inferred from use, bound at run/emit time. |
|
|
46
|
-
| `field-ref` | `<source>.<field>` — a field's value from a bound source. |
|
|
47
|
-
| `relation-path` | Walks relation fields from a source (optionally ending at a scalar); planner synthesizes the joins. |
|
|
48
|
+
| `field-ref` | `<source>.<field>` — a field's value from a bound source. A BELONGS-TO relation field projects that relation's IDENTITY off this row (no join); a HAS-MANY is refused (`ref.relation-has-many`). Read the target's OTHER fields through a `relation` join. |
|
|
48
49
|
| `binary` | Arithmetic `left <op> right` (`+ - * / %`). |
|
|
49
50
|
| `unary` | `<op> operand` (`-` / `+`). |
|
|
50
51
|
| `comparison` | `left <op> right` → boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION operand compares by identity in `=`/`<>` only: RHS a same-target relation (FK key) or a `{ pk }` value param; a has-many compares by membership (correlated `EXISTS`). |
|
|
51
52
|
| `logical` | Boolean connective `and` / `or` / `not` over operands. |
|
|
52
|
-
| `is-null` | `value IS [NOT] NULL`. |
|
|
53
|
+
| `is-null` | `value IS [NOT] NULL`. On a belongs-to relation it tests the KEY COLUMNS — i.e. whether the relation is UNSET — so it stays index-usable. |
|
|
53
54
|
| `between` | `value BETWEEN lower AND upper` (negatable). |
|
|
54
|
-
| `in` | `value IN (list \| subquery)` (negatable). A RELATION `value` matches list `{ pk }` values by FK key (belongs-to) or membership (has-many). |
|
|
55
|
+
| `in` | `value IN (list \| subquery)` (negatable). A RELATION `value` matches list `{ pk }` values by FK key (belongs-to) or membership (has-many); a COMPOSITE-key relation may not use the subquery form (`in.relation-composite`). |
|
|
55
56
|
| `case` | `CASE WHEN … THEN … [ELSE …] END`. |
|
|
56
57
|
| `function-call` | A scalar function call by name with named args. |
|
|
57
|
-
| `aggregate` | An aggregate function over a group (`count(*)` = empty args); optional `distinct`. |
|
|
58
|
+
| `aggregate` | An aggregate function over a group (`count(*)` = empty args); optional `distinct`. A relation field-ref is not aggregable (`ref.relation-aggregate`) — group by it instead. |
|
|
58
59
|
| `window` | A window (or windowed-aggregate) function over `partitionBy` / `orderBy`. |
|
|
59
60
|
| `subquery` | A scalar / single-field subquery in value position. |
|
|
60
61
|
| `exists` | `[NOT] EXISTS (subquery)` → boolean. |
|
|
61
62
|
| `array-op` | Predicate over an array field: `contains` / `containsAny` / `containsAll` / `isEmpty` / `notEmpty`. |
|
|
62
|
-
| `text-search` | Full-text predicate over a source (optionally one field) → boolean. |
|
|
63
|
-
| `text-score` | Numeric full-text relevance score of a source (optionally one field) → number (`ts_rank`). |
|
|
63
|
+
| `text-search` | Full-text predicate over a source (optionally one field) → boolean. Narrow it to a field unless the Type declares a search DOCUMENT — an unbacked whole-source search is refused (`text-search.unbacked`). |
|
|
64
|
+
| `text-score` | Numeric full-text relevance score of a source (optionally one field) → number (`ts_rank`). Same backing rule as `text-search` (`text-score.unbacked`). |
|
|
64
65
|
| `semantic` | Embedding-similarity score of a source's row vs a query (string / param / pairing ref) → number. |
|
|
65
66
|
| `filters` | An execution-time filter placeholder bound to a source (optional `fields` allowlist); predicate supplied at run time. |
|
|
66
67
|
| `excluded` | `EXCLUDED."field"` — the proposed row inside `INSERT … ON CONFLICT DO UPDATE`. |
|
|
67
68
|
| `output` | References a projected SELECT output field by name (valid ONLY in `groupBy`/`orderBy`/`having`); expands to that item's expr. |
|
|
68
69
|
| `tabular-function-call` | A row-producing (table-valued) function call, usable as a source. |
|
|
69
70
|
|
|
71
|
+
**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.
|
|
72
|
+
|
|
73
|
+
- **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.
|
|
74
|
+
- **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).
|
|
75
|
+
- **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.
|
|
76
|
+
|
|
70
77
|
## Sources & aliasing
|
|
71
78
|
|
|
72
79
|
Everything is referenced by its **Type name** — there is no alias to invent or keep in sync.
|
|
73
80
|
|
|
74
81
|
- **FROM** — `{ kind: 'type', type: 'user' }` binds under `source: 'user'` (not aliasable). Also available: `aliased` (escape hatch), `subquery`, and `function` (a tabular-function source).
|
|
75
|
-
- **Joins** — a `JoinDef` crosses a **single relation hop**: `on` is a `{ source, field }` ref (the bound source + its relation field). Joined rows bind under the target Type name; the join key is synthesized from the relation (you never write ON). Multi-hop = chained single-hop joins
|
|
82
|
+
- **Joins** — a `JoinDef` crosses a **single relation hop**: `on` is a `{ source, field }` ref (the bound source + its relation field). Joined rows bind under the target Type name; the join key is synthesized from the relation (you never write ON). Multi-hop = chained single-hop joins. `joinType` (`inner`/`left`/`right`/`full`, default `left`) is renamed from `type` to free that key. `and` adds an optional extra predicate.
|
|
76
83
|
- **DML** targets (`insert.into` / `update.type` / `delete.from`) bind under the Type name; DML targets take no alias.
|
|
77
84
|
- **`type` vs `source` rule.** `type` = a registered Type name (FROM `type`, DML targets, relation `to`, a `{ type, field }` semantic ref). `source` = a bound name in scope (Type name / join alias / CTE / aliased source) — used by `field-ref`, `semantic`/`text-search`/`text-score`/`filters`, and a join's `on.source`.
|
|
78
85
|
- **Disambiguation.** For a self-join or two instances of one Type, use `{ kind: 'aliased', type, as }` on FROM, or `as` on a join to override its hop's bound name. Two sources bound under one name → a `source.duplicate` validation error.
|
|
@@ -99,11 +106,15 @@ Types and fields declare **what write operations are possible**, and the model f
|
|
|
99
106
|
- **Field flags** — `insertable` / `updatable` on a `FieldDef` (default **true**). A field whose `FieldBacking.compute` is set defaults to `insertable:false, updatable:false` (override with an explicit flag). Validation rejects a listed non-insertable field (`insert.field-readonly`) / an assigned non-updatable field (`update.field-readonly`); the paired schema offers only insertable `fields` / updatable `set` fields.
|
|
100
107
|
- **Insert-requiredness (THE rule)** — a field is REQUIRED on insert iff it is **insertable AND non-nullable AND has no default AND is not computed**; otherwise optional (nullable / has-default) or excluded (non-insertable). One shared helper (`requiredOnInsert`) drives both the schema (required-vs-optional in paired mode) and validation (`insert.missing-required`, which lists the missing names).
|
|
101
108
|
- **Defaults** — `FieldBacking.default` is a `Value` or a factory `() => Value | Promise<Value>`. Its **presence alone** makes the field optional-on-insert (there is no `hasDefault` flag). At **runtime** an omitted defaulted field is materialized (the value is evaluated / the factory awaited, per row) into the inserted record. In **SQL** the column is simply left out of the INSERT and the database's own column `DEFAULT` fills it — so a JS-factory default is a runtime-only concern.
|
|
109
|
+
- **A write CELL carries a JSON value or an expression** — `WriteValueDef = JsonValue | ExprDef`. A raw SCALAR or a whole DOCUMENT (object / array, for a `json` / `array` column) becomes a literal; a `{ kind }` object is read as an EXPRESSION only when the kind names a REGISTERED expr kind, so a settings blob carrying a `kind` key stays data. An absent key OR a JSON `null` OMITS the field (its default fills in / it stays unset); `{ kind:"literal", value:null }` is the only way to set SQL NULL. A document is bound as ONE parameter cast to the COLUMN's type (`Dialect.jsonValue`) — Postgres `CAST($1 AS jsonb)`, or `ARRAY[$1,$2]::text[]` for a native array column, which cannot take JSON text. A param bound to a document is bound, never silently NULL.
|
|
110
|
+
- **A write value is checked against its COLUMN** — the cell's expr is walked in the target's scope, a `param` cell is OBSERVED against the column's field type (which is the only place a write param's type can come from), and a value of an incompatible category is refused (`write.type`). A RELATION column is exempt: what you write to it is the target's identity, not a value of the relation's own category.
|
|
102
111
|
- **Expr restrictions** — `FieldDef.exprs` is `{ not: ExprKind[] }` (exclude these kinds) or `{ only: ExprKind[] }` (allow exactly these). It can only NARROW what the field TYPE already permits. `field.allowsExpr(kind)` respects both the type floor and the restriction. Validation rejects a denied kind at the field's use site (`field.expr-denied`) — checked on a standalone `field-ref` (gated as `field-ref`), on each gating operator's DIRECT field-ref operand (gated as `comparison` / `between` / `in` / `is-null` / `array-op`), and on the field-naming exprs (`text-search` / `text-score` / `semantic` / `filters`). The paired schema omits an excluded field from the relevant enum and gates a kind away entirely when every candidate field excludes it.
|
|
103
112
|
|
|
104
113
|
## Semantic & text search + scoring / ranking
|
|
105
114
|
|
|
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.
|
|
115
|
+
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).
|
|
116
|
+
|
|
117
|
+
**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
118
|
|
|
108
119
|
- **`text-search`** — full-text **predicate** (boolean). `query` is a literal string or a `param`.
|
|
109
120
|
- **`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?)`.
|
|
@@ -129,7 +140,7 @@ The flat `TypeDef` the LLM sees can be arbitrarily richer behind the scenes. A `
|
|
|
129
140
|
- **Default ordering** (`TypeBacking.defaultOrder`) — a Type's NATURAL sort, applied to a SELECT's `ORDER BY` when the query specifies none (and ordering is meaningful). `DefaultOrder` is `{ by: DefaultOrderTerm[]; applyTo? }`; each `DefaultOrderTerm` is `{ by: Computed; dir?; nulls? }` whose `by` is the sort KEY — the same dual `{ expr }` / `sql` / `run` `Computed` as computed fields, so one key emits to SQL AND sorts in memory identically (`dir` default `'asc'`; `nulls` else the direction-based default — asc ⇒ nulls first, desc ⇒ last — matching an explicit ORDER BY). It applies ONLY when the FROM binds the backed Type (joins never contribute their default order), the query has NO explicit `order`, and it is NOT aggregated (no `groupBy`, no bare aggregate) and NOT `DISTINCT` (both skipped — a base-field order is meaningless post-aggregation, and a non-selected DISTINCT key is illegal SQL). `applyTo` scopes WHICH selects receive it: `'result'` (default) ⇒ the ROOT query being run/emitted OR any `LIMIT`/`OFFSET` select; `'paginated'` ⇒ only a `LIMIT`/`OFFSET` select; `'all'` ⇒ every eligible select (incl. subqueries / CTEs). The ROOT is tracked by an `isRoot` marker threaded from `engine.run` / `engine.toSQL` onto the runtime / SQL context; nested queries (a subquery / EXISTS / IN subquery, a FROM subquery, a CTE body, a set-op branch) run/emit non-root. Example — newest-first: `defaultOrder: { by: [{ by: { expr: (a) => ref(a, 'createdAt') }, dir: 'desc' }] }` ⇒ an unsorted select over the Type gets `ORDER BY "t"."createdAt" DESC`. SELECT-only; DML is never reordered.
|
|
130
141
|
- **FLS** (`FieldBacking.access`) — a per-field gate emitting `CASE WHEN <pred> THEN <value> ELSE NULL END`; `false` ⇒ constant `NULL`.
|
|
131
142
|
- **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
|
-
- **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,
|
|
143
|
+
- **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, 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
144
|
- **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
145
|
|
|
135
146
|
## Function library
|
|
@@ -158,14 +169,14 @@ Shapes: `scalar` `(args, ctx)→value`, `tabular` `(args, ctx)→rows`, `aggrega
|
|
|
158
169
|
|
|
159
170
|
| axis | levels (loose → tight) | constrains |
|
|
160
171
|
| ---- | ---------------------- | ---------- |
|
|
161
|
-
| `refs` | `open` · `types` · `fields` · `both` · `paired` | `field-ref` / `
|
|
172
|
+
| `refs` | `open` · `types` · `fields` · `both` · `paired` | every `{ source/type, field }` reference position — `field-ref`, a join's `on`, `semantic` / `text-search` / `text-score` / `filters` |
|
|
162
173
|
| `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
|
|
163
174
|
| `functions` | `open` · `names` · `typed` | function name + named-arg objects |
|
|
164
175
|
| `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
|
|
165
176
|
|
|
166
177
|
Pass a full/partial `SchemaDepth` object, or a preset string: `'open'` (every axis loose) / `'paired'` (every axis tight); the deprecated `strict: true`/`false` are sugar for those. A `FunctionSelector` (`{ scalar: [...], … }`) picks which functions appear; `maxEnumSize` auto-degrades any axis whose enumeration overflows the budget one level looser so a large catalog never yields an unusable schema.
|
|
167
178
|
|
|
168
|
-
**Capability gating** (independent of depth) omits any expr kind the available Types/functions can't use: `semantic` (some Type `isSemantic()`), `text-search`/`text-score` (`isSearchable()`), `array-op` (a Type has an array field), `
|
|
179
|
+
**Capability gating** (independent of depth) omits any expr kind the available Types/functions can't use: `semantic` (some Type `isSemantic()`), `text-search`/`text-score` (`isSearchable()`), `array-op` (a Type has an array field), `joins` (a Type has a relation), `tabular-function-call` (≥1 tabular fn), `aggregate`/`window`/`function-call` (≥1 fn of that shape), `filters` (a Type has filterable fields). The always-usable core (`literal`/`param`/`binary`/`unary`/`comparison`/`logical`/`in`/`between`/`is-null`/`exists`/`case`/`field-ref`/`subquery`) is never gated.
|
|
169
180
|
|
|
170
181
|
## Execution model
|
|
171
182
|
|
|
@@ -250,7 +261,7 @@ Both the owned parser AND the wire schema draw their DIRECTED text from the SAME
|
|
|
250
261
|
|
|
251
262
|
**"Did you mean?" on EVERY unknown-name diagnostic.** A single reusable suggester — `didYouMean(input, candidates, { max? })` in `src/aids.ts` — appends "` — did you mean \`X\`?`" (or "`\`X\` or \`Y\`?`" up to `max`, default 1) whenever a bad NAME is a genuine typo of a valid one, and appends nothing otherwise. It is **typo-only**: a case-insensitive edit distance under a length-scaled budget (`suggestionBudget(len) = min(3, max(1, floor(len/3)))`, exposed alongside the lower-level `nearest(input, candidates, budget?)` primitive), so a short word tolerates one edit and a long one up to three — never a false match on an unrelated word. It powers, uniformly:
|
|
252
263
|
- **schema-enum** failures — a near-miss `op` / `dir` / `nulls` / function-name / Type-name / field-name value gets the canonical spelling appended to `expected <label>: <allowed>` (e.g. `"op": "notlike"` → "… like, notLike, ilike — did you mean `notLike`?"), and the union-no-match `kind` suggestion (`nearestKind` now just calls `nearest`);
|
|
253
|
-
- **validation** (`validateWalk`) unknown-name diagnostics — **field** (`ref` / `filters` / `
|
|
264
|
+
- **validation** (`validateWalk`) unknown-name diagnostics — **field** (`ref` / `filters` / `semantic` / `text-search` / `text-score` / `excluded` / `insert` / `update`, suggested from the resolved Type's field names), **source** (suggested from the bound source names in scope, via the new `QueryScope.sources()` accessor — every source bound anywhere up the chain), **Type** (`insert` / `update` / `delete` / `source` / relation-target, from the registry's Type names), **function** (`function-call` / `aggregate` / `window` / `tabular`, from the registry's function names of that shape), **named-arg** (from the function's declared param names), and **output** (`output` ref, from the SELECT's output field names). Candidates are gathered only when the error is emitted, so there is no hot-path cost.
|
|
254
265
|
|
|
255
266
|
**Tuning the report.** `buildQueryTool(engine, { report })` forwards a `FormatProblemsOptions` (`{ contextLines?, sectionHeaders?, lineNumbers?, maxProblems? }`) straight into `formatProblems`, so a caller can shape the diagnostics the model sees. Absent ⇒ the defaults (`contextLines: 2`, section headers + the `N │` line-number gutter on). E.g. `{ contextLines: 0 }` drops the surrounding context (just the underlined line), `{ contextLines: 4 }` widens it, `{ lineNumbers: false }` drops the gutter, and `{ maxProblems: 3 }` caps how many problems render.
|
|
256
267
|
|
|
@@ -266,13 +277,13 @@ Three DEFENSIVE dispatches — the zod-free parallels to `parseExpr` / `parseQue
|
|
|
266
277
|
|
|
267
278
|
The recursion is completed by four child-slot combinators alongside `exprRef`: **`queryRef`** (a parsed `Query` child — the set-operation arms, CTE bindings, subquery sources, `INSERT … SELECT`), **`queryDefRef`** (a subquery kept as a raw `QueryDef` — the value-position `subquery` / `exists` / `in`-subquery exprs re-parse it lazily, so it validates through `parseCheckedQuery` but returns the normalized `toJSON()` def), and **`sourceRef`** (a `QuerySource` child — a SELECT's `from`). The small building blocks are shared shapes in `queries/_shape.ts`: `selectFieldShape` (`{ expr, as? }`), `fieldValueShape` (`{ field, value }`), and `boundShape` (a limit/offset — a literal integer or a `{ kind:'param' }` def); `QueryOrder.SHAPE` and `QueryJoin.SHAPE` cover an ORDER BY term and a JOIN clause.
|
|
268
279
|
|
|
269
|
-
**The whole query tree now parses through the owned parser.** Expr kinds with a `static SHAPE`: the C1 exemplars (`comparison`, `field-ref`, `literal`, `param`, `logical`) + the C2 operators/predicates/functions/refs (`binary`, `unary`, `is-null`, `between`, `case`, `aggregate`, `window`, `function-call`, `
|
|
280
|
+
**The whole query tree now parses through the owned parser.** Expr kinds with a `static SHAPE`: the C1 exemplars (`comparison`, `field-ref`, `literal`, `param`, `logical`) + the C2 operators/predicates/functions/refs (`binary`, `unary`, `is-null`, `between`, `case`, `aggregate`, `window`, `function-call`, `array-op`, `output`, `excluded`, `text-search`, `text-score`) + the C3 finishers: `subquery`, `exists`, `in` (BOTH forms — its `SHAPE` dispatches on `in`: an array → the list form, an object → the subquery form via `queryDefRef`), `semantic` (whose `query` shape dispatches over the string / `param` / `{source,field}` / `{type,field}` forms), `tabular-function-call`, and `filters`. Query kinds with a `static SHAPE`: `select`, `insert` (incl. `onConflict`), `update`, `delete`, `union` / `intersect` / `except` (three `lit(kind)`-anchored shapes over the shared `SetOperationQuery`), `cte` (its entry shape structurally discriminates the plain vs recursive binding), and `expr`. Source kinds: `type`, `aliased`, `subquery`, `function`. Cross-field rules a plain `obj` can't express (e.g. `logical`'s `not`-arity, `in`'s list-vs-subquery dispatch, `cte`'s entry discrimination) live in a thin hand-written `Shape` wrapper around the base `obj`. An end-to-end test parses a complex SELECT (joins + where + groupBy + having + subquery + aggregate) to a `Query` `.toJSON()`-equal to the throwing `parseQuery`, and a SELECT malformed across several clauses surfaces every problem in ONE pass.
|
|
270
281
|
|
|
271
282
|
**This is the ACTIVE structural gate (C4 flipped).** `parseQueryInput` gates on `parseCheckedQuery` and feeds the sound result to `validateWalk`; the zod `safeParse` structural authority (and `problemsFromZod` / `flattenZodIssues`) has been retired. Zod remains ONLY the model-facing wire schema (`querySchema` / `buildSchemas`), unchanged. This is the intended structure-vs-semantics split: the owned parser accepts any registered kind + any string field, and unknown types / fields / functions are caught downstream by `validateWalk` with the existing aid-directed + `didYouMean` semantic messages.
|
|
272
283
|
|
|
273
284
|
### Compact tool-call schema (shared `$defs`)
|
|
274
285
|
|
|
275
|
-
The model-facing JSON-Schema (what `z.toJSONSchema` — and core's `compile()` — emit from `querySchema`) is **structurally factored**: the largest repeated fragments are built ONCE per schema-generation (a `SchemaCache` threaded on `SchemaOptions.cache`) and REUSED by identity everywhere they occur, so the converter emits each as a single `$def` + `$ref`s instead of inlining every copy. Factored fragments: each Type's **field-name enum** (`$def` `Fields_<Type>`, shared by field-ref /
|
|
286
|
+
The model-facing JSON-Schema (what `z.toJSONSchema` — and core's `compile()` — emit from `querySchema`) is **structurally factored**: the largest repeated fragments are built ONCE per schema-generation (a `SchemaCache` threaded on `SchemaOptions.cache`) and REUSED by identity everywhere they occur, so the converter emits each as a single `$def` + `$ref`s instead of inlining every copy. Factored fragments: each Type's **field-name enum** (`$def` `Fields_<Type>`, shared by field-ref / order / group-by / having / filters / text-search / semantic), the shared **`param`** expr, the reused **`Limit`** (number-or-param), and — the biggest win — the per-function **typed-args** blocks, keyed by argument SIGNATURE so the 100+ builtin functions (which collapse to a few dozen distinct signatures — dozens share a lone `value` arg) reuse one `$def` each. Names come from each shared fragment's `aid`, stamped as `meta.id` (`Fields_user`, `param`, `Limit`, `Args…`) so `z.toJSONSchema` factors AND names them; the ids are salted per schema-generation to stay unique in zod's process-global registry. This is a pure size/structure win — the schema accepts and rejects exactly the same queries with the same aid-directed diagnostics (a golden invariance test guards that), only smaller: on the bundled example fixture the minified `z.toJSONSchema` drops from **21.3 KB → 20.2 KB** (`open`) and **105.6 KB → 95.5 KB** (`paired`), the paired reduction concentrated in the field enums + typed-args (the ~100 genuinely-distinct per-function branches of `typed` mode are irreducible). A size-threshold test catches any regression that re-inlines the shared fragments.
|
|
276
287
|
|
|
277
288
|
## Self-describing the engine to a model
|
|
278
289
|
|
|
@@ -280,8 +291,8 @@ The `describe*` helpers render a compact, promptable capability summary (plain t
|
|
|
280
291
|
|
|
281
292
|
- **`describeEngine(engine, { types?, functions?, maxExamples?, instructions?, examples? })`** composes ONE block a model can read to know everything it may use: every (supplied) Type, then `describeExprs`, then `describeFunctions`, then `describeQueryExamples`, then `describeDialects`. `functions` narrows both the expr gating and the function listing to the schema's selection; `types` narrows the Type list + gating; `maxExamples` caps how many WORKED examples render PER function / node (default `DEFAULT_MAX_EXAMPLES` = 2; `0` omits examples). It no longer needs a separate example-text call — worked examples now live ON the nodes/functions (see below) and are folded in here.
|
|
282
293
|
- **Bring your own instructions / examples (use your OWN Types).** `instructions?: Record<string, string>` and `examples?: Record<string, readonly string[]>` (also `DescribeOverrides`, threaded through `describeExprs` / `describeFunctions` / `describeQueryExamples`) let a caller REPLACE the shipped `INSTRUCTIONS` / `EXAMPLES` for a given item — keyed by function NAME (`sum`, `count`, …) or node KIND (`window`, `in`, `select`, `union`, `cte`, …); names and kinds share ONE flat namespace (they are distinct strings). A key that is PRESENT swaps in the caller's string(s) — e.g. worked examples written against the caller's real domain Types instead of the generic shipped ones — while every key NOT present keeps the shipped default; overridden example lists are still capped by `maxExamples`, and an absent / empty override map renders byte-identically to today. Override strings are the CALLER's responsibility (rendered VERBATIM, not validated at render time): a caller can structurally pre-check their own example strings the same way the shipped-example test does — `JSON.parse` then a bare `createRegistry().parseCheckedQuery(...)` (full queries) / `parseCheckedExpr(...)` (expr fragments) and assert zero problems — before passing them in.
|
|
283
|
-
- **`describeExprs(engine, types?, functions?, maxExamples?)`** lists the CAPABILITY-GATED expression kinds — one `kind — INSTRUCTIONS` line per kind actually usable for the current Types/functions, filtered by the SAME gate the schema uses (`exprKindApplicable`), each followed by up to `maxExamples` `e.g. <json>` lines from the kind's `static EXAMPLES`. The always-usable core is never gated; `semantic` / `text-search` / `text-score` / `array-op` / `
|
|
294
|
+
- **`describeExprs(engine, types?, functions?, maxExamples?)`** lists the CAPABILITY-GATED expression kinds — one `kind — INSTRUCTIONS` line per kind actually usable for the current Types/functions, filtered by the SAME gate the schema uses (`exprKindApplicable`), each followed by up to `maxExamples` `e.g. <json>` lines from the kind's `static EXAMPLES`. The always-usable core is never gated; `semantic` / `text-search` / `text-score` / `array-op` / `tabular-function-call` appear only when an eligible Type/function exists (`excluded` / `output` are position-only and never listed).
|
|
284
295
|
- **`describeFunctions(engine, functions?, maxExamples?)`** renders each function as `name(a, b?): output — instructions` (named params, a trailing `?` marks optional), grouped by shape, each followed by up to `maxExamples` `e.g. <json>` lines from the function's `examples`.
|
|
285
296
|
- **`describeQueryExamples(engine, maxExamples?)`** renders a query-examples section: each registered query KIND that ships `static EXAMPLES` (SELECT, UNION/INTERSECT/EXCEPT, WITH/CTE) as `kind — INSTRUCTIONS` plus up to `maxExamples` worked example queries. Query-level constructs have no expr-catalog entry, so they get their own section.
|
|
286
297
|
- **Worked examples are a shipped, first-class surface.** Every `FunctionDef` may carry `examples?: readonly string[]` (RAW JSON strings — expr fragments or full queries that CALL it), and every Expr/Query node class may carry a `static readonly EXAMPLES?: readonly string[]` (plus, for query kinds, an optional `static INSTRUCTIONS`). Examples are TYPE-AGNOSTIC (illustrative generic source/field names like `event.score` / `user.name`) — they teach SHAPE while the catalog supplies the caller's real Type names. The shipped high-confusion set: the window family (`rank` / `denseRank` / `lag` / `lead` / `firstValue` / `lastValue` / `nthValue` / `cumeDist`), `dateTrunc` / `age` / `replace`, `count`; and the `window` / `exists` / `in` / `subquery` / `function-call` exprs and `select` / `union` / `cte` queries. This is the ONE source of truth — `describeEngine` only renders them. A structural test parses EVERY shipped example through a bare `createRegistry()`'s `parseCheckedQuery` / `parseCheckedExpr` and asserts zero problems.
|
|
287
|
-
- **Generated Type / Field docs.** `describeType` / `describeField` always emit a short `label` + long `description`: the developer's `TypeDef.label` / `FieldDef.description` when set, otherwise a sensible default GENERATED on demand from the meta-model — a Field from its FieldType (kind, bounds, `sensitive` / `semantic` / `search` flags, array item/bounds, a relation's `to` + `count` → belongs-to / has-many, nullability), a Type from its name + field/relation/index summary. Read the (possibly-generated) pair directly with `fieldMeta(field)` / `typeMeta(type)` (`{ label, description }`); nothing mutates the stored def — the strings are computed fresh per call.
|
|
298
|
+
- **Generated Type / Field docs.** `describeType` / `describeField` always emit a short `label` + long `description`: the developer's `TypeDef.label` / `FieldDef.description` when set, otherwise a sensible default GENERATED on demand from the meta-model — a Field from its FieldType (kind, bounds, `sensitive` / `semantic` / `search` flags, array item/bounds, a relation's `to` + `count` + its DIRECTION → belongs-to / has-many, read from `isBelongsTo()` rather than `count` so a materialized inverse is never described as a belongs-to, nullability), a Type from its name + field/relation/index summary. Read the (possibly-generated) pair directly with `fieldMeta(field)` / `typeMeta(type)` (`{ label, description }`); nothing mutates the stored def — the strings are computed fresh per call.
|