@aeye/query 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -886,6 +886,31 @@ type QueryDef = SelectDef | InsertDef | UpdateDef | DeleteDef | SetOperationDef
886
886
  type QueryKind = QueryDef['kind'];
887
887
  /** What category of function this is (drives output resolution + SQL emit). */
888
888
  type FunctionShape = 'scalar' | 'tabular' | 'window' | 'aggregate';
889
+ /**
890
+ * How two values of one AGGREGATE combine into the value over the UNION of the
891
+ * groups that produced them — the fact a consumer needs to fold a tail of groups
892
+ * into a residual ("Other" slice / row / column) without re-running the query.
893
+ *
894
+ * For `f` applied to DISJOINT groups `A` and `B`, the declared operation `⊕` must
895
+ * satisfy `f(A ∪ B) = f(A) ⊕ f(B)` for every partition — a claim about the
896
+ * function, not about one dataset:
897
+ * - `'sum'` — additive (`count`, `sum`, `countIf`).
898
+ * - `'min'` / `'max'` — extremal (`min`, `max`).
899
+ * - `'and'` / `'or'` — boolean folds (`boolAnd`, `boolOr`).
900
+ * - `'none'` — NOT recoverable from the per-group values alone, and the default
901
+ * for any function that does not declare otherwise. `avg` is the canonical
902
+ * case: the merge needs each group's WEIGHT (its row count), which the result
903
+ * does not carry — adding the means or averaging them are both simply wrong.
904
+ * `stddev` / `variance` need the same; `stringAgg` / `arrayAgg` depend on a
905
+ * separator / ordering a pair of values cannot supply.
906
+ *
907
+ * `'sum'` is the one arm DISTINCT invalidates — de-duplication is global, so two
908
+ * `count(DISTINCT x)` values cannot be added — while `min`/`max`/`and`/`or` are
909
+ * idempotent and merge identically with or without it. A consumer should read the
910
+ * already-resolved answer on `ComputedResolved.aggregateMerge` rather than
911
+ * re-derive that rule (see `mergeOfAggregateCall`).
912
+ */
913
+ type AggregateMerge = 'sum' | 'min' | 'max' | 'and' | 'or' | 'none';
889
914
  /** A declared function parameter. `type: 'any'` accepts any field type. */
