kern-orm 0.4.0 → 0.5.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.
@@ -209,7 +209,7 @@ interface SqlStatement {
209
209
  declare function createStatement(text: string, parameters?: readonly TextValue[]): SqlStatement;
210
210
  /** Result of a statement. */
211
211
  interface DriverResult {
212
- /** Command tag that PostgreSQL completed the statement with, such as `SELECT` or `ROLLBACK` for a `COMMIT` of a failed transaction. */
212
+ /** Command of the tag that PostgreSQL completed the statement with, such as `SELECT` or `ROLLBACK` for a `COMMIT` of a failed transaction; a driver may give only the first word of a tag of several words, such as `CREATE` of `CREATE TABLE`. */
213
213
  readonly command: string;
214
214
  /** Number of rows that the command tag reports, such as the rows that an `UPDATE` changes, also without `RETURNING`; `0` for a command without one, such as `BEGIN`. */
215
215
  readonly count: number;
@@ -485,51 +485,34 @@ interface ComparisonSignature extends OperatorSignature {
485
485
  * Operators of custom types build comparisons with it, such as `compare(self, "ILIKE", pattern)`.
486
486
  */
487
487
  declare function compare<T, V>(self: AnyExpression<T>, operator: ComparisonNode["operator"], value: V): Expression<BooleanResult<T | OperandValue<V>>>;
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;
494
- }
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;
488
+ /** Runtime mark of the operators of `equalityOperators`, which tell that a type has SQL `=`. */
489
+ declare const equalityBrand: unique symbol;
490
+ /** Generic operator of `equalityOperators`, which gives the type it is added to SQL `=`. */
491
+ interface EqualityOperator<S extends OperatorSignature> extends GenericOperator<S> {
492
+ readonly [equalityBrand]: true;
499
493
  }
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;
494
+ /** 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. */
495
+ declare const valuesQueryNode: unique symbol;
496
+ /** 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`. */
497
+ interface InSignature extends OperatorSignature {
498
+ 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)>>;
520
499
  }
500
+ /** Operators of `equalityOperators`. */
501
+ type EqualityOperators = {
502
+ eq: EqualityOperator<ComparisonSignature>;
503
+ ne: EqualityOperator<ComparisonSignature>;
504
+ in: EqualityOperator<InSignature>;
505
+ };
506
+ /** Tells whether operators `O` include an operator of `equalityOperators`, so that their type has SQL `=`. */
507
+ type HasEquality<O> = true extends { [K in keyof O]: O[K] extends {
508
+ readonly [equalityBrand]: true;
509
+ } ? true : false; }[keyof O] ? true : false;
521
510
  /**
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.
511
+ * Operators of SQL equality: `eq`, `ne`, and `in`; `orderingOperators` include them.
523
512
  *
524
- * Its result mode is the rows mode of the rows it changes and whether a row is the value of its only field.
513
+ * 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 `=`.
525
514
  */
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
- }
515
+ declare const equalityOperators: EqualityOperators;
533
516
  /** Records of a query without selected fields. */
534
517
  type EmptyRecord = Record<never, never>;
535
518
  /** 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. */
@@ -583,21 +566,72 @@ interface InitialQueryState<T extends AnyTable, C extends SchemaContext = NoRela
583
566
  readonly guaranteed: Guaranteed;
584
567
  readonly aggregate: false;
585
568
  }
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>;
569
+ /** Selection of the rows of a nested query as the value of the field `key`. */
570
+ interface NestedSelectionNode {
571
+ readonly key: string;
572
+ readonly query: QueryNode;
573
+ /** `Db` that the nested query is bound to, which must be the `Db` that runs the statement. */
574
+ readonly db: AnyDb | undefined;
575
+ }
576
+ /** Selection of a value from code as the field `key` of every record, which a statement does not select. */
577
+ interface LiteralSelectionNode {
578
+ readonly key: string;
579
+ readonly literal: unknown;
580
+ }
581
+ /** Field that a statement selects: an expression, or the rows of a nested query. */
582
+ type SqlSelectedNode = ProjectionNode | NestedSelectionNode;
583
+ /** Field selected by a query: one that its statement selects, or a literal. */
584
+ type SelectedNode = SqlSelectedNode | LiteralSelectionNode;
585
+ /** Select query of a table; its result mode applies when it is executed or its rows are nested. */
586
+ interface QueryNode extends ResultMode {
587
+ readonly kind: "query";
588
+ readonly from: TableSourceNode;
589
+ /** Relation whose records the query selects, correlated with its parent by the relation filter. */
590
+ readonly relation: RelationDefinition | undefined;
591
+ /** Fields in the order of the result, with unique keys; a query without them returns records without fields. */
592
+ readonly projections: readonly SelectedNode[];
593
+ readonly filters: QueryFilters;
594
+ readonly orderBy: readonly OrderNode[];
595
+ readonly limit: ExpressionNode | undefined;
596
+ readonly offset: ExpressionNode | undefined;
597
+ /** 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`. */
598
+ readonly guaranteed: boolean;
599
+ /** Whether `all` allows a mutation of the query to change every row of the table without a filter. */
600
+ readonly all: boolean;
601
+ }
602
+ /**
603
+ * 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.
604
+ *
605
+ * Its result mode is the rows mode of the rows it changes and whether a row is the value of its only field.
606
+ */
607
+ type MutationNode = MutationStatementNode<SelectedNode>;
608
+ /** Query of `$select` without a source: one record whose fields are the values of expressions, the rows of independent queries, and literals. */
609
+ interface RecordQueryNode {
610
+ readonly kind: "record";
611
+ /** Fields in the order of the record, with unique keys. */
612
+ readonly projections: readonly SelectedNode[];
613
+ }
614
+ /**
615
+ * Field of a selection whose value is `T`, made by `literal`.
616
+ *
617
+ * It is not an expression: it has no SQL, so only a selection takes it.
618
+ */
619
+ declare class Literal<out T> {
620
+ /** Value of the field in every record, which the query returns as it is. */
621
+ readonly literal: T;
622
+ constructor(
623
+ /** Value of the field in every record, which the query returns as it is. */
624
+ literal: T);
625
+ /** Rejects the literal as an operand of an expression: a statement has no SQL of it. */
626
+ [operandNode](): never;
600
627
  }
628
+ /**
629
+ * 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.
630
+ *
631
+ * It lets a branch of a selection skip a column or a nested query, such as `withHint ? field.hint : literal(null)`.
632
+ * To use a value in SQL, such as in a condition, pass it through `param` instead.
633
+ */
634
+ declare function literal<T extends {} | null | undefined>(value: T): Literal<T>;
601
635
  /** 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. */
602
636
  type RelationRows<Kind extends RelationKind, Required extends boolean> = Kind extends "many" ? "many" : Required extends true ? "one" : "nullable";
603
637
  /** Rows mode after a filter of a query whose row a required relation guarantees: `one` becomes `nullable`, or `optional` for a query of values; other modes stay. */
@@ -616,10 +650,299 @@ type OneValueRows<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows
616
650
  type QueryResult<S extends QueryState> = S extends QueryState ? ResultByRows<S["result"], S["rows"]> : never;
617
651
  /** Result of rows of `Result` returned in rows mode `Rows`; a union of modes gives the union of their results. */
618
652
  type ResultByRows<Result, Rows extends ResultRows> = Rows extends "many" ? Result[] : Rows extends "one" ? Result : Rows extends "nullable" ? Result | null : Result | undefined;
