@aeye/query 0.6.1 → 0.6.3

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
@@ -337,6 +337,16 @@ const result = await engine.run(query, { params, filters, includeTotal });
337
337
  // result.total — pre-limit row count, when run with `includeTotal: true`
338
338
  ```
339
339
 
340
+ Each field's `type` is the full `ResolvedType`. A **computed** one carries
341
+ `aggregate` (does a group collapse happen anywhere in this expression?) and
342
+ `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS
343
+ one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'`
344
+ under any alias; `max(a) - min(b)` reports `aggregate: true` with NO
345
+ `aggregateFn` (it contains aggregates but is none); a window over an
346
+ aggregate-shaped function reports neither. Read it rather than inferring the
347
+ function from the output column NAME, which cannot see through an alias and
348
+ mistakes `hours * 2 as count` for an aggregate.
349
+
340
350
  Everything composes around that one call:
341
351
 
342
352
  - **Params.** A `param` (`{ kind: 'param', name }`) infers its type from how it
@@ -359,6 +369,25 @@ Everything composes around that one call:
359
369
  `SelectDef` field): `run` captures the pre-limit count into `result.total`,
360
370
  and `toSQL(query, dialect, { includeTotal: true })` emits
361
371
  `COUNT(*) OVER () AS "$total"`.
372
+
373
+ It applies to the **ENTRY query only** — never a CTE body, a set-operation
374
+ arm, or a FROM subquery. `$total` is a PROJECTED column, so an arm that
375
+ carried it would take part in the set comparison and change the **rows**:
376
+ `UNION` would stop de-duplicating, and `INTERSECT` / `EXCEPT` would compare
377
+ per-arm counts they were never meant to see. A query whose entry is a **set
378
+ operation therefore reports no total at all** (`result.total` is `undefined`;
379
+ the SQL carries no `$total`) rather than a wrong one — both engines agree.
380
+ To page a set operation *and* count it, wrap it in a SELECT and count there:
381
+
382
+ ```ts
383
+ const counted = {
384
+ kind: 'select',
385
+ fields: [{ expr: { kind: 'field-ref', source: 's', field: 'id' } }],
386
+ from: { kind: 'subquery', as: 's', query: theUnion },
387
+ limit: 20,
388
+ } satisfies SelectDef;
389
+ await engine.run(counted, { includeTotal: true }); // → { rows, total }
390
+ ```
362
391
  - **Pagination.** `autoPaginate` adds `limit` / `offset` as bind PARAMS, so
363
392
  pagination is just supplying their values:
364
393
 
@@ -369,6 +398,15 @@ Everything composes around that one call:
369
398
  await engine.run(paged, { params: { limit: 10, offset: 0 } });
370
399
  ```
371
400
 
401
+ It pages exactly the kinds that HAVE a row bound: a **`select`** (its own
402
+ LIMIT / OFFSET), a **set operation** (`union` / `intersect` / `except` — the
403
+ SET-LEVEL bound over the combined rows, never an arm's, since paging an arm
404
+ would change which rows the set operation compares), and a **`cte`**, which is
405
+ paged through its `final` query (a CTE body is an intermediate result). Every
406
+ other kind — `insert` / `update` / `delete` / `expr` — has no bound to bind and
407
+ **throws** `QueryTypeError` with code `paginate.unsupported-kind`. Ask first
408
+ with `canAutoPaginate(query)` when you hold an arbitrary `QueryDef`.
409
+
372
410
  - **Drill-down.** `drillDownInto` rebuilds the underlying-rows query and extracts
373
411
  the drill PARAMS from a chosen aggregated row — then it is the same `run` call
374
412
  with those params (see [Drill-down](#drill-down)).
@@ -850,6 +888,13 @@ identifier; suffixed `_2`, `_3`, … on collision with a param the query already
850
888
  uses). Failure cases (`drill.no-aggregation` / `non-invertible` /
851
889
  `having-aggregate` / `window-unsupported`) return LLM-friendly `Problems`.
852
890
 
891
+ Each aggregate is replaced by its underlying row-level expression, and `count(*)`
892
+ — which has no single value — expands to the FROM type's fields MINUS the ones
893
+ the SELECT already projects itself. So `SELECT status, count(*) … GROUP BY status`
894
+ drills to `status` plus the remaining columns, with the group key projected ONCE.
895
+ The skip is keyed on the EXPRESSION (its canonical form), never on the output
896
+ name: two different expressions may legitimately share a name.
897
+
853
898
  ## Cost & estimation
854
899
 
855
900
  Bottom-up estimates driven by each Type's cardinality (`count` rows, `bytes`
package/aeye-query.md CHANGED
@@ -106,7 +106,7 @@ Types and fields declare **what write operations are possible**, and the model f
106
106
  - **Field flags** — `insertable` / `updatable` on a `FieldDef` (default **true**). A field whose `FieldBacking.compute` is set defaults to `insertable:false, updatable:false` (override with an explicit flag). Validation rejects a listed non-insertable field (`insert.field-readonly`) / an assigned non-updatable field (`update.field-readonly`); the paired schema offers only insertable `fields` / updatable `set` fields.
107
107
  - **Insert-requiredness (THE rule)** — a field is REQUIRED on insert iff it is **insertable AND non-nullable AND has no default AND is not computed**; otherwise optional (nullable / has-default) or excluded (non-insertable). One shared helper (`requiredOnInsert`) drives both the schema (required-vs-optional in paired mode) and validation (`insert.missing-required`, which lists the missing names).
108
108
  - **Defaults** — `FieldBacking.default` is a `Value` or a factory `() => Value | Promise<Value>`. Its **presence alone** makes the field optional-on-insert (there is no `hasDefault` flag). At **runtime** an omitted defaulted field is materialized (the value is evaluated / the factory awaited, per row) into the inserted record. In **SQL** the column is simply left out of the INSERT and the database's own column `DEFAULT` fills it — so a JS-factory default is a runtime-only concern.
109
- - **A write CELL carries a JSON value or an expression** — `WriteValueDef = JsonValue | ExprDef`. A raw SCALAR or a whole DOCUMENT (object / array, for a `json` / `array` column) becomes a literal; a `{ kind }` object is read as an EXPRESSION only when the kind names a REGISTERED expr kind, so a settings blob carrying a `kind` key stays data. An absent key OR a JSON `null` OMITS the field (its default fills in / it stays unset); `{ kind:"literal", value:null }` is the only way to set SQL NULL. A document is bound as ONE parameter cast to the COLUMN's type (`Dialect.jsonValue`) — Postgres `CAST($1 AS jsonb)`, or `ARRAY[$1,$2]::text[]` for a native array column, which cannot take JSON text. A param bound to a document is bound, never silently NULL.
109
+ - **A write CELL carries a JSON value or an expression** — `WriteValueDef = JsonValue | ExprDef`. A raw SCALAR or a whole DOCUMENT (object / array, for a `json` / `array` column) becomes a literal; a `{ kind }` object is read as an EXPRESSION only when the kind names a REGISTERED expr kind, so a settings blob carrying a `kind` key stays data. An absent key OR a JSON `null` OMITS the field (its default fills in / it stays unset); `{ kind:"literal", value:null }` is the only way to set SQL NULL. A value written to a `json` / `array` column is JSON-ENCODED and bound as ONE parameter cast to the COLUMN's type (`Dialect.jsonValue`) — Postgres `CAST($1 AS jsonb)`, or `ARRAY[$1,$2]::text[]` for a native array column, which cannot take JSON text. The COLUMN decides, not the value's shape, so a JSON *scalar* into a `json` column (`"a bare string"`, `42`) is encoded and cast like any document rather than bound raw. SQL NULL is the exception: a null literal and an unbound param bind NULL, never the JSON value `null`. A param bound to a document is bound, never silently NULL.
110
110
  - **A write value is checked against its COLUMN** — the cell's expr is walked in the target's scope, a `param` cell is OBSERVED against the column's field type (which is the only place a write param's type can come from), and a value of an incompatible category is refused (`write.type`). A RELATION column is exempt: what you write to it is the target's identity, not a value of the relation's own category.
111
111
  - **Expr restrictions** — `FieldDef.exprs` is `{ not: ExprKind[] }` (exclude these kinds) or `{ only: ExprKind[] }` (allow exactly these). It can only NARROW what the field TYPE already permits. `field.allowsExpr(kind)` respects both the type floor and the restriction. Validation rejects a denied kind at the field's use site (`field.expr-denied`) — checked on a standalone `field-ref` (gated as `field-ref`), on each gating operator's DIRECT field-ref operand (gated as `comparison` / `between` / `in` / `is-null` / `array-op`), and on the field-naming exprs (`text-search` / `text-score` / `semantic` / `filters`). The paired schema omits an excluded field from the relevant enum and gates a kind away entirely when every candidate field excludes it.
112
112
 
@@ -189,9 +189,10 @@ const result = await engine.run(query, { params, filters, includeTotal });
189
189
  // result.total — pre-limit count, when run with includeTotal: true
190
190
  ```
