@aeye/query 0.6.3 → 0.6.5

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
@@ -353,6 +353,15 @@ Everything composes around that one call:
353
353
  is used and is bound at run time via `options.params`. Introspect what a built
354
354
  query expects with `query.params(engine)` → `ParamDef[]` (name + inferred
355
355
  type).
356
+
357
+ It reports every param the statement binds **at any depth**, so what it
358
+ declares is always enough to bind the emitted SQL. That includes a
359
+ `limit` / `offset` bound, which lives outside the walked expr tree: on the
360
+ statement itself, on a **`cte`'s `final`** (where `autoPaginate` puts it), on a
361
+ set-operation **arm** or its set-level bound, and inside a FROM / `in` /
362
+ `exists` subquery or an `insert … select` source. An under-reported bound is
363
+ not a cosmetic gap — the SQL still emits `LIMIT ?` and a caller that binds the
364
+ declared signature leaves it NULL, which Postgres reads as *no limit*.
356
365
  - **Filters.** `options.filters` is a `Record<source, ExprDef | Expr | null>` —
357
366
  a single **boolean Expr** per source (or `null` / absent for none). The
358
367
  `filters` EXPR in the query is only a placeholder (`{ source, fields? }`); the
package/aeye-query.md CHANGED
@@ -89,14 +89,16 @@ Everything is referenced by its **Type name** — there is no alias to invent or
89
89
  - **SELECT** — `fields` (each `{ expr, as? }`), `from`, `joins`, `where` (ANDed), `groupBy`, `having` (ANDed), `order` (`{ expr, dir, nulls? }`), `limit`/`offset` (a literal or a `param`), and `distinct`.