653
+ /** Expressions, nested queries, and literals selected under the keys of the result fields; a record has no symbol keys. */
654
+ interface Selection {
655
+ readonly [key: string]: TypedExpression | NestedQuery | Literal<unknown>;
656
+ readonly [key: symbol]: never;
657
+ }
658
+ /** 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. */
659
+ type NestedQuery = QueryOf<SelectQueryState>;
660
+ /** Record of the values of the expressions, of the nested rows, and of the literals of a selection. */
661
+ type SelectionResult<S extends Selection> = { [K in keyof S]: FieldValue<S[K]>; };
662
+ /** 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. */
663
+ type FieldValue<V> = V extends NestedQuery ? QueryResult<V["types"]> : V extends Literal<infer T> ? T : ExpressionValue<V>;
664
+ /** Relations whose records the nested queries of a selection select. */
665
+ type SelectionUses<S extends Selection> = S[keyof S] extends (infer V) ? V extends NestedQuery ? V["types"]["uses"] : never : never;
666
+ /** Value of a selected expression. */
667
+ type ExpressionValue<E> = E extends AnyExpression<infer T> ? T : never;
668
+ /** Values that the type of an expression encodes, such as in place of its value. */
669
+ type ExpressionInput<E> = E extends AnyExpression<unknown, infer I> ? I : never;
670
+ declare const helperFields: unique symbol;
671
+ /** Marker of the input fields of a helper, carrying the keys selected by its callback. */
672
+ interface HelperFields<Keys extends PropertyKey = PropertyKey> {
673
+ readonly [helperFields]: Keys;
674
+ }
675
+ /** Records with `Fields` added or replaced, for each branch of either record type; `any` stays `any`. */
676
+ type MergeSelection<Previous, Fields> = Previous extends unknown ? Fields extends unknown ? MergeFields<RecordFields<Previous>, RecordFields<Fields>> & (IsAny<Previous> extends true ? Previous : unknown) : never : never;
677
+ /** Fields with numeric keys represented as the string keys used in result records. */
678
+ 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;
679
+ /** Merge of normalized fields, retaining the previous value when an optional replacement is absent. */
680
+ 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.
681
+ ? Previous[K] | keyof Fields : K extends keyof Fields // A decoder can return undefined, so it cannot be excluded as merely an absent property.
682
+ ? Previous[K] | Fields[K] : Previous[K]; } & { [K in keyof Fields as K extends keyof Previous ? ({} extends Pick<Fields, K> ? never : K) : K]: Fields[K]; }>;
683
+ /** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
684
+ interface RecordQueryState$1<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
685
+ readonly result: R;
686
+ readonly rows: "one";
687
+ readonly value: false;
688
+ readonly uses: U;
689
+ }
690
+ /** 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. */
691
+ type SelectionState<Sel extends Selection> = RecordQueryState$1<MergeSelection<EmptyRecord, SelectionResult<Sel>>, SelectionUses<Sel>>;
692
+ /**
693
+ * 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.
694
+ *
695
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
696
+ * A bound query executes on its `Db` when awaited.
697
+ */
698
+ declare class RecordQuery<out S extends RecordQueryState$1, out Kind extends SelectQueryKind = "unbound"> {
699
+ readonly node: RecordQueryNode;
700
+ readonly types: S;
701
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
702
+ readonly db: QueryDb<Kind>;
703
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
704
+ readonly then: QueryThen<S, Kind>;
705
+ constructor(node: RecordQueryNode, db?: AnyDb);
706
+ /**
707
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
708
+ *
709
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
710
+ */
711
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
712
+ /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
713
+ [operandNode](): never;
714
+ }
715
+ /** Query of `$select` of any state and kind. */
716
+ type AnyRecordQuery = RecordQuery<any, SelectQueryKind>;
717
+ declare const schemaBrand: unique symbol;
718
+ /** Key of the relation definitions of a schema, which composition reads. */
719
+ declare const schemaRelations: unique symbol;
720
+ /** Tables by their keys; a key must not start with `$`, which is reserved for schema and `Db` members. */
721
+ type Tables = Record<string, AnyTable>;
722
+ /**
723
+ * Immutable collection of tables and their relations with query entry points.
724
+ *
725
+ * A schema is not bound to a database, so queries built from it can be defined at module level.
726
+ * A `Db` can execute such a query if its schema contains the tables and the selected relations of the query and every bound nested query belongs to that `Db`.
727
+ */
728
+ type Schema<T extends Tables, R extends SchemaRelations = EmptyRecord> = SchemaEntries<T, R> & SchemaMembers<T, R>;
729
+ /** Query entry points; each access starts a query over a new table occurrence. */
730
+ type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
731
+ /** Members of a schema that composition reads: its tables and the relations of its tables. */
732
+ interface SchemaContents<T extends Tables, R extends SchemaRelations> {
733
+ readonly [schemaBrand]: true;
734
+ /** Tables of the schema by their keys. */
735
+ readonly $tables: T;
736
+ /** Relation definitions by table key and relation name. */
737
+ readonly [schemaRelations]: R;
738
+ }
739
+ interface SchemaMembers<T extends Tables, R extends SchemaRelations> extends SchemaContents<T, R> {
740
+ /**
741
+ * Creates a schema of the same tables with the relations of `relations` added, declared with `many` and `one` by their names under the keys of their tables.
742
+ *
743
+ * A relation refers to a table of the schema by columns of SQL types that `=` compares; a relation that the schema already has is rejected.
744
+ */
745
+ $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>>>;
746
+ /**
747
+ * 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.
748
+ *
749
+ * The value of the field of a query is the result it gives when executed, such as an array of records or one value.
750
+ */
751
+ $select<Sel extends Selection>(selection: Sel): RecordQuery<SelectionState<Sel>>;
752
+ }
753
+ /** Schema of any tables and relations. */
754
+ type AnySchema = SchemaContents<Tables, SchemaRelations>;
755
+ /** Part of a schema definition: an object of tables by their keys, or a schema whose tables and relations it includes. */
756
+ type SchemaPart = Tables | AnySchema;
757
+ /**
758
+ * Tables of the parts of a schema definition by their keys.
759
+ *
760
+ * A part typed as a union gives a union of tables, and parts of an array of unknown length give no tables, since any of them may be missing.
761
+ */
762
+ type SchemaTables<P extends readonly SchemaPart[]> = ComposeParts<P>["tables"] extends (infer T extends Tables) ? { [K in keyof T]: T[K]; } : never;
763
+ /** Relations of the parts of a schema definition by table key and relation name, read as `SchemaTables` reads the tables. */
764
+ type SchemaPartRelations<P extends readonly SchemaPart[]> = ComposeParts<P>["relations"] extends (infer R extends SchemaRelations) ? MergeRelations<R> : never;
765
+ /** Tables and relations of the parts of a schema definition, intersected. */
766
+ interface PartContents {
767
+ readonly tables: Tables;
768
+ readonly relations: SchemaRelations;
769
+ }
770
+ type ComposeParts<P extends readonly SchemaPart[], Composed extends PartContents = {
771
+ tables: EmptyRecord;
772
+ relations: EmptyRecord;
773
+ }> = P extends readonly [infer First extends SchemaPart, ...infer Rest extends readonly SchemaPart[]] ? ComposeParts<Rest, Composed & ReadPart<First>> : P extends readonly [...infer Rest extends readonly SchemaPart[], infer Last extends SchemaPart] ? ComposeParts<Rest, Composed & ReadPart<Last>> : Composed;
774
+ type ReadPart<P extends SchemaPart> = P extends SchemaContents<infer T, any> ? {
775
+ tables: T;
776
+ relations: P[typeof schemaRelations];
777
+ } : {
778
+ tables: P;
779
+ relations: EmptyRecord;
780
+ };
781
+ /**
782
+ * Defines a schema of the tables of `parts`, keyed by their names in queries.
783
+ *
784
+ * A part is an object of tables by their keys or another schema, whose tables and relations the new schema includes as they are, so queries built from that schema run on the new one.
785
+ * A key of two different tables, a table under two keys, and two different definitions of a relation of a table are rejected; the same table under the same key or the same relation in several parts is one.
786
+ */
787
+ declare function defineSchema<P extends SchemaPart[]>(...parts: P): Schema<SchemaTables<P>, SchemaPartRelations<P>>;
788
+ declare const sourceTable: unique symbol;
789
+ declare const sourceKey: unique symbol;
790
+ /** Runtime mark of the declarations of `many` and `one`. */
791
+ declare const declarationBrand: unique symbol;
792
+ /** Kind of a relation: `many` related records, or `one` related record at most. */
793
+ type RelationKind = "many" | "one";
794
+ /** Relation of a table of a schema to the records of table `Target`, which has key `TargetKey` in the schema. */
795
+ interface Relation<Kind extends RelationKind = RelationKind, Target extends AnyTable = AnyTable, TargetKey extends string = string, Required extends boolean = boolean> {
796
+ readonly kind: Kind;
797
+ readonly target: Target;
798
+ readonly targetKey: TargetKey;
799
+ /** Whether every record of the table has its related record, so that a query of a relation `one` without a filter rejects without it rather than giving `null`; `false` for a relation `many`. */
800
+ readonly required: Required;
801
+ }
802
+ /**
803
+ * Relation of a table of a schema as `$relations` defines it: the columns of its keys, compared by SQL `=` in order.
804
+ *
805
+ * Composition includes a definition as it is, so a relation that several parts include is one definition.
806
+ */
807
+ interface RelationDefinition extends Relation {
808
+ readonly name: string;
809
+ /** Key of the source table. */
810
+ readonly key: string;
811
+ readonly source: AnyTable;
812
+ readonly from: readonly string[];
813
+ readonly to: readonly string[];
814
+ }
815
+ /** Relation `N` of the table under key `K` of a schema, of type `R`, whose records a query selects. */
816
+ interface UsedRelation<K extends string = string, N extends string = string, R extends Relation = Relation> {
817
+ readonly key: K;
818
+ readonly name: N;
819
+ readonly relation: R;
820
+ }
821
+ /** Relations of schema relations `R` that the queries of a `Db` of the schema may select. */
822
+ type UsableRelation<R extends SchemaRelations> = { [K in keyof R & string]: { [N in keyof R[K] & string]: UsedRelation<K, N, R[K][N]>; }[keyof R[K] & string]; }[keyof R & string];
823
+ /** Relations of the tables of a schema by table key and relation name. */
824
+ type SchemaRelations = {
825
+ readonly [key: string]: TableRelations;
826
+ };
827
+ /** Relations of a table of a schema by relation name. */
828
+ type TableRelations = {
829
+ readonly [name: string]: Relation;
830
+ };
831
+ /**
832
+ * Declaration of a relation by `many` or `one`, which `$relations` of a schema defines for a table of type `Source` with key `From` of the source table.
833
+ *
834
+ * `Source` and `From` only type the keys of the source table.
835
+ */
836
+ interface RelationDeclaration<Kind extends RelationKind, Source extends AnyTable, Target extends AnyTable, From = unknown, Required extends boolean = boolean> {
837
+ readonly [declarationBrand]: true;
838
+ readonly kind: Kind;
839
+ readonly target: Target;
840
+ readonly from: readonly string[];
841
+ readonly to: readonly string[];
842
+ readonly required: Required;
843
+ readonly [sourceTable]?: (source: Source) => void;
844
+ readonly [sourceKey]?: From;
845
+ }
846
+ /** Column key of table `T` whose type has SQL `=`, which a relation can compare. */
847
+ type EqualityKey<T extends AnyTable> = { [K in keyof T["columns"]]: HasEquality<ColumnOperators<T, K>> extends true ? K : never; }[keyof T["columns"]] & string;
848
+ /** Key of a relation in table `T`: a column key, or a non-empty list of them for a composite key. */
849
+ type RelationKey<T extends AnyTable> = EqualityKey<T> | readonly [EqualityKey<T>, ...EqualityKey<T>[]];
850
+ /** Key of table `T` with as many columns as key `From`. */
851
+ type MatchingKey<T extends AnyTable, From> = From extends string ? EqualityKey<T> : { readonly [I in keyof From]: EqualityKey<T>; };
852
+ /** Keys of a relation: the columns `from` of the source table equal the columns `to` of the target table, in order. */
853
+ interface RelationKeys<Target extends AnyTable, From> {
854
+ readonly from: From;
855
+ readonly to: MatchingKey<Target, From>;
856
+ }
857
+ /** Keys of a relation `one`, as in `RelationKeys`, and whether the relation is required. */
858
+ interface OneRelationKeys<From, To> {
859
+ readonly from: From;
860
+ readonly to: To;
861
+ /** Whether every record has its related record, such as by a foreign key on columns `from` that are not nullable, so that a query of the relation without a filter rejects without it rather than giving `null`. */
862
+ readonly required?: boolean;
863
+ }
864
+ /** Members of the keys `K` of a relation `one` with only `required` typed, so that a call infers `K` with `required` as optional as it is, and reports a wrong key at its own member. */
865
+ type RequiredMember<K> = { readonly [P in keyof K]: P extends "required" ? K[P] : unknown; };
866
+ /** Whether the keys `K` of a relation `one` make it required: only where they set `required` to `true`, and `boolean` where `required` may be `true` or missing, such as `required?: true`. */
867
+ type DeclaredRequiredOf<K> = K extends unknown ? "required" extends keyof K ? K extends {
868
+ readonly required: infer Required;
869
+ } ? IsTrue<Required> : IsTrue<K["required" & keyof K] | undefined> : false : never;
870
+ /** `true` for `true`, and `false` for other values, such as `false` and `undefined`; a union gives the union of their results. */
871
+ type IsTrue<T> = T extends true ? true : false;
872
+ /** Declarations of `$relations` of a schema of tables `T`: relations by name, for tables by their keys. */
873
+ type RelationDeclarations<T extends Tables> = { readonly [K in keyof T]?: {
874
+ readonly [name: string]: RelationDeclaration<RelationKind, T[K], T[keyof T]>;
875
+ }; };
876
+ /**
877
+ * Declarations `D` of `$relations` checked by the names they use: relations of the tables of `T` under their keys, and no other keys.
878
+ *
879
+ * Declarations under the names of `D` get their source table from this type even where the index signature of `RelationDeclarations` gives way to a member of `Object`, such as for a relation named `toString`.
880
+ * A relation name must not be a column key of its table or start with `$`, since the references that the callback of `select` gets have both.
881
+ */
882
+ type CheckDeclarations<T extends Tables, D> = { readonly [K in keyof D]: [TableKey<T, K>] extends [never] ? never : undefined extends D[K] ? D[K] : { readonly [N in keyof D[K]]: `${N & (string | number)}` extends ReservedName<T[TableKey<T, K>]> ? never : RelationDeclaration<RelationKind, T[TableKey<T, K>], T[keyof T], RelationKey<T[TableKey<T, K>]>>; }; };
883
+ /** Names that a relation of table `T` cannot have: the keys of its columns, and names starting with `$`. */
884
+ type ReservedName<T extends AnyTable> = `${keyof T["columns"] & (string | number)}` | `$${string}`;
885
+ /** Key of tables `T` written as key `K`, such as `1` for `"1"`, as object keys are strings at runtime. */
886
+ type TableKey<T extends Tables, K> = { [P in keyof T]: `${P & (string | number)}` extends `${K & (string | number)}` ? P : never; }[keyof T];
887
+ /** Relations that declarations `D` of a schema of tables `T` define, by table key and relation name, as strings like the keys of objects. */
888
+ type DeclaredRelations<T extends Tables, D> = { [K in keyof D as K extends number ? `${K}` : K]: { [N in keyof D[K] as N extends number ? `${N}` : N]: D[K][N] extends RelationDeclaration<infer Kind, never, infer Target, unknown, infer Required> ? Relation<Kind, Target, KeyOfTable<T, Target>, Required> : never; }; };
889
+ /** Column key of relation key `K`: the key itself, or a column of a composite key. */
890
+ type RelationColumn<K> = K extends readonly unknown[] ? K[number] : K;
891
+ /** Check of key `To` of a relation `one` that rejects it when its columns include no key of table `Target`, as far as the types tell. */
892
+ type TargetKeyCheck<Target extends AnyTable, To> = [ContainsKey<Target, RelationColumn<To>>] extends [false] ? {
893
+ readonly to: MissingKey<KeyOf<Target["keys"]>>;
894
+ } : unknown;
895
+ /** Type that a key `to` of a relation `one` without a key of its target is checked against, naming the keys of the target. */
896
+ interface MissingKey<Keys> {
897
+ readonly "columns to must include a key of the target": Keys;
898
+ }
899
+ /** Key of table `Target` among tables `T`, as a string like the keys of objects. */
900
+ type KeyOfTable<T extends Tables, Target> = { [K in keyof T]: [T[K]] extends [Target] ? [Target] extends [T[K]] ? K extends number ? `${K}` : K & string : never : never; }[keyof T];
901
+ /** Relations of `R` by table key, with the relations under the same key merged. */
902
+ type MergeRelations<R> = { [K in keyof R]: { [N in keyof R[K]]: R[K][N]; }; };
903
+ /** Relations of the schema that a query starts from, by table key, and the key of the table of the query there. */
904
+ interface SchemaContext<R extends SchemaRelations = SchemaRelations, K extends string = string> {
905
+ readonly relations: R;
906
+ readonly key: K;
907
+ }
908
+ /** Schema context of a query whose table has no relations, such as one of `from(table)`. */
909
+ type NoRelations = SchemaContext<EmptyRecord, string>;
910
+ /** Schema context of the queries of the table under key `K` of a schema of relations `R`, whose keys are strings, as object keys are at runtime. */
911
+ type TableContext<R extends SchemaRelations, K> = K extends keyof R ? [keyof R[K]] extends [never] ? NoRelations : SchemaContext<R, K & string> : K extends number ? TableContext<R, `${K}`> : NoRelations;
912
+ /**
913
+ * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
914
+ *
915
+ * A composite key lists its columns in arrays of the same length.
916
+ */
917
+ declare function many<Source extends AnyTable, Target extends AnyTable, const From extends RelationKey<Source>>(target: Target, keys: RelationKeys<Target, From>): RelationDeclaration<"many", Source, Target, From, false>;
918
+ /**
919
+ * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
920
+ *
921
+ * A composite key lists its columns in arrays of the same length.
922
+ * The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
923
+ * Without the record, a query of the relation gives `null`, and a query of a relation declared with `required: true` rejects unless it filters the record.
924
+ * Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
925
+ */
926
+ declare function one<Source extends AnyTable, Target extends AnyTable, const From extends RelationKey<Source>, const To extends MatchingKey<Target, From>, const Keys extends object = EmptyRecord>(target: Target, keys: OneRelationKeys<From, To> & RequiredMember<Keys> & TargetKeyCheck<Target, To>): RelationDeclaration<"one", Source, Target, From, NoInfer<DeclaredRequiredOf<Keys>>>;
927
+ /** Type of a count: a `bigint` of PostgreSQL decoded as a number, rejecting a count that a number cannot hold exactly. */
928
+ declare const countType: BaseType<number, number, MergeOperators<NoOperators, {
929
+ eq: EqualityOperator<ComparisonSignature>;
930
+ ne: EqualityOperator<ComparisonSignature>;
931
+ in: EqualityOperator<InSignature>;
932
+ lt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
933
+ lte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
934
+ gt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
935
+ gte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
936
+ }>, undefined>;
937
+ /** Type of the value of a query of a count. */
938
+ interface CountValueType extends QueryValueType {
939
+ readonly input: TypeInput<typeof countType>;
940
+ readonly operators: TypeOperators<typeof countType>;
941
+ }
619
942
  /** References to the columns of the query source, passed to query callbacks. */
