kern-orm 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{database-BJ0hNYrF.mjs → database-CP4oapsQ.mjs} +2348 -1623
- package/dist/{index-Cag6_erK.d.mts → index-CoKpXcBp.d.mts} +1301 -772
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +90 -7
- package/dist/testing.d.mts +1 -1
- package/dist/testing.mjs +12 -3
- package/dist/{text-BTFErHIi.mjs → text-Cti9QLK7.mjs} +7 -1
- package/dist/{types-D9LtZ9W-.mjs → types-DfoL8Oi9.mjs} +1 -1
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs +2 -2
- package/package.json +2 -1
|
@@ -209,9 +209,9 @@ interface SqlStatement {
|
|
|
209
209
|
declare function createStatement(text: string, parameters?: readonly TextValue[]): SqlStatement;
|
|
210
210
|
/** Result of a statement. */
|
|
211
211
|
interface DriverResult {
|
|
212
|
-
/** Command of the tag that PostgreSQL completed the statement with, such as `SELECT` or `ROLLBACK` for a `COMMIT` of a failed transaction; a driver may give only the first word of a tag of several words, such as `CREATE` of `CREATE TABLE
|
|
213
|
-
readonly command: string;
|
|
214
|
-
/** Number of rows that the command tag reports, such as the rows that an `UPDATE` changes, also without `RETURNING`; `0`
|
|
212
|
+
/** Command of the tag that PostgreSQL completed the statement with, such as `SELECT` or `ROLLBACK` for a `COMMIT` of a failed transaction; a driver may give only the first word of a tag of several words, such as `CREATE` of `CREATE TABLE`; `null` for a statement that PostgreSQL completes without a tag, such as an empty text or only a comment. */
|
|
213
|
+
readonly command: string | null;
|
|
214
|
+
/** Number of rows that the command tag reports, such as the rows that an `UPDATE` changes, also without `RETURNING`; `0` when PostgreSQL reports none, such as for `BEGIN` or a statement without a command tag. */
|
|
215
215
|
readonly count: number;
|
|
216
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
217
|
readonly columns: readonly string[];
|
|
@@ -278,6 +278,13 @@ interface RecordTemplateField {
|
|
|
278
278
|
readonly key: string;
|
|
279
279
|
readonly value: unknown;
|
|
280
280
|
}
|
|
281
|
+
/** How code converts the decoded result of a query, by `map` and `transform` of the query: `map` runs before `transform`, since `map` does not apply after `transform`. */
|
|
282
|
+
interface ResultConversion {
|
|
283
|
+
/** Converts each record or value, also `null` of a `NULL` value, and is not called for a missing row. */
|
|
284
|
+
readonly map: ((row: unknown) => unknown) | undefined;
|
|
285
|
+
/** Converts the whole result, once: an array of rows, one row, or `null` or `undefined` of a missing row. */
|
|
286
|
+
readonly transform: ((result: unknown) => unknown) | undefined;
|
|
287
|
+
}
|
|
281
288
|
/**
|
|
282
289
|
* How a query returns its rows: `many` as an array; `one` as one row, rejecting without it; `nullable` as one row or `null` without it; `optional` as one row or `undefined` without it.
|
|
283
290
|
*
|
|
@@ -303,6 +310,8 @@ interface ResultPlan extends ResultMode {
|
|
|
303
310
|
* A record starts from it, so its keys keep their order whichever of them a row holds.
|
|
304
311
|
*/
|
|
305
312
|
readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
|
|
313
|
+
/** How code converts the result that the plan decodes; `undefined` for a query without `transform` and `map`. */
|
|
314
|
+
readonly conversion?: ResultConversion | undefined;
|
|
306
315
|
}
|
|
307
316
|
/** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
|
|
308
317
|
declare class NotFoundError extends Error {
|
|
@@ -328,13 +337,23 @@ declare class RequiredRelationError extends Error {
|
|
|
328
337
|
/** Path of the field of the relation from the result field that holds it, such as `fields[2].form`, after the index of the row of an executed query of rows `many`, such as `[2].form`. */
|
|
329
338
|
path: string);
|
|
330
339
|
}
|
|
331
|
-
/** Error thrown when a row does not match the result fields
|
|
340
|
+
/** Error thrown when a row does not match the result fields, a value fails to decode, or a callback of `transform` or `map` fails; the failure is its cause. */
|
|
332
341
|
declare class ResultDecodeError extends Error {
|
|
333
|
-
/**
|
|
342
|
+
/**
|
|
343
|
+
* 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`.
|
|
344
|
+
*
|
|
345
|
+
* A callback of `map` that fails has the path of its row, such as `fields[2]` or `[2]`, and one of `transform` the path of the field of its nested rows, such as `fields`.
|
|
346
|
+
* It is `undefined` for a row of the driver of another width than the result fields, and for a callback that fails on the only row or the whole result of an executed query.
|
|
347
|
+
*/
|
|
334
348
|
readonly path: string | undefined;
|
|
335
349
|
readonly name = "ResultDecodeError";
|
|
336
350
|
constructor(message: string,
|
|
337
|
-
/**
|
|
351
|
+
/**
|
|
352
|
+
* 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`.
|
|
353
|
+
*
|
|
354
|
+
* A callback of `map` that fails has the path of its row, such as `fields[2]` or `[2]`, and one of `transform` the path of the field of its nested rows, such as `fields`.
|
|
355
|
+
* It is `undefined` for a row of the driver of another width than the result fields, and for a callback that fails on the only row or the whole result of an executed query.
|
|
356
|
+
*/
|
|
338
357
|
path: string | undefined, options?: ErrorOptions);
|
|
339
358
|
}
|
|
340
359
|
/** Tells whether `T` is `any`: only `any` turns `1 & T` into a type that `0` extends. */
|
|
@@ -390,6 +409,11 @@ interface TableOptions<Column extends string = string, PrimaryKeyColumn extends
|
|
|
390
409
|
/** Unique keys of several columns; mark a unique key of one column with `unique()`. */
|
|
391
410
|
readonly unique?: readonly (readonly [Column, Column, ...Column[]])[];
|
|
392
411
|
}
|
|
412
|
+
/** Options of `createTableFactory`. */
|
|
413
|
+
interface TableFactoryOptions {
|
|
414
|
+
/** Returns the physical name of a column from its key, such as `toSnakeCase` does, for each column without an explicit `columnName()`. */
|
|
415
|
+
readonly columnName: (key: string) => string;
|
|
416
|
+
}
|
|
393
417
|
/** Record shape returned when all columns of a table are selected. */
|
|
394
418
|
type Selectable<T extends AnyTable> = { [K in keyof T["columns"]]: TypeOutput<T["columns"][K]["type"]>; };
|
|
395
419
|
/** Input values of the types of the columns. */
|
|
@@ -462,63 +486,26 @@ declare function defineTable<Name extends string, Definitions extends ColumnDefi
|
|
|
462
486
|
* A key of one column is marked on its column, and `options` list the columns of the keys of several columns.
|
|
463
487
|
*/
|
|
464
488
|
declare function defineTable<Name extends string, Definitions extends ColumnDefinitions, const Options extends TableOptions<ColumnKey<ToColumns<Definitions>>, PrimaryKeyOption<ToColumns<Definitions>>> | undefined>(name: Name, definitions: Definitions, options: Options): Table<Name, ToColumns<Definitions>, DefinedKeys<ToColumns<Definitions>, Options>>;
|
|
465
|
-
/** Physical placement of the tables of a query, fixed at compilation. */
|
|
466
|
-
interface CompileOptions {
|
|
467
|
-
/** PostgreSQL schema qualifying every table; tables stay unqualified when it is not set. */
|
|
468
|
-
schemaName?: string;
|
|
469
|
-
}
|
|
470
|
-
/**
|
|
471
|
-
* Value compared with an expression of type `T` accepting values of type `I`: a value, an expression, or a query of one value, such as of `get` or of an aggregate; `null` is matched with `isNull` instead.
|
|
472
|
-
*/
|
|
473
|
-
type Operand<T, I = T> = NonNullable<I> | AnyExpression<NonNullable<T> | null> | ScalarQuery<NonNullable<T> | null>;
|
|
474
|
-
/** SQL value of an operand, unwrapping an expression or a query. */
|
|
475
|
-
type OperandValue<V> = V extends AnyExpression<infer T> ? T : V extends ScalarQuery ? ScalarQueryValue<V> : V;
|
|
476
|
-
/** Boolean result that can be NULL when an input value can be NULL. */
|
|
477
|
-
type BooleanResult<T> = boolean | (null extends T ? null : never);
|
|
478
|
-
/** Signature of a generic operator comparing an expression with an operand of its type, such as `lt`. */
|
|
479
|
-
interface ComparisonSignature extends OperatorSignature {
|
|
480
|
-
readonly method: <V extends Operand<this["T"], this["I"]>>(value: V) => Expression<BooleanResult<this["T"] | OperandValue<V>>>;
|
|
481
|
-
}
|
|
482
|
-
/**
|
|
483
|
-
* Compares an expression with a value, another expression, or a query of one value, encoding a plain value with the type of the expression.
|
|
484
|
-
*
|
|
485
|
-
* Operators of custom types build comparisons with it, such as `compare(self, "ILIKE", pattern)`.
|
|
486
|
-
*/
|
|
487
|
-
declare function compare<T, V>(self: AnyExpression<T>, operator: ComparisonNode["operator"], value: V): Expression<BooleanResult<T | OperandValue<V>>>;
|
|
488
|
-
/** Runtime mark of the operators of `equalityOperators`, which tell that a type has SQL `=`. */
|
|
489
|
-
declare const equalityBrand: unique symbol;
|
|
490
|
-
/** Generic operator of `equalityOperators`, which gives the type it is added to SQL `=`. */
|
|
491
|
-
interface EqualityOperator<S extends OperatorSignature> extends GenericOperator<S> {
|
|
492
|
-
readonly [equalityBrand]: true;
|
|
493
|
-
}
|
|
494
|
-
/** Key of the method of a query of a table that returns its node as the values of `in`, or rejects a query of records. */
|
|
495
|
-
declare const valuesQueryNode: unique symbol;
|
|
496
|
-
/** Signature of `in`: membership in a list of operands of the expression type, or in the values of a query, such as of `pluck`; an empty list or query yields `FALSE`. */
|
|
497
|
-
interface InSignature extends OperatorSignature {
|
|
498
|
-
readonly method: <const L extends readonly Operand<this["T"], this["I"]>[] | ValuesQuery<NonNullable<this["T"]> | null>>(list: L) => Expression<L extends readonly unknown[] ? L extends readonly [] ? boolean : BooleanResult<this["T"] | OperandValue<L[number]>> : BooleanResult<this["T"] | (L extends ValuesQuery ? ValuesQueryValue<L> : never)>>;
|
|
499
|
-
}
|
|
500
|
-
/** Operators of `equalityOperators`. */
|
|
501
|
-
type EqualityOperators = {
|
|
502
|
-
eq: EqualityOperator<ComparisonSignature>;
|
|
503
|
-
ne: EqualityOperator<ComparisonSignature>;
|
|
504
|
-
in: EqualityOperator<InSignature>;
|
|
505
|
-
};
|
|
506
|
-
/** Tells whether operators `O` include an operator of `equalityOperators`, so that their type has SQL `=`. */
|
|
507
|
-
type HasEquality<O> = true extends { [K in keyof O]: O[K] extends {
|
|
508
|
-
readonly [equalityBrand]: true;
|
|
509
|
-
} ? true : false; }[keyof O] ? true : false;
|
|
510
489
|
/**
|
|
511
|
-
*
|
|
490
|
+
* Creates a table-definition function with the given naming convention, for an application to define its tables with.
|
|
512
491
|
*
|
|
513
|
-
*
|
|
492
|
+
* Its tables have the same types as those of `defineTable`.
|
|
514
493
|
*/
|
|
515
|
-
declare
|
|
494
|
+
declare function createTableFactory(factoryOptions: TableFactoryOptions): typeof defineTable;
|
|
516
495
|
/** Records of a query without selected fields. */
|
|
517
496
|
type EmptyRecord = Record<never, never>;
|
|
518
497
|
/** State of a query in types: the record or value of its rows, how its rows become its result, and the relations it selects records of. */
|
|
519
|
-
interface QueryState
|
|
520
|
-
/** Record of a row, or the value of its only field for a query made by `get`, `pluck`, an aggregate method, such as `count`, or `exists
|
|
498
|
+
interface QueryState {
|
|
499
|
+
/** Record of a row, or the value of its only field for a query made by `get`, `pluck`, an aggregate method, such as `count`, or `exists`, or what the callback of `map` or `transform` returns. */
|
|
521
500
|
readonly result: unknown;
|
|
501
|
+
/** How the rows become the result. */
|
|
502
|
+
readonly rows: ResultRows;
|
|
503
|
+
/**
|
|
504
|
+
* What a row is: a record for `false`, the value of its only field for `true`, or what a callback of code returns: of `map` for `"mapped"`, whichever the row was before it, or of `transform` for `"transformed"`, of the whole result.
|
|
505
|
+
*
|
|
506
|
+
* The states of the methods that read the fields of a row or the value of its only field narrow it to `false` or `true`, so that they reject a query that code converts.
|
|
507
|
+
*/
|
|
508
|
+
readonly value: boolean | "mapped" | "transformed";
|
|
522
509
|
/** Relations whose records the query and the queries nested in it select, which a `Db` must have. */
|
|
523
510
|
readonly uses: UsedRelation;
|
|
524
511
|
}
|
|
@@ -528,7 +515,7 @@ interface QueryValueType {
|
|
|
528
515
|
readonly operators: OperatorDefinitions;
|
|
529
516
|
}
|
|
530
517
|
/**
|
|
531
|
-
* State of a select query in types: its table, the relations of its schema, the record or value of its rows
|
|
518
|
+
* State of a select query in types: its table, the relations of its schema, the record or value of its rows, the type of its value or the types of its fields, how its rows become its result, and the relations it selects records of.
|
|
532
519
|
*
|
|
533
520
|
* Methods change only their own parts of the state.
|
|
534
521
|
*/
|
|
@@ -537,6 +524,8 @@ interface SelectQueryState extends QueryState {
|
|
|
537
524
|
readonly schema: SchemaContext;
|
|
538
525
|
/** Type of the value of a query of values, a `QueryValueType`; `never` for a query of records. */
|
|
539
526
|
readonly valueType: unknown;
|
|
527
|
+
/** Types of the values of the selected fields of a query of records, the values that each encodes and its operators, which the callback of `having` gives its references: a `SelectedFieldTypes`, or `EmptyRecord` without selected fields. */
|
|
528
|
+
readonly fieldTypes: unknown;
|
|
540
529
|
/**
|
|
541
530
|
* Whether a required relation guarantees the row of the query, such as of `field.form`.
|
|
542
531
|
*
|
|
@@ -544,7 +533,7 @@ interface SelectQueryState extends QueryState {
|
|
|
544
533
|
* The callback of a helper starts with it, so that the effect of the helper records whether the callback filters.
|
|
545
534
|
*/
|
|
546
535
|
readonly guaranteed: boolean;
|
|
547
|
-
/** Whether the query is made by an aggregate method, such as `count`, or by `exists`, which makes `get`, `pluck`, the aggregate methods, and `exists` reject it. */
|
|
536
|
+
/** Whether the query is made by an aggregate method, such as `count`, or by `exists`, or converted by `map`, which makes `get`, `pluck`, the aggregate methods, and `exists` reject it. */
|
|
548
537
|
readonly aggregate: boolean;
|
|
549
538
|
}
|
|
550
539
|
/** State of a query over table `T` with schema context `C`, whatever its result. */
|
|
@@ -560,12 +549,112 @@ interface QueryStateOf<T extends AnyTable, C extends SchemaContext = SchemaConte
|
|
|
560
549
|
interface InitialQueryState<T extends AnyTable, C extends SchemaContext = NoRelations, U extends UsedRelation = never, Rows extends ResultRows = "many", Guaranteed extends boolean = false> extends QueryStateOf<T, C> {
|
|
561
550
|
readonly result: EmptyRecord;
|
|
562
551
|
readonly valueType: never;
|
|
552
|
+
readonly fieldTypes: EmptyRecord;
|
|
563
553
|
readonly rows: Rows;
|
|
564
554
|
readonly value: false;
|
|
565
555
|
readonly uses: U;
|
|
566
556
|
readonly guaranteed: Guaranteed;
|
|
567
557
|
readonly aggregate: false;
|
|
568
558
|
}
|
|
559
|
+
/** Mark of `aggregate: false` of a query of groups, which aggregate methods replace. */
|
|
560
|
+
interface Grouped {
|
|
561
|
+
readonly grouped: true;
|
|
562
|
+
}
|
|
563
|
+
/** Key of the value of a query in an expression, for types only. */
|
|
564
|
+
declare const scalarValue: unique symbol;
|
|
565
|
+
/** Value of a query of state `S` in an expression: its value, or `NULL` without its row unless the query always has it. */
|
|
566
|
+
type ScalarValue<S extends SelectQueryState> = S["aggregate"] extends true ? S["result"] : S["guaranteed"] extends true ? S["result"] : S["result"] | null;
|
|
567
|
+
/**
|
|
568
|
+
* Query of one value of a table, such as of `get`, of an aggregate, or of `exists`, which an expression takes as a scalar subquery of its value, or as `EXISTS` of the rows of a query of `exists`.
|
|
569
|
+
*
|
|
570
|
+
* `T` is its value there: without its row, a query of `get` is `NULL`, unless a required relation guarantees the row, such as of `field.form`.
|
|
571
|
+
*/
|
|
572
|
+
interface ScalarQuery<T = unknown> {
|
|
573
|
+
/** Value of the query in an expression, from which an expression infers `T`. */
|
|
574
|
+
readonly [scalarValue]: T;
|
|
575
|
+
readonly types: ScalarQueryState;
|
|
576
|
+
readonly exists: unknown;
|
|
577
|
+
}
|
|
578
|
+
/** Value of query `Q` of one value in an expression. */
|
|
579
|
+
type ScalarQueryValue<Q extends ScalarQuery> = Q[typeof scalarValue];
|
|
580
|
+
/** Relations whose records `E`, an expression or a query of one value that a callback returns, selects: those of a query, as an expression does not carry the relations of its queries. */
|
|
581
|
+
type OperandUses<E> = E extends ScalarQuery ? E["types"]["uses"] : never;
|
|
582
|
+
/** State of a query of one value, which an expression takes. */
|
|
583
|
+
interface ScalarQueryState extends SelectQueryState {
|
|
584
|
+
readonly rows: "one" | "optional";
|
|
585
|
+
readonly value: true;
|
|
586
|
+
}
|
|
587
|
+
/** State of a query of one value with the type of its value, whose expression `expr` gives. */
|
|
588
|
+
interface ExpressionQueryState extends ScalarQueryState {
|
|
589
|
+
readonly valueType: QueryValueType;
|
|
590
|
+
}
|
|
591
|
+
/** Query of one value of a table with the type of its value, such as of `get` or of an aggregate, which gives the expression of a function the decoding and the operators of its value. */
|
|
592
|
+
interface TypedScalarQuery extends ScalarQuery {
|
|
593
|
+
readonly types: ExpressionQueryState;
|
|
594
|
+
}
|
|
595
|
+
/** Query of values of a table of any rows, such as of `pluck`, whose value is `T`, which `in` takes as a subquery of its values. */
|
|
596
|
+
interface ValuesQuery<T = unknown> {
|
|
597
|
+
readonly types: ValuesQueryState<T>;
|
|
598
|
+
readonly exists: unknown;
|
|
599
|
+
}
|
|
600
|
+
/** Value of query `Q` of values, of each of its rows. */
|
|
601
|
+
type ValuesQueryValue<Q extends ValuesQuery> = Q["types"]["result"];
|
|
602
|
+
/** State of a query of values whose value is `T`. */
|
|
603
|
+
interface ValuesQueryState<T> extends SelectQueryState {
|
|
604
|
+
readonly result: T;
|
|
605
|
+
readonly value: true;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Value compared with an expression of type `T` accepting values of type `I`: a value, an expression, or a query of one value, such as of `get` or of an aggregate; `null` is matched with `isNull` instead.
|
|
609
|
+
*/
|
|
610
|
+
type Operand<T, I = T> = NonNullable<I> | AnyExpression<NonNullable<T> | null> | ScalarQuery<NonNullable<T> | null>;
|
|
611
|
+
/** SQL value of an operand, unwrapping an expression or a query. */
|
|
612
|
+
type OperandValue<V> = V extends AnyExpression<infer T> ? T : V extends ScalarQuery ? ScalarQueryValue<V> : V;
|
|
613
|
+
/** Boolean result that can be NULL when an input value can be NULL. */
|
|
614
|
+
type BooleanResult<T> = boolean | (null extends T ? null : never);
|
|
615
|
+
/** Signature of a generic operator comparing an expression with an operand of its type, such as `lt`. */
|
|
616
|
+
interface ComparisonSignature extends OperatorSignature {
|
|
617
|
+
readonly method: <V extends Operand<this["T"], this["I"]>>(value: V) => Expression<BooleanResult<this["T"] | OperandValue<V>>>;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Compares an expression with a value, another expression, or a query of one value, encoding a plain value with the type of the expression.
|
|
621
|
+
*
|
|
622
|
+
* Operators of custom types build comparisons with it, such as `compare(self, "ILIKE", pattern)`.
|
|
623
|
+
*/
|
|
624
|
+
declare function compare<T, V>(self: AnyExpression<T>, operator: ComparisonNode["operator"], value: V): Expression<BooleanResult<T | OperandValue<V>>>;
|
|
625
|
+
/** Runtime mark of the operators of `equalityOperators`, which tell that a type has SQL `=`. */
|
|
626
|
+
declare const equalityBrand: unique symbol;
|
|
627
|
+
/** Generic operator of `equalityOperators`, which gives the type it is added to SQL `=`. */
|
|
628
|
+
interface EqualityOperator<S extends OperatorSignature> extends GenericOperator<S> {
|
|
629
|
+
readonly [equalityBrand]: true;
|
|
630
|
+
}
|
|
631
|
+
/** Key of the method of a query of a table that returns its node as the values of `in`, or rejects a query of records. */
|
|
632
|
+
declare const valuesQueryNode: unique symbol;
|
|
633
|
+
/** Signature of `in`: membership in a list of operands of the expression type, or in the values of a query, such as of `pluck`; an empty list or query yields `FALSE`. */
|
|
634
|
+
interface InSignature extends OperatorSignature {
|
|
635
|
+
readonly method: <const L extends readonly Operand<this["T"], this["I"]>[] | ValuesQuery<NonNullable<this["T"]> | null>>(list: L) => Expression<L extends readonly unknown[] ? L extends readonly [] ? boolean : BooleanResult<this["T"] | OperandValue<L[number]>> : BooleanResult<this["T"] | (L extends ValuesQuery ? ValuesQueryValue<L> : never)>>;
|
|
636
|
+
}
|
|
637
|
+
/** Operators of `equalityOperators`. */
|
|
638
|
+
type EqualityOperators = {
|
|
639
|
+
eq: EqualityOperator<ComparisonSignature>;
|
|
640
|
+
ne: EqualityOperator<ComparisonSignature>;
|
|
641
|
+
in: EqualityOperator<InSignature>;
|
|
642
|
+
};
|
|
643
|
+
/** Tells whether operators `O` include an operator of `equalityOperators`, so that their type has SQL `=`. */
|
|
644
|
+
type HasEquality<O> = true extends { [K in keyof O]: O[K] extends {
|
|
645
|
+
readonly [equalityBrand]: true;
|
|
646
|
+
} ? true : false; }[keyof O] ? true : false;
|
|
647
|
+
/**
|
|
648
|
+
* Operators of SQL equality: `eq`, `ne`, and `in`; `orderingOperators` include them.
|
|
649
|
+
*
|
|
650
|
+
* 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 `=`.
|
|
651
|
+
*/
|
|
652
|
+
declare const equalityOperators: EqualityOperators;
|
|
653
|
+
/** Physical placement of the tables of a query, fixed at compilation. */
|
|
654
|
+
interface CompileOptions {
|
|
655
|
+
/** PostgreSQL schema qualifying every table; tables stay unqualified when it is not set. */
|
|
656
|
+
schemaName?: string;
|
|
657
|
+
}
|
|
569
658
|
/** Selection of the rows of a nested query as the value of the field `key`. */
|
|
570
659
|
interface NestedSelectionNode {
|
|
571
660
|
readonly key: string;
|
|
@@ -591,13 +680,31 @@ interface QueryNode extends ResultMode {
|
|
|
591
680
|
/** Fields in the order of the result, with unique keys; a query without them returns records without fields. */
|
|
592
681
|
readonly projections: readonly SelectedNode[];
|
|
593
682
|
readonly filters: QueryFilters;
|
|
683
|
+
/** Keys of the groups of the rows; a query with them gives one row of each group. */
|
|
684
|
+
readonly groupBy: readonly ExpressionNode[];
|
|
685
|
+
/** Condition of the groups, apart from `filters`, which choose the rows that they group. */
|
|
686
|
+
readonly having: ExpressionNode | undefined;
|
|
594
687
|
readonly orderBy: readonly OrderNode[];
|
|
595
688
|
readonly limit: ExpressionNode | undefined;
|
|
596
689
|
readonly offset: ExpressionNode | undefined;
|
|
690
|
+
/** Whether `distinct` removes the duplicates of the rows, comparing the fields that the query selects when it compiles. */
|
|
691
|
+
readonly distinct: boolean;
|
|
692
|
+
/** Keys of `distinctOn`, whose equal values give one row, the first in the order of the query; none without `distinctOn`. */
|
|
693
|
+
readonly distinctOn: readonly ExpressionNode[];
|
|
694
|
+
/**
|
|
695
|
+
* Fields of a query of `distinct` or `distinctOn` that an aggregate method or `exists` replaced, or `undefined` otherwise.
|
|
696
|
+
*
|
|
697
|
+
* `distinct` compares them, and the keys, the order, and the argument of the aggregate read a selected field through its projection.
|
|
698
|
+
*/
|
|
699
|
+
readonly distinctFields: readonly SelectedNode[] | undefined;
|
|
700
|
+
/** Lock of the rows that the query reads. */
|
|
701
|
+
readonly lock: RowLockNode | undefined;
|
|
597
702
|
/** Whether a required relation guarantees the row of the query, so that a filter makes a query of rows `one` resolve without it; see `SelectQueryState`. */
|
|
598
703
|
readonly guaranteed: boolean;
|
|
599
704
|
/** Whether `all` allows a mutation of the query to change every row of the table without a filter. */
|
|
600
705
|
readonly all: boolean;
|
|
706
|
+
/** How `map` and `transform` convert the decoded result. */
|
|
707
|
+
readonly conversion: ResultConversion | undefined;
|
|
601
708
|
}
|
|
602
709
|
/**
|
|
603
710
|
* Mutation of a table that returns the fields of the rows it changes, which may nest queries, or the number of the rows without them.
|
|
@@ -611,31 +718,25 @@ interface RecordQueryNode {
|
|
|
611
718
|
/** Fields in the order of the record, with unique keys. */
|
|
612
719
|
readonly projections: readonly SelectedNode[];
|
|
613
720
|
}
|
|
614
|
-
/**
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
721
|
+
/** Type of a count: a `bigint` of PostgreSQL decoded as a number, rejecting a count that a number cannot hold exactly. */
|
|
722
|
+
declare const countType: BaseType<number, number, MergeOperators<NoOperators, {
|
|
723
|
+
eq: EqualityOperator<ComparisonSignature>;
|
|
724
|
+
ne: EqualityOperator<ComparisonSignature>;
|
|
725
|
+
in: EqualityOperator<InSignature>;
|
|
726
|
+
lt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
727
|
+
lte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
728
|
+
gt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
729
|
+
gte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
730
|
+
}>, undefined>;
|
|
731
|
+
/** Type of the value of a query of a count. */
|
|
732
|
+
interface CountValueType extends QueryValueType {
|
|
733
|
+
readonly input: TypeInput<typeof countType>;
|
|
734
|
+
readonly operators: TypeOperators<typeof countType>;
|
|
627
735
|
}
|
|
628
|
-
/**
|
|
629
|
-
* Creates a field of a selection with `value` in every record, without selecting anything in SQL: the query returns the value itself, not a copy of it, whatever it is.
|
|
630
|
-
*
|
|
631
|
-
* It lets a branch of a selection skip a column or a nested query, such as `withHint ? field.hint : literal(null)`.
|
|
632
|
-
* To use a value in SQL, such as in a condition, pass it through `param` instead.
|
|
633
|
-
*/
|
|
634
|
-
declare function literal<T extends {} | null | undefined>(value: T): Literal<T>;
|
|
635
736
|
/** Rows mode of a query of a relation of kind `Kind`: `many`, or one row, `nullable` unless `Required` is `true`; a union gives the union of their modes. */
|
|
636
737
|
type RelationRows<Kind extends RelationKind, Required extends boolean> = Kind extends "many" ? "many" : Required extends true ? "one" : "nullable";
|
|
637
|
-
/** Rows mode after a filter of a query whose row a required relation guarantees: `one` becomes `nullable`, or `optional` for a query of values; other modes stay. */
|
|
638
|
-
type FilteredRows<Rows extends ResultRows, Value
|
|
738
|
+
/** Rows mode after a filter of a query whose row a required relation guarantees: `one` becomes `nullable`, or `optional` for a query of values that `map` does not convert; other modes stay. */
|
|
739
|
+
type FilteredRows<Rows extends ResultRows, Value> = Rows extends "one" ? Value extends true ? "optional" : "nullable" : Rows;
|
|
639
740
|
/** Rows mode after `take`: `many` becomes `one`; the modes of one row stay. */
|
|
640
741
|
type OneRow<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows;
|
|
641
742
|
/** Rows mode after `pluck`: `nullable` becomes `optional`; the other modes stay. */
|
|
@@ -650,434 +751,117 @@ type OneValueRows<Rows extends ResultRows> = Rows extends "many" ? "one" : Rows
|
|
|
650
751
|
type QueryResult<S extends QueryState> = S extends QueryState ? ResultByRows<S["result"], S["rows"]> : never;
|
|
651
752
|
/** Result of rows of `Result` returned in rows mode `Rows`; a union of modes gives the union of their results. */
|
|
652
753
|
type ResultByRows<Result, Rows extends ResultRows> = Rows extends "many" ? Result[] : Rows extends "one" ? Result : Rows extends "nullable" ? Result | null : Result | undefined;
|
|
653
|
-
/**
|
|
654
|
-
interface
|
|
655
|
-
readonly
|
|
656
|
-
readonly
|
|
657
|
-
}
|
|
658
|
-
/** Query whose rows a selection nests as the value of a field: a query of any state and kind, such as a query of a relation. */
|
|
659
|
-
type NestedQuery = QueryOf<SelectQueryState>;
|
|
660
|
-
/** Record of the values of the expressions, of the nested rows, and of the literals of a selection. */
|
|
661
|
-
type SelectionResult<S extends Selection> = { [K in keyof S]: FieldValue<S[K]>; };
|
|
662
|
-
/** Value of a selected field: of an expression, of the nested rows of a query as the result of executing it, or of a literal, for each member of a union of them. */
|
|
663
|
-
type FieldValue<V> = V extends NestedQuery ? QueryResult<V["types"]> : V extends Literal<infer T> ? T : ExpressionValue<V>;
|
|
664
|
-
/** Relations whose records the nested queries of a selection select. */
|
|
665
|
-
type SelectionUses<S extends Selection> = S[keyof S] extends (infer V) ? V extends NestedQuery ? V["types"]["uses"] : never : never;
|
|
666
|
-
/** Value of a selected expression. */
|
|
667
|
-
type ExpressionValue<E> = E extends AnyExpression<infer T> ? T : never;
|
|
668
|
-
/** Values that the type of an expression encodes, such as in place of its value. */
|
|
669
|
-
type ExpressionInput<E> = E extends AnyExpression<unknown, infer I> ? I : never;
|
|
670
|
-
declare const helperFields: unique symbol;
|
|
671
|
-
/** Marker of the input fields of a helper, carrying the keys selected by its callback. */
|
|
672
|
-
interface HelperFields<Keys extends PropertyKey = PropertyKey> {
|
|
673
|
-
readonly [helperFields]: Keys;
|
|
674
|
-
}
|
|
675
|
-
/** Records with `Fields` added or replaced, for each branch of either record type; `any` stays `any`. */
|
|
676
|
-
type MergeSelection<Previous, Fields> = Previous extends unknown ? Fields extends unknown ? MergeFields<RecordFields<Previous>, RecordFields<Fields>> & (IsAny<Previous> extends true ? Previous : unknown) : never : never;
|
|
677
|
-
/** Fields with numeric keys represented as the string keys used in result records. */
|
|
678
|
-
type RecordFields<Fields> = Fields extends unknown ? [Extract<keyof Fields, number>] extends [never] ? Fields : { [K in keyof Fields as K extends number ? `${K}` : K]: Fields[K]; } : never;
|
|
679
|
-
/** Merge of normalized fields, retaining the previous value when an optional replacement is absent. */
|
|
680
|
-
type MergeFields<Previous, Fields> = Simplify<{ [K in keyof Previous as K extends keyof Fields ? ({} extends Pick<Fields, K> ? K : never) : K]: K extends typeof helperFields // A branch selecting extra keys must not be reduced to one selecting fewer fields or none.
|
|
681
|
-
? Previous[K] | keyof Fields : K extends keyof Fields // A decoder can return undefined, so it cannot be excluded as merely an absent property.
|
|
682
|
-
? Previous[K] | Fields[K] : Previous[K]; } & { [K in keyof Fields as K extends keyof Previous ? ({} extends Pick<Fields, K> ? never : K) : K]: Fields[K]; }>;
|
|
683
|
-
/** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
|
|
684
|
-
interface RecordQueryState$1<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
|
|
685
|
-
readonly result: R;
|
|
686
|
-
readonly rows: "one";
|
|
687
|
-
readonly value: false;
|
|
688
|
-
readonly uses: U;
|
|
754
|
+
/** Type of the value of a query of `exists`. */
|
|
755
|
+
interface ExistsValueType extends QueryValueType {
|
|
756
|
+
readonly input: boolean;
|
|
757
|
+
readonly operators: EqualityOperators;
|
|
689
758
|
}
|
|
690
|
-
|
|
691
|
-
|
|
759
|
+
declare const conditionValues: unique symbol;
|
|
760
|
+
/** Predicate accepted by `where`, `and`, `or`, and `not`; SQL treats a `NULL` predicate as not satisfied. */
|
|
761
|
+
type Predicate = AnyExpression<boolean | null>;
|
|
692
762
|
/**
|
|
693
|
-
*
|
|
763
|
+
* Condition combining expressions with objects of column values, such as `or({ published: true }, form.id.in(ids))`.
|
|
694
764
|
*
|
|
695
|
-
*
|
|
696
|
-
* A bound query executes on its `Db` when awaited.
|
|
765
|
+
* `where` matches the objects against the columns of its query, so a condition is accepted only where `V` matches the table.
|
|
697
766
|
*/
|
|
698
|
-
|
|
699
|
-
readonly
|
|
700
|
-
readonly types: S;
|
|
701
|
-
/** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
|
|
702
|
-
readonly db: QueryDb<Kind>;
|
|
703
|
-
/** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
|
|
704
|
-
readonly then: QueryThen<S, Kind>;
|
|
705
|
-
constructor(node: RecordQueryNode, db?: AnyDb);
|
|
706
|
-
/**
|
|
707
|
-
* Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
|
|
708
|
-
*
|
|
709
|
-
* A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
|
|
710
|
-
*/
|
|
711
|
-
toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
|
|
712
|
-
/** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
|
|
713
|
-
[operandNode](): never;
|
|
767
|
+
interface Condition<V> {
|
|
768
|
+
readonly [conditionValues]?: V;
|
|
714
769
|
}
|
|
715
|
-
/** Query of `$select` of any state and kind. */
|
|
716
|
-
type AnyRecordQuery = RecordQuery<any, SelectQueryKind>;
|
|
717
|
-
declare const schemaBrand: unique symbol;
|
|
718
|
-
/** Key of the relation definitions of a schema, which composition reads. */
|
|
719
|
-
declare const schemaRelations: unique symbol;
|
|
720
|
-
/** Tables by their keys; a key must not start with `$`, which is reserved for schema and `Db` members. */
|
|
721
|
-
type Tables = Record<string, AnyTable>;
|
|
722
770
|
/**
|
|
723
|
-
*
|
|
771
|
+
* Operand of `and`, `or`, and `not`: a predicate, a query of one Boolean value, such as of `exists`, a condition, or an object of column values.
|
|
724
772
|
*
|
|
725
|
-
*
|
|
726
|
-
* A `Db` can execute such a query if its schema contains the tables and the selected relations of the query and every bound nested query belongs to that `Db`.
|
|
773
|
+
* Column values `V` are never inferred from an object, so that object keys are checked against the table instead of determining `V`.
|
|
727
774
|
*/
|
|
728
|
-
type
|
|
729
|
-
/** Query entry points; each access starts a query over a new table occurrence. */
|
|
730
|
-
type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
|
|
731
|
-
/** Members of a schema that composition reads: its tables and the relations of its tables. */
|
|
732
|
-
interface SchemaContents<T extends Tables, R extends SchemaRelations> {
|
|
733
|
-
readonly [schemaBrand]: true;
|
|
734
|
-
/** Tables of the schema by their keys. */
|
|
735
|
-
readonly $tables: T;
|
|
736
|
-
/** Relation definitions by table key and relation name. */
|
|
737
|
-
readonly [schemaRelations]: R;
|
|
738
|
-
}
|
|
739
|
-
interface SchemaMembers<T extends Tables, R extends SchemaRelations> extends SchemaContents<T, R> {
|
|
740
|
-
/**
|
|
741
|
-
* Creates a schema of the same tables with the relations of `relations` added, declared with `many` and `one` by their names under the keys of their tables.
|
|
742
|
-
*
|
|
743
|
-
* A relation refers to a table of the schema by columns of SQL types that `=` compares; a relation that the schema already has is rejected.
|
|
744
|
-
*/
|
|
745
|
-
$relations<S extends AnySchema, D extends RelationDeclarations<S["$tables"]>>(this: S, relations: D & CheckDeclarations<S["$tables"], D>): Schema<S["$tables"], MergeRelations<S[typeof schemaRelations] & DeclaredRelations<S["$tables"], D>>>;
|
|
746
|
-
/**
|
|
747
|
-
* Starts an unbound query of one record whose fields are the values of the expressions and of the literals and the results of the queries of `selection`, selected in one statement.
|
|
748
|
-
*
|
|
749
|
-
* The value of the field of a query is the result it gives when executed, such as an array of records or one value.
|
|
750
|
-
*/
|
|
751
|
-
$select<Sel extends Selection>(selection: Sel): RecordQuery<SelectionState<Sel>>;
|
|
752
|
-
}
|
|
753
|
-
/** Schema of any tables and relations. */
|
|
754
|
-
type AnySchema = SchemaContents<Tables, SchemaRelations>;
|
|
755
|
-
/** Part of a schema definition: an object of tables by their keys, or a schema whose tables and relations it includes. */
|
|
756
|
-
type SchemaPart = Tables | AnySchema;
|
|
775
|
+
type ConditionOperand<V, T extends boolean | null = boolean | null> = AnyExpression<T> | ScalarQuery<T> | Condition<V> | NoInfer<V>;
|
|
757
776
|
/**
|
|
758
|
-
*
|
|
759
|
-
*
|
|
760
|
-
* A part typed as a union gives a union of tables, and parts of an array of unknown length give no tables, since any of them may be missing.
|
|
777
|
+
* Result of `and`, `or`, and `not`: a condition checked against the table inside `where`, a Boolean expression without a table.
|
|
761
778
|
*/
|
|
762
|
-
type
|
|
763
|
-
/**
|
|
764
|
-
|
|
765
|
-
/**
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
}
|
|
770
|
-
type ComposeParts<P extends readonly SchemaPart[], Composed extends PartContents = {
|
|
771
|
-
tables: EmptyRecord;
|
|
772
|
-
relations: EmptyRecord;
|
|
773
|
-
}> = P extends readonly [infer First extends SchemaPart, ...infer Rest extends readonly SchemaPart[]] ? ComposeParts<Rest, Composed & ReadPart<First>> : P extends readonly [...infer Rest extends readonly SchemaPart[], infer Last extends SchemaPart] ? ComposeParts<Rest, Composed & ReadPart<Last>> : Composed;
|
|
774
|
-
type ReadPart<P extends SchemaPart> = P extends SchemaContents<infer T, any> ? {
|
|
775
|
-
tables: T;
|
|
776
|
-
relations: P[typeof schemaRelations];
|
|
777
|
-
} : {
|
|
778
|
-
tables: P;
|
|
779
|
-
relations: EmptyRecord;
|
|
780
|
-
};
|
|
779
|
+
type CombinedCondition<V, T extends boolean | null = boolean | null> = [V] extends [never] ? Expression<BooleanResult<T>> : Condition<V>;
|
|
780
|
+
/** Combines predicates with `AND`; no operands yield `TRUE`. */
|
|
781
|
+
declare function and<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
|
|
782
|
+
/** Combines predicates with `OR`; no operands yield `FALSE`. */
|
|
783
|
+
declare function or<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
|
|
784
|
+
/** Negates a predicate. */
|
|
785
|
+
declare function not<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(operand: ConditionOperand<V, T>): CombinedCondition<V, T>;
|
|
781
786
|
/**
|
|
782
|
-
*
|
|
787
|
+
* Filter by column values, each matched by the `eq` operator of its column; `null` matches `IS NULL`.
|
|
783
788
|
*
|
|
784
|
-
* A
|
|
785
|
-
* A key of two different tables, a table under two keys, and two different definitions of a relation of a table are rejected; the same table under the same key or the same relation in several parts is one.
|
|
789
|
+
* A column without an `eq` operator of one operand accepts only `null` in this filter, when its input type includes `null`.
|
|
786
790
|
*/
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
/**
|
|
793
|
-
type
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
791
|
+
type WhereValues<T extends AnyTable> = { [K in keyof T["columns"]]?: EqValue<T, K> | (null extends ColumnValues<T>[K] ? null : never); };
|
|
792
|
+
/** Operand of the `eq` operator of column `K` of table `T` in an object passed to `where`, such as an expression. */
|
|
793
|
+
type EqValue<T extends AnyTable, K extends keyof T["columns"]> = IsAny<ColumnOperators<T, K>> extends true ? ColumnValues<T>[K] : ColumnOperators<T, K> extends {
|
|
794
|
+
readonly eq: EqualityOperator<ComparisonSignature>;
|
|
795
|
+
} ? Operand<TypeOutput<T["columns"][K]["type"]>, TypeInput<T["columns"][K]["type"]>> : EqOperand<ColumnRefs<T>[K]>;
|
|
796
|
+
/** Operand of the `eq` operator of an expression, if it has one taking a single operand and returning a predicate. */
|
|
797
|
+
type EqOperand<E> = E extends {
|
|
798
|
+
eq: (value: infer V) => Predicate;
|
|
799
|
+
} ? V : never;
|
|
800
|
+
/** Filter of `where`: a Boolean expression, a query of one Boolean value, such as of `exists`, an object of column values, or their combination with `and`, `or`, and `not`. */
|
|
801
|
+
type WhereCondition<T extends AnyTable> = ConditionOperand<WhereValues<T>>;
|
|
802
|
+
/** Callback of `where` over table `T` with schema context `C`: it receives the columns and the queries of the relations of the table and returns a condition. */
|
|
803
|
+
type WhereCallback<T extends AnyTable, C extends SchemaContext = NoRelations> = (columns: ColumnRefs<T> & RelationRefs<C>) => WhereCondition<T>;
|
|
804
|
+
/** Argument of `where` of a query over table `T` with schema context `C`: a condition, or a callback that receives the columns and the relations of the query and returns one. */
|
|
805
|
+
type WhereFilter<T extends AnyTable, C extends SchemaContext = NoRelations> = WhereCondition<T> | WhereCallback<T, C>;
|
|
802
806
|
/**
|
|
803
|
-
*
|
|
807
|
+
* Argument of `where` of a query of state `S`: a `WhereFilter` of its table and schema, which TypeScript resolves with what it has inferred for `S` before it checks a callback in it.
|
|
804
808
|
*
|
|
805
|
-
*
|
|
809
|
+
* TypeScript types the body of a callback once, for every overload, and a plain `WhereFilter` leaves `S` unresolved there, so the body would widen a literal, such as of an enum column, to `string`.
|
|
810
|
+
* It reads the filter only in its branch, since a general alias that takes the filter as an argument resolves it on every call.
|
|
806
811
|
*/
|
|
807
|
-
|
|
808
|
-
readonly name: string;
|
|
809
|
-
/** Key of the source table. */
|
|
810
|
-
readonly key: string;
|
|
811
|
-
readonly source: AnyTable;
|
|
812
|
-
readonly from: readonly string[];
|
|
813
|
-
readonly to: readonly string[];
|
|
814
|
-
}
|
|
815
|
-
/** Relation `N` of the table under key `K` of a schema, of type `R`, whose records a query selects. */
|
|
816
|
-
interface UsedRelation<K extends string = string, N extends string = string, R extends Relation = Relation> {
|
|
817
|
-
readonly key: K;
|
|
818
|
-
readonly name: N;
|
|
819
|
-
readonly relation: R;
|
|
820
|
-
}
|
|
821
|
-
/** Relations of schema relations `R` that the queries of a `Db` of the schema may select. */
|
|
822
|
-
type UsableRelation<R extends SchemaRelations> = { [K in keyof R & string]: { [N in keyof R[K] & string]: UsedRelation<K, N, R[K][N]>; }[keyof R[K] & string]; }[keyof R & string];
|
|
823
|
-
/** Relations of the tables of a schema by table key and relation name. */
|
|
824
|
-
type SchemaRelations = {
|
|
825
|
-
readonly [key: string]: TableRelations;
|
|
826
|
-
};
|
|
827
|
-
/** Relations of a table of a schema by relation name. */
|
|
828
|
-
type TableRelations = {
|
|
829
|
-
readonly [name: string]: Relation;
|
|
830
|
-
};
|
|
812
|
+
type QueryWhereFilter<S extends SelectQueryState> = [S] extends [unknown] ? WhereFilter<S["table"], S["schema"]> : never;
|
|
831
813
|
/**
|
|
832
|
-
*
|
|
814
|
+
* 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.
|
|
833
815
|
*
|
|
834
|
-
*
|
|
816
|
+
* A union of tables gives the union of their values.
|
|
835
817
|
*/
|
|
836
|
-
|
|
837
|
-
readonly [declarationBrand]: true;
|
|
838
|
-
readonly kind: Kind;
|
|
839
|
-
readonly target: Target;
|
|
840
|
-
readonly from: readonly string[];
|
|
841
|
-
readonly to: readonly string[];
|
|
842
|
-
readonly required: Required;
|
|
843
|
-
readonly [sourceTable]?: (source: Source) => void;
|
|
844
|
-
readonly [sourceKey]?: From;
|
|
845
|
-
}
|
|
846
|
-
/** Column key of table `T` whose type has SQL `=`, which a relation can compare. */
|
|
847
|
-
type EqualityKey<T extends AnyTable> = { [K in keyof T["columns"]]: HasEquality<ColumnOperators<T, K>> extends true ? K : never; }[keyof T["columns"]] & string;
|
|
848
|
-
/** Key of a relation in table `T`: a column key, or a non-empty list of them for a composite key. */
|
|
849
|
-
type RelationKey<T extends AnyTable> = EqualityKey<T> | readonly [EqualityKey<T>, ...EqualityKey<T>[]];
|
|
850
|
-
/** Key of table `T` with as many columns as key `From`. */
|
|
851
|
-
type MatchingKey<T extends AnyTable, From> = From extends string ? EqualityKey<T> : { readonly [I in keyof From]: EqualityKey<T>; };
|
|
852
|
-
/** Keys of a relation: the columns `from` of the source table equal the columns `to` of the target table, in order. */
|
|
853
|
-
interface RelationKeys<Target extends AnyTable, From> {
|
|
854
|
-
readonly from: From;
|
|
855
|
-
readonly to: MatchingKey<Target, From>;
|
|
856
|
-
}
|
|
857
|
-
/** Keys of a relation `one`, as in `RelationKeys`, and whether the relation is required. */
|
|
858
|
-
interface OneRelationKeys<From, To> {
|
|
859
|
-
readonly from: From;
|
|
860
|
-
readonly to: To;
|
|
861
|
-
/** Whether every record has its related record, such as by a foreign key on columns `from` that are not nullable, so that a query of the relation without a filter rejects without it rather than giving `null`. */
|
|
862
|
-
readonly required?: boolean;
|
|
863
|
-
}
|
|
864
|
-
/** Members of the keys `K` of a relation `one` with only `required` typed, so that a call infers `K` with `required` as optional as it is, and reports a wrong key at its own member. */
|
|
865
|
-
type RequiredMember<K> = { readonly [P in keyof K]: P extends "required" ? K[P] : unknown; };
|
|
866
|
-
/** Whether the keys `K` of a relation `one` make it required: only where they set `required` to `true`, and `boolean` where `required` may be `true` or missing, such as `required?: true`. */
|
|
867
|
-
type DeclaredRequiredOf<K> = K extends unknown ? "required" extends keyof K ? K extends {
|
|
868
|
-
readonly required: infer Required;
|
|
869
|
-
} ? IsTrue<Required> : IsTrue<K["required" & keyof K] | undefined> : false : never;
|
|
870
|
-
/** `true` for `true`, and `false` for other values, such as `false` and `undefined`; a union gives the union of their results. */
|
|
871
|
-
type IsTrue<T> = T extends true ? true : false;
|
|
872
|
-
/** Declarations of `$relations` of a schema of tables `T`: relations by name, for tables by their keys. */
|
|
873
|
-
type RelationDeclarations<T extends Tables> = { readonly [K in keyof T]?: {
|
|
874
|
-
readonly [name: string]: RelationDeclaration<RelationKind, T[K], T[keyof T]>;
|
|
875
|
-
}; };
|
|
818
|
+
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;
|
|
876
819
|
/**
|
|
877
|
-
*
|
|
820
|
+
* 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.
|
|
878
821
|
*
|
|
879
|
-
*
|
|
880
|
-
* A relation name must not be a column key of its table or start with `$`, since the references that the callback of `select` gets have both.
|
|
822
|
+
* A table of `any`, such as of `AnySelectQuery`, takes any columns, as `where` takes any values there.
|
|
881
823
|
*/
|
|
882
|
-
type
|
|
883
|
-
/**
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
type TableKey<T extends Tables, K> = { [P in keyof T]: `${P & (string | number)}` extends `${K & (string | number)}` ? P : never; }[keyof T];
|
|
887
|
-
/** Relations that declarations `D` of a schema of tables `T` define, by table key and relation name, as strings like the keys of objects. */
|
|
888
|
-
type DeclaredRelations<T extends Tables, D> = { [K in keyof D as K extends number ? `${K}` : K]: { [N in keyof D[K] as N extends number ? `${N}` : N]: D[K][N] extends RelationDeclaration<infer Kind, never, infer Target, unknown, infer Required> ? Relation<Kind, Target, KeyOfTable<T, Target>, Required> : never; }; };
|
|
889
|
-
/** Column key of relation key `K`: the key itself, or a column of a composite key. */
|
|
890
|
-
type RelationColumn<K> = K extends readonly unknown[] ? K[number] : K;
|
|
891
|
-
/** Check of key `To` of a relation `one` that rejects it when its columns include no key of table `Target`, as far as the types tell. */
|
|
892
|
-
type TargetKeyCheck<Target extends AnyTable, To> = [ContainsKey<Target, RelationColumn<To>>] extends [false] ? {
|
|
893
|
-
readonly to: MissingKey<KeyOf<Target["keys"]>>;
|
|
894
|
-
} : unknown;
|
|
895
|
-
/** Type that a key `to` of a relation `one` without a key of its target is checked against, naming the keys of the target. */
|
|
896
|
-
interface MissingKey<Keys> {
|
|
897
|
-
readonly "columns to must include a key of the target": Keys;
|
|
898
|
-
}
|
|
899
|
-
/** Key of table `Target` among tables `T`, as a string like the keys of objects. */
|
|
900
|
-
type KeyOfTable<T extends Tables, Target> = { [K in keyof T]: [T[K]] extends [Target] ? [Target] extends [T[K]] ? K extends number ? `${K}` : K & string : never : never; }[keyof T];
|
|
901
|
-
/** Relations of `R` by table key, with the relations under the same key merged. */
|
|
902
|
-
type MergeRelations<R> = { [K in keyof R]: { [N in keyof R[K]]: R[K][N]; }; };
|
|
903
|
-
/** Relations of the schema that a query starts from, by table key, and the key of the table of the query there. */
|
|
904
|
-
interface SchemaContext<R extends SchemaRelations = SchemaRelations, K extends string = string> {
|
|
905
|
-
readonly relations: R;
|
|
906
|
-
readonly key: K;
|
|
824
|
+
type KeyCheck<T extends AnyTable, Columns> = [IsKey<T, Columns>] extends [true] ? unknown : IsAny<T> extends true ? unknown : NotAKey<KeyOf<T["keys"]>>;
|
|
825
|
+
/** Type that the object of `findBy` is checked against when its columns are not exactly a key of the table, naming the keys of the table. */
|
|
826
|
+
interface NotAKey<Keys> {
|
|
827
|
+
readonly "columns must be exactly one key of the table": Keys;
|
|
907
828
|
}
|
|
908
|
-
/**
|
|
909
|
-
type
|
|
910
|
-
/**
|
|
911
|
-
type
|
|
829
|
+
/** Key of a group returned by the callback of `groupBy` or `distinctOn`: an expression or a query of one value, such as of a value of a related record. */
|
|
830
|
+
type GroupTerm = AnyExpression | ScalarQuery;
|
|
831
|
+
/** Keys of a group returned by the callback of `groupBy` or `distinctOn`: one or an array of them. */
|
|
832
|
+
type GroupTerms = GroupTerm | readonly GroupTerm[];
|
|
912
833
|
/**
|
|
913
|
-
*
|
|
834
|
+
* What the callback of `having` of a query of state `S` receives as its second parameter: the references to the selected fields of a query of records, with the operators and the values of the types of their fields, the expression of the value of a query made by `get` or `pluck`, and `undefined` for an aggregate query, a query of `exists`, and a query that `map` converts.
|
|
914
835
|
*
|
|
915
|
-
* A
|
|
836
|
+
* A field of nested rows or of a literal is among the references, but reading it throws; a field of the rows of a query of one value, such as of `get`, has the operators of its value in types.
|
|
916
837
|
*/
|
|
917
|
-
|
|
838
|
+
type HavingFields<S extends SelectQueryState> = S["value"] extends false ? { readonly [K in keyof S["result"] & string]: FieldRef<SelectedFieldTypesOf<S["fieldTypes"]>, K, S["result"][K]>; } : S["value"] extends true ? S["aggregate"] extends false ? ToFieldRef<S["valueType"], S["result"]> : undefined : undefined;
|
|
839
|
+
/** Reference of the callback of `having` to field `K` of values `V`, with the type of its value among field types `F`, for each member of a union of them. */
|
|
840
|
+
type FieldRef<F, K extends string, V> = K extends keyof F ? ToFieldRef<Exclude<F[K], undefined>, V> : AnyExpression<V>;
|
|
841
|
+
/** Expression of values `V` with the operators and the values of type `D` of a value, or without them when `D` is none. */
|
|
842
|
+
type ToFieldRef<D, V> = D extends QueryValueType ? D extends {
|
|
843
|
+
readonly group: infer G;
|
|
844
|
+
} ? unknown extends G ? Expression<V, D["operators"], D["input"]> // References can escape this callback and be selected without grouping, so retain standalone nullability and the group mark.
|
|
845
|
+
: Expression<V | null, D["operators"], D["input"]> & GroupValue<G> : Expression<V, D["operators"], D["input"]> : AnyExpression<V>;
|
|
918
846
|
/**
|
|
919
|
-
*
|
|
847
|
+
* Argument of `having` of a query of state `S`: a condition of `where`, or a callback that receives the columns and the relations of the table, and the fields of `HavingFields`, and returns one.
|
|
920
848
|
*
|
|
921
|
-
*
|
|
922
|
-
* The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
|
|
923
|
-
* Without the record, a query of the relation gives `null`, and a query of a relation declared with `required: true` rejects unless it filters the record.
|
|
924
|
-
* Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
|
|
849
|
+
* It reads `S` only in its branch, as `QueryWhereFilter` does.
|
|
925
850
|
*/
|
|
926
|
-
|
|
927
|
-
/** Type of a count: a `bigint` of PostgreSQL decoded as a number, rejecting a count that a number cannot hold exactly. */
|
|
928
|
-
declare const countType: BaseType<number, number, MergeOperators<NoOperators, {
|
|
929
|
-
eq: EqualityOperator<ComparisonSignature>;
|
|
930
|
-
ne: EqualityOperator<ComparisonSignature>;
|
|
931
|
-
in: EqualityOperator<InSignature>;
|
|
932
|
-
lt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
933
|
-
lte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
934
|
-
gt: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
935
|
-
gte: GenericOperator<ComparisonSignature, AnyExpression<unknown, unknown>>;
|
|
936
|
-
}>, undefined>;
|
|
937
|
-
/** Type of the value of a query of a count. */
|
|
938
|
-
interface CountValueType extends QueryValueType {
|
|
939
|
-
readonly input: TypeInput<typeof countType>;
|
|
940
|
-
readonly operators: TypeOperators<typeof countType>;
|
|
941
|
-
}
|
|
942
|
-
/** References to the columns of the query source, passed to query callbacks. */
|
|
943
|
-
type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
|
|
851
|
+
type QueryHavingFilter<S extends SelectQueryState> = [S] extends [unknown] ? WhereCondition<S["table"]> | ((columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>, selected: HavingFields<S>) => WhereCondition<S["table"]>) : never;
|
|
944
852
|
/**
|
|
945
|
-
*
|
|
853
|
+
* What a query with a row lock does with a row that another transaction has locked, instead of waiting for it:
|
|
946
854
|
*
|
|
947
|
-
*
|
|
948
|
-
*
|
|
855
|
+
* - `skipLocked` leaves the row out of its result, such as to take the next free job of a queue.
|
|
856
|
+
* - `noWait` rejects with a PostgreSQL error of SQLSTATE `55P03`.
|
|
949
857
|
*/
|
|
950
|
-
type
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
readonly relations: PropertyDescriptorMap;
|
|
958
|
-
}
|
|
959
|
-
/** Type of the value of a query of `exists`. */
|
|
960
|
-
interface ExistsValueType extends QueryValueType {
|
|
961
|
-
readonly input: boolean;
|
|
962
|
-
readonly operators: EqualityOperators;
|
|
963
|
-
}
|
|
964
|
-
declare const conditionValues: unique symbol;
|
|
965
|
-
/** Predicate accepted by `where`, `and`, `or`, and `not`; SQL treats a `NULL` predicate as not satisfied. */
|
|
966
|
-
type Predicate = AnyExpression<boolean | null>;
|
|
967
|
-
/**
|
|
968
|
-
* Condition combining expressions with objects of column values, such as `or({ published: true }, form.id.in(ids))`.
|
|
969
|
-
*
|
|
970
|
-
* `where` matches the objects against the columns of its query, so a condition is accepted only where `V` matches the table.
|
|
971
|
-
*/
|
|
972
|
-
interface Condition<V> {
|
|
973
|
-
readonly [conditionValues]?: V;
|
|
974
|
-
}
|
|
975
|
-
/**
|
|
976
|
-
* Operand of `and`, `or`, and `not`: a predicate, a query of one Boolean value, such as of `exists`, a condition, or an object of column values.
|
|
977
|
-
*
|
|
978
|
-
* Column values `V` are never inferred from an object, so that object keys are checked against the table instead of determining `V`.
|
|
979
|
-
*/
|
|
980
|
-
type ConditionOperand<V, T extends boolean | null = boolean | null> = AnyExpression<T> | ScalarQuery<T> | Condition<V> | NoInfer<V>;
|
|
981
|
-
/**
|
|
982
|
-
* Result of `and`, `or`, and `not`: a condition checked against the table inside `where`, a Boolean expression without a table.
|
|
983
|
-
*/
|
|
984
|
-
type CombinedCondition<V, T extends boolean | null = boolean | null> = [V] extends [never] ? Expression<BooleanResult<T>> : Condition<V>;
|
|
985
|
-
/** Combines predicates with `AND`; no operands yield `TRUE`. */
|
|
986
|
-
declare function and<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
|
|
987
|
-
/** Combines predicates with `OR`; no operands yield `FALSE`. */
|
|
988
|
-
declare function or<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(...operands: ConditionOperand<V, T>[]): CombinedCondition<V, T>;
|
|
989
|
-
/** Negates a predicate. */
|
|
990
|
-
declare function not<V = never, T extends boolean | null = [V] extends [never] ? boolean : boolean | null>(operand: ConditionOperand<V, T>): CombinedCondition<V, T>;
|
|
991
|
-
/**
|
|
992
|
-
* Filter by column values, each matched by the `eq` operator of its column; `null` matches `IS NULL`.
|
|
993
|
-
*
|
|
994
|
-
* A column without an `eq` operator of one operand accepts only `null` in this filter, when its input type includes `null`.
|
|
995
|
-
*/
|
|
996
|
-
type WhereValues<T extends AnyTable> = { [K in keyof T["columns"]]?: EqValue<T, K> | (null extends ColumnValues<T>[K] ? null : never); };
|
|
997
|
-
/** Operand of the `eq` operator of column `K` of table `T` in an object passed to `where`, such as an expression. */
|
|
998
|
-
type EqValue<T extends AnyTable, K extends keyof T["columns"]> = IsAny<ColumnOperators<T, K>> extends true ? ColumnValues<T>[K] : ColumnOperators<T, K> extends {
|
|
999
|
-
readonly eq: EqualityOperator<ComparisonSignature>;
|
|
1000
|
-
} ? Operand<TypeOutput<T["columns"][K]["type"]>, TypeInput<T["columns"][K]["type"]>> : EqOperand<ColumnRefs<T>[K]>;
|
|
1001
|
-
/** Operand of the `eq` operator of an expression, if it has one taking a single operand and returning a predicate. */
|
|
1002
|
-
type EqOperand<E> = E extends {
|
|
1003
|
-
eq: (value: infer V) => Predicate;
|
|
1004
|
-
} ? V : never;
|
|
1005
|
-
/** Filter of `where`: a Boolean expression, a query of one Boolean value, such as of `exists`, an object of column values, or their combination with `and`, `or`, and `not`. */
|
|
1006
|
-
type WhereCondition<T extends AnyTable> = ConditionOperand<WhereValues<T>>;
|
|
1007
|
-
/** Callback of `where` over table `T` with schema context `C`: it receives the columns and the queries of the relations of the table and returns a condition. */
|
|
1008
|
-
type WhereCallback<T extends AnyTable, C extends SchemaContext = NoRelations> = (columns: ColumnRefs<T> & RelationRefs<C>) => WhereCondition<T>;
|
|
1009
|
-
/** Argument of `where` of a query over table `T` with schema context `C`: a condition, or a callback that receives the columns and the relations of the query and returns one. */
|
|
1010
|
-
type WhereFilter<T extends AnyTable, C extends SchemaContext = NoRelations> = WhereCondition<T> | WhereCallback<T, C>;
|
|
1011
|
-
/**
|
|
1012
|
-
* Argument of `where` of a query of state `S`: a `WhereFilter` of its table and schema, which TypeScript resolves with what it has inferred for `S` before it checks a callback in it.
|
|
1013
|
-
*
|
|
1014
|
-
* TypeScript types the body of a callback once, for every overload, and a plain `WhereFilter` leaves `S` unresolved there, so the body would widen a literal, such as of an enum column, to `string`.
|
|
1015
|
-
* It reads the filter only in its branch: a general alias that takes the filter as an argument resolves it on every call, which takes about 25 more instantiations.
|
|
1016
|
-
*/
|
|
1017
|
-
type QueryWhereFilter<S extends SelectQueryState> = [S] extends [unknown] ? WhereFilter<S["table"], S["schema"]> : never;
|
|
1018
|
-
/**
|
|
1019
|
-
* Values of the primary key of table `T` that `find` takes, in the order of its columns, or `never` where the type of `T` tells no primary key.
|
|
1020
|
-
*
|
|
1021
|
-
* A union of tables gives the union of their values.
|
|
1022
|
-
*/
|
|
1023
|
-
type PrimaryKeyValues<T extends AnyTable> = T extends AnyTable ? T["keys"] extends TableKeys<infer PrimaryKey extends KeyColumns, infer _UniqueKey> ? { readonly [I in keyof PrimaryKey]: NonNullable<EqValue<T, PrimaryKey[I] & keyof T["columns"]>>; } : never : never;
|
|
1024
|
-
/**
|
|
1025
|
-
* Check of columns `Columns` of the object of `findBy` that rejects them unless they are exactly a key of table `T`, primary or unique, as the type of `T` tells.
|
|
1026
|
-
*
|
|
1027
|
-
* A table of `any`, such as of `AnySelectQuery`, takes any columns, as `where` takes any values there.
|
|
1028
|
-
*/
|
|
1029
|
-
type KeyCheck<T extends AnyTable, Columns> = [IsKey<T, Columns>] extends [true] ? unknown : IsAny<T> extends true ? unknown : NotAKey<KeyOf<T["keys"]>>;
|
|
1030
|
-
/** Type that the object of `findBy` is checked against when its columns are not exactly a key of the table, naming the keys of the table. */
|
|
1031
|
-
interface NotAKey<Keys> {
|
|
1032
|
-
readonly "columns must be exactly one key of the table": Keys;
|
|
1033
|
-
}
|
|
1034
|
-
/**
|
|
1035
|
-
* Direction of a sort key, optionally with the placement of `NULL`.
|
|
1036
|
-
*
|
|
1037
|
-
* Without a placement, `NULL` comes last in ascending order and first in descending order.
|
|
1038
|
-
*/
|
|
1039
|
-
type OrderDirection = "asc" | "desc" | "asc nulls first" | "asc nulls last" | "desc nulls first" | "desc nulls last";
|
|
1040
|
-
/** Columns of table `T` with the directions to sort by them, in the order of their keys. */
|
|
1041
|
-
type OrderColumns<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: OrderDirection; };
|
|
1042
|
-
/** Argument of `orderBy` of a query over table `T`: a column key, sorted in ascending order, or columns with directions. */
|
|
1043
|
-
type OrderKey<T extends AnyTable> = (keyof T["columns"] & string) | OrderColumns<T>;
|
|
1044
|
-
declare const ordering: unique symbol;
|
|
1045
|
-
/** Expression or query of one value with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
|
|
1046
|
-
interface Ordering {
|
|
1047
|
-
readonly [ordering]: true;
|
|
1048
|
-
}
|
|
1049
|
-
/** Sort key returned by the callback of `orderBy`: an expression or a query of one value, such as of an aggregate of related records, sorted in ascending order, or one with a direction. */
|
|
1050
|
-
type OrderTerm = AnyExpression | ScalarQuery | Ordering;
|
|
1051
|
-
/**
|
|
1052
|
-
* References of the callback of `orderBy` to the fields of records `R` selected by a query: their expressions by key.
|
|
1053
|
-
*
|
|
1054
|
-
* A field of nested rows or of a literal is among them in types, but reading it throws; a field of an aggregate or of `exists` sorts by its value.
|
|
1055
|
-
*/
|
|
1056
|
-
type SelectedRefs<R> = { readonly [K in keyof R & string]: AnyExpression<R[K]>; };
|
|
1057
|
-
/** Sort keys returned by the callback of `orderBy`: one or an array of them. */
|
|
1058
|
-
type OrderTerms = OrderTerm | readonly OrderTerm[];
|
|
1059
|
-
/** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
|
|
1060
|
-
declare function asc(value: AnyExpression | ScalarQuery): Ordering;
|
|
1061
|
-
/** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
|
|
1062
|
-
declare function desc(value: AnyExpression | ScalarQuery): Ordering;
|
|
1063
|
-
/** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
|
|
1064
|
-
declare function orderBy(value: AnyExpression | ScalarQuery, direction: OrderDirection): Ordering;
|
|
1065
|
-
/**
|
|
1066
|
-
* Value of column `K` of table `T` that an insert or an update sets: a value that its type encodes, `null` for a nullable column, an expression of its values, or a query of one such value.
|
|
1067
|
-
*
|
|
1068
|
-
* A query may be `NULL` without its row, which PostgreSQL rejects for a column that is not nullable.
|
|
1069
|
-
*/
|
|
1070
|
-
type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValues<T>[K] | AnyExpression<Selectable<T>[K]> | ScalarQuery<Selectable<T>[K] | null>;
|
|
1071
|
-
/** Key of a column of table `T` that an insert may omit, which gets its default: one that the database gives a value, as `hasDefault` marks it, or a nullable one, whose default is `NULL` unless the database declares another. */
|
|
1072
|
-
type OptionalColumnKey<T extends AnyTable> = { [K in keyof T["columns"]]: T["columns"][K]["attributes"]["hasDefault"] extends true ? K : null extends ColumnValues<T>[K] ? K : never; }[keyof T["columns"]];
|
|
1073
|
-
/** Record of an insert into table `T`: the values of its columns, which may omit a column with a default or a nullable column, or give it as `undefined`. */
|
|
1074
|
-
type InsertValues<T extends AnyTable> = { readonly [K in keyof T["columns"] as K extends OptionalColumnKey<T> ? never : K]: ColumnValue<T, K>; } & { readonly [K in OptionalColumnKey<T>]?: ColumnValue<T, K> | undefined; };
|
|
1075
|
-
/** Values of the columns of table `T` that an update sets; a column omitted or given as `undefined` keeps its value. */
|
|
1076
|
-
type UpdateValues<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: ColumnValue<T, K> | undefined; };
|
|
1077
|
-
/** Argument of `update` of table `T` with schema context `C`: the values that it sets, or a callback that receives the columns and the queries of the relations of the changed rows and returns them. */
|
|
1078
|
-
type UpdateSet<T extends AnyTable, C extends SchemaContext = NoRelations> = UpdateValues<T> | ((columns: ColumnRefs<T> & RelationRefs<C>) => UpdateValues<T>);
|
|
1079
|
-
/** State `S` with the parts of `Changes` replaced. */
|
|
1080
|
-
type ChangeState<S extends SelectQueryState, Changes extends Partial<SelectQueryState>> = { readonly [K in keyof SelectQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
|
|
858
|
+
type RowLockOptions = {
|
|
859
|
+
readonly noWait?: boolean;
|
|
860
|
+
readonly skipLocked?: false;
|
|
861
|
+
} | {
|
|
862
|
+
readonly noWait?: false;
|
|
863
|
+
readonly skipLocked?: boolean;
|
|
864
|
+
};
|
|
1081
865
|
/** Rows mode of a query of state `S` after a filter: `FilteredRows` of a query whose row is guaranteed, and the rows of other queries. */
|
|
1082
866
|
type FilteredStateRows<S extends SelectQueryState> = [S["guaranteed"]] extends [false] ? S["rows"] : [S["value"]] extends [false] ? S["result"] extends HelperFields ? S["rows"] : FilteredRows<S["rows"], false> : FilteredRows<S["rows"], S["value"]>;
|
|
1083
867
|
/** State `S` after a filter, which ends the guarantee of its row. */
|
|
@@ -1090,53 +874,8 @@ type FoundState<S extends SelectQueryState> = ChangeState<S, {
|
|
|
1090
874
|
rows: OneRow<FilteredStateRows<S>>;
|
|
1091
875
|
guaranteed: false;
|
|
1092
876
|
}>;
|
|
1093
|
-
/** Query of state `S`, bound or unbound. */
|
|
1094
|
-
type QueryOf<S extends SelectQueryState> = SelectQuery<S, SelectQueryKind>;
|
|
1095
|
-
declare const scalarValue: unique symbol;
|
|
1096
|
-
/** Value of a query of state `S` in an expression: its value, or `NULL` without its row unless the query always has it. */
|
|
1097
|
-
type ScalarValue<S extends SelectQueryState> = S["aggregate"] extends true ? S["result"] : S["guaranteed"] extends true ? S["result"] : S["result"] | null;
|
|
1098
|
-
/**
|
|
1099
|
-
* Query of one value of a table, such as of `get`, of an aggregate, or of `exists`, which an expression takes as a scalar subquery of its value, or as `EXISTS` of the rows of a query of `exists`.
|
|
1100
|
-
*
|
|
1101
|
-
* `T` is its value there: without its row, a query of `get` is `NULL`, unless a required relation guarantees the row, such as of `field.form`.
|
|
1102
|
-
*/
|
|
1103
|
-
interface ScalarQuery<T = unknown> {
|
|
1104
|
-
/** Value of the query in an expression, from which an expression infers `T`. */
|
|
1105
|
-
readonly [scalarValue]: T;
|
|
1106
|
-
readonly types: ScalarQueryState;
|
|
1107
|
-
readonly exists: unknown;
|
|
1108
|
-
}
|
|
1109
|
-
/** Value of query `Q` of one value in an expression. */
|
|
1110
|
-
type ScalarQueryValue<Q extends ScalarQuery> = Q[typeof scalarValue];
|
|
1111
|
-
/** Relations whose records `E`, an expression or a query of one value that a callback returns, selects: those of a query, as an expression does not carry the relations of its queries. */
|
|
1112
|
-
type OperandUses<E> = E extends ScalarQuery ? E["types"]["uses"] : never;
|
|
1113
|
-
/** State of a query of one value, which an expression takes. */
|
|
1114
|
-
interface ScalarQueryState extends SelectQueryState {
|
|
1115
|
-
readonly rows: "one" | "optional";
|
|
1116
|
-
readonly value: true;
|
|
1117
|
-
}
|
|
1118
|
-
/** State of a query of one value with the type of its value, whose expression `expr` gives. */
|
|
1119
|
-
interface ExpressionQueryState extends ScalarQueryState {
|
|
1120
|
-
readonly valueType: QueryValueType;
|
|
1121
|
-
}
|
|
1122
|
-
/** Query of one value of a table with the type of its value, such as of `get` or of an aggregate, which gives the expression of a function the decoding and the operators of its value. */
|
|
1123
|
-
interface TypedScalarQuery extends ScalarQuery {
|
|
1124
|
-
readonly types: ExpressionQueryState;
|
|
1125
|
-
}
|
|
1126
|
-
/** Query of values of a table of any rows, such as of `pluck`, whose value is `T`, which `in` takes as a subquery of its values. */
|
|
1127
|
-
interface ValuesQuery<T = unknown> {
|
|
1128
|
-
readonly types: ValuesQueryState<T>;
|
|
1129
|
-
readonly exists: unknown;
|
|
1130
|
-
}
|
|
1131
|
-
/** Value of query `Q` of values, of each of its rows. */
|
|
1132
|
-
type ValuesQueryValue<Q extends ValuesQuery> = Q["types"]["result"];
|
|
1133
|
-
/** State of a query of values whose value is `T`. */
|
|
1134
|
-
interface ValuesQueryState<T> extends SelectQueryState {
|
|
1135
|
-
readonly result: T;
|
|
1136
|
-
readonly value: true;
|
|
1137
|
-
}
|
|
1138
877
|
/** State of a query whose rows are records, which `select` and `clearSelect` change. */
|
|
1139
|
-
type RecordQueryState = SelectQueryState & {
|
|
878
|
+
type RecordQueryState$1 = SelectQueryState & {
|
|
1140
879
|
readonly value: false;
|
|
1141
880
|
};
|
|
1142
881
|
/** State of a query whose row no relation guarantees, which a filter keeps. */
|
|
@@ -1147,16 +886,22 @@ type UnguaranteedQueryState = SelectQueryState & {
|
|
|
1147
886
|
type ValueQueryState = SelectQueryState & {
|
|
1148
887
|
readonly value: true;
|
|
1149
888
|
};
|
|
889
|
+
/** State of a query converted by `map`, whose callback of `orderBy` reads no selected fields, which its result no longer tells. */
|
|
890
|
+
type MappedQueryState = SelectQueryState & {
|
|
891
|
+
readonly value: "mapped";
|
|
892
|
+
};
|
|
1150
893
|
/** State of a query of values with the values that the type of its value encodes, which `coalesce` takes; it narrows nothing else, so that a call compares no operators. */
|
|
1151
894
|
type CoalesceQueryState = ValueQueryState & {
|
|
1152
895
|
readonly valueType: {
|
|
1153
896
|
readonly input: unknown;
|
|
1154
897
|
};
|
|
1155
898
|
};
|
|
1156
|
-
/** State of a query not made by an aggregate method or `exists`, which `get`, `pluck`, the aggregate methods, and `
|
|
899
|
+
/** State of a query not made by an aggregate method or `exists`, which `get`, `pluck`, the aggregate methods, `exists`, and `groupBy` apply to. */
|
|
1157
900
|
type UnaggregatedQueryState = SelectQueryState & {
|
|
1158
901
|
readonly aggregate: false;
|
|
1159
902
|
};
|
|
903
|
+
/** State of a query of values not made by an aggregate method or `exists`, such as of `pluck`, whose callback of `groupBy` reads its value. */
|
|
904
|
+
type UnaggregatedValueQueryState = ValueQueryState & UnaggregatedQueryState;
|
|
1160
905
|
/** Type of the value of a query of column `K` of table `T`. */
|
|
1161
906
|
type ColumnValueType<T extends AnyTable, K extends keyof T["columns"]> = {
|
|
1162
907
|
readonly input: ColumnValues<T>[K];
|
|
@@ -1167,6 +912,27 @@ type OperandValueType<E extends TypedOperand> = {
|
|
|
1167
912
|
readonly input: TypedOperandInput<E>;
|
|
1168
913
|
readonly operators: TypedOperandOperators<E>;
|
|
1169
914
|
};
|
|
915
|
+
/** State `S` after grouping, with the values of its directly selected aggregates in nonempty groups. */
|
|
916
|
+
interface GroupedState<S extends SelectQueryState> extends SelectQueryState {
|
|
917
|
+
readonly table: S["table"];
|
|
918
|
+
readonly schema: S["schema"];
|
|
919
|
+
readonly result: GroupedResult<S>;
|
|
920
|
+
readonly rows: S["rows"];
|
|
921
|
+
readonly value: S["value"];
|
|
922
|
+
readonly valueType: S["valueType"];
|
|
923
|
+
readonly fieldTypes: S["fieldTypes"];
|
|
924
|
+
readonly uses: S["uses"];
|
|
925
|
+
readonly guaranteed: S["guaranteed"];
|
|
926
|
+
readonly aggregate: false & Grouped;
|
|
927
|
+
}
|
|
928
|
+
/** Selected result after grouping, retaining the records or scalar value of the query. */
|
|
929
|
+
type GroupedResult<S extends SelectQueryState> = S["value"] extends false ? S["fieldTypes"] extends SelectedFieldTypes<unknown, unknown> ? GroupedRecord<S["result"], S["fieldTypes"]["types"]> : S["result"] : S["value"] extends true ? GroupedField<S["result"], S["valueType"]> : S["result"];
|
|
930
|
+
/** Type of a selected operand, carrying its value in a group for a later call of `groupBy`. */
|
|
931
|
+
interface SelectedOperandType<E extends TypedOperand> extends QueryValueType {
|
|
932
|
+
readonly input: TypedOperandInput<E>;
|
|
933
|
+
readonly operators: TypedOperandOperators<E>;
|
|
934
|
+
readonly group: E extends GroupValue<infer V> ? V : unknown;
|
|
935
|
+
}
|
|
1170
936
|
/** State of a query of the value `V` of type `Type` of an aggregate or of `exists` over the rows of a query of state `S`, which always returns one row. */
|
|
1171
937
|
type AggregateState<S extends SelectQueryState, V, Type extends QueryValueType> = ChangeState<S, {
|
|
1172
938
|
result: V;
|
|
@@ -1198,14 +964,38 @@ type CoalescedValue<V, F> = Exclude<V, null> | Extract<OperandValue<F>, null>;
|
|
|
1198
964
|
type ManyRowsQueryState = SelectQueryState & {
|
|
1199
965
|
readonly rows: "many";
|
|
1200
966
|
};
|
|
967
|
+
/** State of a query that returns rows of its table, which a row lock applies to: not of an aggregate or of `exists`. */
|
|
968
|
+
type LockableQueryState = SelectQueryState & ({
|
|
969
|
+
readonly aggregate: false;
|
|
970
|
+
} | {
|
|
971
|
+
readonly value: "mapped";
|
|
972
|
+
});
|
|
1201
973
|
/** State of a query of one row, which `optional` and `required` apply to. */
|
|
1202
974
|
type OneRowQueryState = SelectQueryState & {
|
|
1203
975
|
readonly rows: "one" | "nullable" | "optional";
|
|
1204
976
|
};
|
|
1205
|
-
/** State of a query of one row whose rows are records, which `nullable` applies to. */
|
|
977
|
+
/** State of a query of one row whose rows are records or what `map` gives, which `nullable` applies to. */
|
|
1206
978
|
type OneRecordQueryState = OneRowQueryState & {
|
|
1207
|
-
readonly value: false;
|
|
979
|
+
readonly value: false | "mapped";
|
|
1208
980
|
};
|
|
981
|
+
/**
|
|
982
|
+
* Value of column `K` of table `T` that an insert or an update sets: a value that its type encodes, `null` for a nullable column, an expression of its values, or a query of one such value.
|
|
983
|
+
*
|
|
984
|
+
* A query may be `NULL` without its row, which PostgreSQL rejects for a column that is not nullable.
|
|
985
|
+
*/
|
|
986
|
+
type ColumnValue<T extends AnyTable, K extends keyof T["columns"]> = ColumnValues<T>[K] | AnyExpression<Selectable<T>[K]> | ScalarQuery<Selectable<T>[K] | null>;
|
|
987
|
+
/** 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. */
|
|
988
|
+
type OptionalColumnKey<T extends AnyTable> = { [K in keyof T["columns"]]: T["columns"][K]["attributes"]["hasDefault"] extends true ? K : null extends ColumnValues<T>[K] ? K : never; }[keyof T["columns"]];
|
|
989
|
+
/** Record of an insert into table `T`: the values of its columns, which may omit a column with a default or a nullable column, or give it as `undefined`. */
|
|
990
|
+
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; };
|
|
991
|
+
/** Values of the columns of table `T` that an update sets; a column omitted or given as `undefined` keeps its value. */
|
|
992
|
+
type UpdateValues<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: ColumnValue<T, K> | undefined; };
|
|
993
|
+
/** Argument of `update` of table `T` with schema context `C`: the values that it sets, or a callback that receives the columns and the queries of the relations of the changed rows and returns them. */
|
|
994
|
+
type UpdateSet<T extends AnyTable, C extends SchemaContext = NoRelations> = UpdateValues<T> | ((columns: ColumnRefs<T> & RelationRefs<C>) => UpdateValues<T>);
|
|
995
|
+
/** State `S` with the parts of `Changes` replaced. */
|
|
996
|
+
type ChangeState<S extends SelectQueryState, Changes extends Partial<SelectQueryState>> = { readonly [K in keyof SelectQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
|
|
997
|
+
/** Query of state `S`, bound or unbound. */
|
|
998
|
+
type QueryOf<S extends SelectQueryState> = SelectQuery<S, SelectQueryKind>;
|
|
1209
999
|
/**
|
|
1210
1000
|
* Immutable select query of state `S`, unbound or bound to a `Db`.
|
|
1211
1001
|
*
|
|
@@ -1237,12 +1027,14 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1237
1027
|
*/
|
|
1238
1028
|
where<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: QueryWhereFilter<S>): SelectQuery<FilteredState<S>, Kind>;
|
|
1239
1029
|
/** Selects all columns of the table, replacing fields under their keys. */
|
|
1240
|
-
select<S extends RecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
|
|
1030
|
+
select<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, all: "*"): SelectQuery<ChangeState<S, {
|
|
1241
1031
|
result: MergeSelection<S["result"], Selectable<S["table"]>>;
|
|
1032
|
+
fieldTypes: SelectedFieldTypes<S["fieldTypes"], ColumnFieldTypes<S["table"], keyof S["table"]["columns"]>>;
|
|
1242
1033
|
}>, Kind>;
|
|
1243
1034
|
/** Selects the listed columns, replacing fields under their keys. */
|
|
1244
|
-
select<S extends RecordQueryState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, ...keys: K[]): SelectQuery<ChangeState<S, {
|
|
1035
|
+
select<S extends RecordQueryState$1, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: SelectQuery<S, Kind>, ...keys: K[]): SelectQuery<ChangeState<S, {
|
|
1245
1036
|
result: MergeSelection<S["result"], Pick<Selectable<S["table"]>, K>>;
|
|
1037
|
+
fieldTypes: SelectedFieldTypes<S["fieldTypes"], ColumnFieldTypes<S["table"], K>>;
|
|
1246
1038
|
}>, Kind>;
|
|
1247
1039
|
/**
|
|
1248
1040
|
* Selects the expressions and nested queries returned by `callback`, replacing fields under their keys.
|
|
@@ -1251,13 +1043,15 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1251
1043
|
* Each expression is decoded with its type, so it must have one: a column, an operator result, or a fragment of `sql(type)`, but not of `sql<T>`.
|
|
1252
1044
|
* A nested query is unbound, such as a query of a relation, or bound to the `Db` that runs the query; its rows become the value of its field as they become the result of an executed query.
|
|
1253
1045
|
*/
|
|
1254
|
-
select<S extends RecordQueryState, Kind extends SelectQueryKind, Sel extends Selection>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => Sel): SelectQuery<ChangeState<S, {
|
|
1255
|
-
result: MergeSelection<S["result"], SelectionResult<Sel>>;
|
|
1046
|
+
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, {
|
|
1047
|
+
result: MergeSelection<S["result"], S["aggregate"] extends Grouped ? GroupSelectionResult<Sel> : SelectionResult<Sel>>;
|
|
1256
1048
|
uses: S["uses"] | SelectionUses<Sel>;
|
|
1049
|
+
fieldTypes: SelectedFieldTypes<S["fieldTypes"], SelectionFieldTypes<Sel>>;
|
|
1257
1050
|
}>, Kind>;
|
|
1258
1051
|
/** Removes all selected fields and keeps the other clauses. */
|
|
1259
|
-
clearSelect<S extends RecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
|
|
1052
|
+
clearSelect<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
|
|
1260
1053
|
result: EmptyRecord;
|
|
1054
|
+
fieldTypes: EmptyRecord;
|
|
1261
1055
|
}>, Kind>;
|
|
1262
1056
|
/**
|
|
1263
1057
|
* 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`.
|
|
@@ -1305,8 +1099,8 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1305
1099
|
* A `NULL` value is `null`.
|
|
1306
1100
|
*/
|
|
1307
1101
|
get<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<ChangeState<S, {
|
|
1308
|
-
result: OperandValue<E>;
|
|
1309
|
-
valueType:
|
|
1102
|
+
result: S["aggregate"] extends Grouped ? GroupOperandValue<E> : OperandValue<E>;
|
|
1103
|
+
valueType: SelectedOperandType<E>;
|
|
1310
1104
|
rows: OneValueRows<S["rows"]>;
|
|
1311
1105
|
value: true;
|
|
1312
1106
|
uses: S["uses"] | OperandUses<E>;
|
|
@@ -1330,8 +1124,8 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1330
1124
|
* It keeps whether the query returns an array or one value, such as after `take`, and how it handles a missing row, except that a nullable query resolves to `undefined` without a row.
|
|
1331
1125
|
*/
|
|
1332
1126
|
pluck<S extends UnaggregatedQueryState, Kind extends SelectQueryKind, E extends TypedOperand>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): SelectQuery<ChangeState<S, {
|
|
1333
|
-
result: OperandValue<E>;
|
|
1334
|
-
valueType:
|
|
1127
|
+
result: S["aggregate"] extends Grouped ? GroupOperandValue<E> : OperandValue<E>;
|
|
1128
|
+
valueType: SelectedOperandType<E>;
|
|
1335
1129
|
rows: ValueRows<S["rows"]>;
|
|
1336
1130
|
value: true;
|
|
1337
1131
|
uses: S["uses"] | OperandUses<E>;
|
|
@@ -1339,7 +1133,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1339
1133
|
/**
|
|
1340
1134
|
* Replaces the selected fields with the number of rows of the query and returns the number instead of the rows.
|
|
1341
1135
|
*
|
|
1342
|
-
* It keeps the filters and ignores the order; with `limit` or `offset`, it counts the rows of that page.
|
|
1136
|
+
* It keeps the filters and ignores the order; with `limit` or `offset`, it counts the rows of that page, after `groupBy`, the groups, after `distinct`, the distinct rows of the selected fields, and after `distinctOn`, the first rows.
|
|
1343
1137
|
*/
|
|
1344
1138
|
count<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<CountState<S>, Kind>;
|
|
1345
1139
|
/** Replaces the selected fields with the number of the values of the column other than `NULL` among the rows of the query and returns it instead of the rows. */
|
|
@@ -1417,7 +1211,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1417
1211
|
/**
|
|
1418
1212
|
* Replaces the selected fields with whether the query has a row and returns it instead of the rows, such as to filter by related records in `where`.
|
|
1419
1213
|
*
|
|
1420
|
-
* It keeps the filters, the limit, and the offset, and ignores the order.
|
|
1214
|
+
* It keeps the filters, the limit, and the offset, and ignores the order; after `groupBy`, it tells whether the query has a group, and after `distinct` and `distinctOn`, it checks the distinct rows and the first rows.
|
|
1421
1215
|
*/
|
|
1422
1216
|
exists<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<AggregateState<S, boolean, ExistsValueType>, Kind>;
|
|
1423
1217
|
/**
|
|
@@ -1428,6 +1222,9 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1428
1222
|
*/
|
|
1429
1223
|
coalesce<S extends CoalesceQueryState, Kind extends SelectQueryKind, F extends Operand<S["result"], S["valueType"]["input"]>>(this: SelectQuery<S, Kind>, fallback: F): SelectQuery<ChangeState<S, {
|
|
1430
1224
|
result: CoalescedValue<S["result"], F>;
|
|
1225
|
+
valueType: S["valueType"] extends {
|
|
1226
|
+
readonly group: unknown;
|
|
1227
|
+
} ? Omit<S["valueType"], "group"> : S["valueType"];
|
|
1431
1228
|
}>, Kind>;
|
|
1432
1229
|
/**
|
|
1433
1230
|
* Returns an expression of the value of a query of one value, such as of `get` or of an aggregate, with the operators of its type, such as `form.fields.count().expr().gt(3)`.
|
|
@@ -1435,6 +1232,36 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1435
1232
|
* Without a row, the expression is `NULL`, and the query does not reject.
|
|
1436
1233
|
*/
|
|
1437
1234
|
expr<Q extends QueryOf<ExpressionQueryState>>(this: Q): Expression<ScalarQueryValue<Q>, Q["types"]["valueType"]["operators"], Q["types"]["valueType"]["input"]>;
|
|
1235
|
+
/** Groups the rows by the listed columns, after the keys of earlier calls, so that the query gives one row of each group, whose fields are its keys and the aggregates of its rows, such as `sum(field.position)`. */
|
|
1236
|
+
groupBy<S extends UnaggregatedQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, ...keys: (keyof S["table"]["columns"] & string)[]): SelectQuery<GroupedState<S>, Kind>;
|
|
1237
|
+
/**
|
|
1238
|
+
* Groups the rows by the keys returned by `callback`, after the keys of earlier calls, so that the query gives one row of each group, whose fields are its keys and the aggregates of its rows, such as `sum(field.position)`.
|
|
1239
|
+
*
|
|
1240
|
+
* `callback` receives the columns with the queries of the relations of the table, and the fields selected so far, and returns an expression or a query of one value, or an array of them.
|
|
1241
|
+
* A selected field groups by the value of the field; a field of nested rows or of a literal cannot be grouped by.
|
|
1242
|
+
* Methods that choose rows and read values, such as `limit`, `take`, and `pluck`, apply to the groups, and an aggregate method aggregates them, such as `count` for the number of the groups.
|
|
1243
|
+
* The query cannot take a row lock, `update`, or `delete`.
|
|
1244
|
+
*/
|
|
1245
|
+
groupBy<S extends RecordQueryState$1, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>, selected: SelectedRefs<S["result"]>) => GroupTerms): SelectQuery<GroupedState<S>, Kind>;
|
|
1246
|
+
/**
|
|
1247
|
+
* Groups the rows of a query made by `get` or `pluck` by the keys returned by `callback`, after the keys of earlier calls.
|
|
1248
|
+
*
|
|
1249
|
+
* `callback` receives the columns with the queries of the relations of the table, and the expression of the value, and returns what `groupBy` of a query of records takes.
|
|
1250
|
+
*/
|
|
1251
|
+
groupBy<S extends UnaggregatedValueQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>, value: AnyExpression<S["result"]>) => GroupTerms): SelectQuery<GroupedState<S>, Kind>;
|
|
1252
|
+
/**
|
|
1253
|
+
* Filters the groups of a query of `groupBy` by what `where` takes, such as an aggregate of a group, combined with `AND` with the previous conditions of the groups; `where` keeps filtering the rows of the groups.
|
|
1254
|
+
*
|
|
1255
|
+
* A callback also receives the fields selected so far, such as `having((submission, selected) => selected.submissions.gt(1))`, or the value of a query made by `get` or `pluck`.
|
|
1256
|
+
*/
|
|
1257
|
+
having<Q extends QueryOf<UnguaranteedQueryState>>(this: Q, filter: QueryHavingFilter<Q["types"]>): Q;
|
|
1258
|
+
/**
|
|
1259
|
+
* Filters the groups of a query of `groupBy` by what `where` takes, such as an aggregate of a group, combined with `AND` with the previous conditions of the groups; `where` keeps filtering the rows of the groups.
|
|
1260
|
+
*
|
|
1261
|
+
* A callback also receives the fields selected so far, or the value of a query made by `get` or `pluck`.
|
|
1262
|
+
* A query of the record of a required relation, such as `field.form`, resolves to `null` without a group that passes the filter, or to `undefined` after `get` or `pluck`.
|
|
1263
|
+
*/
|
|
1264
|
+
having<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>, filter: QueryHavingFilter<S>): SelectQuery<FilteredState<S>, Kind>;
|
|
1438
1265
|
/**
|
|
1439
1266
|
* Sorts the rows by the sort keys returned by `callback`, after the sort keys of earlier calls.
|
|
1440
1267
|
*
|
|
@@ -1442,7 +1269,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1442
1269
|
* It returns an expression or a query of one value, such as of an aggregate of related records, sorted in ascending order, `asc`, `desc`, or `orderBy` of one, or an array of them.
|
|
1443
1270
|
* A selected field sorts by the value of the field, also when it changes from row to row, such as `random()`; a field of nested rows cannot be sorted by.
|
|
1444
1271
|
*/
|
|
1445
|
-
orderBy<Q extends QueryOf<RecordQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, selected: SelectedRefs<Q["types"]["result"]>) => OrderTerms): Q;
|
|
1272
|
+
orderBy<Q extends QueryOf<RecordQueryState$1>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, selected: SelectedRefs<Q["types"]["result"]>) => OrderTerms): Q;
|
|
1446
1273
|
/**
|
|
1447
1274
|
* Sorts the values of a query made by `get` or `pluck` by the sort keys returned by `callback`, after the sort keys of earlier calls.
|
|
1448
1275
|
*
|
|
@@ -1450,12 +1277,73 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1450
1277
|
* It returns an expression or a query of one value, sorted in ascending order, `asc`, `desc`, or `orderBy` of one, or an array of them.
|
|
1451
1278
|
*/
|
|
1452
1279
|
orderBy<Q extends QueryOf<ValueQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, value: AnyExpression<Q["types"]["result"]>) => OrderTerms): Q;
|
|
1280
|
+
/**
|
|
1281
|
+
* Sorts the rows of a query that `map` converts by the sort keys returned by `callback`, after the sort keys of earlier calls.
|
|
1282
|
+
*
|
|
1283
|
+
* `callback` receives the columns with the queries of the relations of the table, and returns what `orderBy` of a query of records takes.
|
|
1284
|
+
*/
|
|
1285
|
+
orderBy<Q extends QueryOf<MappedQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>) => OrderTerms): Q;
|
|
1453
1286
|
/** Sorts the rows by the listed columns in ascending order, or in the directions of objects of columns, after the sort keys of earlier calls. */
|
|
1454
1287
|
orderBy<Q extends AnySelectQuery>(this: Q, ...keys: OrderKey<Q["types"]["table"]>[]): Q;
|
|
1455
1288
|
/** Returns at most `count` rows of a query of many rows, replacing an earlier limit. */
|
|
1456
1289
|
limit<Q extends QueryOf<ManyRowsQueryState>>(this: Q, count: number): Q;
|
|
1457
1290
|
/** Skips the first `count` rows of a query of many rows, replacing an earlier offset. */
|
|
1458
1291
|
offset<Q extends QueryOf<ManyRowsQueryState>>(this: Q, count: number): Q;
|
|
1292
|
+
/**
|
|
1293
|
+
* Removes the duplicate rows of a query of many rows, such as of `pluck` for `in`, comparing the fields that the query selects, also those selected after it.
|
|
1294
|
+
*
|
|
1295
|
+
* Sort the query only by its selected fields.
|
|
1296
|
+
* The query cannot select nested rows, which `distinct` cannot compare.
|
|
1297
|
+
* The aggregate methods and `exists` after it read the distinct rows of the fields selected before them, and an aggregate method takes only a selected column or expression.
|
|
1298
|
+
*/
|
|
1299
|
+
distinct<Q extends QueryOf<ManyRowsQueryState>>(this: Q): Q;
|
|
1300
|
+
/**
|
|
1301
|
+
* Keeps the first row of each group of the rows of a query of many rows with equal values of the keys returned by `callback`, after the keys of earlier calls, such as the latest submission of each user.
|
|
1302
|
+
*
|
|
1303
|
+
* `callback` receives the columns with the queries of the relations of the table, and the fields selected so far, and returns an expression or a query of one value, or an array of them; a field of nested rows or of a literal cannot be a key.
|
|
1304
|
+
* Sort the query by the keys first, then by the order that chooses the first row of each group; the rows keep that order.
|
|
1305
|
+
* To sort by a key of an expression, select it and take it from the second parameter of the callbacks of `distinctOn` and `orderBy`.
|
|
1306
|
+
* The aggregate methods and `exists` after it read the first rows, such as `count` for the number of the groups.
|
|
1307
|
+
*/
|
|
1308
|
+
distinctOn<Q extends QueryOf<RecordQueryState$1 & ManyRowsQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, selected: SelectedRefs<Q["types"]["result"]>) => GroupTerms): Q;
|
|
1309
|
+
/**
|
|
1310
|
+
* Keeps the first value of each group of the values of a query made by `pluck` with equal values of the keys returned by `callback`, after the keys of earlier calls.
|
|
1311
|
+
*
|
|
1312
|
+
* `callback` receives the columns with the queries of the relations of the table, and the expression of the value, and returns what `distinctOn` of a query of records takes.
|
|
1313
|
+
*/
|
|
1314
|
+
distinctOn<Q extends QueryOf<ValueQueryState & ManyRowsQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>, value: AnyExpression<Q["types"]["result"]>) => GroupTerms): Q;
|
|
1315
|
+
/**
|
|
1316
|
+
* Keeps the first row of each group of the rows of a query that `map` converts with equal values of the keys returned by `callback`, after the keys of earlier calls.
|
|
1317
|
+
*
|
|
1318
|
+
* `callback` receives the columns with the queries of the relations of the table, and returns what `distinctOn` of a query of records takes.
|
|
1319
|
+
*/
|
|
1320
|
+
distinctOn<Q extends QueryOf<MappedQueryState & ManyRowsQueryState>>(this: Q, callback: (columns: ColumnRefs<Q["types"]["table"]> & RelationRefs<Q["types"]["schema"]>) => GroupTerms): Q;
|
|
1321
|
+
/**
|
|
1322
|
+
* Keeps the first row of each group of the rows of a query of many rows with equal values of the listed columns, after the keys of earlier calls, such as the latest submission of each user.
|
|
1323
|
+
*
|
|
1324
|
+
* Sort the query by the keys first, then by the order that chooses the first row of each group; the rows keep that order.
|
|
1325
|
+
*/
|
|
1326
|
+
distinctOn<Q extends QueryOf<ManyRowsQueryState>>(this: Q, ...keys: (keyof Q["types"]["table"]["columns"] & string)[]): Q;
|
|
1327
|
+
/**
|
|
1328
|
+
* Locks the rows of the query until its transaction ends, so that code can read a row and then update it based on the values it read: another transaction waits to change or lock them.
|
|
1329
|
+
*
|
|
1330
|
+
* It replaces an earlier lock of the query, and reaches no other query: lock the records of a nested query by calling it there.
|
|
1331
|
+
* Without `options`, the query waits for the rows that another transaction has locked.
|
|
1332
|
+
*
|
|
1333
|
+
* It requires a transaction, unless the query is part of a mutation, such as of its filter.
|
|
1334
|
+
* The query cannot use `distinct`, `distinctOn`, or `groupBy`, and the aggregate methods and `exists` reject it after the lock.
|
|
1335
|
+
*/
|
|
1336
|
+
forUpdate<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
|
|
1337
|
+
/**
|
|
1338
|
+
* Locks the rows of the query as `forUpdate` does, but lets other transactions insert records that refer to them.
|
|
1339
|
+
*
|
|
1340
|
+
* Use it when the transaction only updates columns outside the keys of the rows.
|
|
1341
|
+
*/
|
|
1342
|
+
forNoKeyUpdate<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
|
|
1343
|
+
/** Keeps the rows of the query from changing until its transaction ends, as `forUpdate` does, while other transactions read and share-lock them too. */
|
|
1344
|
+
forShare<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
|
|
1345
|
+
/** Keeps the rows of the query from being deleted or changing their keys until its transaction ends, as `forUpdate` does, while other transactions change their other columns. */
|
|
1346
|
+
forKeyShare<Q extends QueryOf<LockableQueryState>>(this: Q, options?: RowLockOptions): Q;
|
|
1459
1347
|
/** Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without a row. */
|
|
1460
1348
|
optional<S extends OneRowQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
|
|
1461
1349
|
rows: "optional";
|
|
@@ -1464,7 +1352,7 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1464
1352
|
/**
|
|
1465
1353
|
* Makes a query of one record, such as one of `take`, resolve to `null` without a row.
|
|
1466
1354
|
*
|
|
1467
|
-
* A value of `get` or `pluck` is never `null` for a missing row, which would read as a `NULL` value, so a query of values does not accept it, and after `get` or `pluck` the query resolves to `undefined` without a row.
|
|
1355
|
+
* A value of `get` or `pluck` is never `null` for a missing row, which would read as a `NULL` value, so a query of values does not accept it, unless `map` converts them, and after `get` or `pluck` the query resolves to `undefined` without a row.
|
|
1468
1356
|
*/
|
|
1469
1357
|
nullable<S extends OneRecordQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): SelectQuery<ChangeState<S, {
|
|
1470
1358
|
rows: "nullable";
|
|
@@ -1520,6 +1408,26 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1520
1408
|
delete<S extends SelectQueryState, Kind extends SelectQueryKind>(this: SelectQuery<S, Kind>): MutationQuery<InitialMutationState<S["table"], S["schema"], S["rows"]>, Kind>;
|
|
1521
1409
|
/** Allows `update` and `delete` to change every row of the table when the query has no filter; it changes nothing else. */
|
|
1522
1410
|
all<Q extends QueryOf<ManyRowsQueryState>>(this: Q): Q;
|
|
1411
|
+
/**
|
|
1412
|
+
* Converts each record or value of the result in code, after decoding, executed or nested, such as to add a field that SQL cannot compute.
|
|
1413
|
+
*
|
|
1414
|
+
* `callback` receives one record or value, also `null` of a `NULL` value, and is not called for a missing row, so an optional query still resolves to `undefined` without a row; it returns its result synchronously.
|
|
1415
|
+
* The SQL stays as it is, so the methods that read the fields, such as `select` and `count`, and expressions reject the query after it, whereas `where`, `orderBy`, `limit`, `take`, and further `map` apply.
|
|
1416
|
+
* A failure of `callback` rejects with `ResultDecodeError`, whose cause is the error.
|
|
1417
|
+
*/
|
|
1418
|
+
map<S extends SelectQueryState, Kind extends SelectQueryKind, R>(this: SelectQuery<S, Kind>, callback: (row: S["result"]) => R & SynchronousResult<R>): SelectQuery<ChangeState<S, {
|
|
1419
|
+
result: R;
|
|
1420
|
+
value: "mapped";
|
|
1421
|
+
aggregate: true;
|
|
1422
|
+
}>, Kind>;
|
|
1423
|
+
/**
|
|
1424
|
+
* Converts the whole result in code, after decoding, executed or nested, such as to group rows or to compute a value from them.
|
|
1425
|
+
*
|
|
1426
|
+
* `callback` receives what the query resolves to, once: the array of rows, one row, or `null` or `undefined` of a missing row of a nullable or optional query; it returns its result synchronously.
|
|
1427
|
+
* The SQL stays as it is, so call it last: the returned query only executes, nests in a selection, and takes further `transform`.
|
|
1428
|
+
* A failure of `callback` rejects with `ResultDecodeError`, whose cause is the error.
|
|
1429
|
+
*/
|
|
1430
|
+
transform<S extends SelectQueryState, Kind extends SelectQueryKind, R>(this: SelectQuery<S, Kind>, callback: (result: QueryResult<S>) => R & SynchronousResult<R>): TransformedQuery<TransformedQueryState<S["table"], R, S["uses"]>, Kind>;
|
|
1523
1431
|
/**
|
|
1524
1432
|
* Returns the query that `callback` builds from this query, such as one with a conditional clause, or that a helper of `defineHelper` builds with `args`.
|
|
1525
1433
|
*
|
|
@@ -1552,20 +1460,30 @@ declare class SelectQuery<out S extends SelectQueryState, out Kind extends Selec
|
|
|
1552
1460
|
* It adds the changes of `take` to `changes`, which must leave the limit as it is.
|
|
1553
1461
|
*/
|
|
1554
1462
|
private deriveTaken;
|
|
1555
|
-
/**
|
|
1463
|
+
/**
|
|
1464
|
+
* Creates the query of the value of `projection`, of an aggregate or of `exists` over the rows of this query, which always returns one row.
|
|
1465
|
+
*
|
|
1466
|
+
* A query of `distinct` or `distinctOn` keeps the fields that `projection` replaces: `distinct` compares them, and the keys, the order, and the argument of an aggregate read a selected field through its projection.
|
|
1467
|
+
*/
|
|
1556
1468
|
private deriveAggregate;
|
|
1557
1469
|
/** Creates the query of the aggregate of `method` over `arg`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value; `delimiter` is the delimiter of `stringAgg`. */
|
|
1558
1470
|
private aggregateBy;
|
|
1559
1471
|
/** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
|
|
1560
1472
|
private addFilter;
|
|
1473
|
+
/** Returns the rows mode of this query after a filter, as `FilteredStateRows` gives it in types. */
|
|
1474
|
+
private getFilteredRows;
|
|
1561
1475
|
/** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
|
|
1562
1476
|
private takeWhere;
|
|
1563
1477
|
/** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
|
|
1564
1478
|
private changeOneRow;
|
|
1479
|
+
/** Rejects `method`, which reads or changes the fields of the query, on a query that `map` converts. */
|
|
1480
|
+
private rejectMapped;
|
|
1565
1481
|
/** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
|
|
1566
1482
|
private rejectValue;
|
|
1567
1483
|
/** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method or `exists`. */
|
|
1568
1484
|
private rejectAggregate;
|
|
1485
|
+
/** Rejects `method`, an aggregate method or `exists`, on a query made by one of them or with a row lock. */
|
|
1486
|
+
private rejectAggregation;
|
|
1569
1487
|
}
|
|
1570
1488
|
/** Select query bound to a `Db`, executed by awaiting it; every method returns a query bound to the same `Db`. */
|
|
1571
1489
|
type BoundSelectQuery<S extends SelectQueryState> = SelectQuery<S, "bound">;
|
|
@@ -1577,17 +1495,221 @@ type ResultOf<Q extends AnyQuery> = Q["types"]["result"];
|
|
|
1577
1495
|
type TableOrQuery<T extends AnyTable, C extends SchemaContext = SchemaContext> = T | QueryOf<QueryStateOf<T, C>>;
|
|
1578
1496
|
/** Starts a query over a new occurrence of the table. */
|
|
1579
1497
|
declare function from<T extends AnyTable>(table: T): SelectQuery<InitialQueryState<T>>;
|
|
1580
|
-
/**
|
|
1581
|
-
type
|
|
1582
|
-
/**
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
type
|
|
1590
|
-
/**
|
|
1498
|
+
/** References to the columns of the query source, passed to query callbacks. */
|
|
1499
|
+
type ColumnRefs<T extends AnyTable> = { readonly [K in keyof T["columns"]]: Expression<Selectable<T>[K], ColumnOperators<T, K>, ColumnValues<T>[K]>; };
|
|
1500
|
+
/**
|
|
1501
|
+
* Queries of the records of the relations of the table of schema context `C`, by relation name, which the callbacks of queries receive beside the columns.
|
|
1502
|
+
*
|
|
1503
|
+
* A relation name is never a column key of its table.
|
|
1504
|
+
* A context whose table key is not known, such as one of a query of any schema, has no relations.
|
|
1505
|
+
*/
|
|
1506
|
+
type RelationRefs<C extends SchemaContext> = string extends C["key"] ? EmptyRecord : C["key"] extends keyof C["relations"] ? RelationQueries<C["relations"], C["key"]> : EmptyRecord;
|
|
1507
|
+
type RelationQueries<R extends SchemaContext["relations"], K extends keyof R & string> = { readonly [N in keyof R[K]]: RelatedQuery<R, K, N & string>; };
|
|
1508
|
+
/** 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. */
|
|
1509
|
+
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"]>>;
|
|
1510
|
+
/** Runtime context of the queries of a table in the schema they start from. */
|
|
1511
|
+
interface QueryContext {
|
|
1512
|
+
/** Getters of the queries of the relations of the table, which the references of the callbacks of queries have as their own properties and which read the key columns from them. */
|
|
1513
|
+
readonly relations: PropertyDescriptorMap;
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* Direction of a sort key, optionally with the placement of `NULL`.
|
|
1517
|
+
*
|
|
1518
|
+
* Without a placement, `NULL` comes last in ascending order and first in descending order.
|
|
1519
|
+
*/
|
|
1520
|
+
type OrderDirection = "asc" | "desc" | "asc nulls first" | "asc nulls last" | "desc nulls first" | "desc nulls last";
|
|
1521
|
+
/** Columns of table `T` with the directions to sort by them, in the order of their keys. */
|
|
1522
|
+
type OrderColumns<T extends AnyTable> = { readonly [K in keyof T["columns"]]?: OrderDirection; };
|
|
1523
|
+
/** Argument of `orderBy` of a query over table `T`: a column key, sorted in ascending order, or columns with directions. */
|
|
1524
|
+
type OrderKey<T extends AnyTable> = (keyof T["columns"] & string) | OrderColumns<T>;
|
|
1525
|
+
declare const ordering: unique symbol;
|
|
1526
|
+
/** Expression or query of one value with the direction of its sort key, made by `asc`, `desc`, or `orderBy`. */
|
|
1527
|
+
interface Ordering {
|
|
1528
|
+
readonly [ordering]: true;
|
|
1529
|
+
}
|
|
1530
|
+
/** Sort key returned by the callback of `orderBy`: an expression or a query of one value, such as of an aggregate of related records, sorted in ascending order, or one with a direction. */
|
|
1531
|
+
type OrderTerm = AnyExpression | ScalarQuery | Ordering;
|
|
1532
|
+
/**
|
|
1533
|
+
* References of the callbacks of `orderBy`, `groupBy`, and `distinctOn` to the fields of records `R` selected by a query: their expressions by key.
|
|
1534
|
+
*
|
|
1535
|
+
* A field of nested rows or of a literal is among them in types, but reading it throws; a field of an aggregate or of `exists` gives its value.
|
|
1536
|
+
*/
|
|
1537
|
+
type SelectedRefs<R> = { readonly [K in keyof R & string]: AnyExpression<R[K]>; };
|
|
1538
|
+
/** Sort keys returned by the callback of `orderBy`: one or an array of them. */
|
|
1539
|
+
type OrderTerms = OrderTerm | readonly OrderTerm[];
|
|
1540
|
+
/** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
|
|
1541
|
+
declare function asc(value: AnyExpression | ScalarQuery): Ordering;
|
|
1542
|
+
/** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
|
|
1543
|
+
declare function desc(value: AnyExpression | ScalarQuery): Ordering;
|
|
1544
|
+
/** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
|
|
1545
|
+
declare function orderBy(value: AnyExpression | ScalarQuery, direction: OrderDirection): Ordering;
|
|
1546
|
+
/** Expression of a count: a number, with the operators of `orderingOperators`. */
|
|
1547
|
+
type CountExpression = Expression<number, CountValueType["operators"], CountValueType["input"]>;
|
|
1548
|
+
/** Expression of an aggregate of the values of `E`, an expression or a query of one value, `NULL` without values other than `NULL`, with the operators of its type. */
|
|
1549
|
+
type AggregateExpression<E extends TypedOperand> = Expression<OperandValue<E> | null, TypedOperandOperators<E>, TypedOperandInput<E>>;
|
|
1550
|
+
declare const groupValue: unique symbol;
|
|
1551
|
+
/** Value `T` of a directly selected expression in a nonempty group. */
|
|
1552
|
+
interface GroupValue<T> {
|
|
1553
|
+
readonly [groupValue]: T;
|
|
1554
|
+
}
|
|
1555
|
+
/** Aggregate without a filter, whose value in a group keeps only the nullability of its argument. */
|
|
1556
|
+
type GroupAggregateExpression<E extends TypedOperand> = AggregateExpression<E> & GroupValue<OperandValue<E>>;
|
|
1557
|
+
/** Options of an aggregate function. */
|
|
1558
|
+
interface AggregateOptions {
|
|
1559
|
+
/** Condition of the rows that the function aggregates, as `FILTER (WHERE ...)`: a Boolean expression or a query of one Boolean value. */
|
|
1560
|
+
readonly filter?: AnyExpression<boolean | null> | ScalarQuery<boolean | null>;
|
|
1561
|
+
}
|
|
1562
|
+
/** Options of `stringAgg`. */
|
|
1563
|
+
interface StringAggOptions extends AggregateOptions {
|
|
1564
|
+
/** Order in which the values are joined: a sort key or an array of them, as the callback of `orderBy` of a query returns; without it, PostgreSQL joins them in any order. */
|
|
1565
|
+
readonly orderBy?: OrderTerms;
|
|
1566
|
+
}
|
|
1567
|
+
/** Options of an aggregate function without `filter`, which takes every row. */
|
|
1568
|
+
interface UnfilteredAggregateOptions {
|
|
1569
|
+
/** No rows are removed from the aggregate input. */
|
|
1570
|
+
readonly filter?: undefined;
|
|
1571
|
+
}
|
|
1572
|
+
/** Options of `stringAgg` without `filter`, which takes every row. */
|
|
1573
|
+
interface UnfilteredStringAggOptions extends UnfilteredAggregateOptions {
|
|
1574
|
+
/** Order in which the values are joined: a sort key or an array of them, as the callback of `orderBy` of a query returns; without it, PostgreSQL joins them in any order. */
|
|
1575
|
+
readonly orderBy?: OrderTerms;
|
|
1576
|
+
}
|
|
1577
|
+
/** Returns the number of the rows of the query that selects it, or of each of its groups, as `count(*)`. */
|
|
1578
|
+
declare function count(): CountExpression;
|
|
1579
|
+
/** Returns the number of the rows of the query that selects it, or of each of its groups, as `count(*)`; `options.filter` chooses the rows that it counts. */
|
|
1580
|
+
declare function count(options: AggregateOptions): CountExpression;
|
|
1581
|
+
/** Returns the number of the values of `value`, an expression with a type or a query of one value, other than `NULL`; `options.filter` chooses the rows that it takes. */
|
|
1582
|
+
declare function count(value: TypedOperand, options?: AggregateOptions): CountExpression;
|
|
1583
|
+
/** Returns the number of the distinct values of `value`, an expression with a type or a query of one value, other than `NULL`; `options.filter` chooses the rows that it takes. */
|
|
1584
|
+
declare function countDistinct(value: TypedOperand, options?: AggregateOptions): CountExpression;
|
|
1585
|
+
/** Returns the smallest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`. */
|
|
1586
|
+
declare function min<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
|
|
1587
|
+
/** Returns the smallest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
|
|
1588
|
+
declare function min<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
|
|
1589
|
+
/** Returns the largest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`. */
|
|
1590
|
+
declare function max<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
|
|
1591
|
+
/** Returns the largest of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
|
|
1592
|
+
declare function max<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
|
|
1593
|
+
/** Returns the sum of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`. */
|
|
1594
|
+
declare function sum<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
|
|
1595
|
+
/** Returns the sum of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
|
|
1596
|
+
declare function sum<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
|
|
1597
|
+
/**
|
|
1598
|
+
* Returns the average of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`.
|
|
1599
|
+
*
|
|
1600
|
+
* For `bigint` values, average an expression of a type that can represent fractional values.
|
|
1601
|
+
*/
|
|
1602
|
+
declare function avg<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
|
|
1603
|
+
/**
|
|
1604
|
+
* Returns the average of the values of `value`, an expression with a type or a query of one value, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes.
|
|
1605
|
+
*
|
|
1606
|
+
* For `bigint` values, average an expression of a type that can represent fractional values.
|
|
1607
|
+
*/
|
|
1608
|
+
declare function avg<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
|
|
1609
|
+
/** Returns whether every value of `value`, a Boolean expression with a type or a query of one Boolean value, other than `NULL` is true, or `null` without such values. */
|
|
1610
|
+
declare function every<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
|
|
1611
|
+
/** Returns whether every value of `value`, a Boolean expression with a type or a query of one Boolean value, other than `NULL` is true, or `null` without such values; `options.filter` chooses the rows that it takes. */
|
|
1612
|
+
declare function every<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
|
|
1613
|
+
/** Returns whether any value of `value`, a Boolean expression with a type or a query of one Boolean value, is true, or `null` without values other than `NULL`. */
|
|
1614
|
+
declare function some<E extends TypedOperand>(value: E, options?: UnfilteredAggregateOptions): GroupAggregateExpression<E>;
|
|
1615
|
+
/** Returns whether any value of `value`, a Boolean expression with a type or a query of one Boolean value, is true, or `null` without values other than `NULL`; `options.filter` chooses the rows that it takes. */
|
|
1616
|
+
declare function some<E extends TypedOperand>(value: E, options?: AggregateOptions): AggregateExpression<E>;
|
|
1617
|
+
/** Returns the values other than `NULL` of `value`, a text expression with a type or a query of one text value, joined with `delimiter` in the order of `options.orderBy`, or `null` without such values. */
|
|
1618
|
+
declare function stringAgg<E extends TypedOperand>(value: E, delimiter: string, options?: UnfilteredStringAggOptions): GroupAggregateExpression<E>;
|
|
1619
|
+
/** Returns the values other than `NULL` of `value`, a text expression with a type or a query of one text value, joined with `delimiter` in the order of `options.orderBy`, or `null` without such values; `options.filter` chooses the rows that it takes. */
|
|
1620
|
+
declare function stringAgg<E extends TypedOperand>(value: E, delimiter: string, options?: StringAggOptions): AggregateExpression<E>;
|
|
1621
|
+
/**
|
|
1622
|
+
* Field of a selection whose value is `T`, made by `literal`.
|
|
1623
|
+
*
|
|
1624
|
+
* It is not an expression: it has no SQL, so only a selection takes it.
|
|
1625
|
+
*/
|
|
1626
|
+
declare class Literal<out T> {
|
|
1627
|
+
/** Value of the field in every record, which the query returns as it is. */
|
|
1628
|
+
readonly literal: T;
|
|
1629
|
+
constructor(
|
|
1630
|
+
/** Value of the field in every record, which the query returns as it is. */
|
|
1631
|
+
literal: T);
|
|
1632
|
+
/** Rejects the literal as an operand of an expression: a statement has no SQL of it. */
|
|
1633
|
+
[operandNode](): never;
|
|
1634
|
+
}
|
|
1635
|
+
/**
|
|
1636
|
+
* Creates a field of a selection with `value` in every record, without selecting anything in SQL: the query returns the value itself, not a copy of it, whatever it is.
|
|
1637
|
+
*
|
|
1638
|
+
* It lets a branch of a selection skip a column or a nested query, such as `withHint ? field.hint : literal(null)`.
|
|
1639
|
+
* To use a value in SQL, such as in a condition, pass it through `param` instead.
|
|
1640
|
+
*/
|
|
1641
|
+
declare function literal<T extends {} | null | undefined>(value: T): Literal<T>;
|
|
1642
|
+
/** Expressions, nested queries, and literals selected under the keys of the result fields; a record has no symbol keys. */
|
|
1643
|
+
interface Selection {
|
|
1644
|
+
readonly [key: string]: TypedExpression | NestedQuery | Literal<unknown>;
|
|
1645
|
+
readonly [key: symbol]: never;
|
|
1646
|
+
}
|
|
1647
|
+
/** Query whose rows a selection nests as the value of a field: a query of any state and kind, such as a query of a relation, also converted by `map` or `transform`. */
|
|
1648
|
+
type NestedQuery = QueryOf<SelectQueryState> | TransformedQuery<TransformedQueryState, SelectQueryKind>;
|
|
1649
|
+
/** Record of the values of the expressions, of the nested rows, and of the literals of a selection. */
|
|
1650
|
+
type SelectionResult<S extends Selection> = { [K in keyof S]: FieldValue<S[K]>; };
|
|
1651
|
+
/** Record of a selection in a query of groups. */
|
|
1652
|
+
type GroupSelectionResult<S extends Selection> = { [K in keyof S]: GroupFieldValue<S[K]>; };
|
|
1653
|
+
/** Value of a field selected in a group, leaving nested queries and literals unchanged. */
|
|
1654
|
+
type GroupFieldValue<V> = V extends GroupValue<infer T> ? T : FieldValue<V>;
|
|
1655
|
+
/** Value of an operand in a query of groups. */
|
|
1656
|
+
type GroupOperandValue<E> = E extends GroupValue<infer T> ? T : OperandValue<E>;
|
|
1657
|
+
/** Value of a selected field: of an expression, of the nested rows of a query as the result of executing it, or of a literal, for each member of a union of them. */
|
|
1658
|
+
type FieldValue<V> = V extends NestedQuery ? QueryResult<V["types"]> : V extends Literal<infer T> ? T : ExpressionValue<V>;
|
|
1659
|
+
/** Relations whose records the nested queries of a selection select. */
|
|
1660
|
+
type SelectionUses<S extends Selection> = S[keyof S] extends (infer V) ? V extends NestedQuery ? V["types"]["uses"] : never : never;
|
|
1661
|
+
/** Value of a selected expression. */
|
|
1662
|
+
type ExpressionValue<E> = E extends AnyExpression<infer T> ? T : never;
|
|
1663
|
+
/** Values that the type of an expression encodes, such as in place of its value. */
|
|
1664
|
+
type ExpressionInput<E> = E extends AnyExpression<unknown, infer I> ? I : never;
|
|
1665
|
+
declare const helperFields: unique symbol;
|
|
1666
|
+
/** Marker of the input fields of a helper, carrying the keys selected by its callback. */
|
|
1667
|
+
interface HelperFields<Keys extends PropertyKey = PropertyKey> {
|
|
1668
|
+
readonly [helperFields]: Keys;
|
|
1669
|
+
}
|
|
1670
|
+
/** Result `R` of a callback of a helper without the marker, which a record of the callback keeps, also through a spread, so that the declarations of a module exporting a helper never name it; `any` stays `any`. */
|
|
1671
|
+
type WithoutHelperFields<R> = IsAny<R> extends true ? R : R extends HelperFields ? { [K in keyof R as K extends keyof HelperFields ? never : K]: R[K]; } : R;
|
|
1672
|
+
/** Records with `Fields` added or replaced, for each branch of either record type; `any` stays `any`. */
|
|
1673
|
+
type MergeSelection<Previous, Fields> = Previous extends unknown ? Fields extends unknown ? MergeFields<RecordFields<Previous>, RecordFields<Fields>> & (IsAny<Previous> extends true ? Previous : unknown) : never : never;
|
|
1674
|
+
/** Fields with numeric keys represented as the string keys used in result records. */
|
|
1675
|
+
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;
|
|
1676
|
+
/** Merge of normalized fields, retaining the previous value when an optional replacement is absent. */
|
|
1677
|
+
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.
|
|
1678
|
+
? Previous[K] | keyof Fields : K extends keyof Fields // A decoder can return undefined, so it cannot be excluded as merely an absent property.
|
|
1679
|
+
? Previous[K] | Fields[K] : Previous[K]; } & { [K in keyof Fields as K extends keyof Previous ? ({} extends Pick<Fields, K> ? never : K) : K]: Fields[K]; }>;
|
|
1680
|
+
/** Types of the values of columns `K` of table `T` as selected fields: the values that each encodes and its operators. */
|
|
1681
|
+
type ColumnFieldTypes<T extends AnyTable, K extends keyof T["columns"]> = { [P in K]: ColumnValueType<T, P>; };
|
|
1682
|
+
/** Types of the values of the expressions and the queries of one value of selection `Sel`, under the keys of the result records, as `MergeSelection` normalizes them. */
|
|
1683
|
+
type SelectionFieldTypes<Sel> = { [K in keyof Sel as K extends number ? `${K}` : K]: FieldType<Exclude<Sel[K], undefined>>; };
|
|
1684
|
+
/** Type of the value of a selected field `F`, for each member of a union of them, so that each keeps its own operators and values. */
|
|
1685
|
+
type FieldType<F> = F extends TypedOperand ? F extends GroupValue<infer T> ? OperandValueType<F> & {
|
|
1686
|
+
readonly group: T;
|
|
1687
|
+
} : OperandValueType<F> : unknown;
|
|
1688
|
+
/** Record `R` of a query whose rows become groups, with field types `F`. */
|
|
1689
|
+
type GroupedRecord<R, F> = IsAny<R> extends true ? R : R extends unknown ? { [K in keyof R]: K extends keyof F ? GroupedField<R[K], Exclude<F[K], undefined>> : R[K]; } : never;
|
|
1690
|
+
/** Value of a selected field after grouping; a union of field types must all guarantee a non-null value to remove `null`. */
|
|
1691
|
+
type GroupedField<V, D> = [D] extends [{
|
|
1692
|
+
readonly group: infer G;
|
|
1693
|
+
}] ? null extends G ? V : Exclude<V, null> : V;
|
|
1694
|
+
/** Types of the values of fields `P` with those of fields `N` added or replaced, by the rules of `MergeSelection`, for each branch of either. */
|
|
1695
|
+
type MergeFieldTypes<P, N> = P extends unknown ? N extends unknown ? [keyof N] extends [never] ? P : [keyof P] extends [never] ? N : { [K in keyof P | keyof N]: K extends keyof N ? {} extends Pick<N, K> ? K extends keyof P ? P[K] | Exclude<N[K], undefined> : Exclude<N[K], undefined> : N[K] : K extends keyof P ? P[K] : never; } : never : never;
|
|
1696
|
+
/** Types of the values of the selected fields of a query: those of `P`, the `fieldTypes` part of the state before a selection, with `N` added or replaced. */
|
|
1697
|
+
interface SelectedFieldTypes<out P, N> {
|
|
1698
|
+
readonly types: MergeFieldTypes<SelectedFieldTypesOf<P>, N>;
|
|
1699
|
+
}
|
|
1700
|
+
/** Types of the values of the selected fields of the `fieldTypes` part `F` of a state, by key; none for `EmptyRecord` of a query without selected fields. */
|
|
1701
|
+
type SelectedFieldTypesOf<F> = F extends SelectedFieldTypes<unknown, unknown> ? F["types"] : EmptyRecord;
|
|
1702
|
+
/** First operand of `coalesce`, `greatest`, and `least`: an expression with a type, or a query of one value, such as of an aggregate, whose type decodes the result and gives it its operators. */
|
|
1703
|
+
type TypedOperand = TypedExpression | TypedScalarQuery;
|
|
1704
|
+
/** Values that the type of the first operand `F` encodes. */
|
|
1705
|
+
type TypedOperandInput<F> = F extends TypedScalarQuery ? F["types"]["valueType"]["input"] : ExpressionInput<F>;
|
|
1706
|
+
/** Operators of the type of the first operand `F`. */
|
|
1707
|
+
type TypedOperandOperators<F> = F extends TypedScalarQuery ? F["types"]["valueType"]["operators"] : F extends TypedExpression ? ExpressionOperators<F> : never;
|
|
1708
|
+
/** Operand of `coalesce`, `greatest`, and `least` after the first operand `F`: a value that its type encodes, or an expression or a query of one value of its values. */
|
|
1709
|
+
type FollowingOperand<F> = Operand<OperandValue<F>, TypedOperandInput<F>>;
|
|
1710
|
+
/** `null` when every operand can be `NULL`: the first operand `F` and the following operands `R`. */
|
|
1711
|
+
type NullOfEveryOperand<F, R extends readonly unknown[]> = null extends OperandValue<F> ? number extends R["length"] ? null : { [K in keyof R]: null extends OperandValue<R[K]> ? never : true; }[number] extends never ? null : never : never;
|
|
1712
|
+
/** Result of a function of the first operand `F` and the following operands `R` that is `NULL` only when every operand is, whose operands all have the values of `F`. */
|
|
1591
1713
|
type NullSkippingResult<F, R extends readonly unknown[]> = Expression<Exclude<OperandValue<F>, null> | NullOfEveryOperand<F, R>, TypedOperandOperators<F>, TypedOperandInput<F>>;
|
|
1592
1714
|
/**
|
|
1593
1715
|
* Returns the first of its operands other than `NULL`, such as `coalesce(field.hint, "")`, as an expression usable wherever a column is.
|
|
@@ -1629,7 +1751,115 @@ declare function caseWhen<Output, Input, O extends OperatorDefinitions>(type: Ty
|
|
|
1629
1751
|
*/
|
|
1630
1752
|
declare function caseWhen<Output, Input, O extends OperatorDefinitions, const B extends readonly CaseBranch<Output, Input>[], const E extends CaseValue<Output, Input>>(type: Type<Output, Input, O, any>, branches: B, otherwise: E): Expression<CaseResult<Output, B[number][1] | E>, O, Input>;
|
|
1631
1753
|
/**
|
|
1632
|
-
* State
|
|
1754
|
+
* State of the query that the callback of a helper of table `T` with schema context `C` receives: the fields of the query the helper is applied to, and all its rows.
|
|
1755
|
+
*
|
|
1756
|
+
* It is guaranteed, so that the state that the callback returns tells whether the callback ends the guarantee of the query the helper is applied to.
|
|
1757
|
+
*/
|
|
1758
|
+
interface HelperState<T extends AnyTable, C extends SchemaContext> extends QueryStateOf<T, C> {
|
|
1759
|
+
readonly result: HelperFields<never>;
|
|
1760
|
+
readonly valueType: never;
|
|
1761
|
+
readonly fieldTypes: EmptyRecord;
|
|
1762
|
+
readonly rows: "many";
|
|
1763
|
+
readonly value: false;
|
|
1764
|
+
readonly uses: never;
|
|
1765
|
+
readonly guaranteed: true;
|
|
1766
|
+
readonly aggregate: false;
|
|
1767
|
+
}
|
|
1768
|
+
/**
|
|
1769
|
+
* Effect of a helper: the fields it selects and the types of their values, or whether `map` converts its rows and what it gives, its rows mode on a query of many rows, `one` after `take` or `required` and `nullable` or `optional` after the method of the same name, the relations it selects records of, and whether it keeps the guarantee of the row of a query of a required relation.
|
|
1770
|
+
*
|
|
1771
|
+
* `reads` are the relations of the schema of the helper among them, which its callback may read from the references of the query it is applied to, and `key` is the key of its table there.
|
|
1772
|
+
*/
|
|
1773
|
+
interface HelperEffect {
|
|
1774
|
+
/** Whether the helper guarantees that the query is grouped. */
|
|
1775
|
+
readonly grouped: boolean;
|
|
1776
|
+
readonly fields: object;
|
|
1777
|
+
/** Types of the values of the fields it selects, the `fieldTypes` part of the state that its callback returns, which `having` and the narrowing of grouped selections read. */
|
|
1778
|
+
readonly fieldTypes: unknown;
|
|
1779
|
+
/** Whether `map` converts the rows, whose fields the result no longer tells, so that `fields` are empty. */
|
|
1780
|
+
readonly mapped: boolean;
|
|
1781
|
+
/** What `map` gives for each row of a query the helper is applied to; `never` when `mapped` is `false`. */
|
|
1782
|
+
readonly output: unknown;
|
|
1783
|
+
readonly rows: ResultRows;
|
|
1784
|
+
readonly uses: UsedRelation;
|
|
1785
|
+
readonly reads: UsedRelation;
|
|
1786
|
+
readonly key: string;
|
|
1787
|
+
readonly guaranteed: boolean;
|
|
1788
|
+
}
|
|
1789
|
+
/** Effect of a helper whose callback returns a query of state `S`, for each state of a union. */
|
|
1790
|
+
type ReadEffect<S extends SelectQueryState> = S extends SelectQueryState ? {
|
|
1791
|
+
readonly grouped: S["aggregate"] extends Grouped ? true : false;
|
|
1792
|
+
readonly fields: S["value"] extends "mapped" ? EmptyRecord : { [K in keyof S["result"] as K extends keyof HelperFields ? never : K]: S["result"][K]; };
|
|
1793
|
+
readonly fieldTypes: S["value"] extends "mapped" ? EmptyRecord : S["fieldTypes"];
|
|
1794
|
+
readonly mapped: S["value"] extends "mapped" ? true : false;
|
|
1795
|
+
readonly output: S["value"] extends "mapped" ? WithoutHelperFields<S["result"]> : never;
|
|
1796
|
+
readonly rows: S["rows"];
|
|
1797
|
+
readonly uses: S["uses"];
|
|
1798
|
+
readonly reads: Extract<UsableRelation<S["schema"]["relations"]>, S["uses"]>;
|
|
1799
|
+
readonly key: S["schema"]["key"];
|
|
1800
|
+
readonly guaranteed: S["guaranteed"];
|
|
1801
|
+
} : never;
|
|
1802
|
+
/** Error of a helper that a query does not accept, or whose callback returns a query it does not accept. */
|
|
1803
|
+
interface HelperError<Message extends string> {
|
|
1804
|
+
readonly error: Message;
|
|
1805
|
+
}
|
|
1806
|
+
/** `unknown` when every result state retains the input marker and returns records, or converts such records with `map`, or the error. */
|
|
1807
|
+
type CheckResult<S extends SelectQueryState> = [S] extends [{
|
|
1808
|
+
readonly result: HelperFields;
|
|
1809
|
+
readonly value: false;
|
|
1810
|
+
} | {
|
|
1811
|
+
readonly value: "mapped";
|
|
1812
|
+
readonly valueType: never;
|
|
1813
|
+
}] ? unknown : HelperError<"A helper can filter, select fields, map them, and take one row, but cannot clear the selection or use get, pluck, or aggregates">;
|
|
1814
|
+
/** State of a query over table `T` that accepts a helper of effect `E`. */
|
|
1815
|
+
type HelperInput<T extends AnyTable, E extends HelperEffect> = QueryStateOf<T, ReadsContext<E>> & ValueCheck<E> & (true extends E["grouped"] ? {
|
|
1816
|
+
readonly aggregate: false;
|
|
1817
|
+
} : unknown);
|
|
1818
|
+
/** Constraint of `value` of a query that accepts a helper of effect `E`. */
|
|
1819
|
+
type ValueCheck<E extends HelperEffect> = [E extends HelperEffect ? keyof E["fields"] : never] extends [never] ? [Extract<E["rows"], "nullable">] extends [never] ? [E["mapped"]] extends [false] ? unknown : RecordRows<"A helper cannot apply map to a query made by get, pluck, an aggregate, or map"> : RecordRows<"A helper cannot apply nullable to a query made by get, pluck, an aggregate, or map"> : RecordRows<"A helper cannot select fields on a query made by get, pluck, an aggregate, or map">;
|
|
1820
|
+
/** Constraint of a query whose rows are records, which a query of values fails with error `Message`. */
|
|
1821
|
+
interface RecordRows<Message extends string> {
|
|
1822
|
+
readonly value: false | HelperError<Message>;
|
|
1823
|
+
}
|
|
1824
|
+
/** Schema context of a query that has the relations of its schema that a helper of effect `E` may read. */
|
|
1825
|
+
type ReadsContext<E extends HelperEffect> = [E["reads"]] extends [never] ? SchemaContext : SchemaContext<{ readonly [K in E["reads"]["key"]]: { readonly [N in Extract<E["reads"], {
|
|
1826
|
+
readonly key: K;
|
|
1827
|
+
}>["name"]]: Extract<E["reads"], {
|
|
1828
|
+
readonly key: K;
|
|
1829
|
+
readonly name: N;
|
|
1830
|
+
}>["relation"]; }; }, E["key"]>;
|
|
1831
|
+
/** State of a query of state `S` after a helper of effect `E`. */
|
|
1832
|
+
type ApplyEffect<S extends SelectQueryState, E extends HelperEffect> = ApplySelectionEffect<E["grouped"] extends true ? GroupedState<S> : S, E>;
|
|
1833
|
+
/** Applies the selected fields and row effects after the grouping guaranteed by the helper. */
|
|
1834
|
+
type ApplySelectionEffect<S extends SelectQueryState, E extends HelperEffect> = ChangeState<S, {
|
|
1835
|
+
result: E["mapped"] extends true ? E["output"] : [keyof E["fields"]] extends [never] ? S["result"] : MergeSelection<S["result"], S["aggregate"] extends Grouped ? GroupedRecord<E["fields"], SelectedFieldTypesOf<E["fieldTypes"]>> : E["fields"]>;
|
|
1836
|
+
fieldTypes: SelectedFieldTypes<S["fieldTypes"], SelectedFieldTypesOf<E["fieldTypes"]>>;
|
|
1837
|
+
value: E["mapped"] extends true ? "mapped" : S["value"];
|
|
1838
|
+
aggregate: E["mapped"] extends true ? true : S["aggregate"];
|
|
1839
|
+
rows: E["rows"] extends "many" ? EffectRows<S, E> : E["rows"] extends "one" ? OneRow<EffectRows<S, E>> : E["rows"];
|
|
1840
|
+
uses: S["uses"] | E["uses"];
|
|
1841
|
+
guaranteed: E["guaranteed"] extends true ? S["guaranteed"] : false;
|
|
1842
|
+
}>;
|
|
1843
|
+
/** Rows mode of a query of state `S` after a helper of effect `E` that keeps the rows, before `take`: relaxed as after a filter when the helper ends the guarantee. */
|
|
1844
|
+
type EffectRows<S extends SelectQueryState, E extends HelperEffect> = E["guaranteed"] extends true ? S["rows"] : FilteredStateRows<S>;
|
|
1845
|
+
/**
|
|
1846
|
+
* Helper of `defineHelper` for queries over table `T`: it applies effect `E` to the query it receives with arguments `A` and returns a query of the same kind.
|
|
1847
|
+
*
|
|
1848
|
+
* Selected fields replace earlier fields under the same keys; a query made by `get`, `pluck`, an aggregate method, or `map` does not accept a helper that selects fields or maps them.
|
|
1849
|
+
* `use` of a mutation also applies a helper that only selects fields and maps them.
|
|
1850
|
+
*/
|
|
1851
|
+
type Helper<T extends AnyTable, E extends HelperEffect, A extends unknown[]> = <S extends HelperInput<T, E>, Kind extends SelectQueryKind>(query: SelectQuery<S, Kind>, ...args: A) => E extends HelperEffect ? SelectQuery<ApplyEffect<S, E>, Kind> : never;
|
|
1852
|
+
/**
|
|
1853
|
+
* Defines a reusable helper of a table that filters, selects fields, converts them with `map`, and applies `take`, `optional`, `nullable`, and `required`, used with `use` or called with a query.
|
|
1854
|
+
*
|
|
1855
|
+
* `helper` receives the query it is applied to and any further arguments, and returns the query with its clauses.
|
|
1856
|
+
* Defined with a query of a schema, such as `schema.form`, it can select the relations of the table in that schema, and applies to queries whose schema has them.
|
|
1857
|
+
* The helper returns a query of the same kind as the one it is applied to, bound to the same `Db` if any.
|
|
1858
|
+
* A helper that only selects fields and maps them also applies to an insert, an update, and a delete with their `use`, where it selects what they return; other methods fail there.
|
|
1859
|
+
*/
|
|
1860
|
+
declare function defineHelper<T extends AnyTable, R extends SelectQuery<any, SelectQueryKind>, A extends unknown[], C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, helper: (query: SelectQuery<HelperState<T, C>, SelectQueryKind>, ...args: A) => R & CheckResult<R["types"]>): Helper<T, ReadEffect<R["types"]>, A>;
|
|
1861
|
+
/**
|
|
1862
|
+
* State in types of a query that inserts, updates, or deletes rows: its table and the relations of its schema, the rows mode of the rows it changes, and its result, which is their number until a selection returns their fields or `transform` converts it.
|
|
1633
1863
|
*
|
|
1634
1864
|
* Methods change only their own parts of the state.
|
|
1635
1865
|
*/
|
|
@@ -1638,7 +1868,7 @@ interface MutationQueryState extends QueryState {
|
|
|
1638
1868
|
readonly schema: SchemaContext;
|
|
1639
1869
|
/** Rows mode of the rows that the query changes, which `select`, `get`, and `pluck` return. */
|
|
1640
1870
|
readonly changed: ResultRows;
|
|
1641
|
-
/** Whether the query
|
|
1871
|
+
/** Whether the query resolves to something other than the number of the rows it changes: their fields or what `transform` makes of that number. */
|
|
1642
1872
|
readonly returning: boolean;
|
|
1643
1873
|
}
|
|
1644
1874
|
/** State of a query that inserts, updates, or deletes rows of table `T` with schema context `C` in rows mode `Rows` and returns their number, whose values select records of relations `U`. */
|
|
@@ -1660,10 +1890,38 @@ type RecordMutationState = MutationQueryState & ({
|
|
|
1660
1890
|
} | {
|
|
1661
1891
|
readonly value: false;
|
|
1662
1892
|
});
|
|
1663
|
-
/** State of a mutation
|
|
1664
|
-
type
|
|
1893
|
+
/** State of a mutation that `map` and `transform` do not convert, which `pluck` applies to. */
|
|
1894
|
+
type UnconvertedMutationState = MutationQueryState & {
|
|
1895
|
+
readonly value: boolean;
|
|
1896
|
+
};
|
|
1897
|
+
/** State of a mutation of one row that `map` and `transform` do not convert, which `get` applies to. */
|
|
1898
|
+
type OneRowMutationState = UnconvertedMutationState & {
|
|
1665
1899
|
readonly changed: "one" | "nullable" | "optional";
|
|
1666
1900
|
};
|
|
1901
|
+
/** State of a mutation that returns the fields of the rows it changes, which `map` applies to unless `transform` converts it; the number of the rows has no rows to convert. */
|
|
1902
|
+
type ReturningMutationState = MutationQueryState & {
|
|
1903
|
+
readonly returning: true;
|
|
1904
|
+
readonly value: boolean | "mapped";
|
|
1905
|
+
};
|
|
1906
|
+
/** Constraint of a mutation that does not accept a helper that filters or takes one row, whose methods it lacks. */
|
|
1907
|
+
interface NotMutationEffect {
|
|
1908
|
+
readonly returning: HelperError<"A helper of a mutation can only select fields and map them">;
|
|
1909
|
+
}
|
|
1910
|
+
/** Constraint of a mutation that accepts a helper of table `T` of effect `E`, whose callback reads the relations of its schema context from the mutation. */
|
|
1911
|
+
type HelperMutationInput<T extends AnyTable, E extends HelperEffect> = MutationQueryState & {
|
|
1912
|
+
readonly table: T;
|
|
1913
|
+
readonly schema: ReadsContext<E>;
|
|
1914
|
+
} & ([E["guaranteed"]] extends [true] ? [E["rows"]] extends ["many"] ? [E extends HelperEffect ? keyof E["fields"] : never, E["mapped"]] extends [never, false] ? unknown : RecordMutationState : NotMutationEffect : NotMutationEffect);
|
|
1915
|
+
/** State of a mutation of state `S` after a helper of effect `E`: the rows that `map` gives, or the records with the fields that it selects. */
|
|
1916
|
+
type HelperMutationState<S extends MutationQueryState, E extends HelperEffect> = E["mapped"] extends true ? ChangeMutationState<S, {
|
|
1917
|
+
result: E["output"];
|
|
1918
|
+
rows: S["changed"];
|
|
1919
|
+
value: "mapped";
|
|
1920
|
+
returning: true;
|
|
1921
|
+
uses: S["uses"] | E["uses"];
|
|
1922
|
+
}> : [keyof E["fields"]] extends [never] ? ChangeMutationState<S, {
|
|
1923
|
+
uses: S["uses"] | E["uses"];
|
|
1924
|
+
}> : RecordsState<S, E["fields"], E["uses"]>;
|
|
1667
1925
|
/** Record that the returned fields of a mutation of state `S` add to: the fields selected earlier, or none. */
|
|
1668
1926
|
type ReturnedRecord$1<S extends MutationQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
|
|
1669
1927
|
/** State of a mutation of state `S` that returns records with `Fields`, which its nested queries select records of relations `U` for. */
|
|
@@ -1692,7 +1950,7 @@ type OperandState<S extends MutationQueryState, E extends TypedOperand, Rows ext
|
|
|
1692
1950
|
/**
|
|
1693
1951
|
* Immutable query of state `S` that inserts, updates, or deletes rows, unbound or bound to a `Db`.
|
|
1694
1952
|
*
|
|
1695
|
-
* Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead.
|
|
1953
|
+
* Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead, and `map` and `transform` convert them in code.
|
|
1696
1954
|
* An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
|
|
1697
1955
|
* A bound query executes on its `Db` when awaited.
|
|
1698
1956
|
*/
|
|
@@ -1734,13 +1992,48 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
|
|
|
1734
1992
|
*/
|
|
1735
1993
|
get<S extends OneRowMutationState, Kind extends SelectQueryKind, E extends TypedOperand>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): MutationQuery<OperandState<S, E, OneValueRows<S["changed"]>>, Kind>;
|
|
1736
1994
|
/** Returns the value of a column of each changed row instead of the number of the rows, keeping whether the query returns an array or one value. */
|
|
1737
|
-
pluck<S extends
|
|
1995
|
+
pluck<S extends UnconvertedMutationState, Kind extends SelectQueryKind, K extends keyof S["table"]["columns"] & string>(this: MutationQuery<S, Kind>, key: K): MutationQuery<ValueState$1<S, Selectable<S["table"]>[K], ValueRows<S["changed"]>>, Kind>;
|
|
1738
1996
|
/**
|
|
1739
1997
|
* Returns the value of the expression that `callback` returns for each changed row instead of the number of the rows, keeping whether the query returns an array or one value.
|
|
1740
1998
|
*
|
|
1741
1999
|
* `callback` receives what the callback of `select` receives, and may return a query of one value, which gives `NULL` without its row.
|
|
1742
2000
|
*/
|
|
1743
|
-
pluck<S extends
|
|
2001
|
+
pluck<S extends UnconvertedMutationState, Kind extends SelectQueryKind, E extends TypedOperand>(this: MutationQuery<S, Kind>, callback: (columns: ColumnRefs<S["table"]> & RelationRefs<S["schema"]>) => E): MutationQuery<OperandState<S, E, ValueRows<S["changed"]>>, Kind>;
|
|
2002
|
+
/**
|
|
2003
|
+
* Converts each record or value that the mutation returns in code, after decoding, such as to add a field that SQL cannot compute; select the fields before it, since the number of the rows has no rows to convert, which `transform` converts instead.
|
|
2004
|
+
*
|
|
2005
|
+
* `callback` receives one record or value, also `null` of a `NULL` value, and is not called for a missing row; it returns its result synchronously.
|
|
2006
|
+
* A failure of `callback` rejects with `ResultDecodeError`, after the mutation has changed its rows.
|
|
2007
|
+
*/
|
|
2008
|
+
map<S extends ReturningMutationState, Kind extends SelectQueryKind, R>(this: MutationQuery<S, Kind>, callback: (row: S["result"]) => R & SynchronousResult<R>): MutationQuery<ChangeMutationState<S, {
|
|
2009
|
+
result: R;
|
|
2010
|
+
value: "mapped";
|
|
2011
|
+
}>, Kind>;
|
|
2012
|
+
/**
|
|
2013
|
+
* Converts the whole result of the mutation in code, after decoding, such as the number of the rows it changes into whether it changed any.
|
|
2014
|
+
*
|
|
2015
|
+
* `callback` receives what the mutation resolves to, once, and returns its result synchronously; call `select`, `get`, `pluck`, and `map` before it.
|
|
2016
|
+
* A failure of `callback` rejects with `ResultDecodeError`, after the mutation has changed its rows.
|
|
2017
|
+
*/
|
|
2018
|
+
transform<S extends MutationQueryState, Kind extends SelectQueryKind, R>(this: MutationQuery<S, Kind>, callback: (result: QueryResult<S>) => R & SynchronousResult<R>): MutationQuery<ChangeMutationState<S, {
|
|
2019
|
+
result: R;
|
|
2020
|
+
rows: "one";
|
|
2021
|
+
value: "transformed";
|
|
2022
|
+
returning: true;
|
|
2023
|
+
}>, Kind>;
|
|
2024
|
+
/**
|
|
2025
|
+
* Returns the mutation that `callback` builds from this mutation, such as one that selects the fields it returns.
|
|
2026
|
+
*
|
|
2027
|
+
* `callback` receives this mutation and `args` and returns this mutation or a mutation derived from it, which keeps the binding of this mutation.
|
|
2028
|
+
*/
|
|
2029
|
+
use<Q, Kind extends SelectQueryKind, R extends MutationQuery<any, Kind>, A extends unknown[] = []>(this: Q & MutationQuery<any, Kind>, callback: (query: Q, ...args: A) => R, ...args: A): R;
|
|
2030
|
+
/**
|
|
2031
|
+
* Applies a helper of `defineHelper` that only selects fields and maps them to what the mutation returns, as `use` of a select query does.
|
|
2032
|
+
*
|
|
2033
|
+
* Another method of a query in the helper fails: types reject those that filter or take one row, but not `groupBy`, `orderBy`, `limit`, `offset`, `distinct`, `distinctOn`, and the row locks, which they do not tell from a selection.
|
|
2034
|
+
* A selection of no fields fails as well on a mutation that returns the number of its rows.
|
|
2035
|
+
*/
|
|
2036
|
+
use<S extends HelperMutationInput<T, E>, Kind extends SelectQueryKind, T extends AnyTable, E extends HelperEffect, A extends unknown[]>(this: MutationQuery<S, Kind>, helper: Helper<T, E, A>, ...args: A): E extends HelperEffect ? MutationQuery<HelperMutationState<S, E>, Kind> : never;
|
|
1744
2037
|
/**
|
|
1745
2038
|
* Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
|
|
1746
2039
|
*
|
|
@@ -1753,151 +2046,441 @@ declare class MutationQuery<out S extends MutationQueryState, out Kind extends S
|
|
|
1753
2046
|
private derive;
|
|
1754
2047
|
/** Creates the mutation that returns the value of `arg` of `method`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value, of each changed row. */
|
|
1755
2048
|
private deriveValue;
|
|
2049
|
+
/** Rejects `method`, which changes the fields that the mutation returns, on a mutation that `map` or `transform` converts. */
|
|
2050
|
+
private rejectConverted;
|
|
2051
|
+
}
|
|
2052
|
+
/** Query of any state and kind that inserts, updates, or deletes rows. */
|
|
2053
|
+
type AnyMutationQuery = MutationQuery<any, SelectQueryKind>;
|
|
2054
|
+
/** Types of the fields of the rows of a query of SQL text by the names of the result columns they decode. */
|
|
2055
|
+
interface FieldTypes {
|
|
2056
|
+
readonly [key: string]: AnyType;
|
|
2057
|
+
readonly [key: symbol]: never;
|
|
2058
|
+
}
|
|
2059
|
+
/** Record of the values that the types of fields `F` decode. */
|
|
2060
|
+
type DecodedFields<F extends FieldTypes> = { -readonly [K in keyof F]: TypeOutput<F[K]>; };
|
|
2061
|
+
/**
|
|
2062
|
+
* 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.
|
|
2063
|
+
*
|
|
2064
|
+
* Methods change only their own parts of the state.
|
|
2065
|
+
*/
|
|
2066
|
+
interface SqlQueryState extends QueryState {
|
|
2067
|
+
/** Rows mode of the rows of the statement, which `select`, `get`, and `pluck` return. */
|
|
2068
|
+
readonly returned: ResultRows;
|
|
2069
|
+
/** Whether the query returns the fields of the rows of the statement rather than their number. */
|
|
2070
|
+
readonly returning: boolean;
|
|
2071
|
+
}
|
|
2072
|
+
/** State of a query of SQL text that returns the number of the rows of its command tag. */
|
|
2073
|
+
interface InitialSqlQueryState extends SqlQueryState {
|
|
2074
|
+
readonly result: number;
|
|
2075
|
+
readonly rows: "one";
|
|
2076
|
+
readonly value: true;
|
|
2077
|
+
readonly uses: never;
|
|
2078
|
+
readonly returned: "many";
|
|
2079
|
+
readonly returning: false;
|
|
2080
|
+
}
|
|
2081
|
+
/** State `S` of a query of SQL text with the parts of `Changes` replaced. */
|
|
2082
|
+
type ChangeSqlQueryState<S extends SqlQueryState, Changes extends Partial<SqlQueryState>> = { readonly [K in keyof SqlQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
|
|
2083
|
+
/** State of a query of SQL text that returns the number of the rows or their records, which `select` applies to. */
|
|
2084
|
+
type RecordSqlQueryState = SqlQueryState & ({
|
|
2085
|
+
readonly returning: false;
|
|
2086
|
+
} | {
|
|
2087
|
+
readonly value: false;
|
|
2088
|
+
});
|
|
2089
|
+
/** State of a query of SQL text of one row, which `optional` applies to. */
|
|
2090
|
+
type OneRowSqlQueryState = SqlQueryState & {
|
|
2091
|
+
readonly returned: "one" | "nullable" | "optional";
|
|
2092
|
+
};
|
|
2093
|
+
/** State of a query of SQL text of one row that returns its number or its record, which `nullable` applies to. */
|
|
2094
|
+
type OneRecordSqlQueryState = OneRowSqlQueryState & RecordSqlQueryState;
|
|
2095
|
+
/** Record that the fields of a query of SQL text of state `S` add to: the fields selected earlier, or none. */
|
|
2096
|
+
type ReturnedRecord<S extends SqlQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
|
|
2097
|
+
/** State of a query of SQL text of state `S` whose rows are in rows mode `Rows`. */
|
|
2098
|
+
type RowsState<S extends SqlQueryState, Rows extends ResultRows> = ChangeSqlQueryState<S, {
|
|
2099
|
+
returned: Rows;
|
|
2100
|
+
rows: S["returning"] extends true ? Rows : "one";
|
|
2101
|
+
}>;
|
|
2102
|
+
/** State of a query of SQL text of state `S` that returns value `V` of each row in rows mode `Rows`. */
|
|
2103
|
+
type ValueState<S extends SqlQueryState, V, Rows extends ResultRows> = ChangeSqlQueryState<S, {
|
|
2104
|
+
result: V;
|
|
2105
|
+
rows: Rows;
|
|
2106
|
+
returned: Rows;
|
|
2107
|
+
value: true;
|
|
2108
|
+
returning: true;
|
|
2109
|
+
}>;
|
|
2110
|
+
/**
|
|
2111
|
+
* Immutable query of a statement of SQL text, bound to the `Db` that executes it when awaited.
|
|
2112
|
+
*
|
|
2113
|
+
* 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.
|
|
2114
|
+
*/
|
|
2115
|
+
declare class SqlQuery<out S extends SqlQueryState> {
|
|
2116
|
+
readonly node: TextStatementNode;
|
|
2117
|
+
/** `Db` that executes the query when it is awaited. */
|
|
2118
|
+
readonly db: AnyDb;
|
|
2119
|
+
readonly types: S;
|
|
2120
|
+
/** Executes the query on its `Db`. */
|
|
2121
|
+
readonly then: QueryThen<S, "bound">;
|
|
2122
|
+
constructor(node: TextStatementNode,
|
|
2123
|
+
/** `Db` that executes the query when it is awaited. */
|
|
2124
|
+
db: AnyDb);
|
|
2125
|
+
/**
|
|
2126
|
+
* 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.
|
|
2127
|
+
*
|
|
2128
|
+
* A type of a column that can be `NULL` must be nullable.
|
|
2129
|
+
* The statement rejects without a column of a field, or with the column twice; other columns are ignored.
|
|
2130
|
+
*/
|
|
2131
|
+
select<S extends RecordSqlQueryState, F extends FieldTypes>(this: SqlQuery<S>, fields: F): SqlQuery<ChangeSqlQueryState<S, {
|
|
2132
|
+
result: MergeSelection<ReturnedRecord<S>, DecodedFields<F>>;
|
|
2133
|
+
rows: S["returned"];
|
|
2134
|
+
value: false;
|
|
2135
|
+
returning: true;
|
|
2136
|
+
}>>;
|
|
2137
|
+
/**
|
|
2138
|
+
* Returns the value of the only column of the row of the statement instead of the number of the rows, decoded by `type`.
|
|
2139
|
+
*
|
|
2140
|
+
* Without a row, it rejects with `NotFoundError` unless `optional` makes the query resolve to `undefined`; it rejects several rows.
|
|
2141
|
+
* A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
|
|
2142
|
+
*/
|
|
2143
|
+
get<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, OneValueRows<S["returned"]>>>;
|
|
2144
|
+
/**
|
|
2145
|
+
* 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.
|
|
2146
|
+
*
|
|
2147
|
+
* A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
|
|
2148
|
+
*/
|
|
2149
|
+
pluck<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, ValueRows<S["returned"]>>>;
|
|
2150
|
+
/**
|
|
2151
|
+
* 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.
|
|
2152
|
+
*
|
|
2153
|
+
* Before a selection, the query resolves to the number of the rows, `1`, and rejects as well.
|
|
2154
|
+
*/
|
|
2155
|
+
take<S extends SqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, OneRow<S["returned"]>>>;
|
|
2156
|
+
/**
|
|
2157
|
+
* Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without the row.
|
|
2158
|
+
*
|
|
2159
|
+
* Before a selection, the query resolves to `0` without the row.
|
|
2160
|
+
*/
|
|
2161
|
+
optional<S extends OneRowSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "optional">>;
|
|
2162
|
+
/**
|
|
2163
|
+
* Makes a query of one record, such as one of `take`, resolve to `null` without the row.
|
|
2164
|
+
*
|
|
2165
|
+
* 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.
|
|
2166
|
+
* Before a selection, the query resolves to `0` without the row.
|
|
2167
|
+
*/
|
|
2168
|
+
nullable<S extends OneRecordSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "nullable">>;
|
|
2169
|
+
/** Compiles the query into SQL text and parameters, as its `Db` executes it. */
|
|
2170
|
+
toSQL(): SqlStatement;
|
|
2171
|
+
/** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
|
|
2172
|
+
[operandNode](): never;
|
|
2173
|
+
/** Creates a query of the same `Db` with the node changes applied. */
|
|
2174
|
+
private derive;
|
|
2175
|
+
/** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
|
|
2176
|
+
private deriveValue;
|
|
2177
|
+
/** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
|
|
2178
|
+
private changeOneRow;
|
|
2179
|
+
}
|
|
2180
|
+
/** Query of SQL text of any state. */
|
|
2181
|
+
type AnySqlQuery = SqlQuery<any>;
|
|
2182
|
+
/** Kind of a select query: `unbound`, or `bound` to a `Db`. */
|
|
2183
|
+
type SelectQueryKind = "unbound" | "bound";
|
|
2184
|
+
/**
|
|
2185
|
+
* `then` of a query of kind `Kind`: a bound query executes when awaited, and an unbound query is not thenable.
|
|
2186
|
+
*
|
|
2187
|
+
* Awaiting a query of either kind or returning it from an async function is a type error, since it may execute.
|
|
2188
|
+
*/
|
|
2189
|
+
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;
|
|
2190
|
+
/** `Db` of a query of kind `Kind`, which only a bound query has. */
|
|
2191
|
+
type QueryDb<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? AnyDb : [Kind] extends ["unbound"] ? undefined : AnyDb | undefined;
|
|
2192
|
+
/** Arguments of `toSQL` of a query of kind `Kind`: a bound query compiles with the options of its `Db`. */
|
|
2193
|
+
type ToSQLArgs<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? [] : [options?: CompileOptions];
|
|
2194
|
+
/** Query of any class, state, and kind: a select query of a table, one converted by `transform`, a query of `$select`, one that inserts, updates, or deletes rows, or a query of SQL text. */
|
|
2195
|
+
type AnyQuery = AnySelectQuery | AnyTransformedQuery | AnyRecordQuery | AnyMutationQuery | AnySqlQuery;
|
|
2196
|
+
/** State of a query of `$select` in types: one record `R`, whose nested queries select records of relations `U`. */
|
|
2197
|
+
interface RecordQueryState<R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
|
|
2198
|
+
readonly result: R;
|
|
2199
|
+
readonly rows: "one";
|
|
2200
|
+
readonly value: false;
|
|
2201
|
+
readonly uses: U;
|
|
2202
|
+
}
|
|
2203
|
+
/** State of the query of `$select` of `Sel`: the record of the values of its expressions and of its literals and the results of its queries. */
|
|
2204
|
+
type SelectionState<Sel extends Selection> = RecordQueryState<MergeSelection<EmptyRecord, SelectionResult<Sel>>, SelectionUses<Sel>>;
|
|
2205
|
+
/**
|
|
2206
|
+
* Immutable query of `$select` of state `S`, unbound or bound to a `Db`: one record whose fields are the values of expressions and of literals and the results of independent queries, selected in one statement.
|
|
2207
|
+
*
|
|
2208
|
+
* An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
|
|
2209
|
+
* A bound query executes on its `Db` when awaited.
|
|
2210
|
+
*/
|
|
2211
|
+
declare class RecordQuery<out S extends RecordQueryState, out Kind extends SelectQueryKind = "unbound"> {
|
|
2212
|
+
readonly node: RecordQueryNode;
|
|
2213
|
+
readonly types: S;
|
|
2214
|
+
/** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
|
|
2215
|
+
readonly db: QueryDb<Kind>;
|
|
2216
|
+
/** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
|
|
2217
|
+
readonly then: QueryThen<S, Kind>;
|
|
2218
|
+
constructor(node: RecordQueryNode, db?: AnyDb);
|
|
2219
|
+
/**
|
|
2220
|
+
* Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
|
|
2221
|
+
*
|
|
2222
|
+
* A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
|
|
2223
|
+
*/
|
|
2224
|
+
toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
|
|
2225
|
+
/** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
|
|
2226
|
+
[operandNode](): never;
|
|
2227
|
+
}
|
|
2228
|
+
/** Query of `$select` of any state and kind. */
|
|
2229
|
+
type AnyRecordQuery = RecordQuery<any, SelectQueryKind>;
|
|
2230
|
+
declare const schemaBrand: unique symbol;
|
|
2231
|
+
/** Key of the relation definitions of a schema, which composition reads. */
|
|
2232
|
+
declare const schemaRelations: unique symbol;
|
|
2233
|
+
/** Tables by their keys; a key must not start with `$`, which is reserved for schema and `Db` members. */
|
|
2234
|
+
type Tables = Record<string, AnyTable>;
|
|
2235
|
+
/**
|
|
2236
|
+
* Immutable collection of tables and their relations with query entry points.
|
|
2237
|
+
*
|
|
2238
|
+
* A schema is not bound to a database, so queries built from it can be defined at module level.
|
|
2239
|
+
* A `Db` can execute such a query if its schema contains the tables and the selected relations of the query and every bound nested query belongs to that `Db`.
|
|
2240
|
+
*/
|
|
2241
|
+
type Schema<T extends Tables, R extends SchemaRelations = EmptyRecord> = SchemaEntries<T, R> & SchemaMembers<T, R>;
|
|
2242
|
+
/** Query entry points; each access starts a query over a new table occurrence. */
|
|
2243
|
+
type SchemaEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: SelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
|
|
2244
|
+
/** Members of a schema that composition reads: its tables and the relations of its tables. */
|
|
2245
|
+
interface SchemaContents<T extends Tables, R extends SchemaRelations> {
|
|
2246
|
+
readonly [schemaBrand]: true;
|
|
2247
|
+
/** Tables of the schema by their keys. */
|
|
2248
|
+
readonly $tables: T;
|
|
2249
|
+
/** Relation definitions by table key and relation name. */
|
|
2250
|
+
readonly [schemaRelations]: R;
|
|
2251
|
+
}
|
|
2252
|
+
interface SchemaMembers<T extends Tables, R extends SchemaRelations> extends SchemaContents<T, R> {
|
|
2253
|
+
/**
|
|
2254
|
+
* 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.
|
|
2255
|
+
*
|
|
2256
|
+
* 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.
|
|
2257
|
+
*/
|
|
2258
|
+
$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>>>;
|
|
2259
|
+
/**
|
|
2260
|
+
* Starts an unbound query of one record whose fields are the values of the expressions and of the literals and the results of the queries of `selection`, selected in one statement.
|
|
2261
|
+
*
|
|
2262
|
+
* The value of the field of a query is the result it gives when executed, such as an array of records or one value.
|
|
2263
|
+
*/
|
|
2264
|
+
$select<Sel extends Selection>(selection: Sel): RecordQuery<SelectionState<Sel>>;
|
|
2265
|
+
}
|
|
2266
|
+
/** Schema of any tables and relations. */
|
|
2267
|
+
type AnySchema = SchemaContents<Tables, SchemaRelations>;
|
|
2268
|
+
/** Part of a schema definition: an object of tables by their keys, or a schema whose tables and relations it includes. */
|
|
2269
|
+
type SchemaPart = Tables | AnySchema;
|
|
2270
|
+
/**
|
|
2271
|
+
* Tables of the parts of a schema definition by their keys.
|
|
2272
|
+
*
|
|
2273
|
+
* 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.
|
|
2274
|
+
*/
|
|
2275
|
+
type SchemaTables<P extends readonly SchemaPart[]> = ComposeParts<P>["tables"] extends (infer T extends Tables) ? { [K in keyof T]: T[K]; } : never;
|
|
2276
|
+
/** Relations of the parts of a schema definition by table key and relation name, read as `SchemaTables` reads the tables. */
|
|
2277
|
+
type SchemaPartRelations<P extends readonly SchemaPart[]> = ComposeParts<P>["relations"] extends (infer R extends SchemaRelations) ? MergeRelations<R> : never;
|
|
2278
|
+
/** Tables and relations of the parts of a schema definition, intersected. */
|
|
2279
|
+
interface PartContents {
|
|
2280
|
+
readonly tables: Tables;
|
|
2281
|
+
readonly relations: SchemaRelations;
|
|
2282
|
+
}
|
|
2283
|
+
type ComposeParts<P extends readonly SchemaPart[], Composed extends PartContents = {
|
|
2284
|
+
tables: EmptyRecord;
|
|
2285
|
+
relations: EmptyRecord;
|
|
2286
|
+
}> = 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;
|
|
2287
|
+
type ReadPart<P extends SchemaPart> = P extends SchemaContents<infer T, any> ? {
|
|
2288
|
+
tables: T;
|
|
2289
|
+
relations: P[typeof schemaRelations];
|
|
2290
|
+
} : {
|
|
2291
|
+
tables: P;
|
|
2292
|
+
relations: EmptyRecord;
|
|
2293
|
+
};
|
|
2294
|
+
/**
|
|
2295
|
+
* Defines a schema of the tables of `parts`, keyed by their names in queries.
|
|
2296
|
+
*
|
|
2297
|
+
* 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.
|
|
2298
|
+
* 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.
|
|
2299
|
+
*/
|
|
2300
|
+
declare function defineSchema<P extends SchemaPart[]>(...parts: P): Schema<SchemaTables<P>, SchemaPartRelations<P>>;
|
|
2301
|
+
declare const sourceTable: unique symbol;
|
|
2302
|
+
declare const sourceKey: unique symbol;
|
|
2303
|
+
/** Runtime mark of the declarations of `many` and `one`. */
|
|
2304
|
+
declare const declarationBrand: unique symbol;
|
|
2305
|
+
/** Kind of a relation: `many` related records, or `one` related record at most. */
|
|
2306
|
+
type RelationKind = "many" | "one";
|
|
2307
|
+
/** Relation of a table of a schema to the records of table `Target`, which has key `TargetKey` in the schema. */
|
|
2308
|
+
interface Relation<Kind extends RelationKind = RelationKind, Target extends AnyTable = AnyTable, TargetKey extends string = string, Required extends boolean = boolean> {
|
|
2309
|
+
readonly kind: Kind;
|
|
2310
|
+
readonly target: Target;
|
|
2311
|
+
readonly targetKey: TargetKey;
|
|
2312
|
+
/** 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`. */
|
|
2313
|
+
readonly required: Required;
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Relation of a table of a schema as `$relations` defines it: the columns of its keys, compared by SQL `=` in order.
|
|
2317
|
+
*
|
|
2318
|
+
* Composition includes a definition as it is, so a relation that several parts include is one definition.
|
|
2319
|
+
*/
|
|
2320
|
+
interface RelationDefinition extends Relation {
|
|
2321
|
+
readonly name: string;
|
|
2322
|
+
/** Key of the source table. */
|
|
2323
|
+
readonly key: string;
|
|
2324
|
+
readonly source: AnyTable;
|
|
2325
|
+
readonly from: readonly string[];
|
|
2326
|
+
readonly to: readonly string[];
|
|
2327
|
+
}
|
|
2328
|
+
/** Relation `N` of the table under key `K` of a schema, of type `R`, whose records a query selects. */
|
|
2329
|
+
interface UsedRelation<K extends string = string, N extends string = string, R extends Relation = Relation> {
|
|
2330
|
+
readonly key: K;
|
|
2331
|
+
readonly name: N;
|
|
2332
|
+
readonly relation: R;
|
|
2333
|
+
}
|
|
2334
|
+
/** Relations of schema relations `R` that the queries of a `Db` of the schema may select. */
|
|
2335
|
+
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];
|
|
2336
|
+
/** Relations of the tables of a schema by table key and relation name. */
|
|
2337
|
+
type SchemaRelations = {
|
|
2338
|
+
readonly [key: string]: TableRelations;
|
|
2339
|
+
};
|
|
2340
|
+
/** Relations of a table of a schema by relation name. */
|
|
2341
|
+
type TableRelations = {
|
|
2342
|
+
readonly [name: string]: Relation;
|
|
2343
|
+
};
|
|
2344
|
+
/**
|
|
2345
|
+
* 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.
|
|
2346
|
+
*
|
|
2347
|
+
* `Source` and `From` only type the keys of the source table.
|
|
2348
|
+
*/
|
|
2349
|
+
interface RelationDeclaration<Kind extends RelationKind, Source extends AnyTable, Target extends AnyTable, From = unknown, Required extends boolean = boolean> {
|
|
2350
|
+
readonly [declarationBrand]: true;
|
|
2351
|
+
readonly kind: Kind;
|
|
2352
|
+
readonly target: Target;
|
|
2353
|
+
readonly from: readonly string[];
|
|
2354
|
+
readonly to: readonly string[];
|
|
2355
|
+
readonly required: Required;
|
|
2356
|
+
readonly [sourceTable]?: (source: Source) => void;
|
|
2357
|
+
readonly [sourceKey]?: From;
|
|
2358
|
+
}
|
|
2359
|
+
/** Column key of table `T` whose type has SQL `=`, which a relation can compare. */
|
|
2360
|
+
type EqualityKey<T extends AnyTable> = { [K in keyof T["columns"]]: HasEquality<ColumnOperators<T, K>> extends true ? K : never; }[keyof T["columns"]] & string;
|
|
2361
|
+
/** Key of a relation in table `T`: a column key, or a non-empty list of them for a composite key. */
|
|
2362
|
+
type RelationKey<T extends AnyTable> = EqualityKey<T> | readonly [EqualityKey<T>, ...EqualityKey<T>[]];
|
|
2363
|
+
/** Key of table `T` with as many columns as key `From`. */
|
|
2364
|
+
type MatchingKey<T extends AnyTable, From> = From extends string ? EqualityKey<T> : { readonly [I in keyof From]: EqualityKey<T>; };
|
|
2365
|
+
/** Keys of a relation: the columns `from` of the source table equal the columns `to` of the target table, in order. */
|
|
2366
|
+
interface RelationKeys<Target extends AnyTable, From> {
|
|
2367
|
+
readonly from: From;
|
|
2368
|
+
readonly to: MatchingKey<Target, From>;
|
|
2369
|
+
}
|
|
2370
|
+
/** Keys of a relation `one`, as in `RelationKeys`, and whether the relation is required. */
|
|
2371
|
+
interface OneRelationKeys<From, To> {
|
|
2372
|
+
readonly from: From;
|
|
2373
|
+
readonly to: To;
|
|
2374
|
+
/** 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`. */
|
|
2375
|
+
readonly required?: boolean;
|
|
2376
|
+
}
|
|
2377
|
+
/** 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. */
|
|
2378
|
+
type RequiredMember<K> = { readonly [P in keyof K]: P extends "required" ? K[P] : unknown; };
|
|
2379
|
+
/** 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`. */
|
|
2380
|
+
type DeclaredRequiredOf<K> = K extends unknown ? "required" extends keyof K ? K extends {
|
|
2381
|
+
readonly required: infer Required;
|
|
2382
|
+
} ? IsTrue<Required> : IsTrue<K["required" & keyof K] | undefined> : false : never;
|
|
2383
|
+
/** `true` for `true`, and `false` for other values, such as `false` and `undefined`; a union gives the union of their results. */
|
|
2384
|
+
type IsTrue<T> = T extends true ? true : false;
|
|
2385
|
+
/** Declarations of `$relations` of a schema of tables `T`: relations by name, for tables by their keys. */
|
|
2386
|
+
type RelationDeclarations<T extends Tables> = { readonly [K in keyof T]?: {
|
|
2387
|
+
readonly [name: string]: RelationDeclaration<RelationKind, T[K], T[keyof T]>;
|
|
2388
|
+
}; };
|
|
2389
|
+
/**
|
|
2390
|
+
* Declarations `D` of `$relations` checked by the names they use: relations of the tables of `T` under their keys, and no other keys.
|
|
2391
|
+
*
|
|
2392
|
+
* 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`.
|
|
2393
|
+
* 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.
|
|
2394
|
+
*/
|
|
2395
|
+
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>]>>; }; };
|
|
2396
|
+
/** Names that a relation of table `T` cannot have: the keys of its columns, and names starting with `$`. */
|
|
2397
|
+
type ReservedName<T extends AnyTable> = `${keyof T["columns"] & (string | number)}` | `$${string}`;
|
|
2398
|
+
/** Key of tables `T` written as key `K`, such as `1` for `"1"`, as object keys are strings at runtime. */
|
|
2399
|
+
type TableKey<T extends Tables, K> = { [P in keyof T]: `${P & (string | number)}` extends `${K & (string | number)}` ? P : never; }[keyof T];
|
|
2400
|
+
/** Relations that declarations `D` of a schema of tables `T` define, by table key and relation name, as strings like the keys of objects. */
|
|
2401
|
+
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; }; };
|
|
2402
|
+
/** Column key of relation key `K`: the key itself, or a column of a composite key. */
|
|
2403
|
+
type RelationColumn<K> = K extends readonly unknown[] ? K[number] : K;
|
|
2404
|
+
/** 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. */
|
|
2405
|
+
type TargetKeyCheck<Target extends AnyTable, To> = [ContainsKey<Target, RelationColumn<To>>] extends [false] ? {
|
|
2406
|
+
readonly to: MissingKey<KeyOf<Target["keys"]>>;
|
|
2407
|
+
} : unknown;
|
|
2408
|
+
/** Type that a key `to` of a relation `one` without a key of its target is checked against, naming the keys of the target. */
|
|
2409
|
+
interface MissingKey<Keys> {
|
|
2410
|
+
readonly "columns to must include a key of the target": Keys;
|
|
1756
2411
|
}
|
|
1757
|
-
/**
|
|
1758
|
-
type
|
|
1759
|
-
/**
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
2412
|
+
/** Key of table `Target` among tables `T`, as a string like the keys of objects. */
|
|
2413
|
+
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];
|
|
2414
|
+
/** Relations of `R` by table key, with the relations under the same key merged. */
|
|
2415
|
+
type MergeRelations<R> = { [K in keyof R]: { [N in keyof R[K]]: R[K][N]; }; };
|
|
2416
|
+
/** Relations of the schema that a query starts from, by table key, and the key of the table of the query there. */
|
|
2417
|
+
interface SchemaContext<R extends SchemaRelations = SchemaRelations, K extends string = string> {
|
|
2418
|
+
readonly relations: R;
|
|
2419
|
+
readonly key: K;
|
|
1763
2420
|
}
|
|
1764
|
-
/**
|
|
1765
|
-
type
|
|
2421
|
+
/** Schema context of a query whose table has no relations, such as one of `from(table)`. */
|
|
2422
|
+
type NoRelations = SchemaContext<EmptyRecord, string>;
|
|
2423
|
+
/** 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. */
|
|
2424
|
+
type TableContext<R extends SchemaRelations, K> = K extends keyof R ? [keyof R[K]] extends [never] ? NoRelations : SchemaContext<R, K & string> : K extends number ? TableContext<R, `${K}`> : NoRelations;
|
|
1766
2425
|
/**
|
|
1767
|
-
*
|
|
2426
|
+
* Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
|
|
1768
2427
|
*
|
|
1769
|
-
*
|
|
2428
|
+
* A composite key lists its columns in arrays of the same length.
|
|
1770
2429
|
*/
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
2430
|
+
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>;
|
|
2431
|
+
/**
|
|
2432
|
+
* Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
|
|
2433
|
+
*
|
|
2434
|
+
* A composite key lists its columns in arrays of the same length.
|
|
2435
|
+
* The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
|
|
2436
|
+
* 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.
|
|
2437
|
+
* Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
|
|
2438
|
+
*/
|
|
2439
|
+
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>>>;
|
|
2440
|
+
/** Type that the result of a callback of `transform` and `map` is checked against when it may be a Promise. */
|
|
2441
|
+
interface NotSynchronous {
|
|
2442
|
+
readonly "the callback must return its result synchronously": never;
|
|
2443
|
+
}
|
|
2444
|
+
/** Check of `R`, the result of a callback of `transform` and `map`: it fails against `NotSynchronous` when `R` may be a Promise, such as a union with one, but not for `any` and `unknown`. */
|
|
2445
|
+
type SynchronousResult<R> = [Extract<R, PromiseLike<unknown>>] extends [never] ? unknown : IsAny<R> extends true ? unknown : NotSynchronous;
|
|
2446
|
+
/** State of a query of `transform` of a table in types: over table `T`, whose whole result is `R`, selecting records of relations `U`. */
|
|
2447
|
+
interface TransformedQueryState<T extends AnyTable = AnyTable, R = unknown, U extends UsedRelation = UsedRelation> extends QueryState {
|
|
2448
|
+
readonly table: T;
|
|
2449
|
+
readonly result: R;
|
|
1780
2450
|
readonly rows: "one";
|
|
1781
|
-
readonly value:
|
|
1782
|
-
readonly uses:
|
|
1783
|
-
readonly returned: "many";
|
|
1784
|
-
readonly returning: false;
|
|
2451
|
+
readonly value: "transformed";
|
|
2452
|
+
readonly uses: U;
|
|
1785
2453
|
}
|
|
1786
|
-
/** State `S` of a query of SQL text with the parts of `Changes` replaced. */
|
|
1787
|
-
type ChangeSqlQueryState<S extends SqlQueryState, Changes extends Partial<SqlQueryState>> = { readonly [K in keyof SqlQueryState]: K extends keyof Changes ? Changes[K] : S[K]; } & {};
|
|
1788
|
-
/** State of a query of SQL text that returns the number of the rows or their records, which `select` applies to. */
|
|
1789
|
-
type RecordSqlQueryState = SqlQueryState & ({
|
|
1790
|
-
readonly returning: false;
|
|
1791
|
-
} | {
|
|
1792
|
-
readonly value: false;
|
|
1793
|
-
});
|
|
1794
|
-
/** State of a query of SQL text of one row, which `optional` applies to. */
|
|
1795
|
-
type OneRowSqlQueryState = SqlQueryState & {
|
|
1796
|
-
readonly returned: "one" | "nullable" | "optional";
|
|
1797
|
-
};
|
|
1798
|
-
/** State of a query of SQL text of one row that returns its number or its record, which `nullable` applies to. */
|
|
1799
|
-
type OneRecordSqlQueryState = OneRowSqlQueryState & RecordSqlQueryState;
|
|
1800
|
-
/** Record that the fields of a query of SQL text of state `S` add to: the fields selected earlier, or none. */
|
|
1801
|
-
type ReturnedRecord<S extends SqlQueryState> = S["returning"] extends true ? S["result"] : EmptyRecord;
|
|
1802
|
-
/** State of a query of SQL text of state `S` whose rows are in rows mode `Rows`. */
|
|
1803
|
-
type RowsState<S extends SqlQueryState, Rows extends ResultRows> = ChangeSqlQueryState<S, {
|
|
1804
|
-
returned: Rows;
|
|
1805
|
-
rows: S["returning"] extends true ? Rows : "one";
|
|
1806
|
-
}>;
|
|
1807
|
-
/** State of a query of SQL text of state `S` that returns value `V` of each row in rows mode `Rows`. */
|
|
1808
|
-
type ValueState<S extends SqlQueryState, V, Rows extends ResultRows> = ChangeSqlQueryState<S, {
|
|
1809
|
-
result: V;
|
|
1810
|
-
rows: Rows;
|
|
1811
|
-
returned: Rows;
|
|
1812
|
-
value: true;
|
|
1813
|
-
returning: true;
|
|
1814
|
-
}>;
|
|
1815
2454
|
/**
|
|
1816
|
-
* Immutable query of a
|
|
2455
|
+
* Immutable query of a table of state `S` whose whole result `transform` converts after decoding, unbound or bound to a `Db`.
|
|
1817
2456
|
*
|
|
1818
|
-
*
|
|
2457
|
+
* It executes and nests in a selection as the query it comes from, with the same SQL, so it has only `transform`, which converts the result further: another method would change what the callback receives, and an expression does not take it, since SQL does not see the conversion.
|
|
2458
|
+
* An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
|
|
2459
|
+
* A bound query executes on its `Db` when awaited.
|
|
1819
2460
|
*/
|
|
1820
|
-
declare class
|
|
1821
|
-
readonly node:
|
|
1822
|
-
/** `Db` that executes the query when it is awaited. */
|
|
1823
|
-
readonly db: AnyDb;
|
|
2461
|
+
declare class TransformedQuery<out S extends TransformedQueryState, out Kind extends SelectQueryKind = "unbound"> {
|
|
2462
|
+
readonly node: QueryNode;
|
|
1824
2463
|
readonly types: S;
|
|
1825
|
-
/**
|
|
1826
|
-
readonly
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
* The statement rejects without a column of a field, or with the column twice; other columns are ignored.
|
|
1835
|
-
*/
|
|
1836
|
-
select<S extends RecordSqlQueryState, F extends FieldTypes>(this: SqlQuery<S>, fields: F): SqlQuery<ChangeSqlQueryState<S, {
|
|
1837
|
-
result: MergeSelection<ReturnedRecord<S>, DecodedFields<F>>;
|
|
1838
|
-
rows: S["returned"];
|
|
1839
|
-
value: false;
|
|
1840
|
-
returning: true;
|
|
1841
|
-
}>>;
|
|
1842
|
-
/**
|
|
1843
|
-
* Returns the value of the only column of the row of the statement instead of the number of the rows, decoded by `type`.
|
|
1844
|
-
*
|
|
1845
|
-
* Without a row, it rejects with `NotFoundError` unless `optional` makes the query resolve to `undefined`; it rejects several rows.
|
|
1846
|
-
* A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
|
|
1847
|
-
*/
|
|
1848
|
-
get<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, OneValueRows<S["returned"]>>>;
|
|
1849
|
-
/**
|
|
1850
|
-
* Returns the values of the only column of the rows of the statement instead of their number, decoded by `type`, keeping whether the query returns an array or one value.
|
|
1851
|
-
*
|
|
1852
|
-
* A `NULL` value is `null`, so a type of a column that can be `NULL` must be nullable.
|
|
1853
|
-
*/
|
|
1854
|
-
pluck<S extends SqlQueryState, T extends AnyType>(this: SqlQuery<S>, type: T): SqlQuery<ValueState<S, TypeOutput<T>, ValueRows<S["returned"]>>>;
|
|
1855
|
-
/**
|
|
1856
|
-
* Returns the row of the statement instead of an array, and rejects with `NotFoundError` without it and with several rows; it adds no limit to the statement.
|
|
1857
|
-
*
|
|
1858
|
-
* Before a selection, the query resolves to the number of the rows, `1`, and rejects as well.
|
|
1859
|
-
*/
|
|
1860
|
-
take<S extends SqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, OneRow<S["returned"]>>>;
|
|
1861
|
-
/**
|
|
1862
|
-
* Makes a query of one row, such as one of `take` or `get`, resolve to `undefined` without the row.
|
|
1863
|
-
*
|
|
1864
|
-
* Before a selection, the query resolves to `0` without the row.
|
|
1865
|
-
*/
|
|
1866
|
-
optional<S extends OneRowSqlQueryState>(this: SqlQuery<S>): SqlQuery<RowsState<S, "optional">>;
|
|
2464
|
+
/** Marks a query of `transform`, for types only, so that TypeScript rejects a query of a table as one by this member, without comparing their states. */
|
|
2465
|
+
readonly transformed: true;
|
|
2466
|
+
/** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
|
|
2467
|
+
readonly db: QueryDb<Kind>;
|
|
2468
|
+
/** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
|
|
2469
|
+
readonly then: QueryThen<S, Kind>;
|
|
2470
|
+
constructor(node: QueryNode, db?: AnyDb);
|
|
2471
|
+
/** Converts the whole result further, after the earlier conversions; see `transform` of a query of a table. */
|
|
2472
|
+
transform<S extends TransformedQueryState, Kind extends SelectQueryKind, R>(this: TransformedQuery<S, Kind>, callback: (result: QueryResult<S>) => R & SynchronousResult<R>): TransformedQuery<TransformedQueryState<S["table"], R, S["uses"]>, Kind>;
|
|
1867
2473
|
/**
|
|
1868
|
-
*
|
|
2474
|
+
* Compiles the query into SQL text and parameters; `schemaName` qualifies its tables.
|
|
1869
2475
|
*
|
|
1870
|
-
* A
|
|
1871
|
-
* Before a selection, the query resolves to `0` without the row.
|
|
2476
|
+
* A query bound to a `Db` compiles as the `Db` executes it, with the PostgreSQL schema of the `Db`, and rejects options.
|
|
1872
2477
|
*/
|
|
1873
|
-
|
|
1874
|
-
/**
|
|
1875
|
-
toSQL(): SqlStatement;
|
|
1876
|
-
/** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
|
|
2478
|
+
toSQL(...args: ToSQLArgs<Kind>): SqlStatement;
|
|
2479
|
+
/** Rejects the query as an operand of an expression, whose value SQL reads without its conversion. */
|
|
1877
2480
|
[operandNode](): never;
|
|
1878
|
-
/** Creates a query of the same `Db` with the node changes applied. */
|
|
1879
|
-
private derive;
|
|
1880
|
-
/** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
|
|
1881
|
-
private deriveValue;
|
|
1882
|
-
/** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
|
|
1883
|
-
private changeOneRow;
|
|
1884
2481
|
}
|
|
1885
|
-
/** Query of
|
|
1886
|
-
type
|
|
1887
|
-
/** Kind of a select query: `unbound`, or `bound` to a `Db`. */
|
|
1888
|
-
type SelectQueryKind = "unbound" | "bound";
|
|
1889
|
-
/**
|
|
1890
|
-
* `then` of a query of kind `Kind`: a bound query executes when awaited, and an unbound query is not thenable.
|
|
1891
|
-
*
|
|
1892
|
-
* Awaiting a query of either kind or returning it from an async function is a type error, since it may execute.
|
|
1893
|
-
*/
|
|
1894
|
-
type QueryThen<S extends QueryState, Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? <R1 = QueryResult<S>, R2 = never>(onFulfilled?: ((result: QueryResult<S>) => R1 | PromiseLike<R1>) | null, onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null) => Promise<R1 | R2> : [Kind] extends ["unbound"] ? undefined : ((onFulfilled: never) => unknown) | undefined;
|
|
1895
|
-
/** `Db` of a query of kind `Kind`, which only a bound query has. */
|
|
1896
|
-
type QueryDb<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? AnyDb : [Kind] extends ["unbound"] ? undefined : AnyDb | undefined;
|
|
1897
|
-
/** Arguments of `toSQL` of a query of kind `Kind`: a bound query compiles with the options of its `Db`. */
|
|
1898
|
-
type ToSQLArgs<Kind extends SelectQueryKind> = [Kind] extends ["bound"] ? [] : [options?: CompileOptions];
|
|
1899
|
-
/** Query of any class, state, and kind: a select query of a table, a query of `$select`, one that inserts, updates, or deletes rows, or a query of SQL text. */
|
|
1900
|
-
type AnyQuery = AnySelectQuery | AnyRecordQuery | AnyMutationQuery | AnySqlQuery;
|
|
2482
|
+
/** Query of `transform` of a table of any state and kind. */
|
|
2483
|
+
type AnyTransformedQuery = TransformedQuery<any, SelectQueryKind>;
|
|
1901
2484
|
/** Test fixture of `useTestFixture`, open while the tests of its `describe` block or test file run. */
|
|
1902
2485
|
interface TestFixture<T = unknown> {
|
|
1903
2486
|
/** Result of the seed of the fixture; reading it while the fixture is not open throws. */
|
|
@@ -2112,8 +2695,8 @@ interface BindOptions {
|
|
|
2112
2695
|
type Db<T extends Tables, R extends SchemaRelations = EmptyRecord> = DbEntries<T, R> & DbMethods<T, R>;
|
|
2113
2696
|
/** Bound query entry points; each access starts a query over a new table occurrence. */
|
|
2114
2697
|
type DbEntries<T extends Tables, R extends SchemaRelations> = { readonly [K in keyof T]: BoundSelectQuery<InitialQueryState<T[K], TableContext<R, K>>>; };
|
|
2115
|
-
/** Bound or unbound query over a table of `T`, of `$select`, or that changes the rows of a table of `T`, that selects records only of relations of `R`, or a query of SQL text. */
|
|
2116
|
-
type DbQuery<T extends Tables, R extends SchemaRelations> = QueryOf<DbQueryState<T[keyof T], UsableRelation<R>>> | RecordQuery<RecordQueryState
|
|
2698
|
+
/** Bound or unbound query over a table of `T`, also converted by `transform`, of `$select`, or that changes the rows of a table of `T`, that selects records only of relations of `R`, or a query of SQL text. */
|
|
2699
|
+
type DbQuery<T extends Tables, R extends SchemaRelations> = QueryOf<DbQueryState<T[keyof T], UsableRelation<R>>> | TransformedQuery<TransformedQueryState<T[keyof T], unknown, UsableRelation<R>>, SelectQueryKind> | RecordQuery<RecordQueryState<unknown, UsableRelation<R>>, SelectQueryKind> | MutationQuery<DbMutationState<T[keyof T], UsableRelation<R>>, SelectQueryKind> | SqlQuery<SqlQueryState>;
|
|
2117
2700
|
/** State of a query that a `Db` can execute: over table `T`, selecting records only of relations `U`. */
|
|
2118
2701
|
interface DbQueryState<T extends AnyTable, U extends UsedRelation> extends QueryStateOf<T> {
|
|
2119
2702
|
readonly uses: U;
|
|
@@ -2340,6 +2923,8 @@ interface AggregateNode {
|
|
|
2340
2923
|
readonly distinct: boolean;
|
|
2341
2924
|
readonly arguments: readonly ExpressionNode[];
|
|
2342
2925
|
readonly orderBy: readonly OrderNode[];
|
|
2926
|
+
/** Condition of the rows that the function takes, as `FILTER (WHERE ...)`, or `undefined` for every row. */
|
|
2927
|
+
readonly filter: ExpressionNode | undefined;
|
|
2343
2928
|
}
|
|
2344
2929
|
type ExpressionNode = ColumnRefNode | ParamNode | CastNode | BooleanNode | AndNode | OrNode | NotNode | ValuesNode | NestedQueryNode | ComparisonNode | InNode | InQueryNode | IsNullNode | RawSqlNode | TableNameNode | SubqueryNode | ExistsNode | TextSubqueryNode | AggregateNode;
|
|
2345
2930
|
/**
|
|
@@ -2376,6 +2961,13 @@ interface OrderNode {
|
|
|
2376
2961
|
readonly direction: "asc" | "desc";
|
|
2377
2962
|
readonly nulls: "first" | "last" | undefined;
|
|
2378
2963
|
}
|
|
2964
|
+
/** Lock of the rows that a select statement reads, in the words of PostgreSQL. */
|
|
2965
|
+
interface RowLockNode {
|
|
2966
|
+
/** Strength of the lock, which follows `FOR`. */
|
|
2967
|
+
readonly strength: "UPDATE" | "NO KEY UPDATE" | "SHARE" | "KEY SHARE";
|
|
2968
|
+
/** What the statement does with a row that another transaction has locked, instead of waiting for it. */
|
|
2969
|
+
readonly onLocked: "NOWAIT" | "SKIP LOCKED" | undefined;
|
|
2970
|
+
}
|
|
2379
2971
|
/** Select query; its result mode applies only when it is executed or its rows are packed. */
|
|
2380
2972
|
interface SelectNode<From extends SourceNode | undefined = SourceNode | undefined> extends ResultMode {
|
|
2381
2973
|
readonly kind: "select";
|
|
@@ -2385,13 +2977,25 @@ interface SelectNode<From extends SourceNode | undefined = SourceNode | undefine
|
|
|
2385
2977
|
/** Projections in the order of the result fields, with unique keys; a query without them returns records without fields. */
|
|
2386
2978
|
readonly projections: readonly ProjectionNode[];
|
|
2387
2979
|
readonly filters: QueryFilters;
|
|
2980
|
+
/** Keys of `GROUP BY`, at least one; a key that a projection has is compiled as the position of the projection, whichever part of lowering adds it. */
|
|
2981
|
+
readonly groupBy?: readonly ExpressionNode[] | undefined;
|
|
2982
|
+
/** Condition of `HAVING`; it requires `groupBy`, which the semantic query checks. */
|
|
2983
|
+
readonly having?: ExpressionNode | undefined;
|
|
2388
2984
|
readonly orderBy: readonly OrderNode[];
|
|
2389
2985
|
readonly limit: ExpressionNode | undefined;
|
|
2390
2986
|
readonly offset: ExpressionNode | undefined;
|
|
2987
|
+
/** Whether the query removes the duplicates of its rows, as `SELECT DISTINCT`; it requires a projection, as PostgreSQL does. */
|
|
2988
|
+
readonly distinct?: boolean | undefined;
|
|
2989
|
+
/** Keys of `DISTINCT ON`, at least one, whose equal values give one row, the first in the order; a key that a projection has is compiled as the position of the projection, as a key of `groupBy` is. */
|
|
2990
|
+
readonly distinctOn?: readonly ExpressionNode[] | undefined;
|
|
2991
|
+
/** Lock of the rows of the source of the statement, which does not reach the subqueries of its other clauses; it requires a source of rows, as PostgreSQL does. */
|
|
2992
|
+
readonly lock?: RowLockNode | undefined;
|
|
2391
2993
|
/** Required relation that guarantees the row of the query, such as `field.form`; see `ResultPlan`. */
|
|
2392
2994
|
readonly guaranteedBy: string | undefined;
|
|
2393
2995
|
/** Template of the records of a query with literals; see `ResultPlan`. */
|
|
2394
2996
|
readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
|
|
2997
|
+
/** How code converts the decoded result of the query; see `ResultPlan`. */
|
|
2998
|
+
readonly conversion?: ResultConversion | undefined;
|
|
2395
2999
|
}
|
|
2396
3000
|
/** Assignment of `SET` of an update: the value of the column under `key`. */
|
|
2397
3001
|
interface AssignmentNode {
|
|
@@ -2408,6 +3012,8 @@ interface MutationParts<Field> extends ResultMode {
|
|
|
2408
3012
|
readonly returning: readonly Field[] | undefined;
|
|
2409
3013
|
/** Template of the records of a mutation with literals; see `ResultPlan`. */
|
|
2410
3014
|
readonly recordTemplate?: readonly RecordTemplateField[] | undefined;
|
|
3015
|
+
/** How code converts the decoded result of the mutation; see `ResultPlan`. */
|
|
3016
|
+
readonly conversion?: ResultConversion | undefined;
|
|
2411
3017
|
}
|
|
2412
3018
|
/** Insert statement of rows of `VALUES`. */
|
|
2413
3019
|
interface InsertNode<Field = ProjectionNode> extends MutationParts<Field> {
|
|
@@ -2564,89 +3170,6 @@ type MatchResult<R, V> = boolean | (V extends unknown ? { [K in keyof V]-?: K ex
|
|
|
2564
3170
|
* Unlike such an object in `and`, `or`, and `not`, the expression refers to the columns it receives whichever query it is used in, and applies wherever an expression does, such as in `select`.
|
|
2565
3171
|
*/
|
|
2566
3172
|
declare function matches<R extends object, const V extends { readonly [K in ColumnRefKey<R>]?: unknown; }>(columns: R, values: V & MatchCheck<R, V>): Expression<MatchResult<R, V>>;
|
|
2567
|
-
/**
|
|
2568
|
-
* State of the query that the callback of a helper of table `T` with schema context `C` receives: the fields of the query the helper is applied to, and all its rows.
|
|
2569
|
-
*
|
|
2570
|
-
* It is guaranteed, so that the state that the callback returns tells whether the callback ends the guarantee of the query the helper is applied to.
|
|
2571
|
-
*/
|
|
2572
|
-
interface HelperState<T extends AnyTable, C extends SchemaContext> extends QueryStateOf<T, C> {
|
|
2573
|
-
readonly result: HelperFields<never>;
|
|
2574
|
-
readonly valueType: never;
|
|
2575
|
-
readonly rows: "many";
|
|
2576
|
-
readonly value: false;
|
|
2577
|
-
readonly uses: never;
|
|
2578
|
-
readonly guaranteed: true;
|
|
2579
|
-
readonly aggregate: false;
|
|
2580
|
-
}
|
|
2581
|
-
/**
|
|
2582
|
-
* Effect of a helper: the fields it selects, its rows mode on a query of many rows, `one` after `take` or `required` and `nullable` or `optional` after the method of the same name, the relations it selects records of, and whether it keeps the guarantee of the row of a query of a required relation.
|
|
2583
|
-
*
|
|
2584
|
-
* `reads` are the relations of the schema of the helper among them, which its callback may read from the references of the query it is applied to, and `key` is the key of its table there.
|
|
2585
|
-
*/
|
|
2586
|
-
interface HelperEffect {
|
|
2587
|
-
readonly fields: object;
|
|
2588
|
-
readonly rows: ResultRows;
|
|
2589
|
-
readonly uses: UsedRelation;
|
|
2590
|
-
readonly reads: UsedRelation;
|
|
2591
|
-
readonly key: string;
|
|
2592
|
-
readonly guaranteed: boolean;
|
|
2593
|
-
}
|
|
2594
|
-
/** Effect of a helper whose callback returns a query of state `S`, for each state of a union. */
|
|
2595
|
-
type ReadEffect<S extends SelectQueryState> = S extends SelectQueryState ? {
|
|
2596
|
-
readonly fields: { [K in keyof S["result"] as K extends keyof HelperFields ? never : K]: S["result"][K]; };
|
|
2597
|
-
readonly rows: S["rows"];
|
|
2598
|
-
readonly uses: S["uses"];
|
|
2599
|
-
readonly reads: Extract<UsableRelation<S["schema"]["relations"]>, S["uses"]>;
|
|
2600
|
-
readonly key: S["schema"]["key"];
|
|
2601
|
-
readonly guaranteed: S["guaranteed"];
|
|
2602
|
-
} : never;
|
|
2603
|
-
/** Error of a helper that a query does not accept, or whose callback returns a query it does not accept. */
|
|
2604
|
-
interface HelperError<Message extends string> {
|
|
2605
|
-
readonly error: Message;
|
|
2606
|
-
}
|
|
2607
|
-
/** `unknown` when every result state retains the input marker and returns records, or the error. */
|
|
2608
|
-
type CheckResult<S extends SelectQueryState> = [S] extends [{
|
|
2609
|
-
readonly result: HelperFields;
|
|
2610
|
-
readonly value: false;
|
|
2611
|
-
}] ? unknown : HelperError<"A helper can filter, select fields, and take one row, but cannot clear the selection or use get, pluck, or aggregates">;
|
|
2612
|
-
/** State of a query over table `T` that accepts a helper of effect `E`. */
|
|
2613
|
-
type HelperInput<T extends AnyTable, E extends HelperEffect> = QueryStateOf<T, ReadsContext<E>> & ValueCheck<E>;
|
|
2614
|
-
/** Constraint of `value` of a query that accepts a helper of effect `E`. */
|
|
2615
|
-
type ValueCheck<E extends HelperEffect> = [E extends HelperEffect ? keyof E["fields"] : never] extends [never] ? [Extract<E["rows"], "nullable">] extends [never] ? unknown : RecordRows<"A helper cannot apply nullable to a query made by get, pluck, or an aggregate"> : RecordRows<"A helper cannot select fields on a query made by get, pluck, or an aggregate">;
|
|
2616
|
-
/** Constraint of a query whose rows are records, which a query of values fails with error `Message`. */
|
|
2617
|
-
interface RecordRows<Message extends string> {
|
|
2618
|
-
readonly value: false | HelperError<Message>;
|
|
2619
|
-
}
|
|
2620
|
-
/** Schema context of a query that has the relations of its schema that a helper of effect `E` may read. */
|
|
2621
|
-
type ReadsContext<E extends HelperEffect> = [E["reads"]] extends [never] ? SchemaContext : SchemaContext<{ readonly [K in E["reads"]["key"]]: { readonly [N in Extract<E["reads"], {
|
|
2622
|
-
readonly key: K;
|
|
2623
|
-
}>["name"]]: Extract<E["reads"], {
|
|
2624
|
-
readonly key: K;
|
|
2625
|
-
readonly name: N;
|
|
2626
|
-
}>["relation"]; }; }, E["key"]>;
|
|
2627
|
-
/** State of a query of state `S` after a helper of effect `E`. */
|
|
2628
|
-
type ApplyEffect<S extends SelectQueryState, E extends HelperEffect> = ChangeState<S, {
|
|
2629
|
-
result: [keyof E["fields"]] extends [never] ? S["result"] : MergeSelection<S["result"], E["fields"]>;
|
|
2630
|
-
rows: E["rows"] extends "many" ? EffectRows<S, E> : E["rows"] extends "one" ? OneRow<EffectRows<S, E>> : E["rows"];
|
|
2631
|
-
uses: S["uses"] | E["uses"];
|
|
2632
|
-
guaranteed: E["guaranteed"] extends true ? S["guaranteed"] : false;
|
|
2633
|
-
}>;
|
|
2634
|
-
/** Rows mode of a query of state `S` after a helper of effect `E` that keeps the rows, before `take`: relaxed as after a filter when the helper ends the guarantee. */
|
|
2635
|
-
type EffectRows<S extends SelectQueryState, E extends HelperEffect> = E["guaranteed"] extends true ? S["rows"] : FilteredStateRows<S>;
|
|
2636
|
-
/**
|
|
2637
|
-
* Helper of `defineHelper` for queries over table `T`: it applies effect `E` to the query it receives with arguments `A` and returns a query of the same kind.
|
|
2638
|
-
*
|
|
2639
|
-
* Selected fields replace earlier fields under the same keys; a query made by `get`, `pluck`, or an aggregate method does not accept a helper that selects fields.
|
|
2640
|
-
*/
|
|
2641
|
-
type Helper<T extends AnyTable, E extends HelperEffect, A extends unknown[]> = <S extends HelperInput<T, E>, Kind extends SelectQueryKind>(query: SelectQuery<S, Kind>, ...args: A) => E extends HelperEffect ? SelectQuery<ApplyEffect<S, E>, Kind> : never;
|
|
2642
|
-
/**
|
|
2643
|
-
* Defines a reusable helper of a table that filters, selects fields, and applies `take`, `optional`, `nullable`, and `required`, used with `use` or called with a query.
|
|
2644
|
-
*
|
|
2645
|
-
* `helper` receives the query it is applied to and any further arguments, and returns the query with its clauses.
|
|
2646
|
-
* Defined with a query of a schema, such as `schema.form`, it can select the relations of the table in that schema, and applies to queries whose schema has them.
|
|
2647
|
-
* The helper returns a query of the same kind as the one it is applied to, bound to the same `Db` if any.
|
|
2648
|
-
*/
|
|
2649
|
-
declare function defineHelper<T extends AnyTable, R extends SelectQuery<any, SelectQueryKind>, A extends unknown[], C extends SchemaContext = NoRelations>(table: TableOrQuery<T, C>, helper: (query: SelectQuery<HelperState<T, C>, SelectQueryKind>, ...args: A) => R & CheckResult<R["types"]>): Helper<T, ReadEffect<R["types"]>, A>;
|
|
2650
3173
|
/** Tagged template building a SQL fragment of values `T` that accepts compared values `I`. */
|
|
2651
3174
|
type SqlTemplate<T, O extends OperatorDefinitions, I = T> = (strings: TemplateStringsArray, ...values: unknown[]) => Expression<T, O, I>;
|
|
2652
3175
|
/**
|
|
@@ -2683,4 +3206,10 @@ declare function identifier(...names: [string, ...string[]]): UntypedExpression;
|
|
|
2683
3206
|
*/
|
|
2684
3207
|
declare function param<Output, Input, O extends OperatorDefinitions>(type: Type<Output, Input, O, any>, value: Input): Expression<Output, O, Input>;
|
|
2685
3208
|
declare function param<E extends AnyExpression, V extends (E extends AnyExpression<infer T, infer I> ? Operand<T, I> : never)>(type: E, value: V): V extends AnyExpression ? V : V extends ScalarQuery ? AnyExpression<ScalarQueryValue<V>> : E;
|
|
2686
|
-
|
|
3209
|
+
/**
|
|
3210
|
+
* Converts a column key to snake case, such as `form_id` for `formId`, for the `columnName` option of `createTableFactory`.
|
|
3211
|
+
*
|
|
3212
|
+
* A run of capital letters is one word, such as `user_id` for `userID`, and digits stay in their word, such as `line2`.
|
|
3213
|
+
*/
|
|
3214
|
+
declare function toSnakeCase(key: string): string;
|
|
3215
|
+
export { NoRelations as $, UpdateSet as $n, AnyTableKeys as $r, least as $t, Db as A, TypeOptions as Ai, some as An, CompileOptions as Ar, DecodedFields as At, PendingTestFixture as B, MergeOperators as Bi, asc as Bn, compare as Br, HelperEffect as Bt, BaseOperators as C, createStatement as Ci, UnfilteredStringAggOptions as Cn, FilteredRows as Cr, AnyRecordQuery as Ct, UntypedExpression as D, Type as Di, every as Dn, ResultByRows as Dr, AnyQuery as Dt, TypedExpression as E, TextValue as Ei, countDistinct as En, QueryResult as Er, SelectionState as Et, DatabaseOptions as F, Column as Fi, OrderKey as Fn, equalityOperators as Fr, AnyMutationQuery as Ft, createTestHelpers as G, OperatorSignature as Gi, RelationRefs as Gn, EmptyRecord as Gr, FollowingOperand as Gt, TestHelpers as H, OperatorDefinitions as Hi, orderBy as Hn, ScalarQuery as Hr, CaseBranch as Ht, TransactionOptions as I, ColumnAttributes as Ii, OrderTerm as In, BooleanResult as Ir, InitialMutationState as It, SynchronousResult as J, ResultOf as Jn, QueryState as Jr, TypedOperandInput as Jt, AnyTransformedQuery as K, defineGenericOperator as Ki, AnySelectQuery as Kn, Grouped as Kr, NullSkippingResult as Kt, createDatabase as L, KeyKind as Li, OrderTerms as Ln, ComparisonSignature as Lr, MutationQuery as Lt, DbOf as M, TypeTransform as Mi, sum as Mn, EqualityOperators as Mr, InitialSqlQueryState as Mt, DbQueryState as N, defineType as Ni, OrderColumns as Nn, HasEquality as Nr, SqlQuery as Nt, AnyDb as O, TypeInput as Oi, max as On, ValueRows as Or, SelectQueryKind as Ot, Database as P, AnyColumn as Pi, OrderDirection as Pn, InSignature as Pr, SqlQueryState as Pt, MergeRelations as Q, InsertValues as Qn, AnyTable as Qr, greatest as Qt, TransactionCoordinator as R, ToColumn as Ri, Ordering as Rn, Operand as Rr, MutationQueryState as Rt, AnyExpression as S, TransactionFailure as Si, UnfilteredAggregateOptions as Sn, ExistsValueType as Sr, defineSchema as St, ExpressionOperators as T, BaseType as Ti, count as Tn, OneValueRows as Tr, RecordQueryState as Tt, TestHooks as U, GenericOperator as Ui, ColumnRefs as Un, TypedScalarQuery as Ur, CaseCondition as Ut, TestFixture as V, NoOperators as Vi, desc as Vn, OperandUses as Vr, defineHelper as Vt, TestTransactionOptions as W, GenericOperatorImplementation as Wi, QueryContext as Wn, ValuesQuery as Wr, CaseValue as Wt, TransformedQueryState as X, from as Xn, QueryValueType as Xr, caseWhen as Xt, TransformedQuery as Y, SelectQuery as Yn, QueryStateOf as Yr, TypedOperandOperators as Yt, DeclaredRelations as Z, ColumnValue as Zn, SelectQueryState as Zr, coalesce as Zt, TextOperators as _, ResultRows as _i, AggregateOptions as _n, ConditionOperand as _r, Schema as _t, sql as a, Selectable as ai, GroupedField as an, GroupTerm as ar, RelationKeys as at, NumberTypeOperators as b, DriverResult as bi, GroupValue as bn, not as br, SchemaTables as bt, MatchResult as c, TableKeys as ci, NestedQuery as cn, NotAKey as cr, SchemaContext as ct, defineExpression as d, createTableFactory as di, SelectionFieldTypes as dn, WhereCallback as dr, TableRelations as dt, ColumnDefinitions as ei, ColumnFieldTypes as en, UpdateValues as er, OneRelationKeys as et, FALSE as f, defineTable as fi, SelectionResult as fn, WhereCondition as fr, UsableRelation as ft, TextLengthSignature as g, ResultMode as gi, AggregateExpression as gn, Condition as gr, AnySchema as gt, TextConversionSignature as h, ResultDecodeError as hi, literal as hn, CombinedCondition as hr, one as ht, param as i, KeyColumns as ii, GroupSelectionResult as in, RowLockOptions as ir, RelationKey as it, DbMutationState as j, TypeOutput as ji, stringAgg as jn, EqualityOperator as jr, FieldTypes as jt, BindOptions as k, TypeOperators as ki, min as kn, CountValueType as kr, AnySqlQuery as kt, NotAColumn as l, TableOptions as li, SelectedFieldTypes as ln, PrimaryKeyValues as lr, SchemaRelations as lt, PatternSignature as m, RequiredRelationError as mi, Literal as mn, WhereValues as mr, many as mt, SqlTemplate as n, ColumnShape as ni, ExpressionValue as nn, GroupedState as nr, RelationDeclaration as nt, ColumnRefKey as o, Table as oi, GroupedRecord as on, GroupTerms as or, RelationKind as ot, TRUE as p, NotFoundError as pi, SelectionUses as pn, WhereFilter as pr, UsedRelation as pt, NotSynchronous as q, BoundSelectQuery as qn, InitialQueryState as qr, TypedOperand as qt, identifier as r, ColumnValues as ri, GroupOperandValue as rn, SelectedOperandType as rr, RelationDeclarations as rt, MatchCheck as s, TableFactoryOptions as si, MergeSelection as sn, KeyCheck as sr, RequiredMember as st, toSnakeCase as t, ColumnOperators as ti, ExpressionInput as tn, FilteredStateRows as tr, Relation as tt, matches as u, ToColumns as ui, Selection as un, EqValue as ur, TableContext as ut, TextTypeOperators as v, Connection as vi, CountExpression as vn, Predicate as vr, SchemaPart as vt, Expression as w, AnyType as wi, avg as wn, OneRow as wr, RecordQuery as wt, orderingOperators as x, SqlStatement as xi, StringAggOptions as xn, or as xr, Tables as xt, textOperators as y, Driver as yi, GroupAggregateExpression as yn, and as yr, SchemaPartRelations as yt, OpenedTestFixture as z, BoundOperators as zi, SelectedRefs as zn, OperandValue as zr, Helper as zt };
|