@aeye/query 0.3.9

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