620
943
  type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
621
944
  /**
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.
945
+ * Queries of the records of the relations of the table of schema context `C`, by relation name, which the callbacks of queries receive beside the columns.
623
946
  *
624
947
  * A relation name is never a column key of its table.
625
948
  * A context whose table key is not known, such as one of a query of any schema, has no relations.
@@ -630,7 +953,7 @@ type RelationQueries<R extends SchemaContext["relations"], K extends keyof R & s
630
953
  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"]>>;
631
954
  /** Runtime context of the queries of a table in the schema they start from. */
632
955
  interface QueryContext {
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. */
956
+ /** Getters of the queries of the relations of the table, which the references of the callbacks of queries have as their own properties and which read the key columns from them. */
634
957
  readonly relations: PropertyDescriptorMap;
635
958
  }
636
959
  /** Type of the value of a query of `exists`. */
@@ -686,20 +1009,12 @@ type WhereCallback<T extends AnyTable, C extends SchemaContext = NoRelations> =
686
1009
  /** 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
1010
  type WhereFilter<T extends AnyTable, C extends SchemaContext = NoRelations> = WhereCondition<T> | WhereCallback<T, C>;
688
1011
  /**
689
- * Defines a reusable condition of `where` for queries over a table, checking its objects of column values against the columns.
690
- *
691
- * The condition can be combined further with `and`, `or`, and `not`.
692
- */
693
- declare function defineFilter<T extends AnyTable, C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, filter: NoInfer<WhereCondition<T>>): WhereCondition<T>;
694
- /**
695
- * Defines a reusable callback of `where` for queries over a table, checking its objects of column values against the columns.
1012
+ * Argument of `where` of a query of state `S`: a `WhereFilter` of its table and schema, which TypeScript resolves with what it has inferred for `S` before it checks a callback in it.
696
1013
  *
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.
1014
+ * TypeScript types the body of a callback once, for every overload, and a plain `WhereFilter` leaves `S` unresolved there, so the body would widen a literal, such as of an enum column, to `string`.
1015
+ * It reads the filter only in its branch: a general alias that takes the filter as an argument resolves it on every call, which takes about 25 more instantiations.
699
1016
  */
700
- declare function defineFilter<T extends AnyTable, C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, filter: NoInfer<WhereCallback<T, C>>): WhereCallback<T, C>;
701
- /** Defines a reusable filter of `where` for queries over a table, either a condition or a callback. */
702
- declare function defineFilter<T extends AnyTable, C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, filter: NoInfer<WhereFilter<T, C>>): WhereFilter<T, C>;
1017
+ type QueryWhereFilter<S extends SelectQueryState> = [S] extends [unknown] ? WhereFilter<S["table"], S["schema"]> : never;
703
1018
  /**
704
1019
  * 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.
705
1020
  *
@@ -729,85 +1044,38 @@ type OrderKey<T extends AnyTable> = (keyof T["columns"] & string) | OrderColumns
729
1044
  declare const ordering: unique symbol;
730
1045
  /** Expression or query of one value with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
731
1046
  interface Ordering {
732
- readonly [ordering]: true;
733
- }
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;
736
- /**
737
- * References of the callback of `orderBy` to the fields of records `R` selected by a query: their expressions by key.
738
- *
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.
740
- */
741
- type SelectedRefs<R> = { readonly [K in keyof R & string]: AnyExpression<R[K]>; };
742
- /** Sort keys returned by the callback of `orderBy`: one or an array of them. */
743
- type OrderTerms = OrderTerm | readonly OrderTerm[];
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]; }>;
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. */
802
- type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValues<T>[K] | AnyExpression<Selectable<T>[K]>;
1047
+ readonly [ordering]: true;
1048
+ }
1049
+ /** 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. */
1050
+ type OrderTerm = AnyExpression | ScalarQuery | Ordering;
1051
+ /**
1052
+ * References of the callback of `orderBy` to the fields of records `R` selected by a query: their expressions by key.
1053
+ *
1054
+ * 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.
1055
+ */
1056
+ type SelectedRefs<R> = { readonly [K in keyof R & string]: AnyExpression<R[K]>; };
1057
+ /** Sort keys returned by the callback of `orderBy`: one or an array of them. */
1058
+ type OrderTerms = OrderTerm | readonly OrderTerm[];
1059
+ /** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
1060
+ declare function asc(value: AnyExpression | ScalarQuery): Ordering;
1061
+ /** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
1062
+ declare function desc(value: AnyExpression | ScalarQuery): Ordering;
1063
+ /** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
1064
+ declare function orderBy(value: AnyExpression | ScalarQuery, direction: OrderDirection): Ordering;
1065
+ /**
1066
+ * 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, an expression of its values, or a query of one such value.
1067
+ *
1068
+ * A query may be `NULL` without its row, which PostgreSQL rejects for a column that is not nullable.
1069
+ */
1070
+ type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValues<T>[K] | AnyExpression<Selectable<T>[K]> | ScalarQuery<Selectable<T>[K] | null>;
803
1071
  /** 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. */
804
1072
  type OptionalColumnKey<T extends AnyTable> = { [K in keyof T["columns"]]: T["columns"][K]["attributes"]["hasDefault"] extends true ? K : null extends ColumnValues<T>[K] ? K : never; }[keyof T["columns"]];
805
1073
  /** Record of an insert into table `T`: the values of its columns, which may omit a column with a default or a nullable column, or give it as `undefined`. */
806
1074
  type InsertValues<T extends AnyTable> = { readonly [K in keyof T["columns"] as K extends OptionalColumnKey<T> ? never : K]: ColumnValue<T, K>; } & { readonly [K in OptionalColumnKey<T>]?: ColumnValue<T, K> | undefined; };
807
1075
  /** Values of the columns of table `T` that an update sets; a column omitted or given as `undefined` keeps its value. */
808
1076
  type UpdateValues<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: ColumnValue<T, K> | undefined; };
809
- /** Argument of `update`: the values that it sets, or a callback that receives the columns of the changed rows and returns them. */
810
- type UpdateSet<T extends AnyTable> = UpdateValues<T> | ((columns: ColumnRefs<T>) => UpdateValues<T>);
1077
+ /** Argument of `update` of table `T` with schema context `C`: the values that it sets, or a callback that receives the columns and the queries of the relations of the changed rows and returns them. */
1078
+ type UpdateSet<T extends AnyTable, C extends SchemaContext = NoRelations> = UpdateValues<T> | ((columns: ColumnRefs<T> & RelationRefs<C>) => UpdateValues<T>);
811
1079
  /** State `S` with the parts of `Changes` replaced. */
