kern-orm 0.2.0 → 0.4.0

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.
@@ -273,6 +273,11 @@ interface NestedField {
273
273
  readonly key: string;
274
274
  readonly nested: ResultPlan;
275
275
  }
276
+ /** Field of a record in the template of a result plan: its key and its value before the values of a row are assigned. */
277
+ interface RecordTemplateField {
278
+ readonly key: string;
279
+ readonly value: unknown;
280
+ }
276
281
  /**
277
282
  * How a query returns its rows: `many` as an array; `one` as one row, rejecting without it; `nullable` as one row or `null` without it; `optional` as one row or `undefined` without it.
278
283
  *
@@ -292,6 +297,12 @@ interface ResultPlan extends ResultMode {
292
297
  readonly fields: readonly ResultField[];
293
298
  /** Required relation that guarantees the row of nested rows `one`, such as `field.form`, whose missing row is a `RequiredRelationError` rather than a `NotFoundError`. */
294
299
  readonly guaranteedBy?: string | undefined;
300
+ /**
301
+ * Every field of a record in its order, with the values of its literals, which a row does not hold; `undefined` for a query without literals.
302
+ *
303
+ * A record starts from it, so its keys keep their order whichever of them a row holds.
304
+ */
305
+ readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
295
306
  }
296
307
  /** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
297
308
  declare class NotFoundError extends Error {
@@ -456,10 +467,12 @@ interface CompileOptions {
456
467
  /** PostgreSQL schema qualifying every table; tables stay unqualified when it is not set. */
457
468
  schemaName?: string;
458
469
  }
459
- /** Value compared with an expression of type `T` accepting values of type `I`; `null` is matched with `isNull` instead. */
460
- type Operand<T, I = T> = NonNullable<I> | AnyExpression<NonNullable<T> | null>;
461
- /** SQL value of an operand, unwrapping an expression. */
462
- type OperandValue<V> = V extends AnyExpression<infer T> ? T : V;
470
+ /**
471
+ * Value compared with an expression of type `T` accepting values of type `I`: a value, an expression, or a query of one value, such as of `get` or of an aggregate; `null` is matched with `isNull` instead.
472
+ */
473
+ type Operand<T, I = T> = NonNullable<I> | AnyExpression<NonNullable<T> | null> | ScalarQuery<NonNullable<T> | null>;
474
+ /** SQL value of an operand, unwrapping an expression or a query. */
475
+ type OperandValue<V> = V extends AnyExpression<infer T> ? T : V extends ScalarQuery ? ScalarQueryValue<V> : V;
463
476
  /** Boolean result that can be NULL when an input value can be NULL. */
464
477
  type BooleanResult<T> = boolean | (null extends T ? null : never);
465
478
  /** Signature of a generic operator comparing an expression with an operand of its type, such as `lt`. */
@@ -467,56 +480,80 @@ interface ComparisonSignature extends OperatorSignature {
467
480
  readonly method: <V extends Operand<this["T"], this["I"]>>(value: V) => Expression<BooleanResult<this["T"] | OperandValue<V>>>;
468
481
  }
469
482
  /**
470
- * Compares an expression with a value or another expression, encoding a plain value with the type of the expression.
483
+ * Compares an expression with a value, another expression, or a query of one value, encoding a plain value with the type of the expression.
471
484
  *
472
485
  * Operators of custom types build comparisons with it, such as `compare(self, "ILIKE", pattern)`.
473
486
  */
474
487
  declare function compare<T, V>(self: AnyExpression<T>, operator: ComparisonNode["operator"], value: V): Expression<BooleanResult<T | OperandValue<V>>>;
