@aeye/query 0.6.2 → 0.6.4

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
@@ -369,6 +378,25 @@ Everything composes around that one call:
369
378
  `SelectDef` field): `run` captures the pre-limit count into `result.total`,
370
379
  and `toSQL(query, dialect, { includeTotal: true })` emits
371
380
  `COUNT(*) OVER () AS "$total"`.
381
+
382
+ It applies to the **ENTRY query only** — never a CTE body, a set-operation
383
+ arm, or a FROM subquery. `$total` is a PROJECTED column, so an arm that
384
+ carried it would take part in the set comparison and change the **rows**:
385
+ `UNION` would stop de-duplicating, and `INTERSECT` / `EXCEPT` would compare
386
+ per-arm counts they were never meant to see. A query whose entry is a **set
387
+ operation therefore reports no total at all** (`result.total` is `undefined`;
388
+ the SQL carries no `$total`) rather than a wrong one — both engines agree.
389
+ To page a set operation *and* count it, wrap it in a SELECT and count there:
390
+
391
+ ```ts
392
+ const counted = {
393
+ kind: 'select',
394
+ fields: [{ expr: { kind: 'field-ref', source: 's', field: 'id' } }],
395
+ from: { kind: 'subquery', as: 's', query: theUnion },
396
+ limit: 20,
397
+ } satisfies SelectDef;
398
+ await engine.run(counted, { includeTotal: true }); // → { rows, total }
399
+ ```
372
400
  - **Pagination.** `autoPaginate` adds `limit` / `offset` as bind PARAMS, so
373
401
  pagination is just supplying their values:
374
402
 
@@ -379,6 +407,15 @@ Everything composes around that one call:
379
407
  await engine.run(paged, { params: { limit: 10, offset: 0 } });
380
408
  ```
381
409
 
410
+ It pages exactly the kinds that HAVE a row bound: a **`select`** (its own
411
+ LIMIT / OFFSET), a **set operation** (`union` / `intersect` / `except` — the
412
+ SET-LEVEL bound over the combined rows, never an arm's, since paging an arm
413
+ would change which rows the set operation compares), and a **`cte`**, which is
414
+ paged through its `final` query (a CTE body is an intermediate result). Every
415
+ other kind — `insert` / `update` / `delete` / `expr` — has no bound to bind and
416
+ **throws** `QueryTypeError` with code `paginate.unsupported-kind`. Ask first
417
+ with `canAutoPaginate(query)` when you hold an arbitrary `QueryDef`.
418
+
382
419
  - **Drill-down.** `drillDownInto` rebuilds the underlying-rows query and extracts
383
420
  the drill PARAMS from a chosen aggregated row — then it is the same `run` call
384
421
  with those params (see [Drill-down](#drill-down)).
package/aeye-query.md CHANGED
@@ -94,7 +94,7 @@ Everything is referenced by its **Type name** — there is no alias to invent or
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
100
 
@@ -190,8 +190,8 @@ const result = await engine.run(query, { params, filters, includeTotal });
190
190
  ```
191
191
 