812
1080
  type ChangeState<S extends SelectQueryState, Changes extends Partial<SelectQueryState>> = { readonly [K in keyof SelectQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
813
1081
  /** Rows mode of a query of state `S` after a filter: `FilteredRows` of a query whose row is guaranteed, and the rows of other queries. */
@@ -840,6 +1108,8 @@ interface ScalarQuery<T = unknown> {
840
1108
  }
841
1109
  /** Value of query `Q` of one value in an expression. */
842
1110
  type ScalarQueryValue<Q extends ScalarQuery> = Q[typeof scalarValue];
1111
+ /** Relations whose records `E`, an expression or a query of one value that a callback returns, selects: those of a query, as an expression does not carry the relations of its queries. */
1112
+ type OperandUses<E> = E extends ScalarQuery ? E["types"]["uses"] : never;
843
1113
  /** State of a query of one value, which an expression takes. */
844
1114
  interface ScalarQueryState extends SelectQueryState {
845
1115
  readonly rows: "one" | "optional";
@@ -866,7 +1136,7 @@ interface ValuesQueryState<T> extends SelectQueryState {
866
1136
  readonly value: true;
867
1137
  }
868
1138
  /** State of a query whose rows are records, which `select` and `clearSelect` change. */
869
- type RecordQueryState$1 = SelectQueryState & {
1139
+ type RecordQueryState = SelectQueryState & {
870
1140
  readonly value: false;
871
1141
  };
872
1142
  /** State of a query whose row no relation guarantees, which a filter keeps. */
@@ -892,10 +1162,10 @@ type ColumnValueType<T extends AnyTable, K extends keyof T["columns"]> = {
892
1162
  readonly input: ColumnValues<T>[K];
893
1163
  readonly operators: ColumnOperators<T, K>;
894
1164
  };
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>;
1165
+ /** Type of the value of a query of `E`, an expression or a query of one value that a callback returns. */
1166
+ type OperandValueType<E extends TypedOperand> = {
1167
+ readonly input: TypedOperandInput<E>;
1168
+ readonly operators: TypedOperandOperators<E>;
899
1169
  };
900
1170
  /** 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
1171
  type AggregateState<S extends SelectQueryState, V, Type extends QueryValueType> = ChangeState<S, {
@@ -906,12 +1176,22 @@ type AggregateState<S extends SelectQueryState, V, Type extends QueryValueType>
906
1176
  guaranteed: false;
907
1177
  aggregate: true;
908
1178
  }>;
1179
+ /** State of a query of the value `V` of type `Type` of an aggregate over the rows of a query of state `S`, whose argument is `E`, an expression or a query of one value that a callback returns. */
1180
+ type OperandAggregateState<S extends SelectQueryState, V, Type extends QueryValueType, E> = ChangeState<S, {
1181
+ result: V;
1182
+ valueType: Type;
1183
+ rows: "one";
1184
+ value: true;
1185
+ guaranteed: false;
1186
+ aggregate: true;
1187
+ uses: S["uses"] | OperandUses<E>;
1188
+ }>;
909
1189
  /** State of a query of the number of rows or of values among the rows of a query of state `S`. */
910
1190
  type CountState<S extends SelectQueryState> = AggregateState<S, number, CountValueType>;
911
1191
  /** 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
1192
  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>>;
1193
+ /** State of a query of an aggregate of the values of `E`, an expression or a query of one value that a callback returns, over the rows of a query of state `S`, `NULL` without values other than `NULL`. */
1194
+ type OperandValueAggregateState<S extends SelectQueryState, E extends TypedOperand> = OperandAggregateState<S, OperandValue<E> | null, OperandValueType<E>, E>;
915
1195
  /** Value `V` of a query of values whose `NULL` `coalesce` replaces with fallback `F`. */
916
1196
  type CoalescedValue<V, F> = Exclude<V, null> | Extract<OperandValue<F>, null>;
917
1197
  /** State of a query of many rows, which `limit` and `offset` apply to. */
@@ -936,7 +1216,7 @@ type OneRecordQueryState = OneRowQueryState & {
936
1216
  declare class SelectQuery<out S extends SelectQueryState, out Kind extends SelectQueryKind = "unbound"> {
937
1217
  readonly table: S["table"];
938
1218
  readonly node: QueryNode;
939
- /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
1219
+ /** Relations of the table in the schema the query starts from, which its callbacks receive. */
940
1220
  readonly context: QueryContext;
941
1221
  readonly types: S;
942
1222
  /** Value of the query in an expression, for types only. */
@@ -946,22 +1226,22 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
946
1226
  /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
947
1227
  readonly then: QueryThen<S, Kind>;
948
1228
  constructor(table: S["table"], node: QueryNode,
949
- /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
1229
+ /** Relations of the table in the schema the query starts from, which its callbacks receive. */
950
1230
  context: QueryContext, db?: AnyDb);
951
1231
  /** 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;
1232
+ where<Q extends QueryOf<UnguaranteedQueryState>>(this: Q, filter: QueryWhereFilter<Q["types"]>): Q;
953
1233
  /**
954
1234
  * Adds a filter combined with `AND` with the previous ones; a callback receives the columns and the queries of the relations of the table.
955
1235
  *
956
1236
  * 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`.
957
1237
  */
958
- where<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: WhereFilter<S["table"], S["schema"]>): SelectQuery<FilteredState<S>, Kind>;
1238
+ where<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: QueryWhereFilter<S>): SelectQuery<FilteredState<S>, Kind>;
959
1239
  /** Selects all columns of the table, replacing fields under their keys. */
960
- select<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
1240
+ select<S extends RecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
961
1241
  result: MergeSelection<S["result"], Selectable<S["table"]>>;
962
1242
  }>, Kind>;
963
1243
  /** Selects the listed columns, replacing fields under their keys. */
964
- select<S extends RecordQueryState$1, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, ...keys: K[]): SelectQuery<ChangeState<S, {
1244
+ select<S extends RecordQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, ...keys: K[]): SelectQuery<ChangeState<S, {
965
1245
  result: MergeSelection<S["result"], Pick<Selectable<S["table"]>, K>>;
966
1246
  }>, Kind>;
967
1247
  /**
@@ -971,12 +1251,12 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
971
1251
  * Each expression is decoded with its type, so it must have one: a column, an operator result, or a fragment of `sql(type)`, but not of `sql<T>`.
972
1252
  * A nested query is unbound, such as a query of a relation, or bound to the `Db` that runs the query; its rows become the value of its field as they become the result of an executed query.
973
1253
  */
974
- select<S extends RecordQueryState$1, Kind extends SelectQueryKind, Sel extends Selection>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => Sel): SelectQuery<ChangeState<S, {
1254
+ select<S extends RecordQueryState, Kind extends SelectQueryKind, Sel extends Selection>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => Sel): SelectQuery<ChangeState<S, {
975
1255
  result: MergeSelection<S["result"], SelectionResult<Sel>>;
976
1256
  uses: S["uses"] | SelectionUses<Sel>;
977
1257
  }>, Kind>;
978
1258
  /** Removes all selected fields and keeps the other clauses. */
979
- clearSelect<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1259
+ clearSelect<S extends RecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
980
1260
  result: EmptyRecord;
981
1261
  }>, Kind>;
982
1262
  /**
@@ -1018,15 +1298,18 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1018
1298
  /**
1019
1299
  * Replaces the selected fields with the expression returned by `callback`, limits the query to one row, and returns the value of the expression instead of a record.
1020
1300
  *
1301
+ * `callback` receives the columns and the queries of the relations of the table.
1302
+ * It may return a query of one value, such as of an aggregate of related records, which gives `NULL` without its row.
1021
1303
  * Without a row, it rejects with `NotFoundError`, or with `RequiredRelationError` when a required relation still guarantees the row, such as of `field.form`.
1022
1304
  * An optional or nullable query resolves to `undefined` without a row instead.
1023
1305
  * A `NULL` value is `null`.
1024
1306
  */
1025
- get<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ChangeState<S, {
1026
- result: ExpressionValue<E>;
1027
- valueType: ExpressionValueType<E>;
1307
+ get<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<ChangeState<S, {
1308
+ result: OperandValue<E>;
1309
+ valueType: OperandValueType<E>;
1028
1310
  rows: OneValueRows<S["rows"]>;
1029
1311
  value: true;
1312
+ uses: S["uses"] | OperandUses<E>;
1030
1313
  }>, Kind>;
1031
1314
  /**
1032
1315
  * Replaces the selected fields with a column and returns the value of the column of each row instead of a record.
@@ -1042,13 +1325,16 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1042
1325
  /**
1043
1326
  * Replaces the selected fields with the expression returned by `callback` and returns the value of the expression for each row instead of a record.
1044
1327
  *
1328
+ * `callback` receives the columns and the queries of the relations of the table.
1329
+ * It may return a query of one value, such as of an aggregate of related records, which gives `NULL` without its row.
1045
1330
  * It keeps whether the query returns an array or one value, such as after `take`, and how it handles a missing row, except that a nullable query resolves to `undefined` without a row.
1046
1331
  */
1047
- pluck<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ChangeState<S, {
1048
- result: ExpressionValue<E>;
1049
- valueType: ExpressionValueType<E>;
1332
+ pluck<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<ChangeState<S, {
1333
+ result: OperandValue<E>;
1334
+ valueType: OperandValueType<E>;
1050
1335
  rows: ValueRows<S["rows"]>;
1051
1336
  value: true;
1337
+ uses: S["uses"] | OperandUses<E>;
1052
1338
  }>, Kind>;
1053
1339
  /**
1054
1340
  * Replaces the selected fields with the number of rows of the query and returns the number instead of the rows.
@@ -1058,40 +1344,76 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1058
1344
  count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<CountState<S>, Kind>;
1059
1345
  /** 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. */
1060
1346
  count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<CountState<S>, Kind>;
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. */
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>;
1347
+ /**
1348
+ * 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.
1349
+ *
1350
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1351
+ */
1352
+ count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandAggregateState<S, number, CountValueType, E>, Kind>;
1063
1353
  /** 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. */
1064
1354
  countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<CountState<S>, Kind>;
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. */
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>;
1355
+ /**
1356
+ * 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.
1357
+ *
1358
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1359
+ */
1360
+ countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandAggregateState<S, number, CountValueType, E>, Kind>;
1067
1361
  /** 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`. */
1068
1362
  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>;
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`. */
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>;
1363
+ /**
1364
+ * 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`.
1365
+ *
1366
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1367
+ */
1368
+ min<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandValueAggregateState<S, E>, Kind>;
1071
1369
  /** 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`. */
1072
1370
  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>;
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`. */
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>;
1371
+ /**
1372
+ * 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`.
1373
+ *
1374
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1375
+ */
1376
+ max<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandValueAggregateState<S, E>, Kind>;
1075
1377
  /** 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`. */
1076
1378
  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>;
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`. */
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>;
1379
+ /**
1380
+ * 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`.
1381
+ *
1382
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1383
+ */
1384
+ sum<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandValueAggregateState<S, E>, Kind>;
1079
1385
  /** 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. */
1080
1386
  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>;
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. */
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>;
1387
+ /**
1388
+ * 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.
1389
+ *
1390
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1391
+ */
1392
+ avg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandValueAggregateState<S, E>, Kind>;
1083
1393
  /** 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. */
1084
1394
  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>;
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. */
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>;
1395
+ /**
1396
+ * 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.
1397
+ *
1398
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1399
+ */
1400
+ every<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandValueAggregateState<S, E>, Kind>;
1087
1401
  /** 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`. */
1088
1402
  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>;
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`. */
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>;
1403
+ /**
1404
+ * 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`.
1405
+ *
1406
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1407
+ */
1408
+ some<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<OperandValueAggregateState<S, E>, Kind>;
1091
1409
  /** 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. */
1092
1410
  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>;
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. */
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>;
1411
+ /**
1412
+ * 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.
1413
+ *
1414
+ * `callback` receives the columns and the queries of the relations of the table and returns an expression or a query of one value.
1415
+ */
1416
+ stringAgg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E, delimiter: string): SelectQuery<OperandValueAggregateState<S, E>, Kind>;
1095
1417
  /**
1096
1418
  * 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
1419
  *
@@ -1120,7 +1442,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1120
1442
  * 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
1443
  * 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.
1122
1444
  */
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;
1445
+ orderBy<Q extends QueryOf<RecordQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, selected: SelectedRefs<Q["types"]["result"]>) => OrderTerms): Q;
1124
1446
  /**
1125
1447
  * 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.
1126
1448
  *
@@ -1157,7 +1479,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1157
1479
  * Inserts a record into the table of a query without clauses, such as a table of a `Db`, and resolves to the number of the inserted rows, `1`.
1158
1480
  *
1159
1481
  * A column omitted or given as `undefined` gets its default, so only columns marked with `hasDefault` and nullable columns may be omitted.
1160
- * A value is what the type of its column takes, `null` for `NULL`, or an expression, such as a `sql` fragment.
1482
+ * A value is what the type of its column takes, `null` for `NULL`, an expression, such as a `sql` fragment, or a query of one value, which gives `NULL` without its row.
1161
1483
  * Select the fields that it returns after it, such as `insert(values).get("id")`.
1162
1484
  */