475
- /** Runtime mark of the operators of `equalityOperators`, which tell that a type has SQL `=`. */
476
- declare const equalityBrand: unique symbol;
477
- /** Generic operator of `equalityOperators`, which gives the type it is added to SQL `=`. */
478
- interface EqualityOperator<S extends OperatorSignature> extends GenericOperator<S> {
479
- readonly [equalityBrand]: true;
488
+ /** Selection of the rows of a nested query as the value of the field `key`. */
489
+ interface NestedSelectionNode {
490
+ readonly key: string;
491
+ readonly query: QueryNode;
492
+ /** `Db` that the nested query is bound to, which must be the `Db` that runs the statement. */
493
+ readonly db: AnyDb | undefined;
480
494
  }
481
- /** Signature of `in`: membership in a list of operands of the expression type; an empty list yields `FALSE`. */
482
- interface InSignature extends OperatorSignature {
483
- readonly method: <const L extends readonly Operand<this["T"], this["I"]>[]>(list: L) => Expression<L extends readonly [] ? boolean : BooleanResult<this["T"] | OperandValue<L[number]>>>;
495
+ /** Selection of a value from code as the field `key` of every record, which a statement does not select. */
496
+ interface LiteralSelectionNode {
497
+ readonly key: string;
498
+ readonly literal: unknown;
499
+ }
500
+ /** Field that a statement selects: an expression, or the rows of a nested query. */
501
+ type SqlSelectedNode = ProjectionNode | NestedSelectionNode;
502
+ /** Field selected by a query: one that its statement selects, or a literal. */
503
+ type SelectedNode = SqlSelectedNode | LiteralSelectionNode;
504
+ /** Select query of a table; its result mode applies when it is executed or its rows are nested. */
505
+ interface QueryNode extends ResultMode {
506
+ readonly kind: "query";
507
+ readonly from: TableSourceNode;
508
+ /** Relation whose records the query selects, correlated with its parent by the relation filter. */
509
+ readonly relation: RelationDefinition | undefined;
510
+ /** Fields in the order of the result, with unique keys; a query without them returns records without fields. */
511
+ readonly projections: readonly SelectedNode[];
512
+ readonly filters: QueryFilters;
513
+ readonly orderBy: readonly OrderNode[];
514
+ readonly limit: ExpressionNode | undefined;
515
+ readonly offset: ExpressionNode | undefined;
516
+ /** Whether a required relation guarantees the row of the query, so that a filter makes a query of rows `one` resolve without it; see `SelectQueryState`. */
517
+ readonly guaranteed: boolean;
518
+ /** Whether `all` allows a mutation of the query to change every row of the table without a filter. */
519
+ readonly all: boolean;
484
520
  }
485
- /** Operators of `equalityOperators`. */
486
- type EqualityOperators = {
487
- eq: EqualityOperator<ComparisonSignature>;
488
- ne: EqualityOperator<ComparisonSignature>;
489
- in: EqualityOperator<InSignature>;
490
- };
491
- /** Tells whether operators `O` include an operator of `equalityOperators`, so that their type has SQL `=`. */
492
- type HasEquality<O> = true extends { [K in keyof O]: O[K] extends {
493
- readonly [equalityBrand]: true;
494
- } ? true : false; }[keyof O] ? true : false;
495
521
  /**
496
- * Operators of SQL equality: `eq`, `ne`, and `in`; `orderingOperators` include them.
522
+ * Mutation of a table that returns the fields of the rows it changes, which may nest queries, or the number of the rows without them.
497
523
  *
498
- * A type has SQL `=` only with these operators, so that an array of it has them too; another operator named `eq` does not give it `=`.
524
+ * Its result mode is the rows mode of the rows it changes and whether a row is the value of its only field.
499
525
  */
500
- declare const equalityOperators: EqualityOperators;
526
+ type MutationNode = MutationStatementNode<SelectedNode>;
527
+ /** Query of `$select` without a source: one record whose fields are the values of expressions, the rows of independent queries, and literals. */
528
+ interface RecordQueryNode {
529
+ readonly kind: "record";
530
+ /** Fields in the order of the record, with unique keys. */
531
+ readonly projections: readonly SelectedNode[];
532
+ }
501
533
  /** Records of a query without selected fields. */
502
534
  type EmptyRecord = Record<never, never>;
503
535
  /** State of a query in types: the record or value of its rows, how its rows become its result, and the relations it selects records of. */
504
536
  interface QueryState extends ResultMode {
505
- /** Record of a row, or the value of its only field for a query made by `get`, `pluck`, or an aggregate method, such as `count`. */
537
+ /** Record of a row, or the value of its only field for a query made by `get`, `pluck`, an aggregate method, such as `count`, or `exists`. */
506
538
  readonly result: unknown;
507
539
  /** Relations whose records the query and the queries nested in it select, which a `Db` must have. */
508
540
  readonly uses: UsedRelation;
509
541
  }
542
+ /** Type of the value of a query: the values that it encodes, such as the fallback of `coalesce`, and its operators, which `expr` gives its expression. */
543
+ interface QueryValueType {
544
+ readonly input: unknown;
545
+ readonly operators: OperatorDefinitions;
546
+ }
510
547
  /**
511
- * State of a select query in types: its table, the relations of its schema, the record or value of its rows and the values that its value accepts, how its rows become its result, and the relations it selects records of.
548
+ * State of a select query in types: its table, the relations of its schema, the record or value of its rows and the type of its value, how its rows become its result, and the relations it selects records of.
512
549
  *
513
550
  * Methods change only their own parts of the state.
514
551
  */
515
552
  interface SelectQueryState extends QueryState {
516
553
  readonly table: AnyTable;
517
554
  readonly schema: SchemaContext;
518
- /** Values that the type of the value of a query of values encodes, such as the fallback of `coalesce`; `never` for a query of records. */
519
- readonly input: unknown;
555
+ /** Type of the value of a query of values, a `QueryValueType`; `never` for a query of records. */
556
+ readonly valueType: unknown;
520
557
  /**
521
558
  * Whether a required relation guarantees the row of the query, such as of `field.form`.
522
559
  *
@@ -524,7 +561,7 @@ interface SelectQueryState extends QueryState {
524
561
  * The callback of a helper starts with it, so that the effect of the helper records whether the callback filters.
525
562
  */
526
563
  readonly guaranteed: boolean;
527
- /** Whether the query is made by an aggregate method, such as `count`, which makes `get`, `pluck`, and the aggregate methods reject it. */
564
+ /** Whether the query is made by an aggregate method, such as `count`, or by `exists`, which makes `get`, `pluck`, the aggregate methods, and `exists` reject it. */
528
565
  readonly aggregate: boolean;
529
566
  }
530
567
  /** State of a query over table `T` with schema context `C`, whatever its result. */
@@ -539,50 +576,27 @@ interface QueryStateOf<T extends AnyTable, C extends SchemaContext = SchemaConte
539
576
  */
540
577
  interface InitialQueryState<T extends AnyTable, C extends SchemaContext = NoRelations, U extends UsedRelation = never, Rows extends ResultRows = "many", Guaranteed extends boolean = false> extends QueryStateOf<T, C> {
541
578
  readonly result: EmptyRecord;
542
- readonly input: never;
579
+ readonly valueType: never;
543
580
  readonly rows: Rows;
544
581
  readonly value: false;
545
582
  readonly uses: U;
546
583
  readonly guaranteed: Guaranteed;
547
584
  readonly aggregate: false;
548
585
  }
549
- /** Selection of the rows of a nested query as the value of the field `key`. */
550
- interface NestedSelectionNode {
551
- readonly key: string;
552
- readonly query: QueryNode;
553
- /** `Db` that the nested query is bound to, which must be the `Db` that runs the statement. */
554
- readonly db: AnyDb | undefined;
555
- }
556
- /** Field selected by a query: an expression, or the rows of a nested query. */
557
- type SelectedNode = ProjectionNode | NestedSelectionNode;
558
- /** Select query of a table; its result mode applies when it is executed or its rows are nested. */
559
- interface QueryNode extends ResultMode {
560
- readonly kind: "query";
561
- readonly from: TableSourceNode;
562
- /** Relation whose records the query selects, correlated with its parent by the relation filter. */
563
- readonly relation: RelationDefinition | undefined;
564
- /** Fields in the order of the result, with unique keys; a query without them returns records without fields. */
565
- readonly projections: readonly SelectedNode[];
566
- readonly filters: QueryFilters;
567
- readonly orderBy: readonly OrderNode[];
568
- readonly limit: ExpressionNode | undefined;
569
- readonly offset: ExpressionNode | undefined;
570
- /** Whether a required relation guarantees the row of the query, so that a filter makes a query of rows `one` resolve without it; see `SelectQueryState`. */
571
- readonly guaranteed: boolean;
572
- /** Whether `all` allows a mutation of the query to change every row of the table without a filter. */
573
- readonly all: boolean;
574
- }
575
- /**
576
- * Mutation of a table that returns the fields of the rows it changes, which may nest queries, or the number of the rows without them.
577
- *
578
- * Its result mode is the rows mode of the rows it changes and whether a row is the value of its only field.
579
- */
580
- type MutationNode = MutationStatementNode<SelectedNode>;
581
- /** Query of `$select` without a source: one record whose fields are the values of expressions and the rows of independent queries. */
582
- interface RecordQueryNode {
583
- readonly kind: "record";
584
- /** Fields in the order of the record, with unique keys. */
585
- readonly projections: readonly SelectedNode[];
586
+ /** Type of a count: a `bigint` of PostgreSQL decoded as a number, rejecting a count that a number cannot hold exactly. */
587
+ declare const countType: BaseType<number, number, MergeOperators<NoOperators, {
588
+ lt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
589
+ lte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
590
+ gt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
591
+ gte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
592
+ eq: EqualityOperator<ComparisonSignature>;
593
+ ne: EqualityOperator<ComparisonSignature>;
594
+ in: EqualityOperator<InSignature>;
595
+ }>, undefined>;
596
+ /** Type of the value of a query of a count. */
597
+ interface CountValueType extends QueryValueType {
598
+ readonly input: TypeInput<typeof countType>;
599
+ readonly operators: TypeOperators<typeof countType>;
586
600
  }
587
601
  /** Rows mode of a query of a relation of kind `Kind`: `many`, or one row, `nullable` unless `Required` is `true`; a union gives the union of their modes. */
588
602
  type RelationRows<Kind extends RelationKind, Required extends boolean> = Kind extends "many" ? "many" : Required extends true ? "one" : "nullable";
@@ -605,7 +619,7 @@ type ResultByRows<Result, Rows extends ResultRows> = Rows extends "many" ? Resul
605
619
  /** References to the columns of the query source, passed to query callbacks. */
606
620
  type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
607
621
  /**
608
- * Queries of the records of the relations of the table of schema context `C`, by relation name, which the callback of `select` receives beside the columns.
622
+ * Queries of the records of the relations of the table of schema context `C`, by relation name, which the callbacks of `select`, `where`, and `orderBy` receive beside the columns.
609
623
  *
610
624
  * A relation name is never a column key of its table.
611
625
  * A context whose table key is not known, such as one of a query of any schema, has no relations.
@@ -616,9 +630,14 @@ type RelationQueries<R extends SchemaContext["relations"], K extends keyof R & s
616
630
  type RelatedQuery<R extends SchemaContext["relations"], K extends keyof R & string, N extends keyof R[K] & string> = SelectQuery<InitialQueryState<R[K][N]["target"], TableContext<R, R[K][N]["targetKey"]>, UsedRelation<K, N, R[K][N]>, RelationRows<R[K][N]["kind"], R[K][N]["required"]>, R[K][N]["required"]>>;
617
631
  /** Runtime context of the queries of a table in the schema they start from. */
618
632
  interface QueryContext {
619
- /** Getters of the queries of the relations of the table, which the references of `select` have as their own properties and which read the key columns from them. */
633
+ /** Getters of the queries of the relations of the table, which the references of the callbacks of `select`, `where`, and `orderBy` have as their own properties and which read the key columns from them. */
620
634
  readonly relations: PropertyDescriptorMap;
621
635
  }
636
+ /** Type of the value of a query of `exists`. */
637
+ interface ExistsValueType extends QueryValueType {
638
+ readonly input: boolean;
639
+ readonly operators: EqualityOperators;
640
+ }
622
641
  declare const conditionValues: unique symbol;
623
642
  /** Predicate accepted by `where`, `and`, `or`, and `not`; SQL treats a `NULL` predicate as not satisfied. */
624
643
  type Predicate = AnyExpression<boolean | null>;
@@ -631,11 +650,11 @@ interface Condition<V> {
631
650
  readonly [conditionValues]?: V;
632
651
  }
633
652
  /**
634
- * Operand of `and`, `or`, and `not`: a predicate, a condition, or an object of column values.
653
+ * Operand of `and`, `or`, and `not`: a predicate, a query of one Boolean value, such as of `exists`, a condition, or an object of column values.
635
654
  *
636
655
  * Column values `V` are never inferred from an object, so that object keys are checked against the table instead of determining `V`.
637
656
  */
638
- type ConditionOperand<V, T extends boolean | null = boolean | null> = AnyExpression<T> | Condition<V> | NoInfer<V>;
657
+ type ConditionOperand<V, T extends boolean | null = boolean | null> = AnyExpression<T> | ScalarQuery<T> | Condition<V> | NoInfer<V>;
639
658
  /**
640
659
  * Result of `and`, `or`, and `not`: a condition checked against the table inside `where`, a Boolean expression without a table.
641
660
  */
@@ -653,29 +672,34 @@ declare function not<V = never, T extends boolean | null = [V] extends [never] ?
653
672
  */
654
673
  type WhereValues<T extends AnyTable> = { [K in keyof T["columns"]]?: EqValue<T, K> | (null extends ColumnValues<T>[K] ? null : never); };
655
674
  /** Operand of the `eq` operator of column `K` of table `T` in an object passed to `where`, such as an expression. */
656
- type EqValue<T extends AnyTable, K extends keyof T["columns"]> = IsAny<ColumnOperators<T, K>> extends true ? ColumnValues<T>[K] : EqOperand<ColumnRefs<T>[K]>;
657
- /** Operand of the `eq` operator of an expression, if it has one taking a single operand. */
675
+ type EqValue<T extends AnyTable, K extends keyof T["columns"]> = IsAny<ColumnOperators<T, K>> extends true ? ColumnValues<T>[K] : ColumnOperators<T, K> extends {
676
+ readonly eq: EqualityOperator<ComparisonSignature>;
677
+ } ? Operand<TypeOutput<T["columns"][K]["type"]>, TypeInput<T["columns"][K]["type"]>> : EqOperand<ColumnRefs<T>[K]>;
678
+ /** Operand of the `eq` operator of an expression, if it has one taking a single operand and returning a predicate. */
658
679
  type EqOperand<E> = E extends {
659
680
  eq: (value: infer V) => Predicate;
660
681
  } ? V : never;
661
- /** Filter of `where`: a Boolean expression, an object of column values, or their combination with `and`, `or`, and `not`. */
682
+ /** Filter of `where`: a Boolean expression, a query of one Boolean value, such as of `exists`, an object of column values, or their combination with `and`, `or`, and `not`. */
662
683
  type WhereCondition<T extends AnyTable> = ConditionOperand<WhereValues<T>>;
663
- /** Argument of `where`: a condition, or a callback that receives the columns of the query and returns one. */
664
- type WhereFilter<T extends AnyTable> = WhereCondition<T> | ((columns: ColumnRefs<T>) => WhereCondition<T>);
684
+ /** Callback of `where` over table `T` with schema context `C`: it receives the columns and the queries of the relations of the table and returns a condition. */
685
+ type WhereCallback<T extends AnyTable, C extends SchemaContext = NoRelations> = (columns: ColumnRefs<T> & RelationRefs<C>) => WhereCondition<T>;
686
+ /** Argument of `where` of a query over table `T` with schema context `C`: a condition, or a callback that receives the columns and the relations of the query and returns one. */
687
+ type WhereFilter<T extends AnyTable, C extends SchemaContext = NoRelations> = WhereCondition<T> | WhereCallback<T, C>;
665
688
  /**
666
689
  * Defines a reusable condition of `where` for queries over a table, checking its objects of column values against the columns.
667
690
  *
668
691
  * The condition can be combined further with `and`, `or`, and `not`.
669
692
  */
670
- declare function defineFilter<T extends AnyTable>(table: TableOrQuery<T>, filter: NoInfer<WhereCondition<T>>): WhereCondition<T>;
693
+ declare function defineFilter<T extends AnyTable, C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, filter: NoInfer<WhereCondition<T>>): WhereCondition<T>;
671
694
  /**
672
695
  * Defines a reusable callback of `where` for queries over a table, checking its objects of column values against the columns.
673
696
  *
674
- * Another callback can call it with its columns.
697
+ * Defined with a query of a schema or a `Db`, such as `schema.form`, it receives the queries of the relations of the table in that schema, and applies to queries whose schema has them.
698
+ * Another callback of `where` can call it with the columns and the relations it receives.
675
699
  */
676
- declare function defineFilter<T extends AnyTable>(table: TableOrQuery<T>, filter: NoInfer<(columns: ColumnRefs<T>) => WhereCondition<T>>): (columns: ColumnRefs<T>) => WhereCondition<T>;
700
+ declare function defineFilter<T extends AnyTable, C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, filter: NoInfer<WhereCallback<T, C>>): WhereCallback<T, C>;
677
701
  /** Defines a reusable filter of `where` for queries over a table, either a condition or a callback. */
678
- declare function defineFilter<T extends AnyTable>(table: TableOrQuery<T>, filter: NoInfer<WhereFilter<T>>): WhereFilter<T>;
702
+ declare function defineFilter<T extends AnyTable, C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, filter: NoInfer<WhereFilter<T, C>>): WhereFilter<T, C>;
679
703
  /**
680
704
  * Values of the primary key of table `T` that `find` takes, in the order of its columns, or `never` where the type of `T` tells no primary key.
681
705
  *
@@ -703,26 +727,77 @@ type OrderColumns<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: O
703
727
  /** Argument of `orderBy` of a query over table `T`: a column key, sorted in ascending order, or columns with directions. */
704
728
  type OrderKey<T extends AnyTable> = (keyof T["columns"] & string) | OrderColumns<T>;
705
729
  declare const ordering: unique symbol;
706
- /** Expression with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
730
+ /** Expression or query of one value with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
707
731
  interface Ordering {
708
732
  readonly [ordering]: true;
709
733
  }
710
- /** Sort key returned by the callback of `orderBy`: an expression, sorted in ascending order, or an expression with a direction. */
711
- type OrderTerm = AnyExpression | Ordering;
734
+ /** Sort key returned by the callback of `orderBy`: an expression or a query of one value, such as of an aggregate of related records, sorted in ascending order, or one with a direction. */
735
+ type OrderTerm = AnyExpression | ScalarQuery | Ordering;
712
736
  /**
713
737
  * References of the callback of `orderBy` to the fields of records `R` selected by a query: their expressions by key.
714
738
  *
715
- * A field of a nested query, such as of nested rows or of an aggregate, is among them in types, but reading it throws.
739
+ * A field of nested rows or of a literal is among them in types, but reading it throws; a field of an aggregate or of `exists` sorts by its value.
716
740
  */
717
741
  type SelectedRefs<R> = { readonly [K in keyof R & string]: AnyExpression<R[K]>; };
718
742
  /** Sort keys returned by the callback of `orderBy`: one or an array of them. */
719
743
  type OrderTerms = OrderTerm | readonly OrderTerm[];
