@aeye/query 0.6.7 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1332 +1,1332 @@
1
- # @aeye/query
2
-
3
- An **LLM-friendly relational query language**, in-memory runtime, and SQL
4
- converter. You define *Types* (type-like entities) with *Fields*; from that an
5
- LLM (or a developer) can build a **typed, validated, runnable** query — a
6
- `select` / `insert` / `update` / `delete` / set-operation / CTE / single
7
- expression. A built query resolves to an output type, has typed bind params,
8
- can be cost-bounded, run in-memory, converted to SQL (base + Postgres),
9
- auto-paginated, and **drilled down** (aggregate un-ravelling).
10
-
11
- It is fully standalone (only depends on `zod`) and obsessively type-safe: no
12
- `any`, no `unknown` in public APIs, no casts; every polymorphic node is a
13
- discriminated union so handling is exhaustively checkable.
14
-
15
- ```bash
16
- npm install # from the monorepo root (workspace)
17
- npm run typecheck # tsc --noEmit
18
- npm test # vitest
19
- npm run examples # runnable, end-to-end tour (examples/)
20
- ```
21
-
22
- ## The type / field model
23
-
24
- A `Type` is a named collection of `Field`s plus index + cardinality estimates.
25
- Each field has a `FieldType` (one of `number`, `text`, `money`, `bool`,
26
- `relation`, `date`, `timestamp`, `json`, `array`); nullability lives on the
27
- *field*, not the field type.
28
-
29
- An `array` field is an ordered collection. It carries optional `minItems` /
30
- `maxItems` element-count bounds and an optional `item` element field type
31
- (omit `item` for heterogeneous / unknown elements). Because `item` is itself a
32
- field type, arrays nest (`array<array<number>>`). `inferType` detects arrays
33
- from sampled rows and infers the element type from homogeneous scalars.
34
-
35
- ```ts
36
- // array of text tags, 0–8 items
37
- { name: 'tags', type: { kind: 'array', item: { kind: 'text' }, maxItems: 8 }, nullable: true }
38
- ```
39
-
40
- Relations carry a target Type and a cardinality `count`: a relation field's
41
- **name is the join key** for all purposes — `count === 1` is belongs-to (the FK
42
- lives on this type), `count > 1` is has-many. There are no explicit FK fields.
43
- A belongs-to relation may set `inverseRelation` to have its target Type
44
- automatically gain the matching has-many field pointing back. The join key on
45
- either side resolves through each Type's *identity field* (the field of its
46
- first unique single-field index, else the field named `id`).
47
-
48
- A relation field can be **compared directly to a value** in `= <> in notIn`,
49
- where the value is an object keyed by the target's **primary key** (single or
50
- composite) — `{ kind: 'comparison', op: '=', left: relRef, right: { kind:
51
- 'param', name: 'u' } }` with `:u = { id: 5 }` (a single-key relation also
52
- accepts a bare scalar). A **belongs-to** matches its FK columns; a **has-many**
53
- matches by **membership** — `= value` is a correlated `EXISTS` testing that the
54
- value's key is in the related set (`<>` / `notIn` → `NOT EXISTS`). Two relations
55
- of the same target compare by their FK key (`order.customer = invoice.customer`);
56
- a has-many may not be compared to another relation. Ordering / LIKE on a relation
57
- is rejected — a relation compares by identity, not order.
58
-
59
- Indexes are **composite**: an ordered list of parts, each with a prefix
60
- distinct-row `count` (non-increasing); the index is unique iff its last part's
61
- `count === 1`. Text matching is governed by a text field's `casing`, else the engine's
62
- `textCasing` default (`'fold'` unless you set it):
63
-
64
- | `casing` | means | SQL for `a = b` | in-memory runtime |
65
- |--------------|------------------------------------------------|-----------------------|-------------------|
66
- | `'fold'` | case-INSENSITIVE, folded by the query | `LOWER(a) = LOWER(b)` | folds |
67
- | `'collated'` | case-INSENSITIVE, folded by the COLUMN's collation | `a = b` | folds |
68
- | `'exact'` | case-SENSITIVE | `a = b` | compares as-is |
69
-
70
- `LOWER(col)` is not sargable, so `'fold'` costs every predicate over the column
71
- its index — and on Postgres a column modelled as `text` may physically be a
72
- `uuid`, where `LOWER()` does not exist at all. So set `textCasing: 'exact'` on
73
- the engine for a schema of identifiers / codes / enums (`'collated'` when the
74
- columns really do carry a case-insensitive collation, e.g. `citext`), and let
75
- the individual columns that DO want folding say `casing: 'fold'` — a field's own
76
- declaration always wins over the engine default. A Type may also be
77
- flagged `semantic` / `search` to make it eligible for embedding similarity /
78
- full-text search even when no individual field is flagged.
79
-
80
- ```ts
81
- import { createRegistry, QueryEngine, arrayExecutor, type TypeDef } from '@aeye/query';
82
-
83
- const userDef: TypeDef = {
84
- name: 'user',
85
- fields: [
86
- { name: 'id', type: { kind: 'number', whole: true } },
87
- { name: 'name', type: { kind: 'text' } },
88
- { name: 'age', type: { kind: 'number', whole: true }, nullable: true },
89
- ],
90
- // unique single-field index on `id` ⇒ `id` is the identity / join key.
91
- indexes: [{ exprs: [{ expr: { kind: 'field-ref', source: 'user', field: 'id' }, count: 1 }] }],
92
- count: 1000,
93
- bytes: 64,
94
- };
95
-
96
- const orderDef: TypeDef = {
97
- name: 'order',
98
- fields: [
99
- { name: 'id', type: { kind: 'number', whole: true } },
100
- // belongs-to user; materializes `user.orders` (has-many) pointing back.
101
- { name: 'userId', type: { kind: 'relation', to: 'user', count: 1, inverseRelation: 'orders' } },
102
- ],
103
- indexes: [{ exprs: [{ expr: { kind: 'field-ref', source: 'order', field: 'id' }, count: 1 }] }],
104
- count: 5000,
105
- bytes: 48,
106
- };
107
-
108
- const registry = createRegistry();
109
- const user = registry.parseType(userDef);
110
- const order = registry.parseType(orderDef);
111
- registry.registerType(user);
112
- registry.registerType(order);
113
-
114
- const engine = new QueryEngine(registry, {
115
- executors: { user: arrayExecutor(userRows) }, // wire data for in-memory runs
116
- textCasing: 'exact', // default case policy for text columns that declare none
117
- });
118
- ```
119
-
120
- You can also **infer** a `TypeDef` straight from raw JSON rows:
121
-
122
- ```ts
123
- import { inferType } from '@aeye/query';
124
- const def = inferType('user', userRows); // field types + nullability inferred
125
- ```
126
-
127
- ## Build, validate, and run a query
128
-
129
- A query is plain JSON (a `QueryDef`). Validate it to get LLM-friendly
130
- `Problems`, then run it in-memory.
131
-
132
- ```ts
133
- const select = {
134
- kind: 'select',
135
- fields: [{ expr: { kind: 'field-ref', source: 'user', field: 'name' } }],
136
- from: { kind: 'type', type: 'user' },
137
- where: [{
138
- kind: 'comparison', op: '>',
139
- left: { kind: 'field-ref', source: 'user', field: 'age' },
140
- right: { kind: 'literal', value: 30 },
141
- }],
142
- } as const;
143
-
144
- const problems = engine.validateQuery(select); // structure + params + per-Type hooks
145
- if (!problems.hasErrors) {
146
- const result = await engine.run(select); // { rows, fields, outputType }
147
- }
148
- ```
149
-
150
- ### Building expressions with `e.*`
151
-
152
- Hand-writing the raw `ExprDef` JSON above gets verbose fast. The **`e.*`
153
- builder** composes the same trees with terse, fully-typed function calls — and
154
- each `e.*` returns a **real `Expr` instance** (the exact subclass), so it is
155
- strictly more capable than a def factory:
156
-
157
- ```ts
158
- import { e } from '@aeye/query';
159
-
160
- // e.eq(...) is a ComparisonExpr, e.and(...) a LogicalExpr, e.ref(...) a FieldRefExpr, …
161
- const cond = e.and(
162
- e.eq(e.ref('task', 'done'), e.value(true)),
163
- e.gt(e.ref('task', 'hours'), e.value(0)),
164
- );
165
- ```
166
-
167
- There is **one builder per expression kind**, grouped as: leaves (`value`/`lit`,
168
- `param`, `ref`, `path`, `output`, `excluded`, `filters`), arithmetic
169
- (`add`/`sub`/`mul`/`div`/`mod`, `neg`/`pos`), comparison
170
- (`eq`/`neq`/`lt`/`lte`/`gt`/`gte`/`like`/`notLike`/`ilike`), logical
171
- (`and`/`or`/`not`), predicates (`isNull`/`notNull`, `between`/`notBetween`,
172
- `inList`/`notInList`, `inSubquery`/`notInSubquery`, `exists`/`notExists`), array
173
- ops (`contains`/`containsAny`/`containsAll`/`isEmpty`/`notEmpty`), `case`/`when`,
174
- calls (`fn`, `agg`/`count`/`countStar`/`sum`/`avg`/`min`/`max`, `window`,
175
- `tableFn`), `subquery`, and search (`textSearch`, `semantic`). Every function is
176
- also a named export (`import { eq, and, ref } from '@aeye/query'`).
177
-
178
- **Run or emit a built expr standalone** — the engine normalizes either an `Expr`
179
- or a raw `ExprDef`:
180
-
181
- ```ts
182
- // Evaluate against a row (defaults to an empty row for constant predicates):
183
- const v = await engine.evaluateExpr(e.gt(e.ref('task', 'hours'), e.value(0)), {
184
- task: { hours: 5 },
185
- }); // Value(true)
186
-
187
- // Emit SQL + ordered bind params for a dialect (params never interpolated):
188
- const { sql, params } = engine.exprToSQL(cond, 'postgres');
189
- // sql: ("task"."done" = $1 AND "task"."hours" > $2)
190
- // params: [true, 0]
191
- ```
192
-
193
- **Embed a built expr into a query** via `.toJSON()` — a query def's `where` /
194
- `order` / field slots are `ExprDef`, and `.toJSON()` is the free wire form:
195
-
196
- ```ts
197
- const select = {
198
- kind: 'select',
199
- fields: [{ expr: e.ref('user', 'name').toJSON() }],
200
- from: { kind: 'type', type: 'user' },
201
- where: [e.gt(e.ref('user', 'age'), e.value(30)).toJSON()],
202
- } as const;
203
- ```
204
-
205
- `registry.parseExpr` is a **pass-through** for an already-built `Expr`, so built
206
- and parsed exprs compose freely.
207
-
208
- ### Sources & aliasing
209
-
210
- Every source is referenced by its **type name** — there is no alias to invent or
211
- keep in sync:
212
-
213
- - **FROM.** `from: { kind: 'type', type: 'user' }` binds under `source: 'user'`.
214
- - **Joins.** A join crosses a **single relation field** — `on` is a
215
- `{ kind: 'relation', source, field, as }` ref
216
- (`{ on: { kind: 'relation', source: 'user', field: 'orders', as: 'order' } }`):
217
- the bound source to join FROM, its relation field, and the **required alias**
218
- the joined rows bind under (field-refs into them then use `source: 'order'`).
219
- **Multi-hop** joins are expressed as **chained** single-hop joins, and reading a
220
- value across a relation is a join + a plain `{ source, field }` field-ref (there
221
- is no separate relation-path expr). The relation key is synthesized — you never
222
- write ON. A join can also add a **fresh source** — `on` may instead be a
223
- `type` / `aliased` / `subquery` / `function` source, with `and` as its ON (a
224
- manual join). `joinType` (freeing `type` for the Type-name rule) defaults to
225
- `left`.
226
- - **DML.** `update` / `delete` / `insert` target a type by name (`type` / `from`
227
- / `into`) and bind it under that name — DML targets take no alias.
228
-
229
- When you need a distinct binding — a **self-join**, or **two instances of the
230
- same Type** — reach for the `aliased` escape hatch on a FROM source
231
- (`{ kind: 'aliased', type: 'user', as: 'u1' }`) or set `as` on a join to override
232
- the bound name of its hop (`{ on: { source: 'u1', field: 'orders' }, as: 'o1' }`).
233
- The `as` on a join is the **collision-breaker**.
234
-
235
- > **The `type` vs `source` rule.** `type` is used only where the value MUST be a
236
- > registered Type name (FROM `type`, DML `into` / `type` / `from`, relation `to`,
237
- > a semantic query's `{ type, field }`); `source` is a **bound** name in the
238
- > query's scope (a Type name, a join alias, a CTE, an aliased source) — used by
239
- > `field-ref`, `semantic` / `text-search` / `filters`, and a join's `on.source`.
240
-
241
- If two sources end up bound under the same name — two joins landing on one target
242
- type, or a join hop rebinding the FROM / DML target type — the engine reports a
243
- `source.duplicate` validation error pointing you at the `aliased` form (or a join
244
- `as`) to disambiguate.
245
-
246
- > **Known limitation.** A self-referential DML that would need two instances of
247
- > its target type (e.g. an `UPDATE user` joined back to `user` via its relations,
248
- > whose hop rebinds `user`) currently errors with `source.duplicate`; an
249
- > aliased-DML target mechanism is a deferred follow-up.
250
-
251
- ### Output references (`groupBy` / `orderBy` / `having`)
252
-
253
- A SELECT's `groupBy`, `order`, and `having` can reference a **projected output
254
- field by name** instead of repeating its expression — via
255
- `{ kind: 'output', name }`. The `name` is the output's `as`, or its natural
256
- derived name (a field-ref's field, an aggregate's function name). The reference **EXPANDS to** (delegates to) the
257
- referenced select item's expression: the SQL emits the target's SQL (portable
258
- across dialects, in every clause), and the runtime re-evaluates the target — so
259
- a group key re-computes over the source row while an ORDER BY / HAVING ref
260
- re-computes over the group (including an aggregate target). This keeps queries
261
- smaller and removes a whole class of GROUP BY / ORDER BY mismatches.
262
-
263
- ```ts
264
- // Revenue per user, grouped + ordered by output name — the `sum` / `userId`
265
- // expressions are written ONCE, in `fields`.
266
- const revenuePerUser = {
267
- kind: 'select',
268
- fields: [
269
- { expr: { kind: 'field-ref', source: 'order', field: 'userId' }, as: 'userId' },
270
- { expr: { kind: 'aggregate', function: 'sum', args: { value: { kind: 'field-ref', source: 'order', field: 'total' } } }, as: 'revenue' },
271
- ],
272
- from: { kind: 'type', type: 'order' },
273
- groupBy: [{ kind: 'output', name: 'userId' }], // ← by output name, not the expr
274
- having: [{ kind: 'comparison', op: '>', left: { kind: 'output', name: 'revenue' }, right: { kind: 'literal', value: 100 } }],
275
- order: [{ expr: { kind: 'output', name: 'revenue' }, dir: 'desc' }],
276
- } as const;
277
- ```
278
-
279
- It is valid **only** in those three clause positions — in WHERE, a join `on`, or
280
- any general expression argument (where no outputs are bound) it fails validation
281
- with `output.not-available`. An unknown name reports `output.unknown`, and using
282
- one as a GROUP BY key whose target is an aggregate reports `output.aggregate`
283
- (you cannot group BY an aggregate). The LLM schema offers `output` in exactly
284
- those `groupBy` / `orderBy` / `having` positions and nowhere else. `drillDown`
285
- expands any `output` references against the original projection before it
286
- un-ravels the aggregates, so a drilled query never dangles.
287
-
288
- ## Write model & permissions
289
-
290
- Types and fields declare **what write operations are possible**, and that flows
291
- into BOTH validation AND the LLM-facing schema — so the generated schema never
292
- offers a write the engine would reject.
293
-
294
- - **Type permissions.** `insertable` / `updatable` / `deletable` on a `TypeDef`
295
- (each default **true**). A restricted Type is rejected by validation
296
- (`insert.type-readonly` / `update.type-readonly` / `delete.type-readonly`), the
297
- schema **drops the DML kind** when no Type permits it, and each DML's
298
- target-name enum is filtered (`into` → insertable, `update.type` → updatable,
299
- `delete.from` → deletable).
300
- - **Field permissions.** `insertable` / `updatable` on a `FieldDef` (default
301
- **true**). A **computed** field (`FieldBacking.compute`) defaults to
302
- `insertable:false, updatable:false` (override with an explicit flag).
303
- Validation rejects a listed non-insertable field (`insert.field-readonly`) / an
304
- assigned non-updatable field (`update.field-readonly`); the paired schema
305
- offers only insertable `fields` / updatable `set` fields.
306
- - **Insert-requiredness (one rule).** A field is REQUIRED on insert iff it is
307
- **insertable AND non-nullable AND has no default AND is not computed** —
308
- otherwise optional or excluded. A shared `requiredOnInsert` helper drives both
309
- the schema (required-vs-optional in paired mode) and validation
310
- (`insert.missing-required`, listing the missing names).
311
- - **Defaults live on the backing.** `FieldBacking.default` is a `Value` or a
312
- factory `() => Value | Promise<Value>` — its presence alone makes the field
313
- optional-on-insert (no `hasDefault` flag). At **runtime** an omitted defaulted
314
- field is materialized (value evaluated / factory awaited, per row) into the
315
- record; in **SQL** the column is left out of the INSERT so the DB's own column
316
- `DEFAULT` fills it (a JS-factory default is runtime-only).
317
- - **Per-field expr restrictions.** `FieldDef.exprs` = `{ not: ExprKind[] }` or
318
- `{ only: ExprKind[] }` NARROWS which expr kinds may target the field (never
319
- enables one the field TYPE disallows). `field.allowsExpr(kind)` respects both.
320
- Validation reports `field.expr-denied` at the use site — a standalone
321
- `field-ref`, a gating operator's DIRECT field-ref operand (`comparison` /
322
- `between` / `in` / `is-null` / `array-op`), and the field-naming exprs
323
- (`text-search` / `text-score` / `semantic` / `filters`). The paired schema
324
- omits an excluded field from the relevant enum, and gates a kind away entirely
325
- when every candidate field excludes it.
326
-
327
- ```ts
328
- const doc: TypeDef = {
329
- name: 'doc', count: 1000, bytes: 256,
330
- fields: [
331
- { name: 'id', type: { kind: 'text' } }, // required on insert
332
- { name: 'title', type: { kind: 'text' } }, // required
333
- { name: 'views', type: { kind: 'number' }, updatable: false }, // write-once
334
- { name: 'notes', type: { kind: 'text' }, nullable: true }, // optional
335
- ],
336
- };
337
- // `createdAt` is optional-on-insert (has a default) and materialized at runtime.
338
- const backing: TypeBacking = {
339
- fields: { createdAt: { default: () => Value.of(new Date().toISOString()) } },
340
- };
341
- ```
342
-
343
- ## Execution model
344
-
345
- There is ONE execution contract: **run a query, optionally with param values
346
- and filters, and get back `{ rows, fields, total }`**.
347
-
348
- ```ts
349
- const result = await engine.run(query, { params, filters, includeTotal });
350
- // result.rows — the output rows (objects; pass { rows: 'array' } for arrays)
351
- // result.fields — resolved output fields (name + type + summary metadata)
352
- // result.total — pre-limit row count, when run with `includeTotal: true`
353
- ```
354
-
355
- Each field's `type` is the full `ResolvedType`. A **computed** one carries
356
- `aggregate` (does a group collapse happen anywhere in this expression?) and
357
- `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS
358
- one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'`
359
- under any alias; `max(a) - min(b)` reports `aggregate: true` with NO
360
- `aggregateFn` (it contains aggregates but is none); a window over an
361
- aggregate-shaped function reports neither. Read it rather than inferring the
362
- function from the output column NAME, which cannot see through an alias and
363
- mistakes `hours * 2 as count` for an aggregate.
364
-
365
- Everything composes around that one call:
366
-
367
- - **Params.** A `param` (`{ kind: 'param', name }`) infers its type from how it
368
- is used and is bound at run time via `options.params`. Introspect what a built
369
- query expects with `query.params(engine)` → `ParamDef[]` (name + inferred
370
- type).
371
-
372
- It reports every param the statement binds **at any depth**, so what it
373
- declares is always enough to bind the emitted SQL. That includes a
374
- `limit` / `offset` bound, which lives outside the walked expr tree: on the
375
- statement itself, on a **`cte`'s `final`** (where `autoPaginate` puts it), on a
376
- set-operation **arm** or its set-level bound, and inside a FROM / `in` /
377
- `exists` subquery or an `insert … select` source. An under-reported bound is
378
- not a cosmetic gap — the SQL still emits `LIMIT ?` and a caller that binds the
379
- declared signature leaves it NULL, which Postgres reads as *no limit*.
380
-
381
- A param's type is the **meet** of every use — the most specific type
382
- compatible with all of them, folded through `FieldType.meet`. Compared against
383
- an `enum` in one place and plain `text` in another it is the **enum**;
384
- `text{minLength:5}` beside `text{maxLength:10}` carries **both** bounds;
385
- `number` beside `money` is `money`. The meet is commutative, associative,
386
- idempotent and **sound** (it accepts nothing that both operands do not), so the
387
- answer never depends on where in the JSON each use sits. Where the uses have no
388
- meet the param is in **conflict** (`param.conflict`) and `params()` omits it.
389
-
390
- It is the *greatest* lower bound for every type built from a **def** —
391
- `x ⊓ ⊤ = x` holds for anything `parseType` / `parseFieldType` can produce. A
392
- closed set IS the value schema, so a meet narrows a merged set by the merged
393
- scalar constraints, and for a self-inconsistent type
394
- (`text{values:['ab'], minLength:5}`, whose own bound rejects its own member)
395
- even `x ⊓ text` narrows or conflicts. Since `0.6.6` that declaration is
396
- **refused at parse time** (`field-type.bad-values`) rather than tolerated, so
397
- the exception is gone from the def road. The public **constructors** do not
398
- validate — `new TextFieldType({ values: [{ value: 'ab' }], minLength: 5 })` is
399
- still buildable, and for one of those the meet is a lower bound only, exactly
400
- as an uncompilable `pattern` is still constructible by hand. Soundness is kept
401
- unconditionally on both roads, because it is the law a validator actually
402
- depends on.
403
-
404
- `engine.parameters(query)` → `ParamInfo[]` is the detailed view: per param,
405
- every `use` (`{ at, type, category, field? }` — path, required type, category
406
- summary, and the column the requirement came from), the merged `type`, and the
407
- `conflict` when there is none. `engine.checkParams(query, params)` →
408
- `Problems` checks SUPPLIED values against that merged type before execution
409
- (`param.value` / `param.missing` / `param.unknown`); `null` always passes, and
410
- the same check rides on `validateQuery(query, _, _, { params })`.
411
- - **Filters.** `options.filters` is a `Record<source, ExprDef | Expr | null>` —
412
- a single **boolean Expr** per source (or `null` / absent for none). The
413
- `filters` EXPR in the query is only a placeholder (`{ source, fields? }`); the
414
- predicate is supplied here, keyed by source, and the placeholder evaluates /
415
- emits it (vacuously `TRUE` when none is supplied). Introspect which sources a
416
- built query exposes — and the fields each offers — with
417
- `query.filters(engine)` → `Record<source, { fields: QueryField[] }>` (each
418
- field is name + resolved type + nullability + field-type kind, restricted to
419
- the placeholder's `fields` allowlist when it sets one). Build the per-source
420
- bool Expr however you like — e.g. a `comparison` / `logical` `ExprDef`, or one
421
- produced by your own filter-builder UI. `query.filterSources()` still lists the
422
- sources a filter may target; an unknown source or field is a `QueryTypeError`.
423
- - **Total count.** `includeTotal: true` is an **execution-time** option (NOT a
424
- `SelectDef` field): `run` captures the pre-limit count into `result.total`,
425
- and `toSQL(query, dialect, { includeTotal: true })` emits
426
- `COUNT(*) OVER () AS "$total"`.
427
-
428
- It applies to the **ENTRY query only** — never a CTE body, a set-operation
429
- arm, or a FROM subquery. `$total` is a PROJECTED column, so an arm that
430
- carried it would take part in the set comparison and change the **rows**:
431
- `UNION` would stop de-duplicating, and `INTERSECT` / `EXCEPT` would compare
432
- per-arm counts they were never meant to see. A query whose entry is a **set
433
- operation therefore reports no total at all** (`result.total` is `undefined`;
434
- the SQL carries no `$total`) rather than a wrong one — both engines agree.
435
- To page a set operation *and* count it, wrap it in a SELECT and count there:
436
-
437
- ```ts
438
- const counted = {
439
- kind: 'select',
440
- fields: [{ expr: { kind: 'field-ref', source: 's', field: 'id' } }],
441
- from: { kind: 'subquery', as: 's', query: theUnion },
442
- limit: 20,
443
- } satisfies SelectDef;
444
- await engine.run(counted, { includeTotal: true }); // → { rows, total }
445
- ```
446
- - **Pagination.** `autoPaginate` adds `limit` / `offset` as bind PARAMS, so
447
- pagination is just supplying their values:
448
-
449
- ```ts
450
- import { autoPaginate } from '@aeye/query';
451
- const paged = autoPaginate(select); // adds { limit: param('limit'), offset: param('offset') }
452
- paged.params(engine); // → [{ name:'limit', type:{kind:'number'} }, { name:'offset', … }]
453
- await engine.run(paged, { params: { limit: 10, offset: 0 } });
454
- ```
455
-
456
- It pages exactly the kinds that HAVE a row bound: a **`select`** (its own
457
- LIMIT / OFFSET), a **set operation** (`union` / `intersect` / `except` — the
458
- SET-LEVEL bound over the combined rows, never an arm's, since paging an arm
459
- would change which rows the set operation compares), and a **`cte`**, which is
460
- paged through its `final` query (a CTE body is an intermediate result). Every
461
- other kind — `insert` / `update` / `delete` / `expr` — has no bound to bind and
462
- **throws** `QueryTypeError` with code `paginate.unsupported-kind`. Ask first
463
- with `canAutoPaginate(query)` when you hold an arbitrary `QueryDef`.
464
-
465
- - **Drill-down.** `drillDownInto` rebuilds the underlying-rows query and extracts
466
- the drill PARAMS from a chosen aggregated row — then it is the same `run` call
467
- with those params (see [Drill-down](#drill-down)).
468
-
469
- `toSQL` accepts the same `params` and `filters` options and emits them
470
- identically, so emitted SQL matches what would run.
471
-
472
- ## SQL conversion
473
-
474
- The same query emits SQL for any registered dialect. The base dialect uses `?`
475
- placeholders; Postgres uses `$1`, `$2`, … . Relation joins synthesize their ON
476
- clause from the relation key — you never write it.
477
-
478
- ```ts
479
- const base = engine.toSQL(select, 'base'); // { sql, params }
480
- const pg = engine.toSQL(select, 'postgres', { params: { minTotal: 50 } });
481
- ```
482
-
483
- ## Type backing & Access / Computed
484
-
485
- The conceptual model the LLM sees — a `TypeDef`'s flat list of fields — can be
486
- **arbitrarily richer behind the scenes**. A `TypeBacking` is plain dev-side
487
- TypeScript you register *alongside* the Type (`registry.registerType(type,
488
- backing)`, or `new QueryEngine(registry, { backings })`); the JSON `TypeDef` /
489
- `FieldDef` are **never touched**, so the schema stays minimal. A backing can
490
- remap the real source table, compute fields, auto-join other Types, gate
491
- rows / fields, and point full-text / semantic search at hidden physical fields —
492
- all resolved IDENTICALLY in `engine.run` and `engine.toSQL`.
493
-
494
- Two primitives compose everything. Each offers a dual `expr` path plus per-mode
495
- overrides — **SQL** resolves `sql` then `expr`; the **runtime** resolves `run`
496
- then `expr`. Every factory (`expr` / `sql` / `run`) is handed the **`alias` the
497
- Type is bound under for this occurrence** and MUST use it for every reference
498
- (never hardcode the Type name) — so when a Type is aliased (multiple joins to the
499
- same Type, a self-join, an `{kind:'aliased'}` FROM) the references resolve to the
500
- correct source:
501
-
502
- - **`Access`** — a security *predicate*. It resolves to a predicate `Expr`
503
- (apply it), `true` (visible), `false` (denied), or `undefined` (no-op).
504
- - **`Computed`** — a field *value* producer (replaces the stored column). It
505
- always yields a value.
506
-
507
- ```ts
508
- const backing: TypeBacking = {
509
- name: 'projects', // real table ⇒ FROM "projects" AS "project"
510
- access: { /* RLS — see below */ },
511
- joins: { /* named hidden joins — see below */ },
512
- fields: { /* per-field compute / access / remap */ },
513
- };
514
- registry.registerType(project, backing); // the TypeDef the LLM sees is unchanged
515
- ```
516
-
517
- `examples/11-computed-fields.ts` is the end-to-end demo: one simple `project`
518
- Type backed by `projects` + `users` + `tasks`, run in-memory AND emitted to SQL.
519
-
520
- ## Computed fields
521
-
522
- A `FieldBacking.compute` supplies a field's value. The primary path is a dual
523
- `expr` (one `Expr` both emitted to SQL and evaluated in memory); `sql` / `run`
524
- override per mode. A bare `name` just remaps the stored column.
525
-
526
- ```ts
527
- fields: {
528
- // dual expr: the auto-joined owner's name (one definition, both modes). Read
529
- // the named join off the BOUND `alias` with `e.ref`, never a literal type name.
530
- ownerName: { joins: ['owner'], compute: { expr: (alias) => e.ref(joinAlias(alias, 'owner'), 'name') } },
531
-
532
- // per-mode override: format money in SQL one way, in memory another. Both use
533
- // the bound `alias` (`row[alias]`), never a hardcoded key.
534
- budgetLabel: { compute: {
535
- sql: (alias, ctx) => SqlText.concat([SqlText.raw("'$' || "), ctx.dialect.field(alias, 'budget')]),
536
- run: (alias, row) => Value.of(`$${row[alias]?.['budget'] ?? 0}`),
537
- } },
538
-
539
- legacyNote: { name: 'note' }, // remap: read the stored `note` column
540
- }
541
- ```
542
-
543
- Compute / access exprs that reach into other sources flow through the join
544
- planner, so two fields reading the **same** auto-join collapse to ONE join.
545
-
546
- ## RLS & FLS
547
-
548
- Same `Access` primitive, two scopes — both apply in `run` AND `toSQL`:
549
-
550
- - **RLS** (`TypeBacking.access`) — a row filter for every occurrence of the
551
- Type. A predicate is ANDed into the SQL `WHERE` and filters executor rows on
552
- load; `false` ⇒ no rows (`WHERE FALSE`); `true` / `undefined` ⇒ no filter.
553
- Combines (AND) with any `RlsProvider` passed to `run` / `toSQL`.
554
- - **FLS** (`FieldBacking.access`) — a per-field gate. A predicate emits
555
- `CASE WHEN <pred> THEN <value> ELSE NULL END` (nulled in memory when false);
556
- `false` ⇒ a constant `NULL`; `true` / `undefined` ⇒ the plain value.
557
-
558
- ```ts
559
- // RLS: only the current org's rows (orgId is NOT a conceptual field — pure backing).
560
- access: { expr: (alias) => e.eq(e.ref(alias, 'orgId'), e.value(currentOrg)) },
561
-
562
- // FLS: `secretField` is visible only for active projects, reading stored `secret`.
563
- secretField: { name: 'secret', access: { expr: (alias) => e.eq(e.ref(alias, 'status'), e.value('active')) } },
564
- ```
565
-
566
- ## Default conditions (soft scope)
567
-
568
- `TypeBacking.defaultConditions` is a **soft, suppressible** default scope —
569
- archived / soft-delete filtering the query can **reveal past**, unlike RLS. Each
570
- `DefaultCondition` is `{ where, without?, ops?, description? }`:
571
-
572
- - **`where`** — an `Access` predicate (dual `{ expr }` / `sql` / `run`, resolved
573
- exactly like RLS: `false` ⇒ no rows, `true` / `undefined` ⇒ no filter, else
574
- ANDed) applied while the condition is **active**, per bound occurrence.
575
- - **`without`** — referencing any of these fields **on that source** in a
576
- **condition position** (the query's `where` / `having`, or a JOIN's `and`)
577
- **lifts** the scope for that source. A reference in a select item / ORDER BY /
578
- GROUP BY does **not** lift it, and each bound alias (incl. a self-join) is
579
- decided independently. Omitted ⇒ derived from the fields `where.expr` reads (a
580
- `sql`/`run`-only `where` with no `without` is then **always-on** — set it
581
- explicitly to make it liftable).
582
- - **`ops`** — which row-filtering ops it scopes (default
583
- `['select', 'update', 'delete']`; **INSERT is never scoped**).
584
- - **`description`** — an optional terse LLM-facing note (else auto-summarized in
585
- `describeType`).
586
-
587
- RLS still always applies and is **never** suppressed; a default condition ANDs in
588
- alongside it.
589
-
590
- ```ts
591
- // Archived files: every query is scoped to `archivedAt IS NULL`…
592
- defaultConditions: [{ where: { expr: (alias) => e.isNull(e.ref(alias, 'archivedAt')) } }],
593
-
594
- // …until a query FILTERS on `archivedAt` (e.g. WHERE archivedAt IS NOT NULL),
595
- // which lifts the scope for that source and reveals the archived rows.
596
- ```
597
-
598
- ## Default ordering
599
-
600
- `TypeBacking.defaultOrder` declares a Type's **natural sort** — the `ORDER BY` a
601
- SELECT gets when it specifies **none** (and ordering is meaningful). A
602
- `DefaultOrder` is `{ by: DefaultOrderTerm[]; applyTo? }`; each `DefaultOrderTerm`
603
- is `{ by: Computed; dir?; nulls? }` whose `by` is the sort **key** — the same
604
- dual `{ expr }` / `sql` / `run` `Computed` computed fields use, so one key
605
- **emits to SQL and sorts in memory identically** (`dir` default `'asc'`; `nulls`
606
- else direction-based — asc ⇒ nulls first, desc ⇒ last — matching an explicit
607
- ORDER BY).
608
-
609
- It applies only when the **FROM** binds the backed Type (joins never contribute
610
- their default order), the query has **no explicit `order`**, and it is **not
611
- aggregated** (no `groupBy`, no bare aggregate) and **not `DISTINCT`** — both are
612
- skipped (a base-field order is meaningless post-aggregation; a non-selected
613
- DISTINCT key is illegal SQL).
614
-
615
- `applyTo` scopes **which** selects receive it:
616
-
617
- - **`'result'`** (default) — the **root** query being run/emitted, **or** any
618
- `LIMIT`/`OFFSET` select.
619
- - **`'paginated'`** — only a `LIMIT`/`OFFSET` select.
620
- - **`'all'`** — every eligible select over the Type (incl. subqueries / CTEs).
621
-
622
- The root is tracked by an `isRoot` marker threaded from `engine.run` /
623
- `engine.toSQL` onto the runtime / SQL context; nested queries (a subquery /
624
- EXISTS / IN subquery, a FROM subquery, a CTE body, a set-op branch) run and emit
625
- **non-root**. SELECT-only — DML is never reordered.
626
-
627
- ```ts
628
- // Newest-first by default: an unsorted SELECT over the Type gets
629
- // `ORDER BY "t"."createdAt" DESC`.
630
- defaultOrder: { by: [{ by: { expr: (alias) => e.ref(alias, 'createdAt') }, dir: 'desc' }] },
631
- ```
632
-
633
- ## Named joins & LATERAL
634
-
635
- `TypeBacking.joins` declares **named, hidden** joins; a field opts in via
636
- `FieldBacking.joins: [name]`. Each join is added to a query **once, only if a
637
- referencing field is emitted**, and deduped by name — so N fields sharing one
638
- join collapse to a single planned join (its alias is `joinAlias(source, name)`).
639
- A `JoinSpec` is either a `relation` (reuses the shared relation-join machinery)
640
- or a `lateral` (a correlated sub-select):
641
-
642
- ```ts
643
- joins: {
644
- // a belongs-to relation auto-join (shared by every field reading the owner).
645
- owner: { expr: (alias) => ({ kind: 'relation', source: alias, relation: 'owner' }) },
646
-
647
- // a LATERAL aggregate over a has-many — `taskCount` + `totalHours` share it.
648
- // The lateral correlates via `outer` (the planner passes this backed Type's
649
- // bound alias to `query`); the inner FROM (`task`) is its own scope.
650
- taskStats: { expr: (alias) => ({ kind: 'lateral', joinType: 'left',
651
- query: (outer) => ({ kind: 'select',
652
- fields: [
653
- { expr: e.countStar().toJSON(), as: 'cnt' },
654
- { expr: e.sum(e.ref('task', 'hours')).toJSON(), as: 'hrs' },
655
- ],
656
- from: { kind: 'type', type: 'task' },
657
- where: [e.eq(e.ref('task', 'projectId'), e.ref(outer, 'id')).toJSON()] }) }) },
658
- }
659
- ```
660
-
661
- A `lateral`'s `pick` names the column a no-`compute` field defaults to. Postgres
662
- emits `LEFT JOIN LATERAL (…) ON true`; the portable base dialect degrades to
663
- `LEFT JOIN LATERAL (…) ON 1 = 1` (a documented correlated-subquery fallback) and
664
- the runtime evaluates the sub-select per outer row.
665
-
666
- ## Relation-join backing (physical FK columns / custom ON)
667
-
668
- By default a relation join's `ON` is synthesized from the relation field's
669
- **name** convention (`source.<local> = target.<foreign>`). `FieldBacking.relation`
670
- (on a relation-typed field only) overrides that with **explicit, LLM-hidden
671
- physical foreign-key columns** — the conceptual `FieldDef` / `TypeDef` the model
672
- sees never change.
673
-
674
- ```ts
675
- const backing: TypeBacking = {
676
- fields: {
677
- // `comment_rating.user` belongs-to `user`; the hidden physical FK is `user_id`.
678
- user: { relation: { keys: [{ local: 'user_id', foreign: 'id' }] } },
679
- },
680
- };
681
- // A user's ratings (the materialized inverse has-many) then emits
682
- // … LEFT JOIN "comment_rating" ON "user"."id" = "comment_rating"."user_id"
683
- // and the belongs-to direction emits the mirror `ON "comment_rating"."user_id" = "user"."id"`.
684
- ```
685
-
686
- - **`keys: [{ local, foreign? }]`** — physical key-column pairs, **all ANDed**
687
- (composite FKs: `keys: [{ local: 'a_id', foreign: 'a' }, { local: 'b_id',
688
- foreign: 'b' }]` ⇒ `ON src.a_id = tgt.a AND src.b_id = tgt.b`). `local` is the
689
- column on the side that **declares** the relation; `foreign` is the column on
690
- the **target** and defaults to the target's identity field.
691
- - **The backing lives on the owning belongs-to relation.** A materialized inverse
692
- has-many **reuses the same FK** (its forward relation's backing, orientation
693
- swapped) — you declare it once.
694
- - **`on`** — a fully custom, alias-correct `ON` (overrides `keys`). `{ expr }` is
695
- the dual path (one predicate emitted to SQL **and** evaluated in memory); `sql`
696
- / `run` are per-mode overrides. Each factory receives the two **bound aliases**
697
- (`localAlias` = the declaring side, `joinedAlias` = the target), so
698
- aliased / self-joins resolve.
699
-
700
- Every ON site honors the backing — authored relation joins (value + at runtime),
701
- the `TypeBacking.joins` relation spec, and joined UPDATE/DELETE — so SQL and the
702
- in-memory runtime always agree. `JoinDef.and`
703
- is still ANDed onto whatever `ON` the backing produces. With no backing the
704
- convention is used unchanged (fully backward-compatible).
705
-
706
- ## Filters and params
707
-
708
- A `filters` expression is an **LLM-opaque placeholder** bound to a source, with
709
- an optional `fields` allowlist — `{ kind: 'filters', source, fields? }`. The LLM
710
- never authors the predicate. At **execution time** the developer supplies a
711
- single **boolean `Expr` / `ExprDef`** per source (keyed by source); the
712
- placeholder evaluates / emits it, vacuously `TRUE` when none is supplied.
713
-
714
- Introspect what a built query exposes with `query.filters(engine)`: it returns
715
- `Record<source, { fields: QueryField[] }>` — for every `filters` placeholder,
716
- its bound source mapped to the fields available on it (each with name, resolved
717
- type, nullability, and field-type kind), restricted to the placeholder's
718
- `fields` allowlist when set. A UI renders controls from that, then supplies the
719
- resulting bool `Expr` at run time.
720
-
721
- ```ts
722
- // In the query: just a placeholder + an allowlist (no predicate).
723
- where: [{ kind: 'filters', source: 'product', fields: ['category', 'price'] }]
724
-
725
- // Introspect the exposed source → fields.
726
- const exposed = engine.registry.parseQuery(select).filters(engine);
727
- // → { product: { fields: [{ name:'category', … }, { name:'price', … }] } }
728
-
729
- // At run time: supply ONE bool ExprDef per source (built however you like — here
730
- // with the `e.*` builder, whose `.toJSON()` is the wire `ExprDef`).
731
- const productFilter: ExprDef = e.and(
732
- e.eq(e.ref('product', 'category'), e.value('hardware')),
733
- e.gte(e.ref('product', 'price'), e.value(30)),
734
- ).toJSON();
735
- await engine.run(select, { filters: { product: productFilter } });
736
- ```
737
-
738
- ## Semantic & text search
739
-
740
- Both are bound to a **source** with an OPTIONAL `field` (omit to target the
741
- whole source):
742
-
743
- - **`semantic`** — `{ kind: 'semantic', source, field?, query }` scores a row's
744
- embedding against `query`, which is a literal string, a `param`, a
745
- `{ source, field }` ref to ANOTHER **bound** source + semantic field (the
746
- cross-source **pairing** form), or a `{ type, field }` ref that resolves to the
747
- single bound source of that Type. The source/field must be semantic-eligible (a
748
- Type flagged `semantic`, or a `semantic`/`search` text field). Requires an
749
- embedder.
750
- - **`text-search`** — `{ kind: 'text-search', source, field?, query }` is a
751
- full-text **predicate** (a boolean); `query` is a literal string or a `param`.
752
- Whole-source search needs a searchable Type; a narrowed `field` must be a text
753
- field.
754
- - **`text-score`** — `{ kind: 'text-score', source, field?, query }` is the
755
- numeric **relevance** counterpart of `text-search` (same eligibility). It
756
- resolves to a **number** — usable in SELECT + ORDER BY — so "top N by text
757
- relevance" works. Postgres emits `ts_rank`; the base (ANSI) dialect degrades to
758
- a numeric `0/1` match. Build it with `e.textScore(source, query, field?)`.
759
-
760
- ```ts
761
- { kind: 'semantic', source: 'doc', field: 'body', query: 'quarterly revenue' }
762
- { kind: 'semantic', source: 'doc', query: { source: 'topic', field: 'label' } } // pairing
763
- { kind: 'text-search', source: 'user', field: 'email', query: 'ada' }
764
- { kind: 'text-score', source: 'doc', field: 'body', query: 'revenue' }
765
- ```
766
-
767
- In the LLM schema these participate in **depth** like field-refs: at `paired`
768
- the `source` is a Type and the `field` enum is restricted to that Type's
769
- semantic / text fields.
770
-
771
- ### Scoring & ranking — pairing + text relevance
772
-
773
- Both `semantic` (pairing) and `text-score` produce a **number** you can put in
774
- SELECT and `ORDER BY … DESC LIMIT N`, so a query returns the top-N by relevance.
775
-
776
- - **Cross-Type semantic pairing.** Join (or cross-join) two Types so BOTH are
777
- bound, then score one against the other's embedding. `toSQL` emits the
778
- dialect's `similarity` over BOTH bound aliases' vectors (each side's hidden
779
- `SemanticBacking.vectorField` if backed, else the default `<alias>."embedding"`
780
- fragment), so a self-pairing of two aliases of ONE Type works too:
781
-
782
- ```sql
783
- -- FROM paper JOIN topic … , fields: [ id, semantic(paper, {source:'topic',field:'label'}) as score ]
784
- SELECT "paper"."id", (1 - ("paper"."emb" <=> "topic"."embedding")) AS "score"
785
- FROM "paper" … INNER JOIN "topic" … ORDER BY "score" DESC LIMIT 10
786
- ```
787
-
788
- Validation requires BOTH sides be bound and semantic-eligible: an unbound
789
- reference is `semantic.query-unbound`; a `{ type }` bound more than once is
790
- `semantic.query-ambiguous` (use the `{ source }` form to disambiguate). The
791
- base dialect degrades similarity to `0` (never throws).
792
-
793
- - **Numeric text score.** `text-score` ranks by full-text relevance:
794
- `ts_rank(to_tsvector(col), plainto_tsquery(query))` in Postgres (honoring a
795
- `SearchBacking`'s hidden `vectorField` / `language` / boolean `sql` override,
796
- the last lifted to a numeric `0/1`); the base dialect degrades to
797
- `CASE WHEN <LIKE> THEN 1 ELSE 0 END`. In memory it is a deterministic
798
- token-overlap fraction (honoring `SearchBacking.run`). See
799
- `examples/13-scoring-ranking.ts`.
800
-
801
- ### Search & semantic backing
802
-
803
- A Type / field flagged `search` / `semantic` in the (unchanged, minimal) schema
804
- very often has a **physical field hidden from the type system** that already
805
- holds a precomputed `tsvector` (full-text) or `pgvector` embedding. A backing
806
- says **how** search / similarity runs per Type or field — most importantly by
807
- pointing at that hidden field. Both `TypeBacking` (whole-type) and `FieldBacking`
808
- (per-field) take an optional `search?: SearchBacking` and `semantic?:
809
- SemanticBacking`; a **field-level** backing overrides the **type-level** one.
810
-
811
- ```ts
812
- const backing: TypeBacking = {
813
- // WHOLE-TYPE: point at hidden precomputed fields (NOT conceptual fields).
814
- search: { vectorField: 'search_tsv', language: 'english' }, // a tsvector field
815
- semantic: { vectorField: 'embedding' }, // a pgvector field
816
- fields: {
817
- // FIELD-LEVEL override wins for a field-narrowed `text-search` / `semantic`.
818
- title: { search: { vectorField: 'title_tsv' }, semantic: { vectorField: 'title_vec' } },
819
- },
820
- };
821
- ```
822
-
823
- **Knobs** (each factory takes the bound `alias` **first** and must reference it,
824
- so aliased / self-joined sources resolve correctly):
825
-
826
- - `vectorField` — the hidden physical field, referenced as `<alias>."<field>"`.
827
- In Postgres a `SearchBacking.vectorField` emits the precomputed-tsvector
828
- predicate `<alias>."f" @@ plainto_tsquery('<language>', $n)` (**not** re-wrapped
829
- in `to_tsvector`); a `SemanticBacking.vectorField` is the left operand of the
830
- dialect's `similarity`, with the query vector bound as a `$n::vector` param.
831
- - `language` — the text-search config for `plainto_tsquery` (default `'english'`).
832
- - `sql` — a full SQL override → a **boolean** predicate (search) / **numeric**
833
- score (semantic). Given `(alias, query|queryVector, ctx)`.
834
- - `run` — a full runtime override → `boolean` (search) / `number` (semantic).
835
- - `SemanticBacking.vector` — where the row's embedding comes from at runtime
836
- (an alternative to `vectorField`), returning `number[]` or `null`.
837
- - `SemanticBacking.embedder` — a per-Type / per-field embedder for the **query**
838
- text (else the run / engine embedder).
839
-
840
- **Precedence** (both modes): a full `sql` / `run` override wins; else the hidden
841
- `vectorField` (or `vector` producer) is used; else today's default (the dialect's
842
- `textSearch` / `similarity` over the conceptual text fields, or an in-memory
843
- token match / embed-the-row-text). `toSQL` stays synchronous — the async embedder
844
- is **never** called there; the query vector is a bound param.
845
-
846
- The **base (ANSI) dialect degrades gracefully** and never throws: a tsvector
847
- field falls back to a case-insensitive `LIKE`, and vector similarity to a
848
- constant `0`. See `examples/12-search-backing.ts`.
849
-
850
- ### Array fields and operations
851
-
852
- An `array` field is queried with the `array-op` predicate expression: `contains`
853
- (a single element is present), `containsAny` / `containsAll` (overlap / superset
854
- against an element list), and `isEmpty` / `notEmpty`. Element count is a
855
- `comparison` over the builtin `arrayLength(field)` scalar function. (Element matching follows the ELEMENT type's `casing`, else the engine's
856
- `textCasing` default — the same rule a scalar text comparison uses.)
857
-
858
- ```ts
859
- // containment — a single element is present:
860
- { kind: 'array-op', op: 'contains', target: { kind: 'field-ref', source: 'user', field: 'tags' },
861
- value: { kind: 'literal', value: 'beta' } }
862
-
863
- // overlap against an element list:
864
- { kind: 'array-op', op: 'containsAny', target: { kind: 'field-ref', source: 'user', field: 'tags' },
865
- value: [{ kind: 'literal', value: 'admin' }, { kind: 'literal', value: 'beta' }] }
866
-
867
- // element count ≥ 2 via the builtin arrayLength function:
868
- { kind: 'comparison', op: '>=',
869
- left: { kind: 'function-call', function: 'arrayLength', args: { arr: { kind: 'field-ref', source: 'user', field: 'tags' } } },
870
- right: { kind: 'literal', value: 2 } }
871
- ```
872
-
873
- > Build these with the `e.*` array builders (`e.contains` / `e.containsAny` /
874
- > `e.containsAll` / `e.isEmpty` / `e.notEmpty`, and `e.fn('arrayLength', …)`).
875
-
876
- **Dialect support.** Array operations are **Postgres-native**: `contains` →
877
- `value = ANY(col)`, `containsAll` → `col @> ARRAY[…]`, `containsAny` →
878
- `col && ARRAY[…]`, and length → `cardinality(col)`. The portable **base (ANSI)
879
- dialect has no array operators**, so containment (`contains` / `containsAny` /
880
- `containsAll`) throws a clear `QueryTypeError` (`array-op.unsupported-dialect`)
881
- rather than emit wrong SQL; emptiness and the length filters still work there
882
- via `COALESCE(json_array_length(col), 0)`.
883
-
884
- A `param` (`{ kind: 'param', name }`) infers its type from how it is used and
885
- is bound at run/emit time. A filter predicate is likewise supplied at EXECUTION
886
- time via `engine.run(query, { filters: { <source>: boolExpr } })` — the
887
- placeholder evaluates it dynamically against the bound source (see
888
- [Execution model](#execution-model)). `autoPaginate` turns a query into a
889
- reusable, paged artifact by binding `limit` / `offset` to params (idempotently):
890
-
891
- ```ts
892
- import { autoPaginate } from '@aeye/query';
893
- const paged = autoPaginate(select); // adds { limit: param('limit'), offset: param('offset') }
894
- await engine.run(paged, { params: { limit: 10, offset: 0 } });
895
- ```
896
-
897
- ## CTEs
898
-
899
- A `WITH` statement (`{ kind: 'cte', ctes, final }`) carries a list of named CTE
900
- entries consumed by a `final` query. An entry is one of two **distinct** shapes,
901
- structurally discriminated:
902
-
903
- - **Non-recursive** — `{ name, query }`.
904
- - **Recursive** — `{ name, base, recursive }`: a `base` seed query UNION-ed with
905
- a `recursive` arm that reads the CTE's own accumulating rows until a fixpoint
906
- (iteration-capped). Recursion is its OWN shape — there is no `recursive?` flag
907
- on the plain entry.
908
-
909
- ```ts
910
- { kind: 'cte',
911
- ctes: [{ name: 'descendants',
912
- base: /* seed select */,
913
- recursive: /* select that reads `descendants` */ }],
914
- final: { kind: 'select', from: { kind: 'type', type: 'descendants' }, fields: [/* … */] } }
915
- ```
916
-
917
- ## Drill-down
918
-
919
- `drillDown` rebuilds the query that returns the **underlying rows** behind an
920
- aggregate — PARAMETERIZED: each GROUP BY key is pinned to a bind param
921
- (`key = param(name)`), so the drilled query is reusable. It returns the rebuilt
922
- `query`, the `params` (a `DrillParam[]` mapping each output `field` → its
923
- `name`), and any `warnings`.
924
-
925
- ```ts
926
- import { drillDown, drillDownInto } from '@aeye/query';
927
-
928
- // The reusable, parameterized drilled query + its field → param mapping.
929
- const d = drillDown(revenuePerUser, engine);
930
- // d.params → [{ name:'userId', field:'userId', key: { kind:'field-ref', source:'order', field:'userId' } }]
931
-
932
- // Or drill into ONE aggregated row: extract its key values, then it's the same
933
- // run call. (This is the old literal-baking behavior, now param-driven.)
934
- const into = drillDownInto(revenuePerUser, groupRow, engine);
935
- if ('query' in into) {
936
- const underlying = await engine.run(into.query, { params: into.params }); // that row's orders
937
- }
938
- ```
939
-
940
- The param NAME is derived from the carrying output field (sanitized to a valid
941
- identifier; suffixed `_2`, `_3`, … on collision with a param the query already
942
- uses). Failure cases (`drill.no-aggregation` / `non-invertible` /
943
- `having-aggregate` / `window-unsupported`) return LLM-friendly `Problems`.
944
-
945
- Each aggregate is replaced by its underlying row-level expression, and `count(*)`
946
- — which has no single value — expands to the FROM type's fields MINUS the ones
947
- the SELECT already projects itself. So `SELECT status, count(*) … GROUP BY status`
948
- drills to `status` plus the remaining columns, with the group key projected ONCE.
949
- The skip is keyed on the EXPRESSION (its canonical form), never on the output
950
- name: two different expressions may legitimately share a name.
951
-
952
- ## Cost & estimation
953
-
954
- Bottom-up estimates driven by each Type's cardinality (`count` rows, `bytes`
955
- per row), its indexes + fixed **selectivity** for predicates (an indexed
956
- equality narrows toward one row; a non-indexed one applies `EQ_SELECTIVITY`),
957
- and per-Type / per-field `changes` rates. Five estimators hang off the engine:
958
-
959
- ```ts
960
- const cost = engine.cost(select); // { rows, bytes } — WORK to produce the result (scanned rows)
961
- const output = engine.outputCost(select); // { rows, bytes } — SIZE of the result (delivered rows × projection width)
962
- const affected = engine.affected(update); // { rows, types: [{ type, rows }] } — rows an INSERT/UPDATE/DELETE (or CTE) mutates
963
- const refs = engine.references(select); // { types, fields, functions } — exactly what the query READS
964
- const ttl = engine.changeInterval(select); // ms until the data behind it could change (0 = always, -1 = never, else fastest rate)
965
-
966
- // Constraints reject over-budget queries during validation:
967
- const problems = engine.validateQuery(select, undefined, { maxRows: 100, maxBytes: 1_000_000 });
968
- // → cost.rows-exceeded / cost.bytes-exceeded when the estimate blows past a cap
969
- ```
970
-
971
- `cost` estimates work (OR-aware, index-probe driven); `outputCost` sizes the
972
- delivered result (post-WHERE/GROUP/DISTINCT, capped by LIMIT/OFFSET);
973
- `affected` counts mutated rows per Type; `references` powers `changeInterval`,
974
- which folds the read Types' / fields' / functions' `changes` rates into a single
975
- freshness / cache-TTL signal. All accept the same execution-time
976
- `options.params` / `filters` / `sort` so the estimate reflects what actually runs.
977
-
978
- ## Functions
979
-
980
- All four function shapes are uniform: declare a `FunctionDef` (name, shape,
981
- **named** params, output) with `registerFunction`, then pair it with a
982
- shape-tagged runtime via `registerFunctionRun`. Calls reference the function by
983
- name with **named arguments** (`args: { paramName: <expr> }`):
984
-
985
- ```ts
986
- // scalar — initials(value: text): text
987
- registry.registerFunction({
988
- name: 'initials', shape: 'scalar',
989
- params: [{ name: 'value', type: { kind: 'text' } }],
990
- output: { kind: 'text' },
991
- });
992
- registry.registerFunctionRun('initials', {
993
- shape: 'scalar',
994
- run: (args) => Value.of(args.value.toText().split(/\s+/).map((w) => w[0]).join('')),
995
- });
996
-
997
- // reference it by name with NAMED args:
998
- // { kind: 'function-call', function: 'initials', args: { value: <expr> } }
999
- ```
1000
-
1001
- The four shapes differ only in what their `run` receives:
1002
-
1003
- | shape | `run(...)` signature | example |
1004
- | ----------- | --------------------------------------------- | ------------- |
1005
- | `scalar` | `(args, ctx)` → one value | `upper` |
1006
- | `tabular` | `(args, ctx)` → rows | `rangeRows` |
1007
- | `aggregate` | `(rows, ctx)` → one value over a group | `sum`, `count`|
1008
- | `window` | `(partition, index, ctx)` → value per row | `rowNumber` |
1009
-
1010
- `count(*)` is the empty-args convention: `{ kind: 'aggregate', function:
1011
- 'count', args: {} }`. The registry ships a **default library** (60+ functions
1012
- across all shapes — `upper`/`concat`/`coalesce`/…, string/math scalars
1013
- (`trimLeft`/`padLeft`/`splitPart`/`log`/`iif`/…), `sum`/`avg`/`min`/`max`/
1014
- `count`, `rowNumber`/`rank`/`lag`/…) registered by `createRegistry()`, so they
1015
- are discoverable and runnable out of the box (see the reference below):
1016
-
1017
- ```ts
1018
- registry.functionList(); // every FunctionDef (default lib + your own)
1019
- describeFunctions(engine); // a promptable, by-shape listing for an LLM
1020
- ```
1021
-
1022
- ### Operators — `&&`, `<->`, `@>`
1023
-
1024
- A function declaration cannot express an INFIX operator: `a && b` has no call
1025
- form in any dialect, and `FunctionDef.sql` is a NAME, never a template.
1026
- `registerOperator` is the other half — a declaration whose SQL is a per-dialect
1027
- template, applied through the `operator` expr kind:
1028
-
1029
- ```ts
1030
- registry.registerOperator({
1031
- name: '&&', // SQL operator punctuation only
1032
- operands: [{ name: 'left', type: { kind: 'json', as: 'Geometry' } },
1033
- { name: 'right', type: { kind: 'json', as: 'Geometry' } }],
1034
- output: { kind: 'bool' }, // concrete, never 'inferred'
1035
- instructions: 'Bounding-box overlap between two geometries. Cheap; a pre-filter for ST_Contains.',
1036
- emit: { postgres: '({left} && {right})' }, // PARENTHESIZED; per Dialect.name
1037
- selectivity: 0.1,
1038
- });
1039
- registry.registerOperatorRun('&&', (args) => Value.of(bboxOverlaps(args.left, args.right)));
1040
-
1041
- // reference it by name with NAMED operands:
1042
- // { kind: 'operator', op: '&&', args: { left: <expr>, right: <expr> } }
1043
- ```
1044
-
1045
- ```sql
1046
- WHERE ("parcel"."shape" && ST_GeomFromGeoJSON($1))
1047
- ```
1048
-
1049
- The operand's **declared type reaches emission**, so a document operand binds
1050
- through that type's own `cast` rather than the dialect's default json cast —
1051
- without it Postgres refuses the statement (`operator does not exist: geometry &&
1052
- jsonb`). A value position asserts only what its declaration WROTE: an operand's
1053
- cast resolves from the operand's own `with` bag and never from the refinement's
1054
- defaults, since those would pin a typmod the value never had to satisfy. A cast
1055
- needing an option the operand did not write is refused at emit
1056
- (`cast.unwritten-option`).
1057
-
1058
- `registry.operatorList()` enumerates them; `describeOperators(engine)` renders
1059
- the promptable block (and `describeEngine` includes it when any is registered).
1060
- A dialect with no `emit` entry is **refused** at emit
1061
- (`operator.unsupported-dialect`), never degraded to a neutral fragment; so is a
1062
- missing `run` on the in-memory road (`operator.no-run`), because an operator is
1063
- usually a predicate and NULL there means zero rows. Full rules — the name
1064
- charset, the template checks, and what `OperatorDef` deliberately does not carry
1065
- — are in `aeye-query.md`.
1066
-
1067
- ### Function reference
1068
-
1069
- All builtin names are **camelCase** (no underscores). Where the emitted SQL
1070
- function name differs from the camelCase name it is shown in the *SQL* column;
1071
- otherwise the SQL is `name(args)` on both dialects. `base` is the portable
1072
- ANSI dialect, `postgres` the pg dialect (they differ only where noted).
1073
-
1074
- **Window** (`e.window`)
1075
-
1076
- | function | SQL (base = postgres) | notes |
1077
- | --------------------------- | --------------------- | --------------------------------------- |
1078
- | `rowNumber()` | `row_number()` | renamed from `row_number` |
1079
- | `rank()` | `rank()` | |
1080
- | `denseRank()` | `dense_rank()` | renamed from `dense_rank` |
1081
- | `lag(value, offset?, default?)` | `lag(…)` | |
1082
- | `lead(value, offset?, default?)` | `lead(…)` | |
1083
- | `percentRank()` | `percent_rank()` | `(rank − 1) / (N − 1)` |
1084
- | `cumeDist()` | `cume_dist()` | |
1085
- | `ntile(n)` | `ntile(n)` | 1-based bucket over `n` equal buckets |
1086
- | `firstValue(value)` | `first_value(value)` | |
1087
- | `lastValue(value)` | `last_value(value)` | full-partition frame (see note below) |
1088
- | `nthValue(value, n)` | `nth_value(value, n)` | 1-based |
1089
-
1090
- **Scalar — string** (`e.fn`)
1091
-
1092
- | function | SQL name |
1093
- | ------------------------------------- | --------------- |
1094
- | `lower` `upper` `trim` `length` `substring` `replace` `concat` | *(same)* |
1095
- | `trimLeft(value)` | `ltrim` |
1096
- | `trimRight(value)` | `rtrim` |
1097
- | `left(value, count)` `right(value, count)` | *(same)* |
1098
- | `padLeft(value, length, fill?)` | `lpad` |
1099
- | `padRight(value, length, fill?)` | `rpad` |
1100
- | `repeat(value, count)` `reverse(value)` | *(same)* |
1101
- | `indexOf(value, search)` | `strpos` (1-based, 0 = absent) |
1102
- | `startsWith(value, search)` | `starts_with` |
1103
- | `splitPart(value, delimiter, index)` | `split_part` (1-based) |
1104
- | `concatWs(separator, values)` | `concat_ws` (`values` = one array arg, like `concat`) |
1105
-
1106
- **Scalar — math** (`e.fn`)
1107
-
1108
- | function | SQL name |
1109
- | ------------------------------------- | --------------- |
1110
- | `abs` `ceil` `floor` `round` `sqrt` `power` | *(same)* |
1111
- | `mod(value, divisor)` `sign` `exp` `ln` `trunc` `pi()` `random()` | *(same)* |
1112
- | `log(base, value)` | `log(base, value)` |
1113
- | `log10(value)` | `log` (pg single-arg `log` is base-10) |
1114
- | `degrees` `radians` `sin` `cos` `tan` `asin` `acos` `atan` `atan2(y, x)` | *(same)* |
1115
-
1116
- **Scalar — conditional / other** (`e.fn`)
1117
-
1118
- | function | SQL |
1119
- | ------------------------------------- | --------------- |
1120
- | `iif(condition, then, else)` | `(CASE WHEN condition THEN then ELSE else END)` (both dialects) |
1121
- | `coalesce` `nullif` `greatest` `least` `arrayLength` | *(same)* |
1122
- | `now()` | `now()` |
1123
- | `currentDate()` | `CURRENT_DATE` (renamed from `current_date`; bare form, no parens) |
1124
-
1125
- **Scalar — date / time** (`e.*`) — temporal inputs accept an ISO date/timestamp
1126
- string or a temporal field; the `field` of a selector is a **literal** token
1127
- (`'year'`/`'month'`/`'day'`/`'dow'`/`'doy'`/`'week'`/`'hour'`/`'minute'`/
1128
- `'second'`/`'quarter'`/`'isodow'`/`'epoch'`) spliced inline (not a bind param).
1129
-
1130
- | function | base SQL | postgres SQL |
1131
- | ------------------------------------- | -------------------------------- | ------------------------------------- |
1132
- | `currentTime()` `currentTimestamp()` | `CURRENT_TIME` / `CURRENT_TIMESTAMP` (bare) | *(same)* |
1133
- | `year/month/day/hour/minute/second(d)`| `EXTRACT(<PART> FROM d)` | *(same)* |
1134
- | `dayOfWeek(d)` | `EXTRACT(DOW FROM d)` | *(same)* — `0`=Sun … `6`=Sat |
1135
- | `dayOfYear(d)` `week(d)` | `EXTRACT(DOY/WEEK FROM d)` | *(same)* — `week` is the ISO week |
1136
- | `datePart(field, d)` | `EXTRACT(<field> FROM d)` | `date_part('field', d)` |
1137
- | `dateAdd(field, n, d)` | `d` (degrade — unchanged) | `(d + (n \|\| ' ' \|\| 'field')::interval)` |
1138
- | `dateDiff(field, a, b)` | `(EXTRACT(field FROM b) − EXTRACT(field FROM a))` | `(date_part('field', b) − date_part('field', a))` — component difference |
1139
- | `dateTrunc(field, d)` | `d` (degrade — unchanged) | `date_trunc('field', d)` |
1140
- | `makeDate(year, month, day)` | `make_date(…)` | `make_date(…)` |
1141
- | `dateFormat(d, format)` | `to_char(d, fmt)` | `to_char(d, fmt)` — tokens `YYYY/MM/DD/HH24/HH/MI/SS` |
1142
- | `epoch(ts)` | `EXTRACT(EPOCH FROM ts)` | *(same)* |
1143
- | `fromEpoch(value)` | `to_timestamp(value)` | `to_timestamp(value)` |
1144
- | `age(a, b)` | `age(a, b)` | `age(a, b)` — runtime returns whole-day span |
1145
-
1146
- **Scalar — array** (`e.*`) — postgres-native; the base (ANSI) dialect DEGRADES
1147
- gracefully (a constant, or the first argument unchanged) and never throws.
1148
-
1149
- | function | base SQL (degrade) | postgres SQL |
1150
- | ------------------------------------- | ------------------ | ------------------------------------- |
1151
- | `arrayContains(arr, value)` | `(1 = 0)` | `(value = ANY(arr))` |
1152
- | `arrayAppend(arr, value)` | `arr` | `array_append(arr, value)` |
1153
- | `arrayPrepend(arr, value)` | `arr` | `array_prepend(value, arr)` |
1154
- | `arrayConcat(a, b)` | `a` | `(a \|\| b)` |
1155
- | `arrayIndexOf(arr, value)` | `0` | `array_position(arr, value)` (1-based)|
1156
- | `arraySlice(arr, lo, hi)` | `arr` | `arr[lo:hi]` (1-based inclusive) |
1157
- | `arrayRemove(arr, value)` | `arr` | `array_remove(arr, value)` |
1158
- | `arrayDistinct(arr)` | `arr` | `ARRAY(SELECT DISTINCT unnest(arr))` |
1159
- | `arrayToString(arr, sep)` | `''` | `array_to_string(arr, sep)` |
1160
- | `stringToArray(str, sep)` | `str` | `string_to_array(str, sep)` |
1161
-
1162
- **Aggregate** (`e.agg` / `e.sum` / …): `count` `sum` `avg` `min` `max`
1163
- — all emit `name(args)` (or `count(*)` for empty args). Group 2d adds:
1164
-
1165
- | function | base SQL | postgres SQL |
1166
- | ------------------------------------- | -------------------------------- | ------------------------------------- |
1167
- | `stddev(value)` `variance(value)` | `stddev(…)` / `variance(…)` (sample) | *(same)* |
1168
- | `stringAgg(value, sep)` | `string_agg(value, sep)` | *(same)* |
1169
- | `countIf(cond)` | `sum(CASE WHEN cond THEN 1 ELSE 0 END)` | *(same, both dialects)* |
1170
- | `arrayAgg(value)` | `NULL` (degrade) | `array_agg(value)` |
1171
- | `boolAnd(value)` | `(MIN(CASE WHEN value THEN 1 ELSE 0 END) = 1)` | `bool_and(value)` |
1172
- | `boolOr(value)` | `(MAX(CASE WHEN value THEN 1 ELSE 0 END) = 1)` | `bool_or(value)` |
1173
-
1174
- ## The LLM loop
1175
-
1176
- The `llm/` surface turns the engine into an LLM tool:
1177
-
1178
- ```ts
1179
- import { selectTypes, buildSchemas, querySchema, buildQueryTool } from '@aeye/query';
1180
-
1181
- // 1. Narrow the schema to the Types a request needs (semantic ranking).
1182
- const types = await selectTypes(engine, 'revenue by customer last month');
1183
-
1184
- // 2. Per-axis `depth` Zod schemas (see "Schema depth" below). `'paired'` locks
1185
- // every axis: Type-name positions are enum-locked, field refs are TYPE+FIELD
1186
- // pairs (an `order` source can't be paired with a `user`-only field),
1187
- // relation paths are rooted at a known Type, and function calls are typed.
1188
- const schemas = buildSchemas(engine, { depth: 'paired', types });
1189
-
1190
- // 3. Or get the tool-input schema, which falls back to a string description
1191
- // past `max` Types (shouldUseStringSchema). `depth` / `functions` thread
1192
- // straight through to `buildSchemas`.
1193
- const schema = querySchema(engine, { types, depth: 'paired' });
1194
-
1195
- // 4. A ready-wired `@aeye/core` `Tool` — drop it into any core / `@aeye/ai`
1196
- // agent's tool set. Its wire `schema` is the query schema; its custom `parse`
1197
- // REPLACES Zod (validate the envelope → build a runnable `Query` → run full
1198
- // engine validation), throwing a rich `QueryToolError` whose `.message` is a
1199
- // compiler-style report on failure. Its `call` RUNS the built query.
1200
- // `instructions` reflect the active depth + the selected functions.
1201
- const tool = buildQueryTool(engine, { depth: 'paired' });
1202
- const query = await tool.parse(ctx, JSON.stringify({ query: someQueryDef })); // built Query (throws QueryToolError on failure)
1203
- const result = await tool.run(query, ctx); // runs it → QueryResult
1204
- ```
1205
-
1206
- Because the custom `parse` bypasses Zod, the model sees the engine's concise
1207
- `Problems` diagnostics (via `formatProblems`) instead of Zod's harder-to-follow
1208
- messages; when the query is clean the decoded value is the built `Query` and the
1209
- tool's `call` executes it.
1210
-
1211
- **Self-describing the engine.** `describeEngine(engine, { types?, functions? })` composes one terse, promptable block a model can read to know everything it may use: every (supplied) Type, then `describeExprs` (the capability-gated `kind — INSTRUCTIONS` list of usable expr kinds — `semantic` / `array-op` / … appear only when an eligible Type/function exists; the core is never gated), then `describeFunctions` (`name(a, b?): output — instructions`, grouped by shape), then `describeDialects`. `describeType` / `describeField` always render a short `label` + long `description` — the dev's `TypeDef` / `FieldDef` values when set, else defaults GENERATED on demand from the meta-model (a Field from its FieldType + flags + nullability + relation cardinality; a Type from its name + field/relation/index summary). Read the pair with `fieldMeta(field)` / `typeMeta(type)`; the stored def is never mutated.
1212
-
1213
- See `examples/` for an end-to-end, runnable tour of all of the above.
1214
-
1215
- ## Schema depth
1216
-
1217
- `buildSchemas` / `querySchema` / `buildQueryTool` constrain the LLM-facing
1218
- schema along **four independent axes**, each dialed by `depth`:
1219
-
1220
- | axis | levels (loose → tight) | constrains |
1221
- | ----------- | -------------------------------------------- | ---------------------------------------- |
1222
- | `refs` | `open` · `types` · `fields` · `both` · `paired` | `field-ref` source + field / relation join `on` |
1223
- | `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
1224
- | `functions` | `open` · `names` · `typed` | function name + named-arg objects |
1225
- | `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
1226
-
1227
- Pass a full `SchemaDepth` object, a partial one (unset axes stay loose), or a
1228
- preset string: `'open'` (every axis loose — free strings) and `'paired'` (every
1229
- axis tight). The deprecated `strict: true` / `false` are sugar for
1230
- `'paired'` / `'open'`.
1231
-
1232
- ```ts
1233
- buildSchemas(engine, { depth: { refs: 'paired', functions: 'typed' } });
1234
- buildSchemas(engine, { depth: 'open' }); // ≡ strict: false
1235
- buildSchemas(engine, { depth: 'paired' }); // ≡ strict: true
1236
-
1237
- // FunctionSelector — which functions appear in the names/typed schema + prompt:
1238
- buildSchemas(engine, { depth: { functions: 'names' }, functions: { scalar: ['upper', 'lower'] } });
1239
-
1240
- // maxEnumSize — AUTO-DEGRADE any axis whose enumeration exceeds the budget one
1241
- // level looser, so a large catalog never produces an unusable schema:
1242
- buildSchemas(engine, { depth: 'paired', maxEnumSize: 50 });
1243
- ```
1244
-
1245
- `examples/10-schema-depth.ts` prints, per depth, whether a cross-type field-ref
1246
- / unknown function / unknown argument is accepted or rejected.
1247
-
1248
- ### Capability gating
1249
-
1250
- INDEPENDENT of depth, the generated `Expr` union **omits any expr kind the
1251
- available Types / functions can't use**, so the model is never offered an
1252
- unusable construct. A kind appears only when it is applicable:
1253
-
1254
- | kind | available when |
1255
- | ---- | -------------- |
1256
- | `semantic` | some Type is semantic-eligible (`isSemantic()`) |
1257
- | `text-search` | some Type is searchable (`isSearchable()`) |
1258
- | `array-op` | some Type has an `array` field |
1259
- | joins | some Type has a relation field |
1260
- | `tabular-function-call` | ≥1 selected `tabular` function |
1261
- | `aggregate` / `window` / `function-call` | ≥1 selected function of that shape |
1262
- | `operator` | ≥1 registered operator whose operand type some in-scope field could supply |
1263
- | `filters` | some Type has filterable fields |
1264
-
1265
- The always-usable core (literal / param / binary / unary / comparison / logical
1266
- / in / between / is-null / exists / case / `field-ref` / subquery) is never
1267
- gated. When no Type has a relation, the `joins` array is gated out of `Select`
1268
- too (it accepts only an empty / absent list).
1269
-
1270
- ## Interactive CLI
1271
-
1272
- `examples/cli.ts` is a small REPL (in the spirit of `ginny`) that ties the
1273
- whole loop together: it loads whatever JSON data lives in a data directory,
1274
- infers a `Type` per file, then lets you type a natural-language request and
1275
- have an LLM build → (auto-repair) → run a query against the inferred schema.
1276
-
1277
- ```bash
1278
- npm run cli # loads examples/data (users / orders / products)
1279
- npm run cli ./path/to/data # load a custom directory of *.json files
1280
- ```
1281
-
1282
- Each `*.json` file must hold a **JSON array of objects**. The Type name comes
1283
- from the filename: it is **singularized + capitalized** (`users.json`→`User`,
1284
- `orders.json`→`Order`, `categories.json`→`Category`). Files that aren't a JSON
1285
- array are skipped with a warning.
1286
-
1287
- The REPL needs an AI provider; set one of these (env vars, mirroring ginny):
1288
-
1289
- | Env var | Provider |
1290
- | -------------------- | ------------------------------------------------------- |
1291
- | `OPENAI_API_KEY` | OpenAI |
1292
- | `OPENROUTER_API_KEY` | OpenRouter |
1293
- | AWS credentials | AWS Bedrock (env vars / `aws sso login` / IAM role / …) |
1294
- | `QUERY_MODEL` | *(optional)* pin a specific model id |
1295
-
1296
- With no provider configured the CLI prints which env var to set and exits
1297
- cleanly (it never crashes). The REPL builds the tool at a tight default depth
1298
- (`refs: 'paired'`, `typeNames: 'enum'`, `functions: 'typed'`, `filters:
1299
- 'paired'`, with a `maxEnumSize` so large catalogs degrade gracefully). REPL
1300
- commands: `:types`, `:fns` (list callable functions by shape), `:depth <spec>`
1301
- (switch schema tightness at runtime — a preset like `:depth open` / `:depth
1302
- paired`, or per-axis `:depth functions=names refs=types`), `:sql` (toggle
1303
- emitting base + postgres SQL per query), `:data <dir>` (reload), `:help`,
1304
- `:exit`.
1305
-
1306
- ```text
1307
- @aeye/query CLI — data: .../examples/data
1308
-
1309
- Loaded Types:
1310
- Order (6 fields): id, userId, productId, total, status, createdAt
1311
- Product (4 fields): id, name, price, category
1312
- User (5 fields): id, name, age, email, city
1313
-
1314
- query> users in London ordered by name
1315
-
1316
- 2 row(s):
1317
- ┌─────────┬─────────────────┬──────────┐
1318
- │ (index) │ name │ city │
1319
- ├─────────┼─────────────────┼──────────┤
1320
- │ 0 │ 'Ada Lovelace' │ 'London' │
1321
- │ 1 │ 'Cleo Nguyen' │ 'London' │
1322
- └─────────┴─────────────────┴──────────┘
1323
- fields: name:text, city:text
1324
- ```
1325
-
1326
- Under the hood each request runs the package's LLM surface: `selectTypes`
1327
- narrows the schema when there are many Types, `buildQueryTool(engine).schema`
1328
- constrains the model's output, and the tool's custom `parse`
1329
- validates + parses it into a runnable `Query` — surfacing LLM-friendly
1330
- `Problems` (as a `QueryToolError`) that drive a single automatic repair round
1331
- before running.
1332
-
1
+ # @aeye/query
2
+
3
+ An **LLM-friendly relational query language**, in-memory runtime, and SQL
4
+ converter. You define *Types* (type-like entities) with *Fields*; from that an
5
+ LLM (or a developer) can build a **typed, validated, runnable** query — a
6
+ `select` / `insert` / `update` / `delete` / set-operation / CTE / single
7
+ expression. A built query resolves to an output type, has typed bind params,
8
+ can be cost-bounded, run in-memory, converted to SQL (base + Postgres),
9
+ auto-paginated, and **drilled down** (aggregate un-ravelling).
10
+
11
+ It is fully standalone (only depends on `zod`) and obsessively type-safe: no
12
+ `any`, no `unknown` in public APIs, no casts; every polymorphic node is a
13
+ discriminated union so handling is exhaustively checkable.
14
+
15
+ ```bash
16
+ npm install # from the monorepo root (workspace)
17
+ npm run typecheck # tsc --noEmit
18
+ npm test # vitest
19
+ npm run examples # runnable, end-to-end tour (examples/)
20
+ ```
21
+
22
+ ## The type / field model
23
+
24
+ A `Type` is a named collection of `Field`s plus index + cardinality estimates.
25
+ Each field has a `FieldType` (one of `number`, `text`, `money`, `bool`,
26
+ `relation`, `date`, `timestamp`, `json`, `array`); nullability lives on the
27
+ *field*, not the field type.
28
+
29
+ An `array` field is an ordered collection. It carries optional `minItems` /
30
+ `maxItems` element-count bounds and an optional `item` element field type
31
+ (omit `item` for heterogeneous / unknown elements). Because `item` is itself a
32
+ field type, arrays nest (`array<array<number>>`). `inferType` detects arrays
33
+ from sampled rows and infers the element type from homogeneous scalars.
34
+
35
+ ```ts
36
+ // array of text tags, 0–8 items
37
+ { name: 'tags', type: { kind: 'array', item: { kind: 'text' }, maxItems: 8 }, nullable: true }
38
+ ```
39
+
40
+ Relations carry a target Type and a cardinality `count`: a relation field's
41
+ **name is the join key** for all purposes — `count === 1` is belongs-to (the FK
42
+ lives on this type), `count > 1` is has-many. There are no explicit FK fields.
43
+ A belongs-to relation may set `inverseRelation` to have its target Type
44
+ automatically gain the matching has-many field pointing back. The join key on
45
+ either side resolves through each Type's *identity field* (the field of its
46
+ first unique single-field index, else the field named `id`).
47
+
48
+ A relation field can be **compared directly to a value** in `= <> in notIn`,
49
+ where the value is an object keyed by the target's **primary key** (single or
50
+ composite) — `{ kind: 'comparison', op: '=', left: relRef, right: { kind:
51
+ 'param', name: 'u' } }` with `:u = { id: 5 }` (a single-key relation also
52
+ accepts a bare scalar). A **belongs-to** matches its FK columns; a **has-many**
53
+ matches by **membership** — `= value` is a correlated `EXISTS` testing that the
54
+ value's key is in the related set (`<>` / `notIn` → `NOT EXISTS`). Two relations
55
+ of the same target compare by their FK key (`order.customer = invoice.customer`);
56
+ a has-many may not be compared to another relation. Ordering / LIKE on a relation
57
+ is rejected — a relation compares by identity, not order.
58
+
59
+ Indexes are **composite**: an ordered list of parts, each with a prefix
60
+ distinct-row `count` (non-increasing); the index is unique iff its last part's
61
+ `count === 1`. Text matching is governed by a text field's `casing`, else the engine's
62
+ `textCasing` default (`'fold'` unless you set it):
63
+
64
+ | `casing` | means | SQL for `a = b` | in-memory runtime |
65
+ |--------------|------------------------------------------------|-----------------------|-------------------|
66
+ | `'fold'` | case-INSENSITIVE, folded by the query | `LOWER(a) = LOWER(b)` | folds |
67
+ | `'collated'` | case-INSENSITIVE, folded by the COLUMN's collation | `a = b` | folds |
68
+ | `'exact'` | case-SENSITIVE | `a = b` | compares as-is |
69
+
70
+ `LOWER(col)` is not sargable, so `'fold'` costs every predicate over the column
71
+ its index — and on Postgres a column modelled as `text` may physically be a
72
+ `uuid`, where `LOWER()` does not exist at all. So set `textCasing: 'exact'` on
73
+ the engine for a schema of identifiers / codes / enums (`'collated'` when the
74
+ columns really do carry a case-insensitive collation, e.g. `citext`), and let
75
+ the individual columns that DO want folding say `casing: 'fold'` — a field's own
76
+ declaration always wins over the engine default. A Type may also be
77
+ flagged `semantic` / `search` to make it eligible for embedding similarity /
78
+ full-text search even when no individual field is flagged.
79
+
80
+ ```ts
81
+ import { createRegistry, QueryEngine, arrayExecutor, type TypeDef } from '@aeye/query';
82
+
83
+ const userDef: TypeDef = {
84
+ name: 'user',
85
+ fields: [
86
+ { name: 'id', type: { kind: 'number', whole: true } },
87
+ { name: 'name', type: { kind: 'text' } },
88
+ { name: 'age', type: { kind: 'number', whole: true }, nullable: true },
89
+ ],
90
+ // unique single-field index on `id` ⇒ `id` is the identity / join key.
91
+ indexes: [{ exprs: [{ expr: { kind: 'field-ref', source: 'user', field: 'id' }, count: 1 }] }],
92
+ count: 1000,
93
+ bytes: 64,
94
+ };
95
+
96
+ const orderDef: TypeDef = {
97
+ name: 'order',
98
+ fields: [
99
+ { name: 'id', type: { kind: 'number', whole: true } },
100
+ // belongs-to user; materializes `user.orders` (has-many) pointing back.
101
+ { name: 'userId', type: { kind: 'relation', to: 'user', count: 1, inverseRelation: 'orders' } },
102
+ ],
103
+ indexes: [{ exprs: [{ expr: { kind: 'field-ref', source: 'order', field: 'id' }, count: 1 }] }],
104
+ count: 5000,
105
+ bytes: 48,
106
+ };
107
+
108
+ const registry = createRegistry();
109
+ const user = registry.parseType(userDef);
110
+ const order = registry.parseType(orderDef);
111
+ registry.registerType(user);
112
+ registry.registerType(order);
113
+
114
+ const engine = new QueryEngine(registry, {
115
+ executors: { user: arrayExecutor(userRows) }, // wire data for in-memory runs
116
+ textCasing: 'exact', // default case policy for text columns that declare none
117
+ });
118
+ ```
119
+
120
+ You can also **infer** a `TypeDef` straight from raw JSON rows:
121
+
122
+ ```ts
123
+ import { inferType } from '@aeye/query';
124
+ const def = inferType('user', userRows); // field types + nullability inferred
125
+ ```
126
+
127
+ ## Build, validate, and run a query
128
+
129
+ A query is plain JSON (a `QueryDef`). Validate it to get LLM-friendly
130
+ `Problems`, then run it in-memory.
131
+
132
+ ```ts
133
+ const select = {
134
+ kind: 'select',
135
+ fields: [{ expr: { kind: 'field-ref', source: 'user', field: 'name' } }],
136
+ from: { kind: 'type', type: 'user' },
137
+ where: [{
138
+ kind: 'comparison', op: '>',
139
+ left: { kind: 'field-ref', source: 'user', field: 'age' },
140
+ right: { kind: 'literal', value: 30 },
141
+ }],
142
+ } as const;
143
+
144
+ const problems = engine.validateQuery(select); // structure + params + per-Type hooks
145
+ if (!problems.hasErrors) {
146
+ const result = await engine.run(select); // { rows, fields, outputType }
147
+ }
148
+ ```
149
+
150
+ ### Building expressions with `e.*`
151
+
152
+ Hand-writing the raw `ExprDef` JSON above gets verbose fast. The **`e.*`
153
+ builder** composes the same trees with terse, fully-typed function calls — and
154
+ each `e.*` returns a **real `Expr` instance** (the exact subclass), so it is
155
+ strictly more capable than a def factory:
156
+
157
+ ```ts
158
+ import { e } from '@aeye/query';
159
+
160
+ // e.eq(...) is a ComparisonExpr, e.and(...) a LogicalExpr, e.ref(...) a FieldRefExpr, …
161
+ const cond = e.and(
162
+ e.eq(e.ref('task', 'done'), e.value(true)),
163
+ e.gt(e.ref('task', 'hours'), e.value(0)),
164
+ );
165
+ ```
166
+
167
+ There is **one builder per expression kind**, grouped as: leaves (`value`/`lit`,
168
+ `param`, `ref`, `path`, `output`, `excluded`, `filters`), arithmetic
169
+ (`add`/`sub`/`mul`/`div`/`mod`, `neg`/`pos`), comparison
170
+ (`eq`/`neq`/`lt`/`lte`/`gt`/`gte`/`like`/`notLike`/`ilike`), logical
171
+ (`and`/`or`/`not`), predicates (`isNull`/`notNull`, `between`/`notBetween`,
172
+ `inList`/`notInList`, `inSubquery`/`notInSubquery`, `exists`/`notExists`), array
173
+ ops (`contains`/`containsAny`/`containsAll`/`isEmpty`/`notEmpty`), `case`/`when`,
174
+ calls (`fn`, `agg`/`count`/`countStar`/`sum`/`avg`/`min`/`max`, `window`,
175
+ `tableFn`), `subquery`, and search (`textSearch`, `semantic`). Every function is
176
+ also a named export (`import { eq, and, ref } from '@aeye/query'`).
177
+
178
+ **Run or emit a built expr standalone** — the engine normalizes either an `Expr`
179
+ or a raw `ExprDef`:
180
+
181
+ ```ts
182
+ // Evaluate against a row (defaults to an empty row for constant predicates):
183
+ const v = await engine.evaluateExpr(e.gt(e.ref('task', 'hours'), e.value(0)), {
184
+ task: { hours: 5 },
185
+ }); // Value(true)
186
+
187
+ // Emit SQL + ordered bind params for a dialect (params never interpolated):
188
+ const { sql, params } = engine.exprToSQL(cond, 'postgres');
189
+ // sql: ("task"."done" = $1 AND "task"."hours" > $2)
190
+ // params: [true, 0]
191
+ ```
192
+
193
+ **Embed a built expr into a query** via `.toJSON()` — a query def's `where` /
194
+ `order` / field slots are `ExprDef`, and `.toJSON()` is the free wire form:
195
+
196
+ ```ts
197
+ const select = {
198
+ kind: 'select',
199
+ fields: [{ expr: e.ref('user', 'name').toJSON() }],
200
+ from: { kind: 'type', type: 'user' },
201
+ where: [e.gt(e.ref('user', 'age'), e.value(30)).toJSON()],
202
+ } as const;
203
+ ```
204
+
205
+ `registry.parseExpr` is a **pass-through** for an already-built `Expr`, so built
206
+ and parsed exprs compose freely.
207
+
208
+ ### Sources & aliasing
209
+
210
+ Every source is referenced by its **type name** — there is no alias to invent or
211
+ keep in sync:
212
+
213
+ - **FROM.** `from: { kind: 'type', type: 'user' }` binds under `source: 'user'`.
214
+ - **Joins.** A join crosses a **single relation field** — `on` is a
215
+ `{ kind: 'relation', source, field, as }` ref
216
+ (`{ on: { kind: 'relation', source: 'user', field: 'orders', as: 'order' } }`):
217
+ the bound source to join FROM, its relation field, and the **required alias**
218
+ the joined rows bind under (field-refs into them then use `source: 'order'`).
219
+ **Multi-hop** joins are expressed as **chained** single-hop joins, and reading a
220
+ value across a relation is a join + a plain `{ source, field }` field-ref (there
221
+ is no separate relation-path expr). The relation key is synthesized — you never
222
+ write ON. A join can also add a **fresh source** — `on` may instead be a
223
+ `type` / `aliased` / `subquery` / `function` source, with `and` as its ON (a
224
+ manual join). `joinType` (freeing `type` for the Type-name rule) defaults to
225
+ `left`.
226
+ - **DML.** `update` / `delete` / `insert` target a type by name (`type` / `from`
227
+ / `into`) and bind it under that name — DML targets take no alias.
228
+
229
+ When you need a distinct binding — a **self-join**, or **two instances of the
230
+ same Type** — reach for the `aliased` escape hatch on a FROM source
231
+ (`{ kind: 'aliased', type: 'user', as: 'u1' }`) or set `as` on a join to override
232
+ the bound name of its hop (`{ on: { source: 'u1', field: 'orders' }, as: 'o1' }`).
233
+ The `as` on a join is the **collision-breaker**.
234
+
235
+ > **The `type` vs `source` rule.** `type` is used only where the value MUST be a
236
+ > registered Type name (FROM `type`, DML `into` / `type` / `from`, relation `to`,
237
+ > a semantic query's `{ type, field }`); `source` is a **bound** name in the
238
+ > query's scope (a Type name, a join alias, a CTE, an aliased source) — used by
239
+ > `field-ref`, `semantic` / `text-search` / `filters`, and a join's `on.source`.
240
+
241
+ If two sources end up bound under the same name — two joins landing on one target
242
+ type, or a join hop rebinding the FROM / DML target type — the engine reports a
243
+ `source.duplicate` validation error pointing you at the `aliased` form (or a join
244
+ `as`) to disambiguate.
245
+
246
+ > **Known limitation.** A self-referential DML that would need two instances of
247
+ > its target type (e.g. an `UPDATE user` joined back to `user` via its relations,
248
+ > whose hop rebinds `user`) currently errors with `source.duplicate`; an
249
+ > aliased-DML target mechanism is a deferred follow-up.
250
+
251
+ ### Output references (`groupBy` / `orderBy` / `having`)
252
+
253
+ A SELECT's `groupBy`, `order`, and `having` can reference a **projected output
254
+ field by name** instead of repeating its expression — via
255
+ `{ kind: 'output', name }`. The `name` is the output's `as`, or its natural
256
+ derived name (a field-ref's field, an aggregate's function name). The reference **EXPANDS to** (delegates to) the
257
+ referenced select item's expression: the SQL emits the target's SQL (portable
258
+ across dialects, in every clause), and the runtime re-evaluates the target — so
259
+ a group key re-computes over the source row while an ORDER BY / HAVING ref
260
+ re-computes over the group (including an aggregate target). This keeps queries
261
+ smaller and removes a whole class of GROUP BY / ORDER BY mismatches.
262
+
263
+ ```ts
264
+ // Revenue per user, grouped + ordered by output name — the `sum` / `userId`
265
+ // expressions are written ONCE, in `fields`.
266
+ const revenuePerUser = {
267
+ kind: 'select',
268
+ fields: [
269
+ { expr: { kind: 'field-ref', source: 'order', field: 'userId' }, as: 'userId' },
270
+ { expr: { kind: 'aggregate', function: 'sum', args: { value: { kind: 'field-ref', source: 'order', field: 'total' } } }, as: 'revenue' },
271
+ ],
272
+ from: { kind: 'type', type: 'order' },
273
+ groupBy: [{ kind: 'output', name: 'userId' }], // ← by output name, not the expr
274
+ having: [{ kind: 'comparison', op: '>', left: { kind: 'output', name: 'revenue' }, right: { kind: 'literal', value: 100 } }],
275
+ order: [{ expr: { kind: 'output', name: 'revenue' }, dir: 'desc' }],
276
+ } as const;
277
+ ```
278
+
279
+ It is valid **only** in those three clause positions — in WHERE, a join `on`, or
280
+ any general expression argument (where no outputs are bound) it fails validation
281
+ with `output.not-available`. An unknown name reports `output.unknown`, and using
282
+ one as a GROUP BY key whose target is an aggregate reports `output.aggregate`
283
+ (you cannot group BY an aggregate). The LLM schema offers `output` in exactly
284
+ those `groupBy` / `orderBy` / `having` positions and nowhere else. `drillDown`
285
+ expands any `output` references against the original projection before it
286
+ un-ravels the aggregates, so a drilled query never dangles.
287
+
288
+ ## Write model & permissions
289
+
290
+ Types and fields declare **what write operations are possible**, and that flows
291
+ into BOTH validation AND the LLM-facing schema — so the generated schema never
292
+ offers a write the engine would reject.
293
+
294
+ - **Type permissions.** `insertable` / `updatable` / `deletable` on a `TypeDef`
295
+ (each default **true**). A restricted Type is rejected by validation
296
+ (`insert.type-readonly` / `update.type-readonly` / `delete.type-readonly`), the
297
+ schema **drops the DML kind** when no Type permits it, and each DML's
298
+ target-name enum is filtered (`into` → insertable, `update.type` → updatable,
299
+ `delete.from` → deletable).
300
+ - **Field permissions.** `insertable` / `updatable` on a `FieldDef` (default
301
+ **true**). A **computed** field (`FieldBacking.compute`) defaults to
302
+ `insertable:false, updatable:false` (override with an explicit flag).
303
+ Validation rejects a listed non-insertable field (`insert.field-readonly`) / an
304
+ assigned non-updatable field (`update.field-readonly`); the paired schema
305
+ offers only insertable `fields` / updatable `set` fields.
306
+ - **Insert-requiredness (one rule).** A field is REQUIRED on insert iff it is
307
+ **insertable AND non-nullable AND has no default AND is not computed** —
308
+ otherwise optional or excluded. A shared `requiredOnInsert` helper drives both
309
+ the schema (required-vs-optional in paired mode) and validation
310
+ (`insert.missing-required`, listing the missing names).
311
+ - **Defaults live on the backing.** `FieldBacking.default` is a `Value` or a
312
+ factory `() => Value | Promise<Value>` — its presence alone makes the field
313
+ optional-on-insert (no `hasDefault` flag). At **runtime** an omitted defaulted
314
+ field is materialized (value evaluated / factory awaited, per row) into the
315
+ record; in **SQL** the column is left out of the INSERT so the DB's own column
316
+ `DEFAULT` fills it (a JS-factory default is runtime-only).
317
+ - **Per-field expr restrictions.** `FieldDef.exprs` = `{ not: ExprKind[] }` or
318
+ `{ only: ExprKind[] }` NARROWS which expr kinds may target the field (never
319
+ enables one the field TYPE disallows). `field.allowsExpr(kind)` respects both.
320
+ Validation reports `field.expr-denied` at the use site — a standalone
321
+ `field-ref`, a gating operator's DIRECT field-ref operand (`comparison` /
322
+ `between` / `in` / `is-null` / `array-op`), and the field-naming exprs
323
+ (`text-search` / `text-score` / `semantic` / `filters`). The paired schema
324
+ omits an excluded field from the relevant enum, and gates a kind away entirely
325
+ when every candidate field excludes it.
326
+
327
+ ```ts
328
+ const doc: TypeDef = {
329
+ name: 'doc', count: 1000, bytes: 256,
330
+ fields: [
331
+ { name: 'id', type: { kind: 'text' } }, // required on insert
332
+ { name: 'title', type: { kind: 'text' } }, // required
333
+ { name: 'views', type: { kind: 'number' }, updatable: false }, // write-once
334
+ { name: 'notes', type: { kind: 'text' }, nullable: true }, // optional
335
+ ],
336
+ };
337
+ // `createdAt` is optional-on-insert (has a default) and materialized at runtime.
338
+ const backing: TypeBacking = {
339
+ fields: { createdAt: { default: () => Value.of(new Date().toISOString()) } },
340
+ };
341
+ ```
342
+
343
+ ## Execution model
344
+
345
+ There is ONE execution contract: **run a query, optionally with param values
346
+ and filters, and get back `{ rows, fields, total }`**.
347
+
348
+ ```ts
349
+ const result = await engine.run(query, { params, filters, includeTotal });
350
+ // result.rows — the output rows (objects; pass { rows: 'array' } for arrays)
351
+ // result.fields — resolved output fields (name + type + summary metadata)
352
+ // result.total — pre-limit row count, when run with `includeTotal: true`
353
+ ```
354
+
355
+ Each field's `type` is the full `ResolvedType`. A **computed** one carries
356
+ `aggregate` (does a group collapse happen anywhere in this expression?) and
357
+ `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS
358
+ one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'`
359
+ under any alias; `max(a) - min(b)` reports `aggregate: true` with NO
360
+ `aggregateFn` (it contains aggregates but is none); a window over an
361
+ aggregate-shaped function reports neither. Read it rather than inferring the
362
+ function from the output column NAME, which cannot see through an alias and
363
+ mistakes `hours * 2 as count` for an aggregate.
364
+
365
+ Everything composes around that one call:
366
+
367
+ - **Params.** A `param` (`{ kind: 'param', name }`) infers its type from how it
368
+ is used and is bound at run time via `options.params`. Introspect what a built
369
+ query expects with `query.params(engine)` → `ParamDef[]` (name + inferred
370
+ type).
371
+
372
+ It reports every param the statement binds **at any depth**, so what it
373
+ declares is always enough to bind the emitted SQL. That includes a
374
+ `limit` / `offset` bound, which lives outside the walked expr tree: on the
375
+ statement itself, on a **`cte`'s `final`** (where `autoPaginate` puts it), on a
376
+ set-operation **arm** or its set-level bound, and inside a FROM / `in` /
377
+ `exists` subquery or an `insert … select` source. An under-reported bound is
378
+ not a cosmetic gap — the SQL still emits `LIMIT ?` and a caller that binds the
379
+ declared signature leaves it NULL, which Postgres reads as *no limit*.
380
+
381
+ A param's type is the **meet** of every use — the most specific type
382
+ compatible with all of them, folded through `FieldType.meet`. Compared against
383
+ an `enum` in one place and plain `text` in another it is the **enum**;
384
+ `text{minLength:5}` beside `text{maxLength:10}` carries **both** bounds;
385
+ `number` beside `money` is `money`. The meet is commutative, associative,
386
+ idempotent and **sound** (it accepts nothing that both operands do not), so the
387
+ answer never depends on where in the JSON each use sits. Where the uses have no
388
+ meet the param is in **conflict** (`param.conflict`) and `params()` omits it.
389
+
390
+ It is the *greatest* lower bound for every type built from a **def** —
391
+ `x ⊓ ⊤ = x` holds for anything `parseType` / `parseFieldType` can produce. A
392
+ closed set IS the value schema, so a meet narrows a merged set by the merged
393
+ scalar constraints, and for a self-inconsistent type
394
+ (`text{values:['ab'], minLength:5}`, whose own bound rejects its own member)
395
+ even `x ⊓ text` narrows or conflicts. Since `0.6.6` that declaration is
396
+ **refused at parse time** (`field-type.bad-values`) rather than tolerated, so
397
+ the exception is gone from the def road. The public **constructors** do not
398
+ validate — `new TextFieldType({ values: [{ value: 'ab' }], minLength: 5 })` is
399
+ still buildable, and for one of those the meet is a lower bound only, exactly
400
+ as an uncompilable `pattern` is still constructible by hand. Soundness is kept
401
+ unconditionally on both roads, because it is the law a validator actually
402
+ depends on.
403
+
404
+ `engine.parameters(query)` → `ParamInfo[]` is the detailed view: per param,
405
+ every `use` (`{ at, type, category, field? }` — path, required type, category
406
+ summary, and the column the requirement came from), the merged `type`, and the
407
+ `conflict` when there is none. `engine.checkParams(query, params)` →
408
+ `Problems` checks SUPPLIED values against that merged type before execution
409
+ (`param.value` / `param.missing` / `param.unknown`); `null` always passes, and
410
+ the same check rides on `validateQuery(query, _, _, { params })`.
411
+ - **Filters.** `options.filters` is a `Record<source, ExprDef | Expr | null>` —
412
+ a single **boolean Expr** per source (or `null` / absent for none). The
413
+ `filters` EXPR in the query is only a placeholder (`{ source, fields? }`); the
414
+ predicate is supplied here, keyed by source, and the placeholder evaluates /
415
+ emits it (vacuously `TRUE` when none is supplied). Introspect which sources a
416
+ built query exposes — and the fields each offers — with
417
+ `query.filters(engine)` → `Record<source, { fields: QueryField[] }>` (each
418
+ field is name + resolved type + nullability + field-type kind, restricted to
419
+ the placeholder's `fields` allowlist when it sets one). Build the per-source
420
+ bool Expr however you like — e.g. a `comparison` / `logical` `ExprDef`, or one
421
+ produced by your own filter-builder UI. `query.filterSources()` still lists the
422
+ sources a filter may target; an unknown source or field is a `QueryTypeError`.
423
+ - **Total count.** `includeTotal: true` is an **execution-time** option (NOT a
424
+ `SelectDef` field): `run` captures the pre-limit count into `result.total`,
425
+ and `toSQL(query, dialect, { includeTotal: true })` emits
426
+ `COUNT(*) OVER () AS "$total"`.
427
+
428
+ It applies to the **ENTRY query only** — never a CTE body, a set-operation
429
+ arm, or a FROM subquery. `$total` is a PROJECTED column, so an arm that
430
+ carried it would take part in the set comparison and change the **rows**:
431
+ `UNION` would stop de-duplicating, and `INTERSECT` / `EXCEPT` would compare
432
+ per-arm counts they were never meant to see. A query whose entry is a **set
433
+ operation therefore reports no total at all** (`result.total` is `undefined`;
434
+ the SQL carries no `$total`) rather than a wrong one — both engines agree.
435
+ To page a set operation *and* count it, wrap it in a SELECT and count there:
436
+
437
+ ```ts
438
+ const counted = {
439
+ kind: 'select',
440
+ fields: [{ expr: { kind: 'field-ref', source: 's', field: 'id' } }],
441
+ from: { kind: 'subquery', as: 's', query: theUnion },
442
+ limit: 20,
443
+ } satisfies SelectDef;
444
+ await engine.run(counted, { includeTotal: true }); // → { rows, total }
445
+ ```
446
+ - **Pagination.** `autoPaginate` adds `limit` / `offset` as bind PARAMS, so
447
+ pagination is just supplying their values:
448
+
449
+ ```ts
450
+ import { autoPaginate } from '@aeye/query';
451
+ const paged = autoPaginate(select); // adds { limit: param('limit'), offset: param('offset') }
452
+ paged.params(engine); // → [{ name:'limit', type:{kind:'number'} }, { name:'offset', … }]
453
+ await engine.run(paged, { params: { limit: 10, offset: 0 } });
454
+ ```
455
+
456
+ It pages exactly the kinds that HAVE a row bound: a **`select`** (its own
457
+ LIMIT / OFFSET), a **set operation** (`union` / `intersect` / `except` — the
458
+ SET-LEVEL bound over the combined rows, never an arm's, since paging an arm
459
+ would change which rows the set operation compares), and a **`cte`**, which is
460
+ paged through its `final` query (a CTE body is an intermediate result). Every
461
+ other kind — `insert` / `update` / `delete` / `expr` — has no bound to bind and
462
+ **throws** `QueryTypeError` with code `paginate.unsupported-kind`. Ask first
463
+ with `canAutoPaginate(query)` when you hold an arbitrary `QueryDef`.
464
+
465
+ - **Drill-down.** `drillDownInto` rebuilds the underlying-rows query and extracts
466
+ the drill PARAMS from a chosen aggregated row — then it is the same `run` call
467
+ with those params (see [Drill-down](#drill-down)).
468
+
469
+ `toSQL` accepts the same `params` and `filters` options and emits them
470
+ identically, so emitted SQL matches what would run.
471
+
472
+ ## SQL conversion
473
+
474
+ The same query emits SQL for any registered dialect. The base dialect uses `?`
475
+ placeholders; Postgres uses `$1`, `$2`, … . Relation joins synthesize their ON
476
+ clause from the relation key — you never write it.
477
+
478
+ ```ts
479
+ const base = engine.toSQL(select, 'base'); // { sql, params }
480
+ const pg = engine.toSQL(select, 'postgres', { params: { minTotal: 50 } });
481
+ ```
482
+
483
+ ## Type backing & Access / Computed
484
+
485
+ The conceptual model the LLM sees — a `TypeDef`'s flat list of fields — can be
486
+ **arbitrarily richer behind the scenes**. A `TypeBacking` is plain dev-side
487
+ TypeScript you register *alongside* the Type (`registry.registerType(type,
488
+ backing)`, or `new QueryEngine(registry, { backings })`); the JSON `TypeDef` /
489
+ `FieldDef` are **never touched**, so the schema stays minimal. A backing can
490
+ remap the real source table, compute fields, auto-join other Types, gate
491
+ rows / fields, and point full-text / semantic search at hidden physical fields —
492
+ all resolved IDENTICALLY in `engine.run` and `engine.toSQL`.
493
+
494
+ Two primitives compose everything. Each offers a dual `expr` path plus per-mode
495
+ overrides — **SQL** resolves `sql` then `expr`; the **runtime** resolves `run`
496
+ then `expr`. Every factory (`expr` / `sql` / `run`) is handed the **`alias` the
497
+ Type is bound under for this occurrence** and MUST use it for every reference
498
+ (never hardcode the Type name) — so when a Type is aliased (multiple joins to the
499
+ same Type, a self-join, an `{kind:'aliased'}` FROM) the references resolve to the
500
+ correct source:
501
+
502
+ - **`Access`** — a security *predicate*. It resolves to a predicate `Expr`
503
+ (apply it), `true` (visible), `false` (denied), or `undefined` (no-op).
504
+ - **`Computed`** — a field *value* producer (replaces the stored column). It
505
+ always yields a value.
506
+
507
+ ```ts
508
+ const backing: TypeBacking = {
509
+ name: 'projects', // real table ⇒ FROM "projects" AS "project"
510
+ access: { /* RLS — see below */ },
511
+ joins: { /* named hidden joins — see below */ },
512
+ fields: { /* per-field compute / access / remap */ },
513
+ };
514
+ registry.registerType(project, backing); // the TypeDef the LLM sees is unchanged
515
+ ```
516
+
517
+ `examples/11-computed-fields.ts` is the end-to-end demo: one simple `project`
518
+ Type backed by `projects` + `users` + `tasks`, run in-memory AND emitted to SQL.
519
+
520
+ ## Computed fields
521
+
522
+ A `FieldBacking.compute` supplies a field's value. The primary path is a dual
523
+ `expr` (one `Expr` both emitted to SQL and evaluated in memory); `sql` / `run`
524
+ override per mode. A bare `name` just remaps the stored column.
525
+
526
+ ```ts
527
+ fields: {
528
+ // dual expr: the auto-joined owner's name (one definition, both modes). Read
529
+ // the named join off the BOUND `alias` with `e.ref`, never a literal type name.
530
+ ownerName: { joins: ['owner'], compute: { expr: (alias) => e.ref(joinAlias(alias, 'owner'), 'name') } },
531
+
532
+ // per-mode override: format money in SQL one way, in memory another. Both use
533
+ // the bound `alias` (`row[alias]`), never a hardcoded key.
534
+ budgetLabel: { compute: {
535
+ sql: (alias, ctx) => SqlText.concat([SqlText.raw("'$' || "), ctx.dialect.field(alias, 'budget')]),
536
+ run: (alias, row) => Value.of(`$${row[alias]?.['budget'] ?? 0}`),
537
+ } },
538
+
539
+ legacyNote: { name: 'note' }, // remap: read the stored `note` column
540
+ }
541
+ ```
542
+
543
+ Compute / access exprs that reach into other sources flow through the join
544
+ planner, so two fields reading the **same** auto-join collapse to ONE join.
545
+
546
+ ## RLS & FLS
547
+
548
+ Same `Access` primitive, two scopes — both apply in `run` AND `toSQL`:
549
+
550
+ - **RLS** (`TypeBacking.access`) — a row filter for every occurrence of the
551
+ Type. A predicate is ANDed into the SQL `WHERE` and filters executor rows on
552
+ load; `false` ⇒ no rows (`WHERE FALSE`); `true` / `undefined` ⇒ no filter.
553
+ Combines (AND) with any `RlsProvider` passed to `run` / `toSQL`.
554
+ - **FLS** (`FieldBacking.access`) — a per-field gate. A predicate emits
555
+ `CASE WHEN <pred> THEN <value> ELSE NULL END` (nulled in memory when false);
556
+ `false` ⇒ a constant `NULL`; `true` / `undefined` ⇒ the plain value.
557
+
558
+ ```ts
559
+ // RLS: only the current org's rows (orgId is NOT a conceptual field — pure backing).
560
+ access: { expr: (alias) => e.eq(e.ref(alias, 'orgId'), e.value(currentOrg)) },
561
+
562
+ // FLS: `secretField` is visible only for active projects, reading stored `secret`.
563
+ secretField: { name: 'secret', access: { expr: (alias) => e.eq(e.ref(alias, 'status'), e.value('active')) } },
564
+ ```
565
+
566
+ ## Default conditions (soft scope)
567
+
568
+ `TypeBacking.defaultConditions` is a **soft, suppressible** default scope —
569
+ archived / soft-delete filtering the query can **reveal past**, unlike RLS. Each
570
+ `DefaultCondition` is `{ where, without?, ops?, description? }`:
571
+
572
+ - **`where`** — an `Access` predicate (dual `{ expr }` / `sql` / `run`, resolved
573
+ exactly like RLS: `false` ⇒ no rows, `true` / `undefined` ⇒ no filter, else
574
+ ANDed) applied while the condition is **active**, per bound occurrence.
575
+ - **`without`** — referencing any of these fields **on that source** in a
576
+ **condition position** (the query's `where` / `having`, or a JOIN's `and`)
577
+ **lifts** the scope for that source. A reference in a select item / ORDER BY /
578
+ GROUP BY does **not** lift it, and each bound alias (incl. a self-join) is
579
+ decided independently. Omitted ⇒ derived from the fields `where.expr` reads (a
580
+ `sql`/`run`-only `where` with no `without` is then **always-on** — set it
581
+ explicitly to make it liftable).
582
+ - **`ops`** — which row-filtering ops it scopes (default
583
+ `['select', 'update', 'delete']`; **INSERT is never scoped**).
584
+ - **`description`** — an optional terse LLM-facing note (else auto-summarized in
585
+ `describeType`).
586
+
587
+ RLS still always applies and is **never** suppressed; a default condition ANDs in
588
+ alongside it.
589
+
590
+ ```ts
591
+ // Archived files: every query is scoped to `archivedAt IS NULL`…
592
+ defaultConditions: [{ where: { expr: (alias) => e.isNull(e.ref(alias, 'archivedAt')) } }],
593
+
594
+ // …until a query FILTERS on `archivedAt` (e.g. WHERE archivedAt IS NOT NULL),
595
+ // which lifts the scope for that source and reveals the archived rows.
596
+ ```
597
+
598
+ ## Default ordering
599
+
600
+ `TypeBacking.defaultOrder` declares a Type's **natural sort** — the `ORDER BY` a
601
+ SELECT gets when it specifies **none** (and ordering is meaningful). A
602
+ `DefaultOrder` is `{ by: DefaultOrderTerm[]; applyTo? }`; each `DefaultOrderTerm`
603
+ is `{ by: Computed; dir?; nulls? }` whose `by` is the sort **key** — the same
604
+ dual `{ expr }` / `sql` / `run` `Computed` computed fields use, so one key
605
+ **emits to SQL and sorts in memory identically** (`dir` default `'asc'`; `nulls`
606
+ else direction-based — asc ⇒ nulls first, desc ⇒ last — matching an explicit
607
+ ORDER BY).
608
+
609
+ It applies only when the **FROM** binds the backed Type (joins never contribute
610
+ their default order), the query has **no explicit `order`**, and it is **not
611
+ aggregated** (no `groupBy`, no bare aggregate) and **not `DISTINCT`** — both are
612
+ skipped (a base-field order is meaningless post-aggregation; a non-selected
613
+ DISTINCT key is illegal SQL).
614
+
615
+ `applyTo` scopes **which** selects receive it:
616
+
617
+ - **`'result'`** (default) — the **root** query being run/emitted, **or** any
618
+ `LIMIT`/`OFFSET` select.
619
+ - **`'paginated'`** — only a `LIMIT`/`OFFSET` select.
620
+ - **`'all'`** — every eligible select over the Type (incl. subqueries / CTEs).
621
+
622
+ The root is tracked by an `isRoot` marker threaded from `engine.run` /
623
+ `engine.toSQL` onto the runtime / SQL context; nested queries (a subquery /
624
+ EXISTS / IN subquery, a FROM subquery, a CTE body, a set-op branch) run and emit
625
+ **non-root**. SELECT-only — DML is never reordered.
626
+
627
+ ```ts
628
+ // Newest-first by default: an unsorted SELECT over the Type gets
629
+ // `ORDER BY "t"."createdAt" DESC`.
630
+ defaultOrder: { by: [{ by: { expr: (alias) => e.ref(alias, 'createdAt') }, dir: 'desc' }] },
631
+ ```
632
+
633
+ ## Named joins & LATERAL
634
+
635
+ `TypeBacking.joins` declares **named, hidden** joins; a field opts in via
636
+ `FieldBacking.joins: [name]`. Each join is added to a query **once, only if a
637
+ referencing field is emitted**, and deduped by name — so N fields sharing one
638
+ join collapse to a single planned join (its alias is `joinAlias(source, name)`).
639
+ A `JoinSpec` is either a `relation` (reuses the shared relation-join machinery)
640
+ or a `lateral` (a correlated sub-select):
641
+
642
+ ```ts
643
+ joins: {
644
+ // a belongs-to relation auto-join (shared by every field reading the owner).
645
+ owner: { expr: (alias) => ({ kind: 'relation', source: alias, relation: 'owner' }) },
646
+
647
+ // a LATERAL aggregate over a has-many — `taskCount` + `totalHours` share it.
648
+ // The lateral correlates via `outer` (the planner passes this backed Type's
649
+ // bound alias to `query`); the inner FROM (`task`) is its own scope.
650
+ taskStats: { expr: (alias) => ({ kind: 'lateral', joinType: 'left',
651
+ query: (outer) => ({ kind: 'select',
652
+ fields: [
653
+ { expr: e.countStar().toJSON(), as: 'cnt' },
654
+ { expr: e.sum(e.ref('task', 'hours')).toJSON(), as: 'hrs' },
655
+ ],
656
+ from: { kind: 'type', type: 'task' },
657
+ where: [e.eq(e.ref('task', 'projectId'), e.ref(outer, 'id')).toJSON()] }) }) },
658
+ }
659
+ ```
660
+
661
+ A `lateral`'s `pick` names the column a no-`compute` field defaults to. Postgres
662
+ emits `LEFT JOIN LATERAL (…) ON true`; the portable base dialect degrades to
663
+ `LEFT JOIN LATERAL (…) ON 1 = 1` (a documented correlated-subquery fallback) and
664
+ the runtime evaluates the sub-select per outer row.
665
+
666
+ ## Relation-join backing (physical FK columns / custom ON)
667
+
668
+ By default a relation join's `ON` is synthesized from the relation field's
669
+ **name** convention (`source.<local> = target.<foreign>`). `FieldBacking.relation`
670
+ (on a relation-typed field only) overrides that with **explicit, LLM-hidden
671
+ physical foreign-key columns** — the conceptual `FieldDef` / `TypeDef` the model
672
+ sees never change.
673
+
674
+ ```ts
675
+ const backing: TypeBacking = {
676
+ fields: {
677
+ // `comment_rating.user` belongs-to `user`; the hidden physical FK is `user_id`.
678
+ user: { relation: { keys: [{ local: 'user_id', foreign: 'id' }] } },
679
+ },
680
+ };
681
+ // A user's ratings (the materialized inverse has-many) then emits
682
+ // … LEFT JOIN "comment_rating" ON "user"."id" = "comment_rating"."user_id"
683
+ // and the belongs-to direction emits the mirror `ON "comment_rating"."user_id" = "user"."id"`.
684
+ ```
685
+
686
+ - **`keys: [{ local, foreign? }]`** — physical key-column pairs, **all ANDed**
687
+ (composite FKs: `keys: [{ local: 'a_id', foreign: 'a' }, { local: 'b_id',
688
+ foreign: 'b' }]` ⇒ `ON src.a_id = tgt.a AND src.b_id = tgt.b`). `local` is the
689
+ column on the side that **declares** the relation; `foreign` is the column on
690
+ the **target** and defaults to the target's identity field.
691
+ - **The backing lives on the owning belongs-to relation.** A materialized inverse
692
+ has-many **reuses the same FK** (its forward relation's backing, orientation
693
+ swapped) — you declare it once.
694
+ - **`on`** — a fully custom, alias-correct `ON` (overrides `keys`). `{ expr }` is
695
+ the dual path (one predicate emitted to SQL **and** evaluated in memory); `sql`
696
+ / `run` are per-mode overrides. Each factory receives the two **bound aliases**
697
+ (`localAlias` = the declaring side, `joinedAlias` = the target), so
698
+ aliased / self-joins resolve.
699
+
700
+ Every ON site honors the backing — authored relation joins (value + at runtime),
701
+ the `TypeBacking.joins` relation spec, and joined UPDATE/DELETE — so SQL and the
702
+ in-memory runtime always agree. `JoinDef.and`
703
+ is still ANDed onto whatever `ON` the backing produces. With no backing the
704
+ convention is used unchanged (fully backward-compatible).
705
+
706
+ ## Filters and params
707
+
708
+ A `filters` expression is an **LLM-opaque placeholder** bound to a source, with
709
+ an optional `fields` allowlist — `{ kind: 'filters', source, fields? }`. The LLM
710
+ never authors the predicate. At **execution time** the developer supplies a
711
+ single **boolean `Expr` / `ExprDef`** per source (keyed by source); the
712
+ placeholder evaluates / emits it, vacuously `TRUE` when none is supplied.
713
+
714
+ Introspect what a built query exposes with `query.filters(engine)`: it returns
715
+ `Record<source, { fields: QueryField[] }>` — for every `filters` placeholder,
716
+ its bound source mapped to the fields available on it (each with name, resolved
717
+ type, nullability, and field-type kind), restricted to the placeholder's
718
+ `fields` allowlist when set. A UI renders controls from that, then supplies the
719
+ resulting bool `Expr` at run time.
720
+
721
+ ```ts
722
+ // In the query: just a placeholder + an allowlist (no predicate).
723
+ where: [{ kind: 'filters', source: 'product', fields: ['category', 'price'] }]
724
+
725
+ // Introspect the exposed source → fields.
726
+ const exposed = engine.registry.parseQuery(select).filters(engine);
727
+ // → { product: { fields: [{ name:'category', … }, { name:'price', … }] } }
728
+
729
+ // At run time: supply ONE bool ExprDef per source (built however you like — here
730
+ // with the `e.*` builder, whose `.toJSON()` is the wire `ExprDef`).
731
+ const productFilter: ExprDef = e.and(
732
+ e.eq(e.ref('product', 'category'), e.value('hardware')),
733
+ e.gte(e.ref('product', 'price'), e.value(30)),
734
+ ).toJSON();
735
+ await engine.run(select, { filters: { product: productFilter } });
736
+ ```
737
+
738
+ ## Semantic & text search
739
+
740
+ Both are bound to a **source** with an OPTIONAL `field` (omit to target the
741
+ whole source):
742
+
743
+ - **`semantic`** — `{ kind: 'semantic', source, field?, query }` scores a row's
744
+ embedding against `query`, which is a literal string, a `param`, a
745
+ `{ source, field }` ref to ANOTHER **bound** source + semantic field (the
746
+ cross-source **pairing** form), or a `{ type, field }` ref that resolves to the
747
+ single bound source of that Type. The source/field must be semantic-eligible (a
748
+ Type flagged `semantic`, or a `semantic`/`search` text field). Requires an
749
+ embedder.
750
+ - **`text-search`** — `{ kind: 'text-search', source, field?, query }` is a
751
+ full-text **predicate** (a boolean); `query` is a literal string or a `param`.
752
+ Whole-source search needs a searchable Type; a narrowed `field` must be a text
753
+ field.
754
+ - **`text-score`** — `{ kind: 'text-score', source, field?, query }` is the
755
+ numeric **relevance** counterpart of `text-search` (same eligibility). It
756
+ resolves to a **number** — usable in SELECT + ORDER BY — so "top N by text
757
+ relevance" works. Postgres emits `ts_rank`; the base (ANSI) dialect degrades to
758
+ a numeric `0/1` match. Build it with `e.textScore(source, query, field?)`.
759
+
760
+ ```ts
761
+ { kind: 'semantic', source: 'doc', field: 'body', query: 'quarterly revenue' }
762
+ { kind: 'semantic', source: 'doc', query: { source: 'topic', field: 'label' } } // pairing
763
+ { kind: 'text-search', source: 'user', field: 'email', query: 'ada' }
764
+ { kind: 'text-score', source: 'doc', field: 'body', query: 'revenue' }
765
+ ```
766
+
767
+ In the LLM schema these participate in **depth** like field-refs: at `paired`
768
+ the `source` is a Type and the `field` enum is restricted to that Type's
769
+ semantic / text fields.
770
+
771
+ ### Scoring & ranking — pairing + text relevance
772
+
773
+ Both `semantic` (pairing) and `text-score` produce a **number** you can put in
774
+ SELECT and `ORDER BY … DESC LIMIT N`, so a query returns the top-N by relevance.
775
+
776
+ - **Cross-Type semantic pairing.** Join (or cross-join) two Types so BOTH are
777
+ bound, then score one against the other's embedding. `toSQL` emits the
778
+ dialect's `similarity` over BOTH bound aliases' vectors (each side's hidden
779
+ `SemanticBacking.vectorField` if backed, else the default `<alias>."embedding"`
780
+ fragment), so a self-pairing of two aliases of ONE Type works too:
781
+
782
+ ```sql
783
+ -- FROM paper JOIN topic … , fields: [ id, semantic(paper, {source:'topic',field:'label'}) as score ]
784
+ SELECT "paper"."id", (1 - ("paper"."emb" <=> "topic"."embedding")) AS "score"
785
+ FROM "paper" … INNER JOIN "topic" … ORDER BY "score" DESC LIMIT 10
786
+ ```
787
+
788
+ Validation requires BOTH sides be bound and semantic-eligible: an unbound
789
+ reference is `semantic.query-unbound`; a `{ type }` bound more than once is
790
+ `semantic.query-ambiguous` (use the `{ source }` form to disambiguate). The
791
+ base dialect degrades similarity to `0` (never throws).
792
+
793
+ - **Numeric text score.** `text-score` ranks by full-text relevance:
794
+ `ts_rank(to_tsvector(col), plainto_tsquery(query))` in Postgres (honoring a
795
+ `SearchBacking`'s hidden `vectorField` / `language` / boolean `sql` override,
796
+ the last lifted to a numeric `0/1`); the base dialect degrades to
797
+ `CASE WHEN <LIKE> THEN 1 ELSE 0 END`. In memory it is a deterministic
798
+ token-overlap fraction (honoring `SearchBacking.run`). See
799
+ `examples/13-scoring-ranking.ts`.
800
+
801
+ ### Search & semantic backing
802
+
803
+ A Type / field flagged `search` / `semantic` in the (unchanged, minimal) schema
804
+ very often has a **physical field hidden from the type system** that already
805
+ holds a precomputed `tsvector` (full-text) or `pgvector` embedding. A backing
806
+ says **how** search / similarity runs per Type or field — most importantly by
807
+ pointing at that hidden field. Both `TypeBacking` (whole-type) and `FieldBacking`
808
+ (per-field) take an optional `search?: SearchBacking` and `semantic?:
809
+ SemanticBacking`; a **field-level** backing overrides the **type-level** one.
810
+
811
+ ```ts
812
+ const backing: TypeBacking = {
813
+ // WHOLE-TYPE: point at hidden precomputed fields (NOT conceptual fields).
814
+ search: { vectorField: 'search_tsv', language: 'english' }, // a tsvector field
815
+ semantic: { vectorField: 'embedding' }, // a pgvector field
816
+ fields: {
817
+ // FIELD-LEVEL override wins for a field-narrowed `text-search` / `semantic`.
818
+ title: { search: { vectorField: 'title_tsv' }, semantic: { vectorField: 'title_vec' } },
819
+ },
820
+ };
821
+ ```
822
+
823
+ **Knobs** (each factory takes the bound `alias` **first** and must reference it,
824
+ so aliased / self-joined sources resolve correctly):
825
+
826
+ - `vectorField` — the hidden physical field, referenced as `<alias>."<field>"`.
827
+ In Postgres a `SearchBacking.vectorField` emits the precomputed-tsvector
828
+ predicate `<alias>."f" @@ plainto_tsquery('<language>', $n)` (**not** re-wrapped
829
+ in `to_tsvector`); a `SemanticBacking.vectorField` is the left operand of the
830
+ dialect's `similarity`, with the query vector bound as a `$n::vector` param.
831
+ - `language` — the text-search config for `plainto_tsquery` (default `'english'`).
832
+ - `sql` — a full SQL override → a **boolean** predicate (search) / **numeric**
833
+ score (semantic). Given `(alias, query|queryVector, ctx)`.
834
+ - `run` — a full runtime override → `boolean` (search) / `number` (semantic).
835
+ - `SemanticBacking.vector` — where the row's embedding comes from at runtime
836
+ (an alternative to `vectorField`), returning `number[]` or `null`.
837
+ - `SemanticBacking.embedder` — a per-Type / per-field embedder for the **query**
838
+ text (else the run / engine embedder).
839
+
840
+ **Precedence** (both modes): a full `sql` / `run` override wins; else the hidden
841
+ `vectorField` (or `vector` producer) is used; else today's default (the dialect's
842
+ `textSearch` / `similarity` over the conceptual text fields, or an in-memory
843
+ token match / embed-the-row-text). `toSQL` stays synchronous — the async embedder
844
+ is **never** called there; the query vector is a bound param.
845
+
846
+ The **base (ANSI) dialect degrades gracefully** and never throws: a tsvector
847
+ field falls back to a case-insensitive `LIKE`, and vector similarity to a
848
+ constant `0`. See `examples/12-search-backing.ts`.
849
+
850
+ ### Array fields and operations
851
+
852
+ An `array` field is queried with the `array-op` predicate expression: `contains`
853
+ (a single element is present), `containsAny` / `containsAll` (overlap / superset
854
+ against an element list), and `isEmpty` / `notEmpty`. Element count is a
855
+ `comparison` over the builtin `arrayLength(field)` scalar function. (Element matching follows the ELEMENT type's `casing`, else the engine's
856
+ `textCasing` default — the same rule a scalar text comparison uses.)
857
+
858
+ ```ts
859
+ // containment — a single element is present:
860
+ { kind: 'array-op', op: 'contains', target: { kind: 'field-ref', source: 'user', field: 'tags' },
861
+ value: { kind: 'literal', value: 'beta' } }
862
+
863
+ // overlap against an element list:
864
+ { kind: 'array-op', op: 'containsAny', target: { kind: 'field-ref', source: 'user', field: 'tags' },
865
+ value: [{ kind: 'literal', value: 'admin' }, { kind: 'literal', value: 'beta' }] }
866
+
867
+ // element count ≥ 2 via the builtin arrayLength function:
868
+ { kind: 'comparison', op: '>=',
869
+ left: { kind: 'function-call', function: 'arrayLength', args: { arr: { kind: 'field-ref', source: 'user', field: 'tags' } } },
870
+ right: { kind: 'literal', value: 2 } }
871
+ ```
872
+
873
+ > Build these with the `e.*` array builders (`e.contains` / `e.containsAny` /
874
+ > `e.containsAll` / `e.isEmpty` / `e.notEmpty`, and `e.fn('arrayLength', …)`).
875
+
876
+ **Dialect support.** Array operations are **Postgres-native**: `contains` →
877
+ `value = ANY(col)`, `containsAll` → `col @> ARRAY[…]`, `containsAny` →
878
+ `col && ARRAY[…]`, and length → `cardinality(col)`. The portable **base (ANSI)
879
+ dialect has no array operators**, so containment (`contains` / `containsAny` /
880
+ `containsAll`) throws a clear `QueryTypeError` (`array-op.unsupported-dialect`)
881
+ rather than emit wrong SQL; emptiness and the length filters still work there
882
+ via `COALESCE(json_array_length(col), 0)`.
883
+
884
+ A `param` (`{ kind: 'param', name }`) infers its type from how it is used and
885
+ is bound at run/emit time. A filter predicate is likewise supplied at EXECUTION
886
+ time via `engine.run(query, { filters: { <source>: boolExpr } })` — the
887
+ placeholder evaluates it dynamically against the bound source (see
888
+ [Execution model](#execution-model)). `autoPaginate` turns a query into a
889
+ reusable, paged artifact by binding `limit` / `offset` to params (idempotently):
890
+
891
+ ```ts
892
+ import { autoPaginate } from '@aeye/query';
893
+ const paged = autoPaginate(select); // adds { limit: param('limit'), offset: param('offset') }
894
+ await engine.run(paged, { params: { limit: 10, offset: 0 } });
895
+ ```
896
+
897
+ ## CTEs
898
+
899
+ A `WITH` statement (`{ kind: 'cte', ctes, final }`) carries a list of named CTE
900
+ entries consumed by a `final` query. An entry is one of two **distinct** shapes,
901
+ structurally discriminated:
902
+
903
+ - **Non-recursive** — `{ name, query }`.
904
+ - **Recursive** — `{ name, base, recursive }`: a `base` seed query UNION-ed with
905
+ a `recursive` arm that reads the CTE's own accumulating rows until a fixpoint
906
+ (iteration-capped). Recursion is its OWN shape — there is no `recursive?` flag
907
+ on the plain entry.
908
+
909
+ ```ts
910
+ { kind: 'cte',
911
+ ctes: [{ name: 'descendants',
912
+ base: /* seed select */,
913
+ recursive: /* select that reads `descendants` */ }],
914
+ final: { kind: 'select', from: { kind: 'type', type: 'descendants' }, fields: [/* … */] } }
915
+ ```
916
+
917
+ ## Drill-down
918
+
919
+ `drillDown` rebuilds the query that returns the **underlying rows** behind an
920
+ aggregate — PARAMETERIZED: each GROUP BY key is pinned to a bind param
921
+ (`key = param(name)`), so the drilled query is reusable. It returns the rebuilt
922
+ `query`, the `params` (a `DrillParam[]` mapping each output `field` → its
923
+ `name`), and any `warnings`.
924
+
925
+ ```ts
926
+ import { drillDown, drillDownInto } from '@aeye/query';
927
+
928
+ // The reusable, parameterized drilled query + its field → param mapping.
929
+ const d = drillDown(revenuePerUser, engine);
930
+ // d.params → [{ name:'userId', field:'userId', key: { kind:'field-ref', source:'order', field:'userId' } }]
931
+
932
+ // Or drill into ONE aggregated row: extract its key values, then it's the same
933
+ // run call. (This is the old literal-baking behavior, now param-driven.)
934
+ const into = drillDownInto(revenuePerUser, groupRow, engine);
935
+ if ('query' in into) {
936
+ const underlying = await engine.run(into.query, { params: into.params }); // that row's orders
937
+ }
938
+ ```
939
+
940
+ The param NAME is derived from the carrying output field (sanitized to a valid
941
+ identifier; suffixed `_2`, `_3`, … on collision with a param the query already
942
+ uses). Failure cases (`drill.no-aggregation` / `non-invertible` /
943
+ `having-aggregate` / `window-unsupported`) return LLM-friendly `Problems`.
944
+
945
+ Each aggregate is replaced by its underlying row-level expression, and `count(*)`
946
+ — which has no single value — expands to the FROM type's fields MINUS the ones
947
+ the SELECT already projects itself. So `SELECT status, count(*) … GROUP BY status`
948
+ drills to `status` plus the remaining columns, with the group key projected ONCE.
949
+ The skip is keyed on the EXPRESSION (its canonical form), never on the output
950
+ name: two different expressions may legitimately share a name.
951
+
952
+ ## Cost & estimation
953
+
954
+ Bottom-up estimates driven by each Type's cardinality (`count` rows, `bytes`
955
+ per row), its indexes + fixed **selectivity** for predicates (an indexed
956
+ equality narrows toward one row; a non-indexed one applies `EQ_SELECTIVITY`),
957
+ and per-Type / per-field `changes` rates. Five estimators hang off the engine:
958
+
959
+ ```ts
960
+ const cost = engine.cost(select); // { rows, bytes } — WORK to produce the result (scanned rows)
961
+ const output = engine.outputCost(select); // { rows, bytes } — SIZE of the result (delivered rows × projection width)
962
+ const affected = engine.affected(update); // { rows, types: [{ type, rows }] } — rows an INSERT/UPDATE/DELETE (or CTE) mutates
963
+ const refs = engine.references(select); // { types, fields, functions } — exactly what the query READS
964
+ const ttl = engine.changeInterval(select); // ms until the data behind it could change (0 = always, -1 = never, else fastest rate)
965
+
966
+ // Constraints reject over-budget queries during validation:
967
+ const problems = engine.validateQuery(select, undefined, { maxRows: 100, maxBytes: 1_000_000 });
968
+ // → cost.rows-exceeded / cost.bytes-exceeded when the estimate blows past a cap
969
+ ```
970
+
971
+ `cost` estimates work (OR-aware, index-probe driven); `outputCost` sizes the
972
+ delivered result (post-WHERE/GROUP/DISTINCT, capped by LIMIT/OFFSET);
973
+ `affected` counts mutated rows per Type; `references` powers `changeInterval`,
974
+ which folds the read Types' / fields' / functions' `changes` rates into a single
975
+ freshness / cache-TTL signal. All accept the same execution-time
976
+ `options.params` / `filters` / `sort` so the estimate reflects what actually runs.
977
+
978
+ ## Functions
979
+
980
+ All four function shapes are uniform: declare a `FunctionDef` (name, shape,
981
+ **named** params, output) with `registerFunction`, then pair it with a
982
+ shape-tagged runtime via `registerFunctionRun`. Calls reference the function by
983
+ name with **named arguments** (`args: { paramName: <expr> }`):
984
+
985
+ ```ts
986
+ // scalar — initials(value: text): text
987
+ registry.registerFunction({
988
+ name: 'initials', shape: 'scalar',
989
+ params: [{ name: 'value', type: { kind: 'text' } }],
990
+ output: { kind: 'text' },
991
+ });
992
+ registry.registerFunctionRun('initials', {
993
+ shape: 'scalar',
994
+ run: (args) => Value.of(args.value.toText().split(/\s+/).map((w) => w[0]).join('')),
995
+ });
996
+
997
+ // reference it by name with NAMED args:
998
+ // { kind: 'function-call', function: 'initials', args: { value: <expr> } }
999
+ ```
1000
+
1001
+ The four shapes differ only in what their `run` receives:
1002
+
1003
+ | shape | `run(...)` signature | example |
1004
+ | ----------- | --------------------------------------------- | ------------- |
1005
+ | `scalar` | `(args, ctx)` → one value | `upper` |
1006
+ | `tabular` | `(args, ctx)` → rows | `rangeRows` |
1007
+ | `aggregate` | `(rows, ctx)` → one value over a group | `sum`, `count`|
1008
+ | `window` | `(partition, index, ctx)` → value per row | `rowNumber` |
1009
+
1010
+ `count(*)` is the empty-args convention: `{ kind: 'aggregate', function:
1011
+ 'count', args: {} }`. The registry ships a **default library** (60+ functions
1012
+ across all shapes — `upper`/`concat`/`coalesce`/…, string/math scalars
1013
+ (`trimLeft`/`padLeft`/`splitPart`/`log`/`iif`/…), `sum`/`avg`/`min`/`max`/
1014
+ `count`, `rowNumber`/`rank`/`lag`/…) registered by `createRegistry()`, so they
1015
+ are discoverable and runnable out of the box (see the reference below):
1016
+
1017
+ ```ts
1018
+ registry.functionList(); // every FunctionDef (default lib + your own)
1019
+ describeFunctions(engine); // a promptable, by-shape listing for an LLM
1020
+ ```
1021
+
1022
+ ### Operators — `&&`, `<->`, `@>`
1023
+
1024
+ A function declaration cannot express an INFIX operator: `a && b` has no call
1025
+ form in any dialect, and `FunctionDef.sql` is a NAME, never a template.
1026
+ `registerOperator` is the other half — a declaration whose SQL is a per-dialect
1027
+ template, applied through the `operator` expr kind:
1028
+
1029
+ ```ts
1030
+ registry.registerOperator({
1031
+ name: '&&', // SQL operator punctuation only
1032
+ operands: [{ name: 'left', type: { kind: 'json', as: 'Geometry' } },
1033
+ { name: 'right', type: { kind: 'json', as: 'Geometry' } }],
1034
+ output: { kind: 'bool' }, // concrete, never 'inferred'
1035
+ instructions: 'Bounding-box overlap between two geometries. Cheap; a pre-filter for ST_Contains.',
1036
+ emit: { postgres: '({left} && {right})' }, // PARENTHESIZED; per Dialect.name
1037
+ selectivity: 0.1,
1038
+ });
1039
+ registry.registerOperatorRun('&&', (args) => Value.of(bboxOverlaps(args.left, args.right)));
1040
+
1041
+ // reference it by name with NAMED operands:
1042
+ // { kind: 'operator', op: '&&', args: { left: <expr>, right: <expr> } }
1043
+ ```
1044
+
1045
+ ```sql
1046
+ WHERE ("parcel"."shape" && ST_GeomFromGeoJSON($1))
1047
+ ```
1048
+
1049
+ The operand's **declared type reaches emission**, so a document operand binds
1050
+ through that type's own `cast` rather than the dialect's default json cast —
1051
+ without it Postgres refuses the statement (`operator does not exist: geometry &&
1052
+ jsonb`). A value position asserts only what its declaration WROTE: an operand's
1053
+ cast resolves from the operand's own `with` bag and never from the refinement's
1054
+ defaults, since those would pin a typmod the value never had to satisfy. A cast
1055
+ needing an option the operand did not write is refused at emit
1056
+ (`cast.unwritten-option`).
1057
+
1058
+ `registry.operatorList()` enumerates them; `describeOperators(engine)` renders
1059
+ the promptable block (and `describeEngine` includes it when any is registered).
1060
+ A dialect with no `emit` entry is **refused** at emit
1061
+ (`operator.unsupported-dialect`), never degraded to a neutral fragment; so is a
1062
+ missing `run` on the in-memory road (`operator.no-run`), because an operator is
1063
+ usually a predicate and NULL there means zero rows. Full rules — the name
1064
+ charset, the template checks, and what `OperatorDef` deliberately does not carry
1065
+ — are in `aeye-query.md`.
1066
+
1067
+ ### Function reference
1068
+
1069
+ All builtin names are **camelCase** (no underscores). Where the emitted SQL
1070
+ function name differs from the camelCase name it is shown in the *SQL* column;
1071
+ otherwise the SQL is `name(args)` on both dialects. `base` is the portable
1072
+ ANSI dialect, `postgres` the pg dialect (they differ only where noted).
1073
+
1074
+ **Window** (`e.window`)
1075
+
1076
+ | function | SQL (base = postgres) | notes |
1077
+ | --------------------------- | --------------------- | --------------------------------------- |
1078
+ | `rowNumber()` | `row_number()` | renamed from `row_number` |
1079
+ | `rank()` | `rank()` | |
1080
+ | `denseRank()` | `dense_rank()` | renamed from `dense_rank` |
1081
+ | `lag(value, offset?, default?)` | `lag(…)` | |
1082
+ | `lead(value, offset?, default?)` | `lead(…)` | |
1083
+ | `percentRank()` | `percent_rank()` | `(rank − 1) / (N − 1)` |
1084
+ | `cumeDist()` | `cume_dist()` | |
1085
+ | `ntile(n)` | `ntile(n)` | 1-based bucket over `n` equal buckets |
1086
+ | `firstValue(value)` | `first_value(value)` | |
1087
+ | `lastValue(value)` | `last_value(value)` | full-partition frame (see note below) |
1088
+ | `nthValue(value, n)` | `nth_value(value, n)` | 1-based |
1089
+
1090
+ **Scalar — string** (`e.fn`)
1091
+
1092
+ | function | SQL name |
1093
+ | ------------------------------------- | --------------- |
1094
+ | `lower` `upper` `trim` `length` `substring` `replace` `concat` | *(same)* |
1095
+ | `trimLeft(value)` | `ltrim` |
1096
+ | `trimRight(value)` | `rtrim` |
1097
+ | `left(value, count)` `right(value, count)` | *(same)* |
1098
+ | `padLeft(value, length, fill?)` | `lpad` |
1099
+ | `padRight(value, length, fill?)` | `rpad` |
1100
+ | `repeat(value, count)` `reverse(value)` | *(same)* |
1101
+ | `indexOf(value, search)` | `strpos` (1-based, 0 = absent) |
1102
+ | `startsWith(value, search)` | `starts_with` |
1103
+ | `splitPart(value, delimiter, index)` | `split_part` (1-based) |
1104
+ | `concatWs(separator, values)` | `concat_ws` (`values` = one array arg, like `concat`) |
1105
+
1106
+ **Scalar — math** (`e.fn`)
1107
+
1108
+ | function | SQL name |
1109
+ | ------------------------------------- | --------------- |
1110
+ | `abs` `ceil` `floor` `round` `sqrt` `power` | *(same)* |
1111
+ | `mod(value, divisor)` `sign` `exp` `ln` `trunc` `pi()` `random()` | *(same)* |
1112
+ | `log(base, value)` | `log(base, value)` |
1113
+ | `log10(value)` | `log` (pg single-arg `log` is base-10) |
1114
+ | `degrees` `radians` `sin` `cos` `tan` `asin` `acos` `atan` `atan2(y, x)` | *(same)* |
1115
+
1116
+ **Scalar — conditional / other** (`e.fn`)
1117
+
1118
+ | function | SQL |
1119
+ | ------------------------------------- | --------------- |
1120
+ | `iif(condition, then, else)` | `(CASE WHEN condition THEN then ELSE else END)` (both dialects) |
1121
+ | `coalesce` `nullif` `greatest` `least` `arrayLength` | *(same)* |
1122
+ | `now()` | `now()` |
1123
+ | `currentDate()` | `CURRENT_DATE` (renamed from `current_date`; bare form, no parens) |
1124
+
1125
+ **Scalar — date / time** (`e.*`) — temporal inputs accept an ISO date/timestamp
1126
+ string or a temporal field; the `field` of a selector is a **literal** token
1127
+ (`'year'`/`'month'`/`'day'`/`'dow'`/`'doy'`/`'week'`/`'hour'`/`'minute'`/
1128
+ `'second'`/`'quarter'`/`'isodow'`/`'epoch'`) spliced inline (not a bind param).
1129
+
1130
+ | function | base SQL | postgres SQL |
1131
+ | ------------------------------------- | -------------------------------- | ------------------------------------- |
1132
+ | `currentTime()` `currentTimestamp()` | `CURRENT_TIME` / `CURRENT_TIMESTAMP` (bare) | *(same)* |
1133
+ | `year/month/day/hour/minute/second(d)`| `EXTRACT(<PART> FROM d)` | *(same)* |
1134
+ | `dayOfWeek(d)` | `EXTRACT(DOW FROM d)` | *(same)* — `0`=Sun … `6`=Sat |
1135
+ | `dayOfYear(d)` `week(d)` | `EXTRACT(DOY/WEEK FROM d)` | *(same)* — `week` is the ISO week |
1136
+ | `datePart(field, d)` | `EXTRACT(<field> FROM d)` | `date_part('field', d)` |
1137
+ | `dateAdd(field, n, d)` | `d` (degrade — unchanged) | `(d + (n \|\| ' ' \|\| 'field')::interval)` |
1138
+ | `dateDiff(field, a, b)` | `(EXTRACT(field FROM b) − EXTRACT(field FROM a))` | `(date_part('field', b) − date_part('field', a))` — component difference |
1139
+ | `dateTrunc(field, d)` | `d` (degrade — unchanged) | `date_trunc('field', d)` |
1140
+ | `makeDate(year, month, day)` | `make_date(…)` | `make_date(…)` |
1141
+ | `dateFormat(d, format)` | `to_char(d, fmt)` | `to_char(d, fmt)` — tokens `YYYY/MM/DD/HH24/HH/MI/SS` |
1142
+ | `epoch(ts)` | `EXTRACT(EPOCH FROM ts)` | *(same)* |
1143
+ | `fromEpoch(value)` | `to_timestamp(value)` | `to_timestamp(value)` |
1144
+ | `age(a, b)` | `age(a, b)` | `age(a, b)` — runtime returns whole-day span |
1145
+
1146
+ **Scalar — array** (`e.*`) — postgres-native; the base (ANSI) dialect DEGRADES
1147
+ gracefully (a constant, or the first argument unchanged) and never throws.
1148
+
1149
+ | function | base SQL (degrade) | postgres SQL |
1150
+ | ------------------------------------- | ------------------ | ------------------------------------- |
1151
+ | `arrayContains(arr, value)` | `(1 = 0)` | `(value = ANY(arr))` |
1152
+ | `arrayAppend(arr, value)` | `arr` | `array_append(arr, value)` |
1153
+ | `arrayPrepend(arr, value)` | `arr` | `array_prepend(value, arr)` |
1154
+ | `arrayConcat(a, b)` | `a` | `(a \|\| b)` |
1155
+ | `arrayIndexOf(arr, value)` | `0` | `array_position(arr, value)` (1-based)|
1156
+ | `arraySlice(arr, lo, hi)` | `arr` | `arr[lo:hi]` (1-based inclusive) |
1157
+ | `arrayRemove(arr, value)` | `arr` | `array_remove(arr, value)` |
1158
+ | `arrayDistinct(arr)` | `arr` | `ARRAY(SELECT DISTINCT unnest(arr))` |
1159
+ | `arrayToString(arr, sep)` | `''` | `array_to_string(arr, sep)` |
1160
+ | `stringToArray(str, sep)` | `str` | `string_to_array(str, sep)` |
1161
+
1162
+ **Aggregate** (`e.agg` / `e.sum` / …): `count` `sum` `avg` `min` `max`
1163
+ — all emit `name(args)` (or `count(*)` for empty args). Group 2d adds:
1164
+
1165
+ | function | base SQL | postgres SQL |
1166
+ | ------------------------------------- | -------------------------------- | ------------------------------------- |
1167
+ | `stddev(value)` `variance(value)` | `stddev(…)` / `variance(…)` (sample) | *(same)* |
1168
+ | `stringAgg(value, sep)` | `string_agg(value, sep)` | *(same)* |
1169
+ | `countIf(cond)` | `sum(CASE WHEN cond THEN 1 ELSE 0 END)` | *(same, both dialects)* |
1170
+ | `arrayAgg(value)` | `NULL` (degrade) | `array_agg(value)` |
1171
+ | `boolAnd(value)` | `(MIN(CASE WHEN value THEN 1 ELSE 0 END) = 1)` | `bool_and(value)` |
1172
+ | `boolOr(value)` | `(MAX(CASE WHEN value THEN 1 ELSE 0 END) = 1)` | `bool_or(value)` |
1173
+
1174
+ ## The LLM loop
1175
+
1176
+ The `llm/` surface turns the engine into an LLM tool:
1177
+
1178
+ ```ts
1179
+ import { selectTypes, buildSchemas, querySchema, buildQueryTool } from '@aeye/query';
1180
+
1181
+ // 1. Narrow the schema to the Types a request needs (semantic ranking).
1182
+ const types = await selectTypes(engine, 'revenue by customer last month');
1183
+
1184
+ // 2. Per-axis `depth` Zod schemas (see "Schema depth" below). `'paired'` locks
1185
+ // every axis: Type-name positions are enum-locked, field refs are TYPE+FIELD
1186
+ // pairs (an `order` source can't be paired with a `user`-only field),
1187
+ // relation paths are rooted at a known Type, and function calls are typed.
1188
+ const schemas = buildSchemas(engine, { depth: 'paired', types });
1189
+
1190
+ // 3. Or get the tool-input schema, which falls back to a string description
1191
+ // past `max` Types (shouldUseStringSchema). `depth` / `functions` thread
1192
+ // straight through to `buildSchemas`.
1193
+ const schema = querySchema(engine, { types, depth: 'paired' });
1194
+
1195
+ // 4. A ready-wired `@aeye/core` `Tool` — drop it into any core / `@aeye/ai`
1196
+ // agent's tool set. Its wire `schema` is the query schema; its custom `parse`
1197
+ // REPLACES Zod (validate the envelope → build a runnable `Query` → run full
1198
+ // engine validation), throwing a rich `QueryToolError` whose `.message` is a
1199
+ // compiler-style report on failure. Its `call` RUNS the built query.
1200
+ // `instructions` reflect the active depth + the selected functions.
1201
+ const tool = buildQueryTool(engine, { depth: 'paired' });
1202
+ const query = await tool.parse(ctx, JSON.stringify({ query: someQueryDef })); // built Query (throws QueryToolError on failure)
1203
+ const result = await tool.run(query, ctx); // runs it → QueryResult
1204
+ ```
1205
+
1206
+ Because the custom `parse` bypasses Zod, the model sees the engine's concise
1207
+ `Problems` diagnostics (via `formatProblems`) instead of Zod's harder-to-follow
1208
+ messages; when the query is clean the decoded value is the built `Query` and the
1209
+ tool's `call` executes it.
1210
+
1211
+ **Self-describing the engine.** `describeEngine(engine, { types?, functions? })` composes one terse, promptable block a model can read to know everything it may use: every (supplied) Type, then `describeExprs` (the capability-gated `kind — INSTRUCTIONS` list of usable expr kinds — `semantic` / `array-op` / … appear only when an eligible Type/function exists; the core is never gated), then `describeFunctions` (`name(a, b?): output — instructions`, grouped by shape), then `describeDialects`. `describeType` / `describeField` always render a short `label` + long `description` — the dev's `TypeDef` / `FieldDef` values when set, else defaults GENERATED on demand from the meta-model (a Field from its FieldType + flags + nullability + relation cardinality; a Type from its name + field/relation/index summary). Read the pair with `fieldMeta(field)` / `typeMeta(type)`; the stored def is never mutated.
1212
+
1213
+ See `examples/` for an end-to-end, runnable tour of all of the above.
1214
+
1215
+ ## Schema depth
1216
+
1217
+ `buildSchemas` / `querySchema` / `buildQueryTool` constrain the LLM-facing
1218
+ schema along **four independent axes**, each dialed by `depth`:
1219
+
1220
+ | axis | levels (loose → tight) | constrains |
1221
+ | ----------- | -------------------------------------------- | ---------------------------------------- |
1222
+ | `refs` | `open` · `types` · `fields` · `both` · `paired` | `field-ref` source + field / relation join `on` |
1223
+ | `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
1224
+ | `functions` | `open` · `names` · `typed` | function name + named-arg objects |
1225
+ | `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
1226
+
1227
+ Pass a full `SchemaDepth` object, a partial one (unset axes stay loose), or a
1228
+ preset string: `'open'` (every axis loose — free strings) and `'paired'` (every
1229
+ axis tight). The deprecated `strict: true` / `false` are sugar for
1230
+ `'paired'` / `'open'`.
1231
+
1232
+ ```ts
1233
+ buildSchemas(engine, { depth: { refs: 'paired', functions: 'typed' } });
1234
+ buildSchemas(engine, { depth: 'open' }); // ≡ strict: false
1235
+ buildSchemas(engine, { depth: 'paired' }); // ≡ strict: true
1236
+
1237
+ // FunctionSelector — which functions appear in the names/typed schema + prompt:
1238
+ buildSchemas(engine, { depth: { functions: 'names' }, functions: { scalar: ['upper', 'lower'] } });
1239
+
1240
+ // maxEnumSize — AUTO-DEGRADE any axis whose enumeration exceeds the budget one
1241
+ // level looser, so a large catalog never produces an unusable schema:
1242
+ buildSchemas(engine, { depth: 'paired', maxEnumSize: 50 });
1243
+ ```
1244
+
1245
+ `examples/10-schema-depth.ts` prints, per depth, whether a cross-type field-ref
1246
+ / unknown function / unknown argument is accepted or rejected.
1247
+
1248
+ ### Capability gating
1249
+
1250
+ INDEPENDENT of depth, the generated `Expr` union **omits any expr kind the
1251
+ available Types / functions can't use**, so the model is never offered an
1252
+ unusable construct. A kind appears only when it is applicable:
1253
+
1254
+ | kind | available when |
1255
+ | ---- | -------------- |
1256
+ | `semantic` | some Type is semantic-eligible (`isSemantic()`) |
1257
+ | `text-search` | some Type is searchable (`isSearchable()`) |
1258
+ | `array-op` | some Type has an `array` field |
1259
+ | joins | some Type has a relation field |
1260
+ | `tabular-function-call` | ≥1 selected `tabular` function |
1261
+ | `aggregate` / `window` / `function-call` | ≥1 selected function of that shape |
1262
+ | `operator` | ≥1 registered operator whose operand type some in-scope field could supply |
1263
+ | `filters` | some Type has filterable fields |
1264
+
1265
+ The always-usable core (literal / param / binary / unary / comparison / logical
1266
+ / in / between / is-null / exists / case / `field-ref` / subquery) is never
1267
+ gated. When no Type has a relation, the `joins` array is gated out of `Select`
1268
+ too (it accepts only an empty / absent list).
1269
+
1270
+ ## Interactive CLI
1271
+
1272
+ `examples/cli.ts` is a small REPL (in the spirit of `ginny`) that ties the
1273
+ whole loop together: it loads whatever JSON data lives in a data directory,
1274
+ infers a `Type` per file, then lets you type a natural-language request and
1275
+ have an LLM build → (auto-repair) → run a query against the inferred schema.
1276
+
1277
+ ```bash
1278
+ npm run cli # loads examples/data (users / orders / products)
1279
+ npm run cli ./path/to/data # load a custom directory of *.json files
1280
+ ```
1281
+
1282
+ Each `*.json` file must hold a **JSON array of objects**. The Type name comes
1283
+ from the filename: it is **singularized + capitalized** (`users.json`→`User`,
1284
+ `orders.json`→`Order`, `categories.json`→`Category`). Files that aren't a JSON
1285
+ array are skipped with a warning.
1286
+
1287
+ The REPL needs an AI provider; set one of these (env vars, mirroring ginny):
1288
+
1289
+ | Env var | Provider |
1290
+ | -------------------- | ------------------------------------------------------- |
1291
+ | `OPENAI_API_KEY` | OpenAI |
1292
+ | `OPENROUTER_API_KEY` | OpenRouter |
1293
+ | AWS credentials | AWS Bedrock (env vars / `aws sso login` / IAM role / …) |
1294
+ | `QUERY_MODEL` | *(optional)* pin a specific model id |
1295
+
1296
+ With no provider configured the CLI prints which env var to set and exits
1297
+ cleanly (it never crashes). The REPL builds the tool at a tight default depth
1298
+ (`refs: 'paired'`, `typeNames: 'enum'`, `functions: 'typed'`, `filters:
1299
+ 'paired'`, with a `maxEnumSize` so large catalogs degrade gracefully). REPL
1300
+ commands: `:types`, `:fns` (list callable functions by shape), `:depth <spec>`
1301
+ (switch schema tightness at runtime — a preset like `:depth open` / `:depth
1302
+ paired`, or per-axis `:depth functions=names refs=types`), `:sql` (toggle
1303
+ emitting base + postgres SQL per query), `:data <dir>` (reload), `:help`,
1304
+ `:exit`.
1305
+
1306
+ ```text
1307
+ @aeye/query CLI — data: .../examples/data
1308
+
1309
+ Loaded Types:
1310
+ Order (6 fields): id, userId, productId, total, status, createdAt
1311
+ Product (4 fields): id, name, price, category
1312
+ User (5 fields): id, name, age, email, city
1313
+
1314
+ query> users in London ordered by name
1315
+
1316
+ 2 row(s):
1317
+ ┌─────────┬─────────────────┬──────────┐
1318
+ │ (index) │ name │ city │
1319
+ ├─────────┼─────────────────┼──────────┤
1320
+ │ 0 │ 'Ada Lovelace' │ 'London' │
1321
+ │ 1 │ 'Cleo Nguyen' │ 'London' │
1322
+ └─────────┴─────────────────┴──────────┘
1323
+ fields: name:text, city:text
1324
+ ```
1325
+
1326
+ Under the hood each request runs the package's LLM surface: `selectTypes`
1327
+ narrows the schema when there are many Types, `buildQueryTool(engine).schema`
1328
+ constrains the model's output, and the tool's custom `parse`
1329
+ validates + parses it into a runnable `Query` — surfacing LLM-friendly
1330
+ `Problems` (as a `QueryToolError`) that drive a single automatic repair round
1331
+ before running.
1332
+