kern-orm 0.9.0 → 0.10.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.
@@ -1,3 +1,5 @@
1
+ import { ResultMode, ResultMode as ResultMode$1, SqlQuery } from "kern-db/builder";
2
+ import { AcceptedNull, AcceptedValues, AnySqlQuery, AnySqlQuery as AnySqlQuery$1, BaseDerivableType, Connection, ConnectionError, Database, Database as Database$1, DatabaseOptions, DecodedFields, DerivableType, DerivableType as DerivableType$1, DerivableTypeWithParameters, Driver, DriverErrorFields, DriverResult, FieldTypes, InitialSqlQueryState, InitialSqlQueryState as InitialSqlQueryState$1, IsolationLevel, NotFoundError as NotFoundError$1, OneRow, OneRow as OneRow$1, OneValueRows, OneValueRows as OneValueRows$1, PollLockOptions, PollLockOptions as PollLockOptions$1, QueryError, QueryErrorCode, QueryErrorCondition, ResultByRows, ResultByRows as ResultByRows$1, ResultDecodeError as ResultDecodeError$1, ResultRows, ResultRows as ResultRows$1, SessionOptions, SessionOptions as SessionOptions$1, SqlFragment as SqlFragment$1, SqlFragment as SqlFragment$2, SqlQuery as SqlQuery$1, SqlQueryResult, SqlQueryState, SqlStatement, SqlStatement as SqlStatement$1, SqlValue, TextValue, TransactionConnectionError, TransactionOptions, TransactionOptions as TransactionOptions$1, TypeOptions, TypeOptions as TypeOptions$1, TypeTransform, TypeTransform as TypeTransform$1, ValueRows, ValueRows as ValueRows$1, createDatabase, createStatement as createStatement$1, isQueryError, toDriverError, typeValues } from "kern-db";
1
3
  declare const operatorSignature: unique symbol;
2
4
  /** Runtime mark of generic operators. */
3
5
  declare const genericOperatorBrand: unique symbol;
@@ -96,13 +98,12 @@ declare class Column<T extends AnyType, Key extends KeyKind | undefined = KeyKin
96
98
  type AnyColumn = Column<any>;
97
99
  /** Column of a column definition: the column itself, or a column of a type without attributes. */
98
100
  type ToColumn<D extends AnyType | AnyColumn> = D extends AnyColumn ? D : D extends AnyType ? Column<D, undefined, false> : never;
99
- declare const typeValues: unique symbol;
100
- /** Runtime mark of types, which tells them apart from columns and other objects. */
101
+ /** Runtime mark of types, which tells them apart from columns, types of kern-db without operators, and other objects. */
101
102
  declare const typeBrand: unique symbol;
102
103
  /**
103
104
  * SQL type: a PostgreSQL type, the JavaScript representation of its values, and the operators of its expressions.
104
105
  *
105
- * A type is shared by columns, parameters, and SQL expressions, so the same value is encoded and decoded identically everywhere.
106
+ * A type is a type of kern-db, shared by columns, parameters, and SQL expressions, so the same value is encoded and decoded identically everywhere.
106
107
  * In a table, a type is a column; `columnName`, `primaryKey`, `unique`, and `hasDefault` create a column of the type with these attributes.
107
108
  * A type with PostgreSQL type parameters, such as the length of `varchar(255)`, has `with`.
108
109
  */
@@ -114,7 +115,6 @@ interface BaseType<Output, Input, Operators extends OperatorDefinitions, Paramet
114
115
  readonly [typeValues]: {
115
116
  output: Output;
116
117
  input: Input;
117
- operators: Operators;
118
118
  };
119
119
  /** SQL type name used in DDL, such as `numeric` or `vector(1536)`. */
120
120
  readonly sqlType: string;
@@ -124,13 +124,13 @@ interface BaseType<Output, Input, Operators extends OperatorDefinitions, Paramet
124
124
  * It omits type parameters, so that their precision, scale, or length do not constrain a parameter.
125
125
  */
126
126
  readonly castType: string;
127
+ readonly isNullable: boolean;
128
+ /** Converts a non-null value to its PostgreSQL text representation; it does not read `this`. */
129
+ readonly encode: (value: NonNullable<Input>) => string;
130
+ /** Converts a non-null PostgreSQL text representation to a value; it does not read `this`. */
131
+ readonly decode: (text: string) => Exclude<Output, null>;
127
132
  /** Operators of expressions of this type, in addition to `isNull` or replacing it. */
128
133
  readonly operators: Operators;
129
- readonly isNullable: boolean;
130
- /** Converts a non-null value to its PostgreSQL text representation. */
131
- encode(value: NonNullable<Input>): string;
132
- /** Converts a non-null PostgreSQL text representation to a value. */
133
- decode(text: string): Exclude<Output, null>;
134
134
  /**
135
135
  * Creates a type whose expressions also have `operators`.
136
136
  *
@@ -178,112 +178,33 @@ interface TypeWithParameters<Output, Input, Operators extends OperatorDefinition
178
178
  /** Creates this type with PostgreSQL type parameters, such as `varchar.with(255)` for `varchar(255)`; other changes of the type are kept. */
179
179
  with(...parameters: Parameters): Type<Output, Input, Operators, Parameters>;
180
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
- }
193
- /** Conversion between the values of a type and their new representation. */
194
- interface TypeTransform<Output, Input, NewOutput, NewInput> {
195
- decode: (value: Output) => NewOutput;
196
- encode: (value: NewInput) => Input;
197
- }
198
181
  /** Type of any values, operators, and parameters. */
199
182
  type AnyType = Type<any, any, any, any>;
200
- /** PostgreSQL text representation of a value, as types encode and decode it; `null` is SQL `NULL`. */
201
- type TextValue = string | null;
202
183
  /** Values that a type decodes. */
203
184
  type TypeOutput<T extends AnyType> = T[typeof typeValues]["output"];
204
185
  /** Values that a type encodes. */
205
186
  type TypeInput<T extends AnyType> = T[typeof typeValues]["input"];
206
187
  /** Operators of the expressions of a type. */
207
- type TypeOperators<T extends AnyType> = T[typeof typeValues]["operators"];
208
- /** Type definition. */
209
- interface TypeOptions {
210
- /** SQL type name, such as `ltree`; `withParameters` adds type parameters to it, and a name with them requires `castType`. */
211
- sqlType: string;
212
- /** SQL type name that `param` casts parameters to when `sqlType` constrains values, such as `bpchar` for `char`, whose length is 1. */
213
- castType?: string;
214
- }
188
+ type TypeOperators<T extends AnyType> = T["operators"];
189
+ /** Defines a type from `type`, keeping its values and PostgreSQL type parameters, without its operators. */
190
+ declare function defineType$1<Output, Input, Parameters extends unknown[] | undefined>(type: Type<Output, Input, any, Parameters>): Type<Output, Input, NoOperators, Parameters>;
215
191
  /**
216
- * Defines a type whose values are the PostgreSQL text representations as they are.
192
+ * Defines a type from `dbType`, a type of kern-db, such as one defined without kern-orm, keeping its values and PostgreSQL type parameters.
217
193
  *
218
- * `transform` converts them to other values, such as `number[]` for `vector`.
194
+ * Its expressions have only `isNull` until `withOperators` adds operators.
219
195
  */
220
- declare function defineType(options: TypeOptions): Type<string>;
221
- /** SQL statement ready for a driver. */
222
- interface SqlStatement {
223
- readonly text: string;
224
- /** Text representations of the parameters; PostgreSQL infers their types from the statement text. */
225
- readonly parameters: readonly TextValue[];
226
- }
227
- /** Creates a statement from SQL text and the text representations of its parameters, such as `createStatement("BEGIN")`. */
228
- declare function createStatement(text: string, parameters?: readonly TextValue[]): SqlStatement;
229
- /** Result of a statement. */
230
- interface DriverResult {
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. */
234
- readonly count: number;
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`. */
236
- readonly columns: readonly string[];
237
- /** Rows as PostgreSQL text representations of their values, in the order of the result columns. */
238
- readonly rows: readonly (readonly TextValue[])[];
239
- }
196
+ declare function defineType$1<Output, Input, Parameters extends unknown[] | undefined>(dbType: DerivableType<Output, Input, Parameters>): Type<Output, Input, NoOperators, Parameters>;
240
197
  /**
241
- * Physical database access: transport, pooling, and connections.
198
+ * Defines a type whose values are the PostgreSQL text representations as they are.
242
199
  *
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.
200
+ * `transform` converts them to other values, such as `number[]` for `vector`.
245
201
  */
246
- interface Driver {
247
- /**
248
- * Executes a statement on any pooled connection.
249
- *
250
- * It rejects a statement that leaves its connection in a transaction, such as `BEGIN`, with `ConnectionError`, and leaves no transaction open on the pool.
251
- */
252
- execute(statement: SqlStatement): Promise<DriverResult>;
253
- /**
254
- * 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.
255
- *
256
- * It rejects a script that leaves its connection in a transaction as `execute` rejects such a statement.
257
- * A script whose statement PostgreSQL rejected in that transaction may reject with that `QueryError` instead.
258
- * Either way, no transaction stays open on the pool.
259
- */
260
- executeScript(text: string): Promise<void>;
261
- /** Reserves a dedicated connection, such as for a transaction. */
262
- acquire(): Promise<Connection>;
263
- /**
264
- * Closes the connections once the statements on the pool and the transactions on reserved connections end.
265
- *
266
- * From the call, it rejects a new statement or script on the pool and a new connection with `ConnectionError`.
267
- */
268
- close(): Promise<void>;
269
- }
270
- /** Connection reserved by a driver, such as for a transaction. */
271
- interface Connection {
272
- /**
273
- * Executes a statement on the connection.
274
- *
275
- * Statements and scripts run one at a time in the order of calls, so a statement sent before `COMMIT` or `ROLLBACK` completes before it.
276
- */
277
- execute(statement: SqlStatement): Promise<DriverResult>;
278
- /** Executes a script of statements without parameters on the connection, in the order of calls with its statements. */
279
- executeScript(text: string): Promise<void>;
280
- /**
281
- * Returns the connection to the pool once its statements complete, if PostgreSQL reported an idle transaction status after the last statement; otherwise the driver closes it, which rolls back a transaction left on it.
282
- *
283
- * The driver tells by itself how the statements on the connection ended.
284
- * After a `ConnectionError`, a statement may still run or the connection may be lost, so the driver closes the connection, unless its client refused the statement without breaking the exchange of messages and still reads the status, such as postgres.js 4 for a statement of too many parameters.
285
- */
286
- release(): void | Promise<void>;
202
+ declare function defineType$1(options: TypeOptions & {
203
+ readonly [typeValues]?: NotADerivableType;
204
+ }): Type<string>;
205
+ /** Type that the options of `defineType` are checked against when they are a type of kern-db typed without the methods that derive types, naming the reason. */
206
+ interface NotADerivableType {
207
+ readonly "defineType takes a type of kern-db typed as a DerivableType, as defineType of kern-db creates it": never;
287
208
  }
288
209
  /** Field of a compiled result: the key of a record and how its value is decoded. */
289
210
  type ResultField = ScalarField | NestedField;
@@ -315,19 +236,6 @@ interface ResultConversion {
315
236
  /** Converts the whole result, once: an array of rows, one row, or `null` or `undefined` of a missing row. */
316
237
  readonly transform: ((result: unknown) => unknown) | undefined;
317
238
  }
318
- /**
319
- * 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.
320
- *
321
- * Without a row, a query of rows `one` rejects with `NotFoundError`, executed or nested, or with `RequiredRelationError` when a required relation guarantees the row.
322
- * This mode does not imply a SQL limit: `take` and `get` add `LIMIT 1` only when they change `many` to `one`.
323
- */
324
- type ResultRows = "many" | "one" | "nullable" | "optional";
325
- /** How the rows of a query become its result, apart from its fields. */
326
- interface ResultMode {
327
- readonly rows: ResultRows;
328
- /** A row is the value of its only field instead of a record. */
329
- readonly value: boolean;
330
- }
331
239
  /** Fields of the rows of a query and how its rows become its result. */
332
240
  interface ResultPlan extends ResultMode {
333
241
  /** Fields of a row, in the order of its values. */
@@ -343,13 +251,6 @@ interface ResultPlan extends ResultMode {
343
251
  /** How code converts the result that the plan decodes; `undefined` for a query without `transform` and `map`. */
344
252
  readonly conversion?: ResultConversion | undefined;
345
253
  }
346
- /** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
347
- declare class NotFoundError extends Error {
348
- readonly name = "NotFoundError";
349
- /** Path of the missing nested rows from the result field that holds them, such as `user` or `fields[2].form`, after the index of the row of an executed query of rows `many`, such as `[2].form`; `undefined` when the executed query itself finds no row. */
350
- readonly path: string | undefined;
351
- constructor(message: string, path?: string);
352
- }
353
254
  /**
354
255
  * Error thrown when a required relation, such as `field.form`, has no record for a row.
355
256
  *
@@ -367,25 +268,6 @@ declare class RequiredRelationError extends Error {
367
268
  /** 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`. */
368
269
  path: string);