720
- /** Sorts by `expression` in ascending order, in the callback of `orderBy`. */
721
- declare function asc(expression: AnyExpression): Ordering;
722
- /** Sorts by `expression` in descending order, in the callback of `orderBy`. */
723
- declare function desc(expression: AnyExpression): Ordering;
724
- /** Sorts by `expression` in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
725
- declare function orderBy(expression: AnyExpression, direction: OrderDirection): Ordering;
744
+ /** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
745
+ declare function asc(value: AnyExpression | ScalarQuery): Ordering;
746
+ /** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
747
+ declare function desc(value: AnyExpression | ScalarQuery): Ordering;
748
+ /** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
749
+ declare function orderBy(value: AnyExpression | ScalarQuery, direction: OrderDirection): Ordering;
750
+ /**
751
+ * Field of a selection whose value is `T`, made by `literal`.
752
+ *
753
+ * It is not an expression: it has no SQL, so only a selection takes it.
754
+ */
755
+ declare class Literal<out T> {
756
+ /** Value of the field in every record, which the query returns as it is. */
757
+ readonly literal: T;
758
+ constructor(
759
+ /** Value of the field in every record, which the query returns as it is. */
760
+ literal: T);
761
+ /** Rejects the literal as an operand of an expression: a statement has no SQL of it. */
762
+ [operandNode](): never;
763
+ }
764
+ /**
765
+ * Creates a field of a selection with `value` in every record, without selecting anything in SQL: the query returns the value itself, not a copy of it, whatever it is.
766
+ *
767
+ * It lets a branch of a selection skip a column or a nested query, such as `withHint ? field.hint : literal(null)`.
768
+ * To use a value in SQL, such as in a condition, pass it through `param` instead.
769
+ */
770
+ declare function literal<T extends {} | null | undefined>(value: T): Literal<T>;
771
+ /** Expressions, nested queries, and literals selected under the keys of the result fields; a record has no symbol keys. */
772
+ interface Selection {
773
+ readonly [key: string]: TypedExpression | NestedQuery | Literal<unknown>;
774
+ readonly [key: symbol]: never;
775
+ }
776
+ /** Query whose rows a selection nests as the value of a field: a query of any state and kind, such as a query of a relation. */
777
+ type NestedQuery = QueryOf<SelectQueryState>;
778
+ /** Record of the values of the expressions, of the nested rows, and of the literals of a selection. */
779
+ type SelectionResult<S extends Selection> = { [K in keyof S]: FieldValue<S[K]>; };
780
+ /** Value of a selected field: of an expression, of the nested rows of a query as the result of executing it, or of a literal, for each member of a union of them. */
781
+ type FieldValue<V> = V extends NestedQuery ? QueryResult<V["types"]> : V extends Literal<infer T> ? T : ExpressionValue<V>;
782
+ /** Relations whose records the nested queries of a selection select. */
783
+ type SelectionUses<S extends Selection> = S[keyof S] extends (infer V) ? V extends NestedQuery ? V["types"]["uses"] : never : never;
784
+ /** Value of a selected expression. */
785
+ type ExpressionValue<E> = E extends AnyExpression<infer T> ? T : never;
786
+ /** Values that the type of an expression encodes, such as in place of its value. */
787
+ type ExpressionInput<E> = E extends AnyExpression<unknown, infer I> ? I : never;
788
+ declare const helperFields: unique symbol;
789
+ /** Marker of the input fields of a helper, carrying the keys selected by its callback. */
790
+ interface HelperFields<Keys extends PropertyKey = PropertyKey> {
791
+ readonly [helperFields]: Keys;
792
+ }
793
+ /** Records with `Fields` added or replaced, for each branch of either record type; `any` stays `any`. */
794
+ type MergeSelection<Previous, Fields> = Previous extends unknown ? Fields extends unknown ? MergeFields<RecordFields<Previous>, RecordFields<Fields>> & (IsAny<Previous> extends true ? Previous : unknown) : never : never;
795
+ /** Fields with numeric keys represented as the string keys used in result records. */
796
+ type RecordFields<Fields> = Fields extends unknown ? [Extract<keyof Fields, number>] extends [never] ? Fields : { [K in keyof Fields as K extends number ? `${K}` : K]: Fields[K]; } : never;
797
+ /** Merge of normalized fields, retaining the previous value when an optional replacement is absent. */
798
+ type MergeFields<Previous, Fields> = Simplify<{ [K in keyof Previous as K extends keyof Fields ? ({} extends Pick<Fields, K> ? K : never) : K]: K extends typeof helperFields // A branch selecting extra keys must not be reduced to one selecting fewer fields or none.
799
+ ? Previous[K] | keyof Fields : K extends keyof Fields // A decoder can return undefined, so it cannot be excluded as merely an absent property.
800
+ ? Previous[K] | Fields[K] : Previous[K]; } & { [K in keyof Fields as K extends keyof Previous ? ({} extends Pick<Fields, K> ? never : K) : K]: Fields[K]; }>;
726
801
  /** Value of column `K` of table `T` that an insert or an update sets: a value that its type encodes, `null` for a nullable column, or an expression of its values. */
727
802
  type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValues<T>[K] | AnyExpression<Selectable<T>[K]>;
728
803
  /** Key of a column of table `T` that an insert may omit, which gets its default: one that the database gives a value, as `hasDefault` marks it, or a nullable one, whose default is `NULL` unless the database declares another. */
@@ -749,6 +824,47 @@ type FoundState<S extends SelectQueryState> = ChangeState<S, {
749
824
  }>;
750
825
  /** Query of state `S`, bound or unbound. */
751
826
  type QueryOf<S extends SelectQueryState> = SelectQuery<S, SelectQueryKind>;
827
+ declare const scalarValue: unique symbol;
828
+ /** Value of a query of state `S` in an expression: its value, or `NULL` without its row unless the query always has it. */
829
+ type ScalarValue<S extends SelectQueryState> = S["aggregate"] extends true ? S["result"] : S["guaranteed"] extends true ? S["result"] : S["result"] | null;
830
+ /**
831
+ * Query of one value of a table, such as of `get`, of an aggregate, or of `exists`, which an expression takes as a scalar subquery of its value, or as `EXISTS` of the rows of a query of `exists`.
832
+ *
833
+ * `T` is its value there: without its row, a query of `get` is `NULL`, unless a required relation guarantees the row, such as of `field.form`.
834
+ */
835
+ interface ScalarQuery<T = unknown> {
836
+ /** Value of the query in an expression, from which an expression infers `T`. */
837
+ readonly [scalarValue]: T;
838
+ readonly types: ScalarQueryState;
839
+ readonly exists: unknown;
840
+ }
841
+ /** Value of query `Q` of one value in an expression. */
842
+ type ScalarQueryValue<Q extends ScalarQuery> = Q[typeof scalarValue];
843
+ /** State of a query of one value, which an expression takes. */
844
+ interface ScalarQueryState extends SelectQueryState {
845
+ readonly rows: "one" | "optional";
846
+ readonly value: true;
847
+ }
848
+ /** State of a query of one value with the type of its value, whose expression `expr` gives. */
849
+ interface ExpressionQueryState extends ScalarQueryState {
850
+ readonly valueType: QueryValueType;
851
+ }
852
+ /** Query of one value of a table with the type of its value, such as of `get` or of an aggregate, which gives the expression of a function the decoding and the operators of its value. */
853
+ interface TypedScalarQuery extends ScalarQuery {
854
+ readonly types: ExpressionQueryState;
855
+ }
856
+ /** Query of values of a table of any rows, such as of `pluck`, whose value is `T`, which `in` takes as a subquery of its values. */
857
+ interface ValuesQuery<T = unknown> {
858
+ readonly types: ValuesQueryState<T>;
859
+ readonly exists: unknown;
860
+ }
861
+ /** Value of query `Q` of values, of each of its rows. */
862
+ type ValuesQueryValue<Q extends ValuesQuery> = Q["types"]["result"];
863
+ /** State of a query of values whose value is `T`. */
864
+ interface ValuesQueryState<T> extends SelectQueryState {
865
+ readonly result: T;
866
+ readonly value: true;
867
+ }
752
868
  /** State of a query whose rows are records, which `select` and `clearSelect` change. */
753
869
  type RecordQueryState$1 = SelectQueryState & {
754
870
  readonly value: false;
@@ -757,25 +873,47 @@ type RecordQueryState$1 = SelectQueryState & {
757
873
  type UnguaranteedQueryState = SelectQueryState & {
758
874
  readonly guaranteed: false;
759
875
  };
760
- /** State of a query whose rows are values, made by `get`, `pluck`, or an aggregate method, such as `count`. */
876
+ /** State of a query whose rows are values, made by `get`, `pluck`, an aggregate method, such as `count`, or `exists`. */
761
877
  type ValueQueryState = SelectQueryState & {
762
878
  readonly value: true;
763
879
  };
764
- /** State of a query not made by an aggregate method, which `get`, `pluck`, and the aggregate methods apply to. */
880
+ /** State of a query of values with the values that the type of its value encodes, which `coalesce` takes; it narrows nothing else, so that a call compares no operators. */
881
+ type CoalesceQueryState = ValueQueryState & {
882
+ readonly valueType: {
883
+ readonly input: unknown;
884
+ };
885
+ };
886
+ /** State of a query not made by an aggregate method or `exists`, which `get`, `pluck`, the aggregate methods, and `exists` apply to. */
765
887
  type UnaggregatedQueryState = SelectQueryState & {
766
888
  readonly aggregate: false;
767
889
  };
768
- /** State of a query of the value `V` of an aggregate over the rows of a query of state `S`, which always returns one row, accepting values `I` in place of its value. */
769
- type AggregateState<S extends SelectQueryState, V, I> = ChangeState<S, {
890
+ /** Type of the value of a query of column `K` of table `T`. */
891
+ type ColumnValueType<T extends AnyTable, K extends keyof T["columns"]> = {
892
+ readonly input: ColumnValues<T>[K];
893
+ readonly operators: ColumnOperators<T, K>;
894
+ };
895
+ /** Type of the value of a query of expression `E`. */
896
+ type ExpressionValueType<E extends TypedExpression> = {
897
+ readonly input: ExpressionInput<E>;
898
+ readonly operators: ExpressionOperators<E>;
899
+ };
900
+ /** State of a query of the value `V` of type `Type` of an aggregate or of `exists` over the rows of a query of state `S`, which always returns one row. */
901
+ type AggregateState<S extends SelectQueryState, V, Type extends QueryValueType> = ChangeState<S, {
770
902
  result: V;
771
- input: I;
903
+ valueType: Type;
772
904
  rows: "one";
773
905
  value: true;
774
906
  guaranteed: false;
775
907
  aggregate: true;
776
908
  }>;
909
+ /** State of a query of the number of rows or of values among the rows of a query of state `S`. */
910
+ type CountState<S extends SelectQueryState> = AggregateState<S, number, CountValueType>;
911
+ /** State of a query of an aggregate of the values of column `K` of the rows of a query of state `S`, `NULL` without values other than `NULL`. */
912
+ type ColumnAggregateState<S extends SelectQueryState, K extends keyof S["table"]["columns"]> = AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValueType<S["table"], K>>;
913
+ /** State of a query of an aggregate of the values of expression `E` over the rows of a query of state `S`, `NULL` without values other than `NULL`. */
914
+ type ExpressionAggregateState<S extends SelectQueryState, E extends TypedExpression> = AggregateState<S, ExpressionValue<E> | null, ExpressionValueType<E>>;
777
915
  /** Value `V` of a query of values whose `NULL` `coalesce` replaces with fallback `F`. */
778
- type CoalescedValue<V, F> = Exclude<V, null> | (F extends AnyExpression<infer T> ? Extract<T, null> : never);
916
+ type CoalescedValue<V, F> = Exclude<V, null> | Extract<OperandValue<F>, null>;
779
917
  /** State of a query of many rows, which `limit` and `offset` apply to. */
780
918
  type ManyRowsQueryState = SelectQueryState & {
781
919
  readonly rows: "many";
@@ -801,6 +939,8 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
801
939
  /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
802
940
  readonly context: QueryContext;
803
941
  readonly types: S;
942
+ /** Value of the query in an expression, for types only. */
943
+ readonly [scalarValue]: ScalarValue<S>;
804
944
  /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
805
945
  readonly db: QueryDb<Kind>;
806
946
  /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
@@ -808,14 +948,14 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
808
948
  constructor(table: S["table"], node: QueryNode,
809
949
  /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
810
950
  context: QueryContext, db?: AnyDb);
811
- /** Adds a filter combined with `AND` with the previous ones. */
812
- where<Q extends QueryOf<UnguaranteedQueryState>>(this: Q, filter: WhereFilter<Q["types"]["table"]>): Q;
951
+ /** Adds a filter combined with `AND` with the previous ones; a callback receives the columns and the queries of the relations of the table. */
952
+ where<Q extends QueryOf<UnguaranteedQueryState>>(this: Q, filter: WhereFilter<Q["types"]["table"], Q["types"]["schema"]>): Q;
813
953
  /**
814
- * Adds a filter combined with `AND` with the previous ones.
954
+ * Adds a filter combined with `AND` with the previous ones; a callback receives the columns and the queries of the relations of the table.
815
955
  *
816
956
  * A query of the record of a required relation, such as `field.form`, resolves to `null` without a record that passes the filter, or to `undefined` after `get` or `pluck`.
817
957
  */
818
- where<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: WhereFilter<S["table"]>): SelectQuery<FilteredState<S>, Kind>;
958
+ where<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: WhereFilter<S["table"], S["schema"]>): SelectQuery<FilteredState<S>, Kind>;
819
959
  /** Selects all columns of the table, replacing fields under their keys. */
820
960
  select<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
821
961
  result: MergeSelection<S["result"], Selectable<S["table"]>>;
@@ -871,7 +1011,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
871
1011
  */
872
1012
  get<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ChangeState<S, {
873
1013
  result: Selectable<S["table"]>[K];
874
- input: ColumnValues<S["table"]>[K];
1014
+ valueType: ColumnValueType<S["table"], K>;
875
1015
  rows: OneValueRows<S["rows"]>;
876
1016
  value: true;
877
1017
  }>, Kind>;
@@ -884,7 +1024,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
884
1024
  */
885
1025
  get<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ChangeState<S, {
886
1026
  result: ExpressionValue<E>;
887
- input: ExpressionInput<E>;
1027
+ valueType: ExpressionValueType<E>;
888
1028
  rows: OneValueRows<S["rows"]>;
889
1029
  value: true;
890
1030
  }>, Kind>;
@@ -895,7 +1035,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
895
1035
  */
896
1036
  pluck<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ChangeState<S, {
897
1037
  result: Selectable<S["table"]>[K];
898
- input: ColumnValues<S["table"]>[K];
1038
+ valueType: ColumnValueType<S["table"], K>;
899
1039
  rows: ValueRows<S["rows"]>;
900
1040
  value: true;
901
1041
  }>, Kind>;
@@ -906,7 +1046,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
906
1046
  */
907
1047
  pluck<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ChangeState<S, {
908
1048
  result: ExpressionValue<E>;
909
- input: ExpressionInput<E>;
1049
+ valueType: ExpressionValueType<E>;
910
1050
  rows: ValueRows<S["rows"]>;
911
1051
  value: true;
912
1052
  }>, Kind>;
@@ -915,65 +1055,79 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
915
1055
  *
916
1056
  * It keeps the filters and ignores the order; with `limit` or `offset`, it counts the rows of that page.
917
1057
  */
918
- count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<AggregateState<S, number, number>, Kind>;
1058
+ count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<CountState<S>, Kind>;
919
1059
  /** Replaces the selected fields with the number of the values of the column other than `NULL` among the rows of the query and returns it instead of the rows. */
920
- count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, number, number>, Kind>;
1060
+ count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<CountState<S>, Kind>;
921
1061
  /** Replaces the selected fields with the number of the values other than `NULL` of the expression returned by `callback` among the rows of the query and returns it instead of the rows. */
922
- count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, number, number>, Kind>;
1062
+ count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<CountState<S>, Kind>;
923
1063
  /** Replaces the selected fields with the number of the distinct values of the column other than `NULL` among the rows of the query and returns it instead of the rows. */
924
- countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, number, number>, Kind>;
1064
+ countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<CountState<S>, Kind>;
925
1065
  /** Replaces the selected fields with the number of the distinct values other than `NULL` of the expression returned by `callback` among the rows of the query and returns it instead of the rows. */
926
- countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, number, number>, Kind>;
1066
+ countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<CountState<S>, Kind>;
927
1067
  /** Replaces the selected fields with the smallest value of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
928
- min<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
1068
+ min<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ColumnAggregateState<S, K>, Kind>;
929
1069
  /** Replaces the selected fields with the smallest value of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
930
- min<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
1070
+ min<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ExpressionAggregateState<S, E>, Kind>;
931
1071
  /** Replaces the selected fields with the largest value of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
932
- max<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
1072
+ max<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ColumnAggregateState<S, K>, Kind>;
933
1073
  /** Replaces the selected fields with the largest value of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
934
- max<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
1074
+ max<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ExpressionAggregateState<S, E>, Kind>;
935
1075
  /** Replaces the selected fields with the sum of the values of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
936
- sum<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
1076
+ sum<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ColumnAggregateState<S, K>, Kind>;
937
1077
  /** Replaces the selected fields with the sum of the values of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
938
- sum<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
1078
+ sum<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ExpressionAggregateState<S, E>, Kind>;
939
1079
  /** Replaces the selected fields with the average of the values of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`; for `bigint` values, average an expression of a type that can represent fractional values. */
940
- avg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
1080
+ avg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ColumnAggregateState<S, K>, Kind>;
941
1081
  /** Replaces the selected fields with the average of the values of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`; for `bigint` values, average an expression of a type that can represent fractional values. */
942
- avg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
1082
+ avg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ExpressionAggregateState<S, E>, Kind>;
943
1083
  /** Replaces the selected fields with whether every value of the Boolean column other than `NULL` among the rows of the query is true and returns it instead of the rows, or `null` without such values. */
944
- every<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
1084
+ every<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ColumnAggregateState<S, K>, Kind>;
945
1085
  /** Replaces the selected fields with whether every value other than `NULL` of the Boolean expression returned by `callback` among the rows of the query is true and returns it instead of the rows, or `null` without such values. */
946
- every<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
1086
+ every<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ExpressionAggregateState<S, E>, Kind>;
947
1087
  /** Replaces the selected fields with whether any value of the Boolean column among the rows of the query is true and returns it instead of the rows, or `null` without values other than `NULL`. */
948
- some<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
1088
+ some<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ColumnAggregateState<S, K>, Kind>;
949
1089
  /** Replaces the selected fields with whether any value of the Boolean expression returned by `callback` among the rows of the query is true and returns it instead of the rows, or `null` without values other than `NULL`. */
950
- some<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
1090
+ some<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ExpressionAggregateState<S, E>, Kind>;
951
1091
  /** Replaces the selected fields with the values of the text column other than `NULL` among the rows of the query, joined with `delimiter` in the order of the query, and returns them instead of the rows, or `null` without such values. */
952
- stringAgg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K, delimiter: string): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
1092
+ stringAgg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K, delimiter: string): SelectQuery<ColumnAggregateState<S, K>, Kind>;
953
1093
  /** Replaces the selected fields with the values other than `NULL` of the text expression returned by `callback` among the rows of the query, joined with `delimiter` in the order of the query, and returns them instead of the rows, or `null` without such values. */
