kern-orm 0.5.0 → 0.7.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.
@@ -49,7 +49,7 @@ type BoundOperators<O extends OperatorDefinitions, T, I = T> = { [K in keyof O]:
49
49
  /** Kind of a key of a table: its primary key, or a unique key. */
50
50
  type KeyKind = "primaryKey" | "unique";
51
51
  /**
52
- * Type that `primaryKey()` of a type or a column whose values may be `null` is checked against, naming the reason.
52
+ * Type that `primaryKey()` of a type or a column that accepts `null` is checked against, naming the reason.
53
53
  *
54
54
  * Without `strictNullChecks`, `null` belongs to every type, so every column looks nullable; the type then names the option instead.
55
55
  */
@@ -86,7 +86,7 @@ declare class Column<T extends AnyType, Key extends KeyKind | undefined = KeyKin
86
86
  /** Uses a physical column name different from the column key. */
87
87
  columnName(name: string): Column<T, Key, Default>;
88
88
  /** Marks the column as the primary key; the type must not be nullable. */
89
- primaryKey(this: null extends TypeOutput<T> ? NullablePrimaryKey : Column<T, undefined, Default>): Column<T, "primaryKey", Default>;
89
+ primaryKey(this: null extends TypeInput<T> ? NullablePrimaryKey : Column<T, undefined, Default>): Column<T, "primaryKey", Default>;
90
90
  /** Marks the column as a unique key. */
91
91
  unique(this: Column<T, undefined, Default>): Column<T, "unique", Default>;
92
92
  /** Marks the column as one that the database gives a value when an insert omits it, such as by `DEFAULT` or an identity, so that inserts may omit it. */
@@ -148,19 +148,26 @@ interface BaseType<Output, Input, Operators extends OperatorDefinitions, Paramet
148
148
  withParameters<P extends unknown[]>(format: (...parameters: P) => string): Type<Output, Input, Operators, P>;
149
149
  /**
150
150
  * Creates a type with another representation of the values of this type, keeping its SQL type, operators, and nullability.
151
+ * An `encode` that takes `null` also makes the result nullable.
151
152
  *
152
153
  * `decode` receives the values that this type decodes from values other than `NULL`, including `undefined` that an earlier decoder returns, and returns a value other than `null`; `encode` returns values that this type encodes; `NULL` stays `null` without them.
153
154
  */
154
- transform<NewOutput extends {} | undefined, NewInput>(options: TypeTransform<Exclude<Output, null>, NonNullable<Input>, NewOutput, NewInput>): Type<NewOutput | Extract<Output, null>, NewInput | Extract<Input, null>, Operators, Parameters>;
155
+ transform<NewOutput extends {} | undefined, NewInput>(options: TypeTransform<Exclude<Output, null>, NonNullable<Input>, NewOutput, NewInput>): Type<NewOutput | AcceptedNull<NewInput | Input>, NewInput | AcceptedNull<Input>, Operators, Parameters>;
155
156
  /** Creates a type that decodes the values of this type into another representation, other than `null`, and accepts the values that this type accepts. */
156
157
  transform<NewOutput extends {} | undefined>(options: {
157
158
  decode: (value: Exclude<Output, null>) => NewOutput;
158
- }): Type<NewOutput | Extract<Output, null>, Input, Operators, Parameters>;
159
+ }): Type<NewOutput | AcceptedNull<Input>, Input, Operators, Parameters>;
159
160
  nullable(): Type<Output | null, Input | null, Operators, Parameters>;
161
+ /**
162
+ * Narrows the values of this type to `T` in TypeScript, such as to a union of strings that a `CHECK` constraint allows, or to the shape of JSON values.
163
+ *
164
+ * The values are not validated at runtime. `T` must be among the values that this type both returns and accepts, and `nullable` keeps `null` apart from it.
165
+ */
166
+ of<T extends AcceptedValues<Exclude<Output, null>, Exclude<Input, null>>>(): Type<T | AcceptedNull<Input>, T | AcceptedNull<Input>, Operators, Parameters>;
160
167
  /** Creates a column of this type with a physical name different from the column key. */
161
168
  columnName(name: string): Column<Type<Output, Input, Operators, Parameters>, undefined, false>;
162
169
  /** Creates a primary key column of this type; the type must not be nullable. */
163
- primaryKey(this: null extends Output ? NullablePrimaryKey : Type<Output, Input, Operators, Parameters>): Column<Type<Output, Input, Operators, Parameters>, "primaryKey", false>;
170
+ primaryKey(this: null extends Input ? NullablePrimaryKey : Type<Output, Input, Operators, Parameters>): Column<Type<Output, Input, Operators, Parameters>, "primaryKey", false>;
164
171
  /** Creates a column of this type that is a unique key. */
165
172
  unique(): Column<Type<Output, Input, Operators, Parameters>, "unique", false>;
166
173
  /** Creates a column of this type that the database gives a value when an insert omits it, such as by `DEFAULT` or an identity, so that inserts may omit it. */
@@ -171,6 +178,18 @@ interface TypeWithParameters<Output, Input, Operators extends OperatorDefinition
171
178
  /** Creates this type with PostgreSQL type parameters, such as `varchar.with(255)` for `varchar(255)`; other changes of the type are kept. */
172
179
  with(...parameters: Parameters): Type<Output, Input, Operators, Parameters>;
173
180
  }
181
+ /**
182
+ * Values that `of` can narrow a type to: those both among the values `O` that it returns and among the values `I` that it accepts, or `UnacceptedValues` when there are none.
183
+ *
184
+ * A narrowed value is also accepted, so its encoder must take it.
185
+ */
186
+ type AcceptedValues<O, I> = [O] extends [I] ? O : [I] extends [O] ? I : [O & I] extends [never] ? UnacceptedValues : O & I;
187
+ /** `null` when the accepted values `I` include it, also as `unknown`; `never` otherwise. */
188
+ type AcceptedNull<I> = null extends I ? null : never;
189
+ /** Type that `AcceptedValues` names for a type that accepts none of the values it returns. */
190
+ interface UnacceptedValues {
191
+ readonly "of narrows only a type that accepts the values it returns": never;
192
+ }
174
193
  /** Conversion between the values of a type and their new representation. */
175
194
  interface TypeTransform<Output, Input, NewOutput, NewInput> {
176
195
  decode: (value: Output) => NewOutput;
@@ -209,9 +228,9 @@ interface SqlStatement {
209
228
  declare function createStatement(text: string, parameters?: readonly TextValue[]): SqlStatement;
210
229
  /** Result of a statement. */
211
230
  interface DriverResult {
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
- readonly command: string;
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`. */
231
+ /** 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`; `null` for a statement that PostgreSQL completes without a tag, such as an empty text or only a comment. */
232
+ readonly command: string | null;
233
+ /** Number of rows that the command tag reports, such as the rows that an `UPDATE` changes, also without `RETURNING`; `0` when PostgreSQL reports none, such as for `BEGIN` or a statement without a command tag. */
215
234
  readonly count: number;
216
235
  /** Names of the result columns in their order, also when the statement returns no rows; none for a statement without result columns, such as `BEGIN` or an `UPDATE` without `RETURNING`. */
217
236
  readonly columns: readonly string[];
@@ -230,7 +249,11 @@ interface Driver {
230
249
  executeScript(text: string): Promise<void>;
231
250
  /** Reserves a dedicated connection, such as for a transaction. */
232
251
  acquire(): Promise<Connection>;
233
- /** Closes the connections once the transactions on reserved connections end. */
252
+ /**
253
+ * Closes the connections once the statements on the pool and the transactions on reserved connections end.
254
+ *
255
+ * From the call, it rejects a new statement or script on the pool and a new connection.
256
+ */
234
257
  close(): Promise<void>;
235
258
  }
236
259
  /** Connection reserved by a driver, such as for a transaction. */
@@ -278,6 +301,13 @@ interface RecordTemplateField {
278
301
  readonly key: string;
279
302
  readonly value: unknown;
280
303
  }
304
+ /** How code converts the decoded result of a query, by `map` and `transform` of the query: `map` runs before `transform`, since `map` does not apply after `transform`. */
305
+ interface ResultConversion {
306
+ /** Converts each record or value, also `null` of a `NULL` value, and is not called for a missing row. */
307
+ readonly map: ((row: unknown) => unknown) | undefined;
308
+ /** Converts the whole result, once: an array of rows, one row, or `null` or `undefined` of a missing row. */
309
+ readonly transform: ((result: unknown) => unknown) | undefined;
310
+ }
281
311
  /**
282
312
  * How a query returns its rows: `many` as an array; `one` as one row, rejecting without it; `nullable` as one row or `null` without it; `optional` as one row or `undefined` without it.
283
313
  *
@@ -303,6 +333,8 @@ interface ResultPlan extends ResultMode {
303
333
  * A record starts from it, so its keys keep their order whichever of them a row holds.
304
334
  */
305
335
  readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
336
+ /** How code converts the result that the plan decodes; `undefined` for a query without `transform` and `map`. */
337
+ readonly conversion?: ResultConversion | undefined;
306
338
  }
307
339
  /** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
308
340
  declare class NotFoundError extends Error {
@@ -328,13 +360,23 @@ declare class RequiredRelationError extends Error {
328
360
  /** Path of the field of the relation from the result field that holds it, such as `fields[2].form`, after the index of the row of an executed query of rows `many`, such as `[2].form`. */
329
361
  path: string);
330
362
  }
331
- /** Error thrown when a row does not match the result fields or a value fails to decode; the failure of the value is its cause. */
363
+ /** Error thrown when a row does not match the result fields, a value fails to decode, or a callback of `transform` or `map` fails; the failure is its cause. */
332
364
  declare class ResultDecodeError extends Error {
333
- /** Path of the value from its result field, such as `fields[2].label`, after the index of the row of an executed query of rows `many`, such as `[2].label`; `undefined` for a row of the driver of another width than the result fields. */
365
+ /**
366
+ * Path of the value from its result field, such as `fields[2].label`, after the index of the row of an executed query of rows `many`, such as `[2].label`.
367
+ *
368
+ * A callback of `map` that fails has the path of its row, such as `fields[2]` or `[2]`, and one of `transform` the path of the field of its nested rows, such as `fields`.
369
+ * It is `undefined` for a row of the driver of another width than the result fields, and for a callback that fails on the only row or the whole result of an executed query.
370
+ */
334
371
  readonly path: string | undefined;
335
372
  readonly name = "ResultDecodeError";
336
373
  constructor(message: string,
337
- /** Path of the value from its result field, such as `fields[2].label`, after the index of the row of an executed query of rows `many`, such as `[2].label`; `undefined` for a row of the driver of another width than the result fields. */
374
+ /**
375
+ * Path of the value from its result field, such as `fields[2].label`, after the index of the row of an executed query of rows `many`, such as `[2].label`.
376
+ *
377
+ * A callback of `map` that fails has the path of its row, such as `fields[2]` or `[2]`, and one of `transform` the path of the field of its nested rows, such as `fields`.
378
+ * It is `undefined` for a row of the driver of another width than the result fields, and for a callback that fails on the only row or the whole result of an executed query.
379
+ */
338
380
  path: string | undefined, options?: ErrorOptions);
339
381
  }
340
382
  /** Tells whether `T` is `any`: only `any` turns `1 & T` into a type that `0` extends. */
@@ -366,21 +408,23 @@ interface TableKeys<PrimaryKey extends KeyColumns | undefined, UniqueKey extends
366
408
  readonly [keysType]: (primaryKey: PrimaryKey, unique: UniqueKey) => readonly [PrimaryKey, UniqueKey];
367
409
  }
368
410
  /**
369
- * Immutable table descriptor: physical name, columns, and keys.
411
+ * Immutable table descriptor: physical name, columns, keys, and whether it holds at most one row.
370
412
  *
371
413
  * A table knows nothing about relations, schemas, or database connections, so the same table can belong to several schemas.
372
414
  * Its object identity is the logical identity of the table.
373
415
  */
374
- interface Table<Name extends string = string, Columns extends ColumnShape = ColumnShape, Keys extends AnyTableKeys = AnyTableKeys> {
416
+ interface Table<Name extends string = string, Columns extends ColumnShape = ColumnShape, Keys extends AnyTableKeys = AnyTableKeys, Singleton extends boolean = boolean> {
375
417
  readonly kind: "table";
376
418
  readonly name: Name;
377
419
  readonly columns: Columns;
378
420
  readonly keys: Keys;
421
+ /** Whether the table holds at most one row, as the `singleton` option of `defineTable` declares; `boolean` where the type of the table does not tell it. */
422
+ readonly singleton: Singleton;
379
423
  }
380
424
  /** Table of any name, columns, and keys. */
381
425
  type AnyTable = Table<string, ColumnShape>;
382
426
  /**
383
- * Options of `defineTable` over column keys `Column`: the keys of several columns, whose columns are listed in their order.
427
+ * Options of `defineTable` over column keys `Column`: the keys of several columns, whose columns are listed in their order, and whether the table holds at most one row.
384
428
  *
385
429
  * The columns of the primary key are of `PrimaryKeyColumn`.
386
430
  */
@@ -389,6 +433,17 @@ interface TableOptions<Column extends string = string, PrimaryKeyColumn extends
389
433
  readonly primaryKey?: readonly [PrimaryKeyColumn, PrimaryKeyColumn, ...PrimaryKeyColumn[]];
390
434
  /** Unique keys of several columns; mark a unique key of one column with `unique()`. */
391
435
  readonly unique?: readonly (readonly [Column, Column, ...Column[]])[];
436
+ /**
437
+ * Whether the table holds at most one row, such as the settings of an application, which a unique index of `(true)` must guarantee.
438
+ *
439
+ * A query of the table starts as a query of that row, which resolves to `undefined` without it, and `upsert` inserts or updates it.
440
+ */
441
+ readonly singleton?: boolean;
442
+ }
443
+ /** Options of `createTableFactory`. */
444
+ interface TableFactoryOptions {
445
+ /** Returns the physical name of a column from its key, such as `toSnakeCase` does, for each column without an explicit `columnName()`. */
446
+ readonly columnName: (key: string) => string;
392
447
  }
393
448
  /** Record shape returned when all columns of a table are selected. */
394
449
  type Selectable<T extends AnyTable> = { [K in keyof T["columns"]]: TypeOutput<T["columns"][K]["type"]>; };
@@ -415,8 +470,8 @@ type MatchingKey$1<Key, Columns> = Key extends KeyColumns ? [Key[number]] extend
415
470
  type IncludedKey<Key, Columns> = Key extends KeyColumns ? [Key[number]] extends [Columns] ? true : never : never;
416
471
  /** Column key of columns `C` as a string, as object keys are at runtime. */
417
472
  type ColumnKey<C extends ColumnShape> = `${keyof C & (string | number)}`;
418
- /** Column key of columns `C` whose type is not nullable, as a string like `ColumnKey`. */
419
- type NonNullableColumnKey<C extends ColumnShape> = { [K in keyof C]: null extends TypeOutput<C[K]["type"]> ? never : `${K & (string | number)}`; }[keyof C];
473
+ /** Column key of columns `C` whose type does not accept `null`, as a string like `ColumnKey`. */
474
+ type NonNullableColumnKey<C extends ColumnShape> = { [K in keyof C]: null extends TypeInput<C[K]["type"]> ? never : `${K & (string | number)}`; }[keyof C];
420
475
  /** Column key of columns `C`, as a string like `ColumnKey`, whose column forms a key of kind `Kind` alone, as `KnownKeyKind` tells. */
421
476
  type KeyedColumn<C extends ColumnShape, Kind> = { [K in keyof C]: KnownKeyKind<C[K]["attributes"]["keyKind"]> extends Kind ? `${K & (string | number)}` : never; }[keyof C];
422
477
  /** Kind `Kind` of the key that a column forms alone, or `"unknown"` where the type of the column does not tell it. */
@@ -438,6 +493,8 @@ type KnownKeysOf<PrimaryKey extends KeyColumns | undefined, UniqueKey extends Ke
438
493
  type DefinedPrimaryKey<C extends ColumnShape, PrimaryKey> = PrimaryKey extends KeyColumns ? PrimaryKey : [KeyedColumn<C, "primaryKey">] extends [never] ? undefined : SingleColumnKey<KeyedColumn<C, "primaryKey">>;
439
494
  /** Unique key of a table of columns `C`: `UniqueKey` of its options, or of a column marked with `unique()`. */
440
495
  type DefinedUniqueKey<C extends ColumnShape, UniqueKey> = Extract<UniqueKey, KeyColumns> | SingleColumnKey<KeyedColumn<C, "unique">>;
496
+ /** Whether a table of options `O` holds at most one row: `true` or `false` of their `singleton`, `false` without it, or `boolean` where its type does not tell it. */
497
+ type DefinedSingleton<O> = O extends unknown ? [O["singleton" & keyof O]] extends [false | undefined] ? false : [O["singleton" & keyof O]] extends [true] ? true : boolean : never;
441
498
  /** Key of each single column of `K`. */
442
499
  type SingleColumnKey<K> = K extends string ? readonly [K] : never;
443
500
  /** Primary key in options `O`: `undefined` without one, or `"unknown"` where its type does not tell it. */
@@ -455,70 +512,33 @@ type IsExactKey<K> = true extends IsUnion<K> ? false : K extends readonly unknow
455
512
  *
456
513
  * A key of one column is marked on its column.
457
514
  */
458
- declare function defineTable<Name extends string, Definitions extends ColumnDefinitions>(name: Name, definitions: Definitions): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, undefined>>;
515
+ declare function defineTable<Name extends string, Definitions extends ColumnDefinitions>(name: Name, definitions: Definitions): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, undefined>, false>;
459
516
  /**
460
517
  * Defines a table; a type without column attributes becomes a column as it is.
461
518
  *
462
- * A key of one column is marked on its column, and `options` list the columns of the keys of several columns.
463
- */
464
- declare function defineTable<Name extends string, Definitions extends ColumnDefinitions, const Options extends TableOptions<ColumnKey<ToColumns<Definitions>>, PrimaryKeyOption<ToColumns<Definitions>>> | undefined>(name: Name, definitions: Definitions, options: Options): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, Options>>;
465
- /** Physical placement of the tables of a query, fixed at compilation. */
466
- interface CompileOptions {
467
- /** PostgreSQL schema qualifying every table; tables stay unqualified when it is not set. */
468
- schemaName?: string;
469
- }
470
- /**
471
- * Value compared with an expression of type `T` accepting values of type `I`: a value, an expression, or a query of one value, such as of `get` or of an aggregate; `null` is matched with `isNull` instead.
472
- */
473
- type Operand<T, I = T> = NonNullable<I> | AnyExpression<NonNullable<T> | null> | ScalarQuery<NonNullable<T> | null>;
474
- /** SQL value of an operand, unwrapping an expression or a query. */
475
- type OperandValue<V> = V extends AnyExpression<infer T> ? T : V extends ScalarQuery ? ScalarQueryValue<V> : V;
476
- /** Boolean result that can be NULL when an input value can be NULL. */
477
- type BooleanResult<T> = boolean | (null extends T ? null : never);
478
- /** Signature of a generic operator comparing an expression with an operand of its type, such as `lt`. */
479
- interface ComparisonSignature extends OperatorSignature {
480
- readonly method: <V extends Operand<this["T"], this["I"]>>(value: V) => Expression<BooleanResult<this["T"] | OperandValue<V>>>;
481
- }
482
- /**
483
- * Compares an expression with a value, another expression, or a query of one value, encoding a plain value with the type of the expression.
484
- *
485
- * Operators of custom types build comparisons with it, such as `compare(self, "ILIKE", pattern)`.
519
+ * A key of one column is marked on its column, and `options` list the columns of the keys of several columns and tell whether the table holds at most one row.
486
520
  */
487
- declare function compare<T, V>(self: AnyExpression<T>, operator: ComparisonNode["operator"], value: V): Expression<BooleanResult<T | OperandValue<V>>>;
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;
493
- }
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)>>;
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
+ declare function defineTable<Name extends string, Definitions extends ColumnDefinitions, const Options extends TableOptions<ColumnKey<ToColumns<Definitions>>, PrimaryKeyOption<ToColumns<Definitions>>> | undefined>(name: Name, definitions: Definitions, options: Options): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, Options>, DefinedSingleton<Options>>;
510
522
  /**
511
- * Operators of SQL equality: `eq`, `ne`, and `in`; `orderingOperators` include them.
523
+ * Creates a table-definition function with the given naming convention, for an application to define its tables with.
512
524
  *
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
+ * Its tables have the same types as those of `defineTable`.
514
526
  */
515
- declare const equalityOperators: EqualityOperators;
527
+ declare function createTableFactory(factoryOptions: TableFactoryOptions): typeof defineTable;
516
528
  /** Records of a query without selected fields. */
517
529
  type EmptyRecord = Record<never, never>;
518
530
  /** 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. */