1163
1485
  insert<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, values: InsertValues<S["table"]>): MutationQuery<InitialMutationState<S["table"], S["schema"], "one">, Kind>;
@@ -1168,15 +1490,26 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1168
1490
  * Select the fields that it returns for the inserted rows after it, such as `insertMany(records).select("id", "email")`, and match them to the records by a key rather than by their order, which PostgreSQL does not guarantee.
1169
1491
  */
1170
1492
  insertMany<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, records: readonly InsertValues<S["table"]>[]): MutationQuery<InitialMutationState<S["table"], S["schema"], "many">, Kind>;
1493
+ /**
1494
+ * Updates the rows that the filters of the query choose with the values that `callback` returns, and resolves to the number of the updated rows.
1495
+ *
1496
+ * `callback` receives the columns and the queries of the relations of the changed rows, such as to set a column from another one or from related records, and returns the values of the columns to update; a column omitted or given as `undefined` keeps its value.
1497
+ * A value is what `insert` takes as a value, such as a query of an aggregate of related records.
1498
+ * A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
1499
+ * A query without a filter must call `all` to update every row.
1500
+ * Select the fields that it returns after it, with their values after the update, such as `update(callback).select("id")`.
1501
+ */
1502
+ update<S extends SelectQueryState, Kind extends SelectQueryKind, F extends (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => UpdateValues<S["table"]>>(this: SelectQuery<S, Kind>, callback: F): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"], OperandUses<ReturnType<F>[keyof ReturnType<F>]>>, Kind>;
1171
1503
  /**
1172
1504
  * Updates the rows that the filters of the query choose with the values of `set`, and resolves to the number of the updated rows.
1173
1505
  *
1174
- * `set` gives the values of the columns to update, or is a callback that receives the columns and returns them, such as to set a column from another one; a column omitted or given as `undefined` keeps its value.
1506
+ * `set` gives the values of the columns to update, or is a callback that returns them; a column omitted or given as `undefined` keeps its value.
1507
+ * A value is what `insert` takes as a value.
1175
1508
  * A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
1176
1509
  * A query without a filter must call `all` to update every row.
1177
1510
  * Select the fields that it returns after it, with their values after the update, such as `update(set).select("id")`.
1178
1511
  */
1179
- update<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, set: UpdateSet<S["table"]>): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"]>, Kind>;
1512
+ update<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, set: UpdateSet<S["table"], S["schema"]>): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"]>, Kind>;
1180
1513
  /**
1181
1514
  * Deletes the rows that the filters of the query choose, and resolves to the number of the deleted rows.
1182
1515
  *
@@ -1191,331 +1524,110 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1191
1524
  * Returns the query that `callback` builds from this query, such as one with a conditional clause, or that a helper of `defineHelper` builds with `args`.
1192
1525
  *
1193
1526
  * `callback` receives this query and `args` and returns this query or a query derived from it, which keeps the binding of this query.
1194
- */
1195
- use<Q, Kind extends SelectQueryKind, R extends SelectQuery<any, Kind>, A extends unknown[] = []>(this: Q & SelectQuery<any, Kind>, callback: (query: Q, ...args: A) => R, ...args: A): R;
1196
- /**
1197
- * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1198
- *
1199
- * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1200
- */
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;
1214
- /** Creates a query of the same kind and `Db` with the node changes applied. */
1215
- private derive;
1216
- /**
1217
- * Creates a query of the same kind and `Db` with the node changes applied and then those of `take`, in one derived query.
1218
- *
1219
- * It adds the changes of `take` to `changes`, which must leave the limit as it is.
1220
- */
1221
- private deriveTaken;
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. */
1223
- private deriveAggregate;
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`. */
1225
- private aggregateBy;
1226
- /** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
1227
- private addFilter;
1228
- /** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
1229
- private takeWhere;
1230
- /** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
1231
- private changeOneRow;
1232
- /** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
1233
- private rejectValue;
1234
- /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method or `exists`. */
1235
- private rejectAggregate;
1236
- }
1237
- /** Select query bound to a `Db`, executed by awaiting it; every method returns a query bound to the same `Db`. */
1238
- type BoundSelectQuery<S extends SelectQueryState> = SelectQuery<S, "bound">;
1239
- /** Select query of any state and kind. */
1240
- type AnySelectQuery = SelectQuery<any, SelectQueryKind>;
1241
- /** Type of a record of a query result, or of its value for a query made by `get`, `pluck`, or an aggregate method. */
1242
- type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
1243
- /** Table of a definition such as `defineFilter`: the table itself or a query over it with schema context `C`, such as `schema.form`. */
1244
- type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
1245
- /** Starts a query over a new occurrence of the table. */
1246
- declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T>>;
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;
1252
- }
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)>>;
1258
- }
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;
1275
- /** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
1276
- interface RecordQueryState<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
1277
- readonly result: R;
1278
- readonly rows: "one";
1279
- readonly value: false;
1280
- readonly uses: U;
1281
- }
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. */
1283
- type SelectionState<Sel extends Selection> = RecordQueryState<MergeSelection<EmptyRecord, SelectionResult<Sel>>, SelectionUses<Sel>>;
1284
- /**
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.
1286
- *
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`.
1288
- * A bound query executes on its `Db` when awaited.
1289
- */
1290
- declare class RecordQuery<out S extends RecordQueryState, out Kind extends SelectQueryKind = "unbound"> {
1291
- readonly node: RecordQueryNode;
1292
- readonly types: S;
1293
- /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
1294
- readonly db: QueryDb<Kind>;
1295
- /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
1296
- readonly then: QueryThen<S, Kind>;
1297
- constructor(node: RecordQueryNode, db?: AnyDb);
1298
- /**
1299
- * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1300
- *
1301
- * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1302
- */
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;
1306
- }
1307
- /** Query of `$select` of any state and kind. */
1308
- type AnyRecordQuery = RecordQuery<any, SelectQueryKind>;
1309
- declare const schemaBrand: unique symbol;
1310
- /** Key of the relation definitions of a schema, which composition reads. */
1311
- declare const schemaRelations: unique symbol;
1312
- /** Tables by their keys; a key must not start with `$`, which is reserved for schema and `Db` members. */
1313
- type Tables = Record<string, AnyTable>;
1314
- /**
1315
- * Immutable collection of tables and their relations with query entry points.
1316
- *
1317
- * A schema is not bound to a database, so queries built from it can be defined at module level.
1318
- * A `Db` can execute such a query if its schema contains the tables and the selected relations of the query and every bound nested query belongs to that `Db`.
1319
- */
1320
- type Schema<T extends Tables, R extends SchemaRelations = EmptyRecord> = SchemaEntries<T, R> & SchemaMembers<T, R>;
1321
- /** Query entry points; each access starts a query over a new table occurrence. */
1322
- type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
1323
- /** Members of a schema that composition reads: its tables and the relations of its tables. */
1324
- interface SchemaContents<T extends Tables, R extends SchemaRelations> {
1325
- readonly [schemaBrand]: true;
1326
- /** Tables of the schema by their keys. */
1327
- readonly $tables: T;
1328
- /** Relation definitions by table key and relation name. */
1329
- readonly [schemaRelations]: R;
1330
- }
1331
- interface SchemaMembers<T extends Tables, R extends SchemaRelations> extends SchemaContents<T, R> {
1332
- /**
1333
- * Creates a schema of the same tables with the relations of `relations` added, declared with `many` and `one` by their names under the keys of their tables.
1334
- *
1335
- * A relation refers to a table of the schema by columns of SQL types that `=` compares; a relation that the schema already has is rejected.
1336
- */
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>>>;
1338
- /**
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.
1340
- *
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.
1342
- */
1343
- $select<Sel extends Selection>(selection: Sel): RecordQuery<SelectionState<Sel>>;
1344
- }
1345
- /** Schema of any tables and relations. */
1346
- type AnySchema = SchemaContents<Tables, SchemaRelations>;
1347
- /** Part of a schema definition: an object of tables by their keys, or a schema whose tables and relations it includes. */
1348
- type SchemaPart = Tables | AnySchema;
1349
- /**
1350
- * Tables of the parts of a schema definition by their keys.
1351
- *
1352
- * A part typed as a union gives a union of tables, and parts of an array of unknown length give no tables, since any of them may be missing.
1353
- */
1354
- type SchemaTables<P extends readonly SchemaPart[]> = ComposeParts<P>["tables"] extends (infer T extends Tables) ? { [K in keyof T]: T[K]; } : never;
1355
- /** Relations of the parts of a schema definition by table key and relation name, read as `SchemaTables` reads the tables. */
1356
- type SchemaPartRelations<P extends readonly SchemaPart[]> = ComposeParts<P>["relations"] extends (infer R extends SchemaRelations) ? MergeRelations<R> : never;
1357
- /** Tables and relations of the parts of a schema definition, intersected. */
1358
- interface PartContents {
1359
- readonly tables: Tables;
1360
- readonly relations: SchemaRelations;
1361
- }
1362
- type ComposeParts<P extends readonly SchemaPart[], Composed extends PartContents = {
1363
- tables: EmptyRecord;
1364
- relations: EmptyRecord;
1365
- }> = P extends readonly [infer First extends SchemaPart, ...infer Rest extends readonly SchemaPart[]] ? ComposeParts<Rest, Composed & ReadPart<First>> : P extends readonly [...infer Rest extends readonly SchemaPart[], infer Last extends SchemaPart] ? ComposeParts<Rest, Composed & ReadPart<Last>> : Composed;
1366
- type ReadPart<P extends SchemaPart> = P extends SchemaContents<infer T, any> ? {
1367
- tables: T;
1368
- relations: P[typeof schemaRelations];
1369
- } : {
1370
- tables: P;
1371
- relations: EmptyRecord;
1372
- };
1373
- /**
1374
- * Defines a schema of the tables of `parts`, keyed by their names in queries.
1375
- *
1376
- * A part is an object of tables by their keys or another schema, whose tables and relations the new schema includes as they are, so queries built from that schema run on the new one.
1377
- * A key of two different tables, a table under two keys, and two different definitions of a relation of a table are rejected; the same table under the same key or the same relation in several parts is one.
1378
- */
1379
- declare function defineSchema<P extends SchemaPart[]>(...parts: P): Schema<SchemaTables<P>, SchemaPartRelations<P>>;
1380
- declare const sourceTable: unique symbol;
1381
- declare const sourceKey: unique symbol;
1382
- /** Runtime mark of the declarations of `many` and `one`. */
1383
- declare const declarationBrand: unique symbol;
1384
- /** Kind of a relation: `many` related records, or `one` related record at most. */
1385
- type RelationKind = "many" | "one";
1386
- /** Relation of a table of a schema to the records of table `Target`, which has key `TargetKey` in the schema. */
1387
- interface Relation<Kind extends RelationKind = RelationKind, Target extends AnyTable = AnyTable, TargetKey extends string = string, Required extends boolean = boolean> {
1388
- readonly kind: Kind;
1389
- readonly target: Target;
1390
- readonly targetKey: TargetKey;
1391
- /** Whether every record of the table has its related record, so that a query of a relation `one` without a filter rejects without it rather than giving `null`; `false` for a relation `many`. */
1392
- readonly required: Required;
1527
+ */
1528
+ use<Q, Kind extends SelectQueryKind, R extends SelectQuery<any, Kind>, A extends unknown[] = []>(this: Q & SelectQuery<any, Kind>, callback: (query: Q, ...args: A) => R, ...args: A): R;
1529
+ /**
1530
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1531
+ *
1532
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1533
+ */
1534
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1535
+ /**
1536
+ * 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`.
1537
+ *
1538
+ * It rejects a query of records or of rows `many`, which `ScalarQuery` rejects in types.
1539
+ */
1540
+ [operandNode](): ExpressionNode;
1541
+ /**
1542
+ * Returns the node of the query as the values of `in`, which lowering replaces with its statement.
1543
+ *
1544
+ * It rejects a query of records, which `ValuesQuery` rejects in types.
1545
+ */
1546
+ [valuesQueryNode](): NestedQueryNode;
1547
+ /** Creates a query of the same kind and `Db` with the node changes applied. */
1548
+ private derive;
1549
+ /**
1550
+ * Creates a query of the same kind and `Db` with the node changes applied and then those of `take`, in one derived query.
1551
+ *
1552
+ * It adds the changes of `take` to `changes`, which must leave the limit as it is.
1553
+ */
1554
+ private deriveTaken;
1555
+ /** 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. */
1556
+ private deriveAggregate;
1557
+ /** Creates the query of the aggregate of `method` over `arg`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value; `delimiter` is the delimiter of `stringAgg`. */
1558
+ private aggregateBy;
1559
+ /** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
1560
+ private addFilter;
1561
+ /** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
1562
+ private takeWhere;
1563
+ /** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
1564
+ private changeOneRow;
1565
+ /** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
1566
+ private rejectValue;
1567
+ /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method or `exists`. */
1568
+ private rejectAggregate;
1393
1569
  }