954
- stringAgg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E, delimiter: string): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
1094
+ stringAgg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E, delimiter: string): SelectQuery<ExpressionAggregateState<S, E>, Kind>;
1095
+ /**
1096
+ * Replaces the selected fields with whether the query has a row and returns it instead of the rows, such as to filter by related records in `where`.
1097
+ *
1098
+ * It keeps the filters, the limit, and the offset, and ignores the order.
1099
+ */
1100
+ exists<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<AggregateState<S, boolean, ExistsValueType>, Kind>;
955
1101
  /**
956
1102
  * Replaces a `NULL` value of a query of values, such as one made by `get`, `pluck`, or an aggregate, with `fallback`, such as `0` for a sum without rows.
957
1103
  *
958
- * `fallback` is a value that the type of the value accepts or an expression of its values, such as a column of the row of a parent query.
1104
+ * `fallback` is a value that the type of the value accepts, an expression of its values, such as a column of the row of a parent query, or a query of one such value.
959
1105
  * A missing row stays missing: an optional query still resolves to `undefined` without a row.
960
1106
  */
961
- coalesce<S extends ValueQueryState, Kind extends SelectQueryKind, F extends Operand<S["result"], S["input"]>>(this: SelectQuery<S, Kind>, fallback: F): SelectQuery<ChangeState<S, {
1107
+ coalesce<S extends CoalesceQueryState, Kind extends SelectQueryKind, F extends Operand<S["result"], S["valueType"]["input"]>>(this: SelectQuery<S, Kind>, fallback: F): SelectQuery<ChangeState<S, {
962
1108
  result: CoalescedValue<S["result"], F>;
963
1109
  }>, Kind>;
1110
+ /**
1111
+ * Returns an expression of the value of a query of one value, such as of `get` or of an aggregate, with the operators of its type, such as `form.fields.count().expr().gt(3)`.
1112
+ *
1113
+ * Without a row, the expression is `NULL`, and the query does not reject.
1114
+ */
1115
+ expr<Q extends QueryOf<ExpressionQueryState>>(this: Q): Expression<ScalarQueryValue<Q>, Q["types"]["valueType"]["operators"], Q["types"]["valueType"]["input"]>;
964
1116
  /**
965
1117
  * Sorts the rows by the sort keys returned by `callback`, after the sort keys of earlier calls.
966
1118
  *
967
- * `callback` receives the columns and the fields selected so far, and returns an expression, sorted in ascending order, `asc`, `desc`, or `orderBy` of an expression, or an array of them.
968
- * A selected field sorts by the value of the field, also when it changes from row to row, such as `random()`.
1119
+ * `callback` receives the columns with the queries of the relations of the table, and the fields selected so far.
1120
+ * It returns an expression or a query of one value, such as of an aggregate of related records, sorted in ascending order, `asc`, `desc`, or `orderBy` of one, or an array of them.
1121
+ * A selected field sorts by the value of the field, also when it changes from row to row, such as `random()`; a field of nested rows cannot be sorted by.
969
1122
  */
970
- orderBy<Q extends QueryOf<RecordQueryState$1>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]>, selected: SelectedRefs<Q["types"]["result"]>) => OrderTerms): Q;
1123
+ orderBy<Q extends QueryOf<RecordQueryState$1>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, selected: SelectedRefs<Q["types"]["result"]>) => OrderTerms): Q;
971
1124
  /**
972
1125
  * Sorts the values of a query made by `get` or `pluck` by the sort keys returned by `callback`, after the sort keys of earlier calls.
973
1126
  *
974
- * `callback` receives the columns and the expression of the value, and returns an expression, sorted in ascending order, `asc`, `desc`, or `orderBy` of an expression, or an array of them.
1127
+ * `callback` receives the columns with the queries of the relations of the table, and the expression of the value.
1128
+ * It returns an expression or a query of one value, sorted in ascending order, `asc`, `desc`, or `orderBy` of one, or an array of them.
975
1129
  */
976
- orderBy<Q extends QueryOf<ValueQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]>, value: AnyExpression<Q["types"]["result"]>) => OrderTerms): Q;
1130
+ orderBy<Q extends QueryOf<ValueQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, value: AnyExpression<Q["types"]["result"]>) => OrderTerms): Q;
977
1131
  /** Sorts the rows by the listed columns in ascending order, or in the directions of objects of columns, after the sort keys of earlier calls. */
978
1132
  orderBy<Q extends AnySelectQuery>(this: Q, ...keys: OrderKey<Q["types"]["table"]>[]): Q;
979
1133
  /** Returns at most `count` rows of a query of many rows, replacing an earlier limit. */
@@ -1045,6 +1199,18 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1045
1199
  * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1046
1200
  */
1047
1201
  toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1202
+ /**
1203
+ * Returns the node of the query as an operand of an expression, which lowering replaces with a scalar subquery of its value, or with `EXISTS` of its rows for a query of `exists`.
1204
+ *
1205
+ * It rejects a query of records or of rows `many`, which `ScalarQuery` rejects in types.
1206
+ */
1207
+ [operandNode](): ExpressionNode;
1208
+ /**
1209
+ * Returns the node of the query as the values of `in`, which lowering replaces with its statement.
1210
+ *
1211
+ * It rejects a query of records, which `ValuesQuery` rejects in types.
1212
+ */
1213
+ [valuesQueryNode](): NestedQueryNode;
1048
1214
  /** Creates a query of the same kind and `Db` with the node changes applied. */
1049
1215
  private derive;
1050
1216
  /**
@@ -1053,7 +1219,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1053
1219
  * It adds the changes of `take` to `changes`, which must leave the limit as it is.
1054
1220
  */
1055
1221
  private deriveTaken;
1056
- /** Creates the query of the value of `projection`, an aggregate over the rows of this query, which always returns one row. */
1222
+ /** Creates the query of the value of `projection`, of an aggregate or of `exists` over the rows of this query, which always returns one row. */
1057
1223
  private deriveAggregate;
1058
1224
  /** Creates the query of the aggregate of `method` over `arg`, a column key or a callback that receives the columns and returns an expression; `delimiter` is the delimiter of `stringAgg`. */
1059
1225
  private aggregateBy;
@@ -1065,7 +1231,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1065
1231
  private changeOneRow;
1066
1232
  /** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
1067
1233
  private rejectValue;
1068
- /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method. */
1234
+ /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method or `exists`. */
1069
1235
  private rejectAggregate;
1070
1236
  }
1071
1237
  /** Select query bound to a `Db`, executed by awaiting it; every method returns a query bound to the same `Db`. */
@@ -1078,36 +1244,34 @@ type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
1078
1244
  type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
1079
1245
  /** Starts a query over a new occurrence of the table. */
1080
1246
  declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T>>;