519
- interface QueryState extends ResultMode {
520
- /** Record of a row, or the value of its only field for a query made by `get`, `pluck`, an aggregate method, such as `count`, or `exists`. */
531
+ interface QueryState {
532
+ /** Record of a row, or the value of its only field for a query made by `get`, `pluck`, an aggregate method, such as `count`, or `exists`, or what the callback of `map` or `transform` returns. */
521
533
  readonly result: unknown;
534
+ /** How the rows become the result. */
535
+ readonly rows: ResultRows;
536
+ /**
537
+ * What a row is: a record for `false`, the value of its only field for `true`, or what a callback of code returns: of `map` for `"mapped"`, whichever the row was before it, or of `transform` for `"transformed"`, of the whole result.
538
+ *
539
+ * The states of the methods that read the fields of a row or the value of its only field narrow it to `false` or `true`, so that they reject a query that code converts.
540
+ */
541
+ readonly value: boolean | "mapped" | "transformed";
522
542
  /** Relations whose records the query and the queries nested in it select, which a `Db` must have. */
523
543
  readonly uses: UsedRelation;
524
544
  }
@@ -528,7 +548,7 @@ interface QueryValueType {
528
548
  readonly operators: OperatorDefinitions;
529
549
  }
530
550
  /**
531
- * State of a select query in types: its table, the relations of its schema, the record or value of its rows and the type of its value, how its rows become its result, and the relations it selects records of.
551
+ * State of a select query in types: its table, the relations of its schema, the record or value of its rows, the type of its value or the types of its fields, how its rows become its result, and the relations it selects records of.
532
552
  *
533
553
  * Methods change only their own parts of the state.
534
554
  */
@@ -537,6 +557,8 @@ interface SelectQueryState extends QueryState {
537
557
  readonly schema: SchemaContext;
538
558
  /** Type of the value of a query of values, a `QueryValueType`; `never` for a query of records. */
539
559
  readonly valueType: unknown;
560
+ /** Types of the values of the selected fields of a query of records, the values that each encodes and its operators, which the callback of `having` gives its references: a `SelectedFieldTypes`, or `EmptyRecord` without selected fields. */
561
+ readonly fieldTypes: unknown;
540
562
  /**
541
563
  * Whether a required relation guarantees the row of the query, such as of `field.form`.
542
564
  *
@@ -544,7 +566,7 @@ interface SelectQueryState extends QueryState {
544
566
  * The callback of a helper starts with it, so that the effect of the helper records whether the callback filters.
545
567
  */
546
568
  readonly guaranteed: boolean;
547
- /** Whether the query is made by an aggregate method, such as `count`, or by `exists`, which makes `get`, `pluck`, the aggregate methods, and `exists` reject it. */
569
+ /** Whether the query is made by an aggregate method, such as `count`, or by `exists`, or converted by `map`, which makes `get`, `pluck`, the aggregate methods, and `exists` reject it. */
548
570
  readonly aggregate: boolean;
549
571
  }
550
572
  /** State of a query over table `T` with schema context `C`, whatever its result. */
@@ -560,12 +582,129 @@ interface QueryStateOf<T extends AnyTable, C extends SchemaContext = SchemaConte
560
582
  interface InitialQueryState<T extends AnyTable, C extends SchemaContext = NoRelations, U extends UsedRelation = never, Rows extends ResultRows = "many", Guaranteed extends boolean = false> extends QueryStateOf<T, C> {
561
583
  readonly result: EmptyRecord;
562
584
  readonly valueType: never;
585
+ readonly fieldTypes: EmptyRecord;
563
586
  readonly rows: Rows;
564
587
  readonly value: false;
565
588
  readonly uses: U;
566
589
  readonly guaranteed: Guaranteed;
567
590
  readonly aggregate: false;
568
591
  }
592
+ /**
593
+ * State of a query that starts from table `T` with schema context `C`, as the entry points of a schema and a `Db` and `from` start it: of all the rows of the table, or of the one row of a singleton table.
594
+ *
595
+ * Where the type of `T` does not tell whether it is a singleton, such as `Table<Name, Columns>`, it is the union of both.
596
+ */
597
+ type TableQueryState<T extends AnyTable, C extends SchemaContext = NoRelations> = SingletonOrInitialState<T, C, T["singleton"]>;
598
+ /** State of a query that starts from table `T` with schema context `C`, as `TableQueryState` gives it, by `Singleton`, the `singleton` of the type of `T`. */
599
+ type SingletonOrInitialState<T extends AnyTable, C extends SchemaContext, Singleton> = Singleton extends true ? SingletonQueryState<T, C> : InitialQueryState<T, C>;
600
+ /** State of a query that starts from singleton table `T` with schema context `C`: its one row as a record without fields, which resolves to `undefined` without it. */
601
+ interface SingletonQueryState<T extends AnyTable, C extends SchemaContext = NoRelations> extends InitialQueryState<T, C, never, "optional">, FoundKey<never> {}
602
+ /** Key of the member of `FoundKey` that makes it invariant in the columns of the key. */
603
+ declare const foundKeyVariance: unique symbol;
604
+ /** Part of the state of a query of `find` or `findBy` with the columns `K` of its key, or of a query of a singleton table without them, which `upsert` applies to. */
605
+ interface FoundKey<K extends string> {
606
+ readonly foundKey: K;
607
+ readonly [foundKeyVariance]: { readonly [C in K]: true; };
608
+ }
609
+ /** Mark of `aggregate: false` of a query of groups, which aggregate methods replace. */
610
+ interface Grouped {
611
+ readonly grouped: true;
612
+ }
613
+ /** Key of the value of a query in an expression, for types only. */
614
+ declare const scalarValue: unique symbol;
615
+ /** Value of a query of state `S` in an expression: its value, or `NULL` without its row unless the query always has it. */
616
+ type ScalarValue<S extends SelectQueryState> = S["aggregate"] extends true ? S["result"] : S["guaranteed"] extends true ? S["result"] : S["result"] | null;
617
+ /**
618
+ * Query of one value of a table, such as of `get`, of an aggregate, or of `exists`, which an expression takes as a scalar subquery of its value, or as `EXISTS` of the rows of a query of `exists`.
619
+ *
620
+ * `T` is its value there: without its row, a query of `get` is `NULL`, unless a required relation guarantees the row, such as of `field.form`.
621
+ */
622
+ interface ScalarQuery<T = unknown> {
623
+ /** Value of the query in an expression, from which an expression infers `T`. */
624
+ readonly [scalarValue]: T;
625
+ readonly types: ScalarQueryState;
626
+ readonly exists: unknown;
627
+ }
628
+ /** Value of query `Q` of one value in an expression. */
629
+ type ScalarQueryValue<Q extends ScalarQuery> = Q[typeof scalarValue];
630
+ /** 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. */
631
+ type OperandUses<E> = E extends ScalarQuery ? E["types"]["uses"] : never;
632
+ /** State of a query of one value, which an expression takes. */
633
+ interface ScalarQueryState extends SelectQueryState {
634
+ readonly rows: "one" | "optional";
635
+ readonly value: true;
636
+ }
637
+ /** State of a query of one value with the type of its value, whose expression `expr` gives. */
638
+ interface ExpressionQueryState extends ScalarQueryState {
639
+ readonly valueType: QueryValueType;
640
+ }
641
+ /** Query of one value of a table with the type of its value, such as of `get` or of an aggregate, which gives the expression of a function the decoding and the operators of its value. */
642
+ interface TypedScalarQuery extends ScalarQuery {
643
+ readonly types: ExpressionQueryState;
644
+ }
645
+ /** Query of values of a table of any rows, such as of `pluck`, whose value is `T`, which `in` takes as a subquery of its values. */
646
+ interface ValuesQuery<T = unknown> {
647
+ readonly types: ValuesQueryState<T>;
648
+ readonly exists: unknown;
649
+ }
650
+ /** Value of query `Q` of values, of each of its rows. */
651
+ type ValuesQueryValue<Q extends ValuesQuery> = Q["types"]["result"];
652
+ /** State of a query of values whose value is `T`. */
653
+ interface ValuesQueryState<T> extends SelectQueryState {
654
+ readonly result: T;
655
+ readonly value: true;
656
+ }
657
+ /**
658
+ * Value compared with an expression of type `T` accepting values of type `I`: a value, an expression, or a query of one value, such as of `get` or of an aggregate; `null` is matched with `isNull` instead.
659
+ */
660
+ type Operand<T, I = T> = NonNullable<I> | AnyExpression<NonNullable<T> | null> | ScalarQuery<NonNullable<T> | null>;
661
+ /** SQL value of an operand, unwrapping an expression or a query. */
662
+ type OperandValue<V> = V extends AnyExpression<infer T> ? T : V extends ScalarQuery ? ScalarQueryValue<V> : V;
663
+ /** Boolean result that can be NULL when an input value can be NULL. */
664
+ type BooleanResult<T> = boolean | (null extends T ? null : never);
665
+ /** Signature of a generic operator comparing an expression with an operand of its type, such as `lt`. */
666
+ interface ComparisonSignature extends OperatorSignature {
667
+ readonly method: <V extends Operand<this["T"], this["I"]>>(value: V) => Expression<BooleanResult<this["T"] | OperandValue<V>>>;
668
+ }
669
+ /**
670
+ * Compares an expression with a value, another expression, or a query of one value, encoding a plain value with the type of the expression.
671
+ *
672
+ * Operators of custom types build comparisons with it, such as `compare(self, "ILIKE", pattern)`.
673
+ */
674
+ declare function compare<T, V>(self: AnyExpression<T>, operator: ComparisonNode["operator"], value: V): Expression<BooleanResult<T | OperandValue<V>>>;
675
+ /** Runtime mark of the operators of `equalityOperators`, which tell that a type has SQL `=`. */
676
+ declare const equalityBrand: unique symbol;
677
+ /** Generic operator of `equalityOperators`, which gives the type it is added to SQL `=`. */
678
+ interface EqualityOperator<S extends OperatorSignature> extends GenericOperator<S> {
679
+ readonly [equalityBrand]: true;
680
+ }
681
+ /** 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. */
682
+ declare const valuesQueryNode: unique symbol;
683
+ /** 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`. */
684
+ interface InSignature extends OperatorSignature {
685
+ 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)>>;
686
+ }
687
+ /** Operators of `equalityOperators`. */
688
+ type EqualityOperators = {
689
+ eq: EqualityOperator<ComparisonSignature>;
690
+ ne: EqualityOperator<ComparisonSignature>;
691
+ in: EqualityOperator<InSignature>;
692
+ };
693
+ /** Tells whether operators `O` include an operator of `equalityOperators`, so that their type has SQL `=`. */
694
+ type HasEquality<O> = true extends { [K in keyof O]: O[K] extends {
695
+ readonly [equalityBrand]: true;
696
+ } ? true : false; }[keyof O] ? true : false;
697
+ /**
698
+ * Operators of SQL equality: `eq`, `ne`, and `in`; `orderingOperators` include them.
699
+ *
700
+ * 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 `=`.
701
+ */
702
+ declare const equalityOperators: EqualityOperators;
703
+ /** Physical placement of the tables of a query, fixed at compilation. */
704
+ interface CompileOptions {
705
+ /** PostgreSQL schema qualifying every table; tables stay unqualified when it is not set. */
706
+ schemaName?: string;
707
+ }
569
708
  /** Selection of the rows of a nested query as the value of the field `key`. */
570
709
  interface NestedSelectionNode {
571
710
  readonly key: string;
@@ -591,13 +730,37 @@ interface QueryNode extends ResultMode {
591
730
  /** Fields in the order of the result, with unique keys; a query without them returns records without fields. */
592
731
  readonly projections: readonly SelectedNode[];
593
732
  readonly filters: QueryFilters;
733
+ /** Keys of the groups of the rows; a query with them gives one row of each group. */
734
+ readonly groupBy: readonly ExpressionNode[];
735
+ /** Condition of the groups, apart from `filters`, which choose the rows that they group. */
736
+ readonly having: ExpressionNode | undefined;
594
737
  readonly orderBy: readonly OrderNode[];
595
738
  readonly limit: ExpressionNode | undefined;
596
739
  readonly offset: ExpressionNode | undefined;
740
+ /** Whether `distinct` removes the duplicates of the rows, comparing the fields that the query selects when it compiles. */
741
+ readonly distinct: boolean;
742
+ /** Keys of `distinctOn`, whose equal values give one row, the first in the order of the query; none without `distinctOn`. */
743
+ readonly distinctOn: readonly ExpressionNode[];
744
+ /**
745
+ * Fields of a query of `distinct` or `distinctOn` that an aggregate method or `exists` replaced, or `undefined` otherwise.
746
+ *
747
+ * `distinct` compares them, and the keys, the order, and the argument of the aggregate read a selected field through its projection.
748
+ */
749
+ readonly distinctFields: readonly SelectedNode[] | undefined;
750
+ /** Lock of the rows that the query reads. */
751
+ readonly lock: RowLockNode | undefined;
597
752
  /** 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
753
  readonly guaranteed: boolean;
599
754
  /** Whether `all` allows a mutation of the query to change every row of the table without a filter. */
600
755
  readonly all: boolean;
756
+ /** How `map` and `transform` convert the decoded result. */
757
+ readonly conversion: ResultConversion | undefined;
758
+ /**
759
+ * Values of the columns of the key of `find` or `findBy` of a query of a table without clauses, which `upsert` inserts, an empty object for a query that starts from a singleton table, whose key has no columns, or `undefined` for any other query.
760
+ *
761
+ * Every method that derives a node from the query drops them, whereas `use` returns the query of its callback, such as the query itself.
762
+ */
763
+ readonly foundKey: Readonly<Record<string, unknown>> | undefined;
601
764
  }
602
765
  /**
603
766
  * 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.
@@ -611,31 +774,25 @@ interface RecordQueryNode {
611
774
  /** Fields in the order of the record, with unique keys. */
612
775
  readonly projections: readonly SelectedNode[];
613
776
  }
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;
777
+ /** Type of a count: a `bigint` of PostgreSQL decoded as a number, rejecting a count that a number cannot hold exactly. */
778
+ declare const countType: BaseType<number, number, MergeOperators<NoOperators, {
779
+ eq: EqualityOperator<ComparisonSignature>;
780
+ ne: EqualityOperator<ComparisonSignature>;
781
+ in: EqualityOperator<InSignature>;
782
+ lt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
783
+ lte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
784
+ gt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
785
+ gte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
786
+ }>, undefined>;
787
+ /** Type of the value of a query of a count. */
788
+ interface CountValueType extends QueryValueType {
789
+ readonly input: TypeInput<typeof countType>;
790
+ readonly operators: TypeOperators<typeof countType>;
627
791
  }
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>;
635
792
  /** 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. */
636
793
  type RelationRows<Kind extends RelationKind, Required extends boolean> = Kind extends "many" ? "many" : Required extends true ? "one" : "nullable";
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. */
638
- type FilteredRows<Rows extends ResultRows, Value extends boolean> = Rows extends "one" ? Value extends true ? "optional" : "nullable" : Rows;
794
+ /** Rows mode after a filter of a query whose row a required relation guarantees: `one` becomes `nullable`, or `optional` for a query of values that `map` does not convert; other modes stay. */
795
+ type FilteredRows<Rows extends ResultRows, Value> = Rows extends "one" ? Value extends true ? "optional" : "nullable" : Rows;
639
796
  /** Rows mode after `take`: `many` becomes `one`; the modes of one row stay. */
640
797
  type OneRow<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows;
641
798
  /** Rows mode after `pluck`: `nullable` becomes `optional`; the other modes stay. */
@@ -650,434 +807,119 @@ type OneValueRows<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows
650
807
  type QueryResult<S extends QueryState> = S extends QueryState ? ResultByRows<S["result"], S["rows"]> : never;
651
808
  /** Result of rows of `Result` returned in rows mode `Rows`; a union of modes gives the union of their results. */
652
809
  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;