1570
+ /** Select query bound to a `Db`, executed by awaiting it; every method returns a query bound to the same `Db`. */
1571
+ type BoundSelectQuery<S extends SelectQueryState> = SelectQuery<S, "bound">;
1572
+ /** Select query of any state and kind. */
1573
+ type AnySelectQuery = SelectQuery<any, SelectQueryKind>;
1574
+ /** Type of a record of a query result, or of its value for a query made by `get`, `pluck`, or an aggregate method. */
1575
+ type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
1576
+ /** Table of a definition such as `defineExpression`: the table itself or a query over it with schema context `C`, such as `schema.form`. */
1577
+ type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
1578
+ /** Starts a query over a new occurrence of the table. */
1579
+ declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T>>;
1580
+ /** 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. */
1581
+ type TypedOperand = TypedExpression | TypedScalarQuery;
1582
+ /** Values that the type of the first operand `F` encodes. */
1583
+ type TypedOperandInput<F> = F extends TypedScalarQuery ? F["types"]["valueType"]["input"] : ExpressionInput<F>;
1584
+ /** Operators of the type of the first operand `F`. */
1585
+ type TypedOperandOperators<F> = F extends TypedScalarQuery ? F["types"]["valueType"]["operators"] : F extends TypedExpression ? ExpressionOperators<F> : never;
1586
+ /** 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. */
1587
+ type FollowingOperand<F> = Operand<OperandValue<F>, TypedOperandInput<F>>;
1588
+ /** `null` when every operand can be `NULL`: the first operand `F` and the following operands `R`. */
1589
+ 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;
1590
+ /** 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`. */
1591
+ type NullSkippingResult<F, R extends readonly unknown[]> = Expression<Exclude<OperandValue<F>, null> | NullOfEveryOperand<F, R>, TypedOperandOperators<F>, TypedOperandInput<F>>;
1394
1592
  /**
1395
- * Relation of a table of a schema as `$relations` defines it: the columns of its keys, compared by SQL `=` in order.
1593
+ * Returns the first of its operands other than `NULL`, such as `coalesce(field.hint, "")`, as an expression usable wherever a column is.
1396
1594
  *
1397
- * Composition includes a definition as it is, so a relation that several parts include is one definition.
1595
+ * `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`.
1596
+ * A query without its row is `NULL` here, unlike with the method `coalesce` of a query, which keeps a missing row missing.
1398
1597
  */
1399
- interface RelationDefinition extends Relation {
1400
- readonly name: string;
1401
- /** Key of the source table. */
1402
- readonly key: string;
1403
- readonly source: AnyTable;
1404
- readonly from: readonly string[];
1405
- readonly to: readonly string[];
1406
- }
1407
- /** Relation `N` of the table under key `K` of a schema, of type `R`, whose records a query selects. */
1408
- interface UsedRelation<K extends string = string, N extends string = string, R extends Relation = Relation> {
1409
- readonly key: K;
1410
- readonly name: N;
1411
- readonly relation: R;
1412
- }
1413
- /** Relations of schema relations `R` that the queries of a `Db` of the schema may select. */
1414
- type UsableRelation<R extends SchemaRelations> = { [K in keyof R & string]: { [N in keyof R[K] & string]: UsedRelation<K, N, R[K][N]>; }[keyof R[K] & string]; }[keyof R & string];
1415
- /** Relations of the tables of a schema by table key and relation name. */
1416
- type SchemaRelations = {
1417
- readonly [key: string]: TableRelations;
1418
- };
1419
- /** Relations of a table of a schema by relation name. */
1420
- type TableRelations = {
1421
- readonly [name: string]: Relation;
1422
- };
1598
+ declare function coalesce<F extends TypedOperand, const R extends readonly FollowingOperand<F>[]>(first: F, ...rest: R): NullSkippingResult<F, R>;
1423
1599
  /**
1424
- * Declaration of a relation by `many` or `one`, which `$relations` of a schema defines for a table of type `Source` with key `From` of the source table.
1600
+ * Returns the largest of its operands, skipping `NULL`, which is the result only when every operand is `NULL`.
1425
1601
  *
1426
- * `Source` and `From` only type the keys of the source table.
1602
+ * `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`.
1427
1603
  */
1428
- interface RelationDeclaration<Kind extends RelationKind, Source extends AnyTable, Target extends AnyTable, From = unknown, Required extends boolean = boolean> {
1429
- readonly [declarationBrand]: true;
1430
- readonly kind: Kind;
1431
- readonly target: Target;
1432
- readonly from: readonly string[];
1433
- readonly to: readonly string[];
1434
- readonly required: Required;
1435
- readonly [sourceTable]?: (source: Source) => void;
1436
- readonly [sourceKey]?: From;
1437
- }
1438
- /** Column key of table `T` whose type has SQL `=`, which a relation can compare. */
1439
- type EqualityKey<T extends AnyTable> = { [K in keyof T["columns"]]: HasEquality<ColumnOperators<T, K>> extends true ? K : never; }[keyof T["columns"]] & string;
1440
- /** Key of a relation in table `T`: a column key, or a non-empty list of them for a composite key. */
1441
- type RelationKey<T extends AnyTable> = EqualityKey<T> | readonly [EqualityKey<T>, ...EqualityKey<T>[]];
1442
- /** Key of table `T` with as many columns as key `From`. */
1443
- type MatchingKey<T extends AnyTable, From> = From extends string ? EqualityKey<T> : { readonly [I in keyof From]: EqualityKey<T>; };
1444
- /** Keys of a relation: the columns `from` of the source table equal the columns `to` of the target table, in order. */
1445
- interface RelationKeys<Target extends AnyTable, From> {
1446
- readonly from: From;
1447
- readonly to: MatchingKey<Target, From>;
1448
- }
1449
- /** Keys of a relation `one`, as in `RelationKeys`, and whether the relation is required. */
1450
- interface OneRelationKeys<From, To> {
1451
- readonly from: From;
1452
- readonly to: To;
1453
- /** Whether every record has its related record, such as by a foreign key on columns `from` that are not nullable, so that a query of the relation without a filter rejects without it rather than giving `null`. */
1454
- readonly required?: boolean;
1455
- }
1456
- /** Members of the keys `K` of a relation `one` with only `required` typed, so that a call infers `K` with `required` as optional as it is, and reports a wrong key at its own member. */
1457
- type RequiredMember<K> = { readonly [P in keyof K]: P extends "required" ? K[P] : unknown; };
1458
- /** Whether the keys `K` of a relation `one` make it required: only where they set `required` to `true`, and `boolean` where `required` may be `true` or missing, such as `required?: true`. */
1459
- type DeclaredRequiredOf<K> = K extends unknown ? "required" extends keyof K ? K extends {
1460
- readonly required: infer Required;
1461
- } ? IsTrue<Required> : IsTrue<K["required" & keyof K] | undefined> : false : never;
1462
- /** `true` for `true`, and `false` for other values, such as `false` and `undefined`; a union gives the union of their results. */
1463
- type IsTrue<T> = T extends true ? true : false;
1464
- /** Declarations of `$relations` of a schema of tables `T`: relations by name, for tables by their keys. */
1465
- type RelationDeclarations<T extends Tables> = { readonly [K in keyof T]?: {
1466
- readonly [name: string]: RelationDeclaration<RelationKind, T[K], T[keyof T]>;
1467
- }; };
1604
+ declare function greatest<F extends TypedOperand, const R extends readonly FollowingOperand<F>[]>(first: F, ...rest: R): NullSkippingResult<F, R>;
1468
1605
  /**
1469
- * Declarations `D` of `$relations` checked by the names they use: relations of the tables of `T` under their keys, and no other keys.
1606
+ * Returns the smallest of its operands, skipping `NULL`, which is the result only when every operand is `NULL`.
1470
1607
  *
1471
- * Declarations under the names of `D` get their source table from this type even where the index signature of `RelationDeclarations` gives way to a member of `Object`, such as for a relation named `toString`.
1472
- * A relation name must not be a column key of its table or start with `$`, since the references that the callback of `select` gets have both.
1608
+ * `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`.
1473
1609
  */
