@aeye/query 0.6.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 +18 -17
- package/dist/index.d.ts +110 -24
- package/dist/index.js +590 -415
- package/package.json +1 -1
package/aeye-query.md
CHANGED
|
@@ -43,26 +43,25 @@ Every kind is one branch of the `ExprDef` union. Availability in the LLM schema
|
|
|
43
43
|
|
|
44
44
|
| kind | one-line meaning |
|
|
45
45
|
| ---- | ---------------- |
|
|
46
|
-
| `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. |
|
|
47
47
|
| `param` | A named bind parameter; type inferred from use, bound at run/emit time. |
|
|
48
|
-
| `field-ref` | `<source>.<field>` — a field's value from a bound source. |
|
|
49
|
-
| `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. |
|
|
50
49
|
| `binary` | Arithmetic `left <op> right` (`+ - * / %`). |
|
|
51
50
|
| `unary` | `<op> operand` (`-` / `+`). |
|
|
52
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`). |
|
|
53
52
|
| `logical` | Boolean connective `and` / `or` / `not` over operands. |
|
|
54
|
-
| `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. |
|
|
55
54
|
| `between` | `value BETWEEN lower AND upper` (negatable). |
|
|
56
|
-
| `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`). |
|
|
57
56
|
| `case` | `CASE WHEN … THEN … [ELSE …] END`. |
|
|
58
57
|
| `function-call` | A scalar function call by name with named args. |
|
|
59
|
-
| `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. |
|
|
60
59
|
| `window` | A window (or windowed-aggregate) function over `partitionBy` / `orderBy`. |
|
|
61
60
|
| `subquery` | A scalar / single-field subquery in value position. |
|
|
62
61
|
| `exists` | `[NOT] EXISTS (subquery)` → boolean. |
|
|
63
62
|
| `array-op` | Predicate over an array field: `contains` / `containsAny` / `containsAll` / `isEmpty` / `notEmpty`. |
|
|
64
|
-
| `text-search` | Full-text predicate over a source (optionally one field) → boolean. |
|
|
65
|
-
| `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`). |
|
|
66
65
|
| `semantic` | Embedding-similarity score of a source's row vs a query (string / param / pairing ref) → number. |
|
|
67
66
|
| `filters` | An execution-time filter placeholder bound to a source (optional `fields` allowlist); predicate supplied at run time. |
|
|
68
67
|
| `excluded` | `EXCLUDED."field"` — the proposed row inside `INSERT … ON CONFLICT DO UPDATE`. |
|
|
@@ -80,7 +79,7 @@ Every kind is one branch of the `ExprDef` union. Availability in the LLM schema
|
|
|
80
79
|
Everything is referenced by its **Type name** — there is no alias to invent or keep in sync.
|
|
81
80
|
|
|
82
81
|
- **FROM** — `{ kind: 'type', type: 'user' }` binds under `source: 'user'` (not aliasable). Also available: `aliased` (escape hatch), `subquery`, and `function` (a tabular-function source).
|
|
83
|
-
- **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.
|
|
84
83
|
- **DML** targets (`insert.into` / `update.type` / `delete.from`) bind under the Type name; DML targets take no alias.
|
|
85
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`.
|
|
86
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.
|
|
@@ -107,6 +106,8 @@ Types and fields declare **what write operations are possible**, and the model f
|
|
|
107
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.
|
|
108
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).
|
|
109
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.
|
|
110
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.
|
|
111
112
|
|
|
112
113
|
## Semantic & text search + scoring / ranking
|
|
@@ -139,7 +140,7 @@ The flat `TypeDef` the LLM sees can be arbitrarily richer behind the scenes. A `
|
|
|
139
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.
|
|
140
141
|
- **FLS** (`FieldBacking.access`) — a per-field gate emitting `CASE WHEN <pred> THEN <value> ELSE NULL END`; `false` ⇒ constant `NULL`.
|
|
141
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).
|
|
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,
|
|
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`).
|
|
143
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.
|
|
144
145
|
|
|
145
146
|
## Function library
|
|
@@ -168,14 +169,14 @@ Shapes: `scalar` `(args, ctx)→value`, `tabular` `(args, ctx)→rows`, `aggrega
|
|
|
168
169
|
|
|
169
170
|
| axis | levels (loose → tight) | constrains |
|
|
170
171
|
| ---- | ---------------------- | ---------- |
|
|
171
|
-
| `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` |
|
|
172
173
|
| `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
|
|
173
174
|
| `functions` | `open` · `names` · `typed` | function name + named-arg objects |
|
|
174
175
|
| `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
|
|
175
176
|
|
|
176
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.
|
|
177
178
|
|
|
178
|
-
**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.
|
|
179
180
|
|
|
180
181
|
## Execution model
|
|
181
182
|
|
|
@@ -260,7 +261,7 @@ Both the owned parser AND the wire schema draw their DIRECTED text from the SAME
|
|
|
260
261
|
|
|
261
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:
|
|
262
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`);
|
|
263
|
-
- **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.
|
|
264
265
|
|
|
265
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.
|
|
266
267
|
|
|
@@ -276,13 +277,13 @@ Three DEFENSIVE dispatches — the zod-free parallels to `parseExpr` / `parseQue
|
|
|
276
277
|
|
|
277
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.
|
|
278
279
|
|
|
279
|
-
**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.
|
|
280
281
|
|
|
281
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.
|
|
282
283
|
|
|
283
284
|
### Compact tool-call schema (shared `$defs`)
|
|
284
285
|
|
|
285
|
-
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.
|
|
286
287
|
|
|
287
288
|
## Self-describing the engine to a model
|
|
288
289
|
|
|
@@ -290,8 +291,8 @@ The `describe*` helpers render a compact, promptable capability summary (plain t
|
|
|
290
291
|
|
|
291
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.
|
|
292
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.
|
|
293
|
-
- **`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).
|
|
294
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`.
|
|
295
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.
|
|
296
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.
|
|
297
|
-
- **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.
|
package/dist/index.d.ts
CHANGED
|
@@ -123,6 +123,11 @@ interface RelationFieldTypeDef {
|
|
|
123
123
|
* The relation field's NAME is the key for ALL purposes — there are no
|
|
124
124
|
* exposed foreign-key fields. `owns` (the FK living on THIS type) is
|
|
125
125
|
* INFERRED as `count === 1`; `count > 1` means the FK lives on the target.
|
|
126
|
+
* NOTE this holds for a DECLARED def only: the runtime discriminator is
|
|
127
|
+
* `RelationFieldType.isBelongsTo()` (`count === 1` AND no internal
|
|
128
|
+
* `inverseVia`), because a registry-materialized inverse is a has-many
|
|
129
|
+
* whatever its estimated `count` came out as. `inverseVia` is internal and
|
|
130
|
+
* never appears in this def.
|
|
126
131
|
*/
|
|
127
132
|
count: number;
|
|
128
133
|
/**
|
|
@@ -311,10 +316,19 @@ type UnaryOp = '-' | '+';
|
|
|
311
316
|
type ComparisonOp = '=' | '<>' | '<' | '<=' | '>' | '>=' | 'like' | 'notLike' | 'ilike';
|
|
312
317
|
/** Boolean connectives. `not` takes exactly one operand. */
|
|
313
318
|
type LogicalOp = 'and' | 'or' | 'not';
|
|
314
|
-
/**
|
|
319
|
+
/**
|
|
320
|
+
* A literal constant VALUE — a scalar, or a whole JSON document (an object /
|
|
321
|
+
* array) for a `json` / `array` field.
|
|
322
|
+
*
|
|
323
|
+
* The non-scalar half exists because a WRITE CELL had no way to carry one: a
|
|
324
|
+
* `json` column could not be inserted or updated at all (a raw document was
|
|
325
|
+
* refused by the write parser, no expression could carry one, and the `param`
|
|
326
|
+
* route bound SQL `NULL` — see 0.6.1's A9). A non-scalar literal is bound as a
|
|
327
|
+
* single parameter through `Dialect.jsonValue`, never string-interpolated.
|
|
328
|
+
*/
|
|
315
329
|
interface LiteralExprDef {
|
|
316
330
|
kind: 'literal';
|
|
317
|
-
value:
|
|
331
|
+
value: JsonValue;
|
|
318
332
|
}
|
|
319
333
|
/**
|
|
320
334
|
* A direct field reference: `<source>.<field>`. Reuses `SourceFieldRef` — the
|
|
@@ -1280,6 +1294,26 @@ declare abstract class Dialect implements DialectEntry {
|
|
|
1280
1294
|
value: SqlText;
|
|
1281
1295
|
}[]): SqlText;
|
|
1282
1296
|
abstract sqlTypeFor(fieldType: FieldType): string;
|
|
1297
|
+
/**
|
|
1298
|
+
* Bind a whole JSON DOCUMENT (an object / array) as ONE parameter, cast to the
|
|
1299
|
+
* column type it is destined for. The single binding path for a non-scalar
|
|
1300
|
+
* VALUE — a `json` cell, an `array` cell, a document literal in a predicate.
|
|
1301
|
+
*
|
|
1302
|
+
* WHY A CAST, AND WHY THE FIELD TYPE. The document travels as its JSON TEXT in
|
|
1303
|
+
* a normal parameter slot (so `SqlValue` stays scalar and nothing is ever
|
|
1304
|
+
* string-interpolated), which means the server must be told what to parse it
|
|
1305
|
+
* AS. Left to inference, the same text is a `jsonb` in one column and a syntax
|
|
1306
|
+
* error in another. `fieldType` — supplied by the WRITE path, which knows the
|
|
1307
|
+
* column — makes that explicit; without it (a bare literal in a `where`, which
|
|
1308
|
+
* knows only its own shape) the dialect's own JSON type is the default.
|
|
1309
|
+
*
|
|
1310
|
+
* The base dialect casts to whatever `sqlTypeFor` names, which is the portable
|
|
1311
|
+
* answer for a JSON-typed column. A dialect with a NATIVE array type (Postgres
|
|
1312
|
+
* `text[]`) must override — an array literal there is not JSON text.
|
|
1313
|
+
*/
|
|
1314
|
+
jsonValue(value: JsonValue, fieldType?: FieldType): SqlText;
|
|
1315
|
+
/** This dialect's JSON column type — the default cast target for a document. */
|
|
1316
|
+
jsonSqlType(): string;
|
|
1283
1317
|
/**
|
|
1284
1318
|
* Length (element count) of array expression `arg`. Postgres `cardinality`;
|
|
1285
1319
|
* the base dialect degrades to `COALESCE(json_array_length(arg), 0)`.
|
|
@@ -2160,7 +2194,7 @@ declare class FieldRefExpr extends Expr {
|
|
|
2160
2194
|
readonly field: string;
|
|
2161
2195
|
static readonly KIND: "field-ref";
|
|
2162
2196
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
2163
|
-
static readonly INSTRUCTIONS: "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a RELATION field
|
|
2197
|
+
static readonly INSTRUCTIONS: "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a BELONGS-TO RELATION field IS a value: it projects the relation's IDENTITY \u2014 the target's key read off THIS row's own key column(s), as an object keyed by the target's identity field names (`{id:'u1'}`, `{tenantId:3,userId:1}`), NULL when unset \u2014 planning NO join and applying no target scope. Legal in `fields` / `RETURNING`, `order`, `groupBy`, `is null`, and an identity `=` / `<>` / `in`. To read any OTHER field of the target, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. A HAS-MANY ref is REFUSED (`ref.relation-has-many`) \u2014 it has no key on this row and its value is a SET: join it, or test membership against a target key. A relation is still NOT a value as an arithmetic operand / `case` arm / function argument / aggregate; and to CORRELATE a subquery, join the relation and compare the joined key \u2014 never a relation field-ref against an id/scalar.";
|
|
2164
2198
|
readonly kind: "field-ref";
|
|
2165
2199
|
/** Wrap a `<source>.<field>` reference by its source alias and field name. */
|
|
2166
2200
|
constructor(source: string, field: string);
|
|
@@ -2401,15 +2435,15 @@ declare function bytesOfResolved(rt: ResolvedType): number;
|
|
|
2401
2435
|
*/
|
|
2402
2436
|
declare function reportCostProblems(cost: Cost, constraints: CostConstraints, p: Problems): void;
|
|
2403
2437
|
|
|
2404
|
-
/** A constant scalar
|
|
2438
|
+
/** A constant value: a scalar, or a whole JSON document (object / array). */
|
|
2405
2439
|
declare class LiteralExpr extends Expr {
|
|
2406
|
-
readonly value:
|
|
2440
|
+
readonly value: JsonValue;
|
|
2407
2441
|
static readonly KIND: "literal";
|
|
2408
2442
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
2409
|
-
static readonly INSTRUCTIONS: "A constant scalar
|
|
2443
|
+
static readonly INSTRUCTIONS: "A constant value: a scalar (string / number / boolean / null), or a whole JSON DOCUMENT (object / array) for a `json` / `array` field \u2014 which is how a write cell carries one. A document is bound as ONE parameter, never interpolated.";
|
|
2410
2444
|
readonly kind: "literal";
|
|
2411
|
-
/** Wrap a constant
|
|
2412
|
-
constructor(value:
|
|
2445
|
+
/** Wrap a constant value: a scalar, or a whole JSON document. */
|
|
2446
|
+
constructor(value: JsonValue);
|
|
2413
2447
|
/** Reconstruct a LiteralExpr from its JSON def (validates the `kind` discriminant). */
|
|
2414
2448
|
static from(json: ExprDef, _registry: Registry): LiteralExpr;
|
|
2415
2449
|
/**
|
|
@@ -2430,8 +2464,17 @@ declare class LiteralExpr extends Expr {
|
|
|
2430
2464
|
cost(ctx: CostContext, scope: QueryScope): Cost;
|
|
2431
2465
|
/** Evaluate to the wrapped constant value. */
|
|
2432
2466
|
evaluate(): Promise<Value>;
|
|
2433
|
-
/**
|
|
2434
|
-
|
|
2467
|
+
/**
|
|
2468
|
+
* Emit as a SqlText fragment — `NULL` keyword, a bound scalar param, or a
|
|
2469
|
+
* bound DOCUMENT.
|
|
2470
|
+
*
|
|
2471
|
+
* A document has no target field type HERE (a bare literal in a WHERE knows
|
|
2472
|
+
* only its own shape), so it binds through the dialect's default json type.
|
|
2473
|
+
* The WRITE path emits its cells through `writeCellSql`, which supplies the
|
|
2474
|
+
* target COLUMN's field type — the difference between a Postgres `jsonb` cast
|
|
2475
|
+
* and the `ARRAY[…]::text[]` a native array column actually needs.
|
|
2476
|
+
*/
|
|
2477
|
+
toSQL(dialect: Dialect, _ctx: SqlContext): SqlText;
|
|
2435
2478
|
/** Serialize back to its JSON ExprDef. */
|
|
2436
2479
|
toJSON(): LiteralExprDef;
|
|
2437
2480
|
/** Deep-copy this expr. */
|
|
@@ -2691,8 +2734,23 @@ declare class ParamExpr extends Expr {
|
|
|
2691
2734
|
cost(ctx: CostContext, scope: QueryScope): Cost;
|
|
2692
2735
|
/** Evaluate to the runtime-bound value for this param name. */
|
|
2693
2736
|
evaluate(ctx: RuntimeContext): Promise<Value>;
|
|
2694
|
-
/**
|
|
2695
|
-
|
|
2737
|
+
/**
|
|
2738
|
+
* Emit as a bound SqlText param slot (NULL until a value is supplied).
|
|
2739
|
+
*
|
|
2740
|
+
* A NON-SCALAR bound value — a JSON document, or a relation `{ pk }` object
|
|
2741
|
+
* that reached here undecomposed — binds through `Dialect.jsonValue`, NOT as
|
|
2742
|
+
* NULL. Binding NULL was the worst outcome available (A9): the statement
|
|
2743
|
+
* SUCCEEDED and the supplied value was silently dropped, so an INSERT of a
|
|
2744
|
+
* `json` column through a param appeared to work and lost the data. A
|
|
2745
|
+
* relation comparison still decomposes its `{ pk }` object into per-column
|
|
2746
|
+
* binds before reaching here, so that path is unchanged; anything that DOES
|
|
2747
|
+
* get here is a value the caller supplied, and is bound as one.
|
|
2748
|
+
*
|
|
2749
|
+
* A write CELL routes through `writeCellSql` first, which also knows the
|
|
2750
|
+
* target column's field type; this is the fallback for every other position,
|
|
2751
|
+
* which knows only the value's own shape.
|
|
2752
|
+
*/
|
|
2753
|
+
toSQL(dialect: Dialect, ctx: SqlContext): SqlText;
|
|
2696
2754
|
/** Serialize back to its JSON ExprDef. */
|
|
2697
2755
|
toJSON(): ParamExprDef;
|
|
2698
2756
|
/** Deep-copy this expr. */
|
|
@@ -2932,7 +2990,7 @@ declare class InExpr extends BoolExpr {
|
|
|
2932
2990
|
readonly not: boolean;
|
|
2933
2991
|
static readonly KIND: "in";
|
|
2934
2992
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
2935
|
-
static readonly INSTRUCTIONS: "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates.
|
|
2993
|
+
static readonly INSTRUCTIONS: "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. A COMPOSITE-key relation may NOT use the subquery form (`in.relation-composite`) \u2014 one projected field cannot match a multi-column key, so list its `{ pk }` values instead. Inside the SUBQUERY, cross a relation with a `relation` join and field-ref the joined alias: projecting the relation field-ref itself yields its IDENTITY OBJECT, not a scalar id, and is refused here (`compare.relation-vs-value`). To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
|
|
2936
2994
|
/**
|
|
2937
2995
|
* Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
|
|
2938
2996
|
* value LIST, and a single-field SUBQUERY that crosses a relation via a
|
|
@@ -3032,7 +3090,7 @@ declare class IsNullExpr extends BoolExpr {
|
|
|
3032
3090
|
readonly not: boolean;
|
|
3033
3091
|
static readonly KIND: "is-null";
|
|
3034
3092
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
3035
|
-
static readonly INSTRUCTIONS: "`value IS [NOT] NULL`.";
|
|
3093
|
+
static readonly INSTRUCTIONS: "`value IS [NOT] NULL`. On a BELONGS-TO relation field-ref it tests whether the relation is UNSET \u2014 the KEY COLUMNS, so it stays index-usable; a HAS-MANY there is refused (`ref.relation-has-many`) \u2014 use `[NOT] EXISTS` over the related rows instead.";
|
|
3036
3094
|
readonly kind: "is-null";
|
|
3037
3095
|
/** Wrap `value IS [NOT] NULL` as a null test. */
|
|
3038
3096
|
constructor(value: Expr, not: boolean);
|
|
@@ -3249,7 +3307,7 @@ declare class AggregateExpr extends Expr {
|
|
|
3249
3307
|
readonly distinct: boolean;
|
|
3250
3308
|
static readonly KIND: "aggregate";
|
|
3251
3309
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
3252
|
-
static readonly INSTRUCTIONS: "An aggregate function over a group (`count(*)` = empty args); optional `distinct`.";
|
|
3310
|
+
static readonly INSTRUCTIONS: "An aggregate function over a group (`count(*)` = empty args); optional `distinct`. A RELATION field-ref is NOT aggregable (`ref.relation-aggregate`) \u2014 its value is an IDENTITY: group by it, or aggregate a scalar off a `relation`-joined alias.";
|
|
3253
3311
|
readonly kind: "aggregate";
|
|
3254
3312
|
/** Wrap a registered aggregate `fn` with its named `args` and a DISTINCT flag. */
|
|
3255
3313
|
constructor(fn: string,
|
|
@@ -3692,7 +3750,7 @@ declare class TextSearchExpr extends BoolExpr {
|
|
|
3692
3750
|
readonly query: TextSearchQuery;
|
|
3693
3751
|
static readonly KIND: "text-search";
|
|
3694
3752
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
3695
|
-
static readonly INSTRUCTIONS: "Full-text predicate over a source (optionally one field) \u2192 boolean.";
|
|
3753
|
+
static readonly INSTRUCTIONS: "Full-text predicate over a source (optionally one field) \u2192 boolean. NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source search is REFUSED (`text-search.unbacked`) rather than guessing a column.";
|
|
3696
3754
|
readonly kind: "text-search";
|
|
3697
3755
|
/** Wrap the bound `source` (optional `field`) and the search query text. */
|
|
3698
3756
|
constructor(source: string, field: string | undefined, query: TextSearchQuery);
|
|
@@ -3748,7 +3806,7 @@ declare class TextScoreExpr extends Expr {
|
|
|
3748
3806
|
readonly query: TextSearchQuery;
|
|
3749
3807
|
static readonly KIND: "text-score";
|
|
3750
3808
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
3751
|
-
static readonly INSTRUCTIONS: "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`).";
|
|
3809
|
+
static readonly INSTRUCTIONS: "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`). NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source score is REFUSED (`text-score.unbacked`) rather than guessing a column.";
|
|
3752
3810
|
readonly kind: "text-score";
|
|
3753
3811
|
/** Wrap the bound `source` (optional `field`) and the query text to rank against. */
|
|
3754
3812
|
constructor(source: string, field: string | undefined, query: TextSearchQuery);
|
|
@@ -4313,12 +4371,19 @@ declare class JoinCtePlanner {
|
|
|
4313
4371
|
/** A value that may be bound as a SQL parameter. */
|
|
4314
4372
|
type SqlValue = string | number | boolean | null;
|
|
4315
4373
|
/**
|
|
4316
|
-
* A supplied param value:
|
|
4317
|
-
*
|
|
4318
|
-
*
|
|
4319
|
-
*
|
|
4374
|
+
* A supplied param value:
|
|
4375
|
+
* - a bindable SCALAR, bound directly;
|
|
4376
|
+
* - a RELATION KEY object (`{ pk }`, keyed by the target's PK field names) on
|
|
4377
|
+
* the RHS of a relation comparison (`assignedUser = { id: 5 }`), which the
|
|
4378
|
+
* comparison decomposes into per-column binds;
|
|
4379
|
+
* - or a whole JSON DOCUMENT for a `json` / `array` cell, bound as ONE
|
|
4380
|
+
* parameter through `Dialect.jsonValue` (0.6.1's A9 — such a value used to
|
|
4381
|
+
* bind SQL `NULL`, so the write succeeded and the data was dropped).
|
|
4382
|
+
*
|
|
4383
|
+
* `JsonValue` subsumes the relation-key object; the three cases are spelled out
|
|
4384
|
+
* because they are read very differently at the point of use.
|
|
4320
4385
|
*/
|
|
4321
|
-
type SqlParamValue =
|
|
4386
|
+
type SqlParamValue = JsonValue;
|
|
4322
4387
|
/** A rendered SQL string plus its ordered bind parameters. */
|
|
4323
4388
|
interface RenderedSql {
|
|
4324
4389
|
/** The flat SQL string with dialect-numbered placeholders. */
|
|
@@ -9347,6 +9412,27 @@ declare class PostgresDialect extends BaseDialect {
|
|
|
9347
9412
|
key: string;
|
|
9348
9413
|
value: SqlText;
|
|
9349
9414
|
}[]): SqlText;
|
|
9415
|
+
/** Postgres stores JSON as `jsonb` (it has the equality / ordering operators `json` lacks). */
|
|
9416
|
+
jsonSqlType(): string;
|
|
9417
|
+
/**
|
|
9418
|
+
* Bind a JSON DOCUMENT — with the one Postgres wrinkle that makes the base
|
|
9419
|
+
* implementation wrong here: a NATIVE array column (`text[]`, `integer[]`, …)
|
|
9420
|
+
* does NOT accept JSON text. `CAST('["a","b"]' AS text[])` is a syntax error,
|
|
9421
|
+
* because a Postgres array literal is `{a,b}`.
|
|
9422
|
+
*
|
|
9423
|
+
* So a document destined for a native array is CONSTRUCTED instead —
|
|
9424
|
+
* `ARRAY[$1, $2]::text[]` — with each element bound in its own slot. That
|
|
9425
|
+
* reuses the element-binding pattern the array containment operators already
|
|
9426
|
+
* use, needs no array-literal encoder (whose quoting / escaping / NULL rules
|
|
9427
|
+
* would be their own defect surface), and handles the empty array
|
|
9428
|
+
* (`ARRAY[]::text[]`, which Postgres accepts precisely because the cast names
|
|
9429
|
+
* the type). Elements recurse, so a `jsonb[]` column takes documents.
|
|
9430
|
+
*
|
|
9431
|
+
* Everything else — a `json` / `jsonb` column, a heterogeneous array (which
|
|
9432
|
+
* `sqlTypeFor` already stores as `jsonb`), or a bare document with no declared
|
|
9433
|
+
* target — casts the JSON text to `jsonb`.
|
|
9434
|
+
*/
|
|
9435
|
+
jsonValue(value: JsonValue, fieldType?: FieldType): SqlText;
|
|
9350
9436
|
/** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
|
|
9351
9437
|
queryVectorParam(param: SqlText): SqlText;
|
|
9352
9438
|
/**
|
|
@@ -9875,7 +9961,7 @@ declare function describeEngine(engine: QueryEngine | Registry, options?: Descri
|
|
|
9875
9961
|
* so every Type / Field surfaces a human- / LLM-facing doc even when the dev
|
|
9876
9962
|
* authored none. Values are derived from what the meta-model already knows — a
|
|
9877
9963
|
* Field from its `FieldType` (kind, bounds, `sensitive` / `semantic` / `search`
|
|
9878
|
-
* flags, array item / bounds, a relation's `to` + `count`, nullability) and a
|
|
9964
|
+
* flags, array item / bounds, a relation's `to` + DIRECTION + `count`, nullability) and a
|
|
9879
9965
|
* Type from its name plus a field / relation / index summary.
|
|
9880
9966
|
*
|
|
9881
9967
|
* NOTHING here mutates the stored `TypeDef` / `FieldDef`: each string is
|
|
@@ -10026,4 +10112,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
|
|
|
10026
10112
|
*/
|
|
10027
10113
|
declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
|
|
10028
10114
|
|
|
10029
|
-
export { AID_REGISTRY, type Access, type AccessRun, type AccessSql, AggregateExpr, type AggregateExprDef, type AggregateRun, type AidInfo, type AidOptions, type AliasedSourceDef, type ArgExprDef, ArrayFieldType, type ArrayFieldTypeDef, type ArrayOp, ArrayOpExpr, type ArrayOpExprDef, type AutoPaginateOptions, BUILTIN_EXPRS, BUILTIN_FIELD_TYPES, BUILTIN_LIBRARY, BUILTIN_QUERIES, Backing, BaseDialect, BetweenExpr, type BetweenExprDef, BinaryExpr, type BinaryExprDef, type BinaryOp, BoolExpr, BoolFieldType, type BoolFieldTypeDef, type BuildQueryToolOptions, type BuildSchemasOptions, type BuiltinFunction, type CTEDef, type CTERecursiveDef, type CTEStatementDef, CTEStatementQuery, type CaseBranchDef, type CaseBranchSpec, CaseExpr, type CaseExprDef, Code, type CodeLine, type CodeOptions, ComparisonExpr, type ComparisonExprDef, type ComparisonOp, type ComputeRun, type ComputeSql, type Computed, type ComputedResolved, type Cost, type CostConstraints, DEFAULT_MAX_CTE_ITERATIONS, DEFAULT_MAX_EXAMPLES, DEFAULT_MAX_QUERY_SCHEMA_TYPES, DateFieldType, type DateFieldTypeDef, type DefaultCondition, type DefaultConditionOp, type DefaultOrder, type DefaultOrderDir, type DefaultOrderScope, type DefaultOrderTerm, type DeleteDef, DeleteQuery, type DescribeEngineOptions, type DescribeOverrides, Dialect, type DialectEntry, type DrillDownFailure, type DrillDownIntoSuccess, type DrillDownResult, type DrillDownSuccess, type DrillParam, EQ_SELECTIVITY, type Embedder, ExcludedExpr, type ExcludedExprDef, type ExecutorContext, ExistsExpr, type ExistsExprDef, Expr, type ExprClass, type ExprClassEntry, type ExprDef, type ExprKind, ExprQuery, type ExprQueryDef, Field, type FieldBacking, type FieldDef, type FieldExprRestriction, FieldRefExpr, type FieldRefExprDef, type FieldResolved, type FieldSpec, FieldType, type FieldTypeClass, type FieldTypeDef, type FieldTypeKind, type FieldValueDef, type FilterDepth, FiltersExpr, type FiltersExprDef, type FnDepth, type FormatOptions, type FormatProblemsOptions, FunctionCallExpr, type FunctionCallExprDef, type FunctionDef, type FunctionParamDef, type FunctionRun, type FunctionSelector, type FunctionShape, type FunctionSourceDef, IN_SELECTIVITY, InExpr, type InExprDef, Index, type IndexDef, IndexPart, type IndexPartDef, type InferOptions, type InsertDef, InsertQuery, type InsertRowDef, IsNullExpr, type IsNullExprDef, type JSONEntry, type JoinBacking, JoinCtePlanner, type JoinDef, type JoinHop, type JoinOnDef, type JoinRequest, type JoinRunPlan, type JoinSpec, type JoinSqlPlan, type JoinType, JsonFieldType, type JsonFieldTypeDef, type JsonValue, type LateralJoinSpec, LiteralExpr, type LiteralExprDef, LogicalExpr, type LogicalExprDef, type LogicalOp, type MaybePromise, type Meta, MoneyFieldType, type MoneyFieldTypeDef, type MoneyOptions, type NameDepth, type NamedArgs, type Node, NumberFieldType, type NumberFieldTypeDef, type NumberOptions, type OnConflictDef, type OrderDef, type OrderEntry, OutputRefExpr, type OutputRefExprDef, type ParamDef, ParamExpr, type ParamExprDef, ParamSet, PostgresDialect, type Problem, Problems, Query, type QueryClass, type QueryClassEntry, type QueryDef, QueryEngine, type QueryEngineOptions, type QueryField, QueryFunction, QueryJoin, type QueryKind, QueryOrder, type QueryResult, type QueryResultArray, type QuerySchemaOptions, type QuerySchemas, QueryScope, QuerySource, QueryToolError, type QueryToolInput, QueryTypeError, type QueryValidator, RANGE_SELECTIVITY, ROOT_VALIDATE_CONTEXT, type RefDepth, Registry, type RelationBacking, RelationFieldType, type RelationFieldTypeDef, type RelationJoinOnDef, type RelationJoinSpec, type RelationKey, type RelationKeyPair, type RelationOn, type RelationOnPair, type RelationResolved, type RenderedSql, type ResolvedSchemaDepth, type ResolvedType, type RlsProvider, RuntimeContext, type RuntimeJoin, type RuntimeOptions, SEMANTIC_ROW_PENALTY, type ScalarKind, type ScalarRun, type ScalarValue, type SchemaDepth, type SchemaOptions, type SearchBacking, type SelectDef, type SelectFieldDef, SelectQuery, type SelectTypesOptions, type SelectedFunctions, type SemanticBacking, type SemanticEmbeddings, SemanticExpr, type SemanticExprDef, type SemanticQueryDef, type SemanticTextToVector, type SetDef, type SetOperationDef, SetOperationQuery, type SortEntryDef, type SortSelectionDef, type SorterDef, SorterExpr, type SourceDef, type SourceFieldOptionalRef, type SourceFieldRef, type SourceFieldsRef, type SourceRecord, type SourceRow, type Span, type SpanMeta, SqlContext, SqlText, type SqlValue, SubqueryExpr, type SubqueryExprDef, type SubquerySourceDef, TEXT_SEARCH_ROW_PENALTY, TabularFunctionCallExpr, type TabularFunctionCallExprDef, type TabularRun, TextFieldType, type TextFieldTypeDef, type TextOptions, TextScoreExpr, type TextScoreExprDef, TextSearchExpr, type TextSearchExprDef, TimestampFieldType, type TimestampFieldTypeDef, type TimezonePolicy, type ToSqlOptions, Type, type TypeBacking, type TypeDef, type TypeExecutor, type TypeFieldRef, type TypeResolved, type TypeSourceDef, type TypeSpec, type TypeState, UnaryExpr, type UnaryExprDef, type UnaryOp, type UpdateDef, UpdateQuery, type ValidateContext, Value, type ValueCategory, type ValueSchemaOptions, WINDOW_ORDER_ARG, WindowExpr, type WindowExprDef, type WindowOrderSpec, type WindowRun, type WriteValueDef, ZERO_COST, add, addCost, age, agg, aidInfo, aliasedDigest, and, arrayAgg, arrayAppend, arrayConcat, arrayContains, arrayDistinct, arrayExecutor, arrayIndexOf, arrayPrepend, arrayRemove, arraySlice, arrayToString, asFieldType, autoPaginate, avg, between, boolAnd, boolOr, buildQueryTool, buildSchemas, builtinDialects, bytesOfResolved, canonicalize, caseExpr, cloneRecord, code, concat, contains, containsAll, containsAny, count, countIf, countStar, createRegistry, currentTime, currentTimestamp, dateAdd, dateDiff, dateFormat, datePart, dateTrunc, day, dayOfWeek, dayOfYear, defaultConditionOps, defaultConditionWithout, depthInstructions, describeDialects, describeEngine, describeExprs, describeFunctions, describeInput, describeQueryExamples, describeType, describeTypes, didYouMean, directedMessage, div, drillDown, drillDownInto, e, editDistance, embeddingResolver, epoch, eq, excluded, exists, exprDefSchema, exprDigest, fieldMeta, fieldNameOf, fieldTypeDefSchema, filters, firstField, fn, fromEpoch, generatedFieldDescription, generatedFieldLabel, generatedTypeDescription, generatedTypeLabel, gt, gte, hour, humanize, ilike, inList, inSubquery, inferType, isEmpty, isNull, isScalar, isScalarValue, isType, isVectorText, join, joinAlias, joinCode, joinLines, jsonValueSchema, like, lit, lt, lte, makeDate, makeField, makeResult, max, maxCost, mergeRows, min, minute, mod, month, mul, nearest, nearestKind, neg, neq, not, notBetween, notEmpty, notExists, notInList, notInSubquery, notLike, notNull, or, output, param, parseQueryRequest, parseQueryTool, parseVectorText, plain, pos, querySchema, raw, recordKey, recordSignature, ref, relJoin, relationKeyColumns, relationOf, renameSource, reportCostProblems, resolveAccessRun, resolveAccessSql, resolveComputeRun, resolveComputeSql, resolveDefaultConditionRun, resolveDefaultConditionSql, resolveFields, resolveJoinRun, resolveJoinSql, resolveSchemaDepth, rlsPredicate, rowsCost, runAggregateFunction, runScalarFunction, runTabularFunction, runWindowFunction, scaleRows, second, selectFunctions, selectTypes, semantic, shouldUseStringSchema, singleRow, sortEntries, sourcesOf, span, stddev, stringAgg, stringToArray, sub, subquery, suggestionBudget, sum, syntheticType, tableFn, textScore, textSearch, timezoneSchema, toArrayRows, toVectorText, typeFromFields, typeMeta, value, valueFieldType, variance, week, when, widenNullable, window, withAid, year };
|
|
10115
|
+
export { AID_REGISTRY, type Access, type AccessRun, type AccessSql, AggregateExpr, type AggregateExprDef, type AggregateRun, type AidInfo, type AidOptions, type AliasedSourceDef, type ArgExprDef, ArrayFieldType, type ArrayFieldTypeDef, type ArrayOp, ArrayOpExpr, type ArrayOpExprDef, type AutoPaginateOptions, BUILTIN_EXPRS, BUILTIN_FIELD_TYPES, BUILTIN_LIBRARY, BUILTIN_QUERIES, Backing, BaseDialect, BetweenExpr, type BetweenExprDef, BinaryExpr, type BinaryExprDef, type BinaryOp, BoolExpr, BoolFieldType, type BoolFieldTypeDef, type BuildQueryToolOptions, type BuildSchemasOptions, type BuiltinFunction, type CTEDef, type CTERecursiveDef, type CTEStatementDef, CTEStatementQuery, type CaseBranchDef, type CaseBranchSpec, CaseExpr, type CaseExprDef, Code, type CodeLine, type CodeOptions, ComparisonExpr, type ComparisonExprDef, type ComparisonOp, type ComputeRun, type ComputeSql, type Computed, type ComputedResolved, type Cost, type CostConstraints, DEFAULT_MAX_CTE_ITERATIONS, DEFAULT_MAX_EXAMPLES, DEFAULT_MAX_QUERY_SCHEMA_TYPES, DateFieldType, type DateFieldTypeDef, type DefaultCondition, type DefaultConditionOp, type DefaultOrder, type DefaultOrderDir, type DefaultOrderScope, type DefaultOrderTerm, type DeleteDef, DeleteQuery, type DescribeEngineOptions, type DescribeOverrides, Dialect, type DialectEntry, type DrillDownFailure, type DrillDownIntoSuccess, type DrillDownResult, type DrillDownSuccess, type DrillParam, type DrillValue, EQ_SELECTIVITY, type Embedder, ExcludedExpr, type ExcludedExprDef, type ExecutorContext, ExistsExpr, type ExistsExprDef, Expr, type ExprClass, type ExprClassEntry, type ExprDef, type ExprKind, ExprQuery, type ExprQueryDef, Field, type FieldBacking, type FieldDef, type FieldExprRestriction, FieldRefExpr, type FieldRefExprDef, type FieldResolved, type FieldSpec, FieldType, type FieldTypeClass, type FieldTypeDef, type FieldTypeKind, type FieldValueDef, type FilterDepth, FiltersExpr, type FiltersExprDef, type FnDepth, type FormatOptions, type FormatProblemsOptions, FunctionCallExpr, type FunctionCallExprDef, type FunctionDef, type FunctionParamDef, type FunctionRun, type FunctionSelector, type FunctionShape, type FunctionSourceDef, IN_SELECTIVITY, InExpr, type InExprDef, Index, type IndexDef, IndexPart, type IndexPartDef, type InferOptions, type InsertDef, InsertQuery, type InsertRowDef, IsNullExpr, type IsNullExprDef, type JSONEntry, type JoinBacking, JoinCtePlanner, type JoinDef, type JoinHop, type JoinOnDef, type JoinRequest, type JoinRunPlan, type JoinSpec, type JoinSqlPlan, type JoinType, JsonFieldType, type JsonFieldTypeDef, type JsonValue, type LateralJoinSpec, LiteralExpr, type LiteralExprDef, LogicalExpr, type LogicalExprDef, type LogicalOp, type MaybePromise, type Meta, MoneyFieldType, type MoneyFieldTypeDef, type MoneyOptions, type NameDepth, type NamedArgs, type Node, NumberFieldType, type NumberFieldTypeDef, type NumberOptions, type OnConflictDef, type OrderDef, type OrderEntry, OutputRefExpr, type OutputRefExprDef, type ParamDef, ParamExpr, type ParamExprDef, ParamSet, PostgresDialect, type Problem, Problems, Query, type QueryClass, type QueryClassEntry, type QueryDef, QueryEngine, type QueryEngineOptions, type QueryField, QueryFunction, QueryJoin, type QueryKind, QueryOrder, type QueryResult, type QueryResultArray, type QuerySchemaOptions, type QuerySchemas, QueryScope, QuerySource, QueryToolError, type QueryToolInput, QueryTypeError, type QueryValidator, RANGE_SELECTIVITY, ROOT_VALIDATE_CONTEXT, type RefDepth, Registry, type RelationBacking, RelationFieldType, type RelationFieldTypeDef, type RelationJoinOnDef, type RelationJoinSpec, type RelationKey, type RelationKeyPair, type RelationOn, type RelationOnPair, type RelationResolved, type RenderedSql, type ResolvedSchemaDepth, type ResolvedType, type RlsProvider, RuntimeContext, type RuntimeJoin, type RuntimeOptions, SEMANTIC_ROW_PENALTY, type ScalarKind, type ScalarRun, type ScalarValue, type SchemaDepth, type SchemaOptions, type SearchBacking, type SelectDef, type SelectFieldDef, SelectQuery, type SelectTypesOptions, type SelectedFunctions, type SemanticBacking, type SemanticEmbeddings, SemanticExpr, type SemanticExprDef, type SemanticQueryDef, type SemanticTextToVector, type SetDef, type SetOperationDef, SetOperationQuery, type SortEntryDef, type SortSelectionDef, type SorterDef, SorterExpr, type SourceDef, type SourceFieldOptionalRef, type SourceFieldRef, type SourceFieldsRef, type SourceRecord, type SourceRow, type Span, type SpanMeta, SqlContext, type SqlParamValue, SqlText, type SqlValue, SubqueryExpr, type SubqueryExprDef, type SubquerySourceDef, TEXT_SEARCH_ROW_PENALTY, TabularFunctionCallExpr, type TabularFunctionCallExprDef, type TabularRun, TextFieldType, type TextFieldTypeDef, type TextOptions, TextScoreExpr, type TextScoreExprDef, TextSearchExpr, type TextSearchExprDef, TimestampFieldType, type TimestampFieldTypeDef, type TimezonePolicy, type ToSqlOptions, Type, type TypeBacking, type TypeDef, type TypeExecutor, type TypeFieldRef, type TypeResolved, type TypeSourceDef, type TypeSpec, type TypeState, UnaryExpr, type UnaryExprDef, type UnaryOp, type UpdateDef, UpdateQuery, type ValidateContext, Value, type ValueCategory, type ValueSchemaOptions, WINDOW_ORDER_ARG, WindowExpr, type WindowExprDef, type WindowOrderSpec, type WindowRun, type WriteValueDef, ZERO_COST, add, addCost, age, agg, aidInfo, aliasedDigest, and, arrayAgg, arrayAppend, arrayConcat, arrayContains, arrayDistinct, arrayExecutor, arrayIndexOf, arrayPrepend, arrayRemove, arraySlice, arrayToString, asFieldType, autoPaginate, avg, between, boolAnd, boolOr, buildQueryTool, buildSchemas, builtinDialects, bytesOfResolved, canonicalize, caseExpr, cloneRecord, code, concat, contains, containsAll, containsAny, count, countIf, countStar, createRegistry, currentTime, currentTimestamp, dateAdd, dateDiff, dateFormat, datePart, dateTrunc, day, dayOfWeek, dayOfYear, defaultConditionOps, defaultConditionWithout, depthInstructions, describeDialects, describeEngine, describeExprs, describeFunctions, describeInput, describeQueryExamples, describeType, describeTypes, didYouMean, directedMessage, div, drillDown, drillDownInto, e, editDistance, embeddingResolver, epoch, eq, excluded, exists, exprDefSchema, exprDigest, fieldMeta, fieldNameOf, fieldTypeDefSchema, filters, firstField, fn, fromEpoch, generatedFieldDescription, generatedFieldLabel, generatedTypeDescription, generatedTypeLabel, gt, gte, hour, humanize, ilike, inList, inSubquery, inferType, isEmpty, isNull, isScalar, isScalarValue, isType, isVectorText, join, joinAlias, joinCode, joinLines, jsonValueSchema, like, lit, lt, lte, makeDate, makeField, makeResult, max, maxCost, mergeRows, min, minute, mod, month, mul, nearest, nearestKind, neg, neq, not, notBetween, notEmpty, notExists, notInList, notInSubquery, notLike, notNull, or, output, param, parseQueryRequest, parseQueryTool, parseVectorText, plain, pos, querySchema, raw, recordKey, recordSignature, ref, relJoin, relationKeyColumns, relationOf, renameSource, reportCostProblems, resolveAccessRun, resolveAccessSql, resolveComputeRun, resolveComputeSql, resolveDefaultConditionRun, resolveDefaultConditionSql, resolveFields, resolveJoinRun, resolveJoinSql, resolveSchemaDepth, rlsPredicate, rowsCost, runAggregateFunction, runScalarFunction, runTabularFunction, runWindowFunction, scaleRows, second, selectFunctions, selectTypes, semantic, shouldUseStringSchema, singleRow, sortEntries, sourcesOf, span, stddev, stringAgg, stringToArray, sub, subquery, suggestionBudget, sum, syntheticType, tableFn, textScore, textSearch, timezoneSchema, toArrayRows, toVectorText, typeFromFields, typeMeta, value, valueFieldType, variance, week, when, widenNullable, window, withAid, year };
|