810
+ /** Type of the value of a query of `exists`. */
811
+ interface ExistsValueType extends QueryValueType {
812
+ readonly input: boolean;
813
+ readonly operators: EqualityOperators;
689
814
  }
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>>;
815
+ declare const conditionValues: unique symbol;
816
+ /** Predicate accepted by `where`, `and`, `or`, and `not`; SQL treats a `NULL` predicate as not satisfied. */
817
+ type Predicate = AnyExpression<boolean | null>;
692
818
  /**
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.
819
+ * Condition combining expressions with objects of column values, such as `or({ published: true }, form.id.in(ids))`.
694
820
  *
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.
821
+ * `where` matches the objects against the columns of its query, so a condition is accepted only where `V` matches the table.
697
822
  */
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;
823
+ interface Condition<V> {
824
+ readonly [conditionValues]?: V;
714
825
  }
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
826
  /**
723
- * Immutable collection of tables and their relations with query entry points.
827
+ * Operand of `and`, `or`, and `not`: a predicate, a query of one Boolean value, such as of `exists`, a condition, or an object of column values.
724
828
  *
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`.
829
+ * Column values `V` are never inferred from an object, so that object keys are checked against the table instead of determining `V`.
727
830
  */
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;
831
+ type ConditionOperand<V, T extends boolean | null = boolean | null> = AnyExpression<T> | ScalarQuery<T> | Condition<V> | NoInfer<V>;
757
832
  /**
758
- * Tables of the parts of a schema definition by their keys.
833
+ * Result of `and`, `or`, and `not`: a condition checked against the table inside `where`, a Boolean expression without a table.
834
+ */
835
+ type CombinedCondition<V, T extends boolean | null = boolean | null> = [V] extends [never] ? Expression<BooleanResult<T>> : Condition<V>;
836
+ /** Combines predicates with `AND`; no operands yield `TRUE`. */
837
+ declare function and<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
838
+ /** Combines predicates with `OR`; no operands yield `FALSE`. */
839
+ declare function or<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
840
+ /** Negates a predicate. */
841
+ declare function not<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(operand: ConditionOperand<V, T>): CombinedCondition<V, T>;
842
+ /**
843
+ * Filter by column values, each matched by the `eq` operator of its column; `null` matches `IS NULL`.
759
844
  *
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.
845
+ * A column without an `eq` operator of one operand accepts only `null` in this filter, when its input type includes `null`.
761
846
  */
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
- };
847
+ type WhereValues<T extends AnyTable> = { [K in keyof T["columns"]]?: EqValue<T, K> | (null extends ColumnValues<T>[K] ? null : never); };
848
+ /** Operand of the `eq` operator of column `K` of table `T` in an object passed to `where`, such as an expression. */
849
+ type EqValue<T extends AnyTable, K extends keyof T["columns"]> = IsAny<ColumnOperators<T, K>> extends true ? ColumnValues<T>[K] : ColumnOperators<T, K> extends {
850
+ readonly eq: EqualityOperator<ComparisonSignature>;
851
+ } ? Operand<TypeOutput<T["columns"][K]["type"]>, TypeInput<T["columns"][K]["type"]>> : EqOperand<ColumnRefs<T>[K]>;
852
+ /** Operand of the `eq` operator of an expression, if it has one taking a single operand and returning a predicate. */
853
+ type EqOperand<E> = E extends {
854
+ eq: (value: infer V) => Predicate;
855
+ } ? V : never;
856
+ /** Filter of `where`: a Boolean expression, a query of one Boolean value, such as of `exists`, an object of column values, or their combination with `and`, `or`, and `not`. */
857
+ type WhereCondition<T extends AnyTable> = ConditionOperand<WhereValues<T>>;
858
+ /** Callback of `where` over table `T` with schema context `C`: it receives the columns and the queries of the relations of the table and returns a condition. */
859
+ type WhereCallback<T extends AnyTable, C extends SchemaContext = NoRelations> = (columns: ColumnRefs<T> & RelationRefs<C>) => WhereCondition<T>;
860
+ /** 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. */
861
+ type WhereFilter<T extends AnyTable, C extends SchemaContext = NoRelations> = WhereCondition<T> | WhereCallback<T, C>;
781
862
  /**
782
- * Defines a schema of the tables of `parts`, keyed by their names in queries.
863
+ * 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.
783
864
  *
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.
865
+ * 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`.
866
+ * It reads the filter only in its branch, since a general alias that takes the filter as an argument resolves it on every call.
786
867
  */
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
- }
868
+ type QueryWhereFilter<S extends SelectQueryState> = [S] extends [unknown] ? WhereFilter<S["table"], S["schema"]> : never;
802
869
  /**
803
- * Relation of a table of a schema as `$relations` defines it: the columns of its keys, compared by SQL `=` in order.
870
+ * 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.
804
871
  *
805
- * Composition includes a definition as it is, so a relation that several parts include is one definition.
872
+ * A union of tables gives the union of their values.
806
873
  */
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
- };
874
+ type PrimaryKeyValues<T extends AnyTable> = T extends AnyTable ? T["keys"] extends TableKeys<infer PrimaryKey extends KeyColumns, infer _UniqueKey> ? { readonly [I in keyof PrimaryKey]: NonNullable<EqValue<T, PrimaryKey[I] & keyof T["columns"]>>; } : never : never;
875
+ /** Columns of the primary key of table `T`, or `never` where the type of `T` tells no primary key. */
876
+ type PrimaryKeyColumn<T extends AnyTable> = T extends AnyTable ? T["keys"] extends TableKeys<infer PrimaryKey extends KeyColumns, infer _UniqueKey> ? PrimaryKey[number] : never : never;
831
877
  /**
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.
878
+ * Check of columns `Columns`, of the object of `findBy` or of `onConflict`, that rejects them unless they are exactly a key of table `T`, primary or unique, as the type of `T` tells.
833
879
  *
834
- * `Source` and `From` only type the keys of the source table.
880
+ * A table of `any`, such as of `AnySelectQuery`, takes any columns, as `where` takes any values there.
835
881
  */
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;
882
+ type KeyCheck<T extends AnyTable, Columns> = [IsKey<T, Columns>] extends [true] ? unknown : IsAny<T> extends true ? unknown : NotAKey<KeyOf<T["keys"]>>;
883
+ /** Type that the columns of `findBy` and `onConflict` are checked against when they are not exactly a key of the table, naming the keys of the table. */
884
+ interface NotAKey<Keys> {
885
+ readonly "columns must be exactly one key of the table": Keys;
863
886
  }
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
- }; };
887
+ /** Key of a group returned by the callback of `groupBy` or `distinctOn`: an expression or a query of one value, such as of a value of a related record. */
888
+ type GroupTerm = AnyExpression | ScalarQuery;
889
+ /** Keys of a group returned by the callback of `groupBy` or `distinctOn`: one or an array of them. */
890
+ type GroupTerms = GroupTerm | readonly GroupTerm[];
876
891
  /**
877
- * Declarations `D` of `$relations` checked by the names they use: relations of the tables of `T` under their keys, and no other keys.
892
+ * What the callback of `having` of a query of state `S` receives as its second parameter: the references to the selected fields of a query of records, with the operators and the values of the types of their fields, the expression of the value of a query made by `get` or `pluck`, and `undefined` for an aggregate query, a query of `exists`, and a query that `map` converts.
878
893
  *
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.
894
+ * A field of nested rows or of a literal is among the references, but reading it throws; a field of the rows of a query of one value, such as of `get`, has the operators of its value in types.
881
895
  */
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;
896
+ type HavingFields<S extends SelectQueryState> = S["value"] extends false ? { readonly [K in keyof S["result"] & string]: FieldRef<SelectedFieldTypesOf<S["fieldTypes"]>, K, S["result"][K]>; } : S["value"] extends true ? S["aggregate"] extends false ? ToFieldRef<S["valueType"], S["result"]> : undefined : undefined;
897
+ /** Reference of the callback of `having` to field `K` of values `V`, with the type of its value among field types `F`, for each member of a union of them. */
898
+ type FieldRef<F, K extends string, V> = K extends keyof F ? ToFieldRef<Exclude<F[K], undefined>, V> : AnyExpression<V>;
899
+ /** Expression of values `V` with the operators and the values of type `D` of a value, or without them when `D` is none. */
900
+ type ToFieldRef<D, V> = D extends QueryValueType ? D extends {
901
+ readonly group: infer G;
902
+ } ? unknown extends G ? Expression<V, D["operators"], D["input"]> // References can escape this callback and be selected without grouping, so retain standalone nullability and the group mark.
903
+ : Expression<V | null, D["operators"], D["input"]> & GroupValue<G> : Expression<V, D["operators"], D["input"]> : AnyExpression<V>;
912
904
  /**
913
- * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
905
+ * Argument of `having` of a query of state `S`: a condition of `where`, or a callback that receives the columns and the relations of the table, and the fields of `HavingFields`, and returns one.
914
906
  *
915
- * A composite key lists its columns in arrays of the same length.
907
+ * It reads `S` only in its branch, as `QueryWhereFilter` does.
916
908
  */
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>;
909
+ type QueryHavingFilter<S extends SelectQueryState> = [S] extends [unknown] ? WhereCondition<S["table"]> | ((columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>, selected: HavingFields<S>) => WhereCondition<S["table"]>) : never;
918
910
  /**
919
- * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
911
+ * What a query with a row lock does with a row that another transaction has locked, instead of waiting for it:
920
912
  *
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.
913
+ * - `skipLocked` leaves the row out of its result, such as to take the next free job of a queue.
914
+ * - `noWait` rejects with a PostgreSQL error of SQLSTATE `55P03`.
925
915
  */
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
- }
942
- /** References to the columns of the query source, passed to query callbacks. */
943
- type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
944
- /**
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.
946
- *
947
- * A relation name is never a column key of its table.
948
- * A context whose table key is not known, such as one of a query of any schema, has no relations.
949
- */
950
- type RelationRefs<C extends SchemaContext> = string extends C["key"] ? EmptyRecord : C["key"] extends keyof C["relations"] ? RelationQueries<C["relations"], C["key"]> : EmptyRecord;
951
- type RelationQueries<R extends SchemaContext["relations"], K extends keyof R & string> = { readonly [N in keyof R[K]]: RelatedQuery<R, K, N & string>; };
952
- /** Unbound query of the records of relation `N` of the table under key `K` of a schema of relations `R`, in the schema context of its target and the rows mode of the relation, whose row a required relation guarantees. */
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"]>>;
954
- /** Runtime context of the queries of a table in the schema they start from. */
955
- interface QueryContext {
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. */
957
- readonly relations: PropertyDescriptorMap;
958
- }
959
- /** Type of the value of a query of `exists`. */
960
- interface ExistsValueType extends QueryValueType {
961
- readonly input: boolean;
962
- readonly operators: EqualityOperators;
963
- }
964
- declare const conditionValues: unique symbol;
965
- /** Predicate accepted by `where`, `and`, `or`, and `not`; SQL treats a `NULL` predicate as not satisfied. */
966
- type Predicate = AnyExpression<boolean | null>;
967
- /**
968
- * Condition combining expressions with objects of column values, such as `or({ published: true }, form.id.in(ids))`.
969
- *
970
- * `where` matches the objects against the columns of its query, so a condition is accepted only where `V` matches the table.
971
- */
972
- interface Condition<V> {
973
- readonly [conditionValues]?: V;
974
- }
975
- /**
976
- * Operand of `and`, `or`, and `not`: a predicate, a query of one Boolean value, such as of `exists`, a condition, or an object of column values.
977
- *
978
- * Column values `V` are never inferred from an object, so that object keys are checked against the table instead of determining `V`.
979
- */
980
- type ConditionOperand<V, T extends boolean | null = boolean | null> = AnyExpression<T> | ScalarQuery<T> | Condition<V> | NoInfer<V>;
981
- /**
982
- * Result of `and`, `or`, and `not`: a condition checked against the table inside `where`, a Boolean expression without a table.
983
- */
984
- type CombinedCondition<V, T extends boolean | null = boolean | null> = [V] extends [never] ? Expression<BooleanResult<T>> : Condition<V>;
985
- /** Combines predicates with `AND`; no operands yield `TRUE`. */
986
- declare function and<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
987
- /** Combines predicates with `OR`; no operands yield `FALSE`. */
988
- declare function or<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
989
- /** Negates a predicate. */
990
- declare function not<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(operand: ConditionOperand<V, T>): CombinedCondition<V, T>;
991
- /**
992
- * Filter by column values, each matched by the `eq` operator of its column; `null` matches `IS NULL`.
993
- *
994
- * A column without an `eq` operator of one operand accepts only `null` in this filter, when its input type includes `null`.
995
- */
996
- type WhereValues<T extends AnyTable> = { [K in keyof T["columns"]]?: EqValue<T, K> | (null extends ColumnValues<T>[K] ? null : never); };
997
- /** Operand of the `eq` operator of column `K` of table `T` in an object passed to `where`, such as an expression. */
998
- type EqValue<T extends AnyTable, K extends keyof T["columns"]> = IsAny<ColumnOperators<T, K>> extends true ? ColumnValues<T>[K] : ColumnOperators<T, K> extends {
999
- readonly eq: EqualityOperator<ComparisonSignature>;
1000
- } ? Operand<TypeOutput<T["columns"][K]["type"]>, TypeInput<T["columns"][K]["type"]>> : EqOperand<ColumnRefs<T>[K]>;
1001
- /** Operand of the `eq` operator of an expression, if it has one taking a single operand and returning a predicate. */
1002
- type EqOperand<E> = E extends {
1003
- eq: (value: infer V) => Predicate;
1004
- } ? V : never;
1005
- /** Filter of `where`: a Boolean expression, a query of one Boolean value, such as of `exists`, an object of column values, or their combination with `and`, `or`, and `not`. */
1006
- type WhereCondition<T extends AnyTable> = ConditionOperand<WhereValues<T>>;
1007
- /** Callback of `where` over table `T` with schema context `C`: it receives the columns and the queries of the relations of the table and returns a condition. */
1008
- type WhereCallback<T extends AnyTable, C extends SchemaContext = NoRelations> = (columns: ColumnRefs<T> & RelationRefs<C>) => WhereCondition<T>;
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. */
1010
- type WhereFilter<T extends AnyTable, C extends SchemaContext = NoRelations> = WhereCondition<T> | WhereCallback<T, C>;
1011
- /**
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.
1013
- *
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.
1016
- */
1017
- type QueryWhereFilter<S extends SelectQueryState> = [S] extends [unknown] ? WhereFilter<S["table"], S["schema"]> : never;
1018
- /**
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.
1020
- *
1021
- * A union of tables gives the union of their values.
1022
- */
1023
- type PrimaryKeyValues<T extends AnyTable> = T extends AnyTable ? T["keys"] extends TableKeys<infer PrimaryKey extends KeyColumns, infer _UniqueKey> ? { readonly [I in keyof PrimaryKey]: NonNullable<EqValue<T, PrimaryKey[I] & keyof T["columns"]>>; } : never : never;
1024
- /**
1025
- * Check of columns `Columns` of the object of `findBy` that rejects them unless they are exactly a key of table `T`, primary or unique, as the type of `T` tells.
1026
- *
1027
- * A table of `any`, such as of `AnySelectQuery`, takes any columns, as `where` takes any values there.
1028
- */
1029
- type KeyCheck<T extends AnyTable, Columns> = [IsKey<T, Columns>] extends [true] ? unknown : IsAny<T> extends true ? unknown : NotAKey<KeyOf<T["keys"]>>;
1030
- /** Type that the object of `findBy` is checked against when its columns are not exactly a key of the table, naming the keys of the table. */
1031
- interface NotAKey<Keys> {
1032
- readonly "columns must be exactly one key of the table": Keys;
1033
- }
1034
- /**
1035
- * Direction of a sort key, optionally with the placement of `NULL`.
1036
- *
1037
- * Without a placement, `NULL` comes last in ascending order and first in descending order.
1038
- */
1039
- type OrderDirection = "asc" | "desc" | "asc nulls first" | "asc nulls last" | "desc nulls first" | "desc nulls last";
1040
- /** Columns of table `T` with the directions to sort by them, in the order of their keys. */
1041
- type OrderColumns<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: OrderDirection; };
1042
- /** Argument of `orderBy` of a query over table `T`: a column key, sorted in ascending order, or columns with directions. */
1043
- type OrderKey<T extends AnyTable> = (keyof T["columns"] & string) | OrderColumns<T>;
1044
- declare const ordering: unique symbol;
1045
- /** Expression or query of one value with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
1046
- interface Ordering {
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>;
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. */
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"]];
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`. */
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; };
1075
- /** Values of the columns of table `T` that an update sets; a column omitted or given as `undefined` keeps its value. */
1076
- type UpdateValues<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: ColumnValue<T, K> | undefined; };
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>);
1079
- /** State `S` with the parts of `Changes` replaced. */
1080
- type ChangeState<S extends SelectQueryState, Changes extends Partial<SelectQueryState>> = { readonly [K in keyof SelectQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
916
+ type RowLockOptions = {
917
+ readonly noWait?: boolean;
918
+ readonly skipLocked?: false;
919
+ } | {
920
+ readonly noWait?: false;
921
+ readonly skipLocked?: boolean;
922
+ };
1081
923
  /** 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. */
1082
924
  type FilteredStateRows<S extends SelectQueryState> = [S["guaranteed"]] extends [false] ? S["rows"] : [S["value"]] extends [false] ? S["result"] extends HelperFields ? S["rows"] : FilteredRows<S["rows"], false> : FilteredRows<S["rows"], S["value"]>;
1083
925
  /** State `S` after a filter, which ends the guarantee of its row. */
@@ -1085,58 +927,25 @@ type FilteredState<S extends SelectQueryState> = ChangeState<S, {
1085
927
  rows: FilteredStateRows<S>;
1086
928
  guaranteed: false;
1087
929
  }>;
1088
- /** State `S` after a filter followed by `take`, as `find` and `findBy` change it. */
1089
- type FoundState<S extends SelectQueryState> = ChangeState<S, {
1090
- rows: OneRow<FilteredStateRows<S>>;
1091
- guaranteed: false;
1092
- }>;
1093
- /** Query of state `S`, bound or unbound. */
1094
- type QueryOf<S extends SelectQueryState> = SelectQuery<S, SelectQueryKind>;
1095
- declare const scalarValue: unique symbol;
1096
- /** Value of a query of state `S` in an expression: its value, or `NULL` without its row unless the query always has it. */
1097
- type ScalarValue<S extends SelectQueryState> = S["aggregate"] extends true ? S["result"] : S["guaranteed"] extends true ? S["result"] : S["result"] | null;
1098
- /**
1099
- * Query of one value of a table, such as of `get`, of an aggregate, or of `exists`, which an expression takes as a scalar subquery of its value, or as `EXISTS` of the rows of a query of `exists`.
1100
- *
1101
- * `T` is its value there: without its row, a query of `get` is `NULL`, unless a required relation guarantees the row, such as of `field.form`.
1102
- */
1103
- interface ScalarQuery<T = unknown> {
1104
- /** Value of the query in an expression, from which an expression infers `T`. */
1105
- readonly [scalarValue]: T;
1106
- readonly types: ScalarQueryState;
1107
- readonly exists: unknown;
1108
- }
1109
- /** Value of query `Q` of one value in an expression. */
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;
1113
- /** State of a query of one value, which an expression takes. */
1114
- interface ScalarQueryState extends SelectQueryState {
1115
- readonly rows: "one" | "optional";
1116
- readonly value: true;
1117
- }
1118
- /** State of a query of one value with the type of its value, whose expression `expr` gives. */
1119
- interface ExpressionQueryState extends ScalarQueryState {
1120
- readonly valueType: QueryValueType;
1121
- }
1122
- /** Query of one value of a table with the type of its value, such as of `get` or of an aggregate, which gives the expression of a function the decoding and the operators of its value. */
1123
- interface TypedScalarQuery extends ScalarQuery {
1124
- readonly types: ExpressionQueryState;
1125
- }
1126
- /** Query of values of a table of any rows, such as of `pluck`, whose value is `T`, which `in` takes as a subquery of its values. */
1127
- interface ValuesQuery<T = unknown> {
1128
- readonly types: ValuesQueryState<T>;
1129
- readonly exists: unknown;
1130
- }
1131
- /** Value of query `Q` of values, of each of its rows. */
1132
- type ValuesQueryValue<Q extends ValuesQuery> = Q["types"]["result"];
1133
- /** State of a query of values whose value is `T`. */
1134
- interface ValuesQueryState<T> extends SelectQueryState {
1135
- readonly result: T;
1136
- readonly value: true;
930
+ /** State `S` after a filter followed by `take`, as `find` and `findBy` change it, with the columns `K` of their key for `upsert`. */
931
+ interface FoundState<S extends SelectQueryState, K extends string> extends SelectQueryState, FoundKey<K> {
932
+ readonly table: S["table"];
933
+ readonly schema: S["schema"];
934
+ readonly result: S["result"];
935
+ readonly rows: OneRow<FilteredStateRows<S>>;
936
+ readonly value: S["value"];
937
+ readonly valueType: S["valueType"];
938
+ readonly fieldTypes: S["fieldTypes"];
939
+ readonly uses: S["uses"];
940
+ readonly guaranteed: false;
941
+ readonly aggregate: S["aggregate"];
1137
942
  }
943
+ /** State of a query of `find` or `findBy`, or of a singleton table, which `upsert` applies to. */
944
+ type FoundQueryState = SelectQueryState & {
945
+ readonly foundKey: string;
946
+ };
1138
947
  /** State of a query whose rows are records, which `select` and `clearSelect` change. */
1139
- type RecordQueryState = SelectQueryState & {
948
+ type RecordQueryState$1 = SelectQueryState & {
1140
949
  readonly value: false;
1141
950
  };
1142
951
  /** State of a query whose row no relation guarantees, which a filter keeps. */
@@ -1147,16 +956,22 @@ type UnguaranteedQueryState = SelectQueryState & {
1147
956
  type ValueQueryState = SelectQueryState & {
1148
957
  readonly value: true;
1149
958
  };
959
+ /** State of a query converted by `map`, whose callback of `orderBy` reads no selected fields, which its result no longer tells. */
960
+ type MappedQueryState = SelectQueryState & {
961
+ readonly value: "mapped";
962
+ };
1150
963
  /** State of a query of values with the values that the type of its value encodes, which `coalesce` takes; it narrows nothing else, so that a call compares no operators. */
1151
964
  type CoalesceQueryState = ValueQueryState & {
1152
965
  readonly valueType: {
1153
966
  readonly input: unknown;
1154
967
  };
1155
968
  };
1156
- /** State of a query not made by an aggregate method or `exists`, which `get`, `pluck`, the aggregate methods, and `exists` apply to. */
969
+ /** State of a query not made by an aggregate method or `exists`, which `get`, `pluck`, the aggregate methods, `exists`, and `groupBy` apply to. */
1157
970
  type UnaggregatedQueryState = SelectQueryState & {
1158
971
  readonly aggregate: false;
1159
972
  };
973
+ /** State of a query of values not made by an aggregate method or `exists`, such as of `pluck`, whose callback of `groupBy` reads its value. */
974
+ type UnaggregatedValueQueryState = ValueQueryState & UnaggregatedQueryState;
1160
975
  /** Type of the value of a query of column `K` of table `T`. */
1161
976
  type ColumnValueType<T extends AnyTable, K extends keyof T["columns"]> = {
1162
977
  readonly input: ColumnValues<T>[K];
@@ -1167,6 +982,27 @@ type OperandValueType<E extends TypedOperand> = {
1167
982
  readonly input: TypedOperandInput<E>;
1168
983
  readonly operators: TypedOperandOperators<E>;
1169
984
  };
985
+ /** State `S` after grouping, with the values of its directly selected aggregates in nonempty groups. */
986
+ interface GroupedState<S extends SelectQueryState> extends SelectQueryState {
987
+ readonly table: S["table"];
988
+ readonly schema: S["schema"];
989
+ readonly result: GroupedResult<S>;
990
+ readonly rows: S["rows"];
991
+ readonly value: S["value"];
992
+ readonly valueType: S["valueType"];
993
+ readonly fieldTypes: S["fieldTypes"];
994
+ readonly uses: S["uses"];
995
+ readonly guaranteed: S["guaranteed"];
996
+ readonly aggregate: false & Grouped;
997
+ }
998
+ /** Selected result after grouping, retaining the records or scalar value of the query. */
999
+ type GroupedResult<S extends SelectQueryState> = S["value"] extends false ? S["fieldTypes"] extends SelectedFieldTypes<unknown, unknown> ? GroupedRecord<S["result"], S["fieldTypes"]["types"]> : S["result"] : S["value"] extends true ? GroupedField<S["result"], S["valueType"]> : S["result"];
1000
+ /** Type of a selected operand, carrying its value in a group for a later call of `groupBy`. */
1001
+ interface SelectedOperandType<E extends TypedOperand> extends QueryValueType {
1002
+ readonly input: TypedOperandInput<E>;
1003
+ readonly operators: TypedOperandOperators<E>;
1004
+ readonly group: E extends GroupValue<infer V> ? V : unknown;
1005
+ }
1170
1006
  /** 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. */
1171
1007
  type AggregateState<S extends SelectQueryState, V, Type extends QueryValueType> = ChangeState<S, {
1172
1008
  result: V;
@@ -1198,14 +1034,42 @@ type CoalescedValue<V, F> = Exclude<V, null> | Extract<OperandValue<F>, null>;
1198
1034
  type ManyRowsQueryState = SelectQueryState & {
1199
1035
  readonly rows: "many";
1200
1036
  };
1037
+ /** State of a query that returns rows of its table, which a row lock applies to: not of an aggregate or of `exists`. */
1038
+ type LockableQueryState = SelectQueryState & ({
1039
+ readonly aggregate: false;
1040
+ } | {
1041
+ readonly value: "mapped";
1042
+ });
1201
1043
  /** State of a query of one row, which `optional` and `required` apply to. */
1202
1044
  type OneRowQueryState = SelectQueryState & {
1203
1045
  readonly rows: "one" | "nullable" | "optional";
1204
1046
  };
1205
- /** State of a query of one row whose rows are records, which `nullable` applies to. */
1047
+ /** State of a query of one row whose rows are records or what `map` gives, which `nullable` applies to. */
1206
1048
  type OneRecordQueryState = OneRowQueryState & {
1207
- readonly value: false;
1049
+ readonly value: false | "mapped";
1208
1050
  };
1051
+ /**
1052
+ * 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.
1053
+ *
1054
+ * A query may be `NULL` without its row, which PostgreSQL rejects for a column that is not nullable.
1055
+ */
1056
+ type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValues<T>[K] | AnyExpression<Selectable<T>[K]> | ScalarQuery<Selectable<T>[K] | null>;
1057
+ /** 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. */
1058
+ 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"]];
1059
+ /** 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`. */
1060
+ 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; };
1061
+ /** Values of `upsert` into table `T`: a record of an insert without the columns `K` of the key, whose values `find` or `findBy` gives. */
1062
+ type UpsertValues<T extends AnyTable, K extends string> = { readonly [C in keyof T["columns"] as C extends OptionalColumnKey<T> | K ? never : C]: ColumnValue<T, C>; } & { readonly [C in Exclude<OptionalColumnKey<T>, K>]?: ColumnValue<T, C> | undefined; };
1063
+ /** Values of the columns of table `T` that an update sets; a column omitted or given as `undefined` keeps its value. */
1064
+ type UpdateValues<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: ColumnValue<T, K> | undefined; };
1065
+ /** 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. */
1066
+ type UpdateSet<T extends AnyTable, C extends SchemaContext = NoRelations> = UpdateValues<T> | ((columns: ColumnRefs<T> & RelationRefs<C>) => UpdateValues<T>);
1067
+ /** Argument of `update` of a conflict of an insert into table `T` with schema context `C`: the values that it sets on the existing record, or a callback that receives the columns and the queries of the relations of the existing record and the columns of the row proposed for insertion, and returns them. */
1068
+ type ConflictUpdateSet<T extends AnyTable, C extends SchemaContext = NoRelations> = UpdateValues<T> | ((columns: ColumnRefs<T> & RelationRefs<C>, excluded: ColumnRefs<T>) => UpdateValues<T>);
1069
+ /** State `S` with the parts of `Changes` replaced. */
1070
+ type ChangeState<S extends SelectQueryState, Changes extends Partial<SelectQueryState>> = { readonly [K in keyof SelectQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
1071
+ /** Query of state `S`, bound or unbound. */
1072
+ type QueryOf<S extends SelectQueryState> = SelectQuery<S, SelectQueryKind>;
1209
1073
  /**
1210
1074
  * Immutable select query of state `S`, unbound or bound to a `Db`.
1211
1075
  *
@@ -1237,12 +1101,14 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1237
1101
  */
1238
1102
  where<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: QueryWhereFilter<S>): SelectQuery<FilteredState<S>, Kind>;
1239
1103
  /** Selects all columns of the table, replacing fields under their keys. */
1240
- select<S extends RecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
1104
+ select<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
1241
1105
  result: MergeSelection<S["result"], Selectable<S["table"]>>;
1106
+ fieldTypes: SelectedFieldTypes<S["fieldTypes"], ColumnFieldTypes<S["table"], keyof S["table"]["columns"]>>;
1242
1107
  }>, Kind>;
1243
1108
  /** Selects the listed columns, replacing fields under their keys. */
1244
- select<S extends RecordQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, ...keys: K[]): SelectQuery<ChangeState<S, {
1109
+ select<S extends RecordQueryState$1, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, ...keys: K[]): SelectQuery<ChangeState<S, {
1245
1110
  result: MergeSelection<S["result"], Pick<Selectable<S["table"]>, K>>;
1111
+ fieldTypes: SelectedFieldTypes<S["fieldTypes"], ColumnFieldTypes<S["table"], K>>;
1246
1112
  }>, Kind>;
1247
1113
  /**
1248
1114
  * Selects the expressions and nested queries returned by `callback`, replacing fields under their keys.
@@ -1251,13 +1117,15 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1251
1117
  * 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>`.
1252
1118
  * 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.
1253
1119
  */
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, {
1255
- result: MergeSelection<S["result"], SelectionResult<Sel>>;
1120
+ 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, {
1121
+ result: MergeSelection<S["result"], S["aggregate"] extends Grouped ? GroupSelectionResult<Sel> : SelectionResult<Sel>>;
1256
1122
  uses: S["uses"] | SelectionUses<Sel>;
1123
+ fieldTypes: SelectedFieldTypes<S["fieldTypes"], SelectionFieldTypes<Sel>>;
1257
1124
  }>, Kind>;
1258
1125
  /** Removes all selected fields and keeps the other clauses. */
1259
- clearSelect<S extends RecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1126
+ clearSelect<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1260
1127
  result: EmptyRecord;
1128
+ fieldTypes: EmptyRecord;
1261
1129
  }>, Kind>;
1262
1130
  /**
1263
1131
  * Limits the query to one row and returns the row instead of an array; without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
@@ -1273,15 +1141,17 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1273
1141
  *
1274
1142
  * A value is what `where` takes for its column, such as an expression, but never `null` or `undefined`.
1275
1143
  * Without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
1144
+ * To insert the record of the key or update the existing one, call `upsert` right after it.
1276
1145
  */
1277
- find<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, ...values: PrimaryKeyValues<S["table"]>): SelectQuery<FoundState<S>, Kind>;
1146
+ find<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, ...values: PrimaryKeyValues<S["table"]>): SelectQuery<FoundState<S, PrimaryKeyColumn<S["table"]>>, Kind>;
1278
1147
  /**
1279
1148
  * Filters the query by the values of the columns of one key of the table, primary or unique, and returns the row instead of an array, as `where` followed by `take`, but without a limit.
1280
1149
  *
1281
1150
  * A value is what `where` takes for its column, such as an expression, but never `null` or `undefined`.
1282
1151
  * Without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
1152
+ * To insert the record of the key or update the existing one, call `upsert` right after it.
1283
1153
  */
1284
- findBy<S extends SelectQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, values: { readonly [C in K]: NonNullable<EqValue<S["table"], C>>; } & KeyCheck<S["table"], K>): SelectQuery<FoundState<S>, Kind>;
1154
+ findBy<S extends SelectQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, values: { readonly [C in K]: NonNullable<EqValue<S["table"], C>>; } & KeyCheck<S["table"], K>): SelectQuery<FoundState<S, K>, Kind>;
1285
1155
  /**
1286
1156
  * Replaces the selected fields with a column, limits the query to one row, and returns the value of the column instead of a record.
1287
1157
  *
@@ -1305,8 +1175,8 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1305
1175
  * A `NULL` value is `null`.
1306
1176
  */
1307
1177
  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>;
1178
+ result: S["aggregate"] extends Grouped ? GroupOperandValue<E> : OperandValue<E>;
1179
+ valueType: SelectedOperandType<E>;
1310
1180
  rows: OneValueRows<S["rows"]>;
1311
1181
  value: true;
1312
1182
  uses: S["uses"] | OperandUses<E>;
@@ -1330,8 +1200,8 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1330
1200
  * 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.
1331
1201
  */
1332
1202
  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>;
1203
+ result: S["aggregate"] extends Grouped ? GroupOperandValue<E> : OperandValue<E>;
1204
+ valueType: SelectedOperandType<E>;
1335
1205
  rows: ValueRows<S["rows"]>;
1336
1206
  value: true;
1337
1207
  uses: S["uses"] | OperandUses<E>;
@@ -1339,7 +1209,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1339
1209
  /**
1340
1210
  * Replaces the selected fields with the number of rows of the query and returns the number instead of the rows.
1341
1211
  *
1342
- * It keeps the filters and ignores the order; with `limit` or `offset`, it counts the rows of that page.
1212
+ * It keeps the filters and ignores the order; with `limit` or `offset`, it counts the rows of that page, after `groupBy`, the groups, after `distinct`, the distinct rows of the selected fields, and after `distinctOn`, the first rows.
1343
1213
  */