1474
- type CheckDeclarations<T extends Tables, D> = { readonly [K in keyof D]: [TableKey<T, K>] extends [never] ? never : undefined extends D[K] ? D[K] : { readonly [N in keyof D[K]]: `${N & (string | number)}` extends ReservedName<T[TableKey<T, K>]> ? never : RelationDeclaration<RelationKind, T[TableKey<T, K>], T[keyof T], RelationKey<T[TableKey<T, K>]>>; }; };
1475
- /** Names that a relation of table `T` cannot have: the keys of its columns, and names starting with `$`. */
1476
- type ReservedName<T extends AnyTable> = `${keyof T["columns"] & (string | number)}` | `$${string}`;
1477
- /** Key of tables `T` written as key `K`, such as `1` for `"1"`, as object keys are strings at runtime. */
1478
- type TableKey<T extends Tables, K> = { [P in keyof T]: `${P & (string | number)}` extends `${K & (string | number)}` ? P : never; }[keyof T];
1479
- /** Relations that declarations `D` of a schema of tables `T` define, by table key and relation name, as strings like the keys of objects. */
1480
- type DeclaredRelations<T extends Tables, D> = { [K in keyof D as K extends number ? `${K}` : K]: { [N in keyof D[K] as N extends number ? `${N}` : N]: D[K][N] extends RelationDeclaration<infer Kind, never, infer Target, unknown, infer Required> ? Relation<Kind, Target, KeyOfTable<T, Target>, Required> : never; }; };
1481
- /** Column key of relation key `K`: the key itself, or a column of a composite key. */
1482
- type RelationColumn<K> = K extends readonly unknown[] ? K[number] : K;
1483
- /** Check of key `To` of a relation `one` that rejects it when its columns include no key of table `Target`, as far as the types tell. */
1484
- type TargetKeyCheck<Target extends AnyTable, To> = [ContainsKey<Target, RelationColumn<To>>] extends [false] ? {
1485
- readonly to: MissingKey<KeyOf<Target["keys"]>>;
1486
- } : unknown;
1487
- /** Type that a key `to` of a relation `one` without a key of its target is checked against, naming the keys of the target. */
1488
- interface MissingKey<Keys> {
1489
- readonly "columns to must include a key of the target": Keys;
1490
- }
1491
- /** Key of table `Target` among tables `T`, as a string like the keys of objects. */
1492
- type KeyOfTable<T extends Tables, Target> = { [K in keyof T]: [T[K]] extends [Target] ? [Target] extends [T[K]] ? K extends number ? `${K}` : K & string : never : never; }[keyof T];
1493
- /** Relations of `R` by table key, with the relations under the same key merged. */
1494
- type MergeRelations<R> = { [K in keyof R]: { [N in keyof R[K]]: R[K][N]; }; };
1495
- /** Relations of the schema that a query starts from, by table key, and the key of the table of the query there. */
1496
- interface SchemaContext<R extends SchemaRelations = SchemaRelations, K extends string = string> {
1497
- readonly relations: R;
1498
- readonly key: K;
1499
- }
1500
- /** Schema context of a query whose table has no relations, such as one of `from(table)`. */
1501
- type NoRelations = SchemaContext<EmptyRecord, string>;
1502
- /** Schema context of the queries of the table under key `K` of a schema of relations `R`, whose keys are strings, as object keys are at runtime. */
1503
- type TableContext<R extends SchemaRelations, K> = K extends keyof R ? [keyof R[K]] extends [never] ? NoRelations : SchemaContext<R, K & string> : K extends number ? TableContext<R, `${K}`> : NoRelations;
1610
+ declare function least<F extends TypedOperand, const R extends readonly FollowingOperand<F>[]>(first: F, ...rest: R): NullSkippingResult<F, R>;
1611
+ /** Condition of a branch of `caseWhen`: a predicate, or a query of one Boolean value, such as of `exists`. */
1612
+ type CaseCondition = Predicate | ScalarQuery<boolean | null>;
1613
+ /** 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`. */
1614
+ type CaseValue<T, I> = Operand<T, I> | null;
1615
+ /** Branch of `caseWhen`: a condition and the value of the result when it holds. */
1616
+ type CaseBranch<T, I> = readonly [condition: CaseCondition, value: CaseValue<T, I>];
1617
+ /** Value of `caseWhen` of a type of values `T` whose branches and fallback have the values `V`, of which one gives the result. */
1618
+ type CaseResult<T, V> = Exclude<T, null> | Extract<OperandValue<V>, null>;
1504
1619
  /**
1505
- * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1620
+ * Returns the value of the first branch whose condition holds, as a SQL `CASE` expression, or `NULL` when none holds.
1506
1621
  *
1507
- * A composite key lists its columns in arrays of the same length.
1622
+ * `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.
1508
1623
  */
1509
- declare function many<Source extends AnyTable, Target extends AnyTable, const From extends RelationKey<Source>>(target: Target, keys: RelationKeys<Target, From>): RelationDeclaration<"many", Source, Target, From, false>;
1624
+ 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>;
1510
1625
  /**
1511
- * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1626
+ * Returns the value of the first branch whose condition holds, as a SQL `CASE` expression, or `otherwise` when none holds.
1512
1627
  *
1513
- * A composite key lists its columns in arrays of the same length.
1514
- * The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
1515
- * Without the record, a query of the relation gives `null`, and a query of a relation declared with `required: true` rejects unless it filters the record.
1516
- * Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
1628
+ * `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.
1517
1629
  */
1518
- declare function one<Source extends AnyTable, Target extends AnyTable, const From extends RelationKey<Source>, const To extends MatchingKey<Target, From>, const Keys extends object = EmptyRecord>(target: Target, keys: OneRelationKeys<From, To> & RequiredMember<Keys> & TargetKeyCheck<Target, To>): RelationDeclaration<"one", Source, Target, From, NoInfer<DeclaredRequiredOf<Keys>>>;
1630
+ 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>;
1519
1631
  /**
1520
1632
  * State in types of a query that inserts, updates, or deletes rows: its table and the relations of its schema, the rows mode of the rows it changes, and its result, which is their number until a selection returns their fields.
1521
1633
  *
@@ -1529,8 +1641,8 @@ interface MutationQueryState extends QueryState {
1529
1641
  /** Whether the query returns the fields of the rows it changes rather than their number. */
1530
1642
  readonly returning: boolean;
1531
1643
  }
1532
- /** State of a query that inserts, updates, or deletes rows of table `T` with schema context `C` in rows mode `Rows` and returns their number. */
1533
- interface InitialMutationState<T extends AnyTable, C extends SchemaContext, Rows extends ResultRows> extends MutationQueryState {
1644
+ /** State of a query that inserts, updates, or deletes rows of table `T` with schema context `C` in rows mode `Rows` and returns their number, whose values select records of relations `U`. */
1645
+ interface InitialMutationState<T extends AnyTable, C extends SchemaContext, Rows extends ResultRows, U extends UsedRelation = never> extends MutationQueryState {
1534
1646
  readonly table: T;
1535
1647
  readonly schema: C;
1536
1648
  readonly changed: Rows;
@@ -1538,7 +1650,7 @@ interface InitialMutationState<T extends AnyTable, C extends SchemaContext, Rows
1538
1650
  readonly result: number;
1539
1651
  readonly rows: "one";
1540
1652
  readonly value: true;
1541
- readonly uses: never;
1653
+ readonly uses: U;
1542
1654
  }
1543
1655
  /** State `S` of a mutation with the parts of `Changes` replaced. */
1544
1656
  type ChangeMutationState<S extends MutationQueryState, Changes extends Partial<MutationQueryState>> = { readonly [K in keyof MutationQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
@@ -1569,6 +1681,14 @@ type ValueState$1<S extends MutationQueryState, V, Rows extends ResultRows> = Ch
1569
1681
  value: true;
1570
1682
  returning: true;
1571
1683
  }>;
1684
+ /** State of a mutation of state `S` that returns the value of `E`, an expression or a query of one value that a callback returns, of each row it changes in rows mode `Rows`. */
1685
+ type OperandState<S extends MutationQueryState, E extends TypedOperand, Rows extends ResultRows> = ChangeMutationState<S, {
1686
+ result: OperandValue<E>;
1687
+ rows: Rows;
1688
+ value: true;
1689
+ returning: true;
1690
+ uses: S["uses"] | OperandUses<E>;
1691
+ }>;
1572
1692
  /**
1573
1693
  * Immutable query of state `S` that inserts, updates, or deletes rows, unbound or bound to a `Db`.
1574
1694
  *
@@ -1579,7 +1699,7 @@ type ValueState$1<S extends MutationQueryState, V, Rows extends ResultRows> = Ch
1579
1699
  declare class MutationQuery<out S extends MutationQueryState, out Kind extends SelectQueryKind = "unbound"> {
1580
1700
  readonly table: S["table"];
1581
1701
  readonly node: MutationNode;
1582
- /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
1702
+ /** Relations of the table in the schema the query starts from, which its callbacks receive. */
1583
1703
  readonly context: QueryContext;
1584
1704
  readonly types: S;
1585
1705
  /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
@@ -1587,7 +1707,7 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
1587
1707
  /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
1588
1708
  readonly then: QueryThen<S, Kind>;
1589
1709
  constructor(table: S["table"], node: MutationNode,
1590
- /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
1710
+ /** Relations of the table in the schema the query starts from, which its callbacks receive. */
1591
1711
  context: QueryContext, db?: AnyDb);
1592
1712
  /** Returns all columns of each changed row, replacing fields under their keys, instead of the number of the rows. */
1593
1713
  select<S extends RecordMutationState, Kind extends SelectQueryKind>(this: MutationQuery<S, Kind>, all: "*"): MutationQuery<RecordsState<S, Selectable<S["table"]>>, Kind>;
@@ -1609,13 +1729,18 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
1609
1729
  /**
1610
1730
  * Returns the value of the expression that `callback` returns for the changed row instead of the number of the rows, in a query that changes one row, such as of `insert` or `find`.
1611
1731
  *
1732
+ * `callback` receives what the callback of `select` receives, and may return a query of one value, which gives `NULL` without its row.
1612
1733
  * A query of a nullable row resolves to `undefined` without the row.
1613
1734
  */
1614
- get<S extends OneRowMutationState, Kind extends SelectQueryKind, E extends TypedExpression>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): MutationQuery<ValueState$1<S, ExpressionValue<E>, OneValueRows<S["changed"]>>, Kind>;
1735
+ get<S extends OneRowMutationState, Kind extends SelectQueryKind, E extends TypedOperand>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): MutationQuery<OperandState<S, E, OneValueRows<S["changed"]>>, Kind>;
1615
1736
  /** Returns the value of a column of each changed row instead of the number of the rows, keeping whether the query returns an array or one value. */
1616
1737
  pluck<S extends MutationQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: MutationQuery<S, Kind>, key: K): MutationQuery<ValueState$1<S, Selectable<S["table"]>[K], ValueRows<S["changed"]>>, Kind>;
1617
- /** Returns the value of the expression that `callback` returns for each changed row instead of the number of the rows, keeping whether the query returns an array or one value. */
1618
- pluck<S extends MutationQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): MutationQuery<ValueState$1<S, ExpressionValue<E>, ValueRows<S["changed"]>>, Kind>;
1738
+ /**
1739
+ * Returns the value of the expression that `callback` returns for each changed row instead of the number of the rows, keeping whether the query returns an array or one value.
1740
+ *
1741
+ * `callback` receives what the callback of `select` receives, and may return a query of one value, which gives `NULL` without its row.
1742
+ */
1743
+ pluck<S extends MutationQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): MutationQuery<OperandState<S, E, ValueRows<S["changed"]>>, Kind>;
1619
1744
  /**
1620
1745
  * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1621
1746
  *
@@ -1626,7 +1751,7 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
1626
1751
  [operandNode](): never;
1627
1752
  /** Creates a mutation of the same kind and `Db` with the node changes applied. */
1628
1753
  private derive;
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. */
1754
+ /** Creates the mutation that returns the value of `arg` of `method`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value, of each changed row. */
1630
1755
  private deriveValue;
1631
1756
  }
1632
1757
  /** Query of any state and kind that inserts, updates, or deletes rows. */
@@ -1988,7 +2113,7 @@ type Db<T extends Tables, R extends SchemaRelations = EmptyRecord> = DbEntries<T
1988
2113
  /** Bound query entry points; each access starts a query over a new table occurrence. */
1989
2114
  type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
1990
2115
  /** Bound or unbound query over a table of `T`, of `$select`, or that changes the rows of a table of `T`, that selects records only of relations of `R`, or a query of SQL text. */
1991
- type DbQuery<T extends Tables, R extends SchemaRelations> = QueryOf<DbQueryState<T[keyof T], UsableRelation<R>>> | RecordQuery<RecordQueryState<unknown, UsableRelation<R>>, SelectQueryKind> | MutationQuery<DbMutationState<T[keyof T], UsableRelation<R>>, SelectQueryKind> | SqlQuery<SqlQueryState>;
2116
+ type DbQuery<T extends Tables, R extends SchemaRelations> = QueryOf<DbQueryState<T[keyof T], UsableRelation<R>>> | RecordQuery<RecordQueryState$1<unknown, UsableRelation<R>>, SelectQueryKind> | MutationQuery<DbMutationState<T[keyof T], UsableRelation<R>>, SelectQueryKind> | SqlQuery<SqlQueryState>;
1992
2117
  /** State of a query that a `Db` can execute: over table `T`, selecting records only of relations `U`. */