369
270
  }
370
- /** 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. */
371
- declare class ResultDecodeError extends Error {
372
- /**
373
- * 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`.
374
- *
375
- * 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`.
376
- * 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.
377
- */
378
- readonly path: string | undefined;
379
- readonly name = "ResultDecodeError";
380
- constructor(message: string,
381
- /**
382
- * 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`.
383
- *
384
- * 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`.
385
- * 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.
386
- */
387
- path: string | undefined, options?: ErrorOptions);
388
- }
389
271
  /** Tells whether `T` is `any`: only `any` turns `1 & T` into a type that `0` extends. */
390
272
  type IsAny<T> = 0 extends 1 & T ? true : false;
391
273
  /** Flattens an intersection of object types into one object type, so that editors show its fields; `any` stays `any`. */
@@ -800,20 +682,12 @@ interface CountValueType extends QueryValueType {
800
682
  type RelationRows<Kind extends RelationKind, Required extends boolean> = Kind extends "many" ? "many" : Required extends true ? "one" : "nullable";
801
683
  /** 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. */
802
684
  type FilteredRows<Rows extends ResultRows, Value> = Rows extends "one" ? Value extends true ? "optional" : "nullable" : Rows;
803
- /** Rows mode after `take`: `many` becomes `one`; the modes of one row stay. */
804
- type OneRow<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows;
805
- /** Rows mode after `pluck`: `nullable` becomes `optional`; the other modes stay. */
806
- type ValueRows<Rows extends ResultRows> = Rows extends "nullable" ? "optional" : Rows;
807
- /** Rows mode after `get`: `many` becomes `one` and `nullable` becomes `optional`; `one` and `optional` stay. */
808
- type OneValueRows<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows extends "nullable" ? "optional" : Rows;
809
685
  /**
810
686
  * Result of a query of state `S`, executed or nested: an array of records or values, or one of them, `null` or `undefined` when a query of rows `nullable` or `optional` finds no row.
811
687
  *
812
688
  * It is the union of the results of every state that `S` allows, such as of a union of rows modes.
813
689
  */
814
690
  type QueryResult<S extends QueryState> = S extends QueryState ? ResultByRows<S["result"], S["rows"]> : never;
815
- /** Result of rows of `Result` returned in rows mode `Rows`; a union of modes gives the union of their results. */
816
- type ResultByRows<Result, Rows extends ResultRows> = Rows extends "many" ? Result[] : Rows extends "one" ? Result : Rows extends "nullable" ? Result | null : Result | undefined;
817
691
  /** Type of the value of a query of `exists`. */
818
692
  interface ExistsValueType extends QueryValueType {
819
693
  readonly input: boolean;
@@ -1594,8 +1468,8 @@ interface SingletonInsertMany {
1594
1468
  type BoundSelectQuery<S extends SelectQueryState> = SelectQuery<S, "bound">;
1595
1469
  /** Select query of any state and kind. */
1596
1470
  type AnySelectQuery = SelectQuery<any, SelectQueryKind>;
1597
- /** Type of a record of a query result, or of its value for a query made by `get`, `pluck`, or an aggregate method. */
1598
- type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
1471
+ /** Type of a record of a query result, also of a query of SQL text, or of its value for a query made by `get`, `pluck`, or an aggregate method. */
1472
+ type ResultOf<Q extends AnyQuery | AnySqlQuery> = Q["types"]["result"];
1599
1473
  /** Table of a definition such as `defineExpression`: the table itself or a query over it with schema context `C`, such as `schema.form`. */
1600
1474
  type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
1601
1475
  /** Starts a query over a new occurrence of the table. */
@@ -2042,17 +1916,17 @@ type HelperMutationState<S extends MutationQueryState, E extends HelperEffect> =
2042
1916
  uses: S["uses"] | E["uses"];
2043
1917
  }> : RecordsState<S, E["fields"], E["uses"]>;
2044
1918
  /** Record that the returned fields of a mutation of state `S` add to: the fields selected earlier, or none. */
2045
- type ReturnedRecord$1<S extends MutationQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
1919
+ type ReturnedRecord<S extends MutationQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
2046
1920
  /** State of a mutation of state `S` that returns records with `Fields`, which its nested queries select records of relations `U` for. */
2047
1921
  type RecordsState<S extends MutationQueryState, Fields, U extends UsedRelation = never> = ChangeMutationState<S, {
2048
- result: MergeSelection<ReturnedRecord$1<S>, Fields>;
1922
+ result: MergeSelection<ReturnedRecord<S>, Fields>;
2049
1923
  rows: S["changed"];
2050
1924
  value: false;
2051
1925
  returning: true;
2052
1926
  uses: S["uses"] | U;
2053
1927
  }>;
2054
1928
  /** State of a mutation of state `S` that returns value `V` of each row it changes in rows mode `Rows`. */
2055
- type ValueState$1<S extends MutationQueryState, V, Rows extends ResultRows> = ChangeMutationState<S, {
1929
+ type ValueState<S extends MutationQueryState, V, Rows extends ResultRows> = ChangeMutationState<S, {
2056
1930
  result: V;
2057
1931
  rows: Rows;
2058
1932
  value: true;
@@ -2102,7 +1976,7 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
2102
1976
  *
2103
1977
  * A query of a nullable row resolves to `undefined` without the row.
2104
1978
  */
2105
- get<S extends OneRowMutationState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: MutationQuery<S, Kind>, key: K): MutationQuery<ValueState$1<S, Selectable<S["table"]>[K], OneValueRows<S["changed"]>>, Kind>;
1979
+ get<S extends OneRowMutationState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: MutationQuery<S, Kind>, key: K): MutationQuery<ValueState<S, Selectable<S["table"]>[K], OneValueRows<S["changed"]>>, Kind>;
2106
1980
  /**
2107
1981
  * Returns the value of the expression that `callback` returns for the changed row instead of the number of the rows, in a query that changes one row, such as of `insert` or `find`.
2108
1982
  *
@@ -2111,7 +1985,7 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
2111
1985
  */
2112
1986
  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>;
2113
1987
  /** 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. */
2114
- 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>;
1988
+ pluck<S extends UnconvertedMutationState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: MutationQuery<S, Kind>, key: K): MutationQuery<ValueState<S, Selectable<S["table"]>[K], ValueRows<S["changed"]>>, Kind>;
2115
1989
  /**
2116
1990
  * 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.
2117
1991
  *
@@ -2244,134 +2118,6 @@ type ConflictKeyCheck<S extends InsertMutationState, K extends string> = [K] ext
2244
2118
  interface ConflictKeyRequired {
2245
2119
  readonly "merge and update need the columns of a key in onConflict": never;
2246
2120
  }
2247
- /** Types of the fields of the rows of a query of SQL text by the names of the result columns they decode. */
2248
- interface FieldTypes {
2249
- readonly [key: string]: AnyType;
2250
- readonly [key: symbol]: never;
2251
- }
2252
- /** Record of the values that the types of fields `F` decode. */
2253
- type DecodedFields<F extends FieldTypes> = { -readonly [K in keyof F]: TypeOutput<F[K]>; };
2254
- /**
2255
- * 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.
2256
- *
2257
- * Methods change only their own parts of the state.
2258
- */
2259
- interface SqlQueryState extends QueryState {
2260
- /** Rows mode of the rows of the statement, which `select`, `get`, and `pluck` return. */
2261
- readonly returned: ResultRows;
2262
- /** Whether the query returns the fields of the rows of the statement rather than their number. */
2263
- readonly returning: boolean;
2264
- }
2265
- /** State of a query of SQL text that returns the number of the rows of its command tag. */
2266
- interface InitialSqlQueryState extends SqlQueryState {
2267
- readonly result: number;
2268
- readonly rows: "one";
2269
- readonly value: true;
2270
- readonly uses: never;
2271
- readonly returned: "many";
2272
- readonly returning: false;
2273
- }
2274
- /** State `S` of a query of SQL text with the parts of `Changes` replaced. */
2275
- type ChangeSqlQueryState<S extends SqlQueryState, Changes extends Partial<SqlQueryState>> = { readonly [K in keyof SqlQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
2276
- /** State of a query of SQL text that returns the number of the rows or their records, which `select` applies to. */
2277
- type RecordSqlQueryState = SqlQueryState & ({
2278
- readonly returning: false;
2279
- } | {
2280
- readonly value: false;
2281
- });
2282
- /** State of a query of SQL text of one row, which `optional` applies to. */
2283
- type OneRowSqlQueryState = SqlQueryState & {
2284
- readonly returned: "one" | "nullable" | "optional";
2285
- };
2286
- /** State of a query of SQL text of one row that returns its number or its record, which `nullable` applies to. */
2287
- type OneRecordSqlQueryState = OneRowSqlQueryState & RecordSqlQueryState;
2288
- /** Record that the fields of a query of SQL text of state `S` add to: the fields selected earlier, or none. */
2289
- type ReturnedRecord<S extends SqlQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
2290
- /** State of a query of SQL text of state `S` whose rows are in rows mode `Rows`. */
2291
- type RowsState<S extends SqlQueryState, Rows extends ResultRows> = ChangeSqlQueryState<S, {
2292
- returned: Rows;
2293
- rows: S["returning"] extends true ? Rows : "one";
2294
- }>;
2295
- /** State of a query of SQL text of state `S` that returns value `V` of each row in rows mode `Rows`. */
2296
- type ValueState<S extends SqlQueryState, V, Rows extends ResultRows> = ChangeSqlQueryState<S, {
2297
- result: V;
2298
- rows: Rows;
2299
- returned: Rows;
2300
- value: true;
2301
- returning: true;
2302
- }>;
2303
- /**
2304
- * Immutable query of a statement of SQL text, bound to the `Db` that executes it when awaited.
2305
- *
2306
- * 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.
2307
- */
2308
- declare class SqlQuery<out S extends SqlQueryState> {
2309
- readonly node: TextStatementNode;
2310
- /** `Db` that executes the query when it is awaited. */
2311
- readonly db: AnyDb;
2312
- readonly types: S;
2313
- /** Executes the query on its `Db`. */
2314
- readonly then: QueryThen<S, "bound">;
2315
- constructor(node: TextStatementNode,
2316
- /** `Db` that executes the query when it is awaited. */
2317
- db: AnyDb);
2318
- /**
2319
- * 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.
2320
- *
2321
- * A type of a column that can be `NULL` must be nullable.
2322
- * The statement rejects without a column of a field, or with the column twice; other columns are ignored.
2323
- */
2324
- select<S extends RecordSqlQueryState, F extends FieldTypes>(this: SqlQuery<S>, fields: F): SqlQuery<ChangeSqlQueryState<S, {
2325
- result: MergeSelection<ReturnedRecord<S>, DecodedFields<F>>;
2326
- rows: S["returned"];
2327
- value: false;
2328
- returning: true;
2329
- }>>;
2330
- /**
2331
- * Returns the value of the only column of the row of the statement instead of the number of the rows, decoded by `type`.
2332
- *
2333
- * Without a row, it rejects with `NotFoundError` unless `optional` makes the query resolve to `undefined`; it rejects several rows.
2334
- * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
2335
- */
2336
- get<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, OneValueRows<S["returned"]>>>;
2337
- /**
2338
- * 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.
2339
- *
2340
- * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
2341
- */
2342
- pluck<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, ValueRows<S["returned"]>>>;
2343
- /**
2344
- * 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.
2345
- *
2346
- * Before a selection, the query resolves to the number of the rows, `1`, and rejects as well.
2347
- */
2348
- take<S extends SqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, OneRow<S["returned"]>>>;
2349
- /**
2350
- * Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without the row.
2351
- *
2352
- * Before a selection, the query resolves to `0` without the row.
2353
- */
2354
- optional<S extends OneRowSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "optional">>;
2355
- /**
2356
- * Makes a query of one record, such as one of `take`, resolve to `null` without the row.
2357
- *
2358
- * 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.
2359
- * Before a selection, the query resolves to `0` without the row.
2360
- */
2361
- nullable<S extends OneRecordSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "nullable">>;
2362
- /** Compiles the query into SQL text and parameters, as its `Db` executes it. */
2363
- toSQL(): SqlStatement;
2364
- /** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
2365
- [operandNode](): never;
2366
- /** Creates a query of the same `Db` with the node changes applied. */
2367
- private derive;
2368
- /** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
2369
- private deriveValue;
2370
- /** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
2371
- private changeOneRow;
2372
- }
2373
- /** Query of SQL text of any state. */
2374
- type AnySqlQuery = SqlQuery<any>;
2375
2121
  /** Kind of a select query: `unbound`, or `bound` to a `Db`. */
2376
2122
  type SelectQueryKind = "unbound" | "bound";
2377
2123
  /**
@@ -2384,8 +2130,8 @@ type QueryThen<S extends QueryState, Kind extends SelectQueryKind> = [Kind] exte
2384
2130
  type QueryDb<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? AnyDb : [Kind] extends ["unbound"] ? undefined : AnyDb | undefined;
2385
2131
  /** Arguments of `toSQL` of a query of kind `Kind`: a bound query compiles with the options of its `Db`. */
2386
2132
  type ToSQLArgs<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? [] : [options?: CompileOptions];
2387
- /** 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. */
2388
- type AnyQuery = AnySelectQuery | AnyTransformedQuery | AnyRecordQuery | AnyMutationQuery | AnySqlQuery;
2133
+ /** Query of any class, state, and kind: a select query of a table, one converted by `transform`, a query of `$select`, or one that inserts, updates, or deletes rows. */
2134
+ type AnyQuery = AnySelectQuery | AnyTransformedQuery | AnyRecordQuery | AnyMutationQuery;
2389
2135
  /** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
2390
2136
  interface RecordQueryState<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
2391
2137
  readonly result: R;
@@ -2674,250 +2420,21 @@ declare class TransformedQuery<out S extends TransformedQueryState, out Kind ext
2674
2420
  }
2675
2421
  /** Query of `transform` of a table of any state and kind. */
2676
2422
  type AnyTransformedQuery = TransformedQuery<any, SelectQueryKind>;
2677
- /** Test fixture of `useTestFixture`, open while the tests of its `describe` block or test file run. */
2678
- interface TestFixture<T = unknown> {
2679
- /** Result of the seed of the fixture; reading it while the fixture is not open throws. */
2680
- readonly data: T;
2681
- }
2682
- /** Test fixture opened by the transaction coordinator: an outer transaction of a database created for tests, which always rolls back when it closes. */
2683
- interface OpenedTestFixture<T = unknown> extends AsyncDisposable {
2684
- /** Result of the seed of the fixture, such as the records it created; reading it after the fixture closes throws. */
2685
- readonly data: T;
2686
- /** Rolls back the fixture and the fixtures opened inside it; closing a closed fixture does nothing. */
2687
- close(): Promise<void>;
2688
- }
2689
- /** Test fixture that is being opened, with a `close` that can be called before it opens. */
2690
- interface PendingTestFixture<T = unknown> {
2691
- readonly fixture: Promise<OpenedTestFixture<T>>;
2692
- close(): Promise<void>;
2693
- }
2694
- /**
2695
- * Hooks of a test runner that run a function before and after the tests of the current `describe` block or test file.
2696
- *
2697
- * They are `before` and `after` of `node:test`, and `beforeAll` and `afterAll` of `bun:test` and Vitest.
2698
- */
2699
- interface TestHooks {
2700
- before(hook: () => Promise<void>): unknown;
2701
- after(hook: () => Promise<void>): unknown;
2702
- }
2703
- /** Options of `testTransaction`. */
2704
- interface TestTransactionOptions {
2705
- /**
2706
- * Abort signal of the test, such as `t.signal` of `node:test` or `signal` of the test context of Vitest.
2707
- *
2708
- * When it aborts, the test transaction rejects the later queries of the test at once and rolls back without waiting for the test.
2709
- * It then rejects with the reason of the signal.
2710
- * If starting or rolling back the transaction fails, it rejects instead with a `SuppressedError` that keeps the reason.
2711
- * Queries that the test has already sent complete before the rollback.
2712
- */
2713
- signal?: AbortSignal;
2714
- /**
2715
- * Isolation level of the test transaction, such as `serializable`, for code under test that starts a transaction at that level.
2716
- *
2717
- * Inside a test fixture, the test transaction runs at the level of the fixture: given another level, it rejects.
2718
- */
2719
- isolation?: IsolationLevel;
2720
- }
2721
- /** Options of `useTestFixture`. */
2722
- interface TestFixtureOptions {
2723
- /**
2724
- * Isolation level of the transaction of the fixture, such as `serializable`, at which the test transactions and fixtures nested in it run.
2725
- *
2726
- * A fixture nested in another one runs at the level of that fixture: given another level, it rejects.
2727
- */
2728
- isolation?: IsolationLevel;
2729
- }
2730
- /** Test transactions and test fixtures of a database created with `test: true`. */
2731
- interface TestHelpers {
2732
- /**
2733
- * Runs `callback` in a transaction that always rolls back.
2734
- *
2735
- * Wrap the body of every test in it, so that every run of the test gets its own transaction.
2736
- * Inside an existing transaction, it starts a nested transaction that always rolls back.
2737
- */
2738
- testTransaction<T>(callback: () => Promise<T>, options?: TestTransactionOptions): Promise<T>;
2739
- /**
2740
- * Opens a test fixture for the tests of the current `describe` block or test file and runs `seed` in it, such as migrations or data shared by the tests.
2741
- *
2742
- * The fixture opens in the `before` hook and rolls back in the `after` hook.
2743
- * The changes of `seed` stay for the test transactions that run while the fixture is open, and its result is the `data` of the fixture.
2744
- * Test fixtures nest: a new one opens inside the innermost open one, and test transactions run in the innermost one.
2745
- * A fixture whose `seed` rejects rolls back and closes.
2746
- */
2747
- useTestFixture<T>(seed: () => Promise<T>, options?: TestFixtureOptions): TestFixture<T>;
2748
- }
2749
- /** Creates the test helpers of a database created with `test: true`, registering fixtures with the hooks of a test runner. */
2750
- declare function createTestHelpers(database: Database, hooks: TestHooks): TestHelpers;
2751
- /**
2752
- * Routes statements and scripts to the ambient transaction of the current async context or to the pool.
2753
- *
2754
- * This is the only place that decides which connection executes a statement.
2755
- */
2756
- declare class TransactionCoordinator {
2757
- #private;
2758
- readonly driver: Driver;
2759
- /** Rejects statements and transactions outside a test transaction or the seed of a test fixture instead of running them on the pool. */
2760
- readonly test: boolean;
2761
- constructor(driver: Driver, { test, onReleaseError }?: Omit<DatabaseOptions, "driver">);
2762
- execute(statement: SqlStatement): Promise<DriverResult>;
2763
- /** Executes a script of statements without parameters where `execute` executes a statement. */
2764
- executeScript(text: string): Promise<void>;
2765
- /**
2766
- * Runs `callback` in a transaction that commits when it resolves and rolls back when it rejects, with the settings of `options`.
2767
- *
2768
- * Inside a transaction, it runs `callback` in a savepoint nested in it, which restores the settings it changed when it ends, and rejects without the savepoint when the isolation level of `options` differs from that of the transaction.
2769
- * A failed cleanup after an error rejects with a `SuppressedError` that keeps the original error in its `suppressed` chain.
2770
- * A transaction that it starts rolls back instead of `COMMIT` after a `ConnectionError` on its connection, and when it rejects after such an error, also of `COMMIT`, it rejects with `TransactionConnectionError` of the phase of the failure, whose `cause` is the error it would reject with otherwise.
2771
- */
2772
- transaction<T>(callback: () => Promise<T>, options?: TransactionOptions): Promise<T>;
2773
- /**
2774
- * Runs `callback` in the current transaction, or in a new transaction outside of one.
2775
- *
2776
- * Joining starts no savepoint, so a rejection of `callback` does not undo its changes.
2777
- * It rejects without calling `callback` when the current level accepts no statements, as a nested transaction would.
2778
- */
2779
- ensureTransaction<T>(callback: () => Promise<T>): Promise<T>;
2780
- /**
2781
- * Tells whether the current async context runs in a transaction of `transaction`.
2782
- *
2783
- * A test transaction and the seed of a test fixture are not transactions, unless they run inside one, so that code under test behaves as in production.
2784
- */
2785
- isInTransaction(): boolean;
2786
- /**
2787
- * Runs `callback` in a transaction that always rolls back, on a coordinator created for tests.
2788
- *
2789
- * Inside a transaction, it runs `callback` in a savepoint nested in it that always rolls back.
2790
- * When `signal` aborts, the level stops accepting statements at once and ends without waiting for `callback`.
2791
- * Once the level ends, the transaction rejects with the reason of the signal.
2792
- * A failure to start or end the level after the abort suppresses the reason in a `SuppressedError`.
2793
- * Aborted while it waits for its turn in the fixture stack or for a connection, it rejects at once; after the abort, it never calls `callback`.
2794
- */
2795
- testTransaction<T>(callback: () => Promise<T>, options?: TestTransactionOptions): Promise<T>;
2796
- /**
2797
- * Opens a test fixture: a transaction on a reserved connection, or a savepoint in the innermost open fixture, and runs `seed` in it.
2798
- *
2799
- * Test transactions started outside any transaction run in the innermost fixture.
2800
- * A fixture whose `seed` rejects rolls back and closes.
2801
- */
2802
- createTestFixture<T>(seed: () => Promise<T>, options?: TestFixtureOptions): Promise<OpenedTestFixture<T>>;
2803
- /**
2804
- * Starts opening a test fixture, see `createTestFixture`, and returns it with a `close` that can be called before it opens.
2805
- *
2806
- * Closing before the fixture opens rejects the opening without waiting for `seed` and rolls the fixture back, so a fixture or test transaction started after `close` never nests in it, even when its `seed` never settles.
2807
- * Closing an open fixture also closes the fixtures opening in it.
2808
- */
2809
- startTestFixture<T>(seed: () => Promise<T>, options?: TestFixtureOptions): PendingTestFixture<T>;
2810
- /**
2811
- * Closes the test fixtures, including those still opening, and then the driver, which waits for the running transactions to end.
2812
- *
2813
- * A driver waits for every reserved connection, so closing it under an open fixture would wait forever.
2814
- * A failed closing of the driver suppresses the failures of closing the fixtures.
2815
- * From the first call, statements, transactions, and fixtures started outside a transaction reject, while the levels already running can still end; a repeated call returns the same closing.
2816
- */
2817
- close(): Promise<void>;
2818
- }
2819
- /**
2820
- * Physical database shared by all schemas bound to it.
2821
- *
2822
- * Its ambient transaction spans every schema bound to the same database, such as tenant and SaaS schemas.
2823
- * Disposing it, such as with `await using`, closes it.
2824
- */
2825
- interface Database extends AsyncDisposable {
2826
- /** Routes the statements and transactions of the database; `kern-orm/testing` runs test transactions and test fixtures through it. */
2827
- readonly coordinator: TransactionCoordinator;
2828
- /**
2829
- * Binds a schema to this database, placing its tables in a PostgreSQL schema.
2830
- *
2831
- * A database can bind several schemas, which share its connections and transactions.
2832
- */
2833
- bind<T extends Tables, R extends SchemaRelations>(schema: Schema<T, R>, options?: BindOptions): Db<T, R>;
2834
- /**
2835
- * Starts a query of the SQL statement of the template, as `$query` of a `Db` does, for code without a `Db`.
2836
- *
2837
- * It names no tables of a `Db`: run a statement that interpolates them with `$query` of that `Db`.
2838
- */
2839
- query(strings: TemplateStringsArray, ...values: unknown[]): SqlQuery<InitialSqlQueryState>;
2840
- /** Executes a script of statements without parameters, as `$script` of a `Db` does, for code without a `Db`. */
2841
- script(text: string): Promise<void>;
2842
- /**
2843
- * Executes the script of the template, as `$script` of a `Db` does, for code without a `Db`.
2844
- *
2845
- * It names no tables of a `Db`: run a script that interpolates them with `$script` of that `Db`.
2846
- */
2847
- script(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;
2848
- /** Executes a compiled statement, such as of `$compile` of a `Db`, in the ambient transaction, or on the pool outside of one unless the database was created with `test: true`. */
2849
- execute(statement: SqlStatement): Promise<DriverResult>;
2850
- /**
2851
- * Runs `callback` in a transaction that queries of every bound schema join automatically.
2852
- *
2853
- * Inside an existing transaction, it starts a nested transaction.
2854
- */
2855
- transaction<T>(callback: () => Promise<T>, options?: TransactionOptions): Promise<T>;
2856
- /**
2857
- * Runs `callback` in the current transaction without a nested transaction, or in a new transaction outside of one.
2858
- *
2859
- * A rejection of a callback that joined a transaction does not undo its changes: the enclosing transaction commits them unless it fails too.
2860
- * A test transaction is not a transaction to join: there, it starts a nested transaction where it starts a transaction in production.
2861
- */
2862
- ensureTransaction<T>(callback: () => Promise<T>): Promise<T>;
2863
- /** Tells whether the code runs in a transaction, not counting test transactions, so that code under test sees what it sees in production. */
2864
- isInTransaction(): boolean;
2865
- /**
2866
- * Takes the advisory lock of `key` until the transaction ends, waiting while another transaction holds it, such as to keep processes from running the same job at once.
2867
- *
2868
- * It rejects where `isInTransaction()` is `false`, since outside a transaction the lock would end with its statement.
2869
- * A nested transaction that rolls back releases the locks it took.
2870
- */
2871
- lock(key: string): Promise<void>;
2872
- /** Rolls back the open test fixtures and closes the connections of the driver once the running transactions end. */
2873
- close(): Promise<void>;
2874
- }
2875
- /** Isolation level of a transaction in PostgreSQL. */
2876
- type IsolationLevel = "read committed" | "repeatable read" | "serializable";
2877
- /** Options of `transaction` of a `Database` and `$transaction` of a `Db`. */
2878
- interface TransactionOptions {
2879
- /**
2880
- * Isolation level of the transaction, such as `serializable`.
2881
- *
2882
- * A nested transaction runs at the level of its transaction: given another level, it rejects.
2883
- */
2884
- isolation?: IsolationLevel;
2885
- /**
2886
- * PostgreSQL schemas where the unqualified names of the statements of the transaction resolve, in their order, such as the schema of a tenant followed by the schema of extensions.
2887
- *
2888
- * It applies to the statements of the callback, including those of its nested transactions, until the transaction ends; a nested transaction then restores the search path of the enclosing transaction.
2889
- */
2890
- searchPath?: readonly string[];
2891
- }
2892
- /** Options of `createDatabase`. */
2893
- interface DatabaseOptions {
2894
- driver: Driver;
2895
- /** Rejects queries and transactions outside the test transactions and the seeds of test fixtures of `kern-orm/testing`, so that every statement of the tests runs in a transaction that rolls back. */
2896
- test?: boolean;
2897
- /**
2898
- * Receives a failure to release the connection of a transaction, such as to log it; the failure does not change the result or error of the transaction.
2899
- *
2900
- * Without it, the failure goes to `console.error`.
2901
- */
2902
- onReleaseError?: (error: unknown) => void;
2903
- }
2904
- /** Creates a database over a driver; its transactions are shared by every schema bound to it. */
2905
- declare function createDatabase({ driver, ...options }: DatabaseOptions): Database;
2906
2423
  /** Physical placement of the tables of a schema bound to a database. */
2907
2424
  interface BindOptions {
2908
2425
  /** PostgreSQL schema of the tables; a function is called on every query, such as to resolve the current tenant. */
2909
2426
  schemaName?: string | (() => string);
2910
2427
  }
2911
2428
  /**
2912
- * Schema bound to a database with `database.bind`.
2429
+ * Schema bound to a database with `bindSchema`.
2913
2430
  *
2914
2431
  * Its table entries start queries bound to it, which execute when awaited.
2915
2432
  */
2916
2433
  type Db<T extends Tables, R extends SchemaRelations = EmptyRecord> = DbEntries<T, R> & DbMethods<T, R>;
2917
2434
  /** Bound query entry points; each access starts a query over a new table occurrence, of the one row of a singleton table. */
2918
2435
  type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<TableQueryState<T[K], TableContext<R, K>>>; };
2919
- /** 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. */
2920
- 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>;
2436
+ /** 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`. */
2437
+ 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>;
2921
2438
  /** State of a query that a `Db` can execute: over table `T`, selecting records only of relations `U`. */
2922
2439
  interface DbQueryState<T extends AnyTable, U extends UsedRelation> extends QueryStateOf<T> {
2923
2440
  readonly uses: U;
@@ -2962,7 +2479,7 @@ interface DbMethods<T extends Tables, R extends SchemaRelations> {
2962
2479
  */
2963
2480
  $query(strings: TemplateStringsArray, ...values: unknown[]): SqlQuery<InitialSqlQueryState>;
2964
2481
  /**
2965
- * Executes a script of statements without parameters, such as DDL separated by semicolons, in the ambient transaction, or on the pool outside of one, where PostgreSQL runs them in one implicit transaction.
2482
+ * Executes a script of statements without parameters, such as DDL separated by semicolons, in the ambient transaction or session, or on the pool outside of one; outside a transaction, PostgreSQL runs them in one implicit transaction.
2966
2483
  *
2967
2484
  * The script must not start or end transactions, which the database tracks.
2968
2485
  */
@@ -2989,12 +2506,40 @@ interface DbMethods<T extends Tables, R extends SchemaRelations> {
2989
2506
  /** Tells whether the code runs in a transaction of the database, not counting test transactions, so that code under test sees what it sees in production. */
2990
2507
  $isInTransaction(): boolean;
2991
2508
  /**
2992
- * Takes the advisory lock of `key` until the transaction of the database ends, waiting while another transaction holds it, such as to keep processes from running the same job at once.
2509
+ * Tells whether a statement of the code runs in a transaction block of PostgreSQL, counting test transactions, such as to choose a statement that PostgreSQL rejects there, `CREATE INDEX CONCURRENTLY`.
2510
+ *
2511
+ * It is `false` in a session outside its transactions.
2512
+ */
2513
+ $isInTransactionBlock(): boolean;
2514
+ /**
2515
+ * Runs `callback` in a session of the database: on one connection outside a transaction, such as for statements that PostgreSQL rejects in a transaction block and that share a setting of the connection, such as its search path.
2516
+ *
2517
+ * Statements of every schema bound to the database join the session automatically, each in a transaction of its own, and `$transaction` in the callback starts a transaction on the connection of the session.
2518
+ * A rejection of `callback` undoes nothing.
2519
+ * It rejects inside a transaction, also a test transaction, inside another session, and on a database created with `test: true`.
2520
+ */
2521
+ $session<Result>(callback: () => Promise<Result>, options?: SessionOptions): Promise<Result>;
2522
+ /**
2523
+ * Takes the advisory lock of `key` until the transaction of the database ends, waiting while another transaction or session holds it, such as to keep processes from running the same job at once.
2993
2524
  *
2994
- * It rejects where `$isInTransaction()` is `false`, since outside a transaction the lock would end with its statement.
2525
+ * It rejects where `$isInTransaction()` is `false`, since outside a transaction the lock would end with its statement; in a session, take the lock with `$tryLock`, which does not wait.
2995
2526
  * A nested transaction that rolls back releases the locks it took.
2996
2527
  */
2997
2528
  $lock(key: string): Promise<void>;
2529
+ /**
2530
+ * Takes the advisory lock of `key` unless another transaction or session holds it, and tells whether it took it, such as to skip a job that another process is running.
2531
+ *
2532
+ * In a transaction of the database, it holds the lock until the transaction ends, as `$lock` does; in a session outside its transactions, until the session ends.
2533
+ * It rejects outside both, since the lock would end with its statement; a test transaction alone does not count.
2534
+ */
2535
+ $tryLock(key: string): Promise<boolean>;
2536
+ /**
2537
+ * Takes the advisory lock of `key` in a session of the database until the session ends, calling `$tryLock` again after a pause until it takes the lock, such as to let one process at a time run statements outside a transaction.
2538
+ *
2539
+ * It rejects outside a session, and in a transaction, where `$lock` waits for the lock.
2540
+ * Once `signal` of `options` aborts, such as `AbortSignal.timeout(60_000)`, it makes no more attempts and rejects with the reason of the signal, unless the attempt that is running takes the lock.
2541
+ */
2542
+ $pollLock(key: string, options?: PollLockOptions): Promise<void>;
2998
2543
  }
2999
2544
  /**
3000
2545
  * `Db` of schema `S`, such as the type of a parameter of code shared by several schemas.
@@ -3004,6 +2549,12 @@ interface DbMethods<T extends Tables, R extends SchemaRelations> {
3004
2549
  type DbOf<S extends AnySchema> = Db<S["$tables"], S[typeof schemaRelations]>;
3005
2550
  /** `Db` of any schema. */
3006
2551
  type AnyDb = Db<any, any>;
2552
+ /**
2553
+ * Binds a schema to a database, placing its tables in a PostgreSQL schema.
2554
+ *
2555
+ * Schemas bound to the same database, such as tenant and SaaS schemas, share its connections and transactions.
2556
+ */
2557
+ declare function bindSchema<T extends Tables, R extends SchemaRelations>(schema: Schema<T, R>, database: Database, options?: BindOptions): Db<T, R>;
3007
2558
  /** Occurrence of a table in `FROM`. */
3008
2559
  interface TableSourceNode {
3009
2560
  readonly kind: "table";
@@ -3114,6 +2665,11 @@ interface RawSqlNode {
3114
2665
  readonly fragments: readonly string[];
3115
2666
  readonly values: readonly ExpressionNode[];
3116
2667
  }
2668
+ /** SQL fragment of the database layer, such as a quoted name of `identifier`, which the layer renders with the parameters of the statement. */
2669
+ interface FragmentNode {
2670
+ readonly kind: "fragment";
2671
+ readonly fragment: SqlFragment$1;
2672
+ }
3117
2673
  /** Name of a table interpolated into a SQL fragment, qualified by the PostgreSQL schema of the statement. */
3118
2674
  interface TableNameNode {
3119
2675
  readonly kind: "tableName";
@@ -3147,7 +2703,7 @@ interface AggregateNode {
3147
2703
  /** Condition of the rows that the function takes, as `FILTER (WHERE ...)`, or `undefined` for every row. */
3148
2704
  readonly filter: ExpressionNode | undefined;
3149
2705
  }
3150
- type ExpressionNode = ColumnRefNode | ParamNode | CastNode | BooleanNode | AndNode | OrNode | NotNode | ValuesNode | NestedQueryNode | ComparisonNode | InNode | InQueryNode | IsNullNode | RawSqlNode | TableNameNode | SubqueryNode | ExistsNode | TextSubqueryNode | AggregateNode;
2706
+ type ExpressionNode = ColumnRefNode | ParamNode | CastNode | BooleanNode | AndNode | OrNode | NotNode | ValuesNode | NestedQueryNode | ComparisonNode | InNode | InQueryNode | IsNullNode | RawSqlNode | FragmentNode | TableNameNode | SubqueryNode | ExistsNode | TextSubqueryNode | AggregateNode;
3151
2707
  /**
3152
2708
  * Filters of a query, kept apart so that composing one kind never changes the others.
3153
2709
  *
@@ -3275,17 +2831,6 @@ interface DeleteNode<Field = ProjectionNode> extends MutationParts<Field> {
3275
2831
  }
3276
2832
  /** Statement that inserts, updates, or deletes rows, with the fields of `RETURNING` of type `Field`. */
3277
2833
  type MutationStatementNode<Field = ProjectionNode> = InsertNode<Field> | UpdateNode<Field> | DeleteNode<Field>;
3278
- /**
3279
- * Statement of SQL text written by a user, such as of `$query`.
3280
- *
3281
- * Its result mode is the rows mode of the rows that the statement returns and whether a row is the value of its only column.
3282
- */
3283
- interface TextStatementNode extends ResultMode {
3284
- readonly kind: "text";
3285
- readonly sql: RawSqlNode;
3286
- /** Fields decoded from the result columns of their keys, or from the only column for a value; `undefined` for a statement that resolves to the number of the rows of its command tag. */
3287
- readonly fields: readonly ScalarField[] | undefined;
3288
- }
3289
2834
  declare const valueType: unique symbol;
3290
2835
  declare const inputType: unique symbol;
3291
2836
  declare const typed: unique symbol;
@@ -3367,362 +2912,6 @@ declare const textOperators: TextOperators;
3367
2912
  declare const TRUE: Expression<boolean>;
3368
2913
  /** Condition that never holds, such as for a branch of `or` built in code: `or(check, isAdmin ? other : FALSE)`. */
3369
2914
  declare const FALSE: Expression<boolean>;
3370
- /**
3371
- * Error of a statement that PostgreSQL rejected, such as for a violated constraint; the connection of the statement stays usable.
3372
- *
3373
- * 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.
3374
- * 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`.
3375
- */
3376
- declare class QueryError extends Error {
3377
- readonly name = "QueryError";
3378
- /** SQLSTATE of the error, such as `23505` for a violated unique constraint. */
3379
- readonly code: string;
3380
- /** Name of the constraint that the statement violated, if any. */
3381
- readonly constraint: string | undefined;
3382
- constructor(message: string, fields: {
3383
- code: string;
3384
- constraint?: string | undefined;
3385
- cause?: unknown;
3386
- });
3387
- /** Tells whether `value` is an instance of the class, including one of `QueryError` of another copy of kern-orm. */
3388
- static [Symbol.hasInstance]<T>(this: abstract new (...args: never) => T, value: unknown): value is T;
3389
- }
3390
- /**
3391
- * 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.
3392
- *
3393
- * The statement may have run or not, and its connection may be lost or in an unknown state of its transaction.
3394
- */
3395
- declare class ConnectionError extends Error {
3396
- readonly name: string;
3397
- constructor(message: string, options?: {
3398
- cause?: unknown;
3399
- });
3400
- /** Tells whether `value` is an instance of the class, including one of `ConnectionError` of another copy of kern-orm. */
3401
- static [Symbol.hasInstance]<T>(this: abstract new (...args: never) => T, value: unknown): value is T;
3402
- }
3403
- /** Fields of the PostgreSQL error that an error of a client carries, by which `toDriverError` classifies it. */
3404
- interface DriverErrorFields {
3405
- /**
3406
- * Severity of the error, such as `ERROR` or `FATAL`.
3407
- *
3408
- * Pass the severity in English when the client gives it, and the one in the language of the server otherwise.
3409
- */
3410
- readonly severity?: unknown;
3411
- /** SQLSTATE of the error, such as `23505`. */
3412
- readonly code?: unknown;
3413
- /** Name of the constraint that the statement violated. */
3414
- readonly constraint?: unknown;
3415
- }
3416
- /**
3417
- * 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.
3418
- *
3419
- * An error that kern-orm has already classified returns as it is.
3420
- * 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.
3421
- * An error of severity `ERROR` is a `QueryError`.
3422
- * 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`.
3423
- */
3424
- declare function toDriverError(error: unknown, fields?: DriverErrorFields): QueryError | ConnectionError;
3425
- /** Phase of a transaction in which its connection failed. */
3426
- type TransactionPhase = TransactionConnectionError["phase"];
3427
- /**
3428
- * Error of a transaction whose connection failed, which tells whether the transaction may have been committed.
3429
- *
3430
- * Its `cause` is the error that the transaction would reject with otherwise, such as the error of the callback, or a `SuppressedError` of a failed rollback that keeps it.
3431
- */
3432
- declare class TransactionConnectionError extends ConnectionError {
3433
- readonly name: string;
3434
- /**
3435
- * Phase of the transaction in which its connection failed:
3436
- *
3437
- * - `begin`: before the callback, such as getting the connection or `BEGIN`, so the transaction applied nothing;
3438
- * - `transaction`: in the callback or its rollback, so the transaction was rolled back;
3439
- * - `commit`: during `COMMIT`, so whether the transaction was committed is unknown.
3440
- */
3441
- readonly phase: "begin" | "transaction" | "commit";
3442
- constructor(phase: TransactionPhase, options?: {
3443
- cause?: unknown;
3444
- });
3445
- /** Tells whether `value` is an instance of the class, including one of `TransactionConnectionError` of another copy of kern-orm. */
3446
- static [Symbol.hasInstance]<T>(this: abstract new (...args: never) => T, value: unknown): value is T;
3447
- }
3448
- /**
3449
- * Condition names of the SQLSTATE codes of PostgreSQL errors, by code: the codes of type `E` with a condition name, which PL/pgSQL takes in `EXCEPTION WHEN`, under the headings of their classes.
3450
- *
3451
- * A code that ends in `000` is the condition of its class.
3452
- * A few names have two codes, such as `null_value_not_allowed`.
3453
- */
3454
- declare const conditionsByCode: {
3455
- readonly "03000": "sql_statement_not_yet_complete";
3456
- readonly "08000": "connection_exception";
3457
- readonly "08003": "connection_does_not_exist";
3458
- readonly "08006": "connection_failure";
3459
- readonly "08001": "sqlclient_unable_to_establish_sqlconnection";
3460
- readonly "08004": "sqlserver_rejected_establishment_of_sqlconnection";
3461
- readonly "08007": "transaction_resolution_unknown";
3462
- readonly "08P01": "protocol_violation";
3463
- readonly "09000": "triggered_action_exception";
3464
- readonly "0A000": "feature_not_supported";
3465
- readonly "0B000": "invalid_transaction_initiation";
3466
- readonly "0F000": "locator_exception";
3467
- readonly "0F001": "invalid_locator_specification";
3468
- readonly "0L000": "invalid_grantor";
3469
- readonly "0LP01": "invalid_grant_operation";
3470
- readonly "0P000": "invalid_role_specification";
3471
- readonly "0Z000": "diagnostics_exception";
3472
- readonly "0Z002": "stacked_diagnostics_accessed_without_active_handler";
3473
- readonly "10608": "invalid_argument_for_xquery";
3474
- readonly "20000": "case_not_found";
3475
- readonly "21000": "cardinality_violation";
3476
- readonly "22000": "data_exception";
3477
- readonly "2202E": "array_subscript_error";
3478
- readonly "22021": "character_not_in_repertoire";
3479
- readonly "22008": "datetime_field_overflow";
3480
- readonly "22012": "division_by_zero";
3481
- readonly "22005": "error_in_assignment";
3482
- readonly "2200B": "escape_character_conflict";
3483
- readonly "22022": "indicator_overflow";
3484
- readonly "22015": "interval_field_overflow";
3485
- readonly "2201E": "invalid_argument_for_logarithm";
3486
- readonly "22014": "invalid_argument_for_ntile_function";
3487
- readonly "22016": "invalid_argument_for_nth_value_function";
3488
- readonly "2201F": "invalid_argument_for_power_function";
3489
- readonly "2201G": "invalid_argument_for_width_bucket_function";
3490
- readonly "22018": "invalid_character_value_for_cast";
3491
- readonly "22007": "invalid_datetime_format";
3492
- readonly "22019": "invalid_escape_character";
3493
- readonly "2200D": "invalid_escape_octet";
3494
- readonly "22025": "invalid_escape_sequence";
3495
- readonly "22P06": "nonstandard_use_of_escape_character";
3496
- readonly "22010": "invalid_indicator_parameter_value";
3497
- readonly "22023": "invalid_parameter_value";
3498
- readonly "22013": "invalid_preceding_or_following_size";
3499
- readonly "2201B": "invalid_regular_expression";
3500
- readonly "2201W": "invalid_row_count_in_limit_clause";
3501
- readonly "2201X": "invalid_row_count_in_result_offset_clause";
3502
- readonly "2202H": "invalid_tablesample_argument";
3503
- readonly "2202G": "invalid_tablesample_repeat";
3504
- readonly "22009": "invalid_time_zone_displacement_value";
3505
- readonly "2200C": "invalid_use_of_escape_character";
3506
- readonly "2200G": "most_specific_type_mismatch";
3507
- readonly "22004": "null_value_not_allowed";
3508
- readonly "22002": "null_value_no_indicator_parameter";
3509
- readonly "22003": "numeric_value_out_of_range";
3510
- readonly "2200H": "sequence_generator_limit_exceeded";
3511
- readonly "22026": "string_data_length_mismatch";
3512
- readonly "22001": "string_data_right_truncation";
3513
- readonly "22011": "substring_error";
3514
- readonly "22027": "trim_error";
3515
- readonly "22024": "unterminated_c_string";
3516
- readonly "2200F": "zero_length_character_string";
3517
- readonly "22P01": "floating_point_exception";
3518
- readonly "22P02": "invalid_text_representation";
3519
- readonly "22P03": "invalid_binary_representation";
3520
- readonly "22P04": "bad_copy_file_format";
3521
- readonly "22P05": "untranslatable_character";
3522
- readonly "2200L": "not_an_xml_document";
3523
- readonly "2200M": "invalid_xml_document";
3524
- readonly "2200N": "invalid_xml_content";
3525
- readonly "2200S": "invalid_xml_comment";
3526
- readonly "2200T": "invalid_xml_processing_instruction";
3527
- readonly "22030": "duplicate_json_object_key_value";
3528
- readonly "22031": "invalid_argument_for_sql_json_datetime_function";
3529
- readonly "22032": "invalid_json_text";
3530
- readonly "22033": "invalid_sql_json_subscript";
3531
- readonly "22034": "more_than_one_sql_json_item";
3532
- readonly "22035": "no_sql_json_item";
3533
- readonly "22036": "non_numeric_sql_json_item";
3534
- readonly "22037": "non_unique_keys_in_a_json_object";
3535
- readonly "22038": "singleton_sql_json_item_required";
3536
- readonly "22039": "sql_json_array_not_found";
3537
- readonly "2203A": "sql_json_member_not_found";
3538
- readonly "2203B": "sql_json_number_not_found";
3539
- readonly "2203C": "sql_json_object_not_found";
3540
- readonly "2203D": "too_many_json_array_elements";
3541
- readonly "2203E": "too_many_json_object_members";
3542
- readonly "2203F": "sql_json_scalar_required";
3543
- readonly "2203G": "sql_json_item_cannot_be_cast_to_target_type";
3544
- readonly "23000": "integrity_constraint_violation";
3545
- readonly "23001": "restrict_violation";
3546
- readonly "23502": "not_null_violation";
3547
- readonly "23503": "foreign_key_violation";
3548
- readonly "23505": "unique_violation";
3549
- readonly "23514": "check_violation";
3550
- readonly "23P01": "exclusion_violation";
3551
- readonly "24000": "invalid_cursor_state";
3552
- readonly "25000": "invalid_transaction_state";
3553
- readonly "25001": "active_sql_transaction";
3554
- readonly "25002": "branch_transaction_already_active";
3555
- readonly "25008": "held_cursor_requires_same_isolation_level";
3556
- readonly "25003": "inappropriate_access_mode_for_branch_transaction";
3557
- readonly "25004": "inappropriate_isolation_level_for_branch_transaction";
3558
- readonly "25005": "no_active_sql_transaction_for_branch_transaction";
3559
- readonly "25006": "read_only_sql_transaction";
3560
- readonly "25007": "schema_and_data_statement_mixing_not_supported";
3561
- readonly "25P01": "no_active_sql_transaction";
3562
- readonly "25P02": "in_failed_sql_transaction";
3563
- readonly "25P03": "idle_in_transaction_session_timeout";
3564
- readonly "25P04": "transaction_timeout";
3565
- readonly "26000": "invalid_sql_statement_name";
3566
- readonly "27000": "triggered_data_change_violation";
3567
- readonly "28000": "invalid_authorization_specification";
3568
- readonly "28P01": "invalid_password";
3569
- readonly "2B000": "dependent_privilege_descriptors_still_exist";
3570
- readonly "2BP01": "dependent_objects_still_exist";
3571
- readonly "2D000": "invalid_transaction_termination";
3572
- readonly "2F000": "sql_routine_exception";
3573
- readonly "2F005": "function_executed_no_return_statement";
3574
- readonly "2F002": "modifying_sql_data_not_permitted";
3575
- readonly "2F003": "prohibited_sql_statement_attempted";
3576
- readonly "2F004": "reading_sql_data_not_permitted";
3577
- readonly "34000": "invalid_cursor_name";
3578
- readonly "38000": "external_routine_exception";
3579
- readonly "38001": "containing_sql_not_permitted";
3580
- readonly "38002": "modifying_sql_data_not_permitted";
3581
- readonly "38003": "prohibited_sql_statement_attempted";
3582
- readonly "38004": "reading_sql_data_not_permitted";
3583
- readonly "39000": "external_routine_invocation_exception";
3584
- readonly "39001": "invalid_sqlstate_returned";
3585
- readonly "39004": "null_value_not_allowed";
3586
- readonly "39P01": "trigger_protocol_violated";
3587
- readonly "39P02": "srf_protocol_violated";
3588
- readonly "39P03": "event_trigger_protocol_violated";
3589
- readonly "3B000": "savepoint_exception";
3590
- readonly "3B001": "invalid_savepoint_specification";
3591
- readonly "3D000": "invalid_catalog_name";
3592
- readonly "3F000": "invalid_schema_name";
3593
- readonly "40000": "transaction_rollback";
3594
- readonly "40002": "transaction_integrity_constraint_violation";
3595
- readonly "40001": "serialization_failure";
3596
- readonly "40003": "statement_completion_unknown";
3597
- readonly "40P01": "deadlock_detected";
3598
- readonly "42000": "syntax_error_or_access_rule_violation";
3599
- readonly "42601": "syntax_error";
3600
- readonly "42501": "insufficient_privilege";
3601
- readonly "42846": "cannot_coerce";
3602
- readonly "42803": "grouping_error";
3603
- readonly "42P20": "windowing_error";
3604
- readonly "42P19": "invalid_recursion";
3605
- readonly "42830": "invalid_foreign_key";
3606
- readonly "42602": "invalid_name";
3607
- readonly "42622": "name_too_long";
3608
- readonly "42939": "reserved_name";
3609
- readonly "42804": "datatype_mismatch";
3610
- readonly "42P18": "indeterminate_datatype";
3611
- readonly "42P21": "collation_mismatch";
3612
- readonly "42P22": "indeterminate_collation";
3613
- readonly "42809": "wrong_object_type";
3614
- readonly "428C9": "generated_always";
3615
- readonly "42703": "undefined_column";
3616
- readonly "42883": "undefined_function";
3617
- readonly "42P01": "undefined_table";
3618
- readonly "42P02": "undefined_parameter";
3619
- readonly "42704": "undefined_object";
3620
- readonly "42701": "duplicate_column";
3621
- readonly "42P03": "duplicate_cursor";
3622
- readonly "42P04": "duplicate_database";
3623
- readonly "42723": "duplicate_function";
3624
- readonly "42P05": "duplicate_prepared_statement";
3625
- readonly "42P06": "duplicate_schema";
3626
- readonly "42P07": "duplicate_table";
3627
- readonly "42712": "duplicate_alias";
3628
- readonly "42710": "duplicate_object";
3629
- readonly "42702": "ambiguous_column";
3630
- readonly "42725": "ambiguous_function";
3631
- readonly "42P08": "ambiguous_parameter";
3632
- readonly "42P09": "ambiguous_alias";
3633
- readonly "42P10": "invalid_column_reference";
3634
- readonly "42611": "invalid_column_definition";
3635
- readonly "42P11": "invalid_cursor_definition";
3636
- readonly "42P12": "invalid_database_definition";
3637
- readonly "42P13": "invalid_function_definition";
3638
- readonly "42P14": "invalid_prepared_statement_definition";
3639
- readonly "42P15": "invalid_schema_definition";
3640
- readonly "42P16": "invalid_table_definition";
3641
- readonly "42P17": "invalid_object_definition";
3642
- readonly "44000": "with_check_option_violation";
3643
- readonly "53000": "insufficient_resources";
3644
- readonly "53100": "disk_full";
3645
- readonly "53200": "out_of_memory";
3646
- readonly "53300": "too_many_connections";
3647
- readonly "53400": "configuration_limit_exceeded";
3648
- readonly "54000": "program_limit_exceeded";
3649
- readonly "54001": "statement_too_complex";
3650
- readonly "54011": "too_many_columns";
3651
- readonly "54023": "too_many_arguments";
3652
- readonly "55000": "object_not_in_prerequisite_state";
3653
- readonly "55006": "object_in_use";
3654
- readonly "55P02": "cant_change_runtime_param";
3655
- readonly "55P03": "lock_not_available";
3656
- readonly "55P04": "unsafe_new_enum_value_usage";
3657
- readonly "57000": "operator_intervention";
3658
- readonly "57014": "query_canceled";
3659
- readonly "57P01": "admin_shutdown";
3660
- readonly "57P02": "crash_shutdown";
3661
- readonly "57P03": "cannot_connect_now";
3662
- readonly "57P04": "database_dropped";
3663
- readonly "57P05": "idle_session_timeout";
3664
- readonly "58000": "system_error";
3665
- readonly "58030": "io_error";
3666
- readonly "58P01": "undefined_file";
3667
- readonly "58P02": "duplicate_file";
3668
- readonly "58P03": "file_name_too_long";
3669
- readonly F0000: "config_file_error";
3670
- readonly F0001: "lock_file_exists";
3671
- readonly HV000: "fdw_error";
3672
- readonly HV005: "fdw_column_name_not_found";
3673
- readonly HV002: "fdw_dynamic_parameter_value_needed";
3674
- readonly HV010: "fdw_function_sequence_error";
3675
- readonly HV021: "fdw_inconsistent_descriptor_information";
3676
- readonly HV024: "fdw_invalid_attribute_value";
3677
- readonly HV007: "fdw_invalid_column_name";
3678
- readonly HV008: "fdw_invalid_column_number";
3679
- readonly HV004: "fdw_invalid_data_type";
3680
- readonly HV006: "fdw_invalid_data_type_descriptors";
3681
- readonly HV091: "fdw_invalid_descriptor_field_identifier";
3682
- readonly HV00B: "fdw_invalid_handle";
3683
- readonly HV00C: "fdw_invalid_option_index";
3684
- readonly HV00D: "fdw_invalid_option_name";
3685
- readonly HV090: "fdw_invalid_string_length_or_buffer_length";
3686
- readonly HV00A: "fdw_invalid_string_format";
3687
- readonly HV009: "fdw_invalid_use_of_null_pointer";
3688
- readonly HV014: "fdw_too_many_handles";
3689
- readonly HV001: "fdw_out_of_memory";
3690
- readonly HV00P: "fdw_no_schemas";
3691
- readonly HV00J: "fdw_option_name_not_found";
3692
- readonly HV00K: "fdw_reply_handle";
3693
- readonly HV00Q: "fdw_schema_not_found";
3694
- readonly HV00R: "fdw_table_not_found";
3695
- readonly HV00L: "fdw_unable_to_create_execution";
3696
- readonly HV00M: "fdw_unable_to_create_reply";
3697
- readonly HV00N: "fdw_unable_to_establish_connection";
3698
- readonly P0000: "plpgsql_error";
3699
- readonly P0001: "raise_exception";
3700
- readonly P0002: "no_data_found";
3701
- readonly P0003: "too_many_rows";
3702
- readonly P0004: "assert_failure";
3703
- readonly XX000: "internal_error";
3704
- readonly XX001: "data_corrupted";
3705
- readonly XX002: "index_corrupted";
3706
- };
3707
- type ConditionsByCode = typeof conditionsByCode;
3708
- /** Name of a condition of PostgreSQL errors, such as `unique_violation`, or of a class of them, such as `integrity_constraint_violation`. */
3709
- type QueryErrorCondition = ConditionsByCode[keyof ConditionsByCode];
3710
- /**
3711
- * SQLSTATE codes of each condition, with every code of its class for the condition of a class.
3712
- *
3713
- * TypeScript computes the map once, whereas a mapped type of the table for each condition would cost a check of another condition about 70 times as many instantiations.
3714
- */
3715
- type CodesByCondition = { [K in keyof ConditionsByCode as ConditionsByCode[K]]: K extends `${infer Class}000` ? `${Class}${string}` : K; };
3716
- /** SQLSTATE codes of the condition `C`, with every code of its class for the condition of a class. */
3717
- type QueryErrorCode<C extends QueryErrorCondition> = CodesByCondition[C];
3718
- /**
3719
- * Tells whether `error` is a `QueryError` of `condition`, including a `QueryError` of another copy of kern-orm.
3720
- *
3721
- * The condition of a class, such as `integrity_constraint_violation`, matches every error of its class, as in PL/pgSQL.
3722
- */
3723
- declare function isQueryError<C extends QueryErrorCondition>(error: unknown, condition: C): error is QueryError & {
3724
- readonly code: QueryErrorCode<C>;
3725
- };
3726
2915
  /**
3727
2916
  * 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.
3728
2917
  *
@@ -3769,8 +2958,9 @@ type SqlTemplate<T, O extends OperatorDefinitions, I = T> = (strings: TemplateSt
3769
2958
  /**
3770
2959
  * Builds a SQL fragment.
3771
2960
  *
3772
- * Interpolated expressions such as column references stay structured, a query of a table without clauses, such as `db.form`, becomes the name of the table, and other values become query parameters.
2961
+ * Interpolated expressions such as column references stay structured, a query of a table without clauses, such as `db.form`, becomes the name of the table, a SQL fragment of `kern-orm/db` stays SQL, and other values become query parameters.
3773
2962
  * Another query of a table becomes a subquery in parentheses, and a query of one value, such as of an aggregate or of `exists`, its value, as in a condition.
2963
+ * A parameter takes a string, a number, a bigint, a Boolean, `null` for `NULL`, a `Date`, or a `Uint8Array`: pass any other value, such as JSON or an array, with `param` and its type.
3774
2964
  * The type argument declares the TypeScript type of the fragment and does not convert values at runtime, so the fragment cannot be selected; the fragment has `isNull` and the operators of `equalityOperators` only.
3775
2965
  */
3776
2966
  declare function sql<T = unknown>(strings: TemplateStringsArray, ...values: unknown[]): UntypedExpression<T>;
@@ -3781,13 +2971,13 @@ declare function sql<T = unknown>(strings: TemplateStringsArray, ...values: unkn
3781
2971
  */
3782
2972
  declare function sql<Output, Input, O extends OperatorDefinitions>(type: Type<Output, Input, O, any>): SqlTemplate<Output, O, Input>;
3783
2973
  /**
3784
- * Creates a SQL fragment of a quoted name, such as of a table or a column known only at runtime, for the templates of `sql`, of `$query` and `$script` of a `Db`, and of `query` and `script` of a `Database`.
2974
+ * Creates a SQL fragment of a quoted name, such as of a table or a column known only at runtime, for the templates of `sql`, and of `$query` and `$script` of a `Db`; `query` and `script` of a `Database` take `identifier` of `kern-orm/db`.
3785
2975
  *
3786
2976
  * Several names make a qualified name, such as `identifier(schema, table)` for `"schema"."table"`.
3787
- * The fragment has no parameters, so a script takes it.
2977
+ * The fragment has no parameters, so `$script` takes it.
3788
2978
  * The name is not qualified by the PostgreSQL schema of the statement.
3789
2979
  */
3790
- declare function identifier(...names: [string, ...string[]]): UntypedExpression;
2980
+ declare function identifier$1(...names: [string, ...string[]]): UntypedExpression;
3791
2981
  /**
3792
2982
  * Creates an expression of a query parameter encoded with a type, for a value interpolated into `sql` or compared on its own.
3793
2983
  *
@@ -3806,4 +2996,4 @@ declare function param<E extends AnyExpression, V extends (E extends AnyExpressi
3806
2996
  * A run of capital letters is one word, such as `user_id` for `userID`, and digits stay in their word, such as `line2`.
3807
2997
  */
3808
2998
  declare function toSnakeCase(key: string): string;
3809
- export { TestHooks as $, TypeOptions as $i, Ordering as $n, EqualityOperators as $r, MutationQueryState as $t, AnyExpression as A, Table as Ai, literal as An, PrimaryKeyValues as Ar, SchemaTables as At, DbOf as B, ResultMode as Bi, count as Bn, and as Br, DecodedFields as Bt, TextConversionSignature as C, AnyTableKeys as Ci, NestedQuery as Cn, SelectedOperandType as Cr, UsedRelation as Ct, textOperators as D, ColumnValues as Di, SelectionResult as Dn, KeyCheck as Dr, Schema as Dt, TextTypeOperators as E, ColumnShape as Ei, SelectionFieldTypes as En, GroupTerms as Er, AnySchema as Et, UntypedExpression as F, createTableFactory as Fi, GroupValue as Fn, WhereValues as Fr, RecordQueryState as Ft, TransactionOptions as G, SqlStatement as Gi, some as Gn, OneRow as Gr, AnyMutationQuery as Gt, Database as H, Connection as Hi, every as Hn, or as Hr, InitialSqlQueryState as Ht, AnyDb as I, defineTable as Ii, StringAggOptions as In, CombinedCondition as Ir, SelectionState as It, OpenedTestFixture as J, BaseType as Ji, OrderColumns as Jn, ResultByRows as Jr, ConflictTarget as Jt, createDatabase as K, createStatement as Ki, stringAgg as Kn, OneValueRows as Kr, ConflictActionRequired as Kt, BindOptions as L, NotFoundError as Li, UnfilteredAggregateOptions as Ln, Condition as Lr, AnyQuery as Lt, Expression as M, TableKeys as Mi, AggregateOptions as Mn, WhereCallback as Mr, defineSchema as Mt, ExpressionOperators as N, TableOptions as Ni, CountExpression as Nn, WhereCondition as Nr, AnyRecordQuery as Nt, NumberTypeOperators as O, KeyColumns as Oi, SelectionUses as On, NotAKey as Or, SchemaPart as Ot, TypedExpression as P, ToColumns as Pi, GroupAggregateExpression as Pn, WhereFilter as Pr, RecordQuery as Pt, TestHelpers as Q, TypeOperators as Qi, OrderTerms as Qn, EqualityOperator as Qr, MutationQuery as Qt, Db as R, RequiredRelationError as Ri, UnfilteredStringAggOptions as Rn, ConditionOperand as Rr, SelectQueryKind as Rt, PatternSignature as S, AnyTable as Si, MergeSelection as Sn, GroupedState as Sr, UsableRelation as St, TextOperators as T, ColumnOperators as Ti, Selection as Tn, GroupTerm as Tr, one as Tt, DatabaseOptions as U, Driver as Ui, max as Un, ExistsValueType as Ur, SqlQuery as Ut, DbQueryState as V, ResultRows as Vi, countDistinct as Vn, not as Vr, FieldTypes as Vt, IsolationLevel as W, DriverResult as Wi, min as Wn, FilteredRows as Wr, SqlQueryState as Wt, TestFixture as X, Type as Xi, OrderKey as Xn, CountValueType as Xr, InitialMutationState as Xt, PendingTestFixture as Y, TextValue as Yi, OrderDirection as Yn, ValueRows as Yr, InitialInsertState as Yt, TestFixtureOptions as Z, TypeInput as Zi, OrderTerm as Zn, CompileOptions as Zr, InsertMutationState as Zt, DriverErrorFields as _, QueryStateOf as _i, ExpressionValue as _n, UpdateValues as _r, RequiredMember as _t, sql as a, ColumnAttributes as aa, Operand as ai, CaseValue as an, QueryContext as ar, TransformedQuery as at, FALSE as b, SingletonQueryState as bi, GroupedField as bn, FoundQueryState as br, TableContext as bt, MatchResult as c, BoundOperators as ca, OperandUses as ci, TypedOperand as cn, BoundSelectQuery as cr, MergeRelations as ct, defineExpression as d, OperatorDefinitions as da, ValuesQuery as di, caseWhen as dn, SingletonInsertMany as dr, Relation as dt, TypeOutput as ea, HasEquality as ei, Helper as en, SelectedRefs as er, TestTransactionOptions as et, QueryErrorCode as f, GenericOperator as fa, EmptyRecord as fi, coalesce as fn, from as fr, RelationDeclaration as ft, ConnectionError as g, QueryState as gi, ExpressionInput as gn, UpdateSet as gr, RelationKind as gt, TransactionConnectionError as h, defineGenericOperator as ha, InitialQueryState as hi, ColumnFieldTypes as hn, InsertValues as hr, RelationKeys as ht, param as i, Column as ia, ComparisonSignature as ii, CaseCondition as in, ColumnRefs as ir, SynchronousResult as it, BaseOperators as j, TableFactoryOptions as ji, AggregateExpression as jn, EqValue as jr, Tables as jt, orderingOperators as k, Selectable as ki, Literal as kn, PrimaryKeyColumn as kr, SchemaPartRelations as kt, NotAColumn as l, MergeOperators as la, ScalarQuery as li, TypedOperandInput as ln, ResultOf as lr, NoRelations as lt, isQueryError as m, OperatorSignature as ma, Grouped as mi, least as mn, ConflictUpdateSet as mr, RelationKey as mt, SqlTemplate as n, defineType as na, equalityOperators as ni, defineHelper as nn, desc as nr, AnyTransformedQuery as nt, ColumnRefKey as o, KeyKind as oa, OperandValue as oi, FollowingOperand as on, RelationRefs as or, TransformedQueryState as ot, QueryErrorCondition as p, GenericOperatorImplementation as pa, FoundKey as pi, greatest as pn, ColumnValue as pr, RelationDeclarations as pt, TransactionCoordinator as q, AnyType as qi, sum as qn, QueryResult as qr, ConflictKeyRequired as qt, identifier as r, AnyColumn as ra, BooleanResult as ri, CaseBranch as rn, orderBy as rr, NotSynchronous as rt, MatchCheck as s, ToColumn as sa, compare as si, NullSkippingResult as sn, AnySelectQuery as sr, DeclaredRelations as st, toSnakeCase as t, TypeTransform as ta, InSignature as ti, HelperEffect as tn, asc as tr, createTestHelpers as tt, matches as u, NoOperators as ua, TypedScalarQuery as ui, TypedOperandOperators as un, SelectQuery as ur, OneRelationKeys as ut, QueryError as v, QueryValueType as vi, GroupOperandValue as vn, UpsertValues as vr, SchemaContext as vt, TextLengthSignature as w, ColumnDefinitions as wi, SelectedFieldTypes as wn, RowLockOptions as wr, many as wt, TRUE as x, TableQueryState as xi, GroupedRecord as xn, FoundState as xr, TableRelations as xt, toDriverError as y, SelectQueryState as yi, GroupSelectionResult as yn, FilteredStateRows as yr, SchemaRelations as yt, DbMutationState as z, ResultDecodeError as zi, avg as zn, Predicate as zr, AnySqlQuery as zt };
2999
+ export { matches as $, TypeInput as $i, UnfilteredAggregateOptions as $n, Condition as $r, Tables as $t, SqlQueryResult as A, QueryValueType as Ai, least as An, ConflictUpdateSet as Ar, MergeRelations as At, createDatabase as B, KeyColumns as Bi, SelectedFieldTypes as Bn, RowLockOptions as Br, SchemaContext as Bt, ResultByRows$1 as C, ValuesQuery as Ci, NullSkippingResult as Cn, AnySelectQuery as Cr, bindSchema as Ct, SessionOptions$1 as D, InitialQueryState as Di, caseWhen as Dn, SingletonInsertMany as Dr, TransformedQuery as Dt, ResultRows$1 as E, Grouped as Ei, TypedOperandOperators as En, SelectQuery as Er, SynchronousResult as Et, TransactionConnectionError as F, AnyTableKeys as Fi, GroupSelectionResult as Fn, FilteredStateRows as Fr, RelationDeclarations as Ft, SqlTemplate as G, TableOptions as Gi, Literal as Gn, PrimaryKeyColumn as Gr, UsedRelation as Gt, isQueryError as H, Table as Hi, SelectionFieldTypes as Hn, GroupTerms as Hr, TableContext as Ht, TransactionOptions$1 as I, ColumnDefinitions as Ii, GroupedField as In, FoundQueryState as Ir, RelationKey as It, sql as J, defineTable as Ji, AggregateOptions as Jn, WhereCallback as Jr, AnySchema as Jt, identifier$1 as K, ToColumns as Ki, literal as Kn, PrimaryKeyValues as Kr, many as Kt, TypeOptions$1 as L, ColumnOperators as Li, GroupedRecord as Ln, FoundState as Lr, RelationKeys as Lt, SqlStatement$1 as M, SingletonQueryState as Mi, ExpressionInput as Mn, UpdateSet as Mr, OneRelationKeys as Mt, SqlValue as N, TableQueryState as Ni, ExpressionValue as Nn, UpdateValues as Nr, Relation as Nt, SqlFragment$2 as O, QueryState as Oi, coalesce as On, from as Or, TransformedQueryState as Ot, TextValue as P, AnyTable as Pi, GroupOperandValue as Pn, UpsertValues as Pr, RelationDeclaration as Pt, NotAColumn as Q, Type as Qi, StringAggOptions as Qn, CombinedCondition as Qr, SchemaTables as Qt, TypeTransform$1 as R, ColumnShape as Ri, MergeSelection as Rn, GroupedState as Rr, RelationKind as Rt, QueryErrorCondition as S, TypedScalarQuery as Si, FollowingOperand as Sn, RelationRefs as Sr, DbQueryState as St, ResultMode$1 as T, FoundKey as Ti, TypedOperandInput as Tn, ResultOf as Tr, NotSynchronous as Tt, toDriverError as U, TableFactoryOptions as Ui, SelectionResult as Un, KeyCheck as Ur, TableRelations as Ut, createStatement$1 as V, Selectable as Vi, Selection as Vn, GroupTerm as Vr, SchemaRelations as Vt, toSnakeCase as W, TableKeys as Wi, SelectionUses as Wn, NotAKey as Wr, UsableRelation as Wt, MatchCheck as X, AnyType as Xi, GroupAggregateExpression as Xn, WhereFilter as Xr, SchemaPart as Xt, ColumnRefKey as Y, RequiredRelationError as Yi, CountExpression as Yn, WhereCondition as Yr, Schema as Yt, MatchResult as Z, BaseType as Zi, GroupValue as Zn, WhereValues as Zr, SchemaPartRelations as Zt, OneRow$1 as _, Operand as _i, HelperEffect as _n, asc as _r, AnyDb as _t, Database$1 as a, ColumnAttributes as aa, ExistsValueType as ai, AnyQuery as an, max as ar, TextLengthSignature as at, QueryError as b, OperandUses as bi, CaseCondition as bn, ColumnRefs as br, DbMutationState as bt, DerivableType$1 as c, BoundOperators as ca, CountValueType as ci, ConflictActionRequired as cn, stringAgg as cr, textOperators as ct, DriverErrorFields as d, OperatorDefinitions as da, EqualityOperators as di, InitialInsertState as dn, OrderDirection as dr, AnyExpression as dt, TypeOperators as ea, ConditionOperand as ei, defineSchema as en, UnfilteredStringAggOptions as er, defineExpression as et, DriverResult as f, GenericOperator as fa, HasEquality as fi, InitialMutationState as fn, OrderKey as fr, BaseOperators as ft, NotFoundError$1 as g, ComparisonSignature as gi, Helper as gn, SelectedRefs as gr, UntypedExpression as gt, IsolationLevel as h, defineGenericOperator as ha, BooleanResult as hi, MutationQueryState as hn, Ordering as hr, TypedExpression as ht, ConnectionError as i, Column as ia, or as ii, SelectionState as in, every as ir, TextConversionSignature as it, SqlQueryState as j, SelectQueryState as ji, ColumnFieldTypes as jn, InsertValues as jr, NoRelations as jt, SqlQuery$1 as k, QueryStateOf as ki, greatest as kn, ColumnValue as kr, DeclaredRelations as kt, DerivableTypeWithParameters as l, MergeOperators as la, CompileOptions as li, ConflictKeyRequired as ln, sum as lr, NumberTypeOperators as lt, InitialSqlQueryState$1 as m, OperatorSignature as ma, equalityOperators as mi, MutationQuery as mn, OrderTerms as mr, ExpressionOperators as mt, BaseDerivableType as n, defineType$1 as na, and as ni, RecordQuery as nn, count as nr, TRUE as nt, DatabaseOptions as o, KeyKind as oa, FilteredRows as oi, SelectQueryKind as on, min as or, TextOperators as ot, FieldTypes as p, GenericOperatorImplementation as pa, InSignature as pi, InsertMutationState as pn, OrderTerm as pr, Expression as pt, param as q, createTableFactory as qi, AggregateExpression as qn, EqValue as qr, one as qt, Connection as r, AnyColumn as ra, not as ri, RecordQueryState as rn, countDistinct as rr, PatternSignature as rt, DecodedFields as s, ToColumn as sa, QueryResult as si, AnyMutationQuery as sn, some as sr, TextTypeOperators as st, AnySqlQuery$1 as t, TypeOutput as ta, Predicate as ti, AnyRecordQuery as tn, avg as tr, FALSE as tt, Driver as u, NoOperators as ua, EqualityOperator as ui, ConflictTarget as un, OrderColumns as ur, orderingOperators as ut, OneValueRows$1 as v, OperandValue as vi, defineHelper as vn, desc as vr, BindOptions as vt, ResultDecodeError$1 as w, EmptyRecord as wi, TypedOperand as wn, BoundSelectQuery as wr, AnyTransformedQuery as wt, QueryErrorCode as x, ScalarQuery as xi, CaseValue as xn, QueryContext as xr, DbOf as xt, PollLockOptions$1 as y, compare as yi, CaseBranch as yn, orderBy as yr, Db as yt, ValueRows$1 as z, ColumnValues as zi, NestedQuery as zn, SelectedOperandType as zr, RequiredMember as zt };