890
915
  interface FunctionParamDef {
891
916
  name: string;
@@ -950,6 +975,19 @@ interface FunctionDef {
950
975
  * drilled select/order.)
951
976
  */
952
977
  unaggregateEmpty?: ExprDef;
978
+ /**
979
+ * AGGREGATE MERGE semantics — how two of this aggregate's per-group values
980
+ * combine into the value over the union of those groups ({@link AggregateMerge}).
981
+ * Declarable ONLY on an `aggregate`-shaped function — resolving one that is
982
+ * not THROWS (`QueryFunction.from`, exactly as an unknown output Type does),
983
+ * because the notion is meaningless for a scalar / window / tabular call and a
984
+ * silently ignored key is worse than a loud one.
985
+ * Absent ⇒ `'none'` — an aggregate whose author did not say is treated as
986
+ * un-mergeable, so a consumer folding groups fails SAFE rather than inventing
987
+ * arithmetic. Surfaced per CALL (DISTINCT accounted for) on
988
+ * `ComputedResolved.aggregateMerge`.
989
+ */
990
+ merge?: AggregateMerge;
953
991
  /** Intrinsic per-call cost `{ rows, bytes }` this function adds beyond its args. */
954
992
  cost?: {
955
993
  rows: number;
@@ -1475,6 +1513,32 @@ interface ComputedResolved {
1475
1513
  * names the aggregate that was APPLIED, not any function that was called.
1476
1514
  */
1477
1515
  aggregateFn?: string;
1516
+ /**
1517
+ * Whether the APPLIED aggregate call was `DISTINCT` (`count(DISTINCT x)`).
1518
+ * Present exactly when {@link aggregateFn} is, and `false` for an ordinary
1519
+ * call — a companion FACT, not a flag omitted when false, because "not
1520
+ * distinct" is an answer a consumer relies on.
1521
+ *
1522
+ * It exists because `count(x)` and `count(DISTINCT x)` resolved IDENTICALLY
1523
+ * before `0.6.5`: same `fieldType`, same `nullable`, same `aggregateFn`, the
1524
+ * same single source. They answer different questions and combine by different
1525
+ * rules, and nothing on the wire could tell them apart.
1526
+ */
1527
+ aggregateDistinct?: boolean;
1528
+ /**
1529
+ * How two values of THIS CALL combine into the value over the union of the
1530
+ * groups that produced them — the function's declared `AggregateMerge` with
1531
+ * DISTINCT already accounted for (`count(x)` ⇒ `'sum'`, `count(DISTINCT x)` ⇒
1532
+ * `'none'`, `min(DISTINCT x)` ⇒ `'min'`). Present exactly when
1533
+ * {@link aggregateFn} is, and `'none'` when the call cannot be merged — so a
1534
+ * consumer folding a tail of groups into a residual ("Other") reads ONE field
1535
+ * and gets a total answer, including for an aggregate a caller registered.
1536
+ *
1537
+ * Resolved HERE rather than left to the consumer because the browser holds no
1538
+ * engine: the registry lookup (and the DISTINCT rule that goes with it) is not
1539
+ * available on the far side of the wire.
1540
+ */
1541
+ aggregateMerge?: AggregateMerge;
1478
1542
  }
1479
1543
  /** The discriminated union of every expression / source resolution outcome. */
1480
1544
  type ResolvedType = TypeResolved | FieldResolved | ComputedResolved;
@@ -2448,6 +2512,20 @@ declare const EQ_SELECTIVITY = 0.33;
2448
2512
  declare const RANGE_SELECTIVITY = 0.5;
2449
2513
  /** Fixed selectivity of a non-indexed membership predicate (`col IN (...)`). */
2450
2514
  declare const IN_SELECTIVITY = 0.5;
2515
+ /**
2516
+ * Levels of expansion assumed when estimating a RECURSIVE CTE's size: the seed
2517
+ * plus this many runs of the recursive arm.
2518
+ *
2519
+ * The true fixpoint depth is not statically knowable — it depends on the DATA —
2520
+ * so this is a deliberate small constant, in the same spirit as the fixed
2521
+ * selectivities above. It is chosen SMALL rather than at the runtime's safety cap
2522
+ * (`DEFAULT_MAX_CTE_ITERATIONS` = 1000, which is the wrong shape of answer here):
2523
+ * a recursive CTE in practice walks a hierarchy — an org chart, a category tree,
2524
+ * a comment thread — a handful of levels deep, and estimating one at the safety
2525
+ * cap would refuse every ordinary closure under any budget. The point is that a
2526
+ * recursive body is not FREE, which is what it estimated at before `0.6.5`.
2527
+ */
2528
+ declare const RECURSIVE_CTE_LEVELS = 4;
2451
2529
  /** Per-row byte penalty for a semantic-similarity predicate (embedding work). */
2452
2530
  declare const SEMANTIC_ROW_PENALTY = 1000;
2453
2531
  /** Per-row byte penalty for a full-text-search predicate (scan work). */
@@ -3057,6 +3135,8 @@ declare class InExpr extends BoolExpr {
3057
3135
  forEachChild(visit: (child: Expr) => void): void;
3058
3136
  /** Validate that each list element / subquery output field is comparable with the value, infer params on either side, and resolve to bool. */
3059
3137
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): ResolvedType;
3138
+ /** The statement the SUBQUERY form runs; the value-list form runs none. */
3139
+ nestedQueryDef(): QueryDef | undefined;
3060
3140
  /** Estimated cost: children plus the inner query's cost when this is the subquery form. */
3061
3141
  cost(ctx: CostContext, scope: QueryScope): Cost;
3062
3142
  /** Membership keeps ~half the rows (matches a non-indexed range's breadth). */
@@ -3199,6 +3279,8 @@ declare class ExistsExpr extends BoolExpr {
3199
3279
  resolve(_engine: QueryEngine, _scope: QueryScope): ComputedResolved;
3200
3280
  /** FULLY VALIDATE the correlated inner query (problems nested under `query`) and resolve to bool. */
3201
3281
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): ComputedResolved;
3282
+ /** The statement this expr runs (so a nested-statement walk finds it). */
3283
+ nestedQueryDef(): QueryDef;
3202
3284
  /** Estimated cost: the subquery's scan cost (its own output is a single boolean). */
3203
3285
  cost(ctx: CostContext, scope: QueryScope): Cost;
3204
3286
  /** Execute the correlated subquery and return whether it produced any rows (negated for `NOT EXISTS`). */
@@ -3374,16 +3456,27 @@ declare class AggregateExpr extends Expr {
3374
3456
  static toSchema(opts: SchemaOptions): z.ZodTypeAny;
3375
3457
  protected aggregateHere(): boolean;
3376
3458
  forEachChild(visit: (child: Expr) => void): void;
3459
+ /**
3460
+ * The APPLIED-aggregate facts this call stamps onto its resolution: the
3461
+ * function name, whether it was DISTINCT, and how two of ITS values merge over
3462
+ * a union of groups. `merge` is resolved here — the function's declaration
3463
+ * reduced by the DISTINCT rule — rather than left to the consumer, because a
3464
+ * consumer reading `QueryField.type` over the wire has neither the engine to
3465
+ * look the declaration up nor the call to see the DISTINCT.
3466
+ */
3467
+ private applied;
3377
3468
  /**
3378
3469
  * Resolve to the function's declared output type, marked aggregate and nullable
3379
- * (except `count`), and carrying the APPLIED function's name.
3470
+ * (except `count`), and carrying the APPLIED function's name, DISTINCT-ness and
3471
+ * merge semantics.
3380
3472
  *
3381
- * `aggregateFn` is set on BOTH roads — including the unknown-function fallback,
3382
- * where the name is still the fact of what was written even though the
3383
- * resolution is a placeholder. This is the ONE node that can answer "which
3384
- * aggregate is this?": every wrapping expr reports `aggregate: true` from its
3385
- * children without a single applied function, and `Function.resolveOutput`
3386
- * never sets it, so nothing propagates a stale name upward.
3473
+ * Those three are set on BOTH roads — including the unknown-function fallback,
3474
+ * where the written name is still the fact of what was written even though the
3475
+ * resolution is a placeholder (an unknown function declares no merge, so that
3476
+ * road answers `'none'`). This is the ONE node that can answer "which aggregate
3477
+ * is this?": every wrapping expr reports `aggregate: true` from its children
3478
+ * without a single applied function, and `Function.resolveOutput` never sets
3479
+ * it, so nothing propagates a stale name upward.
3387
3480
  */
3388
3481
  resolve(engine: QueryEngine, scope: QueryScope): ResolvedType;
3389
3482
  /** Validate aggregate placement (not in WHERE, not nested) and the function's own named-arg checks. */
@@ -3399,6 +3492,12 @@ declare class AggregateExpr extends Expr {
3399
3492
  * there are no args (`count(*)`). Fan-out over a relation is now expressed as
3400
3493
  * an explicit `relation` JOIN in the query's `joins`, so the aggregate simply
3401
3494
  * runs over the (already-joined) rows; there is no hidden pre-aggregation CTE.
3495
+ *
3496
+ * DISTINCT is dropped for the ARG-LESS form: it de-duplicates argument values
3497
+ * and there are none, the runtime ignores it there too (`evaluate`), and
3498
+ * `count(DISTINCT *)` is a syntax error on every dialect. `validateWalk`
3499
+ * reports it (`aggregate.distinct-no-args`); emission stays TOTAL for a caller
3500
+ * that emits without validating first.
3402
3501
  */
3403
3502
  toSQL(dialect: Dialect, ctx: SqlContext): SqlText;
3404
3503
  /** Serialize back to its JSON ExprDef. */
@@ -3984,6 +4083,8 @@ declare class SubqueryExpr extends Expr {
3984
4083
  resolve(engine: QueryEngine, scope: QueryScope): ResolvedType;
3985
4084
  /** FULLY VALIDATE the correlated inner query (problems nested under `query`) and return its output type. */
3986
4085
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): ResolvedType;
4086
+ /** The statement this expr runs (so a nested-statement walk finds it). */
4087
+ nestedQueryDef(): QueryDef;
3987
4088
  /** Cost of running the inner query in a child scope. */
3988
4089
  cost(ctx: CostContext, scope: QueryScope): Cost;
3989
4090
  /** Execute the subquery (correlated to `row` when present) and return its first field. */
@@ -4099,7 +4200,12 @@ declare class QuerySource {
4099
4200
  static readonly SHAPES: ReadonlyMap<string, Shape<QuerySource>>;
4100
4201
  /** Resolve the type this source binds (its alias → typed type). */
4101
4202
  resolvedType(engine: QueryEngine, scope: QueryScope): TypeResolved;
4102
- /** Bind this source's alias into `scope`. */
4203
+ /**
4204
+ * Bind this source's alias into `scope`. A convenience for a caller that wants
4205
+ * only the binding; one that ALSO needs the resolved Type should call
4206
+ * `resolvedType` once and bind THAT, because resolving a derived source now
4207
+ * estimates its body and is not free (`SelectQuery.computeBind` does so).
4208
+ */
4103
4209
  bindInto(engine: QueryEngine, scope: QueryScope): void;
4104
4210
  /** Validate this source: an unknown type / CTE name, or a bad tabular-function call / subquery. */
4105
4211
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems): void;
@@ -5863,6 +5969,15 @@ declare class QueryFunction {
5863
5969
  */
5864
5970
  readonly unaggregate?: ExprDef;
5865
5971
  readonly unaggregateEmpty?: ExprDef;
5972
+ /**
5973
+ * How two of this AGGREGATE's per-group values combine into the value over the
5974
+ * union of those groups ({@link AggregateMerge}). Always answered — an
5975
+ * aggregate that declares nothing (and every non-aggregate) reports `'none'`,
5976
+ * so a consumer asking "can these two values be combined, and how" gets a total
5977
+ * answer for a caller-registered function as well as a builtin. See
5978
+ * {@link FunctionDef.merge}.
5979
+ */
5980
+ readonly merge: AggregateMerge;
5866
5981
  /** Intrinsic per-call cost this function adds beyond its args (default none). */
5867
5982
  readonly cost: Cost;
5868
5983
  /**
@@ -5885,6 +6000,7 @@ declare class QueryFunction {
5885
6000
  examples?: readonly string[];
5886
6001
  unaggregate?: ExprDef;
5887
6002
  unaggregateEmpty?: ExprDef;
6003
+ merge?: AggregateMerge;
5888
6004
  cost?: Cost;
5889
6005
  changes?: number;
5890
6006
  references?: readonly string[];
@@ -5924,6 +6040,22 @@ declare class QueryFunction {
5924
6040
  */
5925
6041
  validateCall(namedArgs: ReadonlyMap<string, ResolvedType>, p: Problems): void;
5926
6042
  }
6043
+ /**
6044
+ * The merge semantics of ONE aggregate CALL: the function's declared
6045
+ * {@link AggregateMerge}, reduced to `'none'` when the call is DISTINCT and the
6046
+ * declared operation is not idempotent.
6047
+ *
6048
+ * De-duplication is GLOBAL, not per-group: two groups' `count(DISTINCT x)` values
6049
+ * cannot be added, because a value counted in both must be counted once over the
6050
+ * union and the per-group results no longer say which values those were. Only the
6051
+ * idempotent operations survive it — `min`/`max` over a set are unchanged by
6052
+ * duplicates, as are `and`/`or` — so `'sum'` is the single arm DISTINCT cancels.
6053
+ *
6054
+ * Total by construction: every `AggregateMerge` (and `undefined`, for a function
6055
+ * that declares none) maps to an answer, so a consumer never needs a per-function
6056
+ * table of its own — the exact hard-coded list this declaration exists to delete.
6057
+ */
6058
+ declare function mergeOfAggregateCall(declared: AggregateMerge | undefined, distinct: boolean): AggregateMerge;
5927
6059
 
5928
6060
  /**
5929
6061
  * QueryEngine — the minimal engine surface needed by resolution + validation
@@ -6021,6 +6153,23 @@ declare class QueryEngine {
6021
6153
  readonly registry: Registry;
6022
6154
  /** Optional embedding provider (semantic features, Phase 4). */
6023
6155
  readonly embedder?: Embedder;
6156
+ /**
6157
+ * The NEUTRAL cost context over this engine — no execution-time `filters` /
6158
+ * `sort` / `params`.
6159
+ *
6160
+ * Used wherever a RESOLUTION path has to estimate: a DERIVED source sizes the
6161
+ * synthetic Type it binds from its own body (`QuerySource.resolvedType`, a CTE
6162
+ * name's binding — A18). Neutral on purpose, for two reasons. Those selections
6163
+ * belong to the ENCLOSING query — `engine.run` ANDs a `filters` predicate into
6164
+ * a select's WHERE by source name, and neither it nor a `sort` reaches inside a
6165
+ * derived table — and one shared instance gives every such estimate a single
6166
+ * identity to memoize against (see `ScopeMemo`), which is what keeps a deeply
6167
+ * nested statement's resolution linear. The consequence to know: a `LIMIT` bound
6168
+ * to a PARAM *inside* a CTE body / derived table is estimated UNCAPPED (the
6169
+ * conservative direction); one on the statement's own `final` still resolves,
6170
+ * because that is costed with the caller's real context.
6171
+ */
6172
+ readonly neutralCost: CostContext;
6024
6173
  /** Cache of parsed runtime functions, keyed by name. */
6025
6174
  private readonly functionCache;
6026
6175
  /** Per-Type executors (data + validation hooks). */
@@ -6444,14 +6593,34 @@ declare abstract class Query {
6444
6593
  * Params that are referenced but never observed against any type (so no type
6445
6594
  * can be inferred) are OMITTED here — they carry no `type` to report;
6446
6595
  * `validateQuery` surfaces them separately as `param.untyped`.
6596
+ *
6597
+ * Out-of-tree bounds (`limit` / `offset`) are picked up by the same walk —
6598
+ * each kind that OWNS a row bound observes it from its own `validateWalk`
6599
+ * (see {@link observeRowBounds}), so a bound at ANY nesting depth lands here.
6447
6600
  */
6448
6601
  params(engine: QueryEngine, scope?: QueryScope): ParamDef[];
6449
6602
  /**
6450
- * Observe any bind params that live OUTSIDE this query's walked expr tree
6451
- * (e.g. a SELECT's `limit` / `offset`), so `params()` reports them with the
6452
- * right inferred type. Base: none. Overridden by `SelectQuery`.
6603
+ * Observe a `limit` / `offset` ROW BOUND that is bound to a `param` (see
6604
+ * `autoPaginate`) against a number field type — a bound is always a row count
6605
+ * — so `params()` reports it with an inferred type. A bound lives OUTSIDE the
6606
+ * walked expr tree, so nothing else in the walk ever reaches it.
6607
+ *
6608
+ * INVARIANT: the kind that EMITS a row bound is the kind that observes it, and
6609
+ * it does so from its own `validateWalk`. That is what makes the report correct
6610
+ * at every NESTING DEPTH — `validateWalk` already recurses into a CTE body and
6611
+ * its `final`, a set-operation arm, and a FROM / IN / EXISTS subquery, and every
6612
+ * scope in that recursion shares ONE `ParamSet`. Observing only at the ROOT
6613
+ * (what `params()` used to do, via a `SelectQuery`-only hook) reported a paged
6614
+ * `cte` as taking NO params at all while `toSQL` still emitted
6615
+ * `LIMIT $1 OFFSET $2` — an unbindable statement whose declared signature was
6616
+ * empty (bug A17).
6617
+ *
6618
+ * The observation is recorded at the walk's CURRENT path (`p.here`, the
6619
+ * accessor that exists for exactly this), so a `param.conflict` naming a bound
6620
+ * points at the statement that OWNS it (`final.limit`) rather than at a
6621
+ * root-relative `limit` that does not exist.
6453
6622
  */
6454
- protected observeBoundParams(_params: ParamSet): void;
6623
+ protected observeRowBounds(scope: QueryScope, p: Problems, limit: number | ParamExprDef | undefined, offset: number | ParamExprDef | undefined): void;
6455
6624
  /**
6456
6625
  * The source names this query exposes for execution-time `filters` — i.e. the
6457
6626
  * sources a caller may target with `engine.run(query, { filters: [{ kind:
@@ -6521,13 +6690,30 @@ declare abstract class Query {
6521
6690
  * / CTEs refine it.
6522
6691
  */
6523
6692
  outputCost(ctx: CostContext, scope: QueryScope): Cost;
6693
+ /**
6694
+ * Visit every NESTED STATEMENT this query contains, each with the scope it is
6695
+ * evaluated in. The base finds the ones an EXPR carries — a `subquery` /
6696
+ * `exists` / subquery-form `in`, via {@link Expr.nestedQueryDef} over
6697
+ * {@link walkExprs} — in a child scope, exactly as those exprs cost and run
6698
+ * them. A kind that nests a statement somewhere ELSE overrides and adds it:
6699
+ * `SelectQuery` / `UpdateQuery` / `DeleteQuery` their FROM / JOIN subquery
6700
+ * sources (under their own bound scope), `InsertQuery` its `select` source,
6701
+ * `SetOperationQuery` both arms, `CTEStatementQuery` its entries + `final`.
6702
+ *
6703
+ * ONE enumeration, so a statement-level fact derived from it is total by
6704
+ * construction rather than by remembering every position — see
6705
+ * {@link affected}.
6706
+ */
6707
+ protected forEachNestedQuery(ctx: CostContext, scope: QueryScope, visit: (q: Query, s: QueryScope) => void): void;
6524
6708
  /**
6525
6709
  * Estimate the rows this statement MUTATES — a total plus a per-Type breakdown
6526
- * ({@link Affected}). A read-only query is `{ rows: 0, types: [] }` (the
6527
- * default); INSERT / UPDATE / DELETE name their target Type, and a CTE
6528
- * statement SUMS its data-modifying entries plus the final query per Type.
6710
+ * ({@link Affected}). A read-only query is `{ rows: 0, types: [] }`; INSERT /
6711
+ * UPDATE / DELETE add their target Type; and EVERY kind sums what its nested
6712
+ * statements mutate ({@link forEachNestedQuery}), so a data-modifying `WITH`
6713
+ * below a FROM subquery / a set-operation arm / a WHERE `in` is counted rather
6714
+ * than silently reported as zero. Same-Type rows are summed into one entry.
6529
6715
  */
6530
- affected(_ctx: CostContext, _scope: QueryScope): Affected;
6716
+ affected(ctx: CostContext, scope: QueryScope): Affected;
6531
6717
  /**
6532
6718
  * Enumerate what this query READS — the {@link QueryReferences} of Types,
6533
6719
  * specific fields, and DB functions it touches — INCLUDING execution-time
@@ -6594,8 +6780,19 @@ declare function makeField(name: string, type: ResolvedType): QueryField;
6594
6780
  * entries. Pure + order-preserving — the array form of a result's rows.
6595
6781
  */
6596
6782
  declare function toArrayRows(fields: QueryField[], rows: readonly SourceRecord[]): JsonValue[][];
6597
- /** Build a synthetic `Type` describing a set of output fields. */
6598
- declare function syntheticType(name: string, fields: readonly QueryField[]): Type;
6783
+ /**
6784
+ * Build a synthetic `Type` describing a set of output fields.
6785
+ *
6786
+ * `estimate` is the DERIVED SOURCE's own result size (its `outputCost`) — the
6787
+ * rows a reader of this Type will see, and their total width. Supply it whenever
6788
+ * the caller knows the query behind the fields (a CTE name's body, a FROM /
6789
+ * JOIN subquery): the cost model reads `Type.count` for a base scan and a join's
6790
+ * fan-out, so a synthetic Type WITHOUT it is a hard, un-authored zero that makes
6791
+ * everything reading the derived source structurally free (A18). Omit it only
6792
+ * where the Type describes a shape and never a scan — a result's `outputType`, a
6793
+ * set operation's ORDER BY scope.
6794
+ */
6795
+ declare function syntheticType(name: string, fields: readonly QueryField[], estimate?: Cost): Type;
6599
6796
  /** Build a `TypeResolved` over a synthetic Type for the given fields. */
6600
6797
  declare function typeFromFields(name: string, source: string, fields: readonly QueryField[]): TypeResolved;
6601
6798
  /** Single-field ⇒ that field's type; else a synthetic type. */
@@ -7067,6 +7264,17 @@ declare abstract class Expr implements Node {
7067
7264
  * cost / `changes` / referenced Types) without an `instanceof`.
7068
7265
  */
7069
7266
  functionRef(): string | undefined;
7267
+ /**
7268
+ * The nested STATEMENT this expr runs, as its serializable def, or `undefined`
7269
+ * when it holds none. Overridden by `subquery` / `exists` / the subquery form
7270
+ * of `in` — the three positions an expr can carry a whole query.
7271
+ *
7272
+ * Declared here, beside `fieldRef` / `orOperands` / `functionRef`, so a walk
7273
+ * can find EVERY nested statement without switching on expr classes: it is what
7274
+ * makes `Query.affected` total (a data-modifying statement nested in a WHERE is
7275
+ * still a mutation) rather than a list of the positions someone remembered.
7276
+ */
7277
+ nestedQueryDef(): QueryDef | undefined;
7070
7278
  /**
7071
7279
  * Emit this expression as a `SqlText` fragment for `dialect`, threading the
7072
7280
  * per-emit `ctx` (active scope, the join/CTE planner, RLS provider, bound
@@ -8592,8 +8800,18 @@ declare class SelectQuery extends Query {
8592
8800
  private outputExprs;
8593
8801
  /** A child of `inner` exposing this SELECT's outputs to `output` references. */
8594
8802
  private outputScope;
8595
- /** Bind FROM + joins into a fresh child scope; also collect alias → Type. */
8803
+ /**
8804
+ * Bind FROM + joins into a fresh child scope; also collect alias → Type and
8805
+ * return the FROM Type resolved ONCE. Resolving a source is no longer free —
8806
+ * a derived (subquery) source estimates its body to size the synthetic Type it
8807
+ * binds (A18) — so the single resolution is reused by every caller instead of
8808
+ * each re-resolving and re-costing the same subtree.
8809
+ */
8596
8810
  private bind;
8811
+ /** Memoizes {@link bind} per enclosing scope — see {@link ScopeMemo}. */
8812
+ private readonly bindMemo;
8813
+ /** The uncached binding work {@link bind} memoizes. */
8814
+ private computeBind;
8597
8815
  /** Resolve the output fields by binding FROM + joins and resolving each select expr. */
8598
8816
  outputFields(engine: QueryEngine, scope: QueryScope): QueryField[];
8599
8817
  /**
@@ -8645,6 +8863,14 @@ declare class SelectQuery extends Query {
8645
8863
  walkExprs(visit: (e: Expr) => void): void;
8646
8864
  /** Bind FROM + joins so a `filters` placeholder's `source` resolves for `filters()`. */
8647
8865
  protected filterScope(engine: QueryEngine, scope: QueryScope): QueryScope;
8866
+ /**
8867
+ * The statements this SELECT nests: every clause expr's (the base), plus the
8868
+ * DERIVED SOURCES — a FROM subquery and any manually-joined subquery source —
8869
+ * visited under this select's own bound scope.
8870
+ */
8871
+ protected forEachNestedQuery(ctx: CostContext, scope: QueryScope, visit: (q: Query, s: QueryScope) => void): void;
8872
+ /** The FROM source plus every manually-joined source (a relation join adds none). */
8873
+ private sources;
8648
8874
  /** Resolve `references` field-refs against FROM + joins + this SELECT's outputs. */
8649
8875
  protected referenceScope(engine: QueryEngine, scope: QueryScope): QueryScope;
8650
8876
  /**
@@ -8689,13 +8915,6 @@ declare class SelectQuery extends Query {
8689
8915
  * `isRoot` marks the entry query being run/emitted (threaded on the context).
8690
8916
  */
8691
8917
  private effectiveDefaultOrder;
8692
- /**
8693
- * `limit` / `offset` may be bound to a `param` (see `autoPaginate`), but they
8694
- * live outside the walked expr tree, so `params()` never observes them. They
8695
- * are always integer row counts, so observe each against a number field type
8696
- * — making them surface in `params()` with the right inferred type.
8697
- */
8698
- protected observeBoundParams(params: ParamSet): void;
8699
8918
  /**
8700
8919
  * Estimate result `{ rows, bytes }` the way a SQL engine PROCESSES the query.
8701
8920
  *
@@ -8866,13 +9085,26 @@ declare class InsertQuery extends Query {
8866
9085
  private conflictScope;
8867
9086
  /** Resolve the output fields from the RETURNING projection against the target scope. */
8868
9087
  outputFields(engine: QueryEngine, scope: QueryScope): QueryField[];
8869
- /** Validate the target type, fields, row homogeneity, RETURNING, and ON CONFLICT assignments. */
9088
+ /** Validate the target type, the source SELECT, fields, row homogeneity, RETURNING, and ON CONFLICT assignments. */
8870
9089
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, _ctx: ValidateContext): void;
8871
9090
  /** The target type plus any types read by an INSERT … SELECT source. */
8872
9091
  referencedTypes(): readonly string[];
8873
9092
  /** Estimate `{ rows, bytes }`: the VALUES row count (or the source query's rows) at the target's per-row size. */
8874
9093
  cost(ctx: CostContext, scope: QueryScope): Cost;
8875
- /** Rows this INSERT adds (on `into`): the VALUES row count, or the source SELECT's output rows. */
9094
+ /**
9095
+ * Walk every clause expr — each VALUES row's assigned values, RETURNING, and an
9096
+ * ON CONFLICT DO UPDATE's assignments — recursing via `Expr.walk`. The
9097
+ * traversal primitive a statement-wide fact is built on
9098
+ * (`forEachNestedQuery`, and so `affected`).
9099
+ */
9100
+ walkExprs(visit: (e: Expr) => void): void;
9101
+ /** The statements this INSERT nests: its clause exprs' plus the source SELECT. */
9102
+ protected forEachNestedQuery(ctx: CostContext, scope: QueryScope, visit: (q: Query, s: QueryScope) => void): void;
9103
+ /**
9104
+ * Rows this INSERT adds (on `into`): the VALUES row count, or the source
9105
+ * SELECT's output rows — PLUS whatever its nested statements mutate (an
9106
+ * `INSERT … SELECT` whose source is a data-modifying `WITH` writes twice).
9107
+ */
8876
9108
  affected(ctx: CostContext, scope: QueryScope): Affected;
8877
9109
  /** Materialize rows into the target's `TypeState`, applying ON CONFLICT, then project RETURNING. */
8878
9110
  execute(ctx: RuntimeContext): Promise<QueryResult>;
@@ -8965,7 +9197,20 @@ declare class UpdateQuery extends Query {
8965
9197
  referencedTypes(): readonly string[];
8966
9198
  /** Estimate `{ rows, bytes }`: the target scan × join fan-out, reduced by WHERE. */
8967
9199
  cost(ctx: CostContext, scope: QueryScope): Cost;
8968
- /** Rows this UPDATE mutates: the target type's rows matching WHERE (index / selectivity / OR-aware). */
9200
+ /**
9201
+ * Walk every clause expr — SET values, WHERE, RETURNING, and each join's `and`
9202
+ * predicate — recursing into descendants via `Expr.walk`. The traversal
9203
+ * primitive a statement-wide fact is built on (`forEachNestedQuery`, and so
9204
+ * `affected`).
9205
+ */
9206
+ walkExprs(visit: (e: Expr) => void): void;
9207
+ /** The statements this UPDATE nests: its clause exprs' plus any manually-joined subquery source. */
9208
+ protected forEachNestedQuery(ctx: CostContext, scope: QueryScope, visit: (q: Query, s: QueryScope) => void): void;
9209
+ /**
9210
+ * Rows this UPDATE mutates: the target type's rows matching WHERE (index /
9211
+ * selectivity / OR-aware), PLUS whatever its nested statements mutate (a
9212
+ * data-modifying `WITH` inside a SET / WHERE subquery is still a mutation).
9213
+ */
8969
9214
  affected(ctx: CostContext, scope: QueryScope): Affected;
8970
9215
  /** Expand joins, filter by WHERE, apply SET to each matched target row, then project RETURNING. */
8971
9216
  execute(ctx: RuntimeContext): Promise<QueryResult>;
@@ -9055,7 +9300,19 @@ declare class DeleteQuery extends Query {
9055
9300
  referencedTypes(): readonly string[];
9056
9301
  /** Estimate `{ rows, bytes }`: the target scan × join fan-out, reduced by WHERE. */
9057
9302
  cost(ctx: CostContext, scope: QueryScope): Cost;
9058
- /** Rows this DELETE removes: the target type's rows matching WHERE (index / selectivity / OR-aware). */
9303
+ /**
9304
+ * Walk every clause expr — WHERE, RETURNING, and each join's `and` predicate —
9305
+ * recursing into descendants via `Expr.walk`. The traversal primitive a
9306
+ * statement-wide fact is built on (`forEachNestedQuery`, and so `affected`).
9307
+ */
9308
+ walkExprs(visit: (e: Expr) => void): void;
9309
+ /** The statements this DELETE nests: its clause exprs' plus any manually-joined subquery source. */
9310
+ protected forEachNestedQuery(ctx: CostContext, scope: QueryScope, visit: (q: Query, s: QueryScope) => void): void;
9311
+ /**
9312
+ * Rows this DELETE removes: the target type's rows matching WHERE (index /
9313
+ * selectivity / OR-aware), PLUS whatever its nested statements mutate (a
9314
+ * data-modifying `WITH` inside a WHERE subquery is still a mutation).
9315
+ */
9059
9316
  affected(ctx: CostContext, scope: QueryScope): Affected;
9060
9317
  /** Expand joins, filter by WHERE, project RETURNING (pre-removal), then delete the matched rows. */
9061
9318
  execute(ctx: RuntimeContext): Promise<QueryResult>;
@@ -9168,12 +9425,12 @@ declare class SetOperationQuery extends Query {
9168
9425
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): void;
9169
9426
  /** The union of both arms' referenced Type names. */
9170
9427
  referencedTypes(): readonly string[];
9171
- /** Set-level `limit` / `offset` params live outside the walked expr tree. */
9172
- protected observeBoundParams(params: ParamSet): void;
9173
9428
  /** Estimate the WORK `{ rows, bytes }`: combine both arms' cost per operation, then cap by LIMIT. */
9174
9429
  cost(ctx: CostContext, scope: QueryScope): Cost;
9175
9430
  /** Estimate the RESULT SIZE: combine both arms' `outputCost` per operation, then cap by LIMIT. */
9176
9431
  outputCost(ctx: CostContext, scope: QueryScope): Cost;
9432
+ /** The statements this set operation nests: both arms (each in its own child scope). */
9433
+ protected forEachNestedQuery(ctx: CostContext, scope: QueryScope, visit: (q: Query, s: QueryScope) => void): void;
9177
9434
  /** Reads = the union of BOTH arms' references. */
9178
9435
  references(engine: QueryEngine, scope: QueryScope, ctx: CostContext): QueryReferences;
9179
9436
  /** Combine the two arms' costs per the set operation (UNION sums, INTERSECT mins, EXCEPT keeps left). */
@@ -9222,12 +9479,20 @@ interface CteEntry {
9222
9479
  readonly recursive: boolean;
9223
9480
  /** The output fields used to bind this CTE's synthetic type downstream. */
9224
9481
  boundFields(engine: QueryEngine, scope: QueryScope): QueryField[];
9482
+ /**
9483
+ * The SIZE OF THE ROWS this entry materializes under its name — what a later
9484
+ * entry / the `final` query READS when it selects `FROM <name>`, and so the
9485
+ * cardinality its bound synthetic Type must carry (A18).
9486
+ */
9487
+ estimate(ctx: CostContext, scope: QueryScope): Cost;
9488
+ /** The WORK this entry itself does (it runs whether or not `final` reads it). */
9489
+ cost(ctx: CostContext, scope: QueryScope): Cost;
9225
9490
  /** Validate the entry's inner queries (reporting at `ctes[index]`). */
9226
9491
  validate(engine: QueryEngine, inner: QueryScope, p: Problems, ctx: ValidateContext, index: number): void;
9227
9492
  /** Collect referenced Type names (excluding CTE names). */
9228
9493
  collectReferenced(out: Set<string>, cteNames: ReadonlySet<string>): void;
9229
- /** Rows this entry MUTATES (a data-modifying CTE body); none for a read-only entry. */
9230
- affected(ctx: CostContext, scope: QueryScope): Affected;
9494
+ /** Every STATEMENT this entry runs (one body, or a recursive pair). */
9495
+ forEachQuery(visit: (q: Query) => void): void;
9231
9496
  /** What this entry's inner query READS (Types / fields / functions). */
9232
9497
  references(engine: QueryEngine, scope: QueryScope, ctx: CostContext): QueryReferences;
9233
9498
  /** Evaluate the entry, populating `ctx.ctes[name]`. */
@@ -9267,20 +9532,62 @@ declare class CTEStatementQuery extends Query {
9267
9532
  * every problem in one pass (never throws). See `shape/`.
9268
9533
  */
9269
9534
  static readonly SHAPE: Shape<CTEStatementQuery>;
9270
- /** Bind each CTE name as a synthetic type so downstream refs type-check. */
9535
+ /**
9536
+ * Bind each CTE name as a synthetic type so downstream refs type-check — each
9537
+ * carrying its BODY's estimated size, which is what a reader of that name will
9538
+ * actually scan.
9539
+ *
9540
+ * Before `0.6.5` the bound Type was built `count: 0, bytes: 0`, so a `WITH`
9541
+ * cost ZERO however much it read: the root's cost IS the `final`'s cost, and
9542
+ * `final` scans these Types. That made every cost budget structurally
9543
+ * un-fireable on a `cte` — a `DELETE … RETURNING` of ten rows cross-joined to a
9544
+ * million-row table passed `checkCost` at `{rows: 0}` and delivered ten million
9545
+ * (A18). The estimate the body needs is one the engine can already compute, and
9546
+ * the entries bind in order, so entry `i` is estimated with entries `0..i-1`
9547
+ * already bound (a CTE may read an earlier one).
9548
+ *
9549
+ * Costing each body here means `bind` is no longer free, and `bind` runs on the
9550
+ * validate / resolve / emit paths too. That is deliberate — ONE binding shape,
9551
+ * used everywhere, cannot drift into "the count is right when you ask for cost
9552
+ * and zero when you ask for fields" — and it is paid once per scope
9553
+ * ({@link ScopeMemo}), which is what keeps a deeply nested statement linear.
9554
+ *
9555
+ * The estimate is taken with `engine.neutralCost`: execution-time `filters` /
9556
+ * `sort` / `params` are the CALLER's selections against the enclosing query's
9557
+ * sources, so a `LIMIT` bound to a param INSIDE a body is estimated uncapped
9558
+ * (the conservative direction). One on `final` still resolves — the `final` is
9559
+ * costed with the caller's real context.
9560
+ */
9271
9561
  private bind;
9562
+ /** Memoizes {@link bind} per enclosing scope — see {@link ScopeMemo}. */
9563
+ private readonly bindMemo;
9272
9564
  /** The output fields — those of the final query, with CTE names bound. */
9273
9565
  outputFields(engine: QueryEngine, scope: QueryScope): QueryField[];
9274
9566
  /** Validate each CTE entry and the final query, all with CTE names bound. */
9275
9567
  validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): void;
9276
9568
  /** The Type names read by the CTEs + final query, excluding CTE names themselves. */
9277
9569
  referencedTypes(): readonly string[];
9278
- /** Estimate `{ rows, bytes }` — the final query's cost, with CTE names bound. */
9570
+ /**
9571
+ * Estimate the WORK: the final query's cost (over the now non-zero CTE Types)
9572
+ * PLUS every entry's own cost. An entry is not free just because `final`
9573
+ * collapses its rows — `WITH t AS (SELECT … FROM million) SELECT count(*) FROM t`
9574
+ * reads a million rows to produce one — and this runtime MATERIALIZES each
9575
+ * entry's whole result in memory (`CTEEntryImpl.execute`), so those rows are
9576
+ * the most real cost the statement has.
9577
+ */
9279
9578
  cost(ctx: CostContext, scope: QueryScope): Cost;
9280
- /** The RESULT SIZE is the final query's output cost, with CTE names bound. */
9579
+ /**
9580
+ * The RESULT SIZE is the final query's output cost, with CTE names bound —
9581
+ * entries do NOT add here: they are work, not rows delivered to the caller.
9582
+ */
9281
9583
  outputCost(ctx: CostContext, scope: QueryScope): Cost;
9282
- /** Rows mutated: every data-modifying CTE entry plus the final query, summed per Type. */
9283
- affected(ctx: CostContext, scope: QueryScope): Affected;
9584
+ /**
9585
+ * The statements this `WITH` nests: every entry's body (both arms of a
9586
+ * recursive one) and the `final` query, all under the bound scope. `affected`
9587
+ * falls out of this — a data-modifying entry is counted because it is a nested
9588
+ * statement, not because CTEs have a rule of their own.
9589
+ */
9590
+ protected forEachNestedQuery(ctx: CostContext, scope: QueryScope, visit: (q: Query, s: QueryScope) => void): void;
9284
9591
  /** Reads = the final query's plus every entry's references (Types / fields / functions). */
9285
9592
  references(engine: QueryEngine, scope: QueryScope, ctx: CostContext): QueryReferences;
9286
9593
  /** Evaluate each CTE in order (populating `ctx.ctes`), then run the final query. */
@@ -10228,4 +10535,4 @@ declare function parseQueryTool(engine: QueryEngine, raw: unknown, options?: Bui
10228
10535
  */
10229
10536
  declare function buildQueryTool(engine: QueryEngine, options?: BuildQueryToolOptions): Tool<{}, {}, string, QueryToolInput, Promise<QueryResult>, [], Query>;
10230
10537
 
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 };
10538
+ export { AID_REGISTRY, type Access, type AccessRun, type AccessSql, AggregateExpr, type AggregateExprDef, type AggregateMerge, 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, RECURSIVE_CTE_LEVELS, 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, mergeOfAggregateCall, 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 };