1081
- /** Expressions and nested queries selected under the keys of the result fields; a record has no symbol keys. */
1082
- interface Selection {
1083
- readonly [key: string]: TypedExpression | NestedQuery;
1084
- readonly [key: symbol]: never;
1247
+ /** Runtime mark of the operators of `equalityOperators`, which tell that a type has SQL `=`. */
1248
+ declare const equalityBrand: unique symbol;
1249
+ /** Generic operator of `equalityOperators`, which gives the type it is added to SQL `=`. */
1250
+ interface EqualityOperator<S extends OperatorSignature> extends GenericOperator<S> {
1251
+ readonly [equalityBrand]: true;
1085
1252
  }
1086
- /** Query whose rows a selection nests as the value of a field: a query of any state and kind, such as a query of a relation. */
1087
- type NestedQuery = QueryOf<SelectQueryState>;
1088
- /** Record of the values of the expressions and of the nested rows of a selection. */
1089
- type SelectionResult<S extends Selection> = { [K in keyof S]: FieldValue<S[K]>; };
1090
- /** Value of a selected field: of an expression, or of the nested rows of a query as the result of executing it, for each member of a union of them. */
1091
- type FieldValue<V> = V extends NestedQuery ? QueryResult<V["types"]> : ExpressionValue<V>;
1092
- /** Relations whose records the nested queries of a selection select. */
1093
- type SelectionUses<S extends Selection> = S[keyof S] extends (infer V) ? V extends NestedQuery ? V["types"]["uses"] : never : never;
1094
- /** Value of a selected expression. */
1095
- type ExpressionValue<E> = E extends AnyExpression<infer T> ? T : never;
1096
- /** Values that the type of an expression encodes, such as in place of its value. */
1097
- type ExpressionInput<E> = E extends AnyExpression<unknown, infer I> ? I : never;
1098
- declare const helperFields: unique symbol;
1099
- /** Marker of the input fields of a helper, carrying the keys selected by its callback. */
1100
- interface HelperFields<Keys extends PropertyKey = PropertyKey> {
1101
- readonly [helperFields]: Keys;
1253
+ /** Key of the method of a query of a table that returns its node as the values of `in`, or rejects a query of records. */
1254
+ declare const valuesQueryNode: unique symbol;
1255
+ /** Signature of `in`: membership in a list of operands of the expression type, or in the values of a query, such as of `pluck`; an empty list or query yields `FALSE`. */
1256
+ interface InSignature extends OperatorSignature {
1257
+ readonly method: <const L extends readonly Operand<this["T"], this["I"]>[] | ValuesQuery<NonNullable<this["T"]> | null>>(list: L) => Expression<L extends readonly unknown[] ? L extends readonly [] ? boolean : BooleanResult<this["T"] | OperandValue<L[number]>> : BooleanResult<this["T"] | (L extends ValuesQuery ? ValuesQueryValue<L> : never)>>;
1102
1258
  }
1103
- /** Records with `Fields` added or replaced, for each branch of either record type; `any` stays `any`. */
1104
- type MergeSelection<Previous, Fields> = Previous extends unknown ? Fields extends unknown ? MergeFields<RecordFields<Previous>, RecordFields<Fields>> & (IsAny<Previous> extends true ? Previous : unknown) : never : never;
1105
- /** Fields with numeric keys represented as the string keys used in result records. */
1106
- type RecordFields<Fields> = Fields extends unknown ? [Extract<keyof Fields, number>] extends [never] ? Fields : { [K in keyof Fields as K extends number ? `${K}` : K]: Fields[K]; } : never;
1107
- /** Merge of normalized fields, retaining the previous value when an optional replacement is absent. */
1108
- type MergeFields<Previous, Fields> = Simplify<{ [K in keyof Previous as K extends keyof Fields ? ({} extends Pick<Fields, K> ? K : never) : K]: K extends typeof helperFields // A branch selecting extra keys must not be reduced to one selecting fewer fields or none.
1109
- ? Previous[K] | keyof Fields : K extends keyof Fields // A decoder can return undefined, so it cannot be excluded as merely an absent property.
1110
- ? Previous[K] | Fields[K] : Previous[K]; } & { [K in keyof Fields as K extends keyof Previous ? ({} extends Pick<Fields, K> ? never : K) : K]: Fields[K]; }>;
1259
+ /** Operators of `equalityOperators`. */
1260
+ type EqualityOperators = {
1261
+ eq: EqualityOperator<ComparisonSignature>;
1262
+ ne: EqualityOperator<ComparisonSignature>;
1263
+ in: EqualityOperator<InSignature>;
1264
+ };
1265
+ /** Tells whether operators `O` include an operator of `equalityOperators`, so that their type has SQL `=`. */
1266
+ type HasEquality<O> = true extends { [K in keyof O]: O[K] extends {
1267
+ readonly [equalityBrand]: true;
1268
+ } ? true : false; }[keyof O] ? true : false;
1269
+ /**
1270
+ * Operators of SQL equality: `eq`, `ne`, and `in`; `orderingOperators` include them.
1271
+ *
1272
+ * A type has SQL `=` only with these operators, so that an array of it has them too; another operator named `eq` does not give it `=`.
1273
+ */
1274
+ declare const equalityOperators: EqualityOperators;
1111
1275
  /** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
1112
1276
  interface RecordQueryState<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
1113
1277
  readonly result: R;
@@ -1115,10 +1279,10 @@ interface RecordQueryState<R = unknown, U extends UsedRelation = UsedRelation> e
1115
1279
  readonly value: false;
1116
1280
  readonly uses: U;
1117
1281
  }
1118
- /** State of the query of `$select` of `Sel`: the record of the values of its expressions and the results of its queries. */
1282
+ /** State of the query of `$select` of `Sel`: the record of the values of its expressions and of its literals and the results of its queries. */
1119
1283
  type SelectionState<Sel extends Selection> = RecordQueryState<MergeSelection<EmptyRecord, SelectionResult<Sel>>, SelectionUses<Sel>>;
1120
1284
  /**
1121
- * Immutable query of `$select` of state `S`, unbound or bound to a `Db`: one record whose fields are the values of expressions and the results of independent queries, selected in one statement.
1285
+ * Immutable query of `$select` of state `S`, unbound or bound to a `Db`: one record whose fields are the values of expressions and of literals and the results of independent queries, selected in one statement.
1122
1286
  *
1123
1287
  * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
1124
1288
  * A bound query executes on its `Db` when awaited.
@@ -1137,6 +1301,8 @@ declare class RecordQuery<out S extends RecordQueryState, out Kind extends Selec
1137
1301
  * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1138
1302
  */
1139
1303
  toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1304
+ /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
1305
+ [operandNode](): never;
1140
1306
  }
1141
1307
  /** Query of `$select` of any state and kind. */
1142
1308
  type AnyRecordQuery = RecordQuery<any, SelectQueryKind>;
@@ -1170,7 +1336,7 @@ interface SchemaMembers<T extends Tables, R extends SchemaRelations> extends Sch
1170
1336
  */
1171
1337
  $relations<S extends AnySchema, D extends RelationDeclarations<S["$tables"]>>(this: S, relations: D & CheckDeclarations<S["$tables"], D>): Schema<S["$tables"], MergeRelations<S[typeof schemaRelations] & DeclaredRelations<S["$tables"], D>>>;
1172
1338
  /**
1173
- * Starts an unbound query of one record whose fields are the values of the expressions and the results of the queries of `selection`, selected in one statement.
1339
+ * Starts an unbound query of one record whose fields are the values of the expressions and of the literals and the results of the queries of `selection`, selected in one statement.
1174
1340
  *
1175
1341
  * The value of the field of a query is the result it gives when executed, such as an array of records or one value.
1176
1342
  */
@@ -1456,6 +1622,8 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
1456
1622
  * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1457
1623
  */
1458
1624
  toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1625
+ /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
1626
+ [operandNode](): never;
1459
1627
  /** Creates a mutation of the same kind and `Db` with the node changes applied. */
1460
1628
  private derive;
1461
1629
  /** Creates the mutation that returns the value of `arg` of `method`, a column key or a callback that receives the columns and returns an expression, of each changed row. */
@@ -1580,6 +1748,8 @@ declare class SqlQuery<out S extends SqlQueryState> {
1580
1748
  nullable<S extends OneRecordSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "nullable">>;
1581
1749
  /** Compiles the query into SQL text and parameters, as its `Db` executes it. */
1582
1750
  toSQL(): SqlStatement;
1751
+ /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
1752
+ [operandNode](): never;
1583
1753
  /** Creates a query of the same `Db` with the node changes applied. */
1584
1754
  private derive;
1585
1755
  /** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
@@ -1685,6 +1855,19 @@ declare class TransactionCoordinator {
1685
1855
  * A failed cleanup after an error rejects with a `SuppressedError` that keeps the original error in its `suppressed` chain.
1686
1856
  */
1687
1857
  transaction<T>(callback: () => Promise<T>, options?: TransactionOptions): Promise<T>;
1858
+ /**
1859
+ * Runs `callback` in the current transaction, or in a new transaction outside of one.
1860
+ *
1861
+ * Joining starts no savepoint, so a rejection of `callback` does not undo its changes.
1862
+ * It rejects without calling `callback` when the current level accepts no statements, as a nested transaction would.
1863
+ */
1864
+ ensureTransaction<T>(callback: () => Promise<T>): Promise<T>;
1865
+ /**
1866
+ * Tells whether the current async context runs in a transaction of `transaction`.
1867
+ *
1868
+ * A test transaction and the seed of a test fixture are not transactions, unless they run inside one, so that code under test behaves as in production.
1869
+ */
1870
+ isInTransaction(): boolean;
1688
1871
  /**
1689
1872
  * Runs `callback` in a transaction that always rolls back, on a coordinator created for tests.
1690
1873
  *
@@ -1755,6 +1938,22 @@ interface Database extends AsyncDisposable {
1755
1938
  * Inside an existing transaction, it starts a nested transaction.
1756
1939
  */
1757
1940
  transaction<T>(callback: () => Promise<T>, options?: TransactionOptions): Promise<T>;
1941
+ /**
1942
+ * Runs `callback` in the current transaction without a nested transaction, or in a new transaction outside of one.
1943
+ *
1944
+ * A rejection of a callback that joined a transaction does not undo its changes: the enclosing transaction commits them unless it fails too.
1945
+ * A test transaction is not a transaction to join: there, it starts a nested transaction where it starts a transaction in production.
1946
+ */
1947
+ ensureTransaction<T>(callback: () => Promise<T>): Promise<T>;
1948
+ /** Tells whether the code runs in a transaction, not counting test transactions, so that code under test sees what it sees in production. */
1949
+ isInTransaction(): boolean;
1950
+ /**
1951
+ * Takes the advisory lock of `key` until the transaction ends, waiting while another transaction holds it, such as to keep processes from running the same job at once.
1952
+ *
1953
+ * It rejects where `isInTransaction()` is `false`, since outside a transaction the lock would end with its statement.
1954
+ * A nested transaction that rolls back releases the locks it took.
1955
+ */
1956
+ lock(key: string): Promise<void>;
1758
1957
  /** Rolls back the open test fixtures and closes the connections of the driver once the running transactions end. */
1759
1958
  close(): Promise<void>;
1760
1959
  }
@@ -1822,7 +2021,7 @@ interface DbMethods<T extends Tables, R extends SchemaRelations> {
1822
2021
  */
1823
2022
  $execute<Q extends DbQuery<T, R>>(query: Q): Promise<QueryResult<Q["types"]>>;
1824
2023
  /**
1825
- * Starts a query of one record whose fields are the values of the expressions and the results of the queries of `selection`, selected in one statement when awaited.
2024
+ * Starts a query of one record whose fields are the values of the expressions and of the literals and the results of the queries of `selection`, selected in one statement when awaited.
1826
2025
  *
1827
2026
  * A query of `selection` is unbound or bound to this `Db`, and the value of its field is the result it gives when executed, such as an array of records or one value.
1828
2027
  */
@@ -1830,7 +2029,7 @@ interface DbMethods<T extends Tables, R extends SchemaRelations> {
1830
2029
  /**
1831
2030
  * Starts a query of the SQL statement of the template, which resolves to the number of the rows of its command tag when awaited, such as the rows that an `UPDATE` changes; `select`, `get`, and `pluck` return the fields of its rows instead.
1832
2031
  *
1833
- * Interpolated values become query parameters, `sql` fragments and expressions stay SQL, and a table of the `Db`, such as `db.form`, becomes its name, qualified by the PostgreSQL schema of the `Db`.
2032
+ * Interpolated values become query parameters, `sql` fragments and expressions stay SQL, a table of the `Db`, such as `db.form`, becomes its name, qualified by the PostgreSQL schema of the `Db`, and another query becomes a subquery, as in `sql`.
1834
2033
  */
1835
2034
  $query(strings: TemplateStringsArray, ...values: unknown[]): SqlQuery<InitialSqlQueryState>;
1836
2035
  /**
@@ -1842,7 +2041,7 @@ interface DbMethods<T extends Tables, R extends SchemaRelations> {
1842
2041
  /**
1843
2042
  * Executes the script of the template as `$script` of its text does.
1844
2043
  *
1845
- * It interpolates tables of the `Db`, such as `db.form`, and `sql` fragments without values; it rejects values, since a script has no parameters.
2044
+ * It interpolates tables of the `Db`, such as `db.form`, and queries and `sql` fragments without parameters; it rejects values, since a script has no parameters.
1846
2045
  */
1847
2046
  $script(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;
1848
2047
  /**
@@ -1851,6 +2050,22 @@ interface DbMethods<T extends Tables, R extends SchemaRelations> {
1851
2050
  * Inside an existing transaction, it starts a nested transaction.
1852
2051
  */
1853
2052
  $transaction<Result>(callback: () => Promise<Result>, options?: TransactionOptions): Promise<Result>;
2053
+ /**
2054
+ * Runs `callback` in the current transaction without a nested transaction, or in a new transaction of the database outside of one.
2055
+ *
2056
+ * A rejection of a callback that joined a transaction does not undo its changes: the enclosing transaction commits them unless it fails too.
2057
+ * A test transaction is not a transaction to join: there, it starts a nested transaction where it starts a transaction in production.
2058
+ */
2059
+ $ensureTransaction<Result>(callback: () => Promise<Result>): Promise<Result>;
2060
+ /** Tells whether the code runs in a transaction of the database, not counting test transactions, so that code under test sees what it sees in production. */
2061
+ $isInTransaction(): boolean;
2062
+ /**
2063
+ * Takes the advisory lock of `key` until the transaction of the database ends, waiting while another transaction holds it, such as to keep processes from running the same job at once.
2064
+ *
2065
+ * It rejects where `$isInTransaction()` is `false`, since outside a transaction the lock would end with its statement.
2066
+ * A nested transaction that rolls back releases the locks it took.
2067
+ */
2068
+ $lock(key: string): Promise<void>;
1854
2069
  }
1855
2070
  /**
1856
2071
  * `Db` of schema `S`, such as the type of a parameter of code shared by several schemas.
@@ -1927,6 +2142,19 @@ interface ValuesNode {
1927
2142
  readonly kind: "values";
1928
2143
  readonly values: Readonly<Record<string, unknown>>;
1929
2144
  }
2145
+ /**
2146
+ * Query of a table in an expression, such as of `exists` in a condition, which lowering replaces with the SQL of its value before compilation.
2147
+ *
2148
+ * A query interpolated into SQL text may be of records or of rows `many`, which lowering replaces with its statement.
2149
+ */
2150
+ interface NestedQueryNode {
2151
+ readonly kind: "nestedQuery";
2152
+ readonly query: QueryNode;
2153
+ /** `Db` that the query is bound to, which must be the `Db` that runs the statement. */
2154
+ readonly db: AnyDb | undefined;
2155
+ /** Selected field of an aggregate or of `exists` whose value the node is, in a reference of the callback of `orderBy`, by which lowering sorts by the projection of the field. */
2156
+ readonly field?: NestedSelectionNode;
2157
+ }
1930
2158
  interface ComparisonNode {
1931
2159
  readonly kind: "comparison";
1932
2160
  readonly operator: "=" | "<>" | "<" | "<=" | ">" | ">=" | "LIKE" | "ILIKE";
@@ -1939,6 +2167,13 @@ interface InNode {
1939
2167
  /** Never empty: an empty list is represented as a `FALSE` boolean node. */
1940
2168
  readonly list: readonly ExpressionNode[];
1941
2169
  }
2170
+ /** `IN` of the values of a query, such as of `pluck`, whatever its rows. */
2171
+ interface InQueryNode {
2172
+ readonly kind: "inQuery";
2173
+ readonly operand: ExpressionNode;
2174
+ /** Query of the values: a query in an expression, which lowering replaces with its statement of one projection. */
2175
+ readonly query: NestedQueryNode | SelectNode;
2176
+ }
1942
2177
  interface IsNullNode {
1943
2178
  readonly kind: "isNull";
1944
2179
  readonly operand: ExpressionNode;
@@ -1966,6 +2201,11 @@ interface ExistsNode {
1966
2201
  readonly kind: "exists";
1967
2202
  readonly query: SelectNode;
1968
2203
  }
2204
+ /** Subquery interpolated into SQL text: its query in parentheses, of any fields and rows, which the text reads, such as with `EXISTS` or in `FROM`. */
2205
+ interface TextSubqueryNode {
2206
+ readonly kind: "textSubquery";
2207
+ readonly query: SelectNode;
2208
+ }
1969
2209
  /** Call of an aggregate function over the rows of its query, with the order of its input rows. */
1970
2210
  interface AggregateNode {
1971
2211
  readonly kind: "aggregate";
@@ -1976,7 +2216,7 @@ interface AggregateNode {
1976
2216
  readonly arguments: readonly ExpressionNode[];
1977
2217
  readonly orderBy: readonly OrderNode[];
1978
2218
  }
1979
- type ExpressionNode = ColumnRefNode | ParamNode | CastNode | BooleanNode | AndNode | OrNode | NotNode | ValuesNode | ComparisonNode | InNode | IsNullNode | RawSqlNode | TableNameNode | SubqueryNode | ExistsNode | AggregateNode;
2219
+ type ExpressionNode = ColumnRefNode | ParamNode | CastNode | BooleanNode | AndNode | OrNode | NotNode | ValuesNode | NestedQueryNode | ComparisonNode | InNode | InQueryNode | IsNullNode | RawSqlNode | TableNameNode | SubqueryNode | ExistsNode | TextSubqueryNode | AggregateNode;
1980
2220
  /**
1981
2221
  * Filters of a query, kept apart so that composing one kind never changes the others.
1982
2222
  *
@@ -2025,6 +2265,8 @@ interface SelectNode<From extends SourceNode | undefined = SourceNode | undefine
2025
2265
  readonly offset: ExpressionNode | undefined;
2026
2266
  /** Required relation that guarantees the row of the query, such as `field.form`; see `ResultPlan`. */
2027
2267
  readonly guaranteedBy: string | undefined;
2268
+ /** Template of the records of a query with literals; see `ResultPlan`. */
2269
+ readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
2028
2270
  }
2029
2271
  /** Assignment of `SET` of an update: the value of the column under `key`. */
2030
2272
  interface AssignmentNode {
@@ -2039,6 +2281,8 @@ interface AssignmentNode {
2039
2281
  interface MutationParts<Field> extends ResultMode {
2040
2282
  readonly target: TableSourceNode;
2041
2283
  readonly returning: readonly Field[] | undefined;
2284
+ /** Template of the records of a mutation with literals; see `ResultPlan`. */
2285
+ readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
2042
2286
  }
2043
2287
  /** Insert statement of rows of `VALUES`. */
2044
2288
  interface InsertNode<Field = ProjectionNode> extends MutationParts<Field> {
@@ -2076,6 +2320,8 @@ interface TextStatementNode extends ResultMode {
2076
2320
  declare const valueType: unique symbol;
2077
2321
  declare const inputType: unique symbol;
2078
2322
  declare const typed: unique symbol;
2323
+ /** Key of the method of an expression and of every class of queries that returns its node as an operand of an expression, or rejects a query that cannot be one. */
2324
+ declare const operandNode: unique symbol;
2079
2325
  /** Expression of TypeScript type `T` accepting compared values of type `I`, whatever its operators. */
2080
2326
  interface AnyExpression<T = unknown, I = unknown> {
2081
2327
  readonly [valueType]: T;
@@ -2090,19 +2336,236 @@ type ExpressionWithOperators<T, O extends OperatorDefinitions, I> = AnyExpressio
2090
2336
  * It has `isNull` and the operators `O` of its type, which also decodes its values, so it can be selected.
2091
2337
  * The AST node behind it is internal.
2092
2338
  */
2093
- type Expression<T = unknown, O extends OperatorDefinitions = EqualityOperators, I = T> = ExpressionWithOperators<T, O, I> & TypedExpression<T>;
2339
+ type Expression<T = unknown, O extends OperatorDefinitions = EqualityOperators, I = T> = ExpressionWithOperators<T, O, I> & TypedExpression<T, O>;
2094
2340
  /**
2095
2341
  * Expression of TypeScript type `T` without a type, such as a fragment of `sql<T>`, with the operators of `equalityOperators`.
2096
2342
  *
2097
2343
  * Nothing decodes its values to `T`, so it cannot be selected.
2098
2344
  */
2099
2345
  type UntypedExpression<T = unknown> = ExpressionWithOperators<T, EqualityOperators, NoInfer<T>>;
2100
- /** Expression that has a type to decode its values, which `select`, `get`, and `pluck` require. */
2101
- type TypedExpression<T = unknown> = AnyExpression<T> & {
2102
- readonly [typed]: true;
2346
+ /** Expression that has a type to decode its values, which `select`, `get`, and `pluck` require, with the operators `O` of the type. */
2347
+ type TypedExpression<T = unknown, O extends OperatorDefinitions = any> = AnyExpression<T> & {
2348
+ readonly [typed]: O;
2103
2349
  };
2350
+ /** Operators of expression `E`. */
2351
+ type ExpressionOperators<E extends TypedExpression> = E[typeof typed];
2104
2352
  /** Operators of expressions of every type. */
2105
2353
  interface BaseOperators {
2106
2354
  isNull(): Expression<boolean>;
2107
2355
  }
2108
- export { many as $, BaseType as $n, Predicate as $t, SqlQuery as A, ColumnDefinitions as An, UpdateSet as At, Relation as B, defineTable as Bn, desc as Bt, createTestHelpers as C, ComparisonSignature as Cn, FilteredStateRows as Ct, DecodedFields as D, CompileOptions as Dn, from as Dt, AnySqlQuery as E, compare as En, TableOrQuery as Et, MutationQueryState as F, Selectable as Fn, OrderTerm as Ft, RelationKind as G, ResultRows as Gn, EqValue as Gt, RelationDeclarations as H, RequiredRelationError as Hn, KeyCheck as Ht, DeclaredRelations as I, Table as In, OrderTerms as It, SchemaRelations as J, DriverResult as Jn, WhereValues as Jt, RequiredMember as K, Connection as Kn, WhereCondition as Kt, MergeRelations as L, TableKeys as Ln, Ordering as Lt, AnyMutationQuery as M, ColumnShape as Mn, OrderColumns as Mt, InitialMutationState as N, ColumnValues as Nn, OrderDirection as Nt, FieldTypes as O, AnyTable as On, ColumnValue as Ot, MutationQuery as P, KeyColumns as Pn, OrderKey as Pt, UsedRelation as Q, AnyType as Qn, ConditionOperand as Qt, NoRelations as R, TableOptions as Rn, SelectedRefs as Rt, TestTransactionOptions as S, BooleanResult as Sn, ChangeState as St, SelectQueryKind as T, OperandValue as Tn, SelectQuery as Tt, RelationKey as U, ResultDecodeError as Un, NotAKey as Ut, RelationDeclaration as V, NotFoundError as Vn, orderBy as Vt, RelationKeys as W, ResultMode as Wn, PrimaryKeyValues as Wt, TableRelations as X, TransactionFailure as Xn, CombinedCondition as Xt, TableContext as Y, SqlStatement as Yn, defineFilter as Yt, UsableRelation as Z, createStatement as Zn, Condition as Zt, OpenedTestFixture as _, EqualityOperator as _n, GenericOperator as _r, Selection as _t, UntypedExpression as a, RelationRefs as an, TypeOutput as ar, SchemaTables as at, TestHelpers as b, InSignature as bn, defineGenericOperator as br, AnySelectQuery as bt, Db as c, OneValueRows as cn, AnyColumn as cr, AnyRecordQuery as ct, DbQueryState as d, ValueRows as dn, KeyKind as dr, SelectionState as dt, and as en, TextValue as er, one as et, Database as f, EmptyRecord as fn, ToColumn as fr, ExpressionInput as ft, TransactionCoordinator as g, SelectQueryState as gn, OperatorDefinitions as gr, NestedQuery as gt, createDatabase as h, QueryStateOf as hn, NoOperators as hr, MergeSelection as ht, TypedExpression as i, QueryContext as in, TypeOptions as ir, SchemaPartRelations as it, SqlQueryState as j, ColumnOperators as jn, UpdateValues as jt, InitialSqlQueryState as k, AnyTableKeys as kn, InsertValues as kt, DbMutationState as l, QueryResult as ln, Column as lr, RecordQuery as lt, TransactionOptions as m, QueryState as mn, MergeOperators as mr, HelperFields as mt, BaseOperators as n, or as nn, TypeInput as nr, Schema as nt, AnyDb as o, FilteredRows as on, TypeTransform as or, Tables as ot, DatabaseOptions as p, InitialQueryState as pn, BoundOperators as pr, ExpressionValue as pt, SchemaContext as q, Driver as qn, WhereFilter as qt, Expression as r, ColumnRefs as rn, TypeOperators as rr, SchemaPart as rt, BindOptions as s, OneRow as sn, defineType as sr, defineSchema as st, AnyExpression as t, not as tn, Type as tr, AnySchema as tt, DbOf as u, ResultByRows as un, ColumnAttributes as ur, RecordQueryState as ut, PendingTestFixture as v, EqualityOperators as vn, GenericOperatorImplementation as vr, SelectionResult as vt, AnyQuery as w, Operand as wn, ResultOf as wt, TestHooks as x, equalityOperators as xn, BoundSelectQuery as xt, TestFixture as y, HasEquality as yn, OperatorSignature as yr, SelectionUses as yt, OneRelationKeys as z, ToColumns as zn, asc as zt };
2356
+ /** Operators of ordered types: those of `equalityOperators`, and `lt`, `lte`, `gt`, and `gte` comparing with operands of the expression type. */
2357
+ declare const orderingOperators: {
2358
+ lt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2359
+ lte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2360
+ gt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2361
+ gte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2362
+ eq: EqualityOperator<ComparisonSignature>;
2363
+ ne: EqualityOperator<ComparisonSignature>;
2364
+ in: EqualityOperator<InSignature>;
2365
+ };
2366
+ /** Operators of the built-in types of numbers: those of `orderingOperators`. */
2367
+ type NumberTypeOperators = MergeOperators<NoOperators, typeof orderingOperators>;
2368
+ /** Signature of pattern matching: patterns stay strings even when the text values are transformed. */
2369
+ interface PatternSignature extends OperatorSignature {
2370
+ readonly method: <V extends Operand<string>>(pattern: V) => Expression<BooleanResult<this["T"] | OperandValue<V>>>;
2371
+ }
2372
+ /** Signature of `lower`, `upper`, and `trim`: a value of `text`, whatever the representation of the text values, and `NULL` when the text can be. */
2373
+ interface TextConversionSignature extends OperatorSignature {
2374
+ readonly method: () => Expression<string | (null extends this["T"] ? null : never), TextTypeOperators>;
2375
+ }
2376
+ /** Signature of `length`: the number of characters of the text, and `NULL` when the text can be. */
2377
+ interface TextLengthSignature extends OperatorSignature {
2378
+ readonly method: () => Expression<number | (null extends this["T"] ? null : never), NumberTypeOperators>;
2379
+ }
2380
+ /** Operators of `textOperators`. */
2381
+ type TextOperators = {
2382
+ like: GenericOperator<PatternSignature, AnyExpression<string | null>>;
2383
+ ilike: GenericOperator<PatternSignature, AnyExpression<string | null>>;
2384
+ lower: GenericOperator<TextConversionSignature, AnyExpression<string | null>>;
2385
+ upper: GenericOperator<TextConversionSignature, AnyExpression<string | null>>;
2386
+ trim: GenericOperator<TextConversionSignature, AnyExpression<string | null>>;
2387
+ length: GenericOperator<TextLengthSignature, AnyExpression<string | null>>;
2388
+ };
2389
+ /** Operators of the built-in text types: those of `orderingOperators` and `textOperators`. */
2390
+ type TextTypeOperators = MergeOperators<MergeOperators<NoOperators, typeof orderingOperators>, TextOperators>;
2391
+ /**
2392
+ * Operators of text types: pattern matching with `LIKE` and `ILIKE`, `lower` and `upper`, which convert the case of the text, `trim`, which removes spaces from both of its ends, and `length`, which counts its characters.
2393
+ *
2394
+ * A string pattern is sent as it is; `param(type, pattern)` encodes it with a type.
2395
+ */
2396
+ declare const textOperators: TextOperators;
2397
+ /** Condition that always holds, such as for a branch of `and` built in code: `and(check, isAdmin ? TRUE : other)`. */
2398
+ declare const TRUE: Expression<boolean>;
2399
+ /** Condition that never holds, such as for a branch of `or` built in code: `or(check, isAdmin ? other : FALSE)`. */
2400
+ declare const FALSE: Expression<boolean>;
2401
+ /** First operand of `coalesce`, `greatest`, and `least`: an expression with a type, or a query of one value, such as of an aggregate, whose type decodes the result and gives it its operators. */
2402
+ type TypedOperand = TypedExpression | TypedScalarQuery;
2403
+ /** Values that the type of the first operand `F` encodes. */
2404
+ type TypedOperandInput<F> = F extends TypedScalarQuery ? F["types"]["valueType"]["input"] : ExpressionInput<F>;
2405
+ /** Operators of the type of the first operand `F`. */
2406
+ type TypedOperandOperators<F> = F extends TypedScalarQuery ? F["types"]["valueType"]["operators"] : F extends TypedExpression ? ExpressionOperators<F> : never;
2407
+ /** Operand of `coalesce`, `greatest`, and `least` after the first operand `F`: a value that its type encodes, or an expression or a query of one value of its values. */
2408
+ type FollowingOperand<F> = Operand<OperandValue<F>, TypedOperandInput<F>>;
2409
+ /** `null` when every operand can be `NULL`: the first operand `F` and the following operands `R`. */
2410
+ type NullOfEveryOperand<F, R extends readonly unknown[]> = null extends OperandValue<F> ? number extends R["length"] ? null : { [K in keyof R]: null extends OperandValue<R[K]> ? never : true; }[number] extends never ? null : never : never;
2411
+ /** Result of a function of the first operand `F` and the following operands `R` that is `NULL` only when every operand is, whose operands all have the values of `F`. */
2412
+ type NullSkippingResult<F, R extends readonly unknown[]> = Expression<Exclude<OperandValue<F>, null> | NullOfEveryOperand<F, R>, TypedOperandOperators<F>, TypedOperandInput<F>>;
2413
+ /**
2414
+ * Returns the first of its operands other than `NULL`, such as `coalesce(field.hint, "")`, as an expression usable wherever a column is.
2415
+ *
2416
+ * `first` is an expression with a type or a query of one value; its type decodes the result and gives it its operators, and encodes plain values among `rest`.
2417
+ * A query without its row is `NULL` here, unlike with the method `coalesce` of a query, which keeps a missing row missing.
2418
+ */
2419
+ declare function coalesce<F extends TypedOperand, const R extends readonly FollowingOperand<F>[]>(first: F, ...rest: R): NullSkippingResult<F, R>;
2420
+ /**
2421
+ * Returns the largest of its operands, skipping `NULL`, which is the result only when every operand is `NULL`.
2422
+ *
2423
+ * `first` is an expression with a type or a query of one value; its type decodes the result and gives it its operators, and encodes plain values among `rest`.
2424
+ */
2425
+ declare function greatest<F extends TypedOperand, const R extends readonly FollowingOperand<F>[]>(first: F, ...rest: R): NullSkippingResult<F, R>;
2426
+ /**
2427
+ * Returns the smallest of its operands, skipping `NULL`, which is the result only when every operand is `NULL`.
2428
+ *
2429
+ * `first` is an expression with a type or a query of one value; its type decodes the result and gives it its operators, and encodes plain values among `rest`.
2430
+ */
2431
+ declare function least<F extends TypedOperand, const R extends readonly FollowingOperand<F>[]>(first: F, ...rest: R): NullSkippingResult<F, R>;
2432
+ /** Condition of a branch of `caseWhen`: a predicate, or a query of one Boolean value, such as of `exists`. */
2433
+ type CaseCondition = Predicate | ScalarQuery<boolean | null>;
2434
+ /** Value of a branch of `caseWhen` of a type of values `T` that encodes values `I`: an operand of the type, or a plain `null`. */
2435
+ type CaseValue<T, I> = Operand<T, I> | null;
2436
+ /** Branch of `caseWhen`: a condition and the value of the result when it holds. */
2437
+ type CaseBranch<T, I> = readonly [condition: CaseCondition, value: CaseValue<T, I>];
2438
+ /** Value of `caseWhen` of a type of values `T` whose branches and fallback have the values `V`, of which one gives the result. */
2439
+ type CaseResult<T, V> = Exclude<T, null> | Extract<OperandValue<V>, null>;
2440
+ /**
2441
+ * Returns the value of the first branch whose condition holds, as a SQL `CASE` expression, or `NULL` when none holds.
2442
+ *
2443
+ * `type` decodes the result and gives it its operators, and a plain value of a branch is cast to it, so that PostgreSQL does not take plain values for text.
2444
+ */
2445
+ declare function caseWhen<Output, Input, O extends OperatorDefinitions>(type: Type<Output, Input, O, any>, branches: NoInfer<readonly CaseBranch<Output, Input>[]>): Expression<Exclude<Output, null> | null, O, Input>;
2446
+ /**
2447
+ * Returns the value of the first branch whose condition holds, as a SQL `CASE` expression, or `otherwise` when none holds.
2448
+ *
2449
+ * `type` decodes the result and gives it its operators, and a plain value of a branch or of `otherwise` is cast to it, so that PostgreSQL does not take plain values for text.
2450
+ */
2451
+ declare function caseWhen<Output, Input, O extends OperatorDefinitions, const B extends readonly CaseBranch<Output, Input>[], const E extends CaseValue<Output, Input>>(type: Type<Output, Input, O, any>, branches: B, otherwise: E): Expression<CaseResult<Output, B[number][1] | E>, O, Input>;
2452
+ /**
2453
+ * State of the query that the callback of a helper of table `T` with schema context `C` receives: the fields of the query the helper is applied to, and all its rows.
2454
+ *
2455
+ * It is guaranteed, so that the state that the callback returns tells whether the callback ends the guarantee of the query the helper is applied to.
2456
+ */
2457
+ interface HelperState<T extends AnyTable, C extends SchemaContext> extends QueryStateOf<T, C> {
2458
+ readonly result: HelperFields<never>;
2459
+ readonly valueType: never;
2460
+ readonly rows: "many";
2461
+ readonly value: false;
2462
+ readonly uses: never;
2463
+ readonly guaranteed: true;
2464
+ readonly aggregate: false;
2465
+ }
2466
+ /**
2467
+ * Effect of a helper: the fields it selects, its rows mode on a query of many rows, `one` after `take` or `required` and `nullable` or `optional` after the method of the same name, the relations it selects records of, and whether it keeps the guarantee of the row of a query of a required relation.
2468
+ *
2469
+ * `reads` are the relations of the schema of the helper among them, which its callback may read from the references of the query it is applied to, and `key` is the key of its table there.
2470
+ */
2471
+ interface HelperEffect {
2472
+ readonly fields: object;
2473
+ readonly rows: ResultRows;
2474
+ readonly uses: UsedRelation;
2475
+ readonly reads: UsedRelation;
2476
+ readonly key: string;
2477
+ readonly guaranteed: boolean;
2478
+ }
2479
+ /** Effect of a helper whose callback returns a query of state `S`, for each state of a union. */
2480
+ type ReadEffect<S extends SelectQueryState> = S extends SelectQueryState ? {
2481
+ readonly fields: { [K in keyof S["result"] as K extends keyof HelperFields ? never : K]: S["result"][K]; };
2482
+ readonly rows: S["rows"];
2483
+ readonly uses: S["uses"];
2484
+ readonly reads: Extract<UsableRelation<S["schema"]["relations"]>, S["uses"]>;
2485
+ readonly key: S["schema"]["key"];
2486
+ readonly guaranteed: S["guaranteed"];
2487
+ } : never;
2488
+ /** Error of a helper that a query does not accept, or whose callback returns a query it does not accept. */
2489
+ interface HelperError<Message extends string> {
2490
+ readonly error: Message;
2491
+ }
2492
+ /** `unknown` when every result state retains the input marker and returns records, or the error. */
2493
+ type CheckResult<S extends SelectQueryState> = [S] extends [{
2494
+ readonly result: HelperFields;
2495
+ readonly value: false;
2496
+ }] ? unknown : HelperError<"A helper can filter, select fields, and take one row, but cannot clear the selection or use get, pluck, or aggregates">;
2497
+ /** State of a query over table `T` that accepts a helper of effect `E`. */
2498
+ type HelperInput<T extends AnyTable, E extends HelperEffect> = QueryStateOf<T, ReadsContext<E>> & ValueCheck<E>;
2499
+ /** Constraint of `value` of a query that accepts a helper of effect `E`. */
2500
+ type ValueCheck<E extends HelperEffect> = [E extends HelperEffect ? keyof E["fields"] : never] extends [never] ? [Extract<E["rows"], "nullable">] extends [never] ? unknown : RecordRows<"A helper cannot apply nullable to a query made by get, pluck, or an aggregate"> : RecordRows<"A helper cannot select fields on a query made by get, pluck, or an aggregate">;
2501
+ /** Constraint of a query whose rows are records, which a query of values fails with error `Message`. */
2502
+ interface RecordRows<Message extends string> {
2503
+ readonly value: false | HelperError<Message>;
2504
+ }
2505
+ /** Schema context of a query that has the relations of its schema that a helper of effect `E` may read. */
2506
+ type ReadsContext<E extends HelperEffect> = [E["reads"]] extends [never] ? SchemaContext : SchemaContext<{ readonly [K in E["reads"]["key"]]: { readonly [N in Extract<E["reads"], {
2507
+ readonly key: K;
2508
+ }>["name"]]: Extract<E["reads"], {
2509
+ readonly key: K;
2510
+ readonly name: N;
2511
+ }>["relation"]; }; }, E["key"]>;
2512
+ /** State of a query of state `S` after a helper of effect `E`. */
2513
+ type ApplyEffect<S extends SelectQueryState, E extends HelperEffect> = ChangeState<S, {
2514
+ result: [keyof E["fields"]] extends [never] ? S["result"] : MergeSelection<S["result"], E["fields"]>;
2515
+ rows: E["rows"] extends "many" ? EffectRows<S, E> : E["rows"] extends "one" ? OneRow<EffectRows<S, E>> : E["rows"];
2516
+ uses: S["uses"] | E["uses"];
2517
+ guaranteed: E["guaranteed"] extends true ? S["guaranteed"] : false;
2518
+ }>;
2519
+ /** Rows mode of a query of state `S` after a helper of effect `E` that keeps the rows, before `take`: relaxed as after a filter when the helper ends the guarantee. */
2520
+ type EffectRows<S extends SelectQueryState, E extends HelperEffect> = E["guaranteed"] extends true ? S["rows"] : FilteredStateRows<S>;
2521
+ /**
2522
+ * Helper of `defineHelper` for queries over table `T`: it applies effect `E` to the query it receives with arguments `A` and returns a query of the same kind.
2523
+ *
2524
+ * Selected fields replace earlier fields under the same keys; a query made by `get`, `pluck`, or an aggregate method does not accept a helper that selects fields.
2525
+ */
2526
+ type Helper<T extends AnyTable, E extends HelperEffect, A extends unknown[]> = <S extends HelperInput<T, E>, Kind extends SelectQueryKind>(query: SelectQuery<S, Kind>, ...args: A) => E extends HelperEffect ? SelectQuery<ApplyEffect<S, E>, Kind> : never;
2527
+ /**
2528
+ * Defines a reusable helper of a table that filters, selects fields, and applies `take`, `optional`, `nullable`, and `required`, used with `use` or called with a query.
2529
+ *
2530
+ * `helper` receives the query it is applied to and any further arguments, and returns the query with its clauses.
2531
+ * Defined with a query of a schema, such as `schema.form`, it can select the relations of the table in that schema, and applies to queries whose schema has them.
2532
+ * The helper returns a query of the same kind as the one it is applied to, bound to the same `Db` if any.
2533
+ */
2534
+ declare function defineHelper<T extends AnyTable, R extends SelectQuery<any, SelectQueryKind>, A extends unknown[], C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, helper: (query: SelectQuery<HelperState<T, C>, SelectQueryKind>, ...args: A) => R & CheckResult<R["types"]>): Helper<T, ReadEffect<R["types"]>, A>;
2535
+ /** Tagged template building a SQL fragment of values `T` that accepts compared values `I`. */
2536
+ type SqlTemplate<T, O extends OperatorDefinitions, I = T> = (strings: TemplateStringsArray, ...values: unknown[]) => Expression<T, O, I>;
2537
+ /**
2538
+ * Builds a SQL fragment.
2539
+ *
2540
+ * Interpolated expressions such as column references stay structured, a query of a table without clauses, such as `db.form`, becomes the name of the table, and other values become query parameters.
2541
+ * Another query of a table becomes a subquery in parentheses, and a query of one value, such as of an aggregate or of `exists`, its value, as in a condition.
2542
+ * The type argument declares the TypeScript type of the fragment and does not convert values at runtime, so the fragment cannot be selected; the fragment has `isNull` and the operators of `equalityOperators` only.
2543
+ */
2544
+ declare function sql<T = unknown>(strings: TemplateStringsArray, ...values: unknown[]): UntypedExpression<T>;
2545
+ /**
2546
+ * Creates a template building SQL fragments of `type`.
2547
+ *
2548
+ * The fragments have the operators of the type and encode compared values with it; the type adds no SQL cast.
2549
+ */
2550
+ declare function sql<Output, Input, O extends OperatorDefinitions>(type: Type<Output, Input, O, any>): SqlTemplate<Output, O, Input>;
2551
+ /**
2552
+ * Creates a SQL fragment of a quoted name, such as of a table or a column known only at runtime, for the templates of `sql`, of `$query` and `$script` of a `Db`, and of `query` and `script` of a `Database`.
2553
+ *
2554
+ * Several names make a qualified name, such as `identifier(schema, table)` for `"schema"."table"`.
2555
+ * The fragment has no parameters, so a script takes it.
2556
+ * The name is not qualified by the PostgreSQL schema of the statement.
2557
+ */
2558
+ declare function identifier(...names: [string, ...string[]]): UntypedExpression;
2559
+ /**
2560
+ * Creates an expression of a query parameter encoded with a type, for a value interpolated into `sql` or compared on its own.
2561
+ *
2562
+ * With a type, the parameter is cast to it, such as `$1::integer`, so that PostgreSQL applies the operators of the type even where nothing else in the statement determines it.
2563
+ * The cast omits type parameters, such as `$1::numeric` for `numeric(10,2)`, so that their precision, scale, or length do not constrain the value.
2564
+ *
2565
+ * With an expression, such as `param(self, other)` in an operator definition, the type of the expression encodes the value, and the parameter is not cast: PostgreSQL types it by the expression it is used with.
2566
+ * `value` may then also be an expression, such as an operand of a generic operator, which is returned as it is, with its own type and nullability.
2567
+ * A query of one value becomes an expression with the runtime type of the first argument and the nullability of the query, typed as an `AnyExpression` of its value.
2568
+ */
2569
+ declare function param<Output, Input, O extends OperatorDefinitions>(type: Type<Output, Input, O, any>, value: Input): Expression<Output, O, Input>;
2570
+ declare function param<E extends AnyExpression, V extends (E extends AnyExpression<infer T, infer I> ? Operand<T, I> : never)>(type: E, value: V): V extends AnyExpression ? V : V extends ScalarQuery ? AnyExpression<ScalarQueryValue<V>> : E;
2571
+ export { SelectQueryKind as $, QueryStateOf as $n, OperatorSignature as $r, from as $t, Expression as A, WhereValues as An, TransactionFailure as Ar, Schema as At, Database as B, ColumnRefs as Bn, TypeTransform as Br, EqualityOperator as Bt, TextOperators as C, KeyCheck as Cn, ResultDecodeError as Cr, TableContext as Ct, orderingOperators as D, WhereCallback as Dn, Driver as Dr, many as Dt, NumberTypeOperators as E, EqValue as En, Connection as Er, UsedRelation as Et, BindOptions as F, Predicate as Fn, Type as Fr, defineSchema as Ft, OpenedTestFixture as G, OneValueRows as Gn, KeyKind as Gr, AnySelectQuery as Gt, TransactionOptions as H, RelationRefs as Hn, AnyColumn as Hr, HasEquality as Ht, Db as I, and as In, TypeInput as Ir, AnyRecordQuery as It, TestHelpers as J, ValueRows as Jn, MergeOperators as Jr, ResultOf as Jt, PendingTestFixture as K, QueryResult as Kn, ToColumn as Kr, BoundSelectQuery as Kt, DbMutationState as L, not as Ln, TypeOperators as Lr, RecordQuery as Lt, TypedExpression as M, CombinedCondition as Mn, AnyType as Mr, SchemaPartRelations as Mt, UntypedExpression as N, Condition as Nn, BaseType as Nr, SchemaTables as Nt, AnyExpression as O, WhereCondition as On, DriverResult as Or, one as Ot, AnyDb as P, ConditionOperand as Pn, TextValue as Pr, Tables as Pt, AnyQuery as Q, QueryState as Qn, GenericOperatorImplementation as Qr, ValuesQuery as Qt, DbOf as R, or as Rn, TypeOptions as Rr, RecordQueryState as Rt, TextLengthSignature as S, orderBy as Sn, RequiredRelationError as Sr, SchemaRelations as St, textOperators as T, PrimaryKeyValues as Tn, ResultRows as Tr, UsableRelation as Tt, createDatabase as U, FilteredRows as Un, Column as Ur, InSignature as Ut, DatabaseOptions as V, QueryContext as Vn, defineType as Vr, EqualityOperators as Vt, TransactionCoordinator as W, OneRow as Wn, ColumnAttributes as Wr, equalityOperators as Wt, TestTransactionOptions as X, EmptyRecord as Xn, OperatorDefinitions as Xr, SelectQuery as Xt, TestHooks as Y, CountValueType as Yn, NoOperators as Yr, ScalarQuery as Yt, createTestHelpers as Z, InitialQueryState as Zn, GenericOperator as Zr, TypedScalarQuery as Zt, least as _, OrderTerms as _n, TableKeys as _r, RelationKey as _t, Helper as a, ExpressionValue as an, OperandValue as ar, SqlQueryState as at, PatternSignature as b, asc as bn, defineTable as br, RequiredMember as bt, CaseBranch as c, Selection as cn, AnyTable as cr, MutationQuery as ct, FollowingOperand as d, Literal as dn, ColumnOperators as dr, MergeRelations as dt, defineGenericOperator as ei, ColumnValue as en, QueryValueType as er, AnySqlQuery as et, NullSkippingResult as f, literal as fn, ColumnShape as fr, NoRelations as ft, greatest as g, OrderTerm as gn, Table as gr, RelationDeclarations as gt, coalesce as h, OrderKey as hn, Selectable as hr, RelationDeclaration as ht, sql as i, ExpressionInput as in, Operand as ir, SqlQuery as it, ExpressionOperators as j, defineFilter as jn, createStatement as jr, SchemaPart as jt, BaseOperators as k, WhereFilter as kn, SqlStatement as kr, AnySchema as kt, CaseCondition as l, SelectionResult as ln, AnyTableKeys as lr, MutationQueryState as lt, caseWhen as m, OrderDirection as mn, KeyColumns as mr, Relation as mt, identifier as n, UpdateSet as nn, BooleanResult as nr, FieldTypes as nt, HelperEffect as o, MergeSelection as on, compare as or, AnyMutationQuery as ot, TypedOperand as p, OrderColumns as pn, ColumnValues as pr, OneRelationKeys as pt, TestFixture as q, ResultByRows as qn, BoundOperators as qr, FilteredStateRows as qt, param as r, UpdateValues as rn, ComparisonSignature as rr, InitialSqlQueryState as rt, defineHelper as s, NestedQuery as sn, CompileOptions as sr, InitialMutationState as st, SqlTemplate as t, InsertValues as tn, SelectQueryState as tr, DecodedFields as tt, CaseValue as u, SelectionUses as un, ColumnDefinitions as ur, DeclaredRelations as ut, FALSE as v, Ordering as vn, TableOptions as vr, RelationKeys as vt, TextTypeOperators as w, NotAKey as wn, ResultMode as wr, TableRelations as wt, TextConversionSignature as x, desc as xn, NotFoundError as xr, SchemaContext as xt, TRUE as y, SelectedRefs as yn, ToColumns as yr, RelationKind as yt, DbQueryState as z, ExistsValueType as zn, TypeOutput as zr, SelectionState as zt };