kern-orm 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2091 @@
1
+ declare const operatorSignature: unique symbol;
2
+ /** Runtime mark of generic operators. */
3
+ declare const genericOperatorBrand: unique symbol;
4
+ /**
5
+ * Signature of a generic operator: its method on an expression of values `T` that accepts compared values `I`.
6
+ *
7
+ * An interface extending it declares `method` with `this["T"]` and `this["I"]`, such as `(value: Operand<this["T"], this["I"]>) => Expression<boolean>`.
8
+ */
9
+ interface OperatorSignature {
10
+ readonly T: unknown;
11
+ readonly I: unknown;
12
+ readonly method: (...args: any[]) => unknown;
13
+ }
14
+ /**
15
+ * Method of signature `S` on an expression of values `T` accepting values `I`.
16
+ *
17
+ * A signature reads the value types from `this`, because TypeScript cannot instantiate a generic function type with type arguments.
18
+ */
19
+ type ApplySignature<S extends OperatorSignature, T, I> = (S & {
20
+ readonly T: T;
21
+ readonly I: I;
22
+ })["method"];
23
+ /** Implementation of a generic operator of signature `S`: the expression it is called on, followed by the call arguments. */
24
+ type GenericOperatorImplementation<S extends OperatorSignature, Self extends AnyExpression = AnyExpression> = (self: Self, ...args: Parameters<ApplySignature<S, unknown, unknown>>) => ReturnType<ApplySignature<S, unknown, unknown>>;
25
+ /** Operator created by `defineGenericOperator`, whose method has signature `S` on the expression it is called on. */
26
+ interface GenericOperator<S extends OperatorSignature, Self extends AnyExpression = AnyExpression> extends GenericOperatorImplementation<S, Self>, GenericOperatorSignature<S> {}
27
+ /** Inference metadata of a generic operator, independent of its callable implementation. */
28
+ interface GenericOperatorSignature<S extends OperatorSignature> {
29
+ readonly [genericOperatorBrand]: true;
30
+ /** Signature for type inference; absent at runtime. */
31
+ readonly [operatorSignature]?: S;
32
+ }
33
+ /**
34
+ * Defines a generic operator: one definition for every type, which works with the values of the expression it is called on.
35
+ *
36
+ * It receives the expression with its own type, including a type derived with `transform`, and its method has signature `S` with the value types of the expression, such as `lt` of `orderingOperators`.
37
+ * An operator defined as a plain function works with the values of the type it was added to instead.
38
+ * `Self` restricts the types it can be added to with `withOperators`; derived types keep the operator after `transform`.
39
+ */
40
+ declare function defineGenericOperator<S extends OperatorSignature, Self extends AnyExpression = AnyExpression>(implementation: GenericOperatorImplementation<S>): GenericOperator<S, Self>;
41
+ /** Operator implementations by name; each receives the expression it is called on, followed by the call arguments. */
42
+ type OperatorDefinitions<Self = any> = Record<string, (self: Self, ...args: any[]) => unknown>;
43
+ /** Empty set of operators, of an expression with the base operators only. */
44
+ type NoOperators = Record<never, never>;
45
+ /** Operators `O` replacing operators of `A` with the same names. */
46
+ type MergeOperators<A extends OperatorDefinitions, O extends OperatorDefinitions> = Omit<A, keyof O> & O;
47
+ /** Operator methods of an expression of type `T` accepting values of type `I`, without the expression parameter of their definitions. */
48
+ type BoundOperators<O extends OperatorDefinitions, T, I = T> = { [K in keyof O]: O[K] extends GenericOperatorSignature<infer S> ? ApplySignature<S, T, I> : O[K] extends ((self: any, ...args: infer A) => infer R) ? (...args: A) => R : never; };
49
+ /** Kind of a key of a table: its primary key, or a unique key. */
50
+ type KeyKind = "primaryKey" | "unique";
51
+ /**
52
+ * Type that `primaryKey()` of a type or a column whose values may be `null` is checked against, naming the reason.
53
+ *
54
+ * Without `strictNullChecks`, `null` belongs to every type, so every column looks nullable; the type then names the option instead.
55
+ */
56
+ type NullablePrimaryKey = null extends string ? StrictNullChecksRequired : NullableKeyColumn;
57
+ /** Type that `NullablePrimaryKey` names for a column whose type is nullable. */
58
+ interface NullableKeyColumn {
59
+ readonly "primary key columns must not be nullable": never;
60
+ }
61
+ /** Type that `NullablePrimaryKey` names without `strictNullChecks`. */
62
+ interface StrictNullChecksRequired {
63
+ readonly "kern-orm requires strictNullChecks": never;
64
+ }
65
+ /**
66
+ * Attributes that a column adds to its type in a table.
67
+ *
68
+ * `Key` is the kind of the key that the column forms alone, or `undefined` for none, and `Default` tells whether the database gives the column a value when an insert omits it.
69
+ */
70
+ interface ColumnAttributes<Key extends KeyKind | undefined = KeyKind | undefined, Default extends boolean = boolean> {
71
+ /** Physical column name; the column key is used when it is not set. */
72
+ readonly name: string | undefined;
73
+ readonly keyKind: Key;
74
+ /** Whether the database gives the column a value when an insert omits it, such as by `DEFAULT` or an identity. */
75
+ readonly hasDefault: Default;
76
+ }
77
+ /**
78
+ * Column of a table: a type with column attributes, forming a key of kind `Key` alone, or no key for `undefined`, with a value of the database when an insert omits it if `Default` is `true`.
79
+ *
80
+ * A column is not a type, so SQL fragments and parameters reject it; its methods add attributes and return a new column.
81
+ */
82
+ declare class Column<T extends AnyType, Key extends KeyKind | undefined = KeyKind | undefined, Default extends boolean = boolean> {
83
+ readonly type: T;
84
+ readonly attributes: ColumnAttributes<Key, Default>;
85
+ constructor(type: T, attributes: ColumnAttributes<Key, Default>);
86
+ /** Uses a physical column name different from the column key. */
87
+ columnName(name: string): Column<T, Key, Default>;
88
+ /** Marks the column as the primary key; the type must not be nullable. */
89
+ primaryKey(this: null extends TypeOutput<T> ? NullablePrimaryKey : Column<T, undefined, Default>): Column<T, "primaryKey", Default>;
90
+ /** Marks the column as a unique key. */
91
+ unique(this: Column<T, undefined, Default>): Column<T, "unique", Default>;
92
+ /** Marks the column as one that the database gives a value when an insert omits it, such as by `DEFAULT` or an identity, so that inserts may omit it. */
93
+ hasDefault(): Column<T, Key, true>;
94
+ }
95
+ /** Column of any type. */
96
+ type AnyColumn = Column<any>;
97
+ /** Column of a column definition: the column itself, or a column of a type without attributes. */
98
+ 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
+ declare const typeBrand: unique symbol;
102
+ /**
103
+ * SQL type: a PostgreSQL type, the JavaScript representation of its values, and the operators of its expressions.
104
+ *
105
+ * A type is shared by columns, parameters, and SQL expressions, so the same value is encoded and decoded identically everywhere.
106
+ * In a table, a type is a column; `columnName`, `primaryKey`, `unique`, and `hasDefault` create a column of the type with these attributes.
107
+ * A type with PostgreSQL type parameters, such as the length of `varchar(255)`, has `with`.
108
+ */
109
+ type Type<Output, Input = Output, Operators extends OperatorDefinitions = NoOperators, Parameters extends unknown[] | undefined = undefined> = BaseType<Output, Input, Operators, Parameters> & (Parameters extends unknown[] ? TypeWithParameters<Output, Input, Operators, Parameters> : unknown);
110
+ /** Members of every type; see `Type`. */
111
+ interface BaseType<Output, Input, Operators extends OperatorDefinitions, Parameters extends unknown[] | undefined> {
112
+ readonly [typeBrand]: true;
113
+ /** Value types for type inference; absent at runtime. */
114
+ readonly [typeValues]: {
115
+ output: Output;
116
+ input: Input;
117
+ operators: Operators;
118
+ };
119
+ /** SQL type name used in DDL, such as `numeric` or `vector(1536)`. */
120
+ readonly sqlType: string;
121
+ /**
122
+ * SQL type name that `param` casts its parameters to, such as `numeric` for `numeric(10,2)`.
123
+ *
124
+ * It omits type parameters, so that their precision, scale, or length do not constrain a parameter.
125
+ */
126
+ readonly castType: string;
127
+ /** Operators of expressions of this type, in addition to `isNull` or replacing it. */
128
+ 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
+ /**
135
+ * Creates a type whose expressions also have `operators`.
136
+ *
137
+ * An operator replaces a base or previously added operator with the same name.
138
+ * An operator defined as a function receives expressions of this type, as typed, even on the types derived from the created one, so that its arguments keep the encoding of this type.
139
+ * A generic operator from `defineGenericOperator`, such as `lt` of `orderingOperators`, receives the expression with its own type instead.
140
+ * An operator must not be named `then`, which would make expressions thenable.
141
+ */
142
+ withOperators<O extends OperatorDefinitions<Expression<Output, Operators, Input>>>(operators: O): Type<Output, Input, MergeOperators<Operators, O>, Parameters>;
143
+ /**
144
+ * Creates a type that accepts PostgreSQL type parameters with `with`.
145
+ *
146
+ * `format` returns the SQL type name with the parameters, such as `vector(1536)` for `1536`.
147
+ */
148
+ withParameters<P extends unknown[]>(format: (...parameters: P) => string): Type<Output, Input, Operators, P>;
149
+ /**
150
+ * Creates a type with another representation of the values of this type, keeping its SQL type, operators, and nullability.
151
+ *
152
+ * `decode` receives the values that this type decodes from values other than `NULL`, including `undefined` that an earlier decoder returns, and returns a value other than `null`; `encode` returns values that this type encodes; `NULL` stays `null` without them.
153
+ */
154
+ transform<NewOutput extends {} | undefined, NewInput>(options: TypeTransform<Exclude<Output, null>, NonNullable<Input>, NewOutput, NewInput>): Type<NewOutput | Extract<Output, null>, NewInput | Extract<Input, null>, Operators, Parameters>;
155
+ /** Creates a type that decodes the values of this type into another representation, other than `null`, and accepts the values that this type accepts. */
156
+ transform<NewOutput extends {} | undefined>(options: {
157
+ decode: (value: Exclude<Output, null>) => NewOutput;
158
+ }): Type<NewOutput | Extract<Output, null>, Input, Operators, Parameters>;
159
+ nullable(): Type<Output | null, Input | null, Operators, Parameters>;
160
+ /** Creates a column of this type with a physical name different from the column key. */
161
+ columnName(name: string): Column<Type<Output, Input, Operators, Parameters>, undefined, false>;
162
+ /** Creates a primary key column of this type; the type must not be nullable. */
163
+ primaryKey(this: null extends Output ? NullablePrimaryKey : Type<Output, Input, Operators, Parameters>): Column<Type<Output, Input, Operators, Parameters>, "primaryKey", false>;
164
+ /** Creates a column of this type that is a unique key. */
165
+ unique(): Column<Type<Output, Input, Operators, Parameters>, "unique", false>;
166
+ /** Creates a column of this type that the database gives a value when an insert omits it, such as by `DEFAULT` or an identity, so that inserts may omit it. */
167
+ hasDefault(): Column<Type<Output, Input, Operators, Parameters>, undefined, true>;
168
+ }
169
+ /** Members of a type with PostgreSQL type parameters; see `Type`. */
170
+ interface TypeWithParameters<Output, Input, Operators extends OperatorDefinitions, Parameters extends unknown[]> {
171
+ /** Creates this type with PostgreSQL type parameters, such as `varchar.with(255)` for `varchar(255)`; other changes of the type are kept. */
172
+ with(...parameters: Parameters): Type<Output, Input, Operators, Parameters>;
173
+ }
174
+ /** Conversion between the values of a type and their new representation. */
175
+ interface TypeTransform<Output, Input, NewOutput, NewInput> {
176
+ decode: (value: Output) => NewOutput;
177
+ encode: (value: NewInput) => Input;
178
+ }
179
+ /** Type of any values, operators, and parameters. */
180
+ type AnyType = Type<any, any, any, any>;
181
+ /** PostgreSQL text representation of a value, as types encode and decode it; `null` is SQL `NULL`. */
182
+ type TextValue = string | null;
183
+ /** Values that a type decodes. */
184
+ type TypeOutput<T extends AnyType> = T[typeof typeValues]["output"];
185
+ /** Values that a type encodes. */
186
+ type TypeInput<T extends AnyType> = T[typeof typeValues]["input"];
187
+ /** Operators of the expressions of a type. */
188
+ type TypeOperators<T extends AnyType> = T[typeof typeValues]["operators"];
189
+ /** Type definition. */
190
+ interface TypeOptions {
191
+ /** SQL type name, such as `ltree`; `withParameters` adds type parameters to it, and a name with them requires `castType`. */
192
+ sqlType: string;
193
+ /** SQL type name that `param` casts parameters to when `sqlType` constrains values, such as `bpchar` for `char`, whose length is 1. */
194
+ castType?: string;
195
+ }
196
+ /**
197
+ * Defines a type whose values are the PostgreSQL text representations as they are.
198
+ *
199
+ * `transform` converts them to other values, such as `number[]` for `vector`.
200
+ */
201
+ declare function defineType(options: TypeOptions): Type<string>;
202
+ /** SQL statement ready for a driver. */
203
+ interface SqlStatement {
204
+ readonly text: string;
205
+ /** Text representations of the parameters; PostgreSQL infers their types from the statement text. */
206
+ readonly parameters: readonly TextValue[];
207
+ }
208
+ /** Creates a statement from SQL text and the text representations of its parameters, such as `createStatement("BEGIN")`. */
209
+ declare function createStatement(text: string, parameters?: readonly TextValue[]): SqlStatement;
210
+ /** Result of a statement. */
211
+ interface DriverResult {
212
+ /** Command tag that PostgreSQL completed the statement with, such as `SELECT` or `ROLLBACK` for a `COMMIT` of a failed transaction. */
213
+ readonly command: string;
214
+ /** Number of rows that the command tag reports, such as the rows that an `UPDATE` changes, also without `RETURNING`; `0` for a command without one, such as `BEGIN`. */
215
+ readonly count: number;
216
+ /** Names of the result columns in their order, also when the statement returns no rows; none for a statement without result columns, such as `BEGIN` or an `UPDATE` without `RETURNING`. */
217
+ readonly columns: readonly string[];
218
+ /** Rows as PostgreSQL text representations of their values, in the order of the result columns. */
219
+ readonly rows: readonly (readonly TextValue[])[];
220
+ }
221
+ /**
222
+ * Physical database access: transport, pooling, and connections.
223
+ *
224
+ * 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.
225
+ */
226
+ interface Driver {
227
+ /** Executes a statement on any pooled connection. */
228
+ execute(statement: SqlStatement): Promise<DriverResult>;
229
+ /** Executes a script of statements without parameters, such as DDL separated by semicolons, on any pooled connection, where PostgreSQL runs them in one implicit transaction. */
230
+ executeScript(text: string): Promise<void>;
231
+ /** Reserves a dedicated connection, such as for a transaction. */
232
+ acquire(): Promise<Connection>;
233
+ /** Closes the connections once the transactions on reserved connections end. */
234
+ close(): Promise<void>;
235
+ }
236
+ /** Connection reserved by a driver, such as for a transaction. */
237
+ interface Connection {
238
+ /**
239
+ * Executes a statement on the connection.
240
+ *
241
+ * Statements and scripts run one at a time in the order of calls, so a statement sent before `COMMIT` or `ROLLBACK` completes before it.
242
+ */
243
+ execute(statement: SqlStatement): Promise<DriverResult>;
244
+ /** Executes a script of statements without parameters on the connection, in the order of calls with its statements. */
245
+ executeScript(text: string): Promise<void>;
246
+ /**
247
+ * Returns the connection to the pool after a transaction on it.
248
+ *
249
+ * Without `failure`, the transaction ended with a completed `COMMIT` or `ROLLBACK`, and the connection is idle.
250
+ * With `failure`, its `BEGIN`, `COMMIT`, or `ROLLBACK` failed, so the transaction may still be open: the driver returns the connection to the pool only once it is idle, and never returns a connection it lost.
251
+ */
252
+ release(failure?: TransactionFailure): void | Promise<void>;
253
+ }
254
+ /** Failure of the statement that started or ended a transaction on a connection. */
255
+ interface TransactionFailure {
256
+ readonly error: unknown;
257
+ }
258
+ /** Field of a compiled result: the key of a record and how its value is decoded. */
259
+ type ResultField = ScalarField | NestedField;
260
+ /** Field of a value decoded by its type from its PostgreSQL text representation. */
261
+ interface ScalarField {
262
+ readonly key: string;
263
+ readonly type: AnyType;
264
+ readonly nested?: undefined;
265
+ }
266
+ /**
267
+ * Field of the rows of a nested query packed as JSON, decoded by the result plan of that query.
268
+ *
269
+ * Rows `many` are an array of packed rows, and the other rows modes are one packed row or `null` without a row.
270
+ * A packed row is an array of the values of its fields in their order: the PostgreSQL text representation of a scalar or `null` for SQL `NULL`, and JSON for nested rows.
271
+ */
272
+ interface NestedField {
273
+ readonly key: string;
274
+ readonly nested: ResultPlan;
275
+ }
276
+ /**
277
+ * How a query returns its rows: `many` as an array; `one` as one row, rejecting without it; `nullable` as one row or `null` without it; `optional` as one row or `undefined` without it.
278
+ *
279
+ * Without a row, a query of rows `one` rejects with `NotFoundError`, executed or nested, or with `RequiredRelationError` when a required relation guarantees the row.
280
+ * This mode does not imply a SQL limit: `take` and `get` add `LIMIT 1` only when they change `many` to `one`.
281
+ */
282
+ type ResultRows = "many" | "one" | "nullable" | "optional";
283
+ /** How the rows of a query become its result, apart from its fields. */
284
+ interface ResultMode {
285
+ readonly rows: ResultRows;
286
+ /** A row is the value of its only field instead of a record. */
287
+ readonly value: boolean;
288
+ }
289
+ /** Fields of the rows of a query and how its rows become its result. */
290
+ interface ResultPlan extends ResultMode {
291
+ /** Fields of a row, in the order of its values. */
292
+ readonly fields: readonly ResultField[];
293
+ /** Required relation that guarantees the row of nested rows `one`, such as `field.form`, whose missing row is a `RequiredRelationError` rather than a `NotFoundError`. */
294
+ readonly guaranteedBy?: string | undefined;
295
+ }
296
+ /** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
297
+ declare class NotFoundError extends Error {
298
+ readonly name = "NotFoundError";
299
+ /** 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. */
300
+ readonly path: string | undefined;
301
+ constructor(message: string, path?: string);
302
+ }
303
+ /**
304
+ * Error thrown when a required relation, such as `field.form`, has no record for a row.
305
+ *
306
+ * A required relation promises the record, so its absence means that the database breaks the promise, such as without a foreign key, or that the relation should not be required.
307
+ */
308
+ declare class RequiredRelationError extends Error {
309
+ /** Relation by the key of its table and its name, such as `field.form`. */
310
+ readonly relation: string;
311
+ /** 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`. */
312
+ readonly path: string;
313
+ readonly name = "RequiredRelationError";
314
+ constructor(
315
+ /** Relation by the key of its table and its name, such as `field.form`. */
316
+ relation: string,
317
+ /** 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`. */
318
+ path: string);
319
+ }
320
+ /** Error thrown when a row does not match the result fields or a value fails to decode; the failure of the value is its cause. */
321
+ declare class ResultDecodeError extends Error {
322
+ /** Path of the value from its result field, such as `fields[2].label`, after the index of the row of an executed query of rows `many`, such as `[2].label`; `undefined` for a row of the driver of another width than the result fields. */
323
+ readonly path: string | undefined;
324
+ readonly name = "ResultDecodeError";
325
+ constructor(message: string,
326
+ /** Path of the value from its result field, such as `fields[2].label`, after the index of the row of an executed query of rows `many`, such as `[2].label`; `undefined` for a row of the driver of another width than the result fields. */
327
+ path: string | undefined, options?: ErrorOptions);
328
+ }
329
+ /** Tells whether `T` is `any`: only `any` turns `1 & T` into a type that `0` extends. */
330
+ type IsAny<T> = 0 extends 1 & T ? true : false;
331
+ /** Flattens an intersection of object types into one object type, so that editors show its fields; `any` stays `any`. */
332
+ type Simplify<T> = IsAny<T> extends true ? T : { [K in keyof T]: T[K]; } & {};
333
+ /** Tells whether `T` is a union of several types. */
334
+ type IsUnion<T, Whole = T> = T extends unknown ? ([Whole] extends [T] ? false : true) : false;
335
+ /** Column definitions by their keys: types or columns; a key must not start with `$`, which is reserved for members of column references in queries. */
336
+ type ColumnDefinitions = Record<string, AnyType | AnyColumn>;
337
+ /** Columns by their keys. */
338
+ type ColumnShape = Record<string, AnyColumn>;
339
+ /** Columns of column definitions, with a column of every type without attributes. */
340
+ type ToColumns<D extends ColumnDefinitions> = { [K in keyof D]: ToColumn<D[K]>; };
341
+ /** Column keys of a key of a table, in its order. */
342
+ type KeyColumns = readonly [string, ...string[]];
343
+ declare const keysType: unique symbol;
344
+ /**
345
+ * Keys of a table: its primary key, or `undefined` without one, and its other unique keys.
346
+ *
347
+ * This type does not tell which keys a table has, such as for a table typed as `Table<Name, Columns>`; `TableKeys` does.
348
+ */
349
+ interface AnyTableKeys {
350
+ readonly primaryKey: KeyColumns | undefined;
351
+ readonly unique: readonly KeyColumns[];
352
+ }
353
+ /** Keys of a table that its type tells: primary key `PrimaryKey`, or `undefined` without one, and each unique key of `UniqueKey`. */
354
+ interface TableKeys<PrimaryKey extends KeyColumns | undefined, UniqueKey extends KeyColumns> extends AnyTableKeys {
355
+ readonly [keysType]: (primaryKey: PrimaryKey, unique: UniqueKey) => readonly [PrimaryKey, UniqueKey];
356
+ }
357
+ /**
358
+ * Immutable table descriptor: physical name, columns, and keys.
359
+ *
360
+ * A table knows nothing about relations, schemas, or database connections, so the same table can belong to several schemas.
361
+ * Its object identity is the logical identity of the table.
362
+ */
363
+ interface Table<Name extends string = string, Columns extends ColumnShape = ColumnShape, Keys extends AnyTableKeys = AnyTableKeys> {
364
+ readonly kind: "table";
365
+ readonly name: Name;
366
+ readonly columns: Columns;
367
+ readonly keys: Keys;
368
+ }
369
+ /** Table of any name, columns, and keys. */
370
+ type AnyTable = Table<string, ColumnShape>;
371
+ /**
372
+ * Options of `defineTable` over column keys `Column`: the keys of several columns, whose columns are listed in their order.
373
+ *
374
+ * The columns of the primary key are of `PrimaryKeyColumn`.
375
+ */
376
+ interface TableOptions<Column extends string = string, PrimaryKeyColumn extends string = Column> {
377
+ /** Columns of a primary key of several columns; mark a primary key of one column with `primaryKey()`. */
378
+ readonly primaryKey?: readonly [PrimaryKeyColumn, PrimaryKeyColumn, ...PrimaryKeyColumn[]];
379
+ /** Unique keys of several columns; mark a unique key of one column with `unique()`. */
380
+ readonly unique?: readonly (readonly [Column, Column, ...Column[]])[];
381
+ }
382
+ /** Record shape returned when all columns of a table are selected. */
383
+ type Selectable<T extends AnyTable> = { [K in keyof T["columns"]]: TypeOutput<T["columns"][K]["type"]>; };
384
+ /** Input values of the types of the columns. */
385
+ type ColumnValues<T extends AnyTable> = { [K in keyof T["columns"]]: TypeInput<T["columns"][K]["type"]>; };
386
+ /** Operators of the expressions of a column. */
387
+ type ColumnOperators<T extends AnyTable, K extends keyof T["columns"]> = TypeOperators<T["columns"][K]["type"]>;
388
+ /**
389
+ * Tells whether columns `Columns`, a union of column keys, are exactly a key of table `T`, primary or unique, in any order.
390
+ *
391
+ * It is `boolean` when the type of `T` does not tell its keys.
392
+ * A union of tables, or of their keys, gives the union of their results.
393
+ */
394
+ type IsKey<T extends AnyTable, Columns> = T extends AnyTable ? KeysResult<T["keys"], Columns, "exact"> : never;
395
+ /** Tells whether columns `Columns`, a union of column keys, include a key of table `T`, primary or unique, as `IsKey` tells its results. */
396
+ type ContainsKey<T extends AnyTable, Columns> = T extends AnyTable ? KeysResult<T["keys"], Columns, "included"> : never;
397
+ /** Tells for each of keys `K` whether a key of them, primary or unique, matches columns `Columns` as `Match` tells: `"exact"` or `"included"`; `boolean` for keys whose type does not tell them. */
398
+ type KeysResult<K extends AnyTableKeys, Columns, Match> = K extends TableKeys<infer PrimaryKey, infer UniqueKey> ? [Match extends "exact" ? MatchingKey$1<NonNullable<PrimaryKey> | UniqueKey, Columns> : IncludedKey<NonNullable<PrimaryKey> | UniqueKey, Columns>] extends [never] ? false : true : boolean;
399
+ /** Union of the primary key and the unique keys of keys `K` of a table, or `never` where the type of `K` does not tell them. */
400
+ type KeyOf<K extends AnyTableKeys> = K extends TableKeys<infer PrimaryKey, infer UniqueKey> ? NonNullable<PrimaryKey> | UniqueKey : never;
401
+ /** `true` for each key of `Key` whose columns are exactly `Columns`. */
402
+ type MatchingKey$1<Key, Columns> = Key extends KeyColumns ? [Key[number]] extends [Columns] ? [Columns] extends [Key[number]] ? true : never : never : never;
403
+ /** `true` for each key of `Key` whose columns are among `Columns`. */
404
+ type IncludedKey<Key, Columns> = Key extends KeyColumns ? [Key[number]] extends [Columns] ? true : never : never;
405
+ /** Column key of columns `C` as a string, as object keys are at runtime. */
406
+ type ColumnKey<C extends ColumnShape> = `${keyof C & (string | number)}`;
407
+ /** Column key of columns `C` whose type is not nullable, as a string like `ColumnKey`. */
408
+ type NonNullableColumnKey<C extends ColumnShape> = { [K in keyof C]: null extends TypeOutput<C[K]["type"]> ? never : `${K & (string | number)}`; }[keyof C];
409
+ /** Column key of columns `C`, as a string like `ColumnKey`, whose column forms a key of kind `Kind` alone, as `KnownKeyKind` tells. */
410
+ type KeyedColumn<C extends ColumnShape, Kind> = { [K in keyof C]: KnownKeyKind<C[K]["attributes"]["keyKind"]> extends Kind ? `${K & (string | number)}` : never; }[keyof C];
411
+ /** Kind `Kind` of the key that a column forms alone, or `"unknown"` where the type of the column does not tell it. */
412
+ type KnownKeyKind<Kind> = [Kind] extends [undefined] ? undefined : [Kind] extends ["primaryKey"] ? "primaryKey" : [Kind] extends ["unique"] ? "unique" : "unknown";
413
+ /** Column keys that the primary key in the options of a table of columns `C` may list: none when a column is marked with `primaryKey()`. */
414
+ type PrimaryKeyOption<C extends ColumnShape> = [KeyedColumn<C, "primaryKey">] extends [never] ? NonNullableColumnKey<C> : never;
415
+ /**
416
+ * Keys of a table of columns `C` and options `O`, as `defineTable` defines them, or `AnyTableKeys` where the types do not tell them.
417
+ *
418
+ * The types do not tell them for a column whose type does not tell its key, such as `Column<T>`, for several columns marked with `primaryKey()`, which `defineTable` rejects, and for options whose keys are not tuples of single column keys, such as a variable of type `TableOptions` or a union in a key or in the list of unique keys.
419
+ * A union of options, which may include `undefined`, gives the union of their keys.
420
+ */
421
+ type DefinedKeys<C extends ColumnShape, O> = O extends unknown ? [KeyedColumn<C, "unknown">] extends [never] ? true extends IsUnion<KeyedColumn<C, "primaryKey">> ? AnyTableKeys : KeysOf<C, OptionPrimaryKey<O>, OptionUniqueKey<O>> : AnyTableKeys : never;
422
+ /** Keys of a table of columns `C` with primary key `PrimaryKey` and unique keys `UniqueKey` of its options, which are `"unknown"` where their types do not tell them. */
423
+ type KeysOf<C extends ColumnShape, PrimaryKey, UniqueKey> = "unknown" extends PrimaryKey | UniqueKey ? AnyTableKeys : KnownKeysOf<DefinedPrimaryKey<C, PrimaryKey>, DefinedUniqueKey<C, UniqueKey>>;
424
+ /** Keys that a table type tells, with its primary key and unique keys computed before they become arguments of `TableKeys`. */
425
+ type KnownKeysOf<PrimaryKey extends KeyColumns | undefined, UniqueKey extends KeyColumns> = [PrimaryKey] extends [unknown] ? TableKeys<PrimaryKey, UniqueKey> : never;
426
+ /** Primary key of a table of columns `C`: `PrimaryKey` of its options, or of the column marked with `primaryKey()`, or `undefined`. */
427
+ type DefinedPrimaryKey<C extends ColumnShape, PrimaryKey> = PrimaryKey extends KeyColumns ? PrimaryKey : [KeyedColumn<C, "primaryKey">] extends [never] ? undefined : SingleColumnKey<KeyedColumn<C, "primaryKey">>;
428
+ /** Unique key of a table of columns `C`: `UniqueKey` of its options, or of a column marked with `unique()`. */
429
+ type DefinedUniqueKey<C extends ColumnShape, UniqueKey> = Extract<UniqueKey, KeyColumns> | SingleColumnKey<KeyedColumn<C, "unique">>;
430
+ /** Key of each single column of `K`. */
431
+ type SingleColumnKey<K> = K extends string ? readonly [K] : never;
432
+ /** Primary key in options `O`: `undefined` without one, or `"unknown"` where its type does not tell it. */
433
+ type OptionPrimaryKey<O> = [O["primaryKey" & keyof O]] extends [undefined] ? undefined : O extends {
434
+ readonly primaryKey: infer Key;
435
+ } ? IsExactKey<Key> extends true ? Key : "unknown" : "unknown";
436
+ /** Unique key in options `O`, `never` without them, or `"unknown"` where their type does not tell them. */
437
+ type OptionUniqueKey<O> = [O["unique" & keyof O]] extends [undefined] ? never : O extends {
438
+ readonly unique: infer Keys extends readonly unknown[];
439
+ } ? true extends IsUnion<Keys> ? "unknown" : number extends Keys["length"] ? "unknown" : true extends { [I in keyof Keys]: IsExactKey<Keys[I]> extends true ? false : true; }[number] ? "unknown" : Keys[number] : "unknown";
440
+ /** Tells whether key `K` is one tuple of fixed length with one column key in each position, rather than a union. */
441
+ type IsExactKey<K> = true extends IsUnion<K> ? false : K extends readonly unknown[] ? number extends K["length"] ? false : true extends { [I in keyof K]: IsUnion<K[I]>; }[number] ? false : true : false;
442
+ /**
443
+ * Defines a table; a type without column attributes becomes a column as it is.
444
+ *
445
+ * A key of one column is marked on its column.
446
+ */
447
+ declare function defineTable<Name extends string, Definitions extends ColumnDefinitions>(name: Name, definitions: Definitions): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, undefined>>;
448
+ /**
449
+ * Defines a table; a type without column attributes becomes a column as it is.
450
+ *
451
+ * A key of one column is marked on its column, and `options` list the columns of the keys of several columns.
452
+ */
453
+ declare function defineTable<Name extends string, Definitions extends ColumnDefinitions, const Options extends TableOptions<ColumnKey<ToColumns<Definitions>>, PrimaryKeyOption<ToColumns<Definitions>>> | undefined>(name: Name, definitions: Definitions, options: Options): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, Options>>;
454
+ /** Physical placement of the tables of a query, fixed at compilation. */
455
+ interface CompileOptions {
456
+ /** PostgreSQL schema qualifying every table; tables stay unqualified when it is not set. */
457
+ schemaName?: string;
458
+ }
459
+ /** Value compared with an expression of type `T` accepting values of type `I`; `null` is matched with `isNull` instead. */
460
+ type Operand<T, I = T> = NonNullable<I> | AnyExpression<NonNullable<T> | null>;
461
+ /** SQL value of an operand, unwrapping an expression. */
462
+ type OperandValue<V> = V extends AnyExpression<infer T> ? T : V;
463
+ /** Boolean result that can be NULL when an input value can be NULL. */
464
+ type BooleanResult<T> = boolean | (null extends T ? null : never);
465
+ /** Signature of a generic operator comparing an expression with an operand of its type, such as `lt`. */
466
+ interface ComparisonSignature extends OperatorSignature {
467
+ readonly method: <V extends Operand<this["T"], this["I"]>>(value: V) => Expression<BooleanResult<this["T"] | OperandValue<V>>>;
468
+ }
469
+ /**
470
+ * Compares an expression with a value or another expression, encoding a plain value with the type of the expression.
471
+ *
472
+ * Operators of custom types build comparisons with it, such as `compare(self, "ILIKE", pattern)`.
473
+ */
474
+ declare function compare<T, V>(self: AnyExpression<T>, operator: ComparisonNode["operator"], value: V): Expression<BooleanResult<T | OperandValue<V>>>;
475
+ /** Runtime mark of the operators of `equalityOperators`, which tell that a type has SQL `=`. */
476
+ declare const equalityBrand: unique symbol;
477
+ /** Generic operator of `equalityOperators`, which gives the type it is added to SQL `=`. */
478
+ interface EqualityOperator<S extends OperatorSignature> extends GenericOperator<S> {
479
+ readonly [equalityBrand]: true;
480
+ }
481
+ /** Signature of `in`: membership in a list of operands of the expression type; an empty list yields `FALSE`. */
482
+ interface InSignature extends OperatorSignature {
483
+ readonly method: <const L extends readonly Operand<this["T"], this["I"]>[]>(list: L) => Expression<L extends readonly [] ? boolean : BooleanResult<this["T"] | OperandValue<L[number]>>>;
484
+ }
485
+ /** Operators of `equalityOperators`. */
486
+ type EqualityOperators = {
487
+ eq: EqualityOperator<ComparisonSignature>;
488
+ ne: EqualityOperator<ComparisonSignature>;
489
+ in: EqualityOperator<InSignature>;
490
+ };
491
+ /** Tells whether operators `O` include an operator of `equalityOperators`, so that their type has SQL `=`. */
492
+ type HasEquality<O> = true extends { [K in keyof O]: O[K] extends {
493
+ readonly [equalityBrand]: true;
494
+ } ? true : false; }[keyof O] ? true : false;
495
+ /**
496
+ * Operators of SQL equality: `eq`, `ne`, and `in`; `orderingOperators` include them.
497
+ *
498
+ * A type has SQL `=` only with these operators, so that an array of it has them too; another operator named `eq` does not give it `=`.
499
+ */
500
+ declare const equalityOperators: EqualityOperators;
501
+ /** Records of a query without selected fields. */
502
+ type EmptyRecord = Record<never, never>;
503
+ /** State of a query in types: the record or value of its rows, how its rows become its result, and the relations it selects records of. */
504
+ interface QueryState extends ResultMode {
505
+ /** Record of a row, or the value of its only field for a query made by `get`, `pluck`, or an aggregate method, such as `count`. */
506
+ readonly result: unknown;
507
+ /** Relations whose records the query and the queries nested in it select, which a `Db` must have. */
508
+ readonly uses: UsedRelation;
509
+ }
510
+ /**
511
+ * State of a select query in types: its table, the relations of its schema, the record or value of its rows and the values that its value accepts, how its rows become its result, and the relations it selects records of.
512
+ *
513
+ * Methods change only their own parts of the state.
514
+ */
515
+ interface SelectQueryState extends QueryState {
516
+ readonly table: AnyTable;
517
+ readonly schema: SchemaContext;
518
+ /** Values that the type of the value of a query of values encodes, such as the fallback of `coalesce`; `never` for a query of records. */
519
+ readonly input: unknown;
520
+ /**
521
+ * Whether a required relation guarantees the row of the query, such as of `field.form`.
522
+ *
523
+ * The relation does not guarantee a record that also passes a filter, so `where`, `find`, and `findBy` end the guarantee and make rows `one` `nullable`, or `optional` for a query of values; `optional`, `nullable`, and `required` end it as well.
524
+ * The callback of a helper starts with it, so that the effect of the helper records whether the callback filters.
525
+ */
526
+ readonly guaranteed: boolean;
527
+ /** Whether the query is made by an aggregate method, such as `count`, which makes `get`, `pluck`, and the aggregate methods reject it. */
528
+ readonly aggregate: boolean;
529
+ }
530
+ /** State of a query over table `T` with schema context `C`, whatever its result. */
531
+ interface QueryStateOf<T extends AnyTable, C extends SchemaContext = SchemaContext> extends SelectQueryState {
532
+ readonly table: T;
533
+ readonly schema: C;
534
+ }
535
+ /**
536
+ * State of a query that starts from table `T` with schema context `C`: rows as records without fields, all of them or of the records of relation `U` when given, in rows mode `Rows`, guaranteed by a required relation when `Guaranteed`.
537
+ *
538
+ * Without relations in `C`, it also types a query of the table in a schema that has relations of the table.
539
+ */
540
+ interface InitialQueryState<T extends AnyTable, C extends SchemaContext = NoRelations, U extends UsedRelation = never, Rows extends ResultRows = "many", Guaranteed extends boolean = false> extends QueryStateOf<T, C> {
541
+ readonly result: EmptyRecord;
542
+ readonly input: never;
543
+ readonly rows: Rows;
544
+ readonly value: false;
545
+ readonly uses: U;
546
+ readonly guaranteed: Guaranteed;
547
+ readonly aggregate: false;
548
+ }
549
+ /** Selection of the rows of a nested query as the value of the field `key`. */
550
+ interface NestedSelectionNode {
551
+ readonly key: string;
552
+ readonly query: QueryNode;
553
+ /** `Db` that the nested query is bound to, which must be the `Db` that runs the statement. */
554
+ readonly db: AnyDb | undefined;
555
+ }
556
+ /** Field selected by a query: an expression, or the rows of a nested query. */
557
+ type SelectedNode = ProjectionNode | NestedSelectionNode;
558
+ /** Select query of a table; its result mode applies when it is executed or its rows are nested. */
559
+ interface QueryNode extends ResultMode {
560
+ readonly kind: "query";
561
+ readonly from: TableSourceNode;
562
+ /** Relation whose records the query selects, correlated with its parent by the relation filter. */
563
+ readonly relation: RelationDefinition | undefined;
564
+ /** Fields in the order of the result, with unique keys; a query without them returns records without fields. */
565
+ readonly projections: readonly SelectedNode[];
566
+ readonly filters: QueryFilters;
567
+ readonly orderBy: readonly OrderNode[];
568
+ readonly limit: ExpressionNode | undefined;
569
+ readonly offset: ExpressionNode | undefined;
570
+ /** Whether a required relation guarantees the row of the query, so that a filter makes a query of rows `one` resolve without it; see `SelectQueryState`. */
571
+ readonly guaranteed: boolean;
572
+ /** Whether `all` allows a mutation of the query to change every row of the table without a filter. */
573
+ readonly all: boolean;
574
+ }
575
+ /**
576
+ * Mutation of a table that returns the fields of the rows it changes, which may nest queries, or the number of the rows without them.
577
+ *
578
+ * Its result mode is the rows mode of the rows it changes and whether a row is the value of its only field.
579
+ */
580
+ type MutationNode = MutationStatementNode<SelectedNode>;
581
+ /** Query of `$select` without a source: one record whose fields are the values of expressions and the rows of independent queries. */
582
+ interface RecordQueryNode {
583
+ readonly kind: "record";
584
+ /** Fields in the order of the record, with unique keys. */
585
+ readonly projections: readonly SelectedNode[];
586
+ }
587
+ /** Rows mode of a query of a relation of kind `Kind`: `many`, or one row, `nullable` unless `Required` is `true`; a union gives the union of their modes. */
588
+ type RelationRows<Kind extends RelationKind, Required extends boolean> = Kind extends "many" ? "many" : Required extends true ? "one" : "nullable";
589
+ /** Rows mode after a filter of a query whose row a required relation guarantees: `one` becomes `nullable`, or `optional` for a query of values; other modes stay. */
590
+ type FilteredRows<Rows extends ResultRows, Value extends boolean> = Rows extends "one" ? Value extends true ? "optional" : "nullable" : Rows;
591
+ /** Rows mode after `take`: `many` becomes `one`; the modes of one row stay. */
592
+ type OneRow<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows;
593
+ /** Rows mode after `pluck`: `nullable` becomes `optional`; the other modes stay. */
594
+ type ValueRows<Rows extends ResultRows> = Rows extends "nullable" ? "optional" : Rows;
595
+ /** Rows mode after `get`: `many` becomes `one` and `nullable` becomes `optional`; `one` and `optional` stay. */
596
+ type OneValueRows<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows extends "nullable" ? "optional" : Rows;
597
+ /**
598
+ * 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.
599
+ *
600
+ * It is the union of the results of every state that `S` allows, such as of a union of rows modes.
601
+ */
602
+ type QueryResult<S extends QueryState> = S extends QueryState ? ResultByRows<S["result"], S["rows"]> : never;
603
+ /** Result of rows of `Result` returned in rows mode `Rows`; a union of modes gives the union of their results. */
604
+ type ResultByRows<Result, Rows extends ResultRows> = Rows extends "many" ? Result[] : Rows extends "one" ? Result : Rows extends "nullable" ? Result | null : Result | undefined;
605
+ /** References to the columns of the query source, passed to query callbacks. */
606
+ type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
607
+ /**
608
+ * Queries of the records of the relations of the table of schema context `C`, by relation name, which the callback of `select` receives beside the columns.
609
+ *
610
+ * A relation name is never a column key of its table.
611
+ * A context whose table key is not known, such as one of a query of any schema, has no relations.
612
+ */
613
+ type RelationRefs<C extends SchemaContext> = string extends C["key"] ? EmptyRecord : C["key"] extends keyof C["relations"] ? RelationQueries<C["relations"], C["key"]> : EmptyRecord;
614
+ type RelationQueries<R extends SchemaContext["relations"], K extends keyof R & string> = { readonly [N in keyof R[K]]: RelatedQuery<R, K, N & string>; };
615
+ /** Unbound query of the records of relation `N` of the table under key `K` of a schema of relations `R`, in the schema context of its target and the rows mode of the relation, whose row a required relation guarantees. */
616
+ type RelatedQuery<R extends SchemaContext["relations"], K extends keyof R & string, N extends keyof R[K] & string> = SelectQuery<InitialQueryState<R[K][N]["target"], TableContext<R, R[K][N]["targetKey"]>, UsedRelation<K, N, R[K][N]>, RelationRows<R[K][N]["kind"], R[K][N]["required"]>, R[K][N]["required"]>>;
617
+ /** Runtime context of the queries of a table in the schema they start from. */
618
+ interface QueryContext {
619
+ /** Getters of the queries of the relations of the table, which the references of `select` have as their own properties and which read the key columns from them. */
620
+ readonly relations: PropertyDescriptorMap;
621
+ }
622
+ declare const conditionValues: unique symbol;
623
+ /** Predicate accepted by `where`, `and`, `or`, and `not`; SQL treats a `NULL` predicate as not satisfied. */
624
+ type Predicate = AnyExpression<boolean | null>;
625
+ /**
626
+ * Condition combining expressions with objects of column values, such as `or({ published: true }, form.id.in(ids))`.
627
+ *
628
+ * `where` matches the objects against the columns of its query, so a condition is accepted only where `V` matches the table.
629
+ */
630
+ interface Condition<V> {
631
+ readonly [conditionValues]?: V;
632
+ }
633
+ /**
634
+ * Operand of `and`, `or`, and `not`: a predicate, a condition, or an object of column values.
635
+ *
636
+ * Column values `V` are never inferred from an object, so that object keys are checked against the table instead of determining `V`.
637
+ */
638
+ type ConditionOperand<V, T extends boolean | null = boolean | null> = AnyExpression<T> | Condition<V> | NoInfer<V>;
639
+ /**
640
+ * Result of `and`, `or`, and `not`: a condition checked against the table inside `where`, a Boolean expression without a table.
641
+ */
642
+ type CombinedCondition<V, T extends boolean | null = boolean | null> = [V] extends [never] ? Expression<BooleanResult<T>> : Condition<V>;
643
+ /** Combines predicates with `AND`; no operands yield `TRUE`. */
644
+ declare function and<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
645
+ /** Combines predicates with `OR`; no operands yield `FALSE`. */
646
+ declare function or<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
647
+ /** Negates a predicate. */
648
+ declare function not<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(operand: ConditionOperand<V, T>): CombinedCondition<V, T>;
649
+ /**
650
+ * Filter by column values, each matched by the `eq` operator of its column; `null` matches `IS NULL`.
651
+ *
652
+ * A column without an `eq` operator of one operand accepts only `null` in this filter, when its input type includes `null`.
653
+ */
654
+ type WhereValues<T extends AnyTable> = { [K in keyof T["columns"]]?: EqValue<T, K> | (null extends ColumnValues<T>[K] ? null : never); };
655
+ /** Operand of the `eq` operator of column `K` of table `T` in an object passed to `where`, such as an expression. */
656
+ type EqValue<T extends AnyTable, K extends keyof T["columns"]> = IsAny<ColumnOperators<T, K>> extends true ? ColumnValues<T>[K] : EqOperand<ColumnRefs<T>[K]>;
657
+ /** Operand of the `eq` operator of an expression, if it has one taking a single operand. */
658
+ type EqOperand<E> = E extends {
659
+ eq: (value: infer V) => Predicate;
660
+ } ? V : never;
661
+ /** Filter of `where`: a Boolean expression, an object of column values, or their combination with `and`, `or`, and `not`. */
662
+ type WhereCondition<T extends AnyTable> = ConditionOperand<WhereValues<T>>;
663
+ /** Argument of `where`: a condition, or a callback that receives the columns of the query and returns one. */
664
+ type WhereFilter<T extends AnyTable> = WhereCondition<T> | ((columns: ColumnRefs<T>) => WhereCondition<T>);
665
+ /**
666
+ * Defines a reusable condition of `where` for queries over a table, checking its objects of column values against the columns.
667
+ *
668
+ * The condition can be combined further with `and`, `or`, and `not`.
669
+ */
670
+ declare function defineFilter<T extends AnyTable>(table: TableOrQuery<T>, filter: NoInfer<WhereCondition<T>>): WhereCondition<T>;
671
+ /**
672
+ * Defines a reusable callback of `where` for queries over a table, checking its objects of column values against the columns.
673
+ *
674
+ * Another callback can call it with its columns.
675
+ */
676
+ declare function defineFilter<T extends AnyTable>(table: TableOrQuery<T>, filter: NoInfer<(columns: ColumnRefs<T>) => WhereCondition<T>>): (columns: ColumnRefs<T>) => WhereCondition<T>;
677
+ /** Defines a reusable filter of `where` for queries over a table, either a condition or a callback. */
678
+ declare function defineFilter<T extends AnyTable>(table: TableOrQuery<T>, filter: NoInfer<WhereFilter<T>>): WhereFilter<T>;
679
+ /**
680
+ * Values of the primary key of table `T` that `find` takes, in the order of its columns, or `never` where the type of `T` tells no primary key.
681
+ *
682
+ * A union of tables gives the union of their values.
683
+ */
684
+ type PrimaryKeyValues<T extends AnyTable> = T extends AnyTable ? T["keys"] extends TableKeys<infer PrimaryKey extends KeyColumns, infer _UniqueKey> ? { readonly [I in keyof PrimaryKey]: NonNullable<EqValue<T, PrimaryKey[I] & keyof T["columns"]>>; } : never : never;
685
+ /**
686
+ * Check of columns `Columns` of the object of `findBy` that rejects them unless they are exactly a key of table `T`, primary or unique, as the type of `T` tells.
687
+ *
688
+ * A table of `any`, such as of `AnySelectQuery`, takes any columns, as `where` takes any values there.
689
+ */
690
+ type KeyCheck<T extends AnyTable, Columns> = [IsKey<T, Columns>] extends [true] ? unknown : IsAny<T> extends true ? unknown : NotAKey<KeyOf<T["keys"]>>;
691
+ /** Type that the object of `findBy` is checked against when its columns are not exactly a key of the table, naming the keys of the table. */
692
+ interface NotAKey<Keys> {
693
+ readonly "columns must be exactly one key of the table": Keys;
694
+ }
695
+ /**
696
+ * Direction of a sort key, optionally with the placement of `NULL`.
697
+ *
698
+ * Without a placement, `NULL` comes last in ascending order and first in descending order.
699
+ */
700
+ type OrderDirection = "asc" | "desc" | "asc nulls first" | "asc nulls last" | "desc nulls first" | "desc nulls last";
701
+ /** Columns of table `T` with the directions to sort by them, in the order of their keys. */
702
+ type OrderColumns<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: OrderDirection; };
703
+ /** Argument of `orderBy` of a query over table `T`: a column key, sorted in ascending order, or columns with directions. */
704
+ type OrderKey<T extends AnyTable> = (keyof T["columns"] & string) | OrderColumns<T>;
705
+ declare const ordering: unique symbol;
706
+ /** Expression with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
707
+ interface Ordering {
708
+ readonly [ordering]: true;
709
+ }
710
+ /** Sort key returned by the callback of `orderBy`: an expression, sorted in ascending order, or an expression with a direction. */
711
+ type OrderTerm = AnyExpression | Ordering;
712
+ /**
713
+ * References of the callback of `orderBy` to the fields of records `R` selected by a query: their expressions by key.
714
+ *
715
+ * A field of a nested query, such as of nested rows or of an aggregate, is among them in types, but reading it throws.
716
+ */
717
+ type SelectedRefs<R> = { readonly [K in keyof R & string]: AnyExpression<R[K]>; };
718
+ /** Sort keys returned by the callback of `orderBy`: one or an array of them. */
719
+ type OrderTerms = OrderTerm | readonly OrderTerm[];
720
+ /** Sorts by `expression` in ascending order, in the callback of `orderBy`. */
721
+ declare function asc(expression: AnyExpression): Ordering;
722
+ /** Sorts by `expression` in descending order, in the callback of `orderBy`. */
723
+ declare function desc(expression: AnyExpression): Ordering;
724
+ /** Sorts by `expression` in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
725
+ declare function orderBy(expression: AnyExpression, direction: OrderDirection): Ordering;
726
+ /** Value of column `K` of table `T` that an insert or an update sets: a value that its type encodes, `null` for a nullable column, or an expression of its values. */
727
+ type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValues<T>[K] | AnyExpression<Selectable<T>[K]>;
728
+ /** Key of a column of table `T` that an insert may omit, which gets its default: one that the database gives a value, as `hasDefault` marks it, or a nullable one, whose default is `NULL` unless the database declares another. */
729
+ type OptionalColumnKey<T extends AnyTable> = { [K in keyof T["columns"]]: T["columns"][K]["attributes"]["hasDefault"] extends true ? K : null extends ColumnValues<T>[K] ? K : never; }[keyof T["columns"]];
730
+ /** Record of an insert into table `T`: the values of its columns, which may omit a column with a default or a nullable column, or give it as `undefined`. */
731
+ type InsertValues<T extends AnyTable> = { readonly [K in keyof T["columns"] as K extends OptionalColumnKey<T> ? never : K]: ColumnValue<T, K>; } & { readonly [K in OptionalColumnKey<T>]?: ColumnValue<T, K> | undefined; };
732
+ /** Values of the columns of table `T` that an update sets; a column omitted or given as `undefined` keeps its value. */
733
+ type UpdateValues<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: ColumnValue<T, K> | undefined; };
734
+ /** Argument of `update`: the values that it sets, or a callback that receives the columns of the changed rows and returns them. */
735
+ type UpdateSet<T extends AnyTable> = UpdateValues<T> | ((columns: ColumnRefs<T>) => UpdateValues<T>);
736
+ /** State `S` with the parts of `Changes` replaced. */
737
+ type ChangeState<S extends SelectQueryState, Changes extends Partial<SelectQueryState>> = { readonly [K in keyof SelectQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
738
+ /** Rows mode of a query of state `S` after a filter: `FilteredRows` of a query whose row is guaranteed, and the rows of other queries. */
739
+ type FilteredStateRows<S extends SelectQueryState> = [S["guaranteed"]] extends [false] ? S["rows"] : [S["value"]] extends [false] ? S["result"] extends HelperFields ? S["rows"] : FilteredRows<S["rows"], false> : FilteredRows<S["rows"], S["value"]>;
740
+ /** State `S` after a filter, which ends the guarantee of its row. */
741
+ type FilteredState<S extends SelectQueryState> = ChangeState<S, {
742
+ rows: FilteredStateRows<S>;
743
+ guaranteed: false;
744
+ }>;
745
+ /** State `S` after a filter followed by `take`, as `find` and `findBy` change it. */
746
+ type FoundState<S extends SelectQueryState> = ChangeState<S, {
747
+ rows: OneRow<FilteredStateRows<S>>;
748
+ guaranteed: false;
749
+ }>;
750
+ /** Query of state `S`, bound or unbound. */
751
+ type QueryOf<S extends SelectQueryState> = SelectQuery<S, SelectQueryKind>;
752
+ /** State of a query whose rows are records, which `select` and `clearSelect` change. */
753
+ type RecordQueryState$1 = SelectQueryState & {
754
+ readonly value: false;
755
+ };
756
+ /** State of a query whose row no relation guarantees, which a filter keeps. */
757
+ type UnguaranteedQueryState = SelectQueryState & {
758
+ readonly guaranteed: false;
759
+ };
760
+ /** State of a query whose rows are values, made by `get`, `pluck`, or an aggregate method, such as `count`. */
761
+ type ValueQueryState = SelectQueryState & {
762
+ readonly value: true;
763
+ };
764
+ /** State of a query not made by an aggregate method, which `get`, `pluck`, and the aggregate methods apply to. */
765
+ type UnaggregatedQueryState = SelectQueryState & {
766
+ readonly aggregate: false;
767
+ };
768
+ /** State of a query of the value `V` of an aggregate over the rows of a query of state `S`, which always returns one row, accepting values `I` in place of its value. */
769
+ type AggregateState<S extends SelectQueryState, V, I> = ChangeState<S, {
770
+ result: V;
771
+ input: I;
772
+ rows: "one";
773
+ value: true;
774
+ guaranteed: false;
775
+ aggregate: true;
776
+ }>;
777
+ /** Value `V` of a query of values whose `NULL` `coalesce` replaces with fallback `F`. */
778
+ type CoalescedValue<V, F> = Exclude<V, null> | (F extends AnyExpression<infer T> ? Extract<T, null> : never);
779
+ /** State of a query of many rows, which `limit` and `offset` apply to. */
780
+ type ManyRowsQueryState = SelectQueryState & {
781
+ readonly rows: "many";
782
+ };
783
+ /** State of a query of one row, which `optional` and `required` apply to. */
784
+ type OneRowQueryState = SelectQueryState & {
785
+ readonly rows: "one" | "nullable" | "optional";
786
+ };
787
+ /** State of a query of one row whose rows are records, which `nullable` applies to. */
788
+ type OneRecordQueryState = OneRowQueryState & {
789
+ readonly value: false;
790
+ };
791
+ /**
792
+ * Immutable select query of state `S`, unbound or bound to a `Db`.
793
+ *
794
+ * Every method returns a query of the same kind and leaves this query unchanged.
795
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
796
+ * A bound query executes on its `Db` when awaited.
797
+ */
798
+ declare class SelectQuery<out S extends SelectQueryState, out Kind extends SelectQueryKind = "unbound"> {
799
+ readonly table: S["table"];
800
+ readonly node: QueryNode;
801
+ /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
802
+ readonly context: QueryContext;
803
+ readonly types: S;
804
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
805
+ readonly db: QueryDb<Kind>;
806
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
807
+ readonly then: QueryThen<S, Kind>;
808
+ constructor(table: S["table"], node: QueryNode,
809
+ /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
810
+ context: QueryContext, db?: AnyDb);
811
+ /** Adds a filter combined with `AND` with the previous ones. */
812
+ where<Q extends QueryOf<UnguaranteedQueryState>>(this: Q, filter: WhereFilter<Q["types"]["table"]>): Q;
813
+ /**
814
+ * Adds a filter combined with `AND` with the previous ones.
815
+ *
816
+ * A query of the record of a required relation, such as `field.form`, resolves to `null` without a record that passes the filter, or to `undefined` after `get` or `pluck`.
817
+ */
818
+ where<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: WhereFilter<S["table"]>): SelectQuery<FilteredState<S>, Kind>;
819
+ /** Selects all columns of the table, replacing fields under their keys. */
820
+ select<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
821
+ result: MergeSelection<S["result"], Selectable<S["table"]>>;
822
+ }>, Kind>;
823
+ /** Selects the listed columns, replacing fields under their keys. */
824
+ select<S extends RecordQueryState$1, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, ...keys: K[]): SelectQuery<ChangeState<S, {
825
+ result: MergeSelection<S["result"], Pick<Selectable<S["table"]>, K>>;
826
+ }>, Kind>;
827
+ /**
828
+ * Selects the expressions and nested queries returned by `callback`, replacing fields under their keys.
829
+ *
830
+ * `callback` receives the columns and the queries of the relations of the table.
831
+ * Each expression is decoded with its type, so it must have one: a column, an operator result, or a fragment of `sql(type)`, but not of `sql<T>`.
832
+ * A nested query is unbound, such as a query of a relation, or bound to the `Db` that runs the query; its rows become the value of its field as they become the result of an executed query.
833
+ */
834
+ select<S extends RecordQueryState$1, Kind extends SelectQueryKind, Sel extends Selection>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => Sel): SelectQuery<ChangeState<S, {
835
+ result: MergeSelection<S["result"], SelectionResult<Sel>>;
836
+ uses: S["uses"] | SelectionUses<Sel>;
837
+ }>, Kind>;
838
+ /** Removes all selected fields and keeps the other clauses. */
839
+ clearSelect<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
840
+ result: EmptyRecord;
841
+ }>, Kind>;
842
+ /**
843
+ * Limits the query to one row and returns the row instead of an array; without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
844
+ * When a required relation still guarantees the row, such as of `field.form`, it rejects with `RequiredRelationError` instead.
845
+ *
846
+ * A query of one row stays as it is.
847
+ */
848
+ take<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
849
+ rows: OneRow<S["rows"]>;
850
+ }>, Kind>;
851
+ /**
852
+ * Filters the query by the values of the primary key of the table, in the order of its columns, and returns the row instead of an array, as `where` followed by `take`, but without a limit.
853
+ *
854
+ * A value is what `where` takes for its column, such as an expression, but never `null` or `undefined`.
855
+ * Without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
856
+ */
857
+ find<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, ...values: PrimaryKeyValues<S["table"]>): SelectQuery<FoundState<S>, Kind>;
858
+ /**
859
+ * Filters the query by the values of the columns of one key of the table, primary or unique, and returns the row instead of an array, as `where` followed by `take`, but without a limit.
860
+ *
861
+ * A value is what `where` takes for its column, such as an expression, but never `null` or `undefined`.
862
+ * Without a row, it rejects with `NotFoundError` unless `optional` or `nullable` makes the query resolve to `undefined` or `null`.
863
+ */
864
+ findBy<S extends SelectQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, values: { readonly [C in K]: NonNullable<EqValue<S["table"], C>>; } & KeyCheck<S["table"], K>): SelectQuery<FoundState<S>, Kind>;
865
+ /**
866
+ * Replaces the selected fields with a column, limits the query to one row, and returns the value of the column instead of a record.
867
+ *
868
+ * Without a row, it rejects with `NotFoundError`, or with `RequiredRelationError` when a required relation still guarantees the row, such as of `field.form`.
869
+ * An optional or nullable query resolves to `undefined` without a row instead.
870
+ * A `NULL` value is `null`.
871
+ */
872
+ get<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ChangeState<S, {
873
+ result: Selectable<S["table"]>[K];
874
+ input: ColumnValues<S["table"]>[K];
875
+ rows: OneValueRows<S["rows"]>;
876
+ value: true;
877
+ }>, Kind>;
878
+ /**
879
+ * Replaces the selected fields with the expression returned by `callback`, limits the query to one row, and returns the value of the expression instead of a record.
880
+ *
881
+ * Without a row, it rejects with `NotFoundError`, or with `RequiredRelationError` when a required relation still guarantees the row, such as of `field.form`.
882
+ * An optional or nullable query resolves to `undefined` without a row instead.
883
+ * A `NULL` value is `null`.
884
+ */
885
+ get<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ChangeState<S, {
886
+ result: ExpressionValue<E>;
887
+ input: ExpressionInput<E>;
888
+ rows: OneValueRows<S["rows"]>;
889
+ value: true;
890
+ }>, Kind>;
891
+ /**
892
+ * Replaces the selected fields with a column and returns the value of the column of each row instead of a record.
893
+ *
894
+ * It keeps whether the query returns an array or one value, such as after `take`, and how it handles a missing row, except that a nullable query resolves to `undefined` without a row.
895
+ */
896
+ pluck<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<ChangeState<S, {
897
+ result: Selectable<S["table"]>[K];
898
+ input: ColumnValues<S["table"]>[K];
899
+ rows: ValueRows<S["rows"]>;
900
+ value: true;
901
+ }>, Kind>;
902
+ /**
903
+ * Replaces the selected fields with the expression returned by `callback` and returns the value of the expression for each row instead of a record.
904
+ *
905
+ * It keeps whether the query returns an array or one value, such as after `take`, and how it handles a missing row, except that a nullable query resolves to `undefined` without a row.
906
+ */
907
+ pluck<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<ChangeState<S, {
908
+ result: ExpressionValue<E>;
909
+ input: ExpressionInput<E>;
910
+ rows: ValueRows<S["rows"]>;
911
+ value: true;
912
+ }>, Kind>;
913
+ /**
914
+ * Replaces the selected fields with the number of rows of the query and returns the number instead of the rows.
915
+ *
916
+ * It keeps the filters and ignores the order; with `limit` or `offset`, it counts the rows of that page.
917
+ */
918
+ count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<AggregateState<S, number, number>, Kind>;
919
+ /** Replaces the selected fields with the number of the values of the column other than `NULL` among the rows of the query and returns it instead of the rows. */
920
+ count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, number, number>, Kind>;
921
+ /** Replaces the selected fields with the number of the values other than `NULL` of the expression returned by `callback` among the rows of the query and returns it instead of the rows. */
922
+ count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, number, number>, Kind>;
923
+ /** Replaces the selected fields with the number of the distinct values of the column other than `NULL` among the rows of the query and returns it instead of the rows. */
924
+ countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, number, number>, Kind>;
925
+ /** Replaces the selected fields with the number of the distinct values other than `NULL` of the expression returned by `callback` among the rows of the query and returns it instead of the rows. */
926
+ countDistinct<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, number, number>, Kind>;
927
+ /** Replaces the selected fields with the smallest value of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
928
+ min<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
929
+ /** Replaces the selected fields with the smallest value of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
930
+ min<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
931
+ /** Replaces the selected fields with the largest value of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
932
+ max<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
933
+ /** Replaces the selected fields with the largest value of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
934
+ max<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
935
+ /** Replaces the selected fields with the sum of the values of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
936
+ sum<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
937
+ /** Replaces the selected fields with the sum of the values of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`. */
938
+ sum<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
939
+ /** Replaces the selected fields with the average of the values of the column among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`; for `bigint` values, average an expression of a type that can represent fractional values. */
940
+ avg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
941
+ /** Replaces the selected fields with the average of the values of the expression returned by `callback` among the rows of the query and returns it instead of the rows, or `null` without values other than `NULL`; for `bigint` values, average an expression of a type that can represent fractional values. */
942
+ avg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
943
+ /** Replaces the selected fields with whether every value of the Boolean column other than `NULL` among the rows of the query is true and returns it instead of the rows, or `null` without such values. */
944
+ every<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
945
+ /** Replaces the selected fields with whether every value other than `NULL` of the Boolean expression returned by `callback` among the rows of the query is true and returns it instead of the rows, or `null` without such values. */
946
+ every<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
947
+ /** Replaces the selected fields with whether any value of the Boolean column among the rows of the query is true and returns it instead of the rows, or `null` without values other than `NULL`. */
948
+ some<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
949
+ /** Replaces the selected fields with whether any value of the Boolean expression returned by `callback` among the rows of the query is true and returns it instead of the rows, or `null` without values other than `NULL`. */
950
+ some<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
951
+ /** Replaces the selected fields with the values of the text column other than `NULL` among the rows of the query, joined with `delimiter` in the order of the query, and returns them instead of the rows, or `null` without such values. */
952
+ stringAgg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, key: K, delimiter: string): SelectQuery<AggregateState<S, Selectable<S["table"]>[K] | null, ColumnValues<S["table"]>[K]>, Kind>;
953
+ /** Replaces the selected fields with the values other than `NULL` of the text expression returned by `callback` among the rows of the query, joined with `delimiter` in the order of the query, and returns them instead of the rows, or `null` without such values. */
954
+ stringAgg<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E, delimiter: string): SelectQuery<AggregateState<S, ExpressionValue<E> | null, ExpressionInput<E>>, Kind>;
955
+ /**
956
+ * Replaces a `NULL` value of a query of values, such as one made by `get`, `pluck`, or an aggregate, with `fallback`, such as `0` for a sum without rows.
957
+ *
958
+ * `fallback` is a value that the type of the value accepts or an expression of its values, such as a column of the row of a parent query.
959
+ * A missing row stays missing: an optional query still resolves to `undefined` without a row.
960
+ */
961
+ coalesce<S extends ValueQueryState, Kind extends SelectQueryKind, F extends Operand<S["result"], S["input"]>>(this: SelectQuery<S, Kind>, fallback: F): SelectQuery<ChangeState<S, {
962
+ result: CoalescedValue<S["result"], F>;
963
+ }>, Kind>;
964
+ /**
965
+ * Sorts the rows by the sort keys returned by `callback`, after the sort keys of earlier calls.
966
+ *
967
+ * `callback` receives the columns and the fields selected so far, and returns an expression, sorted in ascending order, `asc`, `desc`, or `orderBy` of an expression, or an array of them.
968
+ * A selected field sorts by the value of the field, also when it changes from row to row, such as `random()`.
969
+ */
970
+ orderBy<Q extends QueryOf<RecordQueryState$1>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]>, selected: SelectedRefs<Q["types"]["result"]>) => OrderTerms): Q;
971
+ /**
972
+ * Sorts the values of a query made by `get` or `pluck` by the sort keys returned by `callback`, after the sort keys of earlier calls.
973
+ *
974
+ * `callback` receives the columns and the expression of the value, and returns an expression, sorted in ascending order, `asc`, `desc`, or `orderBy` of an expression, or an array of them.
975
+ */
976
+ orderBy<Q extends QueryOf<ValueQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]>, value: AnyExpression<Q["types"]["result"]>) => OrderTerms): Q;
977
+ /** Sorts the rows by the listed columns in ascending order, or in the directions of objects of columns, after the sort keys of earlier calls. */
978
+ orderBy<Q extends AnySelectQuery>(this: Q, ...keys: OrderKey<Q["types"]["table"]>[]): Q;
979
+ /** Returns at most `count` rows of a query of many rows, replacing an earlier limit. */
980
+ limit<Q extends QueryOf<ManyRowsQueryState>>(this: Q, count: number): Q;
981
+ /** Skips the first `count` rows of a query of many rows, replacing an earlier offset. */
982
+ offset<Q extends QueryOf<ManyRowsQueryState>>(this: Q, count: number): Q;
983
+ /** Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without a row. */
984
+ optional<S extends OneRowQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
985
+ rows: "optional";
986
+ guaranteed: false;
987
+ }>, Kind>;
988
+ /**
989
+ * Makes a query of one record, such as one of `take`, resolve to `null` without a row.
990
+ *
991
+ * A value of `get` or `pluck` is never `null` for a missing row, which would read as a `NULL` value, so a query of values does not accept it, and after `get` or `pluck` the query resolves to `undefined` without a row.
992
+ */
993
+ nullable<S extends OneRecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
994
+ rows: "nullable";
995
+ guaranteed: false;
996
+ }>, Kind>;
997
+ /** Makes a query of one row, such as one of `optional` or `nullable`, reject without a row. */
998
+ required<S extends OneRowQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
999
+ rows: "one";
1000
+ guaranteed: false;
1001
+ }>, Kind>;
1002
+ /**
1003
+ * Inserts a record into the table of a query without clauses, such as a table of a `Db`, and resolves to the number of the inserted rows, `1`.
1004
+ *
1005
+ * A column omitted or given as `undefined` gets its default, so only columns marked with `hasDefault` and nullable columns may be omitted.
1006
+ * A value is what the type of its column takes, `null` for `NULL`, or an expression, such as a `sql` fragment.
1007
+ * Select the fields that it returns after it, such as `insert(values).get("id")`.
1008
+ */
1009
+ insert<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, values: InsertValues<S["table"]>): MutationQuery<InitialMutationState<S["table"], S["schema"], "one">, Kind>;
1010
+ /**
1011
+ * Inserts records into the table of a query without clauses, such as a table of a `Db`, in one statement, and resolves to the number of the inserted rows.
1012
+ *
1013
+ * A record takes the values that `insert` takes, and a column that a record omits gets its default.
1014
+ * Select the fields that it returns for the inserted rows after it, such as `insertMany(records).select("id", "email")`, and match them to the records by a key rather than by their order, which PostgreSQL does not guarantee.
1015
+ */
1016
+ insertMany<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, records: readonly InsertValues<S["table"]>[]): MutationQuery<InitialMutationState<S["table"], S["schema"], "many">, Kind>;
1017
+ /**
1018
+ * Updates the rows that the filters of the query choose with the values of `set`, and resolves to the number of the updated rows.
1019
+ *
1020
+ * `set` gives the values of the columns to update, or is a callback that receives the columns and returns them, such as to set a column from another one; a column omitted or given as `undefined` keeps its value.
1021
+ * A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
1022
+ * A query without a filter must call `all` to update every row.
1023
+ * Select the fields that it returns after it, with their values after the update, such as `update(set).select("id")`.
1024
+ */
1025
+ update<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, set: UpdateSet<S["table"]>): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"]>, Kind>;
1026
+ /**
1027
+ * Deletes the rows that the filters of the query choose, and resolves to the number of the deleted rows.
1028
+ *
1029
+ * A query of `find` or `findBy` rejects with `NotFoundError` without its row, unless `optional` or `nullable` allows it.
1030
+ * A query without a filter must call `all` to delete every row.
1031
+ * Select the fields that it returns after it, such as `delete().pluck("id")`.
1032
+ */
1033
+ delete<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"]>, Kind>;
1034
+ /** Allows `update` and `delete` to change every row of the table when the query has no filter; it changes nothing else. */
1035
+ all<Q extends QueryOf<ManyRowsQueryState>>(this: Q): Q;
1036
+ /**
1037
+ * Returns the query that `callback` builds from this query, such as one with a conditional clause, or that a helper of `defineHelper` builds with `args`.
1038
+ *
1039
+ * `callback` receives this query and `args` and returns this query or a query derived from it, which keeps the binding of this query.
1040
+ */
1041
+ use<Q, Kind extends SelectQueryKind, R extends SelectQuery<any, Kind>, A extends unknown[] = []>(this: Q & SelectQuery<any, Kind>, callback: (query: Q, ...args: A) => R, ...args: A): R;
1042
+ /**
1043
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1044
+ *
1045
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1046
+ */
1047
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1048
+ /** Creates a query of the same kind and `Db` with the node changes applied. */
1049
+ private derive;
1050
+ /**
1051
+ * Creates a query of the same kind and `Db` with the node changes applied and then those of `take`, in one derived query.
1052
+ *
1053
+ * It adds the changes of `take` to `changes`, which must leave the limit as it is.
1054
+ */
1055
+ private deriveTaken;
1056
+ /** Creates the query of the value of `projection`, an aggregate over the rows of this query, which always returns one row. */
1057
+ private deriveAggregate;
1058
+ /** Creates the query of the aggregate of `method` over `arg`, a column key or a callback that receives the columns and returns an expression; `delimiter` is the delimiter of `stringAgg`. */
1059
+ private aggregateBy;
1060
+ /** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
1061
+ private addFilter;
1062
+ /** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
1063
+ private takeWhere;
1064
+ /** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
1065
+ private changeOneRow;
1066
+ /** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
1067
+ private rejectValue;
1068
+ /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method. */
1069
+ private rejectAggregate;
1070
+ }
1071
+ /** Select query bound to a `Db`, executed by awaiting it; every method returns a query bound to the same `Db`. */
1072
+ type BoundSelectQuery<S extends SelectQueryState> = SelectQuery<S, "bound">;
1073
+ /** Select query of any state and kind. */
1074
+ type AnySelectQuery = SelectQuery<any, SelectQueryKind>;
1075
+ /** Type of a record of a query result, or of its value for a query made by `get`, `pluck`, or an aggregate method. */
1076
+ type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
1077
+ /** Table of a definition such as `defineFilter`: the table itself or a query over it with schema context `C`, such as `schema.form`. */
1078
+ type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
1079
+ /** Starts a query over a new occurrence of the table. */
1080
+ declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T>>;
1081
+ /** Expressions and nested queries selected under the keys of the result fields; a record has no symbol keys. */
1082
+ interface Selection {
1083
+ readonly [key: string]: TypedExpression | NestedQuery;
1084
+ readonly [key: symbol]: never;
1085
+ }
1086
+ /** Query whose rows a selection nests as the value of a field: a query of any state and kind, such as a query of a relation. */
1087
+ type NestedQuery = QueryOf<SelectQueryState>;
1088
+ /** Record of the values of the expressions and of the nested rows of a selection. */
1089
+ type SelectionResult<S extends Selection> = { [K in keyof S]: FieldValue<S[K]>; };
1090
+ /** Value of a selected field: of an expression, or of the nested rows of a query as the result of executing it, for each member of a union of them. */
1091
+ type FieldValue<V> = V extends NestedQuery ? QueryResult<V["types"]> : ExpressionValue<V>;
1092
+ /** Relations whose records the nested queries of a selection select. */
1093
+ type SelectionUses<S extends Selection> = S[keyof S] extends (infer V) ? V extends NestedQuery ? V["types"]["uses"] : never : never;
1094
+ /** Value of a selected expression. */
1095
+ type ExpressionValue<E> = E extends AnyExpression<infer T> ? T : never;
1096
+ /** Values that the type of an expression encodes, such as in place of its value. */
1097
+ type ExpressionInput<E> = E extends AnyExpression<unknown, infer I> ? I : never;
1098
+ declare const helperFields: unique symbol;
1099
+ /** Marker of the input fields of a helper, carrying the keys selected by its callback. */
1100
+ interface HelperFields<Keys extends PropertyKey = PropertyKey> {
1101
+ readonly [helperFields]: Keys;
1102
+ }
1103
+ /** Records with `Fields` added or replaced, for each branch of either record type; `any` stays `any`. */
1104
+ type MergeSelection<Previous, Fields> = Previous extends unknown ? Fields extends unknown ? MergeFields<RecordFields<Previous>, RecordFields<Fields>> & (IsAny<Previous> extends true ? Previous : unknown) : never : never;
1105
+ /** Fields with numeric keys represented as the string keys used in result records. */
1106
+ type RecordFields<Fields> = Fields extends unknown ? [Extract<keyof Fields, number>] extends [never] ? Fields : { [K in keyof Fields as K extends number ? `${K}` : K]: Fields[K]; } : never;
1107
+ /** Merge of normalized fields, retaining the previous value when an optional replacement is absent. */
1108
+ type MergeFields<Previous, Fields> = Simplify<{ [K in keyof Previous as K extends keyof Fields ? ({} extends Pick<Fields, K> ? K : never) : K]: K extends typeof helperFields // A branch selecting extra keys must not be reduced to one selecting fewer fields or none.
1109
+ ? Previous[K] | keyof Fields : K extends keyof Fields // A decoder can return undefined, so it cannot be excluded as merely an absent property.
1110
+ ? Previous[K] | Fields[K] : Previous[K]; } & { [K in keyof Fields as K extends keyof Previous ? ({} extends Pick<Fields, K> ? never : K) : K]: Fields[K]; }>;
1111
+ /** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
1112
+ interface RecordQueryState<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
1113
+ readonly result: R;
1114
+ readonly rows: "one";
1115
+ readonly value: false;
1116
+ readonly uses: U;
1117
+ }
1118
+ /** State of the query of `$select` of `Sel`: the record of the values of its expressions and the results of its queries. */
1119
+ type SelectionState<Sel extends Selection> = RecordQueryState<MergeSelection<EmptyRecord, SelectionResult<Sel>>, SelectionUses<Sel>>;
1120
+ /**
1121
+ * Immutable query of `$select` of state `S`, unbound or bound to a `Db`: one record whose fields are the values of expressions and the results of independent queries, selected in one statement.
1122
+ *
1123
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
1124
+ * A bound query executes on its `Db` when awaited.
1125
+ */
1126
+ declare class RecordQuery<out S extends RecordQueryState, out Kind extends SelectQueryKind = "unbound"> {
1127
+ readonly node: RecordQueryNode;
1128
+ readonly types: S;
1129
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
1130
+ readonly db: QueryDb<Kind>;
1131
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
1132
+ readonly then: QueryThen<S, Kind>;
1133
+ constructor(node: RecordQueryNode, db?: AnyDb);
1134
+ /**
1135
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1136
+ *
1137
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1138
+ */
1139
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1140
+ }
1141
+ /** Query of `$select` of any state and kind. */
1142
+ type AnyRecordQuery = RecordQuery<any, SelectQueryKind>;
1143
+ declare const schemaBrand: unique symbol;
1144
+ /** Key of the relation definitions of a schema, which composition reads. */
1145
+ declare const schemaRelations: unique symbol;
1146
+ /** Tables by their keys; a key must not start with `$`, which is reserved for schema and `Db` members. */
1147
+ type Tables = Record<string, AnyTable>;
1148
+ /**
1149
+ * Immutable collection of tables and their relations with query entry points.
1150
+ *
1151
+ * A schema is not bound to a database, so queries built from it can be defined at module level.
1152
+ * A `Db` can execute such a query if its schema contains the tables and the selected relations of the query and every bound nested query belongs to that `Db`.
1153
+ */
1154
+ type Schema<T extends Tables, R extends SchemaRelations = EmptyRecord> = SchemaEntries<T, R> & SchemaMembers<T, R>;
1155
+ /** Query entry points; each access starts a query over a new table occurrence. */
1156
+ type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
1157
+ /** Members of a schema that composition reads: its tables and the relations of its tables. */
1158
+ interface SchemaContents<T extends Tables, R extends SchemaRelations> {
1159
+ readonly [schemaBrand]: true;
1160
+ /** Tables of the schema by their keys. */
1161
+ readonly $tables: T;
1162
+ /** Relation definitions by table key and relation name. */
1163
+ readonly [schemaRelations]: R;
1164
+ }
1165
+ interface SchemaMembers<T extends Tables, R extends SchemaRelations> extends SchemaContents<T, R> {
1166
+ /**
1167
+ * Creates a schema of the same tables with the relations of `relations` added, declared with `many` and `one` by their names under the keys of their tables.
1168
+ *
1169
+ * A relation refers to a table of the schema by columns of SQL types that `=` compares; a relation that the schema already has is rejected.
1170
+ */
1171
+ $relations<S extends AnySchema, D extends RelationDeclarations<S["$tables"]>>(this: S, relations: D & CheckDeclarations<S["$tables"], D>): Schema<S["$tables"], MergeRelations<S[typeof schemaRelations] & DeclaredRelations<S["$tables"], D>>>;
1172
+ /**
1173
+ * Starts an unbound query of one record whose fields are the values of the expressions and the results of the queries of `selection`, selected in one statement.
1174
+ *
1175
+ * The value of the field of a query is the result it gives when executed, such as an array of records or one value.
1176
+ */
1177
+ $select<Sel extends Selection>(selection: Sel): RecordQuery<SelectionState<Sel>>;
1178
+ }
1179
+ /** Schema of any tables and relations. */
1180
+ type AnySchema = SchemaContents<Tables, SchemaRelations>;
1181
+ /** Part of a schema definition: an object of tables by their keys, or a schema whose tables and relations it includes. */
1182
+ type SchemaPart = Tables | AnySchema;
1183
+ /**
1184
+ * Tables of the parts of a schema definition by their keys.
1185
+ *
1186
+ * A part typed as a union gives a union of tables, and parts of an array of unknown length give no tables, since any of them may be missing.
1187
+ */
1188
+ type SchemaTables<P extends readonly SchemaPart[]> = ComposeParts<P>["tables"] extends (infer T extends Tables) ? { [K in keyof T]: T[K]; } : never;
1189
+ /** Relations of the parts of a schema definition by table key and relation name, read as `SchemaTables` reads the tables. */
1190
+ type SchemaPartRelations<P extends readonly SchemaPart[]> = ComposeParts<P>["relations"] extends (infer R extends SchemaRelations) ? MergeRelations<R> : never;
1191
+ /** Tables and relations of the parts of a schema definition, intersected. */
1192
+ interface PartContents {
1193
+ readonly tables: Tables;
1194
+ readonly relations: SchemaRelations;
1195
+ }
1196
+ type ComposeParts<P extends readonly SchemaPart[], Composed extends PartContents = {
1197
+ tables: EmptyRecord;
1198
+ relations: EmptyRecord;
1199
+ }> = P extends readonly [infer First extends SchemaPart, ...infer Rest extends readonly SchemaPart[]] ? ComposeParts<Rest, Composed & ReadPart<First>> : P extends readonly [...infer Rest extends readonly SchemaPart[], infer Last extends SchemaPart] ? ComposeParts<Rest, Composed & ReadPart<Last>> : Composed;
1200
+ type ReadPart<P extends SchemaPart> = P extends SchemaContents<infer T, any> ? {
1201
+ tables: T;
1202
+ relations: P[typeof schemaRelations];
1203
+ } : {
1204
+ tables: P;
1205
+ relations: EmptyRecord;
1206
+ };
1207
+ /**
1208
+ * Defines a schema of the tables of `parts`, keyed by their names in queries.
1209
+ *
1210
+ * A part is an object of tables by their keys or another schema, whose tables and relations the new schema includes as they are, so queries built from that schema run on the new one.
1211
+ * A key of two different tables, a table under two keys, and two different definitions of a relation of a table are rejected; the same table under the same key or the same relation in several parts is one.
1212
+ */
1213
+ declare function defineSchema<P extends SchemaPart[]>(...parts: P): Schema<SchemaTables<P>, SchemaPartRelations<P>>;
1214
+ declare const sourceTable: unique symbol;
1215
+ declare const sourceKey: unique symbol;
1216
+ /** Runtime mark of the declarations of `many` and `one`. */
1217
+ declare const declarationBrand: unique symbol;
1218
+ /** Kind of a relation: `many` related records, or `one` related record at most. */
1219
+ type RelationKind = "many" | "one";
1220
+ /** Relation of a table of a schema to the records of table `Target`, which has key `TargetKey` in the schema. */
1221
+ interface Relation<Kind extends RelationKind = RelationKind, Target extends AnyTable = AnyTable, TargetKey extends string = string, Required extends boolean = boolean> {
1222
+ readonly kind: Kind;
1223
+ readonly target: Target;
1224
+ readonly targetKey: TargetKey;
1225
+ /** Whether every record of the table has its related record, so that a query of a relation `one` without a filter rejects without it rather than giving `null`; `false` for a relation `many`. */
1226
+ readonly required: Required;
1227
+ }
1228
+ /**
1229
+ * Relation of a table of a schema as `$relations` defines it: the columns of its keys, compared by SQL `=` in order.
1230
+ *
1231
+ * Composition includes a definition as it is, so a relation that several parts include is one definition.
1232
+ */
1233
+ interface RelationDefinition extends Relation {
1234
+ readonly name: string;
1235
+ /** Key of the source table. */
1236
+ readonly key: string;
1237
+ readonly source: AnyTable;
1238
+ readonly from: readonly string[];
1239
+ readonly to: readonly string[];
1240
+ }
1241
+ /** Relation `N` of the table under key `K` of a schema, of type `R`, whose records a query selects. */
1242
+ interface UsedRelation<K extends string = string, N extends string = string, R extends Relation = Relation> {
1243
+ readonly key: K;
1244
+ readonly name: N;
1245
+ readonly relation: R;
1246
+ }
1247
+ /** Relations of schema relations `R` that the queries of a `Db` of the schema may select. */
1248
+ type UsableRelation<R extends SchemaRelations> = { [K in keyof R & string]: { [N in keyof R[K] & string]: UsedRelation<K, N, R[K][N]>; }[keyof R[K] & string]; }[keyof R & string];
1249
+ /** Relations of the tables of a schema by table key and relation name. */
1250
+ type SchemaRelations = {
1251
+ readonly [key: string]: TableRelations;
1252
+ };
1253
+ /** Relations of a table of a schema by relation name. */
1254
+ type TableRelations = {
1255
+ readonly [name: string]: Relation;
1256
+ };
1257
+ /**
1258
+ * Declaration of a relation by `many` or `one`, which `$relations` of a schema defines for a table of type `Source` with key `From` of the source table.
1259
+ *
1260
+ * `Source` and `From` only type the keys of the source table.
1261
+ */
1262
+ interface RelationDeclaration<Kind extends RelationKind, Source extends AnyTable, Target extends AnyTable, From = unknown, Required extends boolean = boolean> {
1263
+ readonly [declarationBrand]: true;
1264
+ readonly kind: Kind;
1265
+ readonly target: Target;
1266
+ readonly from: readonly string[];
1267
+ readonly to: readonly string[];
1268
+ readonly required: Required;
1269
+ readonly [sourceTable]?: (source: Source) => void;
1270
+ readonly [sourceKey]?: From;
1271
+ }
1272
+ /** Column key of table `T` whose type has SQL `=`, which a relation can compare. */
1273
+ type EqualityKey<T extends AnyTable> = { [K in keyof T["columns"]]: HasEquality<ColumnOperators<T, K>> extends true ? K : never; }[keyof T["columns"]] & string;
1274
+ /** Key of a relation in table `T`: a column key, or a non-empty list of them for a composite key. */
1275
+ type RelationKey<T extends AnyTable> = EqualityKey<T> | readonly [EqualityKey<T>, ...EqualityKey<T>[]];
1276
+ /** Key of table `T` with as many columns as key `From`. */
1277
+ type MatchingKey<T extends AnyTable, From> = From extends string ? EqualityKey<T> : { readonly [I in keyof From]: EqualityKey<T>; };
1278
+ /** Keys of a relation: the columns `from` of the source table equal the columns `to` of the target table, in order. */
1279
+ interface RelationKeys<Target extends AnyTable, From> {
1280
+ readonly from: From;
1281
+ readonly to: MatchingKey<Target, From>;
1282
+ }
1283
+ /** Keys of a relation `one`, as in `RelationKeys`, and whether the relation is required. */
1284
+ interface OneRelationKeys<From, To> {
1285
+ readonly from: From;
1286
+ readonly to: To;
1287
+ /** Whether every record has its related record, such as by a foreign key on columns `from` that are not nullable, so that a query of the relation without a filter rejects without it rather than giving `null`. */
1288
+ readonly required?: boolean;
1289
+ }
1290
+ /** Members of the keys `K` of a relation `one` with only `required` typed, so that a call infers `K` with `required` as optional as it is, and reports a wrong key at its own member. */
1291
+ type RequiredMember<K> = { readonly [P in keyof K]: P extends "required" ? K[P] : unknown; };
1292
+ /** Whether the keys `K` of a relation `one` make it required: only where they set `required` to `true`, and `boolean` where `required` may be `true` or missing, such as `required?: true`. */
1293
+ type DeclaredRequiredOf<K> = K extends unknown ? "required" extends keyof K ? K extends {
1294
+ readonly required: infer Required;
1295
+ } ? IsTrue<Required> : IsTrue<K["required" & keyof K] | undefined> : false : never;
1296
+ /** `true` for `true`, and `false` for other values, such as `false` and `undefined`; a union gives the union of their results. */
1297
+ type IsTrue<T> = T extends true ? true : false;
1298
+ /** Declarations of `$relations` of a schema of tables `T`: relations by name, for tables by their keys. */
1299
+ type RelationDeclarations<T extends Tables> = { readonly [K in keyof T]?: {
1300
+ readonly [name: string]: RelationDeclaration<RelationKind, T[K], T[keyof T]>;
1301
+ }; };
1302
+ /**
1303
+ * Declarations `D` of `$relations` checked by the names they use: relations of the tables of `T` under their keys, and no other keys.
1304
+ *
1305
+ * Declarations under the names of `D` get their source table from this type even where the index signature of `RelationDeclarations` gives way to a member of `Object`, such as for a relation named `toString`.
1306
+ * A relation name must not be a column key of its table or start with `$`, since the references that the callback of `select` gets have both.
1307
+ */
1308
+ type CheckDeclarations<T extends Tables, D> = { readonly [K in keyof D]: [TableKey<T, K>] extends [never] ? never : undefined extends D[K] ? D[K] : { readonly [N in keyof D[K]]: `${N & (string | number)}` extends ReservedName<T[TableKey<T, K>]> ? never : RelationDeclaration<RelationKind, T[TableKey<T, K>], T[keyof T], RelationKey<T[TableKey<T, K>]>>; }; };
1309
+ /** Names that a relation of table `T` cannot have: the keys of its columns, and names starting with `$`. */
1310
+ type ReservedName<T extends AnyTable> = `${keyof T["columns"] & (string | number)}` | `$${string}`;
1311
+ /** Key of tables `T` written as key `K`, such as `1` for `"1"`, as object keys are strings at runtime. */
1312
+ type TableKey<T extends Tables, K> = { [P in keyof T]: `${P & (string | number)}` extends `${K & (string | number)}` ? P : never; }[keyof T];
1313
+ /** Relations that declarations `D` of a schema of tables `T` define, by table key and relation name, as strings like the keys of objects. */
1314
+ type DeclaredRelations<T extends Tables, D> = { [K in keyof D as K extends number ? `${K}` : K]: { [N in keyof D[K] as N extends number ? `${N}` : N]: D[K][N] extends RelationDeclaration<infer Kind, never, infer Target, unknown, infer Required> ? Relation<Kind, Target, KeyOfTable<T, Target>, Required> : never; }; };
1315
+ /** Column key of relation key `K`: the key itself, or a column of a composite key. */
1316
+ type RelationColumn<K> = K extends readonly unknown[] ? K[number] : K;
1317
+ /** Check of key `To` of a relation `one` that rejects it when its columns include no key of table `Target`, as far as the types tell. */
1318
+ type TargetKeyCheck<Target extends AnyTable, To> = [ContainsKey<Target, RelationColumn<To>>] extends [false] ? {
1319
+ readonly to: MissingKey<KeyOf<Target["keys"]>>;
1320
+ } : unknown;
1321
+ /** Type that a key `to` of a relation `one` without a key of its target is checked against, naming the keys of the target. */
1322
+ interface MissingKey<Keys> {
1323
+ readonly "columns to must include a key of the target": Keys;
1324
+ }
1325
+ /** Key of table `Target` among tables `T`, as a string like the keys of objects. */
1326
+ type KeyOfTable<T extends Tables, Target> = { [K in keyof T]: [T[K]] extends [Target] ? [Target] extends [T[K]] ? K extends number ? `${K}` : K & string : never : never; }[keyof T];
1327
+ /** Relations of `R` by table key, with the relations under the same key merged. */
1328
+ type MergeRelations<R> = { [K in keyof R]: { [N in keyof R[K]]: R[K][N]; }; };
1329
+ /** Relations of the schema that a query starts from, by table key, and the key of the table of the query there. */
1330
+ interface SchemaContext<R extends SchemaRelations = SchemaRelations, K extends string = string> {
1331
+ readonly relations: R;
1332
+ readonly key: K;
1333
+ }
1334
+ /** Schema context of a query whose table has no relations, such as one of `from(table)`. */
1335
+ type NoRelations = SchemaContext<EmptyRecord, string>;
1336
+ /** Schema context of the queries of the table under key `K` of a schema of relations `R`, whose keys are strings, as object keys are at runtime. */
1337
+ type TableContext<R extends SchemaRelations, K> = K extends keyof R ? [keyof R[K]] extends [never] ? NoRelations : SchemaContext<R, K & string> : K extends number ? TableContext<R, `${K}`> : NoRelations;
1338
+ /**
1339
+ * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1340
+ *
1341
+ * A composite key lists its columns in arrays of the same length.
1342
+ */
1343
+ declare function many<Source extends AnyTable, Target extends AnyTable, const From extends RelationKey<Source>>(target: Target, keys: RelationKeys<Target, From>): RelationDeclaration<"many", Source, Target, From, false>;
1344
+ /**
1345
+ * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1346
+ *
1347
+ * A composite key lists its columns in arrays of the same length.
1348
+ * The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
1349
+ * Without the record, a query of the relation gives `null`, and a query of a relation declared with `required: true` rejects unless it filters the record.
1350
+ * Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
1351
+ */
1352
+ declare function one<Source extends AnyTable, Target extends AnyTable, const From extends RelationKey<Source>, const To extends MatchingKey<Target, From>, const Keys extends object = EmptyRecord>(target: Target, keys: OneRelationKeys<From, To> & RequiredMember<Keys> & TargetKeyCheck<Target, To>): RelationDeclaration<"one", Source, Target, From, NoInfer<DeclaredRequiredOf<Keys>>>;
1353
+ /**
1354
+ * State in types of a query that inserts, updates, or deletes rows: its table and the relations of its schema, the rows mode of the rows it changes, and its result, which is their number until a selection returns their fields.
1355
+ *
1356
+ * Methods change only their own parts of the state.
1357
+ */
1358
+ interface MutationQueryState extends QueryState {
1359
+ readonly table: AnyTable;
1360
+ readonly schema: SchemaContext;
1361
+ /** Rows mode of the rows that the query changes, which `select`, `get`, and `pluck` return. */
1362
+ readonly changed: ResultRows;
1363
+ /** Whether the query returns the fields of the rows it changes rather than their number. */
1364
+ readonly returning: boolean;
1365
+ }
1366
+ /** State of a query that inserts, updates, or deletes rows of table `T` with schema context `C` in rows mode `Rows` and returns their number. */
1367
+ interface InitialMutationState<T extends AnyTable, C extends SchemaContext, Rows extends ResultRows> extends MutationQueryState {
1368
+ readonly table: T;
1369
+ readonly schema: C;
1370
+ readonly changed: Rows;
1371
+ readonly returning: false;
1372
+ readonly result: number;
1373
+ readonly rows: "one";
1374
+ readonly value: true;
1375
+ readonly uses: never;
1376
+ }
1377
+ /** State `S` of a mutation with the parts of `Changes` replaced. */
1378
+ type ChangeMutationState<S extends MutationQueryState, Changes extends Partial<MutationQueryState>> = { readonly [K in keyof MutationQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
1379
+ /** State of a mutation that returns the number of the rows it changes or their records, which `select` applies to. */
1380
+ type RecordMutationState = MutationQueryState & ({
1381
+ readonly returning: false;
1382
+ } | {
1383
+ readonly value: false;
1384
+ });
1385
+ /** State of a mutation of one row, which `get` applies to. */
1386
+ type OneRowMutationState = MutationQueryState & {
1387
+ readonly changed: "one" | "nullable" | "optional";
1388
+ };
1389
+ /** Record that the returned fields of a mutation of state `S` add to: the fields selected earlier, or none. */
1390
+ type ReturnedRecord$1<S extends MutationQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
1391
+ /** State of a mutation of state `S` that returns records with `Fields`, which its nested queries select records of relations `U` for. */
1392
+ type RecordsState<S extends MutationQueryState, Fields, U extends UsedRelation = never> = ChangeMutationState<S, {
1393
+ result: MergeSelection<ReturnedRecord$1<S>, Fields>;
1394
+ rows: S["changed"];
1395
+ value: false;
1396
+ returning: true;
1397
+ uses: S["uses"] | U;
1398
+ }>;
1399
+ /** State of a mutation of state `S` that returns value `V` of each row it changes in rows mode `Rows`. */
1400
+ type ValueState$1<S extends MutationQueryState, V, Rows extends ResultRows> = ChangeMutationState<S, {
1401
+ result: V;
1402
+ rows: Rows;
1403
+ value: true;
1404
+ returning: true;
1405
+ }>;
1406
+ /**
1407
+ * Immutable query of state `S` that inserts, updates, or deletes rows, unbound or bound to a `Db`.
1408
+ *
1409
+ * Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead.
1410
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
1411
+ * A bound query executes on its `Db` when awaited.
1412
+ */
1413
+ declare class MutationQuery<out S extends MutationQueryState, out Kind extends SelectQueryKind = "unbound"> {
1414
+ readonly table: S["table"];
1415
+ readonly node: MutationNode;
1416
+ /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
1417
+ readonly context: QueryContext;
1418
+ readonly types: S;
1419
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
1420
+ readonly db: QueryDb<Kind>;
1421
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
1422
+ readonly then: QueryThen<S, Kind>;
1423
+ constructor(table: S["table"], node: MutationNode,
1424
+ /** Relations of the table in the schema the query starts from, which `select` gives its callback. */
1425
+ context: QueryContext, db?: AnyDb);
1426
+ /** Returns all columns of each changed row, replacing fields under their keys, instead of the number of the rows. */
1427
+ select<S extends RecordMutationState, Kind extends SelectQueryKind>(this: MutationQuery<S, Kind>, all: "*"): MutationQuery<RecordsState<S, Selectable<S["table"]>>, Kind>;
1428
+ /** Returns the listed columns of each changed row, replacing fields under their keys, instead of the number of the rows. */
1429
+ select<S extends RecordMutationState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: MutationQuery<S, Kind>, ...keys: K[]): MutationQuery<RecordsState<S, Pick<Selectable<S["table"]>, K>>, Kind>;
1430
+ /**
1431
+ * Returns the expressions and nested queries that `callback` returns for each changed row, replacing fields under their keys, instead of the number of the rows.
1432
+ *
1433
+ * `callback` receives the columns of the changed row, with their values after an insert or an update and those of the deleted row, and the queries of the relations of the table, as the callback of `select` of a select query does.
1434
+ * A nested query reads the database as it was before the change, apart from the changed row.
1435
+ */
1436
+ select<S extends RecordMutationState, Kind extends SelectQueryKind, Sel extends Selection>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => Sel): MutationQuery<RecordsState<S, SelectionResult<Sel>, SelectionUses<Sel>>, Kind>;
1437
+ /**
1438
+ * Returns the value of a column of the changed row instead of the number of the rows, in a query that changes one row, such as of `insert` or `find`.
1439
+ *
1440
+ * A query of a nullable row resolves to `undefined` without the row.
1441
+ */
1442
+ 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>;
1443
+ /**
1444
+ * 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`.
1445
+ *
1446
+ * A query of a nullable row resolves to `undefined` without the row.
1447
+ */
1448
+ get<S extends OneRowMutationState, Kind extends SelectQueryKind, E extends TypedExpression>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): MutationQuery<ValueState$1<S, ExpressionValue<E>, OneValueRows<S["changed"]>>, Kind>;
1449
+ /** 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. */
1450
+ pluck<S extends MutationQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: MutationQuery<S, Kind>, key: K): MutationQuery<ValueState$1<S, Selectable<S["table"]>[K], ValueRows<S["changed"]>>, Kind>;
1451
+ /** 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. */
1452
+ pluck<S extends MutationQueryState, Kind extends SelectQueryKind, E extends TypedExpression>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]>) => E): MutationQuery<ValueState$1<S, ExpressionValue<E>, ValueRows<S["changed"]>>, Kind>;
1453
+ /**
1454
+ * Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
1455
+ *
1456
+ * A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
1457
+ */
1458
+ toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
1459
+ /** Creates a mutation of the same kind and `Db` with the node changes applied. */
1460
+ private derive;
1461
+ /** Creates the mutation that returns the value of `arg` of `method`, a column key or a callback that receives the columns and returns an expression, of each changed row. */
1462
+ private deriveValue;
1463
+ }
1464
+ /** Query of any state and kind that inserts, updates, or deletes rows. */
1465
+ type AnyMutationQuery = MutationQuery<any, SelectQueryKind>;
1466
+ /** Types of the fields of the rows of a query of SQL text by the names of the result columns they decode. */
1467
+ interface FieldTypes {
1468
+ readonly [key: string]: AnyType;
1469
+ readonly [key: symbol]: never;
1470
+ }
1471
+ /** Record of the values that the types of fields `F` decode. */
1472
+ type DecodedFields<F extends FieldTypes> = { -readonly [K in keyof F]: TypeOutput<F[K]>; };
1473
+ /**
1474
+ * 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.
1475
+ *
1476
+ * Methods change only their own parts of the state.
1477
+ */
1478
+ interface SqlQueryState extends QueryState {
1479
+ /** Rows mode of the rows of the statement, which `select`, `get`, and `pluck` return. */
1480
+ readonly returned: ResultRows;
1481
+ /** Whether the query returns the fields of the rows of the statement rather than their number. */
1482
+ readonly returning: boolean;
1483
+ }
1484
+ /** State of a query of SQL text that returns the number of the rows of its command tag. */
1485
+ interface InitialSqlQueryState extends SqlQueryState {
1486
+ readonly result: number;
1487
+ readonly rows: "one";
1488
+ readonly value: true;
1489
+ readonly uses: never;
1490
+ readonly returned: "many";
1491
+ readonly returning: false;
1492
+ }
1493
+ /** State `S` of a query of SQL text with the parts of `Changes` replaced. */
1494
+ type ChangeSqlQueryState<S extends SqlQueryState, Changes extends Partial<SqlQueryState>> = { readonly [K in keyof SqlQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
1495
+ /** State of a query of SQL text that returns the number of the rows or their records, which `select` applies to. */
1496
+ type RecordSqlQueryState = SqlQueryState & ({
1497
+ readonly returning: false;
1498
+ } | {
1499
+ readonly value: false;
1500
+ });
1501
+ /** State of a query of SQL text of one row, which `optional` applies to. */
1502
+ type OneRowSqlQueryState = SqlQueryState & {
1503
+ readonly returned: "one" | "nullable" | "optional";
1504
+ };
1505
+ /** State of a query of SQL text of one row that returns its number or its record, which `nullable` applies to. */
1506
+ type OneRecordSqlQueryState = OneRowSqlQueryState & RecordSqlQueryState;
1507
+ /** Record that the fields of a query of SQL text of state `S` add to: the fields selected earlier, or none. */
1508
+ type ReturnedRecord<S extends SqlQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
1509
+ /** State of a query of SQL text of state `S` whose rows are in rows mode `Rows`. */
1510
+ type RowsState<S extends SqlQueryState, Rows extends ResultRows> = ChangeSqlQueryState<S, {
1511
+ returned: Rows;
1512
+ rows: S["returning"] extends true ? Rows : "one";
1513
+ }>;
1514
+ /** State of a query of SQL text of state `S` that returns value `V` of each row in rows mode `Rows`. */
1515
+ type ValueState<S extends SqlQueryState, V, Rows extends ResultRows> = ChangeSqlQueryState<S, {
1516
+ result: V;
1517
+ rows: Rows;
1518
+ returned: Rows;
1519
+ value: true;
1520
+ returning: true;
1521
+ }>;
1522
+ /**
1523
+ * Immutable query of a statement of SQL text, bound to the `Db` that executes it when awaited.
1524
+ *
1525
+ * 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.
1526
+ */
1527
+ declare class SqlQuery<out S extends SqlQueryState> {
1528
+ readonly node: TextStatementNode;
1529
+ /** `Db` that executes the query when it is awaited. */
1530
+ readonly db: AnyDb;
1531
+ readonly types: S;
1532
+ /** Executes the query on its `Db`. */
1533
+ readonly then: QueryThen<S, "bound">;
1534
+ constructor(node: TextStatementNode,
1535
+ /** `Db` that executes the query when it is awaited. */
1536
+ db: AnyDb);
1537
+ /**
1538
+ * 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.
1539
+ *
1540
+ * A type of a column that can be `NULL` must be nullable.
1541
+ * The statement rejects without a column of a field, or with the column twice; other columns are ignored.
1542
+ */
1543
+ select<S extends RecordSqlQueryState, F extends FieldTypes>(this: SqlQuery<S>, fields: F): SqlQuery<ChangeSqlQueryState<S, {
1544
+ result: MergeSelection<ReturnedRecord<S>, DecodedFields<F>>;
1545
+ rows: S["returned"];
1546
+ value: false;
1547
+ returning: true;
1548
+ }>>;
1549
+ /**
1550
+ * Returns the value of the only column of the row of the statement instead of the number of the rows, decoded by `type`.
1551
+ *
1552
+ * Without a row, it rejects with `NotFoundError` unless `optional` makes the query resolve to `undefined`; it rejects several rows.
1553
+ * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
1554
+ */
1555
+ get<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, OneValueRows<S["returned"]>>>;
1556
+ /**
1557
+ * 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.
1558
+ *
1559
+ * A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
1560
+ */
1561
+ pluck<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, ValueRows<S["returned"]>>>;
1562
+ /**
1563
+ * 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.
1564
+ *
1565
+ * Before a selection, the query resolves to the number of the rows, `1`, and rejects as well.
1566
+ */
1567
+ take<S extends SqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, OneRow<S["returned"]>>>;
1568
+ /**
1569
+ * Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without the row.
1570
+ *
1571
+ * Before a selection, the query resolves to `0` without the row.
1572
+ */
1573
+ optional<S extends OneRowSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "optional">>;
1574
+ /**
1575
+ * Makes a query of one record, such as one of `take`, resolve to `null` without the row.
1576
+ *
1577
+ * 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.
1578
+ * Before a selection, the query resolves to `0` without the row.
1579
+ */
1580
+ nullable<S extends OneRecordSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "nullable">>;
1581
+ /** Compiles the query into SQL text and parameters, as its `Db` executes it. */
1582
+ toSQL(): SqlStatement;
1583
+ /** Creates a query of the same `Db` with the node changes applied. */
1584
+ private derive;
1585
+ /** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
1586
+ private deriveValue;
1587
+ /** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
1588
+ private changeOneRow;
1589
+ }
1590
+ /** Query of SQL text of any state. */
1591
+ type AnySqlQuery = SqlQuery<any>;
1592
+ /** Kind of a select query: `unbound`, or `bound` to a `Db`. */
1593
+ type SelectQueryKind = "unbound" | "bound";
1594
+ /**
1595
+ * `then` of a query of kind `Kind`: a bound query executes when awaited, and an unbound query is not thenable.
1596
+ *
1597
+ * Awaiting a query of either kind or returning it from an async function is a type error, since it may execute.
1598
+ */
1599
+ type QueryThen<S extends QueryState, Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? <R1 = QueryResult<S>, R2 = never>(onFulfilled?: ((result: QueryResult<S>) => R1 | PromiseLike<R1>) | null, onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null) => Promise<R1 | R2> : [Kind] extends ["unbound"] ? undefined : ((onFulfilled: never) => unknown) | undefined;
1600
+ /** `Db` of a query of kind `Kind`, which only a bound query has. */
1601
+ type QueryDb<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? AnyDb : [Kind] extends ["unbound"] ? undefined : AnyDb | undefined;
1602
+ /** Arguments of `toSQL` of a query of kind `Kind`: a bound query compiles with the options of its `Db`. */
1603
+ type ToSQLArgs<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? [] : [options?: CompileOptions];
1604
+ /** Query of any class, state, and kind: a select query of a table, a query of `$select`, one that inserts, updates, or deletes rows, or a query of SQL text. */
1605
+ type AnyQuery = AnySelectQuery | AnyRecordQuery | AnyMutationQuery | AnySqlQuery;
1606
+ /** Test fixture of `useTestFixture`, open while the tests of its `describe` block or test file run. */
1607
+ interface TestFixture<T = unknown> {
1608
+ /** Result of the seed of the fixture; reading it while the fixture is not open throws. */
1609
+ readonly data: T;
1610
+ }
1611
+ /** Test fixture opened by the transaction coordinator: an outer transaction of a database created for tests, which always rolls back when it closes. */
1612
+ interface OpenedTestFixture<T = unknown> extends AsyncDisposable {
1613
+ /** Result of the seed of the fixture, such as the records it created; reading it after the fixture closes throws. */
1614
+ readonly data: T;
1615
+ /** Rolls back the fixture and the fixtures opened inside it; closing a closed fixture does nothing. */
1616
+ close(): Promise<void>;
1617
+ }
1618
+ /** Test fixture that is being opened, with a `close` that can be called before it opens. */
1619
+ interface PendingTestFixture<T = unknown> {
1620
+ readonly fixture: Promise<OpenedTestFixture<T>>;
1621
+ close(): Promise<void>;
1622
+ }
1623
+ /**
1624
+ * Hooks of a test runner that run a function before and after the tests of the current `describe` block or test file.
1625
+ *
1626
+ * They are `before` and `after` of `node:test`, and `beforeAll` and `afterAll` of `bun:test` and Vitest.
1627
+ */
1628
+ interface TestHooks {
1629
+ before(hook: () => Promise<void>): unknown;
1630
+ after(hook: () => Promise<void>): unknown;
1631
+ }
1632
+ /** Options of `testTransaction`. */
1633
+ interface TestTransactionOptions {
1634
+ /**
1635
+ * Abort signal of the test, such as `t.signal` of `node:test` or `signal` of the test context of Vitest.
1636
+ *
1637
+ * When it aborts, the test transaction rejects the later queries of the test at once and rolls back without waiting for the test.
1638
+ * It then rejects with the reason of the signal.
1639
+ * If starting or rolling back the transaction fails, it rejects instead with a `SuppressedError` that keeps the reason.
1640
+ * Queries that the test has already sent complete before the rollback.
1641
+ */
1642
+ signal?: AbortSignal;
1643
+ }
1644
+ /** Test transactions and test fixtures of a database created with `test: true`. */
1645
+ interface TestHelpers {
1646
+ /**
1647
+ * Runs `callback` in a transaction that always rolls back.
1648
+ *
1649
+ * Wrap the body of every test in it, so that every run of the test gets its own transaction.
1650
+ * Inside an existing transaction, it starts a nested transaction that always rolls back.
1651
+ */
1652
+ testTransaction<T>(callback: () => Promise<T>, options?: TestTransactionOptions): Promise<T>;
1653
+ /**
1654
+ * 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.
1655
+ *
1656
+ * The fixture opens in the `before` hook and rolls back in the `after` hook.
1657
+ * 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.
1658
+ * Test fixtures nest: a new one opens inside the innermost open one, and test transactions run in the innermost one.
1659
+ * A fixture whose `seed` rejects rolls back and closes.
1660
+ */
1661
+ useTestFixture<T>(seed: () => Promise<T>): TestFixture<T>;
1662
+ }
1663
+ /** Creates the test helpers of a database created with `test: true`, registering fixtures with the hooks of a test runner. */
1664
+ declare function createTestHelpers(database: Database, hooks: TestHooks): TestHelpers;
1665
+ /**
1666
+ * Routes statements and scripts to the ambient transaction of the current async context or to the pool.
1667
+ *
1668
+ * This is the only place that decides which connection executes a statement.
1669
+ */
1670
+ declare class TransactionCoordinator {
1671
+ #private;
1672
+ readonly driver: Driver;
1673
+ /** Rejects statements and transactions outside a test transaction or the seed of a test fixture instead of running them on the pool. */
1674
+ readonly test: boolean;
1675
+ constructor(driver: Driver,
1676
+ /** Rejects statements and transactions outside a test transaction or the seed of a test fixture instead of running them on the pool. */
1677
+ test?: boolean);
1678
+ execute(statement: SqlStatement): Promise<DriverResult>;
1679
+ /** Executes a script of statements without parameters where `execute` executes a statement. */
1680
+ executeScript(text: string): Promise<void>;
1681
+ /**
1682
+ * Runs `callback` in a transaction that commits when it resolves and rolls back when it rejects.
1683
+ *
1684
+ * Inside a transaction, it runs `callback` in a savepoint nested in it.
1685
+ * A failed cleanup after an error rejects with a `SuppressedError` that keeps the original error in its `suppressed` chain.
1686
+ */
1687
+ transaction<T>(callback: () => Promise<T>): Promise<T>;
1688
+ /**
1689
+ * Runs `callback` in a transaction that always rolls back, on a coordinator created for tests.
1690
+ *
1691
+ * Inside a transaction, it runs `callback` in a savepoint nested in it that always rolls back.
1692
+ * When `signal` aborts, the level stops accepting statements at once and ends without waiting for `callback`.
1693
+ * Once the level ends, the transaction rejects with the reason of the signal.
1694
+ * A failure to start or end the level after the abort suppresses the reason in a `SuppressedError`.
1695
+ * 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`.
1696
+ */
1697
+ testTransaction<T>(callback: () => Promise<T>, { signal }?: TestTransactionOptions): Promise<T>;
1698
+ /**
1699
+ * Opens a test fixture: a transaction on a reserved connection, or a savepoint in the innermost open fixture, and runs `seed` in it.
1700
+ *
1701
+ * Test transactions started outside any transaction run in the innermost fixture.
1702
+ * A fixture whose `seed` rejects rolls back and closes.
1703
+ */
1704
+ createTestFixture<T>(seed: () => Promise<T>): Promise<OpenedTestFixture<T>>;
1705
+ /**
1706
+ * Starts opening a test fixture, see `createTestFixture`, and returns it with a `close` that can be called before it opens.
1707
+ *
1708
+ * 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.
1709
+ * Closing an open fixture also closes the fixtures opening in it.
1710
+ */
1711
+ startTestFixture<T>(seed: () => Promise<T>): PendingTestFixture<T>;
1712
+ /**
1713
+ * Closes the test fixtures, including those still opening, and then the driver, which waits for the running transactions to end.
1714
+ *
1715
+ * A driver waits for every reserved connection, so closing it under an open fixture would wait forever.
1716
+ * A failed closing of the driver suppresses the failures of closing the fixtures.
1717
+ * 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.
1718
+ */
1719
+ close(): Promise<void>;
1720
+ }
1721
+ /**
1722
+ * Physical database shared by all schemas bound to it.
1723
+ *
1724
+ * Its ambient transaction spans every schema bound to the same database, such as tenant and SaaS schemas.
1725
+ * Disposing it, such as with `await using`, closes it.
1726
+ */
1727
+ interface Database extends AsyncDisposable {
1728
+ /** Routes the statements and transactions of the database; `kern-orm/testing` runs test transactions and test fixtures through it. */
1729
+ readonly coordinator: TransactionCoordinator;
1730
+ /**
1731
+ * Binds a schema to this database, placing its tables in a PostgreSQL schema.
1732
+ *
1733
+ * A database can bind several schemas, which share its connections and transactions.
1734
+ */
1735
+ bind<T extends Tables, R extends SchemaRelations>(schema: Schema<T, R>, options?: BindOptions): Db<T, R>;
1736
+ /**
1737
+ * Starts a query of the SQL statement of the template, as `$query` of a `Db` does, for code without a `Db`.
1738
+ *
1739
+ * It names no tables of a `Db`: run a statement that interpolates them with `$query` of that `Db`.
1740
+ */
1741
+ query(strings: TemplateStringsArray, ...values: unknown[]): SqlQuery<InitialSqlQueryState>;
1742
+ /** Executes a script of statements without parameters, as `$script` of a `Db` does, for code without a `Db`. */
1743
+ script(text: string): Promise<void>;
1744
+ /**
1745
+ * Executes the script of the template, as `$script` of a `Db` does, for code without a `Db`.
1746
+ *
1747
+ * It names no tables of a `Db`: run a script that interpolates them with `$script` of that `Db`.
1748
+ */
1749
+ script(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;
1750
+ /** 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`. */
1751
+ execute(statement: SqlStatement): Promise<DriverResult>;
1752
+ /**
1753
+ * Runs `callback` in a transaction that queries of every bound schema join automatically.
1754
+ *
1755
+ * Inside an existing transaction, it starts a nested transaction.
1756
+ */
1757
+ transaction<T>(callback: () => Promise<T>): Promise<T>;
1758
+ /** Rolls back the open test fixtures and closes the connections of the driver once the running transactions end. */
1759
+ close(): Promise<void>;
1760
+ }
1761
+ /** Options of `createDatabase`. */
1762
+ interface DatabaseOptions {
1763
+ driver: Driver;
1764
+ /** 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. */
1765
+ test?: boolean;
1766
+ }
1767
+ /** Creates a database over a driver; its transactions are shared by every schema bound to it. */
1768
+ declare function createDatabase({ driver, test }: DatabaseOptions): Database;
1769
+ /** Physical placement of the tables of a schema bound to a database. */
1770
+ interface BindOptions {
1771
+ /** PostgreSQL schema of the tables; a function is called on every query, such as to resolve the current tenant. */
1772
+ schemaName?: string | (() => string);
1773
+ }
1774
+ /**
1775
+ * Schema bound to a database with `database.bind`.
1776
+ *
1777
+ * Its table entries start queries bound to it, which execute when awaited.
1778
+ */
1779
+ type Db<T extends Tables, R extends SchemaRelations = EmptyRecord> = DbEntries<T, R> & DbMethods<T, R>;
1780
+ /** Bound query entry points; each access starts a query over a new table occurrence. */
1781
+ type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
1782
+ /** Bound or unbound query over a table of `T`, of `$select`, or that changes the rows of a table of `T`, that selects records only of relations of `R`, or a query of SQL text. */
1783
+ type DbQuery<T extends Tables, R extends SchemaRelations> = QueryOf<DbQueryState<T[keyof T], UsableRelation<R>>> | RecordQuery<RecordQueryState<unknown, UsableRelation<R>>, SelectQueryKind> | MutationQuery<DbMutationState<T[keyof T], UsableRelation<R>>, SelectQueryKind> | SqlQuery<SqlQueryState>;
1784
+ /** State of a query that a `Db` can execute: over table `T`, selecting records only of relations `U`. */
1785
+ interface DbQueryState<T extends AnyTable, U extends UsedRelation> extends QueryStateOf<T> {
1786
+ readonly uses: U;
1787
+ }
1788
+ /** State of an insert, update, or delete query that a `Db` can execute: of table `T`, selecting records only of relations `U`. */
1789
+ interface DbMutationState<T extends AnyTable, U extends UsedRelation> extends MutationQueryState {
1790
+ readonly table: T;
1791
+ readonly uses: U;
1792
+ }
1793
+ interface DbMethods<T extends Tables, R extends SchemaRelations> {
1794
+ readonly $schema: Schema<T, R>;
1795
+ /**
1796
+ * Compiles a query over the tables of the schema into SQL text and parameters.
1797
+ *
1798
+ * A query bound to another `Db`, and a query of a relation that the schema does not have, at any depth, are rejected.
1799
+ */
1800
+ $compile<Q extends DbQuery<T, R>>(query: Q): SqlStatement;
1801
+ /**
1802
+ * Executes a query over the tables of the schema.
1803
+ *
1804
+ * A query bound to another `Db`, and a query of a relation that the schema does not have, at any depth, are rejected.
1805
+ */
1806
+ $execute<Q extends DbQuery<T, R>>(query: Q): Promise<QueryResult<Q["types"]>>;
1807
+ /**
1808
+ * Starts a query of one record whose fields are the values of the expressions and the results of the queries of `selection`, selected in one statement when awaited.
1809
+ *
1810
+ * A query of `selection` is unbound or bound to this `Db`, and the value of its field is the result it gives when executed, such as an array of records or one value.
1811
+ */
1812
+ $select<Sel extends Selection>(selection: Sel): RecordQuery<SelectionState<Sel>, "bound">;
1813
+ /**
1814
+ * Starts a query of the SQL statement of the template, which resolves to the number of the rows of its command tag when awaited, such as the rows that an `UPDATE` changes; `select`, `get`, and `pluck` return the fields of its rows instead.
1815
+ *
1816
+ * Interpolated values become query parameters, `sql` fragments and expressions stay SQL, and a table of the `Db`, such as `db.form`, becomes its name, qualified by the PostgreSQL schema of the `Db`.
1817
+ */
1818
+ $query(strings: TemplateStringsArray, ...values: unknown[]): SqlQuery<InitialSqlQueryState>;
1819
+ /**
1820
+ * 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.
1821
+ *
1822
+ * The script must not start or end transactions, which the database tracks.
1823
+ */
1824
+ $script(text: string): Promise<void>;
1825
+ /**
1826
+ * Executes the script of the template as `$script` of its text does.
1827
+ *
1828
+ * It interpolates tables of the `Db`, such as `db.form`, and `sql` fragments without values; it rejects values, since a script has no parameters.
1829
+ */
1830
+ $script(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;
1831
+ /**
1832
+ * Runs `callback` in a transaction of the database, shared by every schema bound to it.
1833
+ *
1834
+ * Inside an existing transaction, it starts a nested transaction.
1835
+ */
1836
+ $transaction<Result>(callback: () => Promise<Result>): Promise<Result>;
1837
+ }
1838
+ /**
1839
+ * `Db` of schema `S`, such as the type of a parameter of code shared by several schemas.
1840
+ *
1841
+ * A `Db` of a schema that includes `S` is a `Db` of `S` too.
1842
+ */
1843
+ type DbOf<S extends AnySchema> = Db<S["$tables"], S[typeof schemaRelations]>;
1844
+ /** `Db` of any schema. */
1845
+ type AnyDb = Db<any, any>;
1846
+ /** Occurrence of a table in `FROM`. */
1847
+ interface TableSourceNode {
1848
+ readonly kind: "table";
1849
+ readonly table: AnyTable;
1850
+ }
1851
+ /**
1852
+ * Occurrence of a subquery in `FROM`, whose columns are the projections of its query, referenced by their keys.
1853
+ *
1854
+ * A plain one sees only the sources of enclosing queries; a `LATERAL` one also sees the sources before it in the same `FROM`.
1855
+ */
1856
+ interface DerivedSourceNode {
1857
+ readonly kind: "derived";
1858
+ readonly query: SelectNode;
1859
+ readonly lateral: boolean;
1860
+ /**
1861
+ * Occurrence of a table in `FROM` of `query` that the derived source stands for outside it, such as with the rows of a page of the table.
1862
+ *
1863
+ * Outside `query`, a column reference to the occurrence resolves to the projection of `query` under the key of the column.
1864
+ */
1865
+ readonly replaces?: TableSourceNode;
1866
+ }
1867
+ /**
1868
+ * One occurrence of a source in `FROM`.
1869
+ *
1870
+ * Column references point to a source by object identity, so two occurrences of the same table never get confused.
1871
+ * The compiler assigns SQL aliases to sources.
1872
+ */
1873
+ type SourceNode = TableSourceNode | DerivedSourceNode;
1874
+ interface ColumnRefNode {
1875
+ readonly kind: "column";
1876
+ readonly source: SourceNode;
1877
+ /** Key of a column of a table, or of a projection of a derived source. */
1878
+ readonly key: string;
1879
+ }
1880
+ /** Value bound as a query parameter and numbered only when the complete statement is compiled. */
1881
+ interface ParamNode {
1882
+ readonly kind: "param";
1883
+ readonly value: unknown;
1884
+ readonly type: AnyType | undefined;
1885
+ }
1886
+ /** Cast of an expression to the `castType` of a type. */
1887
+ interface CastNode {
1888
+ readonly kind: "cast";
1889
+ readonly operand: ExpressionNode;
1890
+ readonly type: AnyType;
1891
+ }
1892
+ interface BooleanNode {
1893
+ readonly kind: "boolean";
1894
+ readonly value: boolean;
1895
+ }
1896
+ interface AndNode {
1897
+ readonly kind: "and";
1898
+ readonly operands: readonly ExpressionNode[];
1899
+ }
1900
+ interface OrNode {
1901
+ readonly kind: "or";
1902
+ readonly operands: readonly ExpressionNode[];
1903
+ }
1904
+ interface NotNode {
1905
+ readonly kind: "not";
1906
+ readonly operand: ExpressionNode;
1907
+ }
1908
+ /** Equality conditions by column key, resolved against the query source by `where` before compilation. */
1909
+ interface ValuesNode {
1910
+ readonly kind: "values";
1911
+ readonly values: Readonly<Record<string, unknown>>;
1912
+ }
1913
+ interface ComparisonNode {
1914
+ readonly kind: "comparison";
1915
+ readonly operator: "=" | "<>" | "<" | "<=" | ">" | ">=" | "LIKE" | "ILIKE";
1916
+ readonly left: ExpressionNode;
1917
+ readonly right: ExpressionNode;
1918
+ }
1919
+ interface InNode {
1920
+ readonly kind: "in";
1921
+ readonly operand: ExpressionNode;
1922
+ /** Never empty: an empty list is represented as a `FALSE` boolean node. */
1923
+ readonly list: readonly ExpressionNode[];
1924
+ }
1925
+ interface IsNullNode {
1926
+ readonly kind: "isNull";
1927
+ readonly operand: ExpressionNode;
1928
+ }
1929
+ /** SQL fragment whose interpolations stay structured nodes until compilation. */
1930
+ interface RawSqlNode {
1931
+ readonly kind: "raw";
1932
+ /** Text around interpolations; always one element longer than `values`. */
1933
+ readonly fragments: readonly string[];
1934
+ readonly values: readonly ExpressionNode[];
1935
+ }
1936
+ /** Name of a table interpolated into a SQL fragment, qualified by the PostgreSQL schema of the statement. */
1937
+ interface TableNameNode {
1938
+ readonly kind: "tableName";
1939
+ readonly table: AnyTable;
1940
+ /** `Db` that the interpolated query of the table is bound to, which must be the `Db` that runs the statement. */
1941
+ readonly db: AnyDb | undefined;
1942
+ }
1943
+ /** Scalar subquery: the value of the only projection of its query, which must return at most one row. */
1944
+ interface SubqueryNode {
1945
+ readonly kind: "subquery";
1946
+ readonly query: SelectNode;
1947
+ }
1948
+ interface ExistsNode {
1949
+ readonly kind: "exists";
1950
+ readonly query: SelectNode;
1951
+ }
1952
+ /** Call of an aggregate function over the rows of its query, with the order of its input rows. */
1953
+ interface AggregateNode {
1954
+ readonly kind: "aggregate";
1955
+ /** Name of the function, such as `json_agg`. */
1956
+ readonly name: string;
1957
+ /** Whether the function takes each distinct value of its arguments once, as `count(DISTINCT ...)`. */
1958
+ readonly distinct: boolean;
1959
+ readonly arguments: readonly ExpressionNode[];
1960
+ readonly orderBy: readonly OrderNode[];
1961
+ }
1962
+ type ExpressionNode = ColumnRefNode | ParamNode | CastNode | BooleanNode | AndNode | OrNode | NotNode | ValuesNode | ComparisonNode | InNode | IsNullNode | RawSqlNode | TableNameNode | SubqueryNode | ExistsNode | AggregateNode;
1963
+ /**
1964
+ * Filters of a query, kept apart so that composing one kind never changes the others.
1965
+ *
1966
+ * The effective predicate is `relation AND scope AND user`.
1967
+ * In particular, a user `OR` cannot bypass a relation condition.
1968
+ */
1969
+ interface QueryFilters {
1970
+ /** Correlation with the parent query of a relation. */
1971
+ readonly relation?: ExpressionNode;
1972
+ /** Mandatory restrictions such as soft delete. */
1973
+ readonly scope?: ExpressionNode;
1974
+ /** Conditions added with `where`. */
1975
+ readonly user?: ExpressionNode;
1976
+ }
1977
+ /**
1978
+ * Expression selected under the key of a result field.
1979
+ *
1980
+ * The key names only the field of the result record: it never shadows a column of a source.
1981
+ */
1982
+ type ProjectionNode = ResultField & {
1983
+ readonly expression: ExpressionNode;
1984
+ };
1985
+ /** Source joined with `LEFT JOIN` to the sources before it; its `ON` condition sees them and the joined source. */
1986
+ interface JoinNode {
1987
+ readonly type: "left";
1988
+ readonly source: SourceNode;
1989
+ readonly on: ExpressionNode;
1990
+ }
1991
+ /** Sort key of `ORDER BY`; `nulls` overrides the placement of `NULL` that PostgreSQL derives from the direction. */
1992
+ interface OrderNode {
1993
+ readonly expression: ExpressionNode;
1994
+ readonly direction: "asc" | "desc";
1995
+ readonly nulls: "first" | "last" | undefined;
1996
+ }
1997
+ /** Select query; its result mode applies only when it is executed or its rows are packed. */
1998
+ interface SelectNode<From extends SourceNode | undefined = SourceNode | undefined> extends ResultMode {
1999
+ readonly kind: "select";
2000
+ /** Source of `FROM`; a query without it has no joins. */
2001
+ readonly from: From;
2002
+ readonly joins: readonly JoinNode[];
2003
+ /** Projections in the order of the result fields, with unique keys; a query without them returns records without fields. */
2004
+ readonly projections: readonly ProjectionNode[];
2005
+ readonly filters: QueryFilters;
2006
+ readonly orderBy: readonly OrderNode[];
2007
+ readonly limit: ExpressionNode | undefined;
2008
+ readonly offset: ExpressionNode | undefined;
2009
+ /** Required relation that guarantees the row of the query, such as `field.form`; see `ResultPlan`. */
2010
+ readonly guaranteedBy: string | undefined;
2011
+ }
2012
+ /** Assignment of `SET` of an update: the value of the column under `key`. */
2013
+ interface AssignmentNode {
2014
+ readonly key: string;
2015
+ readonly value: ExpressionNode;
2016
+ }
2017
+ /**
2018
+ * Parts of a mutation statement of the table occurrence `target`, which its expressions refer to, and the result mode of the rows it changes.
2019
+ *
2020
+ * `returning` holds the fields of `RETURNING` of type `Field`, nested queries of a semantic mutation before lowering, or `undefined` for a statement that returns the number of the rows it changes.
2021
+ */
2022
+ interface MutationParts<Field> extends ResultMode {
2023
+ readonly target: TableSourceNode;
2024
+ readonly returning: readonly Field[] | undefined;
2025
+ }
2026
+ /** Insert statement of rows of `VALUES`. */
2027
+ interface InsertNode<Field = ProjectionNode> extends MutationParts<Field> {
2028
+ readonly kind: "insert";
2029
+ /** Keys of the columns of `VALUES`; none for a row of the defaults of every column. */
2030
+ readonly columns: readonly string[];
2031
+ /** Rows of `VALUES`, at least one, each with a value of every column in their order, or `undefined` for `DEFAULT`. */
2032
+ readonly values: readonly (readonly (ExpressionNode | undefined)[])[];
2033
+ }
2034
+ /** Update statement of the rows that its filters choose. */
2035
+ interface UpdateNode<Field = ProjectionNode> extends MutationParts<Field> {
2036
+ readonly kind: "update";
2037
+ /** Assignments of `SET`, at least one, with unique keys. */
2038
+ readonly set: readonly AssignmentNode[];
2039
+ readonly filters: QueryFilters;
2040
+ }
2041
+ /** Delete statement of the rows that its filters choose. */
2042
+ interface DeleteNode<Field = ProjectionNode> extends MutationParts<Field> {
2043
+ readonly kind: "delete";
2044
+ readonly filters: QueryFilters;
2045
+ }
2046
+ /** Statement that inserts, updates, or deletes rows, with the fields of `RETURNING` of type `Field`. */
2047
+ type MutationStatementNode<Field = ProjectionNode> = InsertNode<Field> | UpdateNode<Field> | DeleteNode<Field>;
2048
+ /**
2049
+ * Statement of SQL text written by a user, such as of `$query`.
2050
+ *
2051
+ * 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.
2052
+ */
2053
+ interface TextStatementNode extends ResultMode {
2054
+ readonly kind: "text";
2055
+ readonly sql: RawSqlNode;
2056
+ /** 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. */
2057
+ readonly fields: readonly ScalarField[] | undefined;
2058
+ }
2059
+ declare const valueType: unique symbol;
2060
+ declare const inputType: unique symbol;
2061
+ declare const typed: unique symbol;
2062
+ /** Expression of TypeScript type `T` accepting compared values of type `I`, whatever its operators. */
2063
+ interface AnyExpression<T = unknown, I = unknown> {
2064
+ readonly [valueType]: T;
2065
+ readonly [inputType]: I;
2066
+ }
2067
+ /** Expression of values `T` accepting compared values `I`, with `isNull` and operators `O`, whether or not it has a type. */
2068
+ type ExpressionWithOperators<T, O extends OperatorDefinitions, I> = AnyExpression<T, I> & Omit<BaseOperators, keyof O> & BoundOperators<O, T, I>;
2069
+ /**
2070
+ * Expression with a type, evaluating to a SQL value of TypeScript type `T`.
2071
+ *
2072
+ * Compared plain values are of type `I`, which differs from `T` when the type of the expression accepts other values than it returns, such as a `Date` for `timestamptz`.
2073
+ * It has `isNull` and the operators `O` of its type, which also decodes its values, so it can be selected.
2074
+ * The AST node behind it is internal.
2075
+ */
2076
+ type Expression<T = unknown, O extends OperatorDefinitions = EqualityOperators, I = T> = ExpressionWithOperators<T, O, I> & TypedExpression<T>;
2077
+ /**
2078
+ * Expression of TypeScript type `T` without a type, such as a fragment of `sql<T>`, with the operators of `equalityOperators`.
2079
+ *
2080
+ * Nothing decodes its values to `T`, so it cannot be selected.
2081
+ */
2082
+ type UntypedExpression<T = unknown> = ExpressionWithOperators<T, EqualityOperators, NoInfer<T>>;
2083
+ /** Expression that has a type to decode its values, which `select`, `get`, and `pluck` require. */
2084
+ type TypedExpression<T = unknown> = AnyExpression<T> & {
2085
+ readonly [typed]: true;
2086
+ };
2087
+ /** Operators of expressions of every type. */
2088
+ interface BaseOperators {
2089
+ isNull(): Expression<boolean>;
2090
+ }
2091
+ export { one as $, TextValue as $n, and as $t, SqlQueryState as A, ColumnOperators as An, UpdateValues as At, RelationDeclaration as B, NotFoundError as Bn, orderBy as Bt, AnyQuery as C, Operand as Cn, ResultOf as Ct, FieldTypes as D, AnyTable as Dn, ColumnValue as Dt, DecodedFields as E, CompileOptions as En, from as Et, DeclaredRelations as F, Table as Fn, OrderTerms as Ft, RequiredMember as G, Connection as Gn, WhereCondition as Gt, RelationKey as H, ResultDecodeError as Hn, NotAKey as Ht, MergeRelations as I, TableKeys as In, Ordering as It, TableContext as J, SqlStatement as Jn, defineFilter as Jt, SchemaContext as K, Driver as Kn, WhereFilter as Kt, NoRelations as L, TableOptions as Ln, SelectedRefs as Lt, InitialMutationState as M, ColumnValues as Mn, OrderDirection as Mt, MutationQuery as N, KeyColumns as Nn, OrderKey as Nt, InitialSqlQueryState as O, AnyTableKeys as On, InsertValues as Ot, MutationQueryState as P, Selectable as Pn, OrderTerm as Pt, many as Q, BaseType as Qn, Predicate as Qt, OneRelationKeys as R, ToColumns as Rn, asc as Rt, createTestHelpers as S, ComparisonSignature as Sn, FilteredStateRows as St, AnySqlQuery as T, compare as Tn, TableOrQuery as Tt, RelationKeys as U, ResultMode as Un, PrimaryKeyValues as Ut, RelationDeclarations as V, RequiredRelationError as Vn, KeyCheck as Vt, RelationKind as W, ResultRows as Wn, EqValue as Wt, UsableRelation as X, createStatement as Xn, Condition as Xt, TableRelations as Y, TransactionFailure as Yn, CombinedCondition as Yt, UsedRelation as Z, AnyType as Zn, ConditionOperand as Zt, PendingTestFixture as _, EqualityOperators as _n, GenericOperatorImplementation as _r, SelectionResult as _t, UntypedExpression as a, FilteredRows as an, TypeTransform as ar, Tables as at, TestHooks as b, equalityOperators as bn, BoundSelectQuery as bt, Db as c, QueryResult as cn, Column as cr, RecordQuery as ct, DbQueryState as d, EmptyRecord as dn, ToColumn as dr, ExpressionInput as dt, not as en, Type as er, AnySchema as et, Database as f, InitialQueryState as fn, BoundOperators as fr, ExpressionValue as ft, OpenedTestFixture as g, EqualityOperator as gn, GenericOperator as gr, Selection as gt, TransactionCoordinator as h, SelectQueryState as hn, OperatorDefinitions as hr, NestedQuery as ht, TypedExpression as i, RelationRefs as in, TypeOutput as ir, SchemaTables as it, AnyMutationQuery as j, ColumnShape as jn, OrderColumns as jt, SqlQuery as k, ColumnDefinitions as kn, UpdateSet as kt, DbMutationState as l, ResultByRows as ln, ColumnAttributes as lr, RecordQueryState as lt, createDatabase as m, QueryStateOf as mn, NoOperators as mr, MergeSelection as mt, BaseOperators as n, ColumnRefs as nn, TypeOperators as nr, SchemaPart as nt, AnyDb as o, OneRow as on, defineType as or, defineSchema as ot, DatabaseOptions as p, QueryState as pn, MergeOperators as pr, HelperFields as pt, SchemaRelations as q, DriverResult as qn, WhereValues as qt, Expression as r, QueryContext as rn, TypeOptions as rr, SchemaPartRelations as rt, BindOptions as s, OneValueRows as sn, AnyColumn as sr, AnyRecordQuery as st, AnyExpression as t, or as tn, TypeInput as tr, Schema as tt, DbOf as u, ValueRows as un, KeyKind as ur, SelectionState as ut, TestFixture as v, HasEquality as vn, OperatorSignature as vr, SelectionUses as vt, SelectQueryKind as w, OperandValue as wn, SelectQuery as wt, TestTransactionOptions as x, BooleanResult as xn, ChangeState as xt, TestHelpers as y, InSignature as yn, defineGenericOperator as yr, AnySelectQuery as yt, Relation as z, defineTable as zn, desc as zt };