@aeye/query 0.6.2 → 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
@@ -369,6 +369,25 @@ Everything composes around that one call:
369
369
  `SelectDef` field): `run` captures the pre-limit count into `result.total`,
370
370
  and `toSQL(query, dialect, { includeTotal: true })` emits
371
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
+ ```
372
391
  - **Pagination.** `autoPaginate` adds `limit` / `offset` as bind PARAMS, so
373
392
  pagination is just supplying their values:
374
393
 
@@ -379,6 +398,15 @@ Everything composes around that one call:
379
398
  await engine.run(paged, { params: { limit: 10, offset: 0 } });
380
399
  ```
381
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
+
382
410
  - **Drill-down.** `drillDownInto` rebuilds the underlying-rows query and extracts
383
411
  the drill PARAMS from a chosen aggregated row — then it is the same `run` call
384
412
  with those params (see [Drill-down](#drill-down)).
package/aeye-query.md CHANGED
@@ -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
@@ -9551,24 +9586,42 @@ interface InferOptions {
9551
9586
  declare function inferType(name: string, rows: ReadonlyArray<Record<string, JsonValue>>, opts?: InferOptions): TypeDef;
9552
9587
 
9553
9588
  /**
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).
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).
9557
9592
  *
9558
9593
  * Behaviour:
9559
- * - 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
9560
9595
  * `opts.limitParam` (default `'limit'`) is added.
9561
- * - 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
9562
9597
  * `opts.offsetParam` (default `'offset'`) is added.
9563
9598
  * - Each is independent: a query that already pins `limit` (literal or param)
9564
9599
  * but not `offset` only gains an `offset` param.
9565
9600
  *
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.
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`.
9618
+ *
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.
9569
9622
  *
9570
- * It never mutates its argument: a `SelectQuery` in produces a fresh
9571
- * `SelectQuery`; a `SelectDef` in produces a fresh `SelectDef`.
9623
+ * It never mutates its argument: a `Query` in produces a fresh `Query`; a
9624
+ * `QueryDef` in produces a fresh `QueryDef`.
9572
9625
  */
9573
9626
 
9574
9627
  /** Options controlling the auto-paginate transform. */
@@ -9583,14 +9636,38 @@ interface AutoPaginateOptions {
9583
9636
  offset?: boolean;
9584
9637
  }
9585
9638
  /**
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.
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}.
9590
9661
  */
9591
9662
  declare function autoPaginate(select: SelectQuery, opts?: AutoPaginateOptions): SelectQuery;
9592
9663
  declare function autoPaginate(select: SelectDef, opts?: AutoPaginateOptions): SelectDef;
9593
- 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;
9594
9671
 
9595
9672
  /**
9596
9673
  * `drillDown` — aggregate UN-RAVELLING, PARAMETERIZED (plan algorithm "(d)").
@@ -10151,4 +10228,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
10151
10228
  */
10152
10229
  declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
10153
10230
 
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 };
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
@@ -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
 
@@ -16796,7 +16799,8 @@ var QueryEngine = class {
16796
16799
  * `opts.filters` (keyed by source) feeds the `filters` placeholders' clauses;
16797
16800
  * `opts.sort` (an ordered `{ sort, dir? }` list) feeds the `sorter` placeholders
16798
16801
  * in a SELECT `order`; `opts.includeTotal` emits the `COUNT(*) OVER () AS
16799
- * "$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}).
16800
16804
  *
16801
16805
  * `opts.embeddings` is a precomputed text→vector cache (see {@link
16802
16806
  * SemanticEmbeddings}): a `semantic(...)` TEXT literal — or the value of a
@@ -17097,6 +17101,18 @@ function inferType(name, rows, opts = {}) {
17097
17101
  function paramBound(name) {
17098
17102
  return { kind: "param", name };
17099
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
+ }
17100
17116
  function resolveBounds(currentLimit, currentOffset, opts) {
17101
17117
  const addLimit = opts.limit ?? true;
17102
17118
  const addOffset = opts.offset ?? true;
@@ -17107,9 +17123,9 @@ function resolveBounds(currentLimit, currentOffset, opts) {
17107
17123
  offset: currentOffset === void 0 && addOffset ? paramBound(offsetName) : currentOffset
17108
17124
  };
17109
17125
  }
17110
- function autoPaginate(select, opts = {}) {
17111
- if (select instanceof SelectQuery) {
17112
- const c = select.clone();
17126
+ function autoPaginate(query, opts = {}) {
17127
+ if (query instanceof SelectQuery) {
17128
+ const c = query.clone();
17113
17129
  const { limit: limit2, offset: offset2 } = resolveBounds(c.limit, c.offset, opts);
17114
17130
  return new SelectQuery(
17115
17131
  c.distinct,
@@ -17124,8 +17140,24 @@ function autoPaginate(select, opts = {}) {
17124
17140
  offset2
17125
17141
  );
17126
17142
  }
17127
- const { limit, offset } = resolveBounds(select.limit, select.offset, opts);
17128
- 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 };
17129
17161
  if (limit === void 0) delete out.limit;
17130
17162
  else out.limit = limit;
17131
17163
  if (offset === void 0) delete out.offset;
@@ -18566,6 +18598,7 @@ export {
18566
18598
  buildSchemas,
18567
18599
  builtinDialects,
18568
18600
  bytesOfResolved,
18601
+ canAutoPaginate,
18569
18602
  canonicalize,
18570
18603
  caseExpr,
18571
18604
  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.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
+ }