1993
2118
  interface DbQueryState<T extends AnyTable, U extends UsedRelation> extends QueryStateOf<T> {
1994
2119
  readonly uses: U;
@@ -2355,13 +2480,13 @@ interface BaseOperators {
2355
2480
  }
2356
2481
  /** Operators of ordered types: those of `equalityOperators`, and `lt`, `lte`, `gt`, and `gte` comparing with operands of the expression type. */
2357
2482
  declare const orderingOperators: {
2483
+ eq: EqualityOperator<ComparisonSignature>;
2484
+ ne: EqualityOperator<ComparisonSignature>;
2485
+ in: EqualityOperator<InSignature>;
2358
2486
  lt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2359
2487
  lte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2360
2488
  gt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2361
2489
  gte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
2362
- eq: EqualityOperator<ComparisonSignature>;
2363
- ne: EqualityOperator<ComparisonSignature>;
2364
- in: EqualityOperator<InSignature>;
2365
2490
  };
2366
2491
  /** Operators of the built-in types of numbers: those of `orderingOperators`. */
2367
2492
  type NumberTypeOperators = MergeOperators<NoOperators, typeof orderingOperators>;
@@ -2398,57 +2523,47 @@ declare const textOperators: TextOperators;
2398
2523
  declare const TRUE: Expression<boolean>;
2399
2524
  /** Condition that never holds, such as for a branch of `or` built in code: `or(check, isAdmin ? other : FALSE)`. */
2400
2525
  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
2526
  /**
2427
- * Returns the smallest of its operands, skipping `NULL`, which is the result only when every operand is `NULL`.
2527
+ * Defines a reusable expression of a table, which the callbacks of queries over the table call with their columns and any further arguments, such as to filter by it and select it in one query.
2428
2528
  *
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`.
2529
+ * `expression` returns an expression or a query of one value, and a call has its type, so that a selected field has its values and an expression has its operators.
2530
+ * 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 queries whose schema has them can call it.
2531
+ * Defined with a table, it receives only the columns, and every query of the table can call it, also one without relations, such as of `from`.
2430
2532
  */
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>;
2533
+ declare function defineExpression<T extends AnyTable, R extends AnyExpression | ScalarQuery, A extends unknown[], C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, expression: (columns: ColumnRefs<T> & RelationRefs<C>, ...args: A) => R): (columns: ColumnRefs<T> & RelationRefs<C>, ...args: A) => R;
2534
+ /** Keys of the columns among references `R`, without the queries of relations. */
2535
+ type ColumnRefKey<R> = { [K in keyof R]: R[K] extends AnyExpression ? K : never; }[keyof R];
2536
+ /** Type that a key of the object of `matches` is checked against when it is not a column of its references, naming the columns. */
2537
+ interface NotAColumn<Keys> {
2538
+ readonly "keys must be columns of the references": Keys;
2539
+ }
2540
+ /** Value of column `E` in the object of `matches`: an operand of its `eq`, or `null` when its input type includes it. */
2541
+ type MatchValue<E> = (E extends TypedExpression ? ExpressionOperators<E> extends {
2542
+ readonly eq: EqualityOperator<ComparisonSignature>;
2543
+ } ? Operand<ExpressionValue<E>, ExpressionInput<E>> : EqOperand<E> : EqOperand<E>) | (null extends ExpressionInput<E> ? null : never);
2440
2544
  /**
2441
- * Returns the value of the first branch whose condition holds, as a SQL `CASE` expression, or `NULL` when none holds.
2545
+ * Check of object `V` of `matches` against references `R`, which gives each of its keys the value of its column.
2442
2546
  *
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.
2547
+ * It maps the keys of the object rather than those of the references, so that a call reads the operands of only the columns it matches.
2444
2548
  */
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>;
2549
+ type MatchCheck<R, V> = { readonly [K in keyof V]: K extends ColumnRefKey<R> ? MatchValue<R[K]> : NotAColumn<ColumnRefKey<R>>; };
2550
+ /** `null` that matching expression `E` with value `V` adds to the result; `never` when `V` is `null`, since `IS NULL` is never `NULL`. */
2551
+ type MatchNull<E, V> = V extends null ? never : E extends TypedExpression ? ExpressionOperators<E> extends {
2552
+ readonly eq: EqualityOperator<ComparisonSignature>;
2553
+ } ? null extends ExpressionValue<E> | OperandValue<V> ? null : never : CustomEqNull<E> : CustomEqNull<E>;
2554
+ /** `null` of the result of a custom `eq` of expression `E`. */
2555
+ type CustomEqNull<E> = E extends {
2556
+ eq: (...args: never[]) => AnyExpression<infer O>;
2557
+ } ? Extract<O, null> : never;
2558
+ /** Value of `matches` of object `V` over references `R`: `boolean`, or also `null` when a comparison of a column can be `NULL`. */
2559
+ type MatchResult<R, V> = boolean | (V extends unknown ? { [K in keyof V]-?: K extends keyof R ? MatchNull<R[K], V[K]> : never; }[keyof V] : never);
2446
2560
  /**
2447
- * Returns the value of the first branch whose condition holds, as a SQL `CASE` expression, or `otherwise` when none holds.
2561
+ * Creates a Boolean expression of an object of column values over the columns that a callback of a query receives, such as `matches(form, { published: true })`.
2448
2562
  *
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.
2563
+ * Each value matches its column as in an object passed to `where`: `null` by `IS NULL`, and another value by the `eq` operator of the column; all of them must match, and an empty object is `TRUE`.
2564
+ * Unlike such an object in `and`, `or`, and `not`, the expression refers to the columns it receives whichever query it is used in, and applies wherever an expression does, such as in `select`.
2450
2565
  */
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>;
2566
+ declare function matches<R extends object, const V extends { readonly [K in ColumnRefKey<R>]?: unknown; }>(columns: R, values: V & MatchCheck<R, V>): Expression<MatchResult<R, V>>;
2452
2567
  /**
2453
2568
  * 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
2569
  *
@@ -2568,4 +2683,4 @@ declare function identifier(...names: [string, ...string[]]): UntypedExpression;
2568
2683
  */
2569
2684
  declare function param<Output, Input, O extends OperatorDefinitions>(type: Type<Output, Input, O, any>, value: Input): Expression<Output, O, Input>;
2570
2685
  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 };
2686
+ export { InitialSqlQueryState as $, EmptyRecord as $n, KeyKind as $r, Predicate as $t, AnyDb as A, SchemaPartRelations as An, RequiredRelationError as Ar, UpdateSet as At, TransactionCoordinator as B, MergeSelection as Bn, AnyType as Br, desc as Bt, orderingOperators as C, UsableRelation as Cn, Selectable as Cr, ScalarQuery as Ct, ExpressionOperators as D, AnySchema as Dn, ToColumns as Dr, from as Dt, Expression as E, one as En, TableOptions as Er, ValuesQuery as Et, DbQueryState as F, RecordQuery as Fn, Driver as Fr, OrderTerm as Ft, TestHooks as G, FilteredRows as Gn, TypeOperators as Gr, EqValue as Gt, PendingTestFixture as H, Selection as Hn, TextValue as Hr, KeyCheck as Ht, Database as I, RecordQueryState$1 as In, DriverResult as Ir, OrderTerms as It, AnyQuery as J, QueryResult as Jn, TypeTransform as Jr, WhereFilter as Jt, TestTransactionOptions as K, OneRow as Kn, TypeOptions as Kr, WhereCallback as Kt, DatabaseOptions as L, SelectionState as Ln, SqlStatement as Lr, Ordering as Lt, Db as M, Tables as Mn, ResultMode as Mr, OrderColumns as Mt, DbMutationState as N, defineSchema as Nn, ResultRows as Nr, OrderDirection as Nt, TypedExpression as O, Schema as On, defineTable as Or, ColumnValue as Ot, DbOf as P, AnyRecordQuery as Pn, Connection as Pr, OrderKey as Pt, FieldTypes as Q, literal as Qn, ColumnAttributes as Qr, ConditionOperand as Qt, TransactionOptions as R, ExpressionInput as Rn, TransactionFailure as Rr, SelectedRefs as Rt, NumberTypeOperators as S, TableRelations as Sn, KeyColumns as Sr, ResultOf as St, BaseOperators as T, many as Tn, TableKeys as Tr, TypedScalarQuery as Tt, TestFixture as U, SelectionResult as Un, Type as Ur, NotAKey as Ut, OpenedTestFixture as V, NestedQuery as Vn, BaseType as Vr, orderBy as Vt, TestHelpers as W, SelectionUses as Wn, TypeInput as Wr, PrimaryKeyValues as Wt, AnySqlQuery as X, ValueRows as Xn, AnyColumn as Xr, CombinedCondition as Xt, SelectQueryKind as Y, ResultByRows as Yn, defineType as Yr, WhereValues as Yt, DecodedFields as Z, Literal as Zn, Column as Zr, Condition as Zt, TextConversionSignature as _, RelationKind as _n, AnyTableKeys as _r, least as _t, Helper as a, GenericOperator as ai, QueryContext as an, EqualityOperator as ar, MutationQueryState as at, TextTypeOperators as b, SchemaRelations as bn, ColumnShape as br, FilteredStateRows as bt, ColumnRefKey as c, defineGenericOperator as ci, DeclaredRelations as cn, InSignature as cr, CaseValue as ct, NotAColumn as d, OneRelationKeys as dn, ComparisonSignature as dr, TypedOperand as dt, ToColumn as ei, and as en, InitialQueryState as er, SqlQuery as et, matches as f, Relation as fn, Operand as fr, TypedOperandInput as ft, PatternSignature as g, RelationKeys as gn, AnyTable as gr, greatest as gt, TRUE as h, RelationKey as hn, CompileOptions as hr, coalesce as ht, sql as i, OperatorDefinitions as ii, ColumnRefs as in, SelectQueryState as ir, MutationQuery as it, BindOptions as j, SchemaTables as jn, ResultDecodeError as jr, UpdateValues as jt, UntypedExpression as k, SchemaPart as kn, NotFoundError as kr, InsertValues as kt, MatchCheck as l, MergeRelations as ln, equalityOperators as lr, FollowingOperand as lt, FALSE as m, RelationDeclarations as mn, compare as mr, caseWhen as mt, identifier as n, MergeOperators as ni, or as nn, QueryStateOf as nr, AnyMutationQuery as nt, HelperEffect as o, GenericOperatorImplementation as oi, RelationRefs as on, EqualityOperators as or, CaseBranch as ot, defineExpression as p, RelationDeclaration as pn, OperandValue as pr, TypedOperandOperators as pt, createTestHelpers as q, OneValueRows as qn, TypeOutput as qr, WhereCondition as qt, param as r, NoOperators as ri, ExistsValueType as rn, QueryValueType as rr, InitialMutationState as rt, defineHelper as s, OperatorSignature as si, CountValueType as sn, HasEquality as sr, CaseCondition as st, SqlTemplate as t, BoundOperators as ti, not as tn, QueryState as tr, SqlQueryState as tt, MatchResult as u, NoRelations as un, BooleanResult as ur, NullSkippingResult as ut, TextLengthSignature as v, RequiredMember as vn, ColumnDefinitions as vr, AnySelectQuery as vt, AnyExpression as w, UsedRelation as wn, Table as wr, SelectQuery as wt, textOperators as x, TableContext as xn, ColumnValues as xr, OperandUses as xt, TextOperators as y, SchemaContext as yn, ColumnOperators as yr, BoundSelectQuery as yt, createDatabase as z, ExpressionValue as zn, createStatement as zr, asc as zt };