1344
1214
  count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<CountState<S>, Kind>;
1345
1215
  /** 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. */
@@ -1417,7 +1287,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1417
1287
  /**
1418
1288
  * 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`.
1419
1289
  *
1420
- * It keeps the filters, the limit, and the offset, and ignores the order.
1290
+ * It keeps the filters, the limit, and the offset, and ignores the order; after `groupBy`, it tells whether the query has a group, and after `distinct` and `distinctOn`, it checks the distinct rows and the first rows.
1421
1291
  */
1422
1292
  exists<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<AggregateState<S, boolean, ExistsValueType>, Kind>;
1423
1293
  /**
@@ -1428,6 +1298,9 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1428
1298
  */
1429
1299
  coalesce<S extends CoalesceQueryState, Kind extends SelectQueryKind, F extends Operand<S["result"], S["valueType"]["input"]>>(this: SelectQuery<S, Kind>, fallback: F): SelectQuery<ChangeState<S, {
1430
1300
  result: CoalescedValue<S["result"], F>;
1301
+ valueType: S["valueType"] extends {
1302
+ readonly group: unknown;
1303
+ } ? Omit<S["valueType"], "group"> : S["valueType"];
1431
1304
  }>, Kind>;
1432
1305
  /**
1433
1306
  * Returns an expression of the value of a query of one value, such as of `get` or of an aggregate, with the operators of its type, such as `form.fields.count().expr().gt(3)`.
@@ -1435,6 +1308,36 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1435
1308
  * Without a row, the expression is `NULL`, and the query does not reject.
1436
1309
  */
1437
1310
  expr<Q extends QueryOf<ExpressionQueryState>>(this: Q): Expression<ScalarQueryValue<Q>, Q["types"]["valueType"]["operators"], Q["types"]["valueType"]["input"]>;
1311
+ /** Groups the rows by the listed columns, after the keys of earlier calls, so that the query gives one row of each group, whose fields are its keys and the aggregates of its rows, such as `sum(field.position)`. */
1312
+ groupBy<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, ...keys: (keyof S["table"]["columns"] & string)[]): SelectQuery<GroupedState<S>, Kind>;
1313
+ /**
1314
+ * Groups the rows by the keys returned by `callback`, after the keys of earlier calls, so that the query gives one row of each group, whose fields are its keys and the aggregates of its rows, such as `sum(field.position)`.
1315
+ *
1316
+ * `callback` receives the columns with the queries of the relations of the table, and the fields selected so far, and returns an expression or a query of one value, or an array of them.
1317
+ * A selected field groups by the value of the field; a field of nested rows or of a literal cannot be grouped by.
1318
+ * Methods that choose rows and read values, such as `limit`, `take`, and `pluck`, apply to the groups, and an aggregate method aggregates them, such as `count` for the number of the groups.
1319
+ * The query cannot take a row lock, `update`, or `delete`.
1320
+ */
1321
+ groupBy<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>, selected: SelectedRefs<S["result"]>) => GroupTerms): SelectQuery<GroupedState<S>, Kind>;
1322
+ /**
1323
+ * Groups the rows of a query made by `get` or `pluck` by the keys returned by `callback`, after the keys of earlier calls.
1324
+ *
1325
+ * `callback` receives the columns with the queries of the relations of the table, and the expression of the value, and returns what `groupBy` of a query of records takes.
1326
+ */
1327
+ groupBy<S extends UnaggregatedValueQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>, value: AnyExpression<S["result"]>) => GroupTerms): SelectQuery<GroupedState<S>, Kind>;
1328
+ /**
1329
+ * Filters the groups of a query of `groupBy` by what `where` takes, such as an aggregate of a group, combined with `AND` with the previous conditions of the groups; `where` keeps filtering the rows of the groups.
1330
+ *
1331
+ * A callback also receives the fields selected so far, such as `having((submission, selected) => selected.submissions.gt(1))`, or the value of a query made by `get` or `pluck`.
1332
+ */
1333
+ having<Q extends QueryOf<UnguaranteedQueryState>>(this: Q, filter: QueryHavingFilter<Q["types"]>): Q;
1334
+ /**
1335
+ * Filters the groups of a query of `groupBy` by what `where` takes, such as an aggregate of a group, combined with `AND` with the previous conditions of the groups; `where` keeps filtering the rows of the groups.
1336
+ *
1337
+ * A callback also receives the fields selected so far, or the value of a query made by `get` or `pluck`.
1338
+ * A query of the record of a required relation, such as `field.form`, resolves to `null` without a group that passes the filter, or to `undefined` after `get` or `pluck`.
1339
+ */
1340
+ having<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: QueryHavingFilter<S>): SelectQuery<FilteredState<S>, Kind>;
1438
1341
  /**
1439
1342
  * Sorts the rows by the sort keys returned by `callback`, after the sort keys of earlier calls.
1440
1343
  *
@@ -1442,7 +1345,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1442
1345
  * 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.
1443
1346
  * 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.
1444
1347
  */
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;
1348
+ 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;
1446
1349
  /**
1447
1350
  * 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.
1448
1351
  *
@@ -1450,53 +1353,126 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1450
1353
  * It returns an expression or a query of one value, sorted in ascending order, `asc`, `desc`, or `orderBy` of one, or an array of them.
1451
1354
  */
1452
1355
  orderBy<Q extends QueryOf<ValueQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, value: AnyExpression<Q["types"]["result"]>) => OrderTerms): Q;
1356
+ /**
1357
+ * Sorts the rows of a query that `map` converts by the sort keys returned by `callback`, after the sort keys of earlier calls.
1358
+ *
1359
+ * `callback` receives the columns with the queries of the relations of the table, and returns what `orderBy` of a query of records takes.
1360
+ */
1361
+ orderBy<Q extends QueryOf<MappedQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>) => OrderTerms): Q;
1453
1362
  /** Sorts the rows by the listed columns in ascending order, or in the directions of objects of columns, after the sort keys of earlier calls. */
1454
1363
  orderBy<Q extends AnySelectQuery>(this: Q, ...keys: OrderKey<Q["types"]["table"]>[]): Q;
1455
1364
  /** Returns at most `count` rows of a query of many rows, replacing an earlier limit. */
1456
1365
  limit<Q extends QueryOf<ManyRowsQueryState>>(this: Q, count: number): Q;
1457
1366
  /** Skips the first `count` rows of a query of many rows, replacing an earlier offset. */
1458
1367
  offset<Q extends QueryOf<ManyRowsQueryState>>(this: Q, count: number): Q;
1459
- /** Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without a row. */
1460
- optional<S extends OneRowQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1461
- rows: "optional";
1462
- guaranteed: false;
1463
- }>, Kind>;
1464
1368
  /**
1465
- * Makes a query of one record, such as one of `take`, resolve to `null` without a row.
1369
+ * Removes the duplicate rows of a query of many rows, such as of `pluck` for `in`, comparing the fields that the query selects, also those selected after it.
1466
1370
  *
1467
- * A value of `get` or `pluck` is never `null` for a missing row, which would read as a `NULL` value, so a query of values does not accept it, and after `get` or `pluck` the query resolves to `undefined` without a row.
1371
+ * Sort the query only by its selected fields.
1372
+ * The query cannot select nested rows, which `distinct` cannot compare.
1373
+ * The aggregate methods and `exists` after it read the distinct rows of the fields selected before them, and an aggregate method takes only a selected column or expression.
1468
1374
  */
1469
- nullable<S extends OneRecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1470
- rows: "nullable";
1471
- guaranteed: false;
1472
- }>, Kind>;
1473
- /** Makes a query of one row, such as one of `optional` or `nullable`, reject without a row. */
1474
- required<S extends OneRowQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1475
- rows: "one";
1476
- guaranteed: false;
1477
- }>, Kind>;
1375
+ distinct<Q extends QueryOf<ManyRowsQueryState>>(this: Q): Q;
1478
1376
  /**
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`.
1377
+ * Keeps the first row of each group of the rows of a query of many rows with equal values of the keys returned by `callback`, after the keys of earlier calls, such as the latest submission of each user.
1480
1378
  *
1481
- * A column omitted or given as `undefined` gets its default, so only columns marked with `hasDefault` and nullable columns may be omitted.
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.
1483
- * Select the fields that it returns after it, such as `insert(values).get("id")`.
1379
+ * `callback` receives the columns with the queries of the relations of the table, and the fields selected so far, and returns an expression or a query of one value, or an array of them; a field of nested rows or of a literal cannot be a key.
1380
+ * Sort the query by the keys first, then by the order that chooses the first row of each group; the rows keep that order.
1381
+ * To sort by a key of an expression, select it and take it from the second parameter of the callbacks of `distinctOn` and `orderBy`.
1382
+ * The aggregate methods and `exists` after it read the first rows, such as `count` for the number of the groups.
1484
1383
  */
1485
- insert<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, values: InsertValues<S["table"]>): MutationQuery<InitialMutationState<S["table"], S["schema"], "one">, Kind>;
1384
+ distinctOn<Q extends QueryOf<RecordQueryState$1 & ManyRowsQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, selected: SelectedRefs<Q["types"]["result"]>) => GroupTerms): Q;
1486
1385
  /**
1487
- * Inserts records into the table of a query without clauses, such as a table of a `Db`, in one statement, and resolves to the number of the inserted rows.
1386
+ * Keeps the first value of each group of the values of a query made by `pluck` with equal values of the keys returned by `callback`, after the keys of earlier calls.
1387
+ *
1388
+ * `callback` receives the columns with the queries of the relations of the table, and the expression of the value, and returns what `distinctOn` of a query of records takes.
1389
+ */
1390
+ distinctOn<Q extends QueryOf<ValueQueryState & ManyRowsQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, value: AnyExpression<Q["types"]["result"]>) => GroupTerms): Q;
1391
+ /**
1392
+ * Keeps the first row of each group of the rows of a query that `map` converts with equal values of the keys returned by `callback`, after the keys of earlier calls.
1393
+ *
1394
+ * `callback` receives the columns with the queries of the relations of the table, and returns what `distinctOn` of a query of records takes.
1395
+ */
1396
+ distinctOn<Q extends QueryOf<MappedQueryState & ManyRowsQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>) => GroupTerms): Q;
1397
+ /**
1398
+ * Keeps the first row of each group of the rows of a query of many rows with equal values of the listed columns, after the keys of earlier calls, such as the latest submission of each user.
1399
+ *
1400
+ * Sort the query by the keys first, then by the order that chooses the first row of each group; the rows keep that order.
1401
+ */
1402
+ distinctOn<Q extends QueryOf<ManyRowsQueryState>>(this: Q, ...keys: (keyof Q["types"]["table"]["columns"] & string)[]): Q;
1403
+ /**
1404
+ * Locks the rows of the query until its transaction ends, so that code can read a row and then update it based on the values it read: another transaction waits to change or lock them.
1405
+ *
1406
+ * It replaces an earlier lock of the query, and reaches no other query: lock the records of a nested query by calling it there.
1407
+ * Without `options`, the query waits for the rows that another transaction has locked.
1408
+ *
1409
+ * It requires a transaction, unless the query is part of a mutation, such as of its filter.
1410
+ * The query cannot use `distinct`, `distinctOn`, or `groupBy`, and the aggregate methods and `exists` reject it after the lock.
1411
+ */
1412
+ forUpdate<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
1413
+ /**
1414
+ * Locks the rows of the query as `forUpdate` does, but lets other transactions insert records that refer to them.
1415
+ *
1416
+ * Use it when the transaction only updates columns outside the keys of the rows.
1417
+ */
1418
+ forNoKeyUpdate<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
1419
+ /** Keeps the rows of the query from changing until its transaction ends, as `forUpdate` does, while other transactions read and share-lock them too. */
1420
+ forShare<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
1421
+ /** Keeps the rows of the query from being deleted or changing their keys until its transaction ends, as `forUpdate` does, while other transactions change their other columns. */
1422
+ forKeyShare<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
1423
+ /** Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without a row. */
1424
+ optional<S extends OneRowQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1425
+ rows: "optional";
1426
+ guaranteed: false;
1427
+ }>, Kind>;
1428
+ /**
1429
+ * Makes a query of one record, such as one of `take`, resolve to `null` without a row.
1430
+ *
1431
+ * A value of `get` or `pluck` is never `null` for a missing row, which would read as a `NULL` value, so a query of values does not accept it, unless `map` converts them, and after `get` or `pluck` the query resolves to `undefined` without a row.
1432
+ */
1433
+ nullable<S extends OneRecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1434
+ rows: "nullable";
1435
+ guaranteed: false;
1436
+ }>, Kind>;
1437
+ /** Makes a query of one row, such as one of `optional` or `nullable`, reject without a row. */
1438
+ required<S extends OneRowQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
1439
+ rows: "one";
1440
+ guaranteed: false;
1441
+ }>, Kind>;
1442
+ /**
1443
+ * 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`.
1444
+ *
1445
+ * A column omitted or given as `undefined` gets its default, so only columns marked with `hasDefault` and nullable columns may be omitted.
1446
+ * 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.
1447
+ * Select the fields that it returns after it, such as `insert(values).get("id")`.
1448
+ * To handle a conflict of the record with an existing one on a key, call `onConflict` right after `insert`.
1449
+ */
1450
+ insert<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, values: InsertValues<S["table"]>): MutationQuery<InitialInsertState<S["table"], S["schema"], "one">, Kind>;
1451
+ /**
1452
+ * Inserts records into the table of a query without clauses, such as a table of a `Db`, in one statement, and resolves to the number of the inserted rows.
1488
1453
  *
1489
1454
  * A record takes the values that `insert` takes, and a column that a record omits gets its default.
1490
1455
  * 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.
1456
+ * To handle a conflict of a record with an existing one on a key, call `onConflict` right after `insertMany`.
1457
+ * A singleton table, which holds one row, takes `insert` or `upsert` instead.
1458
+ */
1459
+ insertMany<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, records: readonly InsertValues<S["table"]>[] & InsertManyCheck<S["table"]>): MutationQuery<InitialInsertState<S["table"], S["schema"], "many">, Kind>;
1460
+ /**
1461
+ * Inserts the record of the key of `find` or `findBy` with `values`, or updates `values` of the existing record of the key, in one statement, and resolves to the number of the inserted or updated rows, `1`.
1462
+ *
1463
+ * `values` takes what `insert` takes, apart from the columns of the key, and at least one value other than `undefined`; a column omitted or given as `undefined` gets its default when the record is inserted and keeps its value when the record is updated.
1464
+ * Call it right after `find` or `findBy` of a query of a table without other clauses, such as filters, or on a query of a singleton table without clauses, such as `db.settings.upsert(values)`, to insert or update its row.
1465
+ * Select the fields that it returns after it, such as `upsert(values).get("id")`.
1466
+ * To update the existing record with other values than the inserted ones, such as to increment a counter, call `onConflict` after `insert` instead.
1491
1467
  */
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>;
1468
+ upsert<S extends FoundQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, values: UpsertValues<S["table"], S["foundKey"]>): MutationQuery<InitialMutationState<S["table"], S["schema"], "one">, Kind>;
1493
1469
  /**
1494
1470
  * 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
1471
  *
1496
1472
  * `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
1473
  * A value is what `insert` takes as a value, such as a query of an aggregate of related records.
1498
1474
  * 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.
1475
+ * A query without a filter must call `all` to update every row, unless it is a query of a singleton table, which updates its row.
1500
1476
  * Select the fields that it returns after it, with their values after the update, such as `update(callback).select("id")`.
1501
1477
  */
1502
1478
  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>;
@@ -1506,7 +1482,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1506
1482
  * `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
1483
  * A value is what `insert` takes as a value.
1508
1484
  * A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
1509
- * A query without a filter must call `all` to update every row.
1485
+ * A query without a filter must call `all` to update every row, unless it is a query of a singleton table, which updates its row.
1510
1486
  * Select the fields that it returns after it, with their values after the update, such as `update(set).select("id")`.
1511
1487
  */
1512
1488
  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>;
@@ -1514,12 +1490,32 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1514
1490
  * Deletes the rows that the filters of the query choose, and resolves to the number of the deleted rows.
1515
1491
  *
1516
1492
  * A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
1517
- * A query without a filter must call `all` to delete every row.
1493
+ * A query without a filter must call `all` to delete every row, unless it is a query of a singleton table, which deletes its row.
1518
1494
  * Select the fields that it returns after it, such as `delete().pluck("id")`.
1519
1495
  */
1520
1496
  delete<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"]>, Kind>;
1521
1497
  /** Allows `update` and `delete` to change every row of the table when the query has no filter; it changes nothing else. */
1522
1498
  all<Q extends QueryOf<ManyRowsQueryState>>(this: Q): Q;
1499
+ /**
1500
+ * Converts each record or value of the result in code, after decoding, executed or nested, such as to add a field that SQL cannot compute.
1501
+ *
1502
+ * `callback` receives one record or value, also `null` of a `NULL` value, and is not called for a missing row, so an optional query still resolves to `undefined` without a row; it returns its result synchronously.
1503
+ * The SQL stays as it is, so the methods that read the fields, such as `select` and `count`, and expressions reject the query after it, whereas `where`, `orderBy`, `limit`, `take`, and further `map` apply.
1504
+ * A failure of `callback` rejects with `ResultDecodeError`, whose cause is the error.
1505
+ */
1506
+ map<S extends SelectQueryState, Kind extends SelectQueryKind, R>(this: SelectQuery<S, Kind>, callback: (row: S["result"]) => R & SynchronousResult<R>): SelectQuery<ChangeState<S, {
1507
+ result: R;
1508
+ value: "mapped";
1509
+ aggregate: true;
1510
+ }>, Kind>;
1511
+ /**
1512
+ * Converts the whole result in code, after decoding, executed or nested, such as to group rows or to compute a value from them.
1513
+ *
1514
+ * `callback` receives what the query resolves to, once: the array of rows, one row, or `null` or `undefined` of a missing row of a nullable or optional query; it returns its result synchronously.
1515
+ * The SQL stays as it is, so call it last: the returned query only executes, nests in a selection, and takes further `transform`.
1516
+ * A failure of `callback` rejects with `ResultDecodeError`, whose cause is the error.
1517
+ */
1518
+ transform<S extends SelectQueryState, Kind extends SelectQueryKind, R>(this: SelectQuery<S, Kind>, callback: (result: QueryResult<S>) => R & SynchronousResult<R>): TransformedQuery<TransformedQueryState<S["table"], R, S["uses"]>, Kind>;
1523
1519
  /**
1524
1520
  * 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`.
1525
1521
  *
@@ -1544,7 +1540,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1544
1540
  * It rejects a query of records, which `ValuesQuery` rejects in types.
1545
1541
  */
1546
1542
  [valuesQueryNode](): NestedQueryNode;
1547
- /** Creates a query of the same kind and `Db` with the node changes applied. */
1543
+ /** Creates a query of the same kind and `Db` with the node changes applied, dropping the key of `find` and `findBy` unless the changes give it. */
1548
1544
  private derive;
1549
1545
  /**
1550
1546
  * Creates a query of the same kind and `Db` with the node changes applied and then those of `take`, in one derived query.
@@ -1552,20 +1548,40 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
1552
1548
  * It adds the changes of `take` to `changes`, which must leave the limit as it is.
1553
1549
  */
1554
1550
  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. */
1551
+ /**
1552
+ * 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.
1553
+ *
1554
+ * A query of `distinct` or `distinctOn` keeps the fields that `projection` replaces: `distinct` compares them, and the keys, the order, and the argument of an aggregate read a selected field through its projection.
1555
+ */
1556
1556
  private deriveAggregate;
1557
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
1558
  private aggregateBy;
1559
1559
  /** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
1560
1560
  private addFilter;
1561
- /** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
1561
+ /** Returns the rows mode of this query after a filter, as `FilteredStateRows` gives it in types. */
1562
+ private getFilteredRows;
1563
+ /**
1564
+ * Creates the query of `find` and `findBy`: `where` of `values`, an object of the values of the columns of a key, returning one row like `take`.
1565
+ *
1566
+ * On a query of a table without clauses, it keeps `values` as the key that `upsert` inserts.
1567
+ */
1562
1568
  private takeWhere;
1563
1569
  /** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
1564
1570
  private changeOneRow;
1571
+ /** Rejects `method`, which reads or changes the fields of the query, on a query that `map` converts. */
1572
+ private rejectMapped;
1565
1573
  /** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
1566
1574
  private rejectValue;
1567
1575
  /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method or `exists`. */
1568
1576
  private rejectAggregate;
1577
+ /** Rejects `method`, an aggregate method or `exists`, on a query made by one of them or with a row lock. */
1578
+ private rejectAggregation;
1579
+ }
1580
+ /** Check of the records of `insertMany` into table `T` that rejects them for a singleton table, which holds one row. */
1581
+ type InsertManyCheck<T extends AnyTable> = T["singleton"] extends true ? SingletonInsertMany : unknown;
1582
+ /** Type that the records of `insertMany` into a singleton table are checked against, naming the reason. */
1583
+ interface SingletonInsertMany {
1584
+ readonly "insertMany cannot insert into a singleton table, which holds one row; use insert or upsert": never;
1569
1585
  }
1570
1586
  /** Select query bound to a `Db`, executed by awaiting it; every method returns a query bound to the same `Db`. */
1571
1587
  type BoundSelectQuery<S extends SelectQueryState> = SelectQuery<S, "bound">;
@@ -1576,7 +1592,215 @@ type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
1576
1592
  /** Table of a definition such as `defineExpression`: the table itself or a query over it with schema context `C`, such as `schema.form`. */
1577
1593
  type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
1578
1594
  /** Starts a query over a new occurrence of the table. */