192
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"`.
194
- - **`autoPaginate(query)`** adds `limit`/`offset` as bind params idempotently, so paging is just supplying values: `run(paged, { params: { limit, offset } })`.
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
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`).
196
196
  - **Standalone exprs.** `engine.evaluateExpr(expr, row?)` evaluates an `Expr`/`ExprDef` against a row; `engine.exprToSQL(expr, dialect)` emits `{ sql, params }` (params never interpolated).
197
197
 
package/dist/index.d.ts CHANGED
@@ -1916,8 +1916,14 @@ interface RuntimeOptions {
1916
1916
  */
1917
1917
  rls?: RlsProvider;
1918
1918
  /**
1919
- * When true, a top-level SELECT also reports `total` — the result count after
1920
- * 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.
1921
1927
  */
1922
1928
  includeTotal?: boolean;
1923
1929
  /** Embedder override (defaults to the engine's). */
@@ -4504,8 +4510,16 @@ declare class SqlContext {
4504
4510
  */
4505
4511
  readonly filters: Readonly<Record<string, Expr>>;
4506
4512
  /**
4507
- * Whether the (top-level) SELECT should emit `COUNT(*) OVER () AS "$total"`.
4508
- * 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.
4509
4523
  */
4510
4524
  readonly includeTotal: boolean;
4511
4525
  /**
@@ -4558,8 +4572,16 @@ declare class SqlContext {
4558
4572
  */
4559
4573
  filters?: Readonly<Record<string, Expr>>,
4560
4574
  /**
4561
- * Whether the (top-level) SELECT should emit `COUNT(*) OVER () AS "$total"`.
4562
- * 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.
4563
4585
  */
4564
4586
  includeTotal?: boolean,
4565
4587
  /**
@@ -4603,6 +4625,9 @@ declare class SqlContext {
4603
4625
  * Mark the NEXT emitted query as NON-root (same level otherwise). Used at the
4604
4626
  * boundaries `withPlanner` does not cover — a CTE body and a set-operation
4605
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).
4606
4631
  */
4607
4632
  nonRoot(): SqlContext;
4608
4633
  }
@@ -5963,7 +5988,16 @@ interface BaseSqlOptions {
5963
5988
  filters?: Record<string, ExprDef | Expr | null>;
5964
5989
  /** Execution-time dynamic-sort selection, feeding a SELECT `order`'s `sorter`. */
5965
5990
  sort?: SortSelectionDef[];
5966
- /** 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
+ */
5967
6001
  includeTotal?: boolean;
5968
6002
  }
5969
6003
  /** Options for {@link QueryEngine.toSQL}. */
@@ -6167,7 +6201,8 @@ declare class QueryEngine {
6167
6201
  * `opts.filters` (keyed by source) feeds the `filters` placeholders' clauses;
6168
6202
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
6169
6203
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
6170
- * "$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}).
6171
6206
  *
6172
6207
  * `opts.embeddings` is a precomputed text→vector cache (see {@link
6173
6208
  * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
@@ -6409,14 +6444,34 @@ declare abstract class Query {
6409
6444
  * Params that are referenced but never observed against any type (so no type
6410
6445
  * can be inferred) are OMITTED here — they carry no `type` to report;
6411
6446
  * `validateQuery` surfaces them separately as `param.untyped`.
6447
+ *
6448
+ * Out-of-tree bounds (`limit` / `offset`) are picked up by the same walk —
6449
+ * each kind that OWNS a row bound observes it from its own `validateWalk`
6450
+ * (see {@link observeRowBounds}), so a bound at ANY nesting depth lands here.
6412
6451
  */
6413
6452
  params(engine: QueryEngine, scope?: QueryScope): ParamDef[];
6414
6453
  /**
6415
- * Observe any bind params that live OUTSIDE this query's walked expr tree
6416
- * (e.g. a SELECT's `limit` / `offset`), so `params()` reports them with the
6417
- * right inferred type. Base: none. Overridden by `SelectQuery`.
6454
+ * Observe a `limit` / `offset` ROW BOUND that is bound to a `param` (see
6455
+ * `autoPaginate`) against a number field type — a bound is always a row count
6456
+ * — so `params()` reports it with an inferred type. A bound lives OUTSIDE the
6457
+ * walked expr tree, so nothing else in the walk ever reaches it.
6458
+ *
6459
+ * INVARIANT: the kind that EMITS a row bound is the kind that observes it, and
6460
+ * it does so from its own `validateWalk`. That is what makes the report correct
6461
+ * at every NESTING DEPTH — `validateWalk` already recurses into a CTE body and
6462
+ * its `final`, a set-operation arm, and a FROM / IN / EXISTS subquery, and every
6463
+ * scope in that recursion shares ONE `ParamSet`. Observing only at the ROOT
6464
+ * (what `params()` used to do, via a `SelectQuery`-only hook) reported a paged
6465
+ * `cte` as taking NO params at all while `toSQL` still emitted
6466
+ * `LIMIT $1 OFFSET $2` — an unbindable statement whose declared signature was
6467
+ * empty (bug A17).
6468
+ *
6469
+ * The observation is recorded at the walk's CURRENT path (`p.here`, the
6470
+ * accessor that exists for exactly this), so a `param.conflict` naming a bound
6471
+ * points at the statement that OWNS it (`final.limit`) rather than at a
6472
+ * root-relative `limit` that does not exist.
6418
6473
  */
6419
- protected observeBoundParams(_params: ParamSet): void;
6474
+ protected observeRowBounds(scope: QueryScope, p: Problems, limit: number | ParamExprDef | undefined, offset: number | ParamExprDef | undefined): void;
6420
6475
  /**
6421
6476
  * The source names this query exposes for execution-time `filters` — i.e. the
6422
6477
  * sources a caller may target with `engine.run(query, { filters: [{ kind:
@@ -8654,13 +8709,6 @@ declare class SelectQuery extends Query {
8654
8709
  * `isRoot` marks the entry query being run/emitted (threaded on the context).
8655
8710
  */
8656
8711
  private effectiveDefaultOrder;
8657
- /**
8658
- * `limit` / `offset` may be bound to a `param` (see `autoPaginate`), but they
8659
- * live outside the walked expr tree, so `params()` never observes them. They
8660
- * are always integer row counts, so observe each against a number field type
8661
- * — making them surface in `params()` with the right inferred type.
8662
- */
8663
- protected observeBoundParams(params: ParamSet): void;
8664
8712
  /**
8665
8713
  * Estimate result `{ rows, bytes }` the way a SQL engine PROCESSES the query.
8666
8714
  *
@@ -8831,7 +8879,7 @@ declare class InsertQuery extends Query {
8831
8879
  private conflictScope;
8832
8880
  /** Resolve the output fields from the RETURNING projection against the target scope. */
8833
8881
  outputFields(engine: QueryEngine, scope: QueryScope): QueryField[];
8834
- /** Validate the target type, fields, row homogeneity, RETURNING, and ON CONFLICT assignments. */
8882
+ /** Validate the target type, the source SELECT, fields, row homogeneity, RETURNING, and ON CONFLICT assignments. */
8835
8883
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, _ctx: ValidateContext): void;
8836
8884
  /** The target type plus any types read by an INSERT … SELECT source. */
8837
8885
  referencedTypes(): readonly string[];
@@ -9133,8 +9181,6 @@ declare class SetOperationQuery extends Query {
9133
9181
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): void;
9134
9182
  /** The union of both arms' referenced Type names. */
9135
9183
  referencedTypes(): readonly string[];
9136
- /** Set-level `limit` / `offset` params live outside the walked expr tree. */
9137
- protected observeBoundParams(params: ParamSet): void;
9138
9184
  /** Estimate the WORK `{ rows, bytes }`: combine both arms' cost per operation, then cap by LIMIT. */
9139
9185
  cost(ctx: CostContext, scope: QueryScope): Cost;
9140
9186
  /** Estimate the RESULT SIZE: combine both arms' `outputCost` per operation, then cap by LIMIT. */
@@ -9551,24 +9597,42 @@ interface InferOptions {
9551
9597
  declare function inferType(name: string, rows: ReadonlyArray<Record<string, JsonValue>>, opts?: InferOptions): TypeDef;
9552
9598
 
9553
9599
  /**
9554
- * `autoPaginate` — a SELECT transform that binds pagination to named bind
9555
- * PARAMETERS, so a single LLM-authored query becomes a reusable, paged
9556
- * artifact (the caller supplies `limit` / `offset` values at run/emit time).
9600
+ * `autoPaginate` — a transform that binds a query's pagination to named bind
9601
+ * PARAMETERS, so a single LLM-authored query becomes a reusable, paged artifact
9602
+ * (the caller supplies `limit` / `offset` values at run/emit time).
9557
9603
  *
9558
9604
  * Behaviour:
9559
- * - If the select does NOT already constrain `limit`, a `param` expr named
9605
+ * - If the query does NOT already constrain `limit`, a `param` expr named
9560
9606
  * `opts.limitParam` (default `'limit'`) is added.
9561
- * - If the select does NOT already constrain `offset`, a `param` expr named
9607
+ * - If the query does NOT already constrain `offset`, a `param` expr named
9562
9608
  * `opts.offsetParam` (default `'offset'`) is added.
9563
9609
  * - Each is independent: a query that already pins `limit` (literal or param)
9564
9610
  * but not `offset` only gains an `offset` param.
9565
9611
  *
9566
- * The transform is IDEMPOTENT — running it twice yields a structurally
9567
- * identical result, because an already-present `limit` / `offset` (whether a
9568
- * literal number or a param this transform added) is left untouched.
9612
+ * WHICH QUERIES IT PAGES — and why it refuses the rest. Pagination is a bound on
9613
+ * the ROWS a statement returns, so the transform is defined exactly on the kinds
9614
+ * that carry one:
9615
+ * - `select` — its own LIMIT / OFFSET;
9616
+ * - `union` / `intersect` / `except` — the SET-LEVEL LIMIT / OFFSET applied to
9617
+ * the combined rows (never to an arm: paging an arm changes which rows the
9618
+ * set operation compares);
9619
+ * - `cte` — a `WITH` statement returns whatever its `final` query returns, so
9620
+ * the bounds are bound on `final` (recursively). Paging a CTE BODY would page
9621
+ * an intermediate result, which is a different query.
9622
+ *
9623
+ * Every other kind — `insert` / `update` / `delete` / `expr` — has no row bound
9624
+ * to bind. Asking for one used to be SILENT: the JSON branch spread whatever it
9625
+ * was given and set `limit` / `offset` on the copy, so a `cte` came back looking
9626
+ * paged while the parser dropped both keys and the statement returned every row.
9627
+ * It now throws a {@link QueryTypeError} (`paginate.unsupported-kind`) instead.
9628
+ * Use {@link canAutoPaginate} to ask first when holding an arbitrary `QueryDef`.
9569
9629
  *
9570
- * It never mutates its argument: a `SelectQuery` in produces a fresh
9571
- * `SelectQuery`; a `SelectDef` in produces a fresh `SelectDef`.
9630
+ * The transform is IDEMPOTENT — running it twice yields a structurally identical
9631
+ * result, because an already-present `limit` / `offset` (whether a literal number
9632
+ * or a param this transform added) is left untouched.
9633
+ *
9634
+ * It never mutates its argument: a `Query` in produces a fresh `Query`; a
9635
+ * `QueryDef` in produces a fresh `QueryDef`.
9572
9636
  */
9573
9637
 
9574
9638
  /** Options controlling the auto-paginate transform. */
@@ -9583,14 +9647,38 @@ interface AutoPaginateOptions {
9583
9647
  offset?: boolean;
9584
9648
  }
9585
9649
  /**
9586
- * Bind a SELECT's pagination to named bind params: add a `limit` / `offset`
9587
- * param (per `opts`) wherever the query does not already constrain that bound.
9588
- * Idempotent and non-mutating — returns a fresh `SelectQuery` / `SelectDef`
9589
- * mirroring the input shape.
9650
+ * The authored query kinds {@link autoPaginate} accepts: the ones carrying a row
9651
+ * bound of their own (`select`, the three set operations) plus `cte`, which
9652
+ * delegates to its `final` query.
9653
+ */
9654
+ type PaginatableDef = SelectDef | SetOperationDef | CTEStatementDef;
9655
+ /** The parsed counterparts of {@link PaginatableDef}. */
9656
+ type PaginatableQuery = SelectQuery | SetOperationQuery | CTEStatementQuery;
9657
+ /**
9658
+ * Whether {@link autoPaginate} can page this query — true for `select`, the set
9659
+ * operations, and `cte` (whose `final` is paged in turn). Ask this when holding
9660
+ * an arbitrary `Query` / `QueryDef`; `autoPaginate` throws otherwise.
9661
+ */
9662
+ declare function canAutoPaginate(query: Query | QueryDef): boolean;
9663
+ /**
9664
+ * Bind a query's pagination to named bind params: add a `limit` / `offset` param
9665
+ * (per `opts`) wherever the query does not already constrain that bound. A `cte`
9666
+ * statement is paged through its `final` query. Idempotent and non-mutating —
9667
+ * returns a fresh `Query` / `QueryDef` mirroring the input shape.
9668
+ *
9669
+ * @throws {QueryTypeError} `paginate.unsupported-kind` for a query kind that has
9670
+ * no row bound (`insert` / `update` / `delete` / `expr`) — see
9671
+ * {@link canAutoPaginate}.
9590
9672
  */
9591
9673
  declare function autoPaginate(select: SelectQuery, opts?: AutoPaginateOptions): SelectQuery;
9592
9674
  declare function autoPaginate(select: SelectDef, opts?: AutoPaginateOptions): SelectDef;
9593
- declare function autoPaginate(select: SelectQuery | SelectDef, opts?: AutoPaginateOptions): SelectQuery | SelectDef;
9675
+ declare function autoPaginate(query: SetOperationQuery, opts?: AutoPaginateOptions): SetOperationQuery;
9676
+ declare function autoPaginate(query: SetOperationDef, opts?: AutoPaginateOptions): SetOperationDef;
9677
+ declare function autoPaginate(query: CTEStatementQuery, opts?: AutoPaginateOptions): CTEStatementQuery;
9678
+ declare function autoPaginate(query: CTEStatementDef, opts?: AutoPaginateOptions): CTEStatementDef;
9679
+ declare function autoPaginate(query: PaginatableQuery, opts?: AutoPaginateOptions): PaginatableQuery;
9680
+ declare function autoPaginate(query: PaginatableDef, opts?: AutoPaginateOptions): PaginatableDef;
9681
+ declare function autoPaginate(query: PaginatableQuery | PaginatableDef, opts?: AutoPaginateOptions): PaginatableQuery | PaginatableDef;
9594
9682
 
9595
9683
  /**
9596
9684
  * `drillDown` — aggregate UN-RAVELLING, PARAMETERIZED (plan algorithm "(d)").
@@ -10151,4 +10239,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
10151
10239
  */
10152
10240
  declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
10153
10241
 
10154
- 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 };
10242
+ 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
@@ -3245,9 +3245,12 @@ var SqlContext = class _SqlContext {
3245
3245
  * Mark the NEXT emitted query as NON-root (same level otherwise). Used at the
3246
3246
  * boundaries `withPlanner` does not cover — a CTE body and a set-operation
3247
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).
3248
3251
  */
3249
3252
  nonRoot() {
3250
- 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);
3251
3254
  }
3252
3255
  };
3253
3256
 
@@ -9220,21 +9223,44 @@ var Query = class {
9220
9223
  * Params that are referenced but never observed against any type (so no type
9221
9224
  * can be inferred) are OMITTED here — they carry no `type` to report;
9222
9225
  * `validateQuery` surfaces them separately as `param.untyped`.
9226
+ *
9227
+ * Out-of-tree bounds (`limit` / `offset`) are picked up by the same walk —
9228
+ * each kind that OWNS a row bound observes it from its own `validateWalk`
9229
+ * (see {@link observeRowBounds}), so a bound at ANY nesting depth lands here.
9223
9230
  */
9224
9231
  params(engine, scope) {
9225
9232
  engine.registry.finalize();
9226
9233
  const s = scope ?? engine.globalScope();
9227
9234
  const p = new Problems();
9228
9235
  this.validateWalk(engine, s, p, ROOT_VALIDATE_CONTEXT);
9229
- this.observeBoundParams(s.params);
9230
9236
  return s.params.toJSON();
9231
9237
  }
9232
9238
  /**
9233
- * Observe any bind params that live OUTSIDE this query's walked expr tree
9234
- * (e.g. a SELECT's `limit` / `offset`), so `params()` reports them with the
9235
- * right inferred type. Base: none. Overridden by `SelectQuery`.
9239
+ * Observe a `limit` / `offset` ROW BOUND that is bound to a `param` (see
9240
+ * `autoPaginate`) against a number field type — a bound is always a row count
9241
+ * — so `params()` reports it with an inferred type. A bound lives OUTSIDE the
9242
+ * walked expr tree, so nothing else in the walk ever reaches it.
9243
+ *
9244
+ * INVARIANT: the kind that EMITS a row bound is the kind that observes it, and
9245
+ * it does so from its own `validateWalk`. That is what makes the report correct
9246
+ * at every NESTING DEPTH — `validateWalk` already recurses into a CTE body and
9247
+ * its `final`, a set-operation arm, and a FROM / IN / EXISTS subquery, and every
9248
+ * scope in that recursion shares ONE `ParamSet`. Observing only at the ROOT
9249
+ * (what `params()` used to do, via a `SelectQuery`-only hook) reported a paged
9250
+ * `cte` as taking NO params at all while `toSQL` still emitted
9251
+ * `LIMIT $1 OFFSET $2` — an unbindable statement whose declared signature was
9252
+ * empty (bug A17).
9253
+ *
9254
+ * The observation is recorded at the walk's CURRENT path (`p.here`, the
9255
+ * accessor that exists for exactly this), so a `param.conflict` naming a bound
9256
+ * points at the statement that OWNS it (`final.limit`) rather than at a
9257
+ * root-relative `limit` that does not exist.
9236
9258
  */
9237
- observeBoundParams(_params) {
9259
+ observeRowBounds(scope, p, limit, offset) {
9260
+ const numeric3 = new NumberFieldType();
9261
+ const at = p.here;
9262
+ if (limit !== void 0 && typeof limit !== "number") scope.params.observe(limit.name, numeric3, [...at, "limit"]);
9263
+ if (offset !== void 0 && typeof offset !== "number") scope.params.observe(offset.name, numeric3, [...at, "offset"]);
9238
9264
  }
9239
9265
  /**
9240
9266
  * The source names this query exposes for execution-time `filters` — i.e. the
@@ -11084,6 +11110,7 @@ var SelectQuery = class _SelectQuery extends Query {
11084
11110
  (o, i) => o instanceof SorterExpr ? p.at(i, () => o.sorts.forEach((e2, name) => p.at(["sorts", name], () => this.checkGrouped(e2, groupCodes, p)))) : p.at([i, "expr"], () => this.checkGrouped(o.expr, groupCodes, p))
11085
11111
  ));
11086
11112
  }
11113
+ this.observeRowBounds(scope, p, this.limit, this.offset);
11087
11114
  }
11088
11115
  /**
11089
11116
  * The GROUP BY keys as `toCode()` strings, with an `output` key EXPANDED to the
@@ -11239,21 +11266,6 @@ var SelectQuery = class _SelectQuery extends Query {
11239
11266
  const inScope = scope === "all" || (scope === "paginated" ? paginated : isRoot || paginated);
11240
11267
  return inScope ? order : void 0;
11241
11268
  }
11242
- /**
11243
- * `limit` / `offset` may be bound to a `param` (see `autoPaginate`), but they
11244
- * live outside the walked expr tree, so `params()` never observes them. They
11245
- * are always integer row counts, so observe each against a number field type
11246
- * — making them surface in `params()` with the right inferred type.
11247
- */
11248
- observeBoundParams(params) {
11249
- const numeric3 = new NumberFieldType();
11250
- if (this.limit !== void 0 && typeof this.limit !== "number") {
11251
- params.observe(this.limit.name, numeric3, ["limit"]);
11252
- }
11253
- if (this.offset !== void 0 && typeof this.offset !== "number") {
11254
- params.observe(this.offset.name, numeric3, ["offset"]);
11255
- }
11256
- }
11257
11269
  // ─── Cost estimation ─────────────────────────────────────────────────────
11258
11270
  /**
11259
11271
  * Estimate result `{ rows, bytes }` the way a SQL engine PROCESSES the query.
@@ -12065,7 +12077,7 @@ var InsertQuery = class _InsertQuery extends Query {
12065
12077
  const inner = this.targetScope(engine, scope);
12066
12078
  return this.returning.map((c, i) => makeField(fieldNameOf(c.expr, c.as, i), c.expr.resolve(engine, inner)));
12067
12079
  }
12068
- /** Validate the target type, fields, row homogeneity, RETURNING, and ON CONFLICT assignments. */
12080
+ /** Validate the target type, the source SELECT, fields, row homogeneity, RETURNING, and ON CONFLICT assignments. */
12069
12081
  validateWalk(engine, scope, p, _ctx) {
12070
12082
  const type = engine.type(this.into);
12071
12083
  if (!type) {
@@ -12125,6 +12137,8 @@ var InsertQuery = class _InsertQuery extends Query {
12125
12137
  }
12126
12138
  const inner = this.targetScope(engine, scope);
12127
12139
  const ctx = { inAggregate: false, inWindow: false, allowAggregate: true, groupKeys: [], inGroupBy: false };
12140
+ const source = this.select;
12141
+ if (source) p.at("select", () => source.validateWalk(engine, scope, p, ctx));
12128
12142
  p.at("returning", () => {
12129
12143
  this.returning.forEach(
12130
12144
  (c, i) => p.at([i, "expr"], () => c.expr.validateWalk(engine, inner, p, identityValueCtx(c.expr, ctx)))
@@ -13080,17 +13094,12 @@ var SetOperationQuery = class _SetOperationQuery extends Query {
13080
13094
  this.order.forEach((o, i) => p.at([i, "expr"], () => o.expr.validateWalk(engine, inner, p, colCtx)));
13081
13095
  });
13082
13096
  }
13097
+ this.observeRowBounds(scope, p, this.limit, this.offset);
13083
13098
  }
13084
13099
  /** The union of both arms' referenced Type names. */
13085
13100
  referencedTypes() {
13086
13101
  return [.../* @__PURE__ */ new Set([...this.left.referencedTypes(), ...this.right.referencedTypes()])];
13087
13102
  }
13088
- /** Set-level `limit` / `offset` params live outside the walked expr tree. */
13089
- observeBoundParams(params) {
13090
- const numeric3 = new NumberFieldType();
13091
- if (this.limit !== void 0 && typeof this.limit !== "number") params.observe(this.limit.name, numeric3, ["limit"]);
13092
- if (this.offset !== void 0 && typeof this.offset !== "number") params.observe(this.offset.name, numeric3, ["offset"]);
13093
- }
13094
13103
  /** Estimate the WORK `{ rows, bytes }`: combine both arms' cost per operation, then cap by LIMIT. */
13095
13104
  cost(ctx, scope) {
13096
13105
  return this.capByLimit(this.combineBranches(this.left.cost(ctx, scope), this.right.cost(ctx, scope)), ctx);
@@ -16796,7 +16805,8 @@ var QueryEngine = class {
16796
16805
  * `opts.filters` (keyed by source) feeds the `filters` placeholders' clauses;
16797
16806
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
16798
16807
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
16799
- * "$total"` column on the top-level SELECT.
16808
+ * "$total"` column on the ENTRY SELECT only (a set operation gets none — see
16809
+ * {@link BaseSqlOptions.includeTotal}).
16800
16810
  *
16801
16811
  * `opts.embeddings` is a precomputed text→vector cache (see {@link
16802
16812
  * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
@@ -17097,6 +17107,18 @@ function inferType(name, rows, opts = {}) {
17097
17107
  function paramBound(name) {
17098
17108
  return { kind: "param", name };
17099
17109
  }
17110
+ function canAutoPaginate(query) {
17111
+ const kind = query.kind;
17112
+ return kind === "select" || kind === "union" || kind === "intersect" || kind === "except" || kind === "cte";
17113
+ }
17114
+ function unsupported2(kind) {
17115
+ return new QueryTypeError({
17116
+ path: [],
17117
+ code: "paginate.unsupported-kind",
17118
+ 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.`,
17119
+ severity: "error"
17120
+ });
17121
+ }
17100
17122
  function resolveBounds(currentLimit, currentOffset, opts) {
17101
17123
  const addLimit = opts.limit ?? true;
17102
17124
  const addOffset = opts.offset ?? true;
@@ -17107,9 +17129,9 @@ function resolveBounds(currentLimit, currentOffset, opts) {
17107
17129
  offset: currentOffset === void 0 && addOffset ? paramBound(offsetName) : currentOffset
17108
17130
  };
17109
17131
  }
17110
- function autoPaginate(select, opts = {}) {
17111
- if (select instanceof SelectQuery) {
17112
- const c = select.clone();
17132
+ function autoPaginate(query, opts = {}) {
17133
+ if (query instanceof SelectQuery) {
17134
+ const c = query.clone();
17113
17135
  const { limit: limit2, offset: offset2 } = resolveBounds(c.limit, c.offset, opts);
17114
17136
  return new SelectQuery(
17115
17137
  c.distinct,
@@ -17124,8 +17146,24 @@ function autoPaginate(select, opts = {}) {
17124
17146
  offset2
17125
17147
  );
17126
17148
  }
17127
- const { limit, offset } = resolveBounds(select.limit, select.offset, opts);
17128
- const out = { ...select };
17149
+ if (query instanceof SetOperationQuery) {
17150
+ const c = query.clone();
17151
+ const { limit: limit2, offset: offset2 } = resolveBounds(c.limit, c.offset, opts);
17152
+ return new SetOperationQuery(c.kind, c.left, c.right, c.all, c.order, limit2, offset2);
17153
+ }
17154
+ if (query instanceof CTEStatementQuery) {
17155
+ const c = query.clone();
17156
+ if (!canAutoPaginate(c.final)) throw unsupported2(c.final.kind);
17157
+ return new CTEStatementQuery(c.ctes, autoPaginate(c.final, opts));
17158
+ }
17159
+ if (query instanceof Query) throw unsupported2(query.kind);
17160
+ if (query.kind === "cte") {
17161
+ if (!canAutoPaginate(query.final)) throw unsupported2(query.final.kind);
17162
+ return { ...query, final: autoPaginate(query.final, opts) };
17163
+ }
17164
+ if (!canAutoPaginate(query)) throw unsupported2(query.kind);
17165
+ const { limit, offset } = resolveBounds(query.limit, query.offset, opts);
17166
+ const out = { ...query };
17129
17167
  if (limit === void 0) delete out.limit;
17130
17168
  else out.limit = limit;
17131
17169
  if (offset === void 0) delete out.offset;
@@ -18566,6 +18604,7 @@ export {
18566
18604
  buildSchemas,
18567
18605
  builtinDialects,
18568
18606
  bytesOfResolved,
18607
+ canAutoPaginate,
18569
18608
  canonicalize,
18570
18609
  caseExpr,
18571
18610
  cloneRecord,
package/package.json CHANGED
@@ -1,51 +1,51 @@
1
- {
2
- "name": "@aeye/query",
3
- "version": "0.6.2",
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.4",
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
+ }