191
191
 
192
- - **`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"`.
193
- - **`autoPaginate(query)`** adds `limit`/`offset` as bind params idempotently, so paging is just supplying values: `run(paged, { params: { limit, offset } })`.
194
- - **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. Failures return LLM-friendly `Problems` (`drill.no-aggregation` / `non-invertible` / `having-aggregate` / `window-unsupported`).
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.
193
+ - **`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
+ - **`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
+ - **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`).
195
196
  - **Standalone exprs.** `engine.evaluateExpr(expr, row?)` evaluates an `Expr`/`ExprDef` against a row; `engine.exprToSQL(expr, dialect)` emits `{ sql, params }` (params never interpolated).
196
197
 
197
198
  ### SQL conversion
package/dist/index.d.ts CHANGED
@@ -1447,6 +1447,34 @@ interface ComputedResolved {
1447
1447
  nullable: boolean;
1448
1448
  /** Whether this computation is (or contains) an aggregate. */
1449
1449
  aggregate: boolean;
1450
+ /**
1451
+ * The APPLIED aggregate function's name (`'sum'`, `'count'`, …) — present
1452
+ * exactly when this value IS one aggregate call, absent when it merely
1453
+ * CONTAINS one (`max(a) - min(b)` is `aggregate: true` with no single applied
1454
+ * function) and absent for every non-aggregate.
1455
+ *
1456
+ * It is a SIBLING of `aggregate` rather than a widening of it because the two
1457
+ * answer different questions: `aggregate` is a property of the whole SUBTREE
1458
+ * ("does a group collapse happen in here?", which drives placement validation
1459
+ * and grouping), while this is a property of ONE node. Folding them into
1460
+ * `false | string` would force a meaningless value for every composite.
1461
+ *
1462
+ * WHY IT EXISTS. Without it, a consumer labelling a computed column has to
1463
+ * recover the function from the column's OUTPUT NAME — `fieldNameOf` is
1464
+ * `as ?? (field-ref ? field : aggregate ? fn : col<i>)`, so an UNALIASED
1465
+ * aggregate's output name IS its function name — and then confirm that name
1466
+ * against the function catalog. That is evidence rather than fact, and it has
1467
+ * two dead spots: an ALIASED aggregate (`sum(hours) as total_hours`) cannot be
1468
+ * recovered at all, and a non-aggregate aliased onto a function name
1469
+ * (`hours * 2 as count`) is a false positive that only `aggregate` then
1470
+ * rejects. Reading this closes both.
1471
+ *
1472
+ * A WINDOW is deliberately excluded, even over an aggregate-shaped function
1473
+ * (`sum(x) OVER (…)`): it is per-row, collapses nothing, and already reports
1474
+ * `aggregate: false`. A scalar `function-call` does not set it either — this
1475
+ * names the aggregate that was APPLIED, not any function that was called.
1476
+ */
1477
+ aggregateFn?: string;
1450
1478
  }
1451
1479
  /** The discriminated union of every expression / source resolution outcome. */
1452
1480
  type ResolvedType = TypeResolved | FieldResolved | ComputedResolved;
@@ -1888,8 +1916,14 @@ interface RuntimeOptions {
1888
1916
  */
1889
1917
  rls?: RlsProvider;
1890
1918
  /**
1891
- * When true, a top-level SELECT also reports `total` — the result count after
1892
- * WHERE/JOIN/GROUP/HAVING/DISTINCT but BEFORE limit/offset.
1919
+ * When true, the ENTRY SELECT also reports `total` — the result count after
1920
+ * WHERE/JOIN/GROUP/HAVING/DISTINCT but BEFORE limit/offset. ONLY the entry
1921
+ * query's total is observable: a NESTED select (a CTE body, a set-op branch, a
1922
+ * FROM subquery) hands its result to a parent that builds a fresh one. So a
1923
+ * query whose ENTRY is a SET OPERATION reports NO `total` — mirroring SQL,
1924
+ * where `$total` is a PROJECTED column and emitting it per arm would change
1925
+ * the set comparison and therefore the ROWS. Wrap the set operation in a
1926
+ * SELECT over a `subquery` source when a paged set operation needs a count.
1893
1927
  */
1894
1928
  includeTotal?: boolean;
1895
1929
  /** Embedder override (defaults to the engine's). */
@@ -3340,7 +3374,17 @@ declare class AggregateExpr extends Expr {
3340
3374
  static toSchema(opts: SchemaOptions): z.ZodTypeAny;
3341
3375
  protected aggregateHere(): boolean;
3342
3376
  forEachChild(visit: (child: Expr) => void): void;
3343
- /** Resolve to the function's declared output type, marked aggregate and nullable (except `count`). */
3377
+ /**
3378
+ * Resolve to the function's declared output type, marked aggregate and nullable
3379
+ * (except `count`), and carrying the APPLIED function's name.
3380
+ *
3381
+ * `aggregateFn` is set on BOTH roads — including the unknown-function fallback,
3382
+ * where the name is still the fact of what was written even though the
3383
+ * resolution is a placeholder. This is the ONE node that can answer "which
3384
+ * aggregate is this?": every wrapping expr reports `aggregate: true` from its
3385
+ * children without a single applied function, and `Function.resolveOutput`
3386
+ * never sets it, so nothing propagates a stale name upward.
3387
+ */
3344
3388
  resolve(engine: QueryEngine, scope: QueryScope): ResolvedType;
3345
3389
  /** Validate aggregate placement (not in WHERE, not nested) and the function's own named-arg checks. */
3346
3390
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): ResolvedType;
@@ -4466,8 +4510,16 @@ declare class SqlContext {
4466
4510
  */
4467
4511
  readonly filters: Readonly<Record<string, Expr>>;
4468
4512
  /**
4469
- * Whether the (top-level) SELECT should emit `COUNT(*) OVER () AS "$total"`.
4470
- * Reset to false at nested levels (a subquery never emits the outer total).
4513
+ * Whether the ENTRY (root) SELECT should emit `COUNT(*) OVER () AS "$total"`.
4514
+ * Cleared at EVERY nesting boundary — `withPlanner` for a subquery / FROM
4515
+ * subquery, `nonRoot()` for a CTE body / set-op branch — so `$total` is only
4516
+ * ever a column of the query the caller actually asked to count.
4517
+ *
4518
+ * That is not an optimization. `$total` is a PROJECTED column, so inside a
4519
+ * set-operation arm it participates in the set comparison and silently
4520
+ * corrupts the ROWS: UNION stops de-duplicating, and INTERSECT / EXCEPT
4521
+ * compare per-arm counts they were never meant to see. A CTE body would
4522
+ * additionally pay a window aggregate nothing selects.
4471
4523
  */
4472
4524
  readonly includeTotal: boolean;
4473
4525
  /**
@@ -4520,8 +4572,16 @@ declare class SqlContext {
4520
4572
  */
4521
4573
  filters?: Readonly<Record<string, Expr>>,
4522
4574
  /**
4523
- * Whether the (top-level) SELECT should emit `COUNT(*) OVER () AS "$total"`.
4524
- * Reset to false at nested levels (a subquery never emits the outer total).
4575
+ * Whether the ENTRY (root) SELECT should emit `COUNT(*) OVER () AS "$total"`.
4576
+ * Cleared at EVERY nesting boundary — `withPlanner` for a subquery / FROM
4577
+ * subquery, `nonRoot()` for a CTE body / set-op branch — so `$total` is only
4578
+ * ever a column of the query the caller actually asked to count.
4579
+ *
4580
+ * That is not an optimization. `$total` is a PROJECTED column, so inside a
4581
+ * set-operation arm it participates in the set comparison and silently
4582
+ * corrupts the ROWS: UNION stops de-duplicating, and INTERSECT / EXCEPT
4583
+ * compare per-arm counts they were never meant to see. A CTE body would
4584
+ * additionally pay a window aggregate nothing selects.
4525
4585
  */
4526
4586
  includeTotal?: boolean,
4527
4587
  /**
@@ -4565,6 +4625,9 @@ declare class SqlContext {
4565
4625
  * Mark the NEXT emitted query as NON-root (same level otherwise). Used at the
4566
4626
  * boundaries `withPlanner` does not cover — a CTE body and a set-operation
4567
4627
  * branch — so those nested SELECTs never inherit the entry's root status.
4628
+ * It clears `includeTotal` for the same reason `withPlanner` does: `$total` is
4629
+ * a PROJECTED column, and a nested SELECT that projects it changes what the
4630
+ * enclosing statement sees (see the `includeTotal` field docs).
4568
4631
  */
4569
4632
  nonRoot(): SqlContext;
4570
4633
  }
@@ -5925,7 +5988,16 @@ interface BaseSqlOptions {
5925
5988
  filters?: Record<string, ExprDef | Expr | null>;
5926
5989
  /** Execution-time dynamic-sort selection, feeding a SELECT `order`'s `sorter`. */
5927
5990
  sort?: SortSelectionDef[];
5928
- /** Emit `COUNT(*) OVER () AS "$total"` on the top-level SELECT. */
5991
+ /**
5992
+ * Emit `COUNT(*) OVER () AS "$total"` on the ENTRY SELECT — and ONLY there.
5993
+ * Every nesting boundary clears it, because `$total` is a PROJECTED column: an
5994
+ * arm's `$total` participates in a set operation's comparison and silently
5995
+ * changes the ROWS (UNION stops de-duplicating; INTERSECT / EXCEPT compare
5996
+ * counts they were never meant to see), and a CTE body would pay a window
5997
+ * aggregate nothing selects. A query whose ENTRY is a SET OPERATION therefore
5998
+ * emits no `$total` at all — matching `run`, which reports none. Wrap it in a
5999
+ * SELECT over a `subquery` source when a paged set operation needs a count.
6000
+ */
5929
6001
  includeTotal?: boolean;
5930
6002
  }
5931
6003
  /** Options for {@link QueryEngine.toSQL}. */
@@ -6129,7 +6201,8 @@ declare class QueryEngine {
6129
6201
  * `opts.filters` (keyed by source) feeds the `filters` placeholders' clauses;
6130
6202
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
6131
6203
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
6132
- * "$total"` column on the top-level SELECT.
6204
+ * "$total"` column on the ENTRY SELECT only (a set operation gets none — see
6205
+ * {@link BaseSqlOptions.includeTotal}).
6133
6206
  *
6134
6207
  * `opts.embeddings` is a precomputed text→vector cache (see {@link
6135
6208
  * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
@@ -9513,24 +9586,42 @@ interface InferOptions {
9513
9586
  declare function inferType(name: string, rows: ReadonlyArray<Record<string, JsonValue>>, opts?: InferOptions): TypeDef;
9514
9587
 
9515
9588
  /**
9516
- * `autoPaginate` — a SELECT transform that binds pagination to named bind
9517
- * PARAMETERS, so a single LLM-authored query becomes a reusable, paged
9518
- * artifact (the caller supplies `limit` / `offset` values at run/emit time).
9589
+ * `autoPaginate` — a transform that binds a query's pagination to named bind
9590
+ * PARAMETERS, so a single LLM-authored query becomes a reusable, paged artifact
9591
+ * (the caller supplies `limit` / `offset` values at run/emit time).
9519
9592
  *
9520
9593
  * Behaviour:
9521
- * - If the select does NOT already constrain `limit`, a `param` expr named
9594
+ * - If the query does NOT already constrain `limit`, a `param` expr named
9522
9595
  * `opts.limitParam` (default `'limit'`) is added.
9523
- * - If the select does NOT already constrain `offset`, a `param` expr named
9596
+ * - If the query does NOT already constrain `offset`, a `param` expr named
9524
9597
  * `opts.offsetParam` (default `'offset'`) is added.
9525
9598
  * - Each is independent: a query that already pins `limit` (literal or param)
9526
9599
  * but not `offset` only gains an `offset` param.
9527
9600
  *
9528
- * The transform is IDEMPOTENT — running it twice yields a structurally
9529
- * identical result, because an already-present `limit` / `offset` (whether a
9530
- * literal number or a param this transform added) is left untouched.
9601
+ * WHICH QUERIES IT PAGES — and why it refuses the rest. Pagination is a bound on
9602
+ * the ROWS a statement returns, so the transform is defined exactly on the kinds
9603
+ * that carry one:
9604
+ * - `select` — its own LIMIT / OFFSET;
9605
+ * - `union` / `intersect` / `except` — the SET-LEVEL LIMIT / OFFSET applied to
9606
+ * the combined rows (never to an arm: paging an arm changes which rows the
9607
+ * set operation compares);
9608
+ * - `cte` — a `WITH` statement returns whatever its `final` query returns, so
9609
+ * the bounds are bound on `final` (recursively). Paging a CTE BODY would page
9610
+ * an intermediate result, which is a different query.
9611
+ *
9612
+ * Every other kind — `insert` / `update` / `delete` / `expr` — has no row bound
9613
+ * to bind. Asking for one used to be SILENT: the JSON branch spread whatever it
9614
+ * was given and set `limit` / `offset` on the copy, so a `cte` came back looking
9615
+ * paged while the parser dropped both keys and the statement returned every row.
9616
+ * It now throws a {@link QueryTypeError} (`paginate.unsupported-kind`) instead.
9617
+ * Use {@link canAutoPaginate} to ask first when holding an arbitrary `QueryDef`.
9531
9618
  *
9532
- * It never mutates its argument: a `SelectQuery` in produces a fresh
9533
- * `SelectQuery`; a `SelectDef` in produces a fresh `SelectDef`.
9619
+ * The transform is IDEMPOTENT — running it twice yields a structurally identical
9620
+ * result, because an already-present `limit` / `offset` (whether a literal number
9621
+ * or a param this transform added) is left untouched.
9622
+ *
9623
+ * It never mutates its argument: a `Query` in produces a fresh `Query`; a
9624
+ * `QueryDef` in produces a fresh `QueryDef`.
9534
9625
  */
9535
9626
 
9536
9627
  /** Options controlling the auto-paginate transform. */
@@ -9545,14 +9636,38 @@ interface AutoPaginateOptions {
9545
9636
  offset?: boolean;
9546
9637
  }
9547
9638
  /**
9548
- * Bind a SELECT's pagination to named bind params: add a `limit` / `offset`
9549
- * param (per `opts`) wherever the query does not already constrain that bound.
9550
- * Idempotent and non-mutating — returns a fresh `SelectQuery` / `SelectDef`
9551
- * mirroring the input shape.
9639
+ * The authored query kinds {@link autoPaginate} accepts: the ones carrying a row
9640
+ * bound of their own (`select`, the three set operations) plus `cte`, which
9641
+ * delegates to its `final` query.
9642
+ */
9643
+ type PaginatableDef = SelectDef | SetOperationDef | CTEStatementDef;
9644
+ /** The parsed counterparts of {@link PaginatableDef}. */
9645
+ type PaginatableQuery = SelectQuery | SetOperationQuery | CTEStatementQuery;
9646
+ /**
9647
+ * Whether {@link autoPaginate} can page this query — true for `select`, the set
9648
+ * operations, and `cte` (whose `final` is paged in turn). Ask this when holding
9649
+ * an arbitrary `Query` / `QueryDef`; `autoPaginate` throws otherwise.
9650
+ */
9651
+ declare function canAutoPaginate(query: Query | QueryDef): boolean;
9652
+ /**
9653
+ * Bind a query's pagination to named bind params: add a `limit` / `offset` param
9654
+ * (per `opts`) wherever the query does not already constrain that bound. A `cte`
9655
+ * statement is paged through its `final` query. Idempotent and non-mutating —
9656
+ * returns a fresh `Query` / `QueryDef` mirroring the input shape.
9657
+ *
9658
+ * @throws {QueryTypeError} `paginate.unsupported-kind` for a query kind that has
9659
+ * no row bound (`insert` / `update` / `delete` / `expr`) — see
9660
+ * {@link canAutoPaginate}.
9552
9661
  */
9553
9662
  declare function autoPaginate(select: SelectQuery, opts?: AutoPaginateOptions): SelectQuery;
9554
9663
  declare function autoPaginate(select: SelectDef, opts?: AutoPaginateOptions): SelectDef;
9555
- declare function autoPaginate(select: SelectQuery | SelectDef, opts?: AutoPaginateOptions): SelectQuery | SelectDef;
9664
+ declare function autoPaginate(query: SetOperationQuery, opts?: AutoPaginateOptions): SetOperationQuery;
9665
+ declare function autoPaginate(query: SetOperationDef, opts?: AutoPaginateOptions): SetOperationDef;
9666
+ declare function autoPaginate(query: CTEStatementQuery, opts?: AutoPaginateOptions): CTEStatementQuery;
9667
+ declare function autoPaginate(query: CTEStatementDef, opts?: AutoPaginateOptions): CTEStatementDef;
9668
+ declare function autoPaginate(query: PaginatableQuery, opts?: AutoPaginateOptions): PaginatableQuery;
9669
+ declare function autoPaginate(query: PaginatableDef, opts?: AutoPaginateOptions): PaginatableDef;
9670
+ declare function autoPaginate(query: PaginatableQuery | PaginatableDef, opts?: AutoPaginateOptions): PaginatableQuery | PaginatableDef;
9556
9671
 
9557
9672
  /**
9558
9673
  * `drillDown` — aggregate UN-RAVELLING, PARAMETERIZED (plan algorithm "(d)").
@@ -9574,7 +9689,8 @@ declare function autoPaginate(select: SelectQuery | SelectDef, opts?: AutoPagina
9574
9689
  * AGGREGATED query's OUTPUT field that carries that key's value per row.
9575
9690
  * No `groupRow`, no literals.
9576
9691
  * 3. Replace each aggregate SELECT item with its underlying non-aggregated
9577
- * expr: `sum(o.total)` → `o.total`, `count(*)` → all FROM fields. An
9692
+ * expr: `sum(o.total)` → `o.total`, `count(*)` → every FROM field the SELECT
9693
+ * does not already project itself (so a group key is not duplicated). An
9578
9694
  * aggregate over a non-field argument (a literal / param) is
9579
9695
  * `drill.non-invertible` (names the offending alias).
9580
9696
  * 4. Drop GROUP BY / HAVING. A HAVING clause that references group keys (no
@@ -10112,4 +10228,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
10112
10228
  */
10113
10229
  declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
10114
10230
 
10115
- export { AID_REGISTRY, type Access, type AccessRun, type AccessSql, AggregateExpr, type AggregateExprDef, type AggregateRun, type AidInfo, type AidOptions, type AliasedSourceDef, type ArgExprDef, ArrayFieldType, type ArrayFieldTypeDef, type ArrayOp, ArrayOpExpr, type ArrayOpExprDef, type AutoPaginateOptions, BUILTIN_EXPRS, BUILTIN_FIELD_TYPES, BUILTIN_LIBRARY, BUILTIN_QUERIES, Backing, BaseDialect, BetweenExpr, type BetweenExprDef, BinaryExpr, type BinaryExprDef, type BinaryOp, BoolExpr, BoolFieldType, type BoolFieldTypeDef, type BuildQueryToolOptions, type BuildSchemasOptions, type BuiltinFunction, type CTEDef, type CTERecursiveDef, type CTEStatementDef, CTEStatementQuery, type CaseBranchDef, type CaseBranchSpec, CaseExpr, type CaseExprDef, Code, type CodeLine, type CodeOptions, ComparisonExpr, type ComparisonExprDef, type ComparisonOp, type ComputeRun, type ComputeSql, type Computed, type ComputedResolved, type Cost, type CostConstraints, DEFAULT_MAX_CTE_ITERATIONS, DEFAULT_MAX_EXAMPLES, DEFAULT_MAX_QUERY_SCHEMA_TYPES, DateFieldType, type DateFieldTypeDef, type DefaultCondition, type DefaultConditionOp, type DefaultOrder, type DefaultOrderDir, type DefaultOrderScope, type DefaultOrderTerm, type DeleteDef, DeleteQuery, type DescribeEngineOptions, type DescribeOverrides, Dialect, type DialectEntry, type DrillDownFailure, type DrillDownIntoSuccess, type DrillDownResult, type DrillDownSuccess, type DrillParam, type DrillValue, EQ_SELECTIVITY, type Embedder, ExcludedExpr, type ExcludedExprDef, type ExecutorContext, ExistsExpr, type ExistsExprDef, Expr, type ExprClass, type ExprClassEntry, type ExprDef, type ExprKind, ExprQuery, type ExprQueryDef, Field, type FieldBacking, type FieldDef, type FieldExprRestriction, FieldRefExpr, type FieldRefExprDef, type FieldResolved, type FieldSpec, FieldType, type FieldTypeClass, type FieldTypeDef, type FieldTypeKind, type FieldValueDef, type FilterDepth, FiltersExpr, type FiltersExprDef, type FnDepth, type FormatOptions, type FormatProblemsOptions, FunctionCallExpr, type FunctionCallExprDef, type FunctionDef, type FunctionParamDef, type FunctionRun, type FunctionSelector, type FunctionShape, type FunctionSourceDef, IN_SELECTIVITY, InExpr, type InExprDef, Index, type IndexDef, IndexPart, type IndexPartDef, type InferOptions, type InsertDef, InsertQuery, type InsertRowDef, IsNullExpr, type IsNullExprDef, type JSONEntry, type JoinBacking, JoinCtePlanner, type JoinDef, type JoinHop, type JoinOnDef, type JoinRequest, type JoinRunPlan, type JoinSpec, type JoinSqlPlan, type JoinType, JsonFieldType, type JsonFieldTypeDef, type JsonValue, type LateralJoinSpec, LiteralExpr, type LiteralExprDef, LogicalExpr, type LogicalExprDef, type LogicalOp, type MaybePromise, type Meta, MoneyFieldType, type MoneyFieldTypeDef, type MoneyOptions, type NameDepth, type NamedArgs, type Node, NumberFieldType, type NumberFieldTypeDef, type NumberOptions, type OnConflictDef, type OrderDef, type OrderEntry, OutputRefExpr, type OutputRefExprDef, type ParamDef, ParamExpr, type ParamExprDef, ParamSet, PostgresDialect, type Problem, Problems, Query, type QueryClass, type QueryClassEntry, type QueryDef, QueryEngine, type QueryEngineOptions, type QueryField, QueryFunction, QueryJoin, type QueryKind, QueryOrder, type QueryResult, type QueryResultArray, type QuerySchemaOptions, type QuerySchemas, QueryScope, QuerySource, QueryToolError, type QueryToolInput, QueryTypeError, type QueryValidator, RANGE_SELECTIVITY, ROOT_VALIDATE_CONTEXT, type RefDepth, Registry, type RelationBacking, RelationFieldType, type RelationFieldTypeDef, type RelationJoinOnDef, type RelationJoinSpec, type RelationKey, type RelationKeyPair, type RelationOn, type RelationOnPair, type RelationResolved, type RenderedSql, type ResolvedSchemaDepth, type ResolvedType, type RlsProvider, RuntimeContext, type RuntimeJoin, type RuntimeOptions, SEMANTIC_ROW_PENALTY, type ScalarKind, type ScalarRun, type ScalarValue, type SchemaDepth, type SchemaOptions, type SearchBacking, type SelectDef, type SelectFieldDef, SelectQuery, type SelectTypesOptions, type SelectedFunctions, type SemanticBacking, type SemanticEmbeddings, SemanticExpr, type SemanticExprDef, type SemanticQueryDef, type SemanticTextToVector, type SetDef, type SetOperationDef, SetOperationQuery, type SortEntryDef, type SortSelectionDef, type SorterDef, SorterExpr, type SourceDef, type SourceFieldOptionalRef, type SourceFieldRef, type SourceFieldsRef, type SourceRecord, type SourceRow, type Span, type SpanMeta, SqlContext, type SqlParamValue, SqlText, type SqlValue, SubqueryExpr, type SubqueryExprDef, type SubquerySourceDef, TEXT_SEARCH_ROW_PENALTY, TabularFunctionCallExpr, type TabularFunctionCallExprDef, type TabularRun, TextFieldType, type TextFieldTypeDef, type TextOptions, TextScoreExpr, type TextScoreExprDef, TextSearchExpr, type TextSearchExprDef, TimestampFieldType, type TimestampFieldTypeDef, type TimezonePolicy, type ToSqlOptions, Type, type TypeBacking, type TypeDef, type TypeExecutor, type TypeFieldRef, type TypeResolved, type TypeSourceDef, type TypeSpec, type TypeState, UnaryExpr, type UnaryExprDef, type UnaryOp, type UpdateDef, UpdateQuery, type ValidateContext, Value, type ValueCategory, type ValueSchemaOptions, WINDOW_ORDER_ARG, WindowExpr, type WindowExprDef, type WindowOrderSpec, type WindowRun, type WriteValueDef, ZERO_COST, add, addCost, age, agg, aidInfo, aliasedDigest, and, arrayAgg, arrayAppend, arrayConcat, arrayContains, arrayDistinct, arrayExecutor, arrayIndexOf, arrayPrepend, arrayRemove, arraySlice, arrayToString, asFieldType, autoPaginate, avg, between, boolAnd, boolOr, buildQueryTool, buildSchemas, builtinDialects, bytesOfResolved, canonicalize, caseExpr, cloneRecord, code, concat, contains, containsAll, containsAny, count, countIf, countStar, createRegistry, currentTime, currentTimestamp, dateAdd, dateDiff, dateFormat, datePart, dateTrunc, day, dayOfWeek, dayOfYear, defaultConditionOps, defaultConditionWithout, depthInstructions, describeDialects, describeEngine, describeExprs, describeFunctions, describeInput, describeQueryExamples, describeType, describeTypes, didYouMean, directedMessage, div, drillDown, drillDownInto, e, editDistance, embeddingResolver, epoch, eq, excluded, exists, exprDefSchema, exprDigest, fieldMeta, fieldNameOf, fieldTypeDefSchema, filters, firstField, fn, fromEpoch, generatedFieldDescription, generatedFieldLabel, generatedTypeDescription, generatedTypeLabel, gt, gte, hour, humanize, ilike, inList, inSubquery, inferType, isEmpty, isNull, isScalar, isScalarValue, isType, isVectorText, join, joinAlias, joinCode, joinLines, jsonValueSchema, like, lit, lt, lte, makeDate, makeField, makeResult, max, maxCost, mergeRows, min, minute, mod, month, mul, nearest, nearestKind, neg, neq, not, notBetween, notEmpty, notExists, notInList, notInSubquery, notLike, notNull, or, output, param, parseQueryRequest, parseQueryTool, parseVectorText, plain, pos, querySchema, raw, recordKey, recordSignature, ref, relJoin, relationKeyColumns, relationOf, renameSource, reportCostProblems, resolveAccessRun, resolveAccessSql, resolveComputeRun, resolveComputeSql, resolveDefaultConditionRun, resolveDefaultConditionSql, resolveFields, resolveJoinRun, resolveJoinSql, resolveSchemaDepth, rlsPredicate, rowsCost, runAggregateFunction, runScalarFunction, runTabularFunction, runWindowFunction, scaleRows, second, selectFunctions, selectTypes, semantic, shouldUseStringSchema, singleRow, sortEntries, sourcesOf, span, stddev, stringAgg, stringToArray, sub, subquery, suggestionBudget, sum, syntheticType, tableFn, textScore, textSearch, timezoneSchema, toArrayRows, toVectorText, typeFromFields, typeMeta, value, valueFieldType, variance, week, when, widenNullable, window, withAid, year };
10231
+ export { AID_REGISTRY, type Access, type AccessRun, type AccessSql, AggregateExpr, type AggregateExprDef, type AggregateRun, type AidInfo, type AidOptions, type AliasedSourceDef, type ArgExprDef, ArrayFieldType, type ArrayFieldTypeDef, type ArrayOp, ArrayOpExpr, type ArrayOpExprDef, type AutoPaginateOptions, BUILTIN_EXPRS, BUILTIN_FIELD_TYPES, BUILTIN_LIBRARY, BUILTIN_QUERIES, Backing, BaseDialect, BetweenExpr, type BetweenExprDef, BinaryExpr, type BinaryExprDef, type BinaryOp, BoolExpr, BoolFieldType, type BoolFieldTypeDef, type BuildQueryToolOptions, type BuildSchemasOptions, type BuiltinFunction, type CTEDef, type CTERecursiveDef, type CTEStatementDef, CTEStatementQuery, type CaseBranchDef, type CaseBranchSpec, CaseExpr, type CaseExprDef, Code, type CodeLine, type CodeOptions, ComparisonExpr, type ComparisonExprDef, type ComparisonOp, type ComputeRun, type ComputeSql, type Computed, type ComputedResolved, type Cost, type CostConstraints, DEFAULT_MAX_CTE_ITERATIONS, DEFAULT_MAX_EXAMPLES, DEFAULT_MAX_QUERY_SCHEMA_TYPES, DateFieldType, type DateFieldTypeDef, type DefaultCondition, type DefaultConditionOp, type DefaultOrder, type DefaultOrderDir, type DefaultOrderScope, type DefaultOrderTerm, type DeleteDef, DeleteQuery, type DescribeEngineOptions, type DescribeOverrides, Dialect, type DialectEntry, type DrillDownFailure, type DrillDownIntoSuccess, type DrillDownResult, type DrillDownSuccess, type DrillParam, type DrillValue, EQ_SELECTIVITY, type Embedder, ExcludedExpr, type ExcludedExprDef, type ExecutorContext, ExistsExpr, type ExistsExprDef, Expr, type ExprClass, type ExprClassEntry, type ExprDef, type ExprKind, ExprQuery, type ExprQueryDef, Field, type FieldBacking, type FieldDef, type FieldExprRestriction, FieldRefExpr, type FieldRefExprDef, type FieldResolved, type FieldSpec, FieldType, type FieldTypeClass, type FieldTypeDef, type FieldTypeKind, type FieldValueDef, type FilterDepth, FiltersExpr, type FiltersExprDef, type FnDepth, type FormatOptions, type FormatProblemsOptions, FunctionCallExpr, type FunctionCallExprDef, type FunctionDef, type FunctionParamDef, type FunctionRun, type FunctionSelector, type FunctionShape, type FunctionSourceDef, IN_SELECTIVITY, InExpr, type InExprDef, Index, type IndexDef, IndexPart, type IndexPartDef, type InferOptions, type InsertDef, InsertQuery, type InsertRowDef, IsNullExpr, type IsNullExprDef, type JSONEntry, type JoinBacking, JoinCtePlanner, type JoinDef, type JoinHop, type JoinOnDef, type JoinRequest, type JoinRunPlan, type JoinSpec, type JoinSqlPlan, type JoinType, JsonFieldType, type JsonFieldTypeDef, type JsonValue, type LateralJoinSpec, LiteralExpr, type LiteralExprDef, LogicalExpr, type LogicalExprDef, type LogicalOp, type MaybePromise, type Meta, MoneyFieldType, type MoneyFieldTypeDef, type MoneyOptions, type NameDepth, type NamedArgs, type Node, NumberFieldType, type NumberFieldTypeDef, type NumberOptions, type OnConflictDef, type OrderDef, type OrderEntry, OutputRefExpr, type OutputRefExprDef, type PaginatableDef, type PaginatableQuery, type ParamDef, ParamExpr, type ParamExprDef, ParamSet, PostgresDialect, type Problem, Problems, Query, type QueryClass, type QueryClassEntry, type QueryDef, QueryEngine, type QueryEngineOptions, type QueryField, QueryFunction, QueryJoin, type QueryKind, QueryOrder, type QueryResult, type QueryResultArray, type QuerySchemaOptions, type QuerySchemas, QueryScope, QuerySource, QueryToolError, type QueryToolInput, QueryTypeError, type QueryValidator, RANGE_SELECTIVITY, ROOT_VALIDATE_CONTEXT, type RefDepth, Registry, type RelationBacking, RelationFieldType, type RelationFieldTypeDef, type RelationJoinOnDef, type RelationJoinSpec, type RelationKey, type RelationKeyPair, type RelationOn, type RelationOnPair, type RelationResolved, type RenderedSql, type ResolvedSchemaDepth, type ResolvedType, type RlsProvider, RuntimeContext, type RuntimeJoin, type RuntimeOptions, SEMANTIC_ROW_PENALTY, type ScalarKind, type ScalarRun, type ScalarValue, type SchemaDepth, type SchemaOptions, type SearchBacking, type SelectDef, type SelectFieldDef, SelectQuery, type SelectTypesOptions, type SelectedFunctions, type SemanticBacking, type SemanticEmbeddings, SemanticExpr, type SemanticExprDef, type SemanticQueryDef, type SemanticTextToVector, type SetDef, type SetOperationDef, SetOperationQuery, type SortEntryDef, type SortSelectionDef, type SorterDef, SorterExpr, type SourceDef, type SourceFieldOptionalRef, type SourceFieldRef, type SourceFieldsRef, type SourceRecord, type SourceRow, type Span, type SpanMeta, SqlContext, type SqlParamValue, SqlText, type SqlValue, SubqueryExpr, type SubqueryExprDef, type SubquerySourceDef, TEXT_SEARCH_ROW_PENALTY, TabularFunctionCallExpr, type TabularFunctionCallExprDef, type TabularRun, TextFieldType, type TextFieldTypeDef, type TextOptions, TextScoreExpr, type TextScoreExprDef, TextSearchExpr, type TextSearchExprDef, TimestampFieldType, type TimestampFieldTypeDef, type TimezonePolicy, type ToSqlOptions, Type, type TypeBacking, type TypeDef, type TypeExecutor, type TypeFieldRef, type TypeResolved, type TypeSourceDef, type TypeSpec, type TypeState, UnaryExpr, type UnaryExprDef, type UnaryOp, type UpdateDef, UpdateQuery, type ValidateContext, Value, type ValueCategory, type ValueSchemaOptions, WINDOW_ORDER_ARG, WindowExpr, type WindowExprDef, type WindowOrderSpec, type WindowRun, type WriteValueDef, ZERO_COST, add, addCost, age, agg, aidInfo, aliasedDigest, and, arrayAgg, arrayAppend, arrayConcat, arrayContains, arrayDistinct, arrayExecutor, arrayIndexOf, arrayPrepend, arrayRemove, arraySlice, arrayToString, asFieldType, autoPaginate, avg, between, boolAnd, boolOr, buildQueryTool, buildSchemas, builtinDialects, bytesOfResolved, canAutoPaginate, canonicalize, caseExpr, cloneRecord, code, concat, contains, containsAll, containsAny, count, countIf, countStar, createRegistry, currentTime, currentTimestamp, dateAdd, dateDiff, dateFormat, datePart, dateTrunc, day, dayOfWeek, dayOfYear, defaultConditionOps, defaultConditionWithout, depthInstructions, describeDialects, describeEngine, describeExprs, describeFunctions, describeInput, describeQueryExamples, describeType, describeTypes, didYouMean, directedMessage, div, drillDown, drillDownInto, e, editDistance, embeddingResolver, epoch, eq, excluded, exists, exprDefSchema, exprDigest, fieldMeta, fieldNameOf, fieldTypeDefSchema, filters, firstField, fn, fromEpoch, generatedFieldDescription, generatedFieldLabel, generatedTypeDescription, generatedTypeLabel, gt, gte, hour, humanize, ilike, inList, inSubquery, inferType, isEmpty, isNull, isScalar, isScalarValue, isType, isVectorText, join, joinAlias, joinCode, joinLines, jsonValueSchema, like, lit, lt, lte, makeDate, makeField, makeResult, max, maxCost, mergeRows, min, minute, mod, month, mul, nearest, nearestKind, neg, neq, not, notBetween, notEmpty, notExists, notInList, notInSubquery, notLike, notNull, or, output, param, parseQueryRequest, parseQueryTool, parseVectorText, plain, pos, querySchema, raw, recordKey, recordSignature, ref, relJoin, relationKeyColumns, relationOf, renameSource, reportCostProblems, resolveAccessRun, resolveAccessSql, resolveComputeRun, resolveComputeSql, resolveDefaultConditionRun, resolveDefaultConditionSql, resolveFields, resolveJoinRun, resolveJoinSql, resolveSchemaDepth, rlsPredicate, rowsCost, runAggregateFunction, runScalarFunction, runTabularFunction, runWindowFunction, scaleRows, second, selectFunctions, selectTypes, semantic, shouldUseStringSchema, singleRow, sortEntries, sourcesOf, span, stddev, stringAgg, stringToArray, sub, subquery, suggestionBudget, sum, syntheticType, tableFn, textScore, textSearch, timezoneSchema, toArrayRows, toVectorText, typeFromFields, typeMeta, value, valueFieldType, variance, week, when, widenNullable, window, withAid, year };
package/dist/index.js CHANGED
@@ -3060,8 +3060,9 @@ import { z as z15 } from "zod";
3060
3060
 
3061
3061
  // src/exprs/_shared.ts
3062
3062
  import { z as z14 } from "zod";
3063
- function computed(fieldType, sources, nullable, aggregate2) {
3064
- return { kind: "computed", fieldType, sources, nullable, aggregate: aggregate2 };
3063
+ function computed(fieldType, sources, nullable, aggregate2, aggregateFn) {
3064
+ const rt = { kind: "computed", fieldType, sources, nullable, aggregate: aggregate2 };
3065
+ return aggregateFn === void 0 ? rt : { ...rt, aggregateFn };
3065
3066
  }
3066
3067
  function boolResult(sources, nullable, aggregate2 = false) {
3067
3068
  return computed(new BoolFieldType(), sources, nullable, aggregate2);
@@ -3244,9 +3245,12 @@ var SqlContext = class _SqlContext {
3244
3245
  * Mark the NEXT emitted query as NON-root (same level otherwise). Used at the
3245
3246
  * boundaries `withPlanner` does not cover — a CTE body and a set-operation
3246
3247
  * branch — so those nested SELECTs never inherit the entry's root status.
3248
+ * It clears `includeTotal` for the same reason `withPlanner` does: `$total` is
3249
+ * a PROJECTED column, and a nested SELECT that projects it changes what the
3250
+ * enclosing statement sees (see the `includeTotal` field docs).
3247
3251
  */
3248
3252
  nonRoot() {
3249
- return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, this.includeTotal, false, this.sortSpec, this.semanticText);
3253
+ return new _SqlContext(this.dialect, this.engine, this.scope, this.planner, this.rls, this.inAggregate, this.params, this.filters, false, false, this.sortSpec, this.semanticText);
3250
3254
  }
3251
3255
  };
3252
3256
 
@@ -7132,16 +7136,26 @@ var AggregateExpr = class _AggregateExpr extends Expr {
7132
7136
  forEachChild(visit) {
7133
7137
  for (const a of this.args.values()) visit(a);
7134
7138
  }
7135
- /** Resolve to the function's declared output type, marked aggregate and nullable (except `count`). */
7139
+ /**
7140
+ * Resolve to the function's declared output type, marked aggregate and nullable
7141
+ * (except `count`), and carrying the APPLIED function's name.
7142
+ *
7143
+ * `aggregateFn` is set on BOTH roads — including the unknown-function fallback,
7144
+ * where the name is still the fact of what was written even though the
7145
+ * resolution is a placeholder. This is the ONE node that can answer "which
7146
+ * aggregate is this?": every wrapping expr reports `aggregate: true` from its
7147
+ * children without a single applied function, and `Function.resolveOutput`
7148
+ * never sets it, so nothing propagates a stale name upward.
7149
+ */
7136
7150
  resolve(engine, scope) {
7137
7151
  const fn2 = engine.lookupFunction(this.fn);
7138
7152
  if (!fn2) {
7139
- return computed(new NumberFieldType(), [], true, true);
7153
+ return computed(new NumberFieldType(), [], true, true, this.fn);
7140
7154
  }
7141
7155
  const base = fn2.resolveOutput(resolveNamedArgs(this.args, engine, scope));
7142
7156
  if (base.kind !== "computed") return base;
7143
7157
  const nullable = this.fn !== "count";
7144
- return { ...base, nullable, aggregate: true };
7158
+ return { ...base, nullable, aggregate: true, aggregateFn: this.fn };
7145
7159
  }
7146
7160
  /** Validate aggregate placement (not in WHERE, not nested) and the function's own named-arg checks. */
7147
7161
  validateWalk(engine, scope, p, ctx) {
@@ -9996,16 +10010,19 @@ function validateWriteValue(engine, scope, p, ctx, field, expr) {
9996
10010
  }
9997
10011
  }
9998
10012
  function writeCellSql(expr, field, dialect, ctx) {
9999
- const document = writeDocument(expr, ctx);
10000
- return document !== void 0 ? dialect.jsonValue(document, field?.fieldType) : expr.toSQL(dialect, ctx);
10001
- }
10002
- function writeDocument(expr, ctx) {
10003
- if (expr instanceof LiteralExpr) {
10004
- return expr.value !== null && typeof expr.value === "object" ? expr.value : void 0;
10013
+ const value2 = writeCellValue(expr, ctx);
10014
+ if (value2 !== void 0 && value2 !== null && (typeof value2 === "object" || isJsonColumn(field))) {
10015
+ return dialect.jsonValue(value2, field?.fieldType);
10005
10016
  }
10017
+ return expr.toSQL(dialect, ctx);
10018
+ }
10019
+ function isJsonColumn(field) {
10020
+ return field?.fieldType.resolve() === "json";
10021
+ }
10022
+ function writeCellValue(expr, ctx) {
10023
+ if (expr instanceof LiteralExpr) return expr.value;
10006
10024
  if (expr instanceof ParamExpr && Object.prototype.hasOwnProperty.call(ctx.params, expr.name)) {
10007
- const bound = ctx.params[expr.name];
10008
- return bound !== null && bound !== void 0 && typeof bound === "object" ? bound : void 0;
10025
+ return ctx.params[expr.name];
10009
10026
  }
10010
10027
  return void 0;
10011
10028
  }
@@ -16782,7 +16799,8 @@ var QueryEngine = class {
16782
16799
  * `opts.filters` (keyed by source) feeds the `filters` placeholders' clauses;
16783
16800
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
16784
16801
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
16785
- * "$total"` column on the top-level SELECT.
16802
+ * "$total"` column on the ENTRY SELECT only (a set operation gets none — see
16803
+ * {@link BaseSqlOptions.includeTotal}).
16786
16804
  *
16787
16805
  * `opts.embeddings` is a precomputed text→vector cache (see {@link
16788
16806
  * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
@@ -17083,6 +17101,18 @@ function inferType(name, rows, opts = {}) {
17083
17101
  function paramBound(name) {
17084
17102
  return { kind: "param", name };
17085
17103
  }
17104
+ function canAutoPaginate(query) {
17105
+ const kind = query.kind;
17106
+ return kind === "select" || kind === "union" || kind === "intersect" || kind === "except" || kind === "cte";
17107
+ }
17108
+ function unsupported2(kind) {
17109
+ return new QueryTypeError({
17110
+ path: [],
17111
+ code: "paginate.unsupported-kind",
17112
+ message: `autoPaginate: cannot page a '${kind}' query \u2014 only 'select', 'union' / 'intersect' / 'except' (set-level bounds) and 'cte' (paged through its 'final' query) carry a row limit / offset. Check with canAutoPaginate() first.`,
17113
+ severity: "error"
17114
+ });
17115
+ }
17086
17116
  function resolveBounds(currentLimit, currentOffset, opts) {
17087
17117
  const addLimit = opts.limit ?? true;
17088
17118
  const addOffset = opts.offset ?? true;
@@ -17093,9 +17123,9 @@ function resolveBounds(currentLimit, currentOffset, opts) {
17093
17123
  offset: currentOffset === void 0 && addOffset ? paramBound(offsetName) : currentOffset
17094
17124
  };
17095
17125
  }
17096
- function autoPaginate(select, opts = {}) {
17097
- if (select instanceof SelectQuery) {
17098
- const c = select.clone();
17126
+ function autoPaginate(query, opts = {}) {
17127
+ if (query instanceof SelectQuery) {
17128
+ const c = query.clone();
17099
17129
  const { limit: limit2, offset: offset2 } = resolveBounds(c.limit, c.offset, opts);
17100
17130
  return new SelectQuery(
17101
17131
  c.distinct,
@@ -17110,8 +17140,24 @@ function autoPaginate(select, opts = {}) {
17110
17140
  offset2
17111
17141
  );
17112
17142
  }
17113
- const { limit, offset } = resolveBounds(select.limit, select.offset, opts);
17114
- const out = { ...select };
17143
+ if (query instanceof SetOperationQuery) {
17144
+ const c = query.clone();
17145
+ const { limit: limit2, offset: offset2 } = resolveBounds(c.limit, c.offset, opts);
17146
+ return new SetOperationQuery(c.kind, c.left, c.right, c.all, c.order, limit2, offset2);
17147
+ }
17148
+ if (query instanceof CTEStatementQuery) {
17149
+ const c = query.clone();
17150
+ if (!canAutoPaginate(c.final)) throw unsupported2(c.final.kind);
17151
+ return new CTEStatementQuery(c.ctes, autoPaginate(c.final, opts));
17152
+ }
17153
+ if (query instanceof Query) throw unsupported2(query.kind);
17154
+ if (query.kind === "cte") {
17155
+ if (!canAutoPaginate(query.final)) throw unsupported2(query.final.kind);
17156
+ return { ...query, final: autoPaginate(query.final, opts) };
17157
+ }
17158
+ if (!canAutoPaginate(query)) throw unsupported2(query.kind);
17159
+ const { limit, offset } = resolveBounds(query.limit, query.offset, opts);
17160
+ const out = { ...query };
17115
17161
  if (limit === void 0) delete out.limit;
17116
17162
  else out.limit = limit;
17117
17163
  if (offset === void 0) delete out.offset;
@@ -17439,14 +17485,18 @@ function uniqueParamName(field, taken) {
17439
17485
  taken.add(name);
17440
17486
  return name;
17441
17487
  }
17442
- function expandStar(select, engine) {
17488
+ function expandStar(select, engine, projected) {
17443
17489
  const from = select.from;
17444
17490
  if (from.sourceKind !== "type" || from.typeName === void 0) return void 0;
17445
17491
  const type = engine.type(from.typeName);
17446
17492
  if (!type) return void 0;
17447
- return type.fields.map((f) => ({
17448
- expr: { kind: "field-ref", source: from.alias, field: f.name }
17449
- }));
17493
+ const fields = [];
17494
+ for (const f of type.fields) {
17495
+ const expr = { kind: "field-ref", source: from.alias, field: f.name };
17496
+ if (projected.has(exprDigest(expr))) continue;
17497
+ fields.push({ expr });
17498
+ }
17499
+ return fields;
17450
17500
  }
17451
17501
  function drillDown(select, engine) {
17452
17502
  const sq = expandSelectOutputs(asSelectQuery(select, engine), engine);
@@ -17479,6 +17529,10 @@ function drillDown(select, engine) {
17479
17529
  canon: canonicalize(c.expr),
17480
17530
  name: nameOf(c.expr, c.as, i)
17481
17531
  }));
17532
+ const projected = /* @__PURE__ */ new Set();
17533
+ sq.fields.forEach((c, i) => {
17534
+ if (!c.expr.containsAggregate()) projected.add(colInfo[i].canon);
17535
+ });
17482
17536
  const taken = referencedParamNames(sq);
17483
17537
  const params = [];
17484
17538
  const pinned = [];
@@ -17495,7 +17549,7 @@ function drillDown(select, engine) {
17495
17549
  sq.fields.forEach((c, i) => {
17496
17550
  const e2 = c.expr;
17497
17551
  if (e2 instanceof AggregateExpr && e2.valueArg() === void 0) {
17498
- const expanded = expandStar(sq, engine);
17552
+ const expanded = expandStar(sq, engine, projected);
17499
17553
  if (!expanded) {
17500
17554
  errors.at(
17501
17555
  ["fields", i],
@@ -18544,6 +18598,7 @@ export {
18544
18598
  buildSchemas,
18545
18599
  builtinDialects,
18546
18600
  bytesOfResolved,
18601
+ canAutoPaginate,
18547
18602
  canonicalize,
18548
18603
  caseExpr,
18549
18604
  cloneRecord,
package/package.json CHANGED
@@ -1,51 +1,51 @@
1
- {
2
- "name": "@aeye/query",
3
- "version": "0.6.1",
4
- "description": "Query - An LLM-friendly relational query language, runtime & SQL converter",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "source": "./src/index.ts",
11
- "import": {
12
- "types": "./dist/index.d.ts",
13
- "default": "./dist/index.js"
14
- },
15
- "default": "./dist/index.js"
16
- }
17
- },
18
- "scripts": {
19
- "build": "tsup src/index.ts --format esm --dts",
20
- "test": "vitest run",
21
- "test:watch": "vitest",
22
- "test:coverage": "vitest run --coverage",
23
- "typecheck": "tsc --noEmit",
24
- "examples": "tsx examples/examples.ts",
25
- "cli": "tsx examples/cli.ts",
26
- "integration": "tsx integration/run.ts",
27
- "integration:check": "tsx integration/run.ts --check",
28
- "clean": "rimraf dist"
29
- },
30
- "dependencies": {
31
- "@aeye/core": "^0.3.9",
32
- "zod": "^4.1.12"
33
- },
34
- "devDependencies": {
35
- "@aeye/ai": "^0.3.9",
36
- "@aeye/aws": "^0.3.9",
37
- "@aeye/models": "^0.3.9",
38
- "@aeye/openai": "^0.3.9",
39
- "@aeye/openrouter": "^0.3.9",
40
- "@vitest/coverage-v8": "^3.2.4",
41
- "tsup": "^8.0.0",
42
- "tsx": "^4.19.0",
43
- "typescript": "^5.9.3",
44
- "vitest": "^3.0.0"
45
- },
46
- "files": [
47
- "dist",
48
- "aeye-*.md"
49
- ],
50
- "license": "GPL-3.0"
51
- }
1
+ {
2
+ "name": "@aeye/query",
3
+ "version": "0.6.3",
4
+ "description": "Query - An LLM-friendly relational query language, runtime & SQL converter",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "source": "./src/index.ts",
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "scripts": {
19
+ "build": "tsup src/index.ts --format esm --dts",
20
+ "test": "vitest run",
21
+ "test:watch": "vitest",
22
+ "test:coverage": "vitest run --coverage",
23
+ "typecheck": "tsc --noEmit",
24
+ "examples": "tsx examples/examples.ts",
25
+ "cli": "tsx examples/cli.ts",
26
+ "integration": "tsx integration/run.ts",
27
+ "integration:check": "tsx integration/run.ts --check",
28
+ "clean": "rimraf dist"
29
+ },
30
+ "dependencies": {
31
+ "@aeye/core": "^0.3.9",
32
+ "zod": "^4.1.12"
33
+ },
34
+ "devDependencies": {
35
+ "@aeye/ai": "^0.3.9",
36
+ "@aeye/aws": "^0.3.9",
37
+ "@aeye/models": "^0.3.9",
38
+ "@aeye/openai": "^0.3.9",
39
+ "@aeye/openrouter": "^0.3.9",
40
+ "@vitest/coverage-v8": "^3.2.4",
41
+ "tsup": "^8.0.0",
42
+ "tsx": "^4.19.0",
43
+ "typescript": "^5.9.3",
44
+ "vitest": "^3.0.0"
45
+ },
46
+ "files": [
47
+ "dist",
48
+ "aeye-*.md"
49
+ ],
50
+ "license": "GPL-3.0"
51
+ }