1579
- declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T>>;
1595
+ declare function from<T extends Table<string, ColumnShape, AnyTableKeys, false>>(table: T): SelectQuery<InitialQueryState<T>>;
1596
+ /** Starts a query of the one row of a singleton table over a new occurrence of the table. */
1597
+ declare function from<T extends Table<string, ColumnShape, AnyTableKeys, true>>(table: T): SelectQuery<SingletonQueryState<T>>;
1598
+ /** Starts a query over a new occurrence of a table whose type does not tell whether it is a singleton table, of all its rows or of its one row. */
1599
+ declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T> | SingletonQueryState<T>>;
1600
+ /** References to the columns of the query source, passed to query callbacks. */
1601
+ type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
1602
+ /**
1603
+ * 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.
1604
+ *
1605
+ * A relation name is never a column key of its table.
1606
+ * A context whose table key is not known, such as one of a query of any schema, has no relations.
1607
+ */
1608
+ type RelationRefs<C extends SchemaContext> = string extends C["key"] ? EmptyRecord : C["key"] extends keyof C["relations"] ? RelationQueries<C["relations"], C["key"]> : EmptyRecord;
1609
+ type RelationQueries<R extends SchemaContext["relations"], K extends keyof R & string> = { readonly [N in keyof R[K]]: RelatedQuery<R, K, N & string>; };
1610
+ /** Unbound query of the records of relation `N` of the table under key `K` of a schema of relations `R`, in the schema context of its target and the rows mode of the relation, whose row a required relation guarantees. */
1611
+ 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"]>>;
1612
+ /** Runtime context of the queries of a table in the schema they start from. */
1613
+ interface QueryContext {
1614
+ /** 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. */
1615
+ readonly relations: PropertyDescriptorMap;
1616
+ }
1617
+ /**
1618
+ * Direction of a sort key, optionally with the placement of `NULL`.
1619
+ *
1620
+ * Without a placement, `NULL` comes last in ascending order and first in descending order.
1621
+ */
1622
+ type OrderDirection = "asc" | "desc" | "asc nulls first" | "asc nulls last" | "desc nulls first" | "desc nulls last";
1623
+ /** Columns of table `T` with the directions to sort by them, in the order of their keys. */
1624
+ type OrderColumns<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: OrderDirection; };
1625
+ /** Argument of `orderBy` of a query over table `T`: a column key, sorted in ascending order, or columns with directions. */
1626
+ type OrderKey<T extends AnyTable> = (keyof T["columns"] & string) | OrderColumns<T>;
1627
+ declare const ordering: unique symbol;
1628
+ /** Expression or query of one value with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
1629
+ interface Ordering {
1630
+ readonly [ordering]: true;
1631
+ }
1632
+ /** 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. */
1633
+ type OrderTerm = AnyExpression | ScalarQuery | Ordering;
1634
+ /**
1635
+ * References of the callbacks of `orderBy`, `groupBy`, and `distinctOn` to the fields of records `R` selected by a query: their expressions by key.
1636
+ *
1637
+ * 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` gives its value.
1638
+ */
1639
+ type SelectedRefs<R> = { readonly [K in keyof R & string]: AnyExpression<R[K]>; };
1640
+ /** Sort keys returned by the callback of `orderBy`: one or an array of them. */
1641
+ type OrderTerms = OrderTerm | readonly OrderTerm[];
1642
+ /** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
1643
+ declare function asc(value: AnyExpression | ScalarQuery): Ordering;
1644
+ /** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
1645
+ declare function desc(value: AnyExpression | ScalarQuery): Ordering;
1646
+ /** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
1647
+ declare function orderBy(value: AnyExpression | ScalarQuery, direction: OrderDirection): Ordering;
1648
+ /** Expression of a count: a number, with the operators of `orderingOperators`. */
1649
+ type CountExpression = Expression<number, CountValueType["operators"], CountValueType["input"]>;
1650
+ /** Expression of an aggregate of the values of `E`, an expression or a query of one value, `NULL` without values other than `NULL`, with the operators of its type. */
1651
+ type AggregateExpression<E extends TypedOperand> = Expression<OperandValue<E> | null, TypedOperandOperators<E>, TypedOperandInput<E>>;
1652
+ declare const groupValue: unique symbol;
1653
+ /** Value `T` of a directly selected expression in a nonempty group. */
1654
+ interface GroupValue<T> {
1655
+ readonly [groupValue]: T;
1656
+ }
1657
+ /** Aggregate without a filter, whose value in a group keeps only the nullability of its argument. */
1658
+ type GroupAggregateExpression<E extends TypedOperand> = AggregateExpression<E> & GroupValue<OperandValue<E>>;
1659
+ /** Options of an aggregate function. */
1660
+ interface AggregateOptions {
1661
+ /** Condition of the rows that the function aggregates, as `FILTER (WHERE ...)`: a Boolean expression or a query of one Boolean value. */
1662
+ readonly filter?: AnyExpression<boolean | null> | ScalarQuery<boolean | null>;
1663
+ }
1664
+ /** Options of `stringAgg`. */
1665
+ interface StringAggOptions extends AggregateOptions {
1666
+ /** Order in which the values are joined: a sort key or an array of them, as the callback of `orderBy` of a query returns; without it, PostgreSQL joins them in any order. */
1667
+ readonly orderBy?: OrderTerms;
1668
+ }
1669
+ /** Options of an aggregate function without `filter`, which takes every row. */
1670
+ interface UnfilteredAggregateOptions {
1671
+ /** No rows are removed from the aggregate input. */
1672
+ readonly filter?: undefined;
1673
+ }
1674
+ /** Options of `stringAgg` without `filter`, which takes every row. */
1675
+ interface UnfilteredStringAggOptions extends UnfilteredAggregateOptions {
1676
+ /** Order in which the values are joined: a sort key or an array of them, as the callback of `orderBy` of a query returns; without it, PostgreSQL joins them in any order. */
1677
+ readonly orderBy?: OrderTerms;
1678
+ }
1679
+ /** Returns the number of the rows of the query that selects it, or of each of its groups, as `count(*)`. */
1680
+ declare function count(): CountExpression;
1681
+ /** Returns the number of the rows of the query that selects it, or of each of its groups, as `count(*)`; `options.filter` chooses the rows that it counts. */
1682
+ declare function count(options: AggregateOptions): CountExpression;
1683
+ /** Returns the number of the values of `value`, an expression with a type or a query of one value, other than `NULL`; `options.filter` chooses the rows that it takes. */
1684
+ declare function count(value: TypedOperand, options?: AggregateOptions): CountExpression;
1685
+ /** Returns the number of the distinct values of `value`, an expression with a type or a query of one value, other than `NULL`; `options.filter` chooses the rows that it takes. */
1686
+ declare function countDistinct(value: TypedOperand, options?: AggregateOptions): CountExpression;
1687
+ /** Returns the smallest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`. */
1688
+ declare function min<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
1689
+ /** Returns the smallest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
1690
+ declare function min<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
1691
+ /** Returns the largest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`. */
1692
+ declare function max<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
1693
+ /** Returns the largest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
1694
+ declare function max<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
1695
+ /** Returns the sum of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`. */
1696
+ declare function sum<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
1697
+ /** Returns the sum of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
1698
+ declare function sum<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
1699
+ /**
1700
+ * Returns the average of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`.
1701
+ *
1702
+ * For `bigint` values, average an expression of a type that can represent fractional values.
1703
+ */
1704
+ declare function avg<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
1705
+ /**
1706
+ * Returns the average of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes.
1707
+ *
1708
+ * For `bigint` values, average an expression of a type that can represent fractional values.
1709
+ */
1710
+ declare function avg<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
1711
+ /** Returns whether every value of `value`, a Boolean expression with a type or a query of one Boolean value, other than `NULL` is true, or `null` without such values. */
1712
+ declare function every<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
1713
+ /** Returns whether every value of `value`, a Boolean expression with a type or a query of one Boolean value, other than `NULL` is true, or `null` without such values; `options.filter` chooses the rows that it takes. */
1714
+ declare function every<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
1715
+ /** Returns whether any value of `value`, a Boolean expression with a type or a query of one Boolean value, is true, or `null` without values other than `NULL`. */
1716
+ declare function some<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
1717
+ /** Returns whether any value of `value`, a Boolean expression with a type or a query of one Boolean value, is true, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
1718
+ declare function some<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
1719
+ /** Returns the values other than `NULL` of `value`, a text expression with a type or a query of one text value, joined with `delimiter` in the order of `options.orderBy`, or `null` without such values. */
1720
+ declare function stringAgg<E extends TypedOperand>(value: E, delimiter: string, options?: UnfilteredStringAggOptions): GroupAggregateExpression<E>;
1721
+ /** Returns the values other than `NULL` of `value`, a text expression with a type or a query of one text value, joined with `delimiter` in the order of `options.orderBy`, or `null` without such values; `options.filter` chooses the rows that it takes. */
1722
+ declare function stringAgg<E extends TypedOperand>(value: E, delimiter: string, options?: StringAggOptions): AggregateExpression<E>;
1723
+ /**
1724
+ * Field of a selection whose value is `T`, made by `literal`.
1725
+ *
1726
+ * It is not an expression: it has no SQL, so only a selection takes it.
1727
+ */
1728
+ declare class Literal<out T> {
1729
+ /** Value of the field in every record, which the query returns as it is. */
1730
+ readonly literal: T;
1731
+ constructor(
1732
+ /** Value of the field in every record, which the query returns as it is. */
1733
+ literal: T);
1734
+ /** Rejects the literal as an operand of an expression: a statement has no SQL of it. */
1735
+ [operandNode](): never;
1736
+ }
1737
+ /**
1738
+ * 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.
1739
+ *
1740
+ * It lets a branch of a selection skip a column or a nested query, such as `withHint ? field.hint : literal(null)`.
1741
+ * To use a value in SQL, such as in a condition, pass it through `param` instead.
1742
+ */
1743
+ declare function literal<T extends {} | null | undefined>(value: T): Literal<T>;
1744
+ /** Expressions, nested queries, and literals selected under the keys of the result fields; a record has no symbol keys. */
1745
+ interface Selection {
1746
+ readonly [key: string]: TypedExpression | NestedQuery | Literal<unknown>;
1747
+ readonly [key: symbol]: never;
1748
+ }
1749
+ /** 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, also converted by `map` or `transform`. */
1750
+ type NestedQuery = QueryOf<SelectQueryState> | TransformedQuery<TransformedQueryState, SelectQueryKind>;
1751
+ /** Record of the values of the expressions, of the nested rows, and of the literals of a selection. */
1752
+ type SelectionResult<S extends Selection> = { [K in keyof S]: FieldValue<S[K]>; };
1753
+ /** Record of a selection in a query of groups. */
1754
+ type GroupSelectionResult<S extends Selection> = { [K in keyof S]: GroupFieldValue<S[K]>; };
1755
+ /** Value of a field selected in a group, leaving nested queries and literals unchanged. */
1756
+ type GroupFieldValue<V> = V extends GroupValue<infer T> ? T : FieldValue<V>;
1757
+ /** Value of an operand in a query of groups. */
1758
+ type GroupOperandValue<E> = E extends GroupValue<infer T> ? T : OperandValue<E>;
1759
+ /** 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. */
1760
+ type FieldValue<V> = V extends NestedQuery ? QueryResult<V["types"]> : V extends Literal<infer T> ? T : ExpressionValue<V>;
1761
+ /** Relations whose records the nested queries of a selection select. */
1762
+ type SelectionUses<S extends Selection> = S[keyof S] extends (infer V) ? V extends NestedQuery ? V["types"]["uses"] : never : never;
1763
+ /** Value of a selected expression. */
1764
+ type ExpressionValue<E> = E extends AnyExpression<infer T> ? T : never;
1765
+ /** Values that the type of an expression encodes, such as in place of its value. */
1766
+ type ExpressionInput<E> = E extends AnyExpression<unknown, infer I> ? I : never;
1767
+ declare const helperFields: unique symbol;
1768
+ /** Marker of the input fields of a helper, carrying the keys selected by its callback. */
1769
+ interface HelperFields<Keys extends PropertyKey = PropertyKey> {
1770
+ readonly [helperFields]: Keys;
1771
+ }
1772
+ /** Result `R` of a callback of a helper without the marker, which a record of the callback keeps, also through a spread, so that the declarations of a module exporting a helper never name it; `any` stays `any`. */
1773
+ type WithoutHelperFields<R> = IsAny<R> extends true ? R : R extends HelperFields ? { [K in keyof R as K extends keyof HelperFields ? never : K]: R[K]; } : R;
1774
+ /** Records with `Fields` added or replaced, for each branch of either record type; `any` stays `any`. */
1775
+ type MergeSelection<Previous, Fields> = Previous extends unknown ? Fields extends unknown ? MergeFields<RecordFields<Previous>, RecordFields<Fields>> & (IsAny<Previous> extends true ? Previous : unknown) : never : never;
1776
+ /** Fields with numeric keys represented as the string keys used in result records. */
1777
+ 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;
1778
+ /** Merge of normalized fields, retaining the previous value when an optional replacement is absent. */
1779
+ 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.
1780
+ ? Previous[K] | keyof Fields : K extends keyof Fields // A decoder can return undefined, so it cannot be excluded as merely an absent property.
1781
+ ? Previous[K] | Fields[K] : Previous[K]; } & { [K in keyof Fields as K extends keyof Previous ? ({} extends Pick<Fields, K> ? never : K) : K]: Fields[K]; }>;
1782
+ /** Types of the values of columns `K` of table `T` as selected fields: the values that each encodes and its operators. */
1783
+ type ColumnFieldTypes<T extends AnyTable, K extends keyof T["columns"]> = { [P in K]: ColumnValueType<T, P>; };
1784
+ /** Types of the values of the expressions and the queries of one value of selection `Sel`, under the keys of the result records, as `MergeSelection` normalizes them. */
1785
+ type SelectionFieldTypes<Sel> = { [K in keyof Sel as K extends number ? `${K}` : K]: FieldType<Exclude<Sel[K], undefined>>; };
1786
+ /** Type of the value of a selected field `F`, for each member of a union of them, so that each keeps its own operators and values. */
1787
+ type FieldType<F> = F extends TypedOperand ? F extends GroupValue<infer T> ? OperandValueType<F> & {
1788
+ readonly group: T;
1789
+ } : OperandValueType<F> : unknown;
1790
+ /** Record `R` of a query whose rows become groups, with field types `F`. */
1791
+ type GroupedRecord<R, F> = IsAny<R> extends true ? R : R extends unknown ? { [K in keyof R]: K extends keyof F ? GroupedField<R[K], Exclude<F[K], undefined>> : R[K]; } : never;
1792
+ /** Value of a selected field after grouping; a union of field types must all guarantee a non-null value to remove `null`. */
1793
+ type GroupedField<V, D> = [D] extends [{
1794
+ readonly group: infer G;
1795
+ }] ? null extends G ? V : Exclude<V, null> : V;
1796
+ /** Types of the values of fields `P` with those of fields `N` added or replaced, by the rules of `MergeSelection`, for each branch of either. */
1797
+ type MergeFieldTypes<P, N> = P extends unknown ? N extends unknown ? [keyof N] extends [never] ? P : [keyof P] extends [never] ? N : { [K in keyof P | keyof N]: K extends keyof N ? {} extends Pick<N, K> ? K extends keyof P ? P[K] | Exclude<N[K], undefined> : Exclude<N[K], undefined> : N[K] : K extends keyof P ? P[K] : never; } : never : never;
1798
+ /** Types of the values of the selected fields of a query: those of `P`, the `fieldTypes` part of the state before a selection, with `N` added or replaced. */
1799
+ interface SelectedFieldTypes<out P, N> {
1800
+ readonly types: MergeFieldTypes<SelectedFieldTypesOf<P>, N>;
1801
+ }
1802
+ /** Types of the values of the selected fields of the `fieldTypes` part `F` of a state, by key; none for `EmptyRecord` of a query without selected fields. */
1803
+ type SelectedFieldTypesOf<F> = F extends SelectedFieldTypes<unknown, unknown> ? F["types"] : EmptyRecord;
1580
1804
  /** 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
1805
  type TypedOperand = TypedExpression | TypedScalarQuery;
1582
1806
  /** Values that the type of the first operand `F` encodes. */
@@ -1629,7 +1853,115 @@ declare function caseWhen<Output, Input, O extends OperatorDefinitions>(type: Ty
1629
1853
  */
1630
1854
  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>;
1631
1855
  /**
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.
1856
+ * 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.
1857
+ *
1858
+ * It is guaranteed, so that the state that the callback returns tells whether the callback ends the guarantee of the query the helper is applied to.
1859
+ */
1860
+ interface HelperState<T extends AnyTable, C extends SchemaContext> extends QueryStateOf<T, C> {
1861
+ readonly result: HelperFields<never>;
1862
+ readonly valueType: never;
1863
+ readonly fieldTypes: EmptyRecord;
1864
+ readonly rows: "many";
1865
+ readonly value: false;
1866
+ readonly uses: never;
1867
+ readonly guaranteed: true;
1868
+ readonly aggregate: false;
1869
+ }
1870
+ /**
1871
+ * Effect of a helper: the fields it selects and the types of their values, or whether `map` converts its rows and what it gives, its rows mode on a query of many rows, `one` after `take` or `required` and `nullable` or `optional` after the method of the same name, the relations it selects records of, and whether it keeps the guarantee of the row of a query of a required relation.
1872
+ *
1873
+ * `reads` are the relations of the schema of the helper among them, which its callback may read from the references of the query it is applied to, and `key` is the key of its table there.
1874
+ */
1875
+ interface HelperEffect {
1876
+ /** Whether the helper guarantees that the query is grouped. */
1877
+ readonly grouped: boolean;
1878
+ readonly fields: object;
1879
+ /** Types of the values of the fields it selects, the `fieldTypes` part of the state that its callback returns, which `having` and the narrowing of grouped selections read. */
1880
+ readonly fieldTypes: unknown;
1881
+ /** Whether `map` converts the rows, whose fields the result no longer tells, so that `fields` are empty. */
1882
+ readonly mapped: boolean;
1883
+ /** What `map` gives for each row of a query the helper is applied to; `never` when `mapped` is `false`. */
1884
+ readonly output: unknown;
1885
+ readonly rows: ResultRows;
1886
+ readonly uses: UsedRelation;
1887
+ readonly reads: UsedRelation;
1888
+ readonly key: string;
1889
+ readonly guaranteed: boolean;
1890
+ }
1891
+ /** Effect of a helper whose callback returns a query of state `S`, for each state of a union. */
1892
+ type ReadEffect<S extends SelectQueryState> = S extends SelectQueryState ? {
1893
+ readonly grouped: S["aggregate"] extends Grouped ? true : false;
1894
+ readonly fields: S["value"] extends "mapped" ? EmptyRecord : { [K in keyof S["result"] as K extends keyof HelperFields ? never : K]: S["result"][K]; };
1895
+ readonly fieldTypes: S["value"] extends "mapped" ? EmptyRecord : S["fieldTypes"];
1896
+ readonly mapped: S["value"] extends "mapped" ? true : false;
1897
+ readonly output: S["value"] extends "mapped" ? WithoutHelperFields<S["result"]> : never;
1898
+ readonly rows: S["rows"];
1899
+ readonly uses: S["uses"];
1900
+ readonly reads: Extract<UsableRelation<S["schema"]["relations"]>, S["uses"]>;
1901
+ readonly key: S["schema"]["key"];
1902
+ readonly guaranteed: S["guaranteed"];
1903
+ } : never;
1904
+ /** Error of a helper that a query does not accept, or whose callback returns a query it does not accept. */
1905
+ interface HelperError<Message extends string> {
1906
+ readonly error: Message;
1907
+ }
1908
+ /** `unknown` when every result state retains the input marker and returns records, or converts such records with `map`, or the error. */
1909
+ type CheckResult<S extends SelectQueryState> = [S] extends [{
1910
+ readonly result: HelperFields;
1911
+ readonly value: false;
1912
+ } | {
1913
+ readonly value: "mapped";
1914
+ readonly valueType: never;
1915
+ }] ? unknown : HelperError<"A helper can filter, select fields, map them, and take one row, but cannot clear the selection or use get, pluck, or aggregates">;
1916
+ /** State of a query over table `T` that accepts a helper of effect `E`. */
1917
+ type HelperInput<T extends AnyTable, E extends HelperEffect> = QueryStateOf<T, ReadsContext<E>> & ValueCheck<E> & (true extends E["grouped"] ? {
1918
+ readonly aggregate: false;
1919
+ } : unknown);
1920
+ /** Constraint of `value` of a query that accepts a helper of effect `E`. */
1921
+ type ValueCheck<E extends HelperEffect> = [E extends HelperEffect ? keyof E["fields"] : never] extends [never] ? [Extract<E["rows"], "nullable">] extends [never] ? [E["mapped"]] extends [false] ? unknown : RecordRows<"A helper cannot apply map to a query made by get, pluck, an aggregate, or map"> : RecordRows<"A helper cannot apply nullable to a query made by get, pluck, an aggregate, or map"> : RecordRows<"A helper cannot select fields on a query made by get, pluck, an aggregate, or map">;
1922
+ /** Constraint of a query whose rows are records, which a query of values fails with error `Message`. */
1923
+ interface RecordRows<Message extends string> {
1924
+ readonly value: false | HelperError<Message>;
1925
+ }
1926
+ /** Schema context of a query that has the relations of its schema that a helper of effect `E` may read. */
1927
+ type ReadsContext<E extends HelperEffect> = [E["reads"]] extends [never] ? SchemaContext : SchemaContext<{ readonly [K in E["reads"]["key"]]: { readonly [N in Extract<E["reads"], {
1928
+ readonly key: K;
1929
+ }>["name"]]: Extract<E["reads"], {
1930
+ readonly key: K;
1931
+ readonly name: N;
1932
+ }>["relation"]; }; }, E["key"]>;
1933
+ /** State of a query of state `S` after a helper of effect `E`. */
1934
+ type ApplyEffect<S extends SelectQueryState, E extends HelperEffect> = ApplySelectionEffect<E["grouped"] extends true ? GroupedState<S> : S, E>;
1935
+ /** Applies the selected fields and row effects after the grouping guaranteed by the helper. */
1936
+ type ApplySelectionEffect<S extends SelectQueryState, E extends HelperEffect> = ChangeState<S, {
1937
+ result: E["mapped"] extends true ? E["output"] : [keyof E["fields"]] extends [never] ? S["result"] : MergeSelection<S["result"], S["aggregate"] extends Grouped ? GroupedRecord<E["fields"], SelectedFieldTypesOf<E["fieldTypes"]>> : E["fields"]>;
1938
+ fieldTypes: SelectedFieldTypes<S["fieldTypes"], SelectedFieldTypesOf<E["fieldTypes"]>>;
1939
+ value: E["mapped"] extends true ? "mapped" : S["value"];
1940
+ aggregate: E["mapped"] extends true ? true : S["aggregate"];
1941
+ rows: E["rows"] extends "many" ? EffectRows<S, E> : E["rows"] extends "one" ? OneRow<EffectRows<S, E>> : E["rows"];
1942
+ uses: S["uses"] | E["uses"];
1943
+ guaranteed: E["guaranteed"] extends true ? S["guaranteed"] : false;
1944
+ }>;
1945
+ /** Rows mode of a query of state `S` after a helper of effect `E` that keeps the rows, before `take`: relaxed as after a filter when the helper ends the guarantee. */
1946
+ type EffectRows<S extends SelectQueryState, E extends HelperEffect> = E["guaranteed"] extends true ? S["rows"] : FilteredStateRows<S>;
1947
+ /**
1948
+ * Helper of `defineHelper` for queries over table `T`: it applies effect `E` to the query it receives with arguments `A` and returns a query of the same kind.
1949
+ *
1950
+ * Selected fields replace earlier fields under the same keys; a query made by `get`, `pluck`, an aggregate method, or `map` does not accept a helper that selects fields or maps them.
1951
+ * `use` of a mutation also applies a helper that only selects fields and maps them.
1952
+ */
1953
+ type Helper<T extends AnyTable, E extends HelperEffect, A extends unknown[]> = <S extends HelperInput<T, E>, Kind extends SelectQueryKind>(query: SelectQuery<S, Kind>, ...args: A) => E extends HelperEffect ? SelectQuery<ApplyEffect<S, E>, Kind> : never;
1954
+ /**
1955
+ * Defines a reusable helper of a table that filters, selects fields, converts them with `map`, and applies `take`, `optional`, `nullable`, and `required`, used with `use` or called with a query.
1956
+ *
1957
+ * `helper` receives the query it is applied to and any further arguments, and returns the query with its clauses.
1958
+ * Defined with a query of a schema, such as `schema.form`, it can select the relations of the table in that schema, and applies to queries whose schema has them.
1959
+ * The helper returns a query of the same kind as the one it is applied to, bound to the same `Db` if any.
1960
+ * A helper that only selects fields and maps them also applies to an insert, an update, and a delete with their `use`, where it selects what they return; other methods fail there.
1961
+ */
1962
+ declare function defineHelper<T extends AnyTable, R extends SelectQuery<any, SelectQueryKind>, A extends unknown[], C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, helper: (query: SelectQuery<HelperState<T, C>, SelectQueryKind>, ...args: A) => R & CheckResult<R["types"]>): Helper<T, ReadEffect<R["types"]>, A>;
1963
+ /**
1964
+ * 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 or `transform` converts it.
1633
1965
  *
1634
1966
  * Methods change only their own parts of the state.
1635
1967
  */