90
90
  - **Condition clauses must be boolean** — every top-level condition predicate (a `where`/`having` entry, a join's `and`, and a DML `update`/`delete` `where`) must resolve to a boolean, exactly as `logical` operands and `case` `when` clauses already require; a non-boolean predicate (a bare `field-ref` to a number/money/text field, a `literal`, an arithmetic `binary`, a non-bool function) is rejected with `condition.non-bool` at the predicate's own path. A bare `param` predicate is EXEMPT (its type is inferred from use).
91
91
  - **Output references** — `groupBy` / `order` / `having` may use `{ kind: 'output', name }` to reference a projected field by name (its `as`, or a natural derived name) instead of repeating the expression. It EXPANDS to the target item's expr in both SQL and runtime (a group key re-computes over the source row; an ORDER BY / HAVING ref re-computes over the group, incl. an aggregate target). Valid **only** in those three positions (`output.not-available` elsewhere; `output.unknown` / `output.aggregate` on misuse). `drillDown` expands `output` refs before un-ravelling.
92
- - **Aggregates & grouping** — any registered aggregate over a `groupBy`; `count(*)` is `count` with empty args; `distinct` on the aggregate. `having` filters groups.
92
+ - **Aggregates & grouping** — any registered aggregate over a `groupBy`; `count(*)` is `count` with empty args; `distinct` on the aggregate. `having` filters groups. `distinct` de-duplicates the ARGUMENT VALUES, so it is refused on the arg-less form (`aggregate.distinct-no-args`) — `count(DISTINCT *)` is a syntax error on every dialect and the runtime never de-duplicated it either; emission drops it, so an unvalidated statement still produces valid SQL.
93
93
  - **Set operations** — `union` / `intersect` / `except` over two queries, `all?` to keep duplicates, plus **set-level** `order` / `limit` / `offset` applied to the combined rows (ORDER BY terms reference output columns by name).
94
94
  - **CTEs** — `{ kind: 'cte', ctes, final }`. Each entry is either non-recursive (`{ name, query }`) or **recursive** (`{ name, base, recursive }` — a seed UNION-ed with an arm reading the CTE's own accumulating rows to a fixpoint, iteration-capped). Recursion is its own structural shape (no `recursive?` flag).
95
95
  - **DML** — `insert` (row tuples or a `select`, optional `returning`, optional `onConflict`), `update` (`set` assignments, optional `joins`/`where`/`returning`), `delete` (optional `joins`/`where`/`returning`). `onConflict` = conflict-target `fields` plus `doNothing` or an `update` assignment list (which may reference the `excluded` proposed row).
96
96
  - **Single-expression query** — `{ kind: 'expr', expr }` for a scalar computation.
97
- - **Params** — `{ kind: 'param', name }` infers its type from use; bound at run/emit via `options.params`. Introspect with `query.params(engine)` → `ParamDef[]`.
97
+ - **Params** — `{ kind: 'param', name }` infers its type from use; bound at run/emit via `options.params`. Introspect with `query.params(engine)` → `ParamDef[]`. It reports **every param the statement binds, at any DEPTH** — including a `limit`/`offset` bound, which lives outside the expr tree, wherever it sits: on a `cte`'s `final` (where `autoPaginate` puts it), on a set-operation arm or its set-level bound, or inside a FROM / `in` / `exists` subquery or an `insert … select` source. So what `params()` declares is always enough to BIND the emitted SQL — an under-reported bound emits `LIMIT ?` with nothing to fill it, and `LIMIT NULL` is *no limit* (the whole table), not an error.
98
98
  - **Filters** — a `filters` placeholder (`{ source, fields? }`) is authored by the LLM but the **predicate is supplied at execution time** by the developer: `options.filters` is a `Record<source, boolean Expr | ExprDef | null>`. The placeholder evaluates/emits it (vacuously `TRUE` when none). Introspect exposed sources + fields with `query.filters(engine)` → `Record<source, { fields: QueryField[] }>` (name + resolved type + nullability + kind, restricted to any `fields` allowlist); `query.filterSources()` lists targetable sources.
99
99
  - **Cost & estimation** — bottom-up estimates driven by Type `count`/`bytes`, indexes + selectivity, and per-Type/field `changes` rates. `engine.cost(query)` → `{ rows, bytes }` (the WORK to produce the result); `engine.outputCost(query)` → `{ rows, bytes }` (the SIZE of the result — delivered rows × projection width); `engine.affected(query)` → `{ rows, types[] }` (rows an INSERT/UPDATE/DELETE or CTE mutates, OR-aware via indexes); `engine.references(query)` → `{ types, fields, functions }` (exactly what the query reads, incl. execution-time `filters`/`sort` and called functions); `engine.changeInterval(query)` → ms until the data behind it could change (freshness/cache-TTL: `0` = always, `-1` = never, else the fastest read rate). `validateQuery(query, _, { maxRows, maxBytes })` rejects over-budget queries (`cost.rows-exceeded` / `cost.bytes-exceeded`).
100
+ - **A DERIVED SOURCE is estimated from its BODY.** A CTE name, a FROM subquery and a joined subquery source all bind a synthetic Type, and that Type carries the rows its body produces — so `SELECT … FROM (SELECT … FROM million) x` costs a million, a join over such a source fans out by its real cardinality, and a `WITH` costs its `final` PLUS every entry's own work (an entry runs whether or not `final` reads it, and this runtime materializes each one in memory). A RECURSIVE entry is estimated as its seed plus `RECURSIVE_CTE_LEVELS` expansions of its arm — the fixpoint depth is data-dependent, so the model assumes a shallow hierarchy rather than pretending to know. Two consequences worth stating: a `cte` / derived table is no longer structurally free, so a `maxRows` budget can finally refuse one (before `0.6.5` these bound a zero-row Type and every such statement passed every budget at `{rows: 0}`); and a `LIMIT` bound to a PARAM *inside* a body is estimated UNCAPPED — those estimates are taken with `engine.neutralCost`, the neutral context, because execution-time `filters` / `sort` / `params` belong to the enclosing query.
101
+ - **`affected` descends into EVERY nesting position** — its own target, plus whatever its nested statements mutate: a FROM / joined subquery source, a `subquery` / `exists` / `in` subquery in any clause, a set-operation arm, an `insert … select` source, and a `cte`'s entries + `final`. Each kind declares its nested statements once, so this is total by construction rather than a list of remembered cases. Rows are summed per Type, in document (= execution) order.
100
102
 
101
103
  ## Write model & permissions
102
104
 
@@ -161,6 +163,8 @@ Shapes: `scalar` `(args, ctx)→value`, `tabular` `(args, ctx)→rows`, `aggrega
161
163
 
162
164
  **Aggregate:** `count`, `sum`, `avg`, `min`, `max`, `stddev`, `variance` (both sample/n-1), `stringAgg`(→`string_agg`), `arrayAgg`(→`array_agg`; base degrades to `NULL`), `boolAnd`(→`bool_and`), `boolOr`(→`bool_or`), `countIf`(→ portable `sum(CASE WHEN … THEN 1 ELSE 0 END)`).
163
165
 
166
+ **An aggregate declares HOW ITS VALUES MERGE.** `FunctionDef.merge` (an `AggregateMerge`: `'sum' | 'min' | 'max' | 'and' | 'or' | 'none'`, default `'none'`, declarable only on an `aggregate` shape) says how two per-group values combine into the value over the UNION of those groups — `f(A ∪ B) = f(A) ⊕ f(B)` for every partition. Builtins: `count`/`sum`/`countIf` → `'sum'`, `min`/`max` → `'min'`/`'max'`, `boolAnd`/`boolOr` → `'and'`/`'or'`; `avg`, `stddev`, `variance`, `stringAgg`, `arrayAgg` declare NONE, deliberately — `avg` over the union needs each group's WEIGHT, which the value does not carry (adding the means or averaging them are both wrong), and the collectors need a separator/ordering. Declare it on your own aggregate and every consumer that folds groups is correct for it with no edit; declare nothing and the answer is `'none'`, which fails safe. Read the ALREADY-RESOLVED per-call answer off `ComputedResolved.aggregateMerge` rather than the raw declaration — or `mergeOfAggregateCall(declared, distinct)` to apply the rule yourself.
167
+
164
168
  **Window:** `rowNumber`(→`row_number`), `rank`, `denseRank`(→`dense_rank`), `lag(value, offset?, default?)`, `lead(value, offset?, default?)`, `percentRank`(→`percent_rank`), `cumeDist`(→`cume_dist`), `ntile(n)`, `firstValue`(→`first_value`), `lastValue`(→`last_value`; full-partition frame), `nthValue`(→`nth_value`; 1-based).
165
169
 
166
170
  ## Schema depth & capability gating
@@ -189,7 +193,7 @@ const result = await engine.run(query, { params, filters, includeTotal });
189
193
  // result.total — pre-limit count, when run with includeTotal: true
190
194
  ```
191
195
 
192
- - **An output field's `type`** is the full `ResolvedType`. A COMPUTED one carries `aggregate` (does a group collapse happen anywhere in this expression?) and `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'` under any alias; `max(a) - min(b)` reports `aggregate: true` with NO `aggregateFn` (it contains aggregates but is none); a window over an aggregate-shaped function reports neither. Read it rather than inferring the function from the output column NAME, which cannot see through an alias and mistakes `hours * 2 as count` for an aggregate.
196
+ - **An output field's `type`** is the full `ResolvedType`. A COMPUTED one carries `aggregate` (does a group collapse happen anywhere in this expression?) and `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'` under any alias; `max(a) - min(b)` reports `aggregate: true` with NO `aggregateFn` (it contains aggregates but is none); a window over an aggregate-shaped function reports neither. Read it rather than inferring the function from the output column NAME, which cannot see through an alias and mistakes `hours * 2 as count` for an aggregate. Alongside it, and present on exactly the same nodes, are **`aggregateDistinct`** (was the call `DISTINCT`?) and **`aggregateMerge`** — the merge semantics OF THIS CALL, i.e. the function's declared `merge` with the DISTINCT rule already applied: `count(hours)` → `'sum'`, `count(DISTINCT hours)` → `'none'` (de-duplication is global, so two such values cannot be added), `min(DISTINCT hours)` → `'min'` (min/max/and/or are idempotent, so DISTINCT changes nothing). Before `0.6.5` `count(x)` and `count(DISTINCT x)` resolved to IDENTICAL output fields while answering different questions; a consumer folding a tail of groups into an "Other" residual reads `aggregateMerge` and gets a total answer, including for an aggregate a caller registered.
193
197
  - **`includeTotal`** is an execution-time option (not a `SelectDef` field): `run` captures the pre-limit count; `toSQL(query, dialect, { includeTotal: true })` emits `COUNT(*) OVER () AS "$total"`. It applies to the **ENTRY query ONLY** — never a CTE body, a set-operation arm, or a FROM subquery — because `$total` is a PROJECTED column: inside a set-operation arm it participates in the set comparison and would change the **rows** (UNION would stop de-duplicating; INTERSECT / EXCEPT would compare per-arm counts they were never meant to see). So a query whose entry is a **set operation reports NO total** — `result.total` is `undefined` and the SQL carries no `$total` — rather than a wrong one. To page a set operation *and* count it, wrap it in a SELECT over a `subquery` source and ask for the total there.
194
198
  - **`autoPaginate(query)`** adds `limit`/`offset` as bind params idempotently, so paging is just supplying values: `run(paged, { params: { limit, offset } })`. It pages exactly the kinds that HAVE a row bound: a `select`, a set operation (`union`/`intersect`/`except` — the SET-LEVEL bound over the combined rows, never an arm's), and a `cte` (paged through its `final`; a CTE body is an intermediate result). Every other kind (`insert`/`update`/`delete`/`expr`) **throws** `QueryTypeError` `paginate.unsupported-kind` — it used to silently return a query that looked paged and wasn't. `canAutoPaginate(query)` asks first.
195
199
  - **Drill-down.** `drillDown(query, engine)` rebuilds the underlying-rows query behind an aggregate, parameterized (each GROUP BY key pinned to a bind param) — returns `{ query, params, warnings }`. `drillDownInto(query, groupRow, engine)` extracts one aggregated row's key values; then it is the same `run` call. Each aggregate becomes its row-level expression; `count(*)` expands to the FROM type's fields MINUS the ones the SELECT already projects (matched on the EXPRESSION, not the output name), so a group key is projected once. Failures return LLM-friendly `Problems` (`drill.no-aggregation` / `non-invertible` / `having-aggregate` / `window-unsupported`).