kern-orm 0.6.0 → 0.8.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.
- package/dist/{database-CP4oapsQ.mjs → driver-error-Dx5R83Rp.mjs} +349 -32
- package/dist/{index-CoKpXcBp.d.mts → index-B1aH5Ht0.d.mts} +301 -40
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +3 -3
- package/dist/testing.d.mts +1 -3
- package/dist/testing.mjs +141 -11
- package/dist/{text-Cti9QLK7.mjs → text-CIUxPWPl.mjs} +1 -0
- package/dist/{types-DfoL8Oi9.mjs → types-D3d35qR2.mjs} +4 -13
- package/dist/types.d.mts +3 -8
- package/dist/types.mjs +2 -2
- package/package.json +1 -7
|
@@ -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
|
|
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
|
|
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 |
|
|
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 |
|
|
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
|
|
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;
|
|
@@ -222,15 +241,22 @@ interface DriverResult {
|
|
|
222
241
|
* Physical database access: transport, pooling, and connections.
|
|
223
242
|
*
|
|
224
243
|
* A driver sends parameters as text without a declared type, so that the statement text alone determines their types, and returns values as text without parsing them.
|
|
244
|
+
* It rejects with `QueryError` a statement or script that PostgreSQL rejected, whose connection stays usable, and with `ConnectionError` any other failure of a statement, a script, or a connection.
|
|
225
245
|
*/
|
|
226
246
|
interface Driver {
|
|
247
|
+
/** Whether the driver closes a reserved connection that it cannot return to the pool, such as one left in a transaction or lost; a driver over a client that cannot close one, such as postgres.js 3, keeps it reserved instead. */
|
|
248
|
+
readonly closesReservedConnections: boolean;
|
|
227
249
|
/** Executes a statement on any pooled connection. */
|
|
228
250
|
execute(statement: SqlStatement): Promise<DriverResult>;
|
|
229
251
|
/** Executes a script of statements without parameters, such as DDL separated by semicolons, on any pooled connection, where PostgreSQL runs them in one implicit transaction. */
|
|
230
252
|
executeScript(text: string): Promise<void>;
|
|
231
253
|
/** Reserves a dedicated connection, such as for a transaction. */
|
|
232
254
|
acquire(): Promise<Connection>;
|
|
233
|
-
/**
|
|
255
|
+
/**
|
|
256
|
+
* Closes the connections once the statements on the pool and the transactions on reserved connections end.
|
|
257
|
+
*
|
|
258
|
+
* From the call, it rejects a new statement or script on the pool and a new connection with `ConnectionError`.
|
|
259
|
+
*/
|
|
234
260
|
close(): Promise<void>;
|
|
235
261
|
}
|
|
236
262
|
/** Connection reserved by a driver, such as for a transaction. */
|
|
@@ -244,14 +270,14 @@ interface Connection {
|
|
|
244
270
|
/** Executes a script of statements without parameters on the connection, in the order of calls with its statements. */
|
|
245
271
|
executeScript(text: string): Promise<void>;
|
|
246
272
|
/**
|
|
247
|
-
* Returns the connection to the pool
|
|
273
|
+
* Returns the connection to the pool.
|
|
248
274
|
*
|
|
249
|
-
* Without `failure`, the transaction
|
|
250
|
-
* With `failure`,
|
|
275
|
+
* Without `failure`, the connection is idle: no transaction ran on it, or its `COMMIT` or `ROLLBACK` completed.
|
|
276
|
+
* With `failure`, the last statement on the connection failed, such as `BEGIN`, `COMMIT`, or `ROLLBACK`, so the connection may be in a transaction or lost: the driver returns it to the pool only once it is idle, and never returns a connection it lost.
|
|
251
277
|
*/
|
|
252
278
|
release(failure?: TransactionFailure): void | Promise<void>;
|
|
253
279
|
}
|
|
254
|
-
/** Failure of the statement
|
|
280
|
+
/** Failure of the last statement on a reserved connection, after which the connection may not be idle. */
|
|
255
281
|
interface TransactionFailure {
|
|
256
282
|
readonly error: unknown;
|
|
257
283
|
}
|
|
@@ -385,21 +411,23 @@ interface TableKeys<PrimaryKey extends KeyColumns | undefined, UniqueKey extends
|
|
|
385
411
|
readonly [keysType]: (primaryKey: PrimaryKey, unique: UniqueKey) => readonly [PrimaryKey, UniqueKey];
|
|
386
412
|
}
|
|
387
413
|
/**
|
|
388
|
-
* Immutable table descriptor: physical name, columns, and
|
|
414
|
+
* Immutable table descriptor: physical name, columns, keys, and whether it holds at most one row.
|
|
389
415
|
*
|
|
390
416
|
* A table knows nothing about relations, schemas, or database connections, so the same table can belong to several schemas.
|
|
391
417
|
* Its object identity is the logical identity of the table.
|
|
392
418
|
*/
|
|
393
|
-
interface Table<Name extends string = string, Columns extends ColumnShape = ColumnShape, Keys extends AnyTableKeys = AnyTableKeys> {
|
|
419
|
+
interface Table<Name extends string = string, Columns extends ColumnShape = ColumnShape, Keys extends AnyTableKeys = AnyTableKeys, Singleton extends boolean = boolean> {
|
|
394
420
|
readonly kind: "table";
|
|
395
421
|
readonly name: Name;
|
|
396
422
|
readonly columns: Columns;
|
|
397
423
|
readonly keys: Keys;
|
|
424
|
+
/** 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. */
|
|
425
|
+
readonly singleton: Singleton;
|
|
398
426
|
}
|
|
399
427
|
/** Table of any name, columns, and keys. */
|
|
400
428
|
type AnyTable = Table<string, ColumnShape>;
|
|
401
429
|
/**
|
|
402
|
-
* Options of `defineTable` over column keys `Column`: the keys of several columns, whose columns are listed in their order.
|
|
430
|
+
* 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.
|
|
403
431
|
*
|
|
404
432
|
* The columns of the primary key are of `PrimaryKeyColumn`.
|
|
405
433
|
*/
|
|
@@ -408,6 +436,12 @@ interface TableOptions<Column extends string = string, PrimaryKeyColumn extends
|
|
|
408
436
|
readonly primaryKey?: readonly [PrimaryKeyColumn, PrimaryKeyColumn, ...PrimaryKeyColumn[]];
|
|
409
437
|
/** Unique keys of several columns; mark a unique key of one column with `unique()`. */
|
|
410
438
|
readonly unique?: readonly (readonly [Column, Column, ...Column[]])[];
|
|
439
|
+
/**
|
|
440
|
+
* Whether the table holds at most one row, such as the settings of an application, which a unique index of `(true)` must guarantee.
|
|
441
|
+
*
|
|
442
|
+
* A query of the table starts as a query of that row, which resolves to `undefined` without it, and `upsert` inserts or updates it.
|
|
443
|
+
*/
|
|
444
|
+
readonly singleton?: boolean;
|
|
411
445
|
}
|
|
412
446
|
/** Options of `createTableFactory`. */
|
|
413
447
|
interface TableFactoryOptions {
|
|
@@ -439,8 +473,8 @@ type MatchingKey$1<Key, Columns> = Key extends KeyColumns ? [Key[number]] extend
|
|
|
439
473
|
type IncludedKey<Key, Columns> = Key extends KeyColumns ? [Key[number]] extends [Columns] ? true : never : never;
|
|
440
474
|
/** Column key of columns `C` as a string, as object keys are at runtime. */
|
|
441
475
|
type ColumnKey<C extends ColumnShape> = `${keyof C & (string | number)}`;
|
|
442
|
-
/** Column key of columns `C` whose type
|
|
443
|
-
type NonNullableColumnKey<C extends ColumnShape> = { [K in keyof C]: null extends
|
|
476
|
+
/** Column key of columns `C` whose type does not accept `null`, as a string like `ColumnKey`. */
|
|
477
|
+
type NonNullableColumnKey<C extends ColumnShape> = { [K in keyof C]: null extends TypeInput<C[K]["type"]> ? never : `${K & (string | number)}`; }[keyof C];
|
|
444
478
|
/** Column key of columns `C`, as a string like `ColumnKey`, whose column forms a key of kind `Kind` alone, as `KnownKeyKind` tells. */
|
|
445
479
|
type KeyedColumn<C extends ColumnShape, Kind> = { [K in keyof C]: KnownKeyKind<C[K]["attributes"]["keyKind"]> extends Kind ? `${K & (string | number)}` : never; }[keyof C];
|
|
446
480
|
/** Kind `Kind` of the key that a column forms alone, or `"unknown"` where the type of the column does not tell it. */
|
|
@@ -462,6 +496,8 @@ type KnownKeysOf<PrimaryKey extends KeyColumns | undefined, UniqueKey extends Ke
|
|
|
462
496
|
type DefinedPrimaryKey<C extends ColumnShape, PrimaryKey> = PrimaryKey extends KeyColumns ? PrimaryKey : [KeyedColumn<C, "primaryKey">] extends [never] ? undefined : SingleColumnKey<KeyedColumn<C, "primaryKey">>;
|
|
463
497
|
/** Unique key of a table of columns `C`: `UniqueKey` of its options, or of a column marked with `unique()`. */
|
|
464
498
|
type DefinedUniqueKey<C extends ColumnShape, UniqueKey> = Extract<UniqueKey, KeyColumns> | SingleColumnKey<KeyedColumn<C, "unique">>;
|
|
499
|
+
/** 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. */
|
|
500
|
+
type DefinedSingleton<O> = O extends unknown ? [O["singleton" & keyof O]] extends [false | undefined] ? false : [O["singleton" & keyof O]] extends [true] ? true : boolean : never;
|
|
465
501
|
/** Key of each single column of `K`. */
|
|
466
502
|
type SingleColumnKey<K> = K extends string ? readonly [K] : never;
|
|
467
503
|
/** Primary key in options `O`: `undefined` without one, or `"unknown"` where its type does not tell it. */
|
|
@@ -479,13 +515,13 @@ type IsExactKey<K> = true extends IsUnion<K> ? false : K extends readonly unknow
|
|
|
479
515
|
*
|
|
480
516
|
* A key of one column is marked on its column.
|
|
481
517
|
*/
|
|
482
|
-
declare function defineTable<Name extends string, Definitions extends ColumnDefinitions>(name: Name, definitions: Definitions): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, undefined
|
|
518
|
+
declare function defineTable<Name extends string, Definitions extends ColumnDefinitions>(name: Name, definitions: Definitions): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, undefined>, false>;
|
|
483
519
|
/**
|
|
484
520
|
* Defines a table; a type without column attributes becomes a column as it is.
|
|
485
521
|
*
|
|
486
|
-
* A key of one column is marked on its column, and `options` list the columns of the keys of several columns.
|
|
522
|
+
* 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.
|
|
487
523
|
*/
|
|
488
|
-
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>>;
|
|
524
|
+
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>>;
|
|
489
525
|
/**
|
|
490
526
|
* Creates a table-definition function with the given naming convention, for an application to define its tables with.
|
|
491
527
|
*
|
|
@@ -556,6 +592,23 @@ interface InitialQueryState<T extends AnyTable, C extends SchemaContext = NoRela
|
|
|
556
592
|
readonly guaranteed: Guaranteed;
|
|
557
593
|
readonly aggregate: false;
|
|
558
594
|
}
|
|
595
|
+
/**
|
|
596
|
+
* 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.
|
|
597
|
+
*
|
|
598
|
+
* Where the type of `T` does not tell whether it is a singleton, such as `Table<Name, Columns>`, it is the union of both.
|
|
599
|
+
*/
|
|
600
|
+
type TableQueryState<T extends AnyTable, C extends SchemaContext = NoRelations> = SingletonOrInitialState<T, C, T["singleton"]>;
|
|
601
|
+
/** 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`. */
|
|
602
|
+
type SingletonOrInitialState<T extends AnyTable, C extends SchemaContext, Singleton> = Singleton extends true ? SingletonQueryState<T, C> : InitialQueryState<T, C>;
|
|
603
|
+
/** 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. */
|
|
604
|
+
interface SingletonQueryState<T extends AnyTable, C extends SchemaContext = NoRelations> extends InitialQueryState<T, C, never, "optional">, FoundKey<never> {}
|
|
605
|
+
/** Key of the member of `FoundKey` that makes it invariant in the columns of the key. */
|
|
606
|
+
declare const foundKeyVariance: unique symbol;
|
|
607
|
+
/** 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. */
|
|
608
|
+
interface FoundKey<K extends string> {
|
|
609
|
+
readonly foundKey: K;
|
|
610
|
+
readonly [foundKeyVariance]: { readonly [C in K]: true; };
|
|
611
|
+
}
|
|
559
612
|
/** Mark of `aggregate: false` of a query of groups, which aggregate methods replace. */
|
|
560
613
|
interface Grouped {
|
|
561
614
|
readonly grouped: true;
|
|
@@ -705,6 +758,12 @@ interface QueryNode extends ResultMode {
|
|
|
705
758
|
readonly all: boolean;
|
|
706
759
|
/** How `map` and `transform` convert the decoded result. */
|
|
707
760
|
readonly conversion: ResultConversion | undefined;
|
|
761
|
+
/**
|
|
762
|
+
* 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.
|
|
763
|
+
*
|
|
764
|
+
* Every method that derives a node from the query drops them, whereas `use` returns the query of its callback, such as the query itself.
|
|
765
|
+
*/
|
|
766
|
+
readonly foundKey: Readonly<Record<string, unknown>> | undefined;
|
|
708
767
|
}
|
|
709
768
|
/**
|
|
710
769
|
* 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.
|
|
@@ -816,13 +875,15 @@ type QueryWhereFilter<S extends SelectQueryState> = [S] extends [unknown] ? Wher
|
|
|
816
875
|
* A union of tables gives the union of their values.
|
|
817
876
|
*/
|
|
818
877
|
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;
|
|
878
|
+
/** Columns of the primary key of table `T`, or `never` where the type of `T` tells no primary key. */
|
|
879
|
+
type PrimaryKeyColumn<T extends AnyTable> = T extends AnyTable ? T["keys"] extends TableKeys<infer PrimaryKey extends KeyColumns, infer _UniqueKey> ? PrimaryKey[number] : never : never;
|
|
819
880
|
/**
|
|
820
|
-
* Check of columns `Columns
|
|
881
|
+
* 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.
|
|
821
882
|
*
|
|
822
883
|
* A table of `any`, such as of `AnySelectQuery`, takes any columns, as `where` takes any values there.
|
|
823
884
|
*/
|
|
824
885
|
type KeyCheck<T extends AnyTable, Columns> = [IsKey<T, Columns>] extends [true] ? unknown : IsAny<T> extends true ? unknown : NotAKey<KeyOf<T["keys"]>>;
|
|
825
|
-
/** Type that the
|
|
886
|
+
/** 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. */
|
|
826
887
|
interface NotAKey<Keys> {
|
|
827
888
|
readonly "columns must be exactly one key of the table": Keys;
|
|
828
889
|
}
|
|
@@ -869,11 +930,23 @@ type FilteredState<S extends SelectQueryState> = ChangeState<S, {
|
|
|
869
930
|
rows: FilteredStateRows<S>;
|
|
870
931
|
guaranteed: false;
|
|
871
932
|
}>;
|
|
872
|
-
/** State `S` after a filter followed by `take`, as `find` and `findBy` change it
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
933
|
+
/** State `S` after a filter followed by `take`, as `find` and `findBy` change it, with the columns `K` of their key for `upsert`. */
|
|
934
|
+
interface FoundState<S extends SelectQueryState, K extends string> extends SelectQueryState, FoundKey<K> {
|
|
935
|
+
readonly table: S["table"];
|
|
936
|
+
readonly schema: S["schema"];
|
|
937
|
+
readonly result: S["result"];
|
|
938
|
+
readonly rows: OneRow<FilteredStateRows<S>>;
|
|
939
|
+
readonly value: S["value"];
|
|
940
|
+
readonly valueType: S["valueType"];
|
|
941
|
+
readonly fieldTypes: S["fieldTypes"];
|
|
942
|
+
readonly uses: S["uses"];
|
|
943
|
+
readonly guaranteed: false;
|
|
944
|
+
readonly aggregate: S["aggregate"];
|
|
945
|
+
}
|
|
946
|
+
/** State of a query of `find` or `findBy`, or of a singleton table, which `upsert` applies to. */
|
|
947
|
+
type FoundQueryState = SelectQueryState & {
|
|
948
|
+
readonly foundKey: string;
|
|
949
|
+
};
|
|
877
950
|
/** State of a query whose rows are records, which `select` and `clearSelect` change. */
|
|
878
951
|
type RecordQueryState$1 = SelectQueryState & {
|
|
879
952
|
readonly value: false;
|
|
@@ -988,10 +1061,14 @@ type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValue
|
|
|
988
1061
|
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"]];
|
|
989
1062
|
/** 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`. */
|
|
990
1063
|
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; };
|
|
1064
|
+
/** Values of `upsert` into table `T`: a record of an insert without the columns `K` of the key, whose values `find` or `findBy` gives. */
|
|
1065
|
+
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; };
|
|
991
1066
|
/** Values of the columns of table `T` that an update sets; a column omitted or given as `undefined` keeps its value. */
|
|
992
1067
|
type UpdateValues<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: ColumnValue<T, K> | undefined; };
|
|
993
1068
|
/** 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. */
|
|
994
1069
|
type UpdateSet<T extends AnyTable, C extends SchemaContext = NoRelations> = UpdateValues<T> | ((columns: ColumnRefs<T> & RelationRefs<C>) => UpdateValues<T>);
|
|
1070
|
+
/** 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. */
|
|
1071
|
+
type ConflictUpdateSet<T extends AnyTable, C extends SchemaContext = NoRelations> = UpdateValues<T> | ((columns: ColumnRefs<T> & RelationRefs<C>, excluded: ColumnRefs<T>) => UpdateValues<T>);
|
|
995
1072
|
/** State `S` with the parts of `Changes` replaced. */
|
|
996
1073
|
type ChangeState<S extends SelectQueryState, Changes extends Partial<SelectQueryState>> = { readonly [K in keyof SelectQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
|
|
997
1074
|
/** Query of state `S`, bound or unbound. */
|
|
@@ -1067,15 +1144,17 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1067
1144
|
*
|
|
1068
1145
|
* A value is what `where` takes for its column, such as an expression, but never `null` or `undefined`.
|
|
1069
1146
|
* Without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
|
|
1147
|
+
* To insert the record of the key or update the existing one, call `upsert` right after it.
|
|
1070
1148
|
*/
|
|
1071
|
-
find<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, ...values: PrimaryKeyValues<S["table"]>): SelectQuery<FoundState<S
|
|
1149
|
+
find<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, ...values: PrimaryKeyValues<S["table"]>): SelectQuery<FoundState<S, PrimaryKeyColumn<S["table"]>>, Kind>;
|
|
1072
1150
|
/**
|
|
1073
1151
|
* 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.
|
|
1074
1152
|
*
|
|
1075
1153
|
* A value is what `where` takes for its column, such as an expression, but never `null` or `undefined`.
|
|
1076
1154
|
* Without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
|
|
1155
|
+
* To insert the record of the key or update the existing one, call `upsert` right after it.
|
|
1077
1156
|
*/
|
|
1078
|
-
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>;
|
|
1157
|
+
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>;
|
|
1079
1158
|
/**
|
|
1080
1159
|
* Replaces the selected fields with a column, limits the query to one row, and returns the value of the column instead of a record.
|
|
1081
1160
|
*
|
|
@@ -1369,22 +1448,34 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1369
1448
|
* A column omitted or given as `undefined` gets its default, so only columns marked with `hasDefault` and nullable columns may be omitted.
|
|
1370
1449
|
* 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.
|
|
1371
1450
|
* Select the fields that it returns after it, such as `insert(values).get("id")`.
|
|
1451
|
+
* To handle a conflict of the record with an existing one on a key, call `onConflict` right after `insert`.
|
|
1372
1452
|
*/
|
|
1373
|
-
insert<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, values: InsertValues<S["table"]>): MutationQuery<
|
|
1453
|
+
insert<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, values: InsertValues<S["table"]>): MutationQuery<InitialInsertState<S["table"], S["schema"], "one">, Kind>;
|
|
1374
1454
|
/**
|
|
1375
1455
|
* 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.
|
|
1376
1456
|
*
|
|
1377
1457
|
* A record takes the values that `insert` takes, and a column that a record omits gets its default.
|
|
1378
1458
|
* 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.
|
|
1459
|
+
* To handle a conflict of a record with an existing one on a key, call `onConflict` right after `insertMany`.
|
|
1460
|
+
* A singleton table, which holds one row, takes `insert` or `upsert` instead.
|
|
1461
|
+
*/
|
|
1462
|
+
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>;
|
|
1463
|
+
/**
|
|
1464
|
+
* 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`.
|
|
1465
|
+
*
|
|
1466
|
+
* `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.
|
|
1467
|
+
* 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.
|
|
1468
|
+
* Select the fields that it returns after it, such as `upsert(values).get("id")`.
|
|
1469
|
+
* To update the existing record with other values than the inserted ones, such as to increment a counter, call `onConflict` after `insert` instead.
|
|
1379
1470
|
*/
|
|
1380
|
-
|
|
1471
|
+
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>;
|
|
1381
1472
|
/**
|
|
1382
1473
|
* 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.
|
|
1383
1474
|
*
|
|
1384
1475
|
* `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.
|
|
1385
1476
|
* A value is what `insert` takes as a value, such as a query of an aggregate of related records.
|
|
1386
1477
|
* A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
|
|
1387
|
-
* A query without a filter must call `all` to update every row.
|
|
1478
|
+
* 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.
|
|
1388
1479
|
* Select the fields that it returns after it, with their values after the update, such as `update(callback).select("id")`.
|
|
1389
1480
|
*/
|
|
1390
1481
|
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>;
|
|
@@ -1394,7 +1485,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1394
1485
|
* `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.
|
|
1395
1486
|
* A value is what `insert` takes as a value.
|
|
1396
1487
|
* A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
|
|
1397
|
-
* A query without a filter must call `all` to update every row.
|
|
1488
|
+
* 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.
|
|
1398
1489
|
* Select the fields that it returns after it, with their values after the update, such as `update(set).select("id")`.
|
|
1399
1490
|
*/
|
|
1400
1491
|
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>;
|
|
@@ -1402,7 +1493,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1402
1493
|
* Deletes the rows that the filters of the query choose, and resolves to the number of the deleted rows.
|
|
1403
1494
|
*
|
|
1404
1495
|
* A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
|
|
1405
|
-
* A query without a filter must call `all` to delete every row.
|
|
1496
|
+
* 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.
|
|
1406
1497
|
* Select the fields that it returns after it, such as `delete().pluck("id")`.
|
|
1407
1498
|
*/
|
|
1408
1499
|
delete<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"]>, Kind>;
|
|
@@ -1452,7 +1543,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1452
1543
|
* It rejects a query of records, which `ValuesQuery` rejects in types.
|
|
1453
1544
|
*/
|
|
1454
1545
|
[valuesQueryNode](): NestedQueryNode;
|
|
1455
|
-
/** Creates a query of the same kind and `Db` with the node changes applied. */
|
|
1546
|
+
/** 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. */
|
|
1456
1547
|
private derive;
|
|
1457
1548
|
/**
|
|
1458
1549
|
* Creates a query of the same kind and `Db` with the node changes applied and then those of `take`, in one derived query.
|
|
@@ -1472,7 +1563,11 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1472
1563
|
private addFilter;
|
|
1473
1564
|
/** Returns the rows mode of this query after a filter, as `FilteredStateRows` gives it in types. */
|
|
1474
1565
|
private getFilteredRows;
|
|
1475
|
-
/**
|
|
1566
|
+
/**
|
|
1567
|
+
* 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`.
|
|
1568
|
+
*
|
|
1569
|
+
* On a query of a table without clauses, it keeps `values` as the key that `upsert` inserts.
|
|
1570
|
+
*/
|
|
1476
1571
|
private takeWhere;
|
|
1477
1572
|
/** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
|
|
1478
1573
|
private changeOneRow;
|
|
@@ -1485,6 +1580,12 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1485
1580
|
/** Rejects `method`, an aggregate method or `exists`, on a query made by one of them or with a row lock. */
|
|
1486
1581
|
private rejectAggregation;
|
|
1487
1582
|
}
|
|
1583
|
+
/** Check of the records of `insertMany` into table `T` that rejects them for a singleton table, which holds one row. */
|
|
1584
|
+
type InsertManyCheck<T extends AnyTable> = T["singleton"] extends true ? SingletonInsertMany : unknown;
|
|
1585
|
+
/** Type that the records of `insertMany` into a singleton table are checked against, naming the reason. */
|
|
1586
|
+
interface SingletonInsertMany {
|
|
1587
|
+
readonly "insertMany cannot insert into a singleton table, which holds one row; use insert or upsert": never;
|
|
1588
|
+
}
|
|
1488
1589
|
/** Select query bound to a `Db`, executed by awaiting it; every method returns a query bound to the same `Db`. */
|
|
1489
1590
|
type BoundSelectQuery<S extends SelectQueryState> = SelectQuery<S, "bound">;
|
|
1490
1591
|
/** Select query of any state and kind. */
|
|
@@ -1494,7 +1595,11 @@ type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
|
|
|
1494
1595
|
/** Table of a definition such as `defineExpression`: the table itself or a query over it with schema context `C`, such as `schema.form`. */
|
|
1495
1596
|
type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
|
|
1496
1597
|
/** Starts a query over a new occurrence of the table. */
|
|
1497
|
-
declare function from<T extends
|
|
1598
|
+
declare function from<T extends Table<string, ColumnShape, AnyTableKeys, false>>(table: T): SelectQuery<InitialQueryState<T>>;
|
|
1599
|
+
/** Starts a query of the one row of a singleton table over a new occurrence of the table. */
|
|
1600
|
+
declare function from<T extends Table<string, ColumnShape, AnyTableKeys, true>>(table: T): SelectQuery<SingletonQueryState<T>>;
|
|
1601
|
+
/** 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. */
|
|
1602
|
+
declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T> | SingletonQueryState<T>>;
|
|
1498
1603
|
/** References to the columns of the query source, passed to query callbacks. */
|
|
1499
1604
|
type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
|
|
1500
1605
|
/**
|
|
@@ -1882,6 +1987,16 @@ interface InitialMutationState<T extends AnyTable, C extends SchemaContext, Rows
|
|
|
1882
1987
|
readonly value: true;
|
|
1883
1988
|
readonly uses: U;
|
|
1884
1989
|
}
|
|
1990
|
+
/** State of an insert of `insert` or `insertMany` of table `T` with schema context `C` in rows mode `Rows`, before any other method. */
|
|
1991
|
+
interface InitialInsertState<T extends AnyTable, C extends SchemaContext, Rows extends ResultRows> extends InitialMutationState<T, C, Rows> {
|
|
1992
|
+
readonly insert: true;
|
|
1993
|
+
}
|
|
1994
|
+
/** State of an insert that no method has changed since `insert` or `insertMany`, which `onConflict` applies to. */
|
|
1995
|
+
interface InsertMutationState extends MutationQueryState {
|
|
1996
|
+
readonly insert: true;
|
|
1997
|
+
}
|
|
1998
|
+
/** 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. */
|
|
1999
|
+
type SkippedRows<Rows extends ResultRows> = Rows extends "one" ? "optional" : Rows;
|
|
1885
2000
|
/** State `S` of a mutation with the parts of `Changes` replaced. */
|
|
1886
2001
|
type ChangeMutationState<S extends MutationQueryState, Changes extends Partial<MutationQueryState>> = { readonly [K in keyof MutationQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
|
|
1887
2002
|
/** State of a mutation that returns the number of the rows it changes or their records, which `select` applies to. */
|
|
@@ -2034,6 +2149,12 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
|
|
|
2034
2149
|
* A selection of no fields fails as well on a mutation that returns the number of its rows.
|
|
2035
2150
|
*/
|
|
2036
2151
|
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;
|
|
2152
|
+
/**
|
|
2153
|
+
* 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.
|
|
2154
|
+
*
|
|
2155
|
+
* 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.
|
|
2156
|
+
*/
|
|
2157
|
+
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>;
|
|
2037
2158
|
/**
|
|
2038
2159
|
* Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
|
|
2039
2160
|
*
|
|
@@ -2051,6 +2172,74 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
|
|
|
2051
2172
|
}
|
|
2052
2173
|
/** Query of any state and kind that inserts, updates, or deletes rows. */
|
|
2053
2174
|
type AnyMutationQuery = MutationQuery<any, SelectQueryKind>;
|
|
2175
|
+
/**
|
|
2176
|
+
* 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.
|
|
2177
|
+
*
|
|
2178
|
+
* It is no query: awaiting it is a type error and rejects, so that an insert without an action does not resolve without running.
|
|
2179
|
+
*/
|
|
2180
|
+
declare class ConflictTarget<out S extends InsertMutationState, out Kind extends SelectQueryKind = "unbound", out K extends string = string> {
|
|
2181
|
+
/** Insert whose rows conflict. */
|
|
2182
|
+
readonly insert: MutationQuery<S, Kind>;
|
|
2183
|
+
/** Columns of the key that the rows conflict on, in its order, or none, as `onConflict` without columns gives them. */
|
|
2184
|
+
readonly target: readonly K[];
|
|
2185
|
+
constructor(
|
|
2186
|
+
/** Insert whose rows conflict. */
|
|
2187
|
+
insert: MutationQuery<S, Kind>,
|
|
2188
|
+
/** Columns of the key that the rows conflict on, in its order, or none, as `onConflict` without columns gives them. */
|
|
2189
|
+
target: readonly K[]);
|
|
2190
|
+
/**
|
|
2191
|
+
* Skips each row that conflicts, as `ON CONFLICT DO NOTHING`, and returns the mutation.
|
|
2192
|
+
*
|
|
2193
|
+
* After `insert`, the mutation resolves to `0` when the row conflicts, and the fields selected after it to `undefined`.
|
|
2194
|
+
* After `insertMany`, it resolves to the number of the inserted rows, and the fields selected after it are those of the inserted rows.
|
|
2195
|
+
*/
|
|
2196
|
+
doNothing<S extends InsertMutationState, Kind extends SelectQueryKind>(this: ConflictTarget<S, Kind>): MutationQuery<ChangeMutationState<S, {
|
|
2197
|
+
changed: SkippedRows<S["changed"]>;
|
|
2198
|
+
}>, Kind>;
|
|
2199
|
+
/**
|
|
2200
|
+
* 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.
|
|
2201
|
+
*
|
|
2202
|
+
* Every record must give each column that it sets.
|
|
2203
|
+
* After `onConflict()` without columns, it updates the row of a singleton table.
|
|
2204
|
+
*/
|
|
2205
|
+
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, {
|
|
2206
|
+
changed: S["changed"];
|
|
2207
|
+
}>, Kind>;
|
|
2208
|
+
/**
|
|
2209
|
+
* 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.
|
|
2210
|
+
*
|
|
2211
|
+
* `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.
|
|
2212
|
+
* After `onConflict()` without columns, it updates the row of a singleton table.
|
|
2213
|
+
*/
|
|
2214
|
+
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, {
|
|
2215
|
+
uses: S["uses"] | OperandUses<ReturnType<F>[keyof ReturnType<F>]>;
|
|
2216
|
+
}>, Kind>;
|
|
2217
|
+
/**
|
|
2218
|
+
* 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.
|
|
2219
|
+
*
|
|
2220
|
+
* `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`.
|
|
2221
|
+
* After `onConflict()` without columns, it updates the row of a singleton table.
|
|
2222
|
+
*/
|
|
2223
|
+
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, {
|
|
2224
|
+
changed: S["changed"];
|
|
2225
|
+
}>, Kind>;
|
|
2226
|
+
/** Rejects awaiting the conflict target, which needs an action, such as `doNothing()`. */
|
|
2227
|
+
then(_action: ConflictActionRequired): never;
|
|
2228
|
+
/** Returns the node of the insert, which `onConflict` takes only of an insert. */
|
|
2229
|
+
private insertNode;
|
|
2230
|
+
/** Creates the insert of the same kind and `Db` with `conflict`, changing rows `rows`. */
|
|
2231
|
+
private derive;
|
|
2232
|
+
}
|
|
2233
|
+
/** Type of the parameter of `then` of a conflict target, which makes awaiting the target before an action a type error. */
|
|
2234
|
+
interface ConflictActionRequired {
|
|
2235
|
+
readonly "onConflict needs an action, such as doNothing()": never;
|
|
2236
|
+
}
|
|
2237
|
+
/** 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. */
|
|
2238
|
+
type ConflictKeyCheck<S extends InsertMutationState, K extends string> = [K] extends [never] ? S["table"]["singleton"] extends true ? unknown : ConflictKeyRequired : unknown;
|
|
2239
|
+
/** Type that a conflict target on any key is checked against by `merge` and `update`, naming the reason. */
|
|
2240
|
+
interface ConflictKeyRequired {
|
|
2241
|
+
readonly "merge and update need the columns of a key in onConflict": never;
|
|
2242
|
+
}
|
|
2054
2243
|
/** Types of the fields of the rows of a query of SQL text by the names of the result columns they decode. */
|
|
2055
2244
|
interface FieldTypes {
|
|
2056
2245
|
readonly [key: string]: AnyType;
|
|
@@ -2239,8 +2428,8 @@ type Tables = Record<string, AnyTable>;
|
|
|
2239
2428
|
* 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`.
|
|
2240
2429
|
*/
|
|
2241
2430
|
type Schema<T extends Tables, R extends SchemaRelations = EmptyRecord> = SchemaEntries<T, R> & SchemaMembers<T, R>;
|
|
2242
|
-
/** Query entry points; each access starts a query over a new table occurrence. */
|
|
2243
|
-
type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<
|
|
2431
|
+
/** Query entry points; each access starts a query over a new table occurrence, of the one row of a singleton table. */
|
|
2432
|
+
type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<TableQueryState<T[K], TableContext<R, K>>>; };
|
|
2244
2433
|
/** Members of a schema that composition reads: its tables and the relations of its tables. */
|
|
2245
2434
|
interface SchemaContents<T extends Tables, R extends SchemaRelations> {
|
|
2246
2435
|
readonly [schemaBrand]: true;
|
|
@@ -2693,8 +2882,8 @@ interface BindOptions {
|
|
|
2693
2882
|
* Its table entries start queries bound to it, which execute when awaited.
|
|
2694
2883
|
*/
|
|
2695
2884
|
type Db<T extends Tables, R extends SchemaRelations = EmptyRecord> = DbEntries<T, R> & DbMethods<T, R>;
|
|
2696
|
-
/** Bound query entry points; each access starts a query over a new table occurrence. */
|
|
2697
|
-
type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<
|
|
2885
|
+
/** Bound query entry points; each access starts a query over a new table occurrence, of the one row of a singleton table. */
|
|
2886
|
+
type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<TableQueryState<T[K], TableContext<R, K>>>; };
|
|
2698
2887
|
/** 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. */
|
|
2699
2888
|
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>;
|
|
2700
2889
|
/** State of a query that a `Db` can execute: over table `T`, selecting records only of relations `U`. */
|
|
@@ -3022,6 +3211,23 @@ interface InsertNode<Field = ProjectionNode> extends MutationParts<Field> {
|
|
|
3022
3211
|
readonly columns: readonly string[];
|
|
3023
3212
|
/** Rows of `VALUES`, at least one, each with a value of every column in their order, or `undefined` for `DEFAULT`. */
|
|
3024
3213
|
readonly values: readonly (readonly (ExpressionNode | undefined)[])[];
|
|
3214
|
+
/** `ON CONFLICT` of the insert, or `undefined` for an insert that rejects a row that conflicts on a key. */
|
|
3215
|
+
readonly conflict?: ConflictNode | undefined;
|
|
3216
|
+
}
|
|
3217
|
+
/** `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. */
|
|
3218
|
+
interface ConflictNode {
|
|
3219
|
+
/**
|
|
3220
|
+
* 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.
|
|
3221
|
+
*/
|
|
3222
|
+
readonly target: readonly string[] | "singleton";
|
|
3223
|
+
readonly update?: ConflictUpdateNode | undefined;
|
|
3224
|
+
}
|
|
3225
|
+
/** `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`. */
|
|
3226
|
+
interface ConflictUpdateNode {
|
|
3227
|
+
/** Assignments of `SET`, at least one, with unique keys. */
|
|
3228
|
+
readonly set: readonly AssignmentNode[];
|
|
3229
|
+
/** 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`. */
|
|
3230
|
+
readonly excluded: TableSourceNode;
|
|
3025
3231
|
}
|
|
3026
3232
|
/** Update statement of the rows that its filters choose. */
|
|
3027
3233
|
interface UpdateNode<Field = ProjectionNode> extends MutationParts<Field> {
|
|
@@ -3129,6 +3335,61 @@ declare const textOperators: TextOperators;
|
|
|
3129
3335
|
declare const TRUE: Expression<boolean>;
|
|
3130
3336
|
/** Condition that never holds, such as for a branch of `or` built in code: `or(check, isAdmin ? other : FALSE)`. */
|
|
3131
3337
|
declare const FALSE: Expression<boolean>;
|
|
3338
|
+
/**
|
|
3339
|
+
* Error of a statement that PostgreSQL rejected, such as for a violated constraint; the connection of the statement stays usable.
|
|
3340
|
+
*
|
|
3341
|
+
* A driver whose client gives the severity of an error only in the language of the server, such as node-postgres, tells such an error by its SQLSTATE when the server translates its messages.
|
|
3342
|
+
* An error that ends the session with a code that a statement also gets, such as `40001` of a conflict with recovery on a replica, then rejects with `QueryError`, and the next statement on the connection with `ConnectionError`.
|
|
3343
|
+
*/
|
|
3344
|
+
declare class QueryError extends Error {
|
|
3345
|
+
readonly name = "QueryError";
|
|
3346
|
+
/** SQLSTATE of the error, such as `23505` for a violated unique constraint. */
|
|
3347
|
+
readonly code: string;
|
|
3348
|
+
/** Name of the constraint that the statement violated, if any. */
|
|
3349
|
+
readonly constraint: string | undefined;
|
|
3350
|
+
constructor(message: string, fields: {
|
|
3351
|
+
code: string;
|
|
3352
|
+
constraint?: string | undefined;
|
|
3353
|
+
cause?: unknown;
|
|
3354
|
+
});
|
|
3355
|
+
/** Tells whether `value` is an instance of the class, including one of `QueryError` of another copy of kern-orm. */
|
|
3356
|
+
static [Symbol.hasInstance]<T>(this: abstract new (...args: never) => T, value: unknown): value is T;
|
|
3357
|
+
}
|
|
3358
|
+
/**
|
|
3359
|
+
* Error of a statement or connection that failed for another reason than PostgreSQL rejecting a statement, such as a lost connection, a timeout of the client, or a closed driver.
|
|
3360
|
+
*
|
|
3361
|
+
* The statement may have run or not, and its connection may be lost or in an unknown state of its transaction.
|
|
3362
|
+
*/
|
|
3363
|
+
declare class ConnectionError extends Error {
|
|
3364
|
+
readonly name = "ConnectionError";
|
|
3365
|
+
constructor(message: string, options?: {
|
|
3366
|
+
cause?: unknown;
|
|
3367
|
+
});
|
|
3368
|
+
/** Tells whether `value` is an instance of the class, including one of `ConnectionError` of another copy of kern-orm. */
|
|
3369
|
+
static [Symbol.hasInstance]<T>(this: abstract new (...args: never) => T, value: unknown): value is T;
|
|
3370
|
+
}
|
|
3371
|
+
/** Fields of the PostgreSQL error that an error of a client carries, by which `toDriverError` classifies it. */
|
|
3372
|
+
interface DriverErrorFields {
|
|
3373
|
+
/**
|
|
3374
|
+
* Severity of the error, such as `ERROR` or `FATAL`.
|
|
3375
|
+
*
|
|
3376
|
+
* Pass the severity in English when the client gives it, and the one in the language of the server otherwise.
|
|
3377
|
+
*/
|
|
3378
|
+
readonly severity?: unknown;
|
|
3379
|
+
/** SQLSTATE of the error, such as `23505`. */
|
|
3380
|
+
readonly code?: unknown;
|
|
3381
|
+
/** Name of the constraint that the statement violated. */
|
|
3382
|
+
readonly constraint?: unknown;
|
|
3383
|
+
}
|
|
3384
|
+
/**
|
|
3385
|
+
* Classifies an error of a client as `QueryError` or `ConnectionError`, by the fields of the PostgreSQL error it carries, for a driver to reject with.
|
|
3386
|
+
*
|
|
3387
|
+
* An error that kern-orm has already classified returns as it is.
|
|
3388
|
+
* An error without a severity or a SQLSTATE, such as of a client that lost its connection, is a `ConnectionError`, and so is one of severity `FATAL` or `PANIC`, which ends the session.
|
|
3389
|
+
* An error of severity `ERROR` is a `QueryError`.
|
|
3390
|
+
* With a translated severity, the SQLSTATE tells an error that ends the session, so a few errors of other codes that end it give `QueryError`.
|
|
3391
|
+
*/
|
|
3392
|
+
declare function toDriverError(error: unknown, fields?: DriverErrorFields): QueryError | ConnectionError;
|
|
3132
3393
|
/**
|
|
3133
3394
|
* Defines a reusable expression of a table, which the callbacks of queries over the table call with their columns and any further arguments, such as to filter by it and select it in one query.
|
|
3134
3395
|
*
|
|
@@ -3212,4 +3473,4 @@ declare function param<E extends AnyExpression, V extends (E extends AnyExpressi
|
|
|
3212
3473
|
* A run of capital letters is one word, such as `user_id` for `userID`, and digits stay in their word, such as `line2`.
|
|
3213
3474
|
*/
|
|
3214
3475
|
declare function toSnakeCase(key: string): string;
|
|
3215
|
-
export {
|
|
3476
|
+
export { TransformedQuery as $, Column as $i, QueryContext as $n, Operand as $r, CaseValue as $t, TypedExpression as A, defineTable as Ai, StringAggOptions as An, CombinedCondition as Ar, SelectionState as At, TransactionOptions as B, TransactionFailure as Bi, stringAgg as Bn, OneValueRows as Br, ConflictActionRequired as Bt, textOperators as C, Selectable as Ci, Literal as Cn, PrimaryKeyColumn as Cr, SchemaPartRelations as Ct, BaseOperators as D, TableOptions as Di, CountExpression as Dn, WhereCondition as Dr, AnyRecordQuery as Dt, AnyExpression as E, TableKeys as Ei, AggregateOptions as En, WhereCallback as Er, defineSchema as Et, DbMutationState as F, ResultRows as Fi, countDistinct as Fn, not as Fr, FieldTypes as Ft, TestFixture as G, Type as Gi, OrderTerm as Gn, CompileOptions as Gr, InsertMutationState as Gt, TransactionCoordinator as H, AnyType as Hi, OrderColumns as Hn, ResultByRows as Hr, ConflictTarget as Ht, DbOf as I, Connection as Ii, every as In, or as Ir, InitialSqlQueryState as It, TestTransactionOptions as J, TypeOptions as Ji, SelectedRefs as Jn, HasEquality as Jr, Helper as Jt, TestHelpers as K, TypeInput as Ki, OrderTerms as Kn, EqualityOperator as Kr, MutationQuery as Kt, DbQueryState as L, Driver as Li, max as Ln, ExistsValueType as Lr, SqlQuery as Lt, AnyDb as M, RequiredRelationError as Mi, UnfilteredStringAggOptions as Mn, ConditionOperand as Mr, SelectQueryKind as Mt, BindOptions as N, ResultDecodeError as Ni, avg as Nn, Predicate as Nr, AnySqlQuery as Nt, Expression as O, ToColumns as Oi, GroupAggregateExpression as On, WhereFilter as Or, RecordQuery as Ot, Db as P, ResultMode as Pi, count as Pn, and as Pr, DecodedFields as Pt, SynchronousResult as Q, AnyColumn as Qi, ColumnRefs as Qn, ComparisonSignature as Qr, CaseCondition as Qt, Database as R, DriverResult as Ri, min as Rn, FilteredRows as Rr, SqlQueryState as Rt, TextTypeOperators as S, KeyColumns as Si, SelectionUses as Sn, NotAKey as Sr, SchemaPart as St, orderingOperators as T, TableFactoryOptions as Ti, AggregateExpression as Tn, EqValue as Tr, Tables as Tt, OpenedTestFixture as U, BaseType as Ui, OrderDirection as Un, ValueRows as Ur, InitialInsertState as Ut, createDatabase as V, createStatement as Vi, sum as Vn, QueryResult as Vr, ConflictKeyRequired as Vt, PendingTestFixture as W, TextValue as Wi, OrderKey as Wn, CountValueType as Wr, InitialMutationState as Wt, AnyTransformedQuery as X, TypeTransform as Xi, desc as Xn, equalityOperators as Xr, defineHelper as Xt, createTestHelpers as Y, TypeOutput as Yi, asc as Yn, InSignature as Yr, HelperEffect as Yt, NotSynchronous as Z, defineType as Zi, orderBy as Zn, BooleanResult as Zr, CaseBranch as Zt, TRUE as _, AnyTableKeys as _i, NestedQuery as _n, SelectedOperandType as _r, UsedRelation as _t, sql as a, NoOperators as aa, ValuesQuery as ai, caseWhen as an, SingletonInsertMany as ar, Relation as at, TextLengthSignature as b, ColumnShape as bi, SelectionFieldTypes as bn, GroupTerms as br, AnySchema as bt, MatchResult as c, GenericOperatorImplementation as ca, Grouped as ci, least as cn, ConflictUpdateSet as cr, RelationKey as ct, defineExpression as d, QueryStateOf as di, ExpressionValue as dn, UpdateValues as dr, RequiredMember as dt, ColumnAttributes as ea, OperandValue as ei, FollowingOperand as en, RelationRefs as er, TransformedQueryState as et, ConnectionError as f, QueryValueType as fi, GroupOperandValue as fn, UpsertValues as fr, SchemaContext as ft, FALSE as g, AnyTable as gi, MergeSelection as gn, GroupedState as gr, UsableRelation as gt, toDriverError as h, TableQueryState as hi, GroupedRecord as hn, FoundState as hr, TableRelations as ht, param as i, MergeOperators as ia, TypedScalarQuery as ii, TypedOperandOperators as in, SelectQuery as ir, OneRelationKeys as it, UntypedExpression as j, NotFoundError as ji, UnfilteredAggregateOptions as jn, Condition as jr, AnyQuery as jt, ExpressionOperators as k, createTableFactory as ki, GroupValue as kn, WhereValues as kr, RecordQueryState as kt, NotAColumn as l, OperatorSignature as la, InitialQueryState as li, ColumnFieldTypes as ln, InsertValues as lr, RelationKeys as lt, QueryError as m, SingletonQueryState as mi, GroupedField as mn, FoundQueryState as mr, TableContext as mt, SqlTemplate as n, ToColumn as na, OperandUses as ni, TypedOperand as nn, BoundSelectQuery as nr, MergeRelations as nt, ColumnRefKey as o, OperatorDefinitions as oa, EmptyRecord as oi, coalesce as on, from as or, RelationDeclaration as ot, DriverErrorFields as p, SelectQueryState as pi, GroupSelectionResult as pn, FilteredStateRows as pr, SchemaRelations as pt, TestHooks as q, TypeOperators as qi, Ordering as qn, EqualityOperators as qr, MutationQueryState as qt, identifier as r, BoundOperators as ra, ScalarQuery as ri, TypedOperandInput as rn, ResultOf as rr, NoRelations as rt, MatchCheck as s, GenericOperator as sa, FoundKey as si, greatest as sn, ColumnValue as sr, RelationDeclarations as st, toSnakeCase as t, KeyKind as ta, compare as ti, NullSkippingResult as tn, AnySelectQuery as tr, DeclaredRelations as tt, matches as u, defineGenericOperator as ua, QueryState as ui, ExpressionInput as un, UpdateSet as ur, RelationKind as ut, PatternSignature as v, ColumnDefinitions as vi, SelectedFieldTypes as vn, RowLockOptions as vr, many as vt, NumberTypeOperators as w, Table as wi, literal as wn, PrimaryKeyValues as wr, SchemaTables as wt, TextOperators as x, ColumnValues as xi, SelectionResult as xn, KeyCheck as xr, Schema as xt, TextConversionSignature as y, ColumnOperators as yi, Selection as yn, GroupTerm as yr, one as yt, DatabaseOptions as z, SqlStatement as zi, some as zn, OneRow as zr, AnyMutationQuery as zt };
|