@@ -1638,7 +1970,7 @@ interface MutationQueryState extends QueryState {
1638
1970
  readonly schema: SchemaContext;
1639
1971
  /** Rows mode of the rows that the query changes, which `select`, `get`, and `pluck` return. */
1640
1972
  readonly changed: ResultRows;
1641
- /** Whether the query returns the fields of the rows it changes rather than their number. */
1973
+ /** Whether the query resolves to something other than the number of the rows it changes: their fields or what `transform` makes of that number. */
1642
1974
  readonly returning: boolean;
1643
1975
  }
1644
1976
  /** 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`. */
@@ -1652,6 +1984,16 @@ interface InitialMutationState<T extends AnyTable, C extends SchemaContext, Rows
1652
1984
  readonly value: true;
1653
1985
  readonly uses: U;
1654
1986
  }
1987
+ /** State of an insert of `insert` or `insertMany` of table `T` with schema context `C` in rows mode `Rows`, before any other method. */
1988
+ interface InitialInsertState<T extends AnyTable, C extends SchemaContext, Rows extends ResultRows> extends InitialMutationState<T, C, Rows> {
1989
+ readonly insert: true;
1990
+ }
1991
+ /** State of an insert that no method has changed since `insert` or `insertMany`, which `onConflict` applies to. */
1992
+ interface InsertMutationState extends MutationQueryState {
1993
+ readonly insert: true;
1994
+ }
1995
+ /** Rows mode of the rows that an insert of rows mode `Rows` changes when it skips the rows that conflict: a missing row of an insert of one record. */
1996
+ type SkippedRows<Rows extends ResultRows> = Rows extends "one" ? "optional" : Rows;
1655
1997
  /** State `S` of a mutation with the parts of `Changes` replaced. */
1656
1998
  type ChangeMutationState<S extends MutationQueryState, Changes extends Partial<MutationQueryState>> = { readonly [K in keyof MutationQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
1657
1999
  /** State of a mutation that returns the number of the rows it changes or their records, which `select` applies to. */
@@ -1660,10 +2002,38 @@ type RecordMutationState = MutationQueryState & ({
1660
2002
  } | {
1661
2003
  readonly value: false;
1662
2004
  });
1663
- /** State of a mutation of one row, which `get` applies to. */
1664
- type OneRowMutationState = MutationQueryState & {
2005
+ /** State of a mutation that `map` and `transform` do not convert, which `pluck` applies to. */
2006
+ type UnconvertedMutationState = MutationQueryState & {
2007
+ readonly value: boolean;
2008
+ };
2009
+ /** State of a mutation of one row that `map` and `transform` do not convert, which `get` applies to. */
2010
+ type OneRowMutationState = UnconvertedMutationState & {
1665
2011
  readonly changed: "one" | "nullable" | "optional";
1666
2012
  };
2013
+ /** State of a mutation that returns the fields of the rows it changes, which `map` applies to unless `transform` converts it; the number of the rows has no rows to convert. */
2014
+ type ReturningMutationState = MutationQueryState & {
2015
+ readonly returning: true;
2016
+ readonly value: boolean | "mapped";
2017
+ };
2018
+ /** Constraint of a mutation that does not accept a helper that filters or takes one row, whose methods it lacks. */
2019
+ interface NotMutationEffect {
2020
+ readonly returning: HelperError<"A helper of a mutation can only select fields and map them">;
2021
+ }
2022
+ /** Constraint of a mutation that accepts a helper of table `T` of effect `E`, whose callback reads the relations of its schema context from the mutation. */
2023
+ type HelperMutationInput<T extends AnyTable, E extends HelperEffect> = MutationQueryState & {
2024
+ readonly table: T;
2025
+ readonly schema: ReadsContext<E>;
2026
+ } & ([E["guaranteed"]] extends [true] ? [E["rows"]] extends ["many"] ? [E extends HelperEffect ? keyof E["fields"] : never, E["mapped"]] extends [never, false] ? unknown : RecordMutationState : NotMutationEffect : NotMutationEffect);
2027
+ /** State of a mutation of state `S` after a helper of effect `E`: the rows that `map` gives, or the records with the fields that it selects. */
2028
+ type HelperMutationState<S extends MutationQueryState, E extends HelperEffect> = E["mapped"] extends true ? ChangeMutationState<S, {
2029
+ result: E["output"];
2030
+ rows: S["changed"];
2031
+ value: "mapped";
2032
+ returning: true;
2033
+ uses: S["uses"] | E["uses"];
2034
+ }> : [keyof E["fields"]] extends [never] ? ChangeMutationState<S, {
2035
+ uses: S["uses"] | E["uses"];
2036
+ }> : RecordsState<S, E["fields"], E["uses"]>;
1667
2037
  /** Record that the returned fields of a mutation of state `S` add to: the fields selected earlier, or none. */
1668
2038
  type ReturnedRecord$1<S extends MutationQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
1669
2039
  /** State of a mutation of state `S` that returns records with `Fields`, which its nested queries select records of relations `U` for. */
@@ -1692,7 +2062,7 @@ type OperandState<S extends MutationQueryState, E extends TypedOperand, Rows ext
1692
2062
  /**
1693
2063
  * Immutable query of state `S` that inserts, updates, or deletes rows, unbound or bound to a `Db`.
1694
2064
  *
1695
- * Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead.
2065
+ * Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead, and `map` and `transform` convert them in code.
1696
2066
  * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
1697
2067
  * A bound query executes on its `Db` when awaited.
1698
2068
  */
@@ -1734,170 +2104,569 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
1734
2104
  */
1735
2105
  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>;
1736
2106
  /** 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. */
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>;
2107
+ pluck<S extends UnconvertedMutationState, 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>;
1738
2108
  /**
1739
2109
  * 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
2110
  *
1741
2111
  * `callback` receives what the callback of `select` receives, and may return a query of one value, which gives `NULL` without its row.
1742
2112
  */
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>;
2113
+ pluck<S extends UnconvertedMutationState, 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>;
1744
2114
  /**
1745
- * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
2115
+ * Converts each record or value that the mutation returns in code, after decoding, such as to add a field that SQL cannot compute; select the fields before it, since the number of the rows has no rows to convert, which `transform` converts instead.
1746
2116
  *
1747
- * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
2117
+ * `callback` receives one record or value, also `null` of a `NULL` value, and is not called for a missing row; it returns its result synchronously.
2118
+ * A failure of `callback` rejects with `ResultDecodeError`, after the mutation has changed its rows.
1748
2119
  */
1749
- toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1750
- /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
1751
- [operandNode](): never;
1752
- /** Creates a mutation of the same kind and `Db` with the node changes applied. */
1753
- private derive;
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. */
1755
- private deriveValue;
2120
+ map<S extends ReturningMutationState, Kind extends SelectQueryKind, R>(this: MutationQuery<S, Kind>, callback: (row: S["result"]) => R & SynchronousResult<R>): MutationQuery<ChangeMutationState<S, {
2121
+ result: R;
2122
+ value: "mapped";
2123
+ }>, Kind>;
2124
+ /**
2125
+ * Converts the whole result of the mutation in code, after decoding, such as the number of the rows it changes into whether it changed any.
2126
+ *
2127
+ * `callback` receives what the mutation resolves to, once, and returns its result synchronously; call `select`, `get`, `pluck`, and `map` before it.
2128
+ * A failure of `callback` rejects with `ResultDecodeError`, after the mutation has changed its rows.
2129
+ */
2130
+ transform<S extends MutationQueryState, Kind extends SelectQueryKind, R>(this: MutationQuery<S, Kind>, callback: (result: QueryResult<S>) => R & SynchronousResult<R>): MutationQuery<ChangeMutationState<S, {
2131
+ result: R;
2132
+ rows: "one";
2133
+ value: "transformed";
2134
+ returning: true;
2135
+ }>, Kind>;
2136
+ /**
2137
+ * Returns the mutation that `callback` builds from this mutation, such as one that selects the fields it returns.
2138
+ *
2139
+ * `callback` receives this mutation and `args` and returns this mutation or a mutation derived from it, which keeps the binding of this mutation.
2140
+ */
2141
+ use<Q, Kind extends SelectQueryKind, R extends MutationQuery<any, Kind>, A extends unknown[] = []>(this: Q & MutationQuery<any, Kind>, callback: (query: Q, ...args: A) => R, ...args: A): R;
2142
+ /**
2143
+ * Applies a helper of `defineHelper` that only selects fields and maps them to what the mutation returns, as `use` of a select query does.
2144
+ *
2145
+ * Another method of a query in the helper fails: types reject those that filter or take one row, but not `groupBy`, `orderBy`, `limit`, `offset`, `distinct`, `distinctOn`, and the row locks, which they do not tell from a selection.
2146
+ * A selection of no fields fails as well on a mutation that returns the number of its rows.
2147
+ */
2148
+ use<S extends HelperMutationInput<T, E>, Kind extends SelectQueryKind, T extends AnyTable, E extends HelperEffect, A extends unknown[]>(this: MutationQuery<S, Kind>, helper: Helper<T, E, A>, ...args: A): E extends HelperEffect ? MutationQuery<HelperMutationState<S, E>, Kind> : never;
2149
+ /**
2150
+ * Chooses the key, primary or unique, of `columns` on which a row of the insert may conflict with an existing record; without columns, `doNothing` skips a row that conflicts on any key, and `merge` and `update` update the row of a singleton table.
2151
+ *
2152
+ * Call it right after `insert` or `insertMany`, choose the action on its result, such as `doNothing()`, and select the fields that the mutation returns after the action.
2153
+ */
2154
+ onConflict<S extends InsertMutationState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string = never>(this: MutationQuery<S, Kind>, ...columns: (K & KeyCheck<S["table"], K>)[]): ConflictTarget<S, Kind, K>;
2155
+ /**
2156
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
2157
+ *
2158
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
2159
+ */
2160
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
2161
+ /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
2162
+ [operandNode](): never;
2163
+ /** Creates a mutation of the same kind and `Db` with the node changes applied. */
2164
+ private derive;
2165
+ /** 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. */
2166
+ private deriveValue;
2167
+ /** Rejects `method`, which changes the fields that the mutation returns, on a mutation that `map` or `transform` converts. */
2168
+ private rejectConverted;
2169
+ }
2170
+ /** Query of any state and kind that inserts, updates, or deletes rows. */
2171
+ type AnyMutationQuery = MutationQuery<any, SelectQueryKind>;
2172
+ /**
2173
+ * Conflict target of an insert of state `S` on the key of columns `K`, or without columns for `never`, with methods that choose the action and return the mutation: without columns, `doNothing` takes any key, and `merge` and `update` the row of a singleton table.
2174
+ *
2175
+ * It is no query: awaiting it is a type error and rejects, so that an insert without an action does not resolve without running.
2176
+ */
2177
+ declare class ConflictTarget<out S extends InsertMutationState, out Kind extends SelectQueryKind = "unbound", out K extends string = string> {
2178
+ /** Insert whose rows conflict. */
2179
+ readonly insert: MutationQuery<S, Kind>;
2180
+ /** Columns of the key that the rows conflict on, in its order, or none, as `onConflict` without columns gives them. */
2181
+ readonly target: readonly K[];
2182
+ constructor(
2183
+ /** Insert whose rows conflict. */
2184
+ insert: MutationQuery<S, Kind>,
2185
+ /** Columns of the key that the rows conflict on, in its order, or none, as `onConflict` without columns gives them. */
2186
+ target: readonly K[]);
2187
+ /**
2188
+ * Skips each row that conflicts, as `ON CONFLICT DO NOTHING`, and returns the mutation.
2189
+ *
2190
+ * After `insert`, the mutation resolves to `0` when the row conflicts, and the fields selected after it to `undefined`.
2191
+ * After `insertMany`, it resolves to the number of the inserted rows, and the fields selected after it are those of the inserted rows.
2192
+ */
2193
+ doNothing<S extends InsertMutationState, Kind extends SelectQueryKind>(this: ConflictTarget<S, Kind>): MutationQuery<ChangeMutationState<S, {
2194
+ changed: SkippedRows<S["changed"]>;
2195
+ }>, Kind>;
2196
+ /**
2197
+ * Updates the existing record of each row that conflicts with the values of `columns` of the row, as `DO UPDATE SET column = EXCLUDED.column`, or with every column that the insert gives, apart from the key, without columns, and returns the mutation of the inserted and the updated rows.
2198
+ *
2199
+ * Every record must give each column that it sets.
2200
+ * After `onConflict()` without columns, it updates the row of a singleton table.
2201
+ */
2202
+ merge<S extends InsertMutationState, Kind extends SelectQueryKind, K extends string, C extends Exclude<keyof S["table"]["columns"] & string, K>>(this: ConflictTarget<S, Kind, K> & ConflictKeyCheck<S, K>, ...columns: C[]): MutationQuery<ChangeMutationState<S, {
2203
+ changed: S["changed"];
2204
+ }>, Kind>;
2205
+ /**
2206
+ * Updates the existing record of each row that conflicts with the values that `callback` returns, as `DO UPDATE SET`, and returns the mutation of the inserted and the updated rows.
2207
+ *
2208
+ * `callback` receives the columns and the queries of the relations of the existing record, and the columns of the row proposed for insertion, `excluded`, such as to add its value to the existing one.
2209
+ * After `onConflict()` without columns, it updates the row of a singleton table.
2210
+ */
2211
+ update<S extends InsertMutationState, Kind extends SelectQueryKind, K extends string, F extends (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>, excluded: ColumnRefs<S["table"]>) => UpdateValues<S["table"]>>(this: ConflictTarget<S, Kind, K> & ConflictKeyCheck<S, K>, callback: F): MutationQuery<ChangeMutationState<S, {
2212
+ uses: S["uses"] | OperandUses<ReturnType<F>[keyof ReturnType<F>]>;
2213
+ }>, Kind>;
2214
+ /**
2215
+ * Updates the existing record of each row that conflicts with the values of `set`, as `DO UPDATE SET`, and returns the mutation of the inserted and the updated rows.
2216
+ *
2217
+ * `set` gives the values of the columns to update, or is a callback that returns them from the existing record and the row proposed for insertion, `excluded`.
2218
+ * After `onConflict()` without columns, it updates the row of a singleton table.
2219
+ */
2220
+ update<S extends InsertMutationState, Kind extends SelectQueryKind, K extends string>(this: ConflictTarget<S, Kind, K> & ConflictKeyCheck<S, K>, set: ConflictUpdateSet<S["table"], S["schema"]>): MutationQuery<ChangeMutationState<S, {
2221
+ changed: S["changed"];
2222
+ }>, Kind>;
2223
+ /** Rejects awaiting the conflict target, which needs an action, such as `doNothing()`. */
2224
+ then(_action: ConflictActionRequired): never;
2225
+ /** Returns the node of the insert, which `onConflict` takes only of an insert. */
2226
+ private insertNode;
2227
+ /** Creates the insert of the same kind and `Db` with `conflict`, changing rows `rows`. */
2228
+ private derive;
2229
+ }
2230
+ /** Type of the parameter of `then` of a conflict target, which makes awaiting the target before an action a type error. */
2231
+ interface ConflictActionRequired {
2232
+ readonly "onConflict needs an action, such as doNothing()": never;
2233
+ }
2234
+ /** Check of the columns `K` of a conflict target of an insert of state `S` that rejects `merge` and `update` of a conflict on any key, which PostgreSQL does not update, unless the table is a singleton table, whose row they update. */
2235
+ type ConflictKeyCheck<S extends InsertMutationState, K extends string> = [K] extends [never] ? S["table"]["singleton"] extends true ? unknown : ConflictKeyRequired : unknown;
2236
+ /** Type that a conflict target on any key is checked against by `merge` and `update`, naming the reason. */
2237
+ interface ConflictKeyRequired {
2238
+ readonly "merge and update need the columns of a key in onConflict": never;
2239
+ }
2240
+ /** Types of the fields of the rows of a query of SQL text by the names of the result columns they decode. */
2241
+ interface FieldTypes {
2242
+ readonly [key: string]: AnyType;
2243
+ readonly [key: symbol]: never;
2244
+ }
2245
+ /** Record of the values that the types of fields `F` decode. */
2246
+ type DecodedFields<F extends FieldTypes> = { -readonly [K in keyof F]: TypeOutput<F[K]>; };
2247
+ /**
2248
+ * State in types of a query of SQL text: the rows mode of the rows that its statement returns, and its result, which is the number of the rows of its command tag until a selection returns their fields.
2249
+ *
2250
+ * Methods change only their own parts of the state.
2251
+ */
2252
+ interface SqlQueryState extends QueryState {
2253
+ /** Rows mode of the rows of the statement, which `select`, `get`, and `pluck` return. */
2254
+ readonly returned: ResultRows;
2255
+ /** Whether the query returns the fields of the rows of the statement rather than their number. */
2256
+ readonly returning: boolean;
2257
+ }
2258
+ /** State of a query of SQL text that returns the number of the rows of its command tag. */
2259
+ interface InitialSqlQueryState extends SqlQueryState {
2260
+ readonly result: number;
2261
+ readonly rows: "one";
2262
+ readonly value: true;
2263
+ readonly uses: never;
2264
+ readonly returned: "many";
2265
+ readonly returning: false;
2266
+ }
2267
+ /** State `S` of a query of SQL text with the parts of `Changes` replaced. */
2268
+ type ChangeSqlQueryState<S extends SqlQueryState, Changes extends Partial<SqlQueryState>> = { readonly [K in keyof SqlQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
2269
+ /** State of a query of SQL text that returns the number of the rows or their records, which `select` applies to. */
2270
+ type RecordSqlQueryState = SqlQueryState & ({
2271
+ readonly returning: false;
2272
+ } | {
2273
+ readonly value: false;
2274
+ });
2275
+ /** State of a query of SQL text of one row, which `optional` applies to. */
2276
+ type OneRowSqlQueryState = SqlQueryState & {
2277
+ readonly returned: "one" | "nullable" | "optional";
2278
+ };
2279
+ /** State of a query of SQL text of one row that returns its number or its record, which `nullable` applies to. */
2280
+ type OneRecordSqlQueryState = OneRowSqlQueryState & RecordSqlQueryState;
2281
+ /** Record that the fields of a query of SQL text of state `S` add to: the fields selected earlier, or none. */
2282
+ type ReturnedRecord<S extends SqlQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
2283
+ /** State of a query of SQL text of state `S` whose rows are in rows mode `Rows`. */
2284
+ type RowsState<S extends SqlQueryState, Rows extends ResultRows> = ChangeSqlQueryState<S, {
2285
+ returned: Rows;
2286
+ rows: S["returning"] extends true ? Rows : "one";
2287
+ }>;
2288
+ /** State of a query of SQL text of state `S` that returns value `V` of each row in rows mode `Rows`. */
2289
+ type ValueState<S extends SqlQueryState, V, Rows extends ResultRows> = ChangeSqlQueryState<S, {
2290
+ result: V;
2291
+ rows: Rows;
2292
+ returned: Rows;
2293
+ value: true;
2294
+ returning: true;
2295
+ }>;
2296
+ /**
2297
+ * Immutable query of a statement of SQL text, bound to the `Db` that executes it when awaited.
2298
+ *
2299
+ * Without a selection, it resolves to the number of the rows of the command tag of its statement, such as the rows that an `UPDATE` changes; `select`, `get`, and `pluck` return the fields of the rows of the statement instead, decoded by types.
2300
+ */
2301
+ declare class SqlQuery<out S extends SqlQueryState> {
2302
+ readonly node: TextStatementNode;
2303
+ /** `Db` that executes the query when it is awaited. */
2304
+ readonly db: AnyDb;
2305
+ readonly types: S;
2306
+ /** Executes the query on its `Db`. */
2307
+ readonly then: QueryThen<S, "bound">;
2308
+ constructor(node: TextStatementNode,
2309
+ /** `Db` that executes the query when it is awaited. */
2310
+ db: AnyDb);
2311
+ /**
2312
+ * Returns the records of the rows of the statement instead of their number, with the values of the result columns named by the keys of `fields`, decoded by their types; it adds the fields to those selected earlier, replacing fields under their keys.
2313
+ *
2314
+ * A type of a column that can be `NULL` must be nullable.
2315
+ * The statement rejects without a column of a field, or with the column twice; other columns are ignored.
2316
+ */
2317
+ select<S extends RecordSqlQueryState, F extends FieldTypes>(this: SqlQuery<S>, fields: F): SqlQuery<ChangeSqlQueryState<S, {
2318
+ result: MergeSelection<ReturnedRecord<S>, DecodedFields<F>>;
2319
+ rows: S["returned"];
2320
+ value: false;
2321
+ returning: true;
2322
+ }>>;
2323
+ /**
2324
+ * Returns the value of the only column of the row of the statement instead of the number of the rows, decoded by `type`.
2325
+ *
2326
+ * Without a row, it rejects with `NotFoundError` unless `optional` makes the query resolve to `undefined`; it rejects several rows.
2327
+ * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
2328
+ */
2329
+ get<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, OneValueRows<S["returned"]>>>;
2330
+ /**
2331
+ * Returns the values of the only column of the rows of the statement instead of their number, decoded by `type`, keeping whether the query returns an array or one value.
2332
+ *
2333
+ * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
2334
+ */
2335
+ pluck<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, ValueRows<S["returned"]>>>;
2336
+ /**
2337
+ * Returns the row of the statement instead of an array, and rejects with `NotFoundError` without it and with several rows; it adds no limit to the statement.
2338
+ *
2339
+ * Before a selection, the query resolves to the number of the rows, `1`, and rejects as well.
2340
+ */
2341
+ take<S extends SqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, OneRow<S["returned"]>>>;
2342
+ /**
2343
+ * Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without the row.
2344
+ *
2345
+ * Before a selection, the query resolves to `0` without the row.
2346
+ */
2347
+ optional<S extends OneRowSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "optional">>;
2348
+ /**
2349
+ * Makes a query of one record, such as one of `take`, resolve to `null` without the row.
2350
+ *
2351
+ * A value of `get` or `pluck` is never `null` for a missing row, which would read as a `NULL` value, so a query of values does not accept it.
2352
+ * Before a selection, the query resolves to `0` without the row.
2353
+ */
2354
+ nullable<S extends OneRecordSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "nullable">>;
2355
+ /** Compiles the query into SQL text and parameters, as its `Db` executes it. */
2356
+ toSQL(): SqlStatement;
2357
+ /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
2358
+ [operandNode](): never;
2359
+ /** Creates a query of the same `Db` with the node changes applied. */
2360
+ private derive;
2361
+ /** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
2362
+ private deriveValue;
2363
+ /** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
2364
+ private changeOneRow;
2365
+ }
2366
+ /** Query of SQL text of any state. */
2367
+ type AnySqlQuery = SqlQuery<any>;
2368
+ /** Kind of a select query: `unbound`, or `bound` to a `Db`. */
2369
+ type SelectQueryKind = "unbound" | "bound";
2370
+ /**
2371
+ * `then` of a query of kind `Kind`: a bound query executes when awaited, and an unbound query is not thenable.
2372
+ *
2373
+ * Awaiting a query of either kind or returning it from an async function is a type error, since it may execute.
2374
+ */
2375
+ type QueryThen<S extends QueryState, Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? <R1 = QueryResult<S>, R2 = never>(onFulfilled?: ((result: QueryResult<S>) => R1 | PromiseLike<R1>) | null, onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null) => Promise<R1 | R2> : [Kind] extends ["unbound"] ? undefined : ((onFulfilled: never) => unknown) | undefined;
2376
+ /** `Db` of a query of kind `Kind`, which only a bound query has. */
2377
+ type QueryDb<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? AnyDb : [Kind] extends ["unbound"] ? undefined : AnyDb | undefined;
2378
+ /** Arguments of `toSQL` of a query of kind `Kind`: a bound query compiles with the options of its `Db`. */
2379
+ type ToSQLArgs<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? [] : [options?: CompileOptions];
2380
+ /** Query of any class, state, and kind: a select query of a table, one converted by `transform`, a query of `$select`, one that inserts, updates, or deletes rows, or a query of SQL text. */
2381
+ type AnyQuery = AnySelectQuery | AnyTransformedQuery | AnyRecordQuery | AnyMutationQuery | AnySqlQuery;
2382
+ /** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
2383
+ interface RecordQueryState<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
2384
+ readonly result: R;
2385
+ readonly rows: "one";
2386
+ readonly value: false;
2387
+ readonly uses: U;
2388
+ }
2389
+ /** 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. */
2390
+ type SelectionState<Sel extends Selection> = RecordQueryState<MergeSelection<EmptyRecord, SelectionResult<Sel>>, SelectionUses<Sel>>;
2391
+ /**
2392
+ * 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.
2393
+ *
2394
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
2395
+ * A bound query executes on its `Db` when awaited.
2396
+ */
2397
+ declare class RecordQuery<out S extends RecordQueryState, out Kind extends SelectQueryKind = "unbound"> {
2398
+ readonly node: RecordQueryNode;
2399
+ readonly types: S;
2400
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
2401
+ readonly db: QueryDb<Kind>;
2402
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
2403
+ readonly then: QueryThen<S, Kind>;
2404
+ constructor(node: RecordQueryNode, db?: AnyDb);
2405
+ /**
2406
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
2407
+ *
2408
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
2409
+ */
2410
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
2411
+ /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
2412
+ [operandNode](): never;
2413
+ }
2414
+ /** Query of `$select` of any state and kind. */
2415
+ type AnyRecordQuery = RecordQuery<any, SelectQueryKind>;
2416
+ declare const schemaBrand: unique symbol;
2417
+ /** Key of the relation definitions of a schema, which composition reads. */
2418
+ declare const schemaRelations: unique symbol;
2419
+ /** Tables by their keys; a key must not start with `$`, which is reserved for schema and `Db` members. */
2420
+ type Tables = Record<string, AnyTable>;
2421
+ /**
2422
+ * Immutable collection of tables and their relations with query entry points.
2423
+ *
2424
+ * A schema is not bound to a database, so queries built from it can be defined at module level.
2425
+ * 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`.
2426
+ */
2427
+ type Schema<T extends Tables, R extends SchemaRelations = EmptyRecord> = SchemaEntries<T, R> & SchemaMembers<T, R>;
2428
+ /** Query entry points; each access starts a query over a new table occurrence, of the one row of a singleton table. */
2429
+ type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<TableQueryState<T[K], TableContext<R, K>>>; };
2430
+ /** Members of a schema that composition reads: its tables and the relations of its tables. */
2431
+ interface SchemaContents<T extends Tables, R extends SchemaRelations> {
2432
+ readonly [schemaBrand]: true;
2433
+ /** Tables of the schema by their keys. */
2434
+ readonly $tables: T;
2435
+ /** Relation definitions by table key and relation name. */
2436
+ readonly [schemaRelations]: R;
2437
+ }
2438
+ interface SchemaMembers<T extends Tables, R extends SchemaRelations> extends SchemaContents<T, R> {
2439
+ /**
2440
+ * 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.
2441
+ *
2442
+ * 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.
2443
+ */
2444
+ $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>>>;
2445
+ /**
2446
+ * 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.
2447
+ *
2448
+ * The value of the field of a query is the result it gives when executed, such as an array of records or one value.
2449
+ */
2450
+ $select<Sel extends Selection>(selection: Sel): RecordQuery<SelectionState<Sel>>;
2451
+ }
2452
+ /** Schema of any tables and relations. */
2453
+ type AnySchema = SchemaContents<Tables, SchemaRelations>;
2454
+ /** Part of a schema definition: an object of tables by their keys, or a schema whose tables and relations it includes. */
2455
+ type SchemaPart = Tables | AnySchema;
2456
+ /**
2457
+ * Tables of the parts of a schema definition by their keys.
2458
+ *
2459
+ * 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.
2460
+ */
2461
+ type SchemaTables<P extends readonly SchemaPart[]> = ComposeParts<P>["tables"] extends (infer T extends Tables) ? { [K in keyof T]: T[K]; } : never;
2462
+ /** Relations of the parts of a schema definition by table key and relation name, read as `SchemaTables` reads the tables. */
2463
+ type SchemaPartRelations<P extends readonly SchemaPart[]> = ComposeParts<P>["relations"] extends (infer R extends SchemaRelations) ? MergeRelations<R> : never;
2464
+ /** Tables and relations of the parts of a schema definition, intersected. */
2465
+ interface PartContents {
2466
+ readonly tables: Tables;
2467
+ readonly relations: SchemaRelations;
2468
+ }
2469
+ type ComposeParts<P extends readonly SchemaPart[], Composed extends PartContents = {
2470
+ tables: EmptyRecord;
2471
+ relations: EmptyRecord;
2472
+ }> = 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;
2473
+ type ReadPart<P extends SchemaPart> = P extends SchemaContents<infer T, any> ? {
2474
+ tables: T;
2475
+ relations: P[typeof schemaRelations];
2476
+ } : {
2477
+ tables: P;
2478
+ relations: EmptyRecord;
2479
+ };
2480
+ /**
2481
+ * Defines a schema of the tables of `parts`, keyed by their names in queries.
2482
+ *
2483
+ * 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.
2484
+ * 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.
2485
+ */
2486
+ declare function defineSchema<P extends SchemaPart[]>(...parts: P): Schema<SchemaTables<P>, SchemaPartRelations<P>>;
2487
+ declare const sourceTable: unique symbol;
2488
+ declare const sourceKey: unique symbol;
2489
+ /** Runtime mark of the declarations of `many` and `one`. */
2490
+ declare const declarationBrand: unique symbol;
2491
+ /** Kind of a relation: `many` related records, or `one` related record at most. */
2492
+ type RelationKind = "many" | "one";
2493
+ /** Relation of a table of a schema to the records of table `Target`, which has key `TargetKey` in the schema. */
2494
+ interface Relation<Kind extends RelationKind = RelationKind, Target extends AnyTable = AnyTable, TargetKey extends string = string, Required extends boolean = boolean> {
2495
+ readonly kind: Kind;
2496
+ readonly target: Target;
2497
+ readonly targetKey: TargetKey;
2498
+ /** 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`. */
2499
+ readonly required: Required;
2500
+ }
2501
+ /**
2502
+ * Relation of a table of a schema as `$relations` defines it: the columns of its keys, compared by SQL `=` in order.
2503
+ *
2504
+ * Composition includes a definition as it is, so a relation that several parts include is one definition.
2505
+ */
2506
+ interface RelationDefinition extends Relation {
2507
+ readonly name: string;
2508
+ /** Key of the source table. */
2509
+ readonly key: string;
2510
+ readonly source: AnyTable;
2511
+ readonly from: readonly string[];
2512
+ readonly to: readonly string[];
2513
+ }
2514
+ /** Relation `N` of the table under key `K` of a schema, of type `R`, whose records a query selects. */
2515
+ interface UsedRelation<K extends string = string, N extends string = string, R extends Relation = Relation> {
2516
+ readonly key: K;
2517
+ readonly name: N;
2518
+ readonly relation: R;
2519
+ }
2520
+ /** Relations of schema relations `R` that the queries of a `Db` of the schema may select. */
2521
+ 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];
2522
+ /** Relations of the tables of a schema by table key and relation name. */
2523
+ type SchemaRelations = {
2524
+ readonly [key: string]: TableRelations;
2525
+ };
2526
+ /** Relations of a table of a schema by relation name. */
2527
+ type TableRelations = {
2528
+ readonly [name: string]: Relation;
2529
+ };
2530
+ /**
2531
+ * 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.
2532
+ *
2533
+ * `Source` and `From` only type the keys of the source table.
2534
+ */
2535
+ interface RelationDeclaration<Kind extends RelationKind, Source extends AnyTable, Target extends AnyTable, From = unknown, Required extends boolean = boolean> {
2536
+ readonly [declarationBrand]: true;
2537
+ readonly kind: Kind;
2538
+ readonly target: Target;
2539
+ readonly from: readonly string[];
2540
+ readonly to: readonly string[];
2541
+ readonly required: Required;
2542
+ readonly [sourceTable]?: (source: Source) => void;
2543
+ readonly [sourceKey]?: From;
2544
+ }
2545
+ /** Column key of table `T` whose type has SQL `=`, which a relation can compare. */
2546
+ type EqualityKey<T extends AnyTable> = { [K in keyof T["columns"]]: HasEquality<ColumnOperators<T, K>> extends true ? K : never; }[keyof T["columns"]] & string;
2547
+ /** Key of a relation in table `T`: a column key, or a non-empty list of them for a composite key. */
2548
+ type RelationKey<T extends AnyTable> = EqualityKey<T> | readonly [EqualityKey<T>, ...EqualityKey<T>[]];
2549
+ /** Key of table `T` with as many columns as key `From`. */
2550
+ type MatchingKey<T extends AnyTable, From> = From extends string ? EqualityKey<T> : { readonly [I in keyof From]: EqualityKey<T>; };
2551
+ /** Keys of a relation: the columns `from` of the source table equal the columns `to` of the target table, in order. */
2552
+ interface RelationKeys<Target extends AnyTable, From> {
2553
+ readonly from: From;
2554
+ readonly to: MatchingKey<Target, From>;
2555
+ }
2556
+ /** Keys of a relation `one`, as in `RelationKeys`, and whether the relation is required. */
2557
+ interface OneRelationKeys<From, To> {
2558
+ readonly from: From;
2559
+ readonly to: To;
2560
+ /** 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`. */
2561
+ readonly required?: boolean;
2562
+ }
2563
+ /** 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. */
2564
+ type RequiredMember<K> = { readonly [P in keyof K]: P extends "required" ? K[P] : unknown; };
2565
+ /** 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`. */
2566
+ type DeclaredRequiredOf<K> = K extends unknown ? "required" extends keyof K ? K extends {
2567
+ readonly required: infer Required;
2568
+ } ? IsTrue<Required> : IsTrue<K["required" & keyof K] | undefined> : false : never;
2569
+ /** `true` for `true`, and `false` for other values, such as `false` and `undefined`; a union gives the union of their results. */
2570
+ type IsTrue<T> = T extends true ? true : false;
2571
+ /** Declarations of `$relations` of a schema of tables `T`: relations by name, for tables by their keys. */
2572
+ type RelationDeclarations<T extends Tables> = { readonly [K in keyof T]?: {
2573
+ readonly [name: string]: RelationDeclaration<RelationKind, T[K], T[keyof T]>;
2574
+ }; };
2575
+ /**
2576
+ * Declarations `D` of `$relations` checked by the names they use: relations of the tables of `T` under their keys, and no other keys.
2577
+ *
2578
+ * 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`.
2579
+ * 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.
2580
+ */
2581
+ 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>]>>; }; };
2582
+ /** Names that a relation of table `T` cannot have: the keys of its columns, and names starting with `$`. */
2583
+ type ReservedName<T extends AnyTable> = `${keyof T["columns"] & (string | number)}` | `$${string}`;
2584
+ /** Key of tables `T` written as key `K`, such as `1` for `"1"`, as object keys are strings at runtime. */
2585
+ type TableKey<T extends Tables, K> = { [P in keyof T]: `${P & (string | number)}` extends `${K & (string | number)}` ? P : never; }[keyof T];
2586
+ /** Relations that declarations `D` of a schema of tables `T` define, by table key and relation name, as strings like the keys of objects. */
2587
+ 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; }; };
2588
+ /** Column key of relation key `K`: the key itself, or a column of a composite key. */
2589
+ type RelationColumn<K> = K extends readonly unknown[] ? K[number] : K;
2590
+ /** 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. */
2591
+ type TargetKeyCheck<Target extends AnyTable, To> = [ContainsKey<Target, RelationColumn<To>>] extends [false] ? {
2592
+ readonly to: MissingKey<KeyOf<Target["keys"]>>;
2593
+ } : unknown;
2594
+ /** Type that a key `to` of a relation `one` without a key of its target is checked against, naming the keys of the target. */
2595
+ interface MissingKey<Keys> {
2596
+ readonly "columns to must include a key of the target": Keys;
1756
2597
  }
1757
- /** Query of any state and kind that inserts, updates, or deletes rows. */
1758
- type AnyMutationQuery = MutationQuery<any, SelectQueryKind>;
1759
- /** Types of the fields of the rows of a query of SQL text by the names of the result columns they decode. */
1760
- interface FieldTypes {
1761
- readonly [key: string]: AnyType;
1762
- readonly [key: symbol]: never;
2598
+ /** Key of table `Target` among tables `T`, as a string like the keys of objects. */
2599
+ 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];
2600
+ /** Relations of `R` by table key, with the relations under the same key merged. */
2601
+ type MergeRelations<R> = { [K in keyof R]: { [N in keyof R[K]]: R[K][N]; }; };
2602
+ /** Relations of the schema that a query starts from, by table key, and the key of the table of the query there. */
2603
+ interface SchemaContext<R extends SchemaRelations = SchemaRelations, K extends string = string> {
2604
+ readonly relations: R;
2605
+ readonly key: K;
1763
2606
  }
1764
- /** Record of the values that the types of fields `F` decode. */
1765
- type DecodedFields<F extends FieldTypes> = { -readonly [K in keyof F]: TypeOutput<F[K]>; };
2607
+ /** Schema context of a query whose table has no relations, such as one of `from(table)`. */
2608
+ type NoRelations = SchemaContext<EmptyRecord, string>;
2609
+ /** 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. */
2610
+ 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;
1766
2611
  /**
1767
- * State in types of a query of SQL text: the rows mode of the rows that its statement returns, and its result, which is the number of the rows of its command tag until a selection returns their fields.
2612
+ * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1768
2613
  *
1769
- * Methods change only their own parts of the state.
2614
+ * A composite key lists its columns in arrays of the same length.
1770
2615
  */
1771
- interface SqlQueryState extends QueryState {
1772
- /** Rows mode of the rows of the statement, which `select`, `get`, and `pluck` return. */
1773
- readonly returned: ResultRows;
1774
- /** Whether the query returns the fields of the rows of the statement rather than their number. */
1775
- readonly returning: boolean;
1776
- }
1777
- /** State of a query of SQL text that returns the number of the rows of its command tag. */
1778
- interface InitialSqlQueryState extends SqlQueryState {
1779
- readonly result: number;
2616
+ 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>;
2617
+ /**
2618
+ * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
2619
+ *
2620
+ * A composite key lists its columns in arrays of the same length.
2621
+ * The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
2622
+ * 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.
2623
+ * Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
2624
+ */
2625
+ 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>>>;
2626
+ /** Type that the result of a callback of `transform` and `map` is checked against when it may be a Promise. */
2627
+ interface NotSynchronous {
2628
+ readonly "the callback must return its result synchronously": never;
2629
+ }
2630
+ /** Check of `R`, the result of a callback of `transform` and `map`: it fails against `NotSynchronous` when `R` may be a Promise, such as a union with one, but not for `any` and `unknown`. */
2631
+ type SynchronousResult<R> = [Extract<R, PromiseLike<unknown>>] extends [never] ? unknown : IsAny<R> extends true ? unknown : NotSynchronous;
2632
+ /** State of a query of `transform` of a table in types: over table `T`, whose whole result is `R`, selecting records of relations `U`. */
2633
+ interface TransformedQueryState<T extends AnyTable = AnyTable, R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
2634
+ readonly table: T;
2635
+ readonly result: R;
1780
2636
  readonly rows: "one";
1781
- readonly value: true;
1782
- readonly uses: never;
1783
- readonly returned: "many";
1784
- readonly returning: false;
2637
+ readonly value: "transformed";
2638
+ readonly uses: U;
1785
2639
  }
1786
- /** State `S` of a query of SQL text with the parts of `Changes` replaced. */
1787
- type ChangeSqlQueryState<S extends SqlQueryState, Changes extends Partial<SqlQueryState>> = { readonly [K in keyof SqlQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
1788
- /** State of a query of SQL text that returns the number of the rows or their records, which `select` applies to. */
1789
- type RecordSqlQueryState = SqlQueryState & ({
1790
- readonly returning: false;
1791
- } | {
1792
- readonly value: false;
1793
- });
1794
- /** State of a query of SQL text of one row, which `optional` applies to. */
1795
- type OneRowSqlQueryState = SqlQueryState & {
1796
- readonly returned: "one" | "nullable" | "optional";
1797
- };
1798
- /** State of a query of SQL text of one row that returns its number or its record, which `nullable` applies to. */
1799
- type OneRecordSqlQueryState = OneRowSqlQueryState & RecordSqlQueryState;
1800
- /** Record that the fields of a query of SQL text of state `S` add to: the fields selected earlier, or none. */
1801
- type ReturnedRecord<S extends SqlQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
1802
- /** State of a query of SQL text of state `S` whose rows are in rows mode `Rows`. */
1803
- type RowsState<S extends SqlQueryState, Rows extends ResultRows> = ChangeSqlQueryState<S, {
1804
- returned: Rows;
1805
- rows: S["returning"] extends true ? Rows : "one";
1806
- }>;
1807
- /** State of a query of SQL text of state `S` that returns value `V` of each row in rows mode `Rows`. */
1808
- type ValueState<S extends SqlQueryState, V, Rows extends ResultRows> = ChangeSqlQueryState<S, {
1809
- result: V;
1810
- rows: Rows;
1811
- returned: Rows;
1812
- value: true;
1813
- returning: true;
1814
- }>;
1815
2640
  /**
1816
- * Immutable query of a statement of SQL text, bound to the `Db` that executes it when awaited.
2641
+ * Immutable query of a table of state `S` whose whole result `transform` converts after decoding, unbound or bound to a `Db`.
1817
2642
  *
1818
- * Without a selection, it resolves to the number of the rows of the command tag of its statement, such as the rows that an `UPDATE` changes; `select`, `get`, and `pluck` return the fields of the rows of the statement instead, decoded by types.
2643
+ * It executes and nests in a selection as the query it comes from, with the same SQL, so it has only `transform`, which converts the result further: another method would change what the callback receives, and an expression does not take it, since SQL does not see the conversion.
2644
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
2645
+ * A bound query executes on its `Db` when awaited.
1819
2646
  */
1820
- declare class SqlQuery<out S extends SqlQueryState> {
1821
- readonly node: TextStatementNode;
1822
- /** `Db` that executes the query when it is awaited. */
1823
- readonly db: AnyDb;
2647
+ declare class TransformedQuery<out S extends TransformedQueryState, out Kind extends SelectQueryKind = "unbound"> {
2648
+ readonly node: QueryNode;
1824
2649
  readonly types: S;
1825
- /** Executes the query on its `Db`. */
1826
- readonly then: QueryThen<S, "bound">;
1827
- constructor(node: TextStatementNode,
1828
- /** `Db` that executes the query when it is awaited. */
1829
- db: AnyDb);
1830
- /**
1831
- * Returns the records of the rows of the statement instead of their number, with the values of the result columns named by the keys of `fields`, decoded by their types; it adds the fields to those selected earlier, replacing fields under their keys.
1832
- *
1833
- * A type of a column that can be `NULL` must be nullable.
1834
- * The statement rejects without a column of a field, or with the column twice; other columns are ignored.
1835
- */
1836
- select<S extends RecordSqlQueryState, F extends FieldTypes>(this: SqlQuery<S>, fields: F): SqlQuery<ChangeSqlQueryState<S, {
1837
- result: MergeSelection<ReturnedRecord<S>, DecodedFields<F>>;
1838
- rows: S["returned"];
1839
- value: false;
1840
- returning: true;
1841
- }>>;
1842
- /**
1843
- * Returns the value of the only column of the row of the statement instead of the number of the rows, decoded by `type`.
1844
- *
1845
- * Without a row, it rejects with `NotFoundError` unless `optional` makes the query resolve to `undefined`; it rejects several rows.
1846
- * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
1847
- */
1848
- get<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, OneValueRows<S["returned"]>>>;
1849
- /**
1850
- * Returns the values of the only column of the rows of the statement instead of their number, decoded by `type`, keeping whether the query returns an array or one value.
1851
- *
1852
- * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
1853
- */
1854
- pluck<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, ValueRows<S["returned"]>>>;
1855
- /**
1856
- * Returns the row of the statement instead of an array, and rejects with `NotFoundError` without it and with several rows; it adds no limit to the statement.
1857
- *
1858
- * Before a selection, the query resolves to the number of the rows, `1`, and rejects as well.
1859
- */
1860
- take<S extends SqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, OneRow<S["returned"]>>>;
1861
- /**
1862
- * Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without the row.
1863
- *
1864
- * Before a selection, the query resolves to `0` without the row.
1865
- */
1866
- optional<S extends OneRowSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "optional">>;
2650
+ /** Marks a query of `transform`, for types only, so that TypeScript rejects a query of a table as one by this member, without comparing their states. */
2651
+ readonly transformed: true;
2652
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
2653
+ readonly db: QueryDb<Kind>;
2654
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
2655
+ readonly then: QueryThen<S, Kind>;
2656
+ constructor(node: QueryNode, db?: AnyDb);
2657
+ /** Converts the whole result further, after the earlier conversions; see `transform` of a query of a table. */
2658
+ transform<S extends TransformedQueryState, Kind extends SelectQueryKind, R>(this: TransformedQuery<S, Kind>, callback: (result: QueryResult<S>) => R & SynchronousResult<R>): TransformedQuery<TransformedQueryState<S["table"], R, S["uses"]>, Kind>;
1867
2659
  /**
1868
- * Makes a query of one record, such as one of `take`, resolve to `null` without the row.
2660
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1869
2661
  *
1870
- * A value of `get` or `pluck` is never `null` for a missing row, which would read as a `NULL` value, so a query of values does not accept it.
1871
- * Before a selection, the query resolves to `0` without the row.
2662
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1872
2663
  */
1873
- nullable<S extends OneRecordSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "nullable">>;
1874
- /** Compiles the query into SQL text and parameters, as its `Db` executes it. */
1875
- toSQL(): SqlStatement;
1876
- /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
2664
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
2665
+ /** Rejects the query as an operand of an expression, whose value SQL reads without its conversion. */
1877
2666
  [operandNode](): never;
1878
- /** Creates a query of the same `Db` with the node changes applied. */
1879
- private derive;
1880
- /** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
1881
- private deriveValue;
1882
- /** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
1883
- private changeOneRow;
1884
2667
  }
1885
- /** Query of SQL text of any state. */
1886
- type AnySqlQuery = SqlQuery<any>;
1887
- /** Kind of a select query: `unbound`, or `bound` to a `Db`. */
1888
- type SelectQueryKind = "unbound" | "bound";
1889
- /**
1890
- * `then` of a query of kind `Kind`: a bound query executes when awaited, and an unbound query is not thenable.
1891
- *
1892
- * Awaiting a query of either kind or returning it from an async function is a type error, since it may execute.
1893
- */
1894
- type QueryThen<S extends QueryState, Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? <R1 = QueryResult<S>, R2 = never>(onFulfilled?: ((result: QueryResult<S>) => R1 | PromiseLike<R1>) | null, onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null) => Promise<R1 | R2> : [Kind] extends ["unbound"] ? undefined : ((onFulfilled: never) => unknown) | undefined;
1895
- /** `Db` of a query of kind `Kind`, which only a bound query has. */
1896
- type QueryDb<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? AnyDb : [Kind] extends ["unbound"] ? undefined : AnyDb | undefined;
1897
- /** Arguments of `toSQL` of a query of kind `Kind`: a bound query compiles with the options of its `Db`. */
1898
- type ToSQLArgs<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? [] : [options?: CompileOptions];
1899
- /** Query of any class, state, and kind: a select query of a table, a query of `$select`, one that inserts, updates, or deletes rows, or a query of SQL text. */
1900
- type AnyQuery = AnySelectQuery | AnyRecordQuery | AnyMutationQuery | AnySqlQuery;
2668
+ /** Query of `transform` of a table of any state and kind. */
2669
+ type AnyTransformedQuery = TransformedQuery<any, SelectQueryKind>;
1901
2670
  /** Test fixture of `useTestFixture`, open while the tests of its `describe` block or test file run. */
1902
2671
  interface TestFixture<T = unknown> {
1903
2672
  /** Result of the seed of the fixture; reading it while the fixture is not open throws. */
@@ -2110,10 +2879,10 @@ interface BindOptions {
2110
2879
  * Its table entries start queries bound to it, which execute when awaited.
2111
2880
  */
2112
2881
  type Db<T extends Tables, R extends SchemaRelations = EmptyRecord> = DbEntries<T, R> & DbMethods<T, R>;
2113
- /** Bound query entry points; each access starts a query over a new table occurrence. */
2114
- type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
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. */
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>;
2882
+ /** Bound query entry points; each access starts a query over a new table occurrence, of the one row of a singleton table. */
2883
+ type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<TableQueryState<T[K], TableContext<R, K>>>; };
2884
+ /** Bound or unbound query over a table of `T`, also converted by `transform`, 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. */
2885
+ type DbQuery<T extends Tables, R extends SchemaRelations> = QueryOf<DbQueryState<T[keyof T], UsableRelation<R>>> | TransformedQuery<TransformedQueryState<T[keyof T], unknown, UsableRelation<R>>, SelectQueryKind> | RecordQuery<RecordQueryState<unknown, UsableRelation<R>>, SelectQueryKind> | MutationQuery<DbMutationState<T[keyof T], UsableRelation<R>>, SelectQueryKind> | SqlQuery<SqlQueryState>;
2117
2886
  /** State of a query that a `Db` can execute: over table `T`, selecting records only of relations `U`. */
2118
2887
  interface DbQueryState<T extends AnyTable, U extends UsedRelation> extends QueryStateOf<T> {
2119
2888
  readonly uses: U;
@@ -2340,6 +3109,8 @@ interface AggregateNode {
2340
3109
  readonly distinct: boolean;
2341
3110
  readonly arguments: readonly ExpressionNode[];
2342
3111
  readonly orderBy: readonly OrderNode[];
3112
+ /** Condition of the rows that the function takes, as `FILTER (WHERE ...)`, or `undefined` for every row. */
3113
+ readonly filter: ExpressionNode | undefined;
2343
3114
  }
2344
3115
  type ExpressionNode = ColumnRefNode | ParamNode | CastNode | BooleanNode | AndNode | OrNode | NotNode | ValuesNode | NestedQueryNode | ComparisonNode | InNode | InQueryNode | IsNullNode | RawSqlNode | TableNameNode | SubqueryNode | ExistsNode | TextSubqueryNode | AggregateNode;
2345
3116
  /**
@@ -2376,6 +3147,13 @@ interface OrderNode {
2376
3147
  readonly direction: "asc" | "desc";
2377
3148
  readonly nulls: "first" | "last" | undefined;
2378
3149
  }
3150
+ /** Lock of the rows that a select statement reads, in the words of PostgreSQL. */
3151
+ interface RowLockNode {
3152
+ /** Strength of the lock, which follows `FOR`. */
3153
+ readonly strength: "UPDATE" | "NO KEY UPDATE" | "SHARE" | "KEY SHARE";
3154
+ /** What the statement does with a row that another transaction has locked, instead of waiting for it. */
3155
+ readonly onLocked: "NOWAIT" | "SKIP LOCKED" | undefined;
3156
+ }
2379
3157
  /** Select query; its result mode applies only when it is executed or its rows are packed. */
2380
3158
  interface SelectNode<From extends SourceNode | undefined = SourceNode | undefined> extends ResultMode {
2381
3159
  readonly kind: "select";
@@ -2385,13 +3163,25 @@ interface SelectNode<From extends SourceNode | undefined = SourceNode | undefine
2385
3163
  /** Projections in the order of the result fields, with unique keys; a query without them returns records without fields. */
2386
3164
  readonly projections: readonly ProjectionNode[];
2387
3165
  readonly filters: QueryFilters;
3166
+ /** Keys of `GROUP BY`, at least one; a key that a projection has is compiled as the position of the projection, whichever part of lowering adds it. */
3167
+ readonly groupBy?: readonly ExpressionNode[] | undefined;
3168
+ /** Condition of `HAVING`; it requires `groupBy`, which the semantic query checks. */
3169
+ readonly having?: ExpressionNode | undefined;
2388
3170
  readonly orderBy: readonly OrderNode[];
2389
3171
  readonly limit: ExpressionNode | undefined;
2390
3172
  readonly offset: ExpressionNode | undefined;
3173
+ /** Whether the query removes the duplicates of its rows, as `SELECT DISTINCT`; it requires a projection, as PostgreSQL does. */
3174
+ readonly distinct?: boolean | undefined;
3175
+ /** Keys of `DISTINCT ON`, at least one, whose equal values give one row, the first in the order; a key that a projection has is compiled as the position of the projection, as a key of `groupBy` is. */
3176
+ readonly distinctOn?: readonly ExpressionNode[] | undefined;
3177
+ /** Lock of the rows of the source of the statement, which does not reach the subqueries of its other clauses; it requires a source of rows, as PostgreSQL does. */
3178
+ readonly lock?: RowLockNode | undefined;
2391
3179
  /** Required relation that guarantees the row of the query, such as `field.form`; see `ResultPlan`. */
2392
3180
  readonly guaranteedBy: string | undefined;
2393
3181
  /** Template of the records of a query with literals; see `ResultPlan`. */
2394
3182
  readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
3183
+ /** How code converts the decoded result of the query; see `ResultPlan`. */
3184
+ readonly conversion?: ResultConversion | undefined;
2395
3185
  }
2396
3186
  /** Assignment of `SET` of an update: the value of the column under `key`. */
2397
3187
  interface AssignmentNode {
@@ -2408,6 +3198,8 @@ interface MutationParts<Field> extends ResultMode {
2408
3198
  readonly returning: readonly Field[] | undefined;
2409
3199
  /** Template of the records of a mutation with literals; see `ResultPlan`. */
2410
3200
  readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
3201
+ /** How code converts the decoded result of the mutation; see `ResultPlan`. */
3202
+ readonly conversion?: ResultConversion | undefined;
2411
3203
  }
2412
3204
  /** Insert statement of rows of `VALUES`. */
2413
3205
  interface InsertNode<Field = ProjectionNode> extends MutationParts<Field> {
@@ -2416,6 +3208,23 @@ interface InsertNode<Field = ProjectionNode> extends MutationParts<Field> {
2416
3208
  readonly columns: readonly string[];
2417
3209
  /** Rows of `VALUES`, at least one, each with a value of every column in their order, or `undefined` for `DEFAULT`. */
2418
3210
  readonly values: readonly (readonly (ExpressionNode | undefined)[])[];
3211
+ /** `ON CONFLICT` of the insert, or `undefined` for an insert that rejects a row that conflicts on a key. */
3212
+ readonly conflict?: ConflictNode | undefined;
3213
+ }
3214
+ /** `ON CONFLICT` of an insert: a row that conflicts on `target` updates the existing row by `update`, or is skipped, as `DO NOTHING`, without it. */
3215
+ interface ConflictNode {
3216
+ /**
3217
+ * What a row conflicts on: the keys of the columns of a key of the table, in its order, none for any key, which only `DO NOTHING` takes, or `"singleton"` for the unique index of `(true)` of a singleton table, which holds its one row.
3218
+ */
3219
+ readonly target: readonly string[] | "singleton";
3220
+ readonly update?: ConflictUpdateNode | undefined;
3221
+ }
3222
+ /** `DO UPDATE SET` of `ON CONFLICT`, whose values see the existing row as the target of the insert and the row proposed for insertion as `excluded`. */
3223
+ interface ConflictUpdateNode {
3224
+ /** Assignments of `SET`, at least one, with unique keys. */
3225
+ readonly set: readonly AssignmentNode[];
3226
+ /** Occurrence of the table that stands for the row proposed for insertion, `EXCLUDED` of PostgreSQL, which the values of `set` refer to and which is in no `FROM`. */
3227
+ readonly excluded: TableSourceNode;
2419
3228
  }
2420
3229
  /** Update statement of the rows that its filters choose. */
2421
3230
  interface UpdateNode<Field = ProjectionNode> extends MutationParts<Field> {
@@ -2564,89 +3373,6 @@ type MatchResult<R, V> = boolean | (V extends unknown ? { [K in keyof V]-?: K ex
2564
3373
  * 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`.
2565
3374
  */
2566
3375
  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>>;
2567
- /**
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.
2569
- *
2570
- * It is guaranteed, so that the state that the callback returns tells whether the callback ends the guarantee of the query the helper is applied to.
2571
- */
2572
- interface HelperState<T extends AnyTable, C extends SchemaContext> extends QueryStateOf<T, C> {
2573
- readonly result: HelperFields<never>;
2574
- readonly valueType: never;
2575
- readonly rows: "many";
2576
- readonly value: false;
2577
- readonly uses: never;
2578
- readonly guaranteed: true;
2579
- readonly aggregate: false;
2580
- }
2581
- /**
2582
- * Effect of a helper: the fields it selects, its rows mode on a query of many rows, `one` after `take` or `required` and `nullable` or `optional` after the method of the same name, the relations it selects records of, and whether it keeps the guarantee of the row of a query of a required relation.
2583
- *
2584
- * `reads` are the relations of the schema of the helper among them, which its callback may read from the references of the query it is applied to, and `key` is the key of its table there.
2585
- */
2586
- interface HelperEffect {
2587
- readonly fields: object;
2588
- readonly rows: ResultRows;
2589
- readonly uses: UsedRelation;
2590
- readonly reads: UsedRelation;
2591
- readonly key: string;
2592
- readonly guaranteed: boolean;
2593
- }
2594
- /** Effect of a helper whose callback returns a query of state `S`, for each state of a union. */
2595
- type ReadEffect<S extends SelectQueryState> = S extends SelectQueryState ? {
2596
- readonly fields: { [K in keyof S["result"] as K extends keyof HelperFields ? never : K]: S["result"][K]; };
2597
- readonly rows: S["rows"];
2598
- readonly uses: S["uses"];
2599
- readonly reads: Extract<UsableRelation<S["schema"]["relations"]>, S["uses"]>;
2600
- readonly key: S["schema"]["key"];
2601
- readonly guaranteed: S["guaranteed"];
2602
- } : never;
2603
- /** Error of a helper that a query does not accept, or whose callback returns a query it does not accept. */
2604
- interface HelperError<Message extends string> {
2605
- readonly error: Message;
2606
- }
2607
- /** `unknown` when every result state retains the input marker and returns records, or the error. */
2608
- type CheckResult<S extends SelectQueryState> = [S] extends [{
2609
- readonly result: HelperFields;
2610
- readonly value: false;
2611
- }] ? unknown : HelperError<"A helper can filter, select fields, and take one row, but cannot clear the selection or use get, pluck, or aggregates">;
2612
- /** State of a query over table `T` that accepts a helper of effect `E`. */
2613
- type HelperInput<T extends AnyTable, E extends HelperEffect> = QueryStateOf<T, ReadsContext<E>> & ValueCheck<E>;
2614
- /** Constraint of `value` of a query that accepts a helper of effect `E`. */
2615
- type ValueCheck<E extends HelperEffect> = [E extends HelperEffect ? keyof E["fields"] : never] extends [never] ? [Extract<E["rows"], "nullable">] extends [never] ? unknown : RecordRows<"A helper cannot apply nullable to a query made by get, pluck, or an aggregate"> : RecordRows<"A helper cannot select fields on a query made by get, pluck, or an aggregate">;
2616
- /** Constraint of a query whose rows are records, which a query of values fails with error `Message`. */
2617
- interface RecordRows<Message extends string> {
2618
- readonly value: false | HelperError<Message>;
2619
- }
2620
- /** Schema context of a query that has the relations of its schema that a helper of effect `E` may read. */
2621
- type ReadsContext<E extends HelperEffect> = [E["reads"]] extends [never] ? SchemaContext : SchemaContext<{ readonly [K in E["reads"]["key"]]: { readonly [N in Extract<E["reads"], {
2622
- readonly key: K;
2623
- }>["name"]]: Extract<E["reads"], {
2624
- readonly key: K;
2625
- readonly name: N;
2626
- }>["relation"]; }; }, E["key"]>;
2627
- /** State of a query of state `S` after a helper of effect `E`. */
2628
- type ApplyEffect<S extends SelectQueryState, E extends HelperEffect> = ChangeState<S, {
2629
- result: [keyof E["fields"]] extends [never] ? S["result"] : MergeSelection<S["result"], E["fields"]>;
2630
- rows: E["rows"] extends "many" ? EffectRows<S, E> : E["rows"] extends "one" ? OneRow<EffectRows<S, E>> : E["rows"];
2631
- uses: S["uses"] | E["uses"];
2632
- guaranteed: E["guaranteed"] extends true ? S["guaranteed"] : false;
2633
- }>;
2634
- /** Rows mode of a query of state `S` after a helper of effect `E` that keeps the rows, before `take`: relaxed as after a filter when the helper ends the guarantee. */
2635
- type EffectRows<S extends SelectQueryState, E extends HelperEffect> = E["guaranteed"] extends true ? S["rows"] : FilteredStateRows<S>;
2636
- /**
2637
- * Helper of `defineHelper` for queries over table `T`: it applies effect `E` to the query it receives with arguments `A` and returns a query of the same kind.
2638
- *
2639
- * Selected fields replace earlier fields under the same keys; a query made by `get`, `pluck`, or an aggregate method does not accept a helper that selects fields.
2640
- */
2641
- type Helper<T extends AnyTable, E extends HelperEffect, A extends unknown[]> = <S extends HelperInput<T, E>, Kind extends SelectQueryKind>(query: SelectQuery<S, Kind>, ...args: A) => E extends HelperEffect ? SelectQuery<ApplyEffect<S, E>, Kind> : never;
2642
- /**
2643
- * Defines a reusable helper of a table that filters, selects fields, and applies `take`, `optional`, `nullable`, and `required`, used with `use` or called with a query.
2644
- *
2645
- * `helper` receives the query it is applied to and any further arguments, and returns the query with its clauses.
2646
- * Defined with a query of a schema, such as `schema.form`, it can select the relations of the table in that schema, and applies to queries whose schema has them.
2647
- * The helper returns a query of the same kind as the one it is applied to, bound to the same `Db` if any.
2648
- */
2649
- declare function defineHelper<T extends AnyTable, R extends SelectQuery<any, SelectQueryKind>, A extends unknown[], C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, helper: (query: SelectQuery<HelperState<T, C>, SelectQueryKind>, ...args: A) => R & CheckResult<R["types"]>): Helper<T, ReadEffect<R["types"]>, A>;
2650
3376
  /** Tagged template building a SQL fragment of values `T` that accepts compared values `I`. */
2651
3377
  type SqlTemplate<T, O extends OperatorDefinitions, I = T> = (strings: TemplateStringsArray, ...values: unknown[]) => Expression<T, O, I>;
2652
3378
  /**
@@ -2683,4 +3409,10 @@ declare function identifier(...names: [string, ...string[]]): UntypedExpression;
2683
3409
  */
2684
3410
  declare function param<Output, Input, O extends OperatorDefinitions>(type: Type<Output, Input, O, any>, value: Input): Expression<Output, O, Input>;
2685
3411
  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;
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 };
3412
+ /**
3413
+ * Converts a column key to snake case, such as `form_id` for `formId`, for the `columnName` option of `createTableFactory`.
3414
+ *
3415
+ * A run of capital letters is one word, such as `user_id` for `userID`, and digits stay in their word, such as `line2`.
3416
+ */
3417
+ declare function toSnakeCase(key: string): string;
3418
+ export { NoRelations as $, BoundOperators as $i, ResultOf as $n, ScalarQuery as $r, TypedOperandInput as $t, Db as A, ResultMode as Ai, count as An, and as Ar, DecodedFields as At, PendingTestFixture as B, TextValue as Bi, OrderKey as Bn, CountValueType as Br, InitialMutationState as Bt, BaseOperators as C, TableOptions as Ci, CountExpression as Cn, WhereCondition as Cr, AnyRecordQuery as Ct, UntypedExpression as D, NotFoundError as Di, UnfilteredAggregateOptions as Dn, Condition as Dr, AnyQuery as Dt, TypedExpression as E, defineTable as Ei, StringAggOptions as En, CombinedCondition as Er, SelectionState as Et, DatabaseOptions as F, SqlStatement as Fi, some as Fn, OneRow as Fr, AnyMutationQuery as Ft, createTestHelpers as G, TypeOutput as Gi, asc as Gn, InSignature as Gr, HelperEffect as Gt, TestHelpers as H, TypeInput as Hi, OrderTerms as Hn, EqualityOperator as Hr, MutationQuery as Ht, TransactionOptions as I, TransactionFailure as Ii, stringAgg as In, OneValueRows as Ir, ConflictActionRequired as It, SynchronousResult as J, AnyColumn as Ji, ColumnRefs as Jn, ComparisonSignature as Jr, CaseCondition as Jt, AnyTransformedQuery as K, TypeTransform as Ki, desc as Kn, equalityOperators as Kr, defineHelper as Kt, createDatabase as L, createStatement as Li, sum as Ln, QueryResult as Lr, ConflictKeyRequired as Lt, DbOf as M, Connection as Mi, every as Mn, or as Mr, InitialSqlQueryState as Mt, DbQueryState as N, Driver as Ni, max as Nn, ExistsValueType as Nr, SqlQuery as Nt, AnyDb as O, RequiredRelationError as Oi, UnfilteredStringAggOptions as On, ConditionOperand as Or, SelectQueryKind as Ot, Database as P, DriverResult as Pi, min as Pn, FilteredRows as Pr, SqlQueryState as Pt, MergeRelations as Q, ToColumn as Qi, BoundSelectQuery as Qn, OperandUses as Qr, TypedOperand as Qt, TransactionCoordinator as R, AnyType as Ri, OrderColumns as Rn, ResultByRows as Rr, ConflictTarget as Rt, AnyExpression as S, TableKeys as Si, AggregateOptions as Sn, WhereCallback as Sr, defineSchema as St, ExpressionOperators as T, createTableFactory as Ti, GroupValue as Tn, WhereValues as Tr, RecordQueryState as Tt, TestHooks as U, TypeOperators as Ui, Ordering as Un, EqualityOperators as Ur, MutationQueryState as Ut, TestFixture as V, Type as Vi, OrderTerm as Vn, CompileOptions as Vr, InsertMutationState as Vt, TestTransactionOptions as W, TypeOptions as Wi, SelectedRefs as Wn, HasEquality as Wr, Helper as Wt, TransformedQueryState as X, ColumnAttributes as Xi, RelationRefs as Xn, OperandValue as Xr, FollowingOperand as Xt, TransformedQuery as Y, Column as Yi, QueryContext as Yn, Operand as Yr, CaseValue as Yt, DeclaredRelations as Z, KeyKind as Zi, AnySelectQuery as Zn, compare as Zr, NullSkippingResult as Zt, TextOperators as _, ColumnValues as _i, SelectionResult as _n, KeyCheck as _r, Schema as _t, sql as a, OperatorSignature as aa, InitialQueryState as ai, ColumnFieldTypes as an, InsertValues as ar, RelationKeys as at, NumberTypeOperators as b, Table as bi, literal as bn, PrimaryKeyValues as br, SchemaTables as bt, MatchResult as c, QueryValueType as ci, GroupOperandValue as cn, UpsertValues as cr, SchemaContext as ct, defineExpression as d, TableQueryState as di, GroupedRecord as dn, FoundState as dr, TableRelations as dt, MergeOperators as ea, TypedScalarQuery as ei, TypedOperandOperators as en, SelectQuery as er, OneRelationKeys as et, FALSE as f, AnyTable as fi, MergeSelection as fn, GroupedState as fr, UsableRelation as ft, TextLengthSignature as g, ColumnShape as gi, SelectionFieldTypes as gn, GroupTerms as gr, AnySchema as gt, TextConversionSignature as h, ColumnOperators as hi, Selection as hn, GroupTerm as hr, one as ht, param as i, GenericOperatorImplementation as ia, Grouped as ii, least as in, ConflictUpdateSet as ir, RelationKey as it, DbMutationState as j, ResultRows as ji, countDistinct as jn, not as jr, FieldTypes as jt, BindOptions as k, ResultDecodeError as ki, avg as kn, Predicate as kr, AnySqlQuery as kt, NotAColumn as l, SelectQueryState as li, GroupSelectionResult as ln, FilteredStateRows as lr, SchemaRelations as lt, PatternSignature as m, ColumnDefinitions as mi, SelectedFieldTypes as mn, RowLockOptions as mr, many as mt, SqlTemplate as n, OperatorDefinitions as na, EmptyRecord as ni, coalesce as nn, from as nr, RelationDeclaration as nt, ColumnRefKey as o, defineGenericOperator as oa, QueryState as oi, ExpressionInput as on, UpdateSet as or, RelationKind as ot, TRUE as p, AnyTableKeys as pi, NestedQuery as pn, SelectedOperandType as pr, UsedRelation as pt, NotSynchronous as q, defineType as qi, orderBy as qn, BooleanResult as qr, CaseBranch as qt, identifier as r, GenericOperator as ra, FoundKey as ri, greatest as rn, ColumnValue as rr, RelationDeclarations as rt, MatchCheck as s, QueryStateOf as si, ExpressionValue as sn, UpdateValues as sr, RequiredMember as st, toSnakeCase as t, NoOperators as ta, ValuesQuery as ti, caseWhen as tn, SingletonInsertMany as tr, Relation as tt, matches as u, SingletonQueryState as ui, GroupedField as un, FoundQueryState as ur, TableContext as ut, TextTypeOperators as v, KeyColumns as vi, SelectionUses as vn, NotAKey as vr, SchemaPart as vt, Expression as w, ToColumns as wi, GroupAggregateExpression as wn, WhereFilter as wr, RecordQuery as wt, orderingOperators as x, TableFactoryOptions as xi, AggregateExpression as xn, EqValue as xr, Tables as xt, textOperators as y, Selectable as yi, Literal as yn, PrimaryKeyColumn as yr, SchemaPartRelations as yt, OpenedTestFixture as z, BaseType as zi, OrderDirection as zn, ValueRows as zr, InitialInsertState as zt };