pqb 0.11.33 → 0.11.35

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/index.d.ts CHANGED
@@ -1,12 +1,161 @@
1
1
  import * as orchid_core from 'orchid-core';
2
- import { Sql, QueryBaseCommon, ColumnsShapeBase, QueryInternal, QueryMetaBase, EmptyObject, RawExpression, ColumnTypeBase, MaybeArray, QueryResultRow, AdapterBase, QueryInput, ColumnsParsers, getValueKey, StringKey, ColumnOutput, QueryThen, QueryCatch, NullableColumn, EmptyTuple, ColumnTypesBase, ColumnShapeOutput, DefaultSelectColumns, DbBase, SetOptional, MergeObjects, CoalesceString, QueryCommon, Spread, BaseNumberData, Code, ColumnWithDefault, numberTypeMethods, BaseStringData, PrimaryKeyColumn, DateTypeMethods, DateColumnData, EncodeColumn, ParseColumn, JSONTypeAny, record, ArrayMethodsData, arrayMethods, ForeignKeyTable, name, ColumnNameOfTable, ColumnDataBase, BaseOperators, ValidationContext, MessageParam } from 'orchid-core';
2
+ import { QueryResultRow, AdapterBase, QueryInput, Sql, ColumnTypesBase, ColumnShapeOutput, DefaultSelectColumns, DbBase, QueryThen, QueryCatch, QueryBaseCommon, ColumnsShapeBase, QueryInternal, QueryMetaBase, EmptyObject, RawExpression, ColumnTypeBase, MaybeArray, ColumnsParsers, getValueKey, StringKey, ColumnOutput, NullableColumn, EmptyTuple, SetOptional, MergeObjects, CoalesceString, QueryCommon, Spread, BaseNumberData, Code, ColumnWithDefault, numberTypeMethods, BaseStringData, PrimaryKeyColumn, DateTypeMethods, DateColumnData, EncodeColumn, ParseColumn, JSONTypeAny, record, ArrayMethodsData, arrayMethods, ForeignKeyTable, name, ColumnNameOfTable, ColumnDataBase, BaseOperators, ValidationContext, MessageParam } from 'orchid-core';
3
3
  import { PoolConfig, Pool, PoolClient } from 'pg';
4
4
  import { inspect } from 'util';
5
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
6
 
7
+ type TypeParsers = Record<number, (input: string) => unknown>;
8
+ type QueryResult<T extends QueryResultRow = any> = {
9
+ rowCount: number;
10
+ rows: T[];
11
+ };
12
+ type QueryArraysResult<R extends any[] = any[]> = {
13
+ rowCount: number;
14
+ rows: R[];
15
+ fields: {
16
+ name: string;
17
+ }[];
18
+ };
19
+ type AdapterConfig = Omit<PoolConfig, 'types' | 'connectionString'> & {
20
+ schema?: string;
21
+ databaseURL?: string;
22
+ };
23
+ type AdapterOptions = AdapterConfig & {
24
+ types?: TypeParsers;
25
+ };
26
+ declare class Adapter implements AdapterBase {
27
+ types: TypeParsers;
28
+ pool: Pool;
29
+ config: PoolConfig;
30
+ schema?: string;
31
+ constructor({ types, ...config }: AdapterOptions);
32
+ query<T extends QueryResultRow = any>(query: QueryInput, types?: TypeParsers): Promise<QueryResult<T>>;
33
+ arrays<R extends any[] = any[]>(query: QueryInput, types?: TypeParsers): Promise<QueryArraysResult<R>>;
34
+ transaction<Result>(begin: Sql, cb: (adapter: TransactionAdapter) => Promise<Result>): Promise<Result>;
35
+ close(): Promise<void>;
36
+ }
37
+ declare class TransactionAdapter implements Adapter {
38
+ adapter: Adapter;
39
+ client: PoolClient;
40
+ types: TypeParsers;
41
+ pool: Pool;
42
+ config: PoolConfig;
43
+ constructor(adapter: Adapter, client: PoolClient, types: TypeParsers);
44
+ query<T extends QueryResultRow = any>(query: QueryInput, types?: TypeParsers): Promise<QueryResult<T>>;
45
+ arrays<R extends any[] = any[]>(query: QueryInput, types?: TypeParsers): Promise<QueryArraysResult<R>>;
46
+ transaction<Result>(_: Sql, cb: (adapter: TransactionAdapter) => Promise<Result>): Promise<Result>;
47
+ close(): Promise<void>;
48
+ }
49
+
50
+ declare abstract class OrchidOrmError extends Error {
51
+ abstract query: Query;
52
+ }
53
+ declare class NotFoundError extends OrchidOrmError {
54
+ query: Query;
55
+ constructor(query: Query, message?: string);
56
+ }
57
+ declare class OrchidOrmInternalError extends Error {
58
+ query: Query;
59
+ constructor(query: Query, message?: string);
60
+ }
61
+ type QueryErrorName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice';
62
+ declare abstract class QueryError<T extends {
63
+ shape: ColumnsShape;
64
+ } = {
65
+ shape: ColumnsShape;
66
+ }> extends OrchidOrmInternalError {
67
+ message: string;
68
+ name: QueryErrorName;
69
+ stack: string | undefined;
70
+ code: string | undefined;
71
+ detail: string | undefined;
72
+ severity: string | undefined;
73
+ hint: string | undefined;
74
+ position: string | undefined;
75
+ internalPosition: string | undefined;
76
+ internalQuery: string | undefined;
77
+ where: string | undefined;
78
+ schema: string | undefined;
79
+ table: string | undefined;
80
+ column: string | undefined;
81
+ dataType: string | undefined;
82
+ constraint: string | undefined;
83
+ file: string | undefined;
84
+ line: string | undefined;
85
+ routine: string | undefined;
86
+ get isUnique(): boolean;
87
+ columnsCache?: {
88
+ [K in keyof T['shape']]?: true;
89
+ };
90
+ get columns(): T["shape"] extends infer T_1 ? { [K in keyof T_1]?: true | undefined; } : never;
91
+ }
92
+ declare class MoreThanOneRowError extends OrchidOrmInternalError {
93
+ constructor(query: Query, message?: string);
94
+ }
95
+ declare class UnhandledTypeError extends OrchidOrmInternalError {
96
+ query: Query;
97
+ constructor(query: Query, value: never);
98
+ }
99
+
100
+ type NoPrimaryKeyOption = 'error' | 'warning' | 'ignore';
101
+ type DbOptions<CT extends ColumnTypesBase> = ({
102
+ adapter: Adapter;
103
+ } | Omit<AdapterOptions, 'log'>) & QueryLogOptions & {
104
+ columnTypes?: CT | ((t: DefaultColumnTypes) => CT);
105
+ autoPreparedStatements?: boolean;
106
+ noPrimaryKey?: NoPrimaryKeyOption;
107
+ snakeCase?: boolean;
108
+ nowSQL?: string;
109
+ };
110
+ type DbTableOptions = {
111
+ schema?: string;
112
+ autoPreparedStatements?: boolean;
113
+ noPrimaryKey?: NoPrimaryKeyOption;
114
+ snakeCase?: boolean;
115
+ } & QueryLogOptions;
116
+ declare const anyShape: Record<string, ColumnType<unknown, orchid_core.BaseOperators, unknown>>;
117
+ interface Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations'], CT extends ColumnTypesBase = DefaultColumnTypes, Data = Pick<ColumnShapeOutput<Shape>, DefaultSelectColumns<Shape>[number]>[]> extends DbBase<Adapter, Table, Shape, CT>, QueryMethods {
118
+ new (adapter: Adapter, queryBuilder: Db<Table, Shape, Relations, CT>, table?: Table, shape?: Shape, options?: DbTableOptions): this;
119
+ queryBuilder: Db;
120
+ whereQueryBuilder: Query['whereQueryBuilder'];
121
+ onQueryBuilder: Query['onQueryBuilder'];
122
+ primaryKeys: Query['primaryKeys'];
123
+ query: QueryData;
124
+ selectable: SelectableFromShape<Shape, Table>;
125
+ returnType: Query['returnType'];
126
+ then: QueryThen<Data>;
127
+ catch: QueryCatch<Data>;
128
+ windows: Query['windows'];
129
+ defaultSelectColumns: DefaultSelectColumns<Shape>;
130
+ relations: Relations;
131
+ relationsQueries: Record<string, Query>;
132
+ withData: Query['withData'];
133
+ error: new (message: string, length: number, name: QueryErrorName) => QueryError<this>;
134
+ isSubQuery: false;
135
+ meta: {
136
+ defaults: Record<{
137
+ [K in keyof Shape]: undefined extends Shape[K]['data']['default'] ? never : K;
138
+ }[keyof Shape], true>;
139
+ };
140
+ }
141
+ declare class Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations'], CT extends ColumnTypesBase = DefaultColumnTypes> implements Query {
142
+ adapter: Adapter;
143
+ queryBuilder: Db;
144
+ table: Table;
145
+ shape: Shape;
146
+ columnTypes: CT;
147
+ constructor(adapter: Adapter, queryBuilder: Db, table: Table, shape: Shape, columnTypes: CT, transactionStorage: AsyncLocalStorage<AdapterBase>, options: DbTableOptions);
148
+ [inspect.custom](): string;
149
+ }
150
+ type DbResult<CT extends ColumnTypesBase> = Db<string, Record<string, never>, Query['relations'], ColumnTypesBase extends CT ? DefaultColumnTypes : CT> & {
151
+ <Table extends string, Shape extends ColumnsShape = ColumnsShape>(table: Table, shape?: ((t: ColumnTypesBase extends CT ? DefaultColumnTypes : CT) => Shape) | Shape, options?: DbTableOptions): Db<Table, Shape>;
152
+ adapter: Adapter;
153
+ close: Adapter['close'];
154
+ };
155
+ declare const createDb: <CT extends Record<string, orchid_core.AnyColumnTypeCreator>>({ log, logger, columnTypes: ctOrFn, snakeCase, nowSQL, ...options }: DbOptions<CT>) => DbResult<CT>;
156
+
7
157
  type ToSqlCtx = {
8
- whereQueryBuilder: typeof WhereQueryBuilder;
9
- onQueryBuilder: typeof OnQueryBuilder;
158
+ queryBuilder: Db;
10
159
  sql: string[];
11
160
  values: unknown[];
12
161
  aliasValue?: true;
@@ -265,49 +414,6 @@ type UnionKind = 'UNION' | 'UNION ALL' | 'INTERSECT' | 'INTERSECT ALL' | 'EXCEPT
265
414
  type OnConflictItem = string | string[] | RawExpression;
266
415
  type OnConflictMergeUpdate = string | string[] | Record<string, unknown> | RawExpression;
267
416
 
268
- type TypeParsers = Record<number, (input: string) => unknown>;
269
- type QueryResult<T extends QueryResultRow = any> = {
270
- rowCount: number;
271
- rows: T[];
272
- };
273
- type QueryArraysResult<R extends any[] = any[]> = {
274
- rowCount: number;
275
- rows: R[];
276
- fields: {
277
- name: string;
278
- }[];
279
- };
280
- type AdapterConfig = Omit<PoolConfig, 'types' | 'connectionString'> & {
281
- schema?: string;
282
- databaseURL?: string;
283
- };
284
- type AdapterOptions = AdapterConfig & {
285
- types?: TypeParsers;
286
- };
287
- declare class Adapter implements AdapterBase {
288
- types: TypeParsers;
289
- pool: Pool;
290
- config: PoolConfig;
291
- schema?: string;
292
- constructor({ types, ...config }: AdapterOptions);
293
- query<T extends QueryResultRow = any>(query: QueryInput, types?: TypeParsers): Promise<QueryResult<T>>;
294
- arrays<R extends any[] = any[]>(query: QueryInput, types?: TypeParsers): Promise<QueryArraysResult<R>>;
295
- transaction<Result>(begin: Sql, cb: (adapter: TransactionAdapter) => Promise<Result>): Promise<Result>;
296
- close(): Promise<void>;
297
- }
298
- declare class TransactionAdapter implements Adapter {
299
- adapter: Adapter;
300
- client: PoolClient;
301
- types: TypeParsers;
302
- pool: Pool;
303
- config: PoolConfig;
304
- constructor(adapter: Adapter, client: PoolClient, types: TypeParsers);
305
- query<T extends QueryResultRow = any>(query: QueryInput, types?: TypeParsers): Promise<QueryResult<T>>;
306
- arrays<R extends any[] = any[]>(query: QueryInput, types?: TypeParsers): Promise<QueryArraysResult<R>>;
307
- transaction<Result>(_: Sql, cb: (adapter: TransactionAdapter) => Promise<Result>): Promise<Result>;
308
- close(): Promise<void>;
309
- }
310
-
311
417
  type JoinedShapes = Record<string, ColumnsShapeBase>;
312
418
  type JoinedParsers = Record<string, ColumnsParsers>;
313
419
  type JoinOverrides = Record<string, string>;
@@ -446,14 +552,6 @@ type CopyOptions<Column = string> = {
446
552
  type QueryData = SelectQueryData | InsertQueryData | UpdateQueryData | DeleteQueryData | TruncateQueryData | ColumnInfoQueryData | CopyQueryData;
447
553
  declare const cloneQueryArrays: (q: QueryData) => void;
448
554
 
449
- declare const getClonedQueryData: (query: QueryData) => QueryData;
450
- declare const getQueryAs: (q: {
451
- table?: string;
452
- query: {
453
- as?: string;
454
- };
455
- }) => string;
456
- declare const makeRegexToFindInSql: (value: string) => RegExp;
457
555
  type AliasOrTable<T extends Pick<Query, 'table' | 'meta'>> = T['meta']['as'] extends string ? T['meta']['as'] : T['table'] extends string ? T['table'] : never;
458
556
  type Expression<T extends Query = Query, C extends ColumnTypeBase = ColumnTypeBase> = StringKey<keyof T['selectable']> | RawExpression<C>;
459
557
  type ExpressionOfType<T extends Query, C extends ColumnTypeBase, Type> = {
@@ -463,6 +561,32 @@ type NumberExpression<T extends Query, C extends ColumnTypeBase = ColumnTypeBase
463
561
  type StringExpression<T extends Query, C extends ColumnTypeBase = ColumnTypeBase> = ExpressionOfType<T, C, string>;
464
562
  type BooleanExpression<T extends Query, C extends ColumnTypeBase = ColumnTypeBase> = ExpressionOfType<T, C, boolean>;
465
563
  type ExpressionOutput<T extends Query, Expr extends Expression<T>> = Expr extends keyof T['selectable'] ? T['selectable'][Expr]['column'] : Expr extends RawExpression<infer ColumnTypeBase> ? ColumnTypeBase : never;
564
+ declare const getClonedQueryData: (query: QueryData) => QueryData;
565
+ declare const getQueryAs: (q: {
566
+ table?: string;
567
+ query: {
568
+ as?: string;
569
+ };
570
+ }) => string;
571
+ declare const makeRegexToFindInSql: (value: string) => RegExp;
572
+ /**
573
+ * In `select`, `update`, `create` it's possible to pass a callback with a sub-query.
574
+ * This function resolves such sub-query.
575
+ *
576
+ * @param q - main query object to pass to a callback as argument
577
+ * @param cb - sub-query callback
578
+ */
579
+ declare const resolveSubQueryCallback: (q: Query, cb: (q: Query) => Query) => Query;
580
+ /**
581
+ * After getting a query from a sub-query callback,
582
+ * join it to the main query in case it's a relation query.
583
+ *
584
+ * If it's not a relation query, it will be returned as is.
585
+ *
586
+ * @param q - main query object
587
+ * @param sub - sub-query query object
588
+ */
589
+ declare const joinSubQuery: (q: Query, sub: Query) => Query;
466
590
 
467
591
  declare const queryMethodByReturnType: Record<QueryReturnType, 'query' | 'arrays'>;
468
592
  type Resolve = (result: any) => any;
@@ -856,148 +980,39 @@ declare class OnQueryBuilder<S extends QueryBase = QueryBase, J extends QueryBas
856
980
  _onJsonPathEquals<T extends OnQueryBuilder>(this: T, ...args: OnJsonPathEqualsArgs<T>): T;
857
981
  }
858
982
 
859
- declare abstract class OrchidOrmError extends Error {
860
- abstract query: Query;
861
- }
862
- declare class NotFoundError extends OrchidOrmError {
863
- query: Query;
864
- constructor(query: Query, message?: string);
983
+ type WithArgsOptions = Omit<WithOptions, 'columns'> & {
984
+ columns?: boolean | string[];
985
+ };
986
+ type WithArgs = [string, ColumnsShapeBase, RawExpression] | [string, WithArgsOptions, ColumnsShapeBase, RawExpression] | [string, Query | ((qb: Db) => Query)] | [string, WithArgsOptions, Query | ((qb: Db) => Query)];
987
+ type WithShape<Args extends WithArgs> = Args[1] extends Query ? Args[1]['result'] : Args[1] extends (qb: Db) => Query ? ReturnType<Args[1]>['result'] : Args[2] extends Query ? Args[2]['result'] : Args[2] extends (qb: Db) => Query ? ReturnType<Args[2]>['result'] : Args[1] extends ColumnsShapeBase ? Args[1] : Args[2] extends ColumnsShapeBase ? Args[2] : Args[2] extends (t: ColumnTypes) => ColumnsShapeBase ? ReturnType<Args[2]> extends ColumnsShapeBase ? ReturnType<Args[2]> : never : never;
988
+ type WithResult<T extends Query, Args extends WithArgs, Shape extends ColumnsShapeBase> = AddQueryWith<T, {
989
+ table: Args[0];
990
+ shape: Shape;
991
+ type: ColumnShapeOutput<Shape>;
992
+ }>;
993
+ declare class With {
994
+ with<T extends Query, Args extends WithArgs, Shape extends ColumnsShapeBase = WithShape<Args>>(this: T, ...args: Args): WithResult<T, Args, Shape>;
995
+ _with<T extends Query, Args extends WithArgs, Shape extends ColumnsShapeBase = WithShape<Args>>(this: T, ...args: Args): WithResult<T, Args, Shape>;
865
996
  }
866
- declare class OrchidOrmInternalError extends Error {
867
- query: Query;
868
- constructor(query: Query, message?: string);
869
- }
870
- type QueryErrorName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice';
871
- declare abstract class QueryError<T extends {
872
- shape: ColumnsShape;
873
- } = {
874
- shape: ColumnsShape;
875
- }> extends OrchidOrmInternalError {
876
- message: string;
877
- name: QueryErrorName;
878
- stack: string | undefined;
879
- code: string | undefined;
880
- detail: string | undefined;
881
- severity: string | undefined;
882
- hint: string | undefined;
883
- position: string | undefined;
884
- internalPosition: string | undefined;
885
- internalQuery: string | undefined;
886
- where: string | undefined;
887
- schema: string | undefined;
888
- table: string | undefined;
889
- column: string | undefined;
890
- dataType: string | undefined;
891
- constraint: string | undefined;
892
- file: string | undefined;
893
- line: string | undefined;
894
- routine: string | undefined;
895
- get isUnique(): boolean;
896
- columnsCache?: {
897
- [K in keyof T['shape']]?: true;
898
- };
899
- get columns(): T["shape"] extends infer T_1 ? { [K in keyof T_1]?: true | undefined; } : never;
900
- }
901
- declare class MoreThanOneRowError extends OrchidOrmInternalError {
902
- constructor(query: Query, message?: string);
903
- }
904
- declare class UnhandledTypeError extends OrchidOrmInternalError {
905
- query: Query;
906
- constructor(query: Query, value: never);
907
- }
908
-
909
- type NoPrimaryKeyOption = 'error' | 'warning' | 'ignore';
910
- type DbOptions<CT extends ColumnTypesBase> = ({
911
- adapter: Adapter;
912
- } | Omit<AdapterOptions, 'log'>) & QueryLogOptions & {
913
- columnTypes?: CT | ((t: DefaultColumnTypes) => CT);
914
- autoPreparedStatements?: boolean;
915
- noPrimaryKey?: NoPrimaryKeyOption;
916
- snakeCase?: boolean;
917
- nowSQL?: string;
918
- };
919
- type DbTableOptions = {
920
- schema?: string;
921
- autoPreparedStatements?: boolean;
922
- noPrimaryKey?: NoPrimaryKeyOption;
923
- snakeCase?: boolean;
924
- } & QueryLogOptions;
925
- declare const anyShape: Record<string, ColumnType<unknown, orchid_core.BaseOperators, unknown>>;
926
- interface Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations'], CT extends ColumnTypesBase = DefaultColumnTypes, Data = Pick<ColumnShapeOutput<Shape>, DefaultSelectColumns<Shape>[number]>[]> extends DbBase<Adapter, Table, Shape, CT>, QueryMethods {
927
- new (adapter: Adapter, queryBuilder: Db<Table, Shape, Relations, CT>, table?: Table, shape?: Shape, options?: DbTableOptions): this;
928
- queryBuilder: Db;
929
- whereQueryBuilder: Query['whereQueryBuilder'];
930
- onQueryBuilder: Query['onQueryBuilder'];
931
- primaryKeys: Query['primaryKeys'];
932
- query: QueryData;
933
- selectable: SelectableFromShape<Shape, Table>;
934
- returnType: Query['returnType'];
935
- then: QueryThen<Data>;
936
- catch: QueryCatch<Data>;
937
- windows: Query['windows'];
938
- defaultSelectColumns: DefaultSelectColumns<Shape>;
939
- relations: Relations;
940
- relationsQueries: Record<string, Query>;
941
- withData: Query['withData'];
942
- error: new (message: string, length: number, name: QueryErrorName) => QueryError<this>;
943
- isSubQuery: false;
944
- meta: {
945
- defaults: Record<{
946
- [K in keyof Shape]: undefined extends Shape[K]['data']['default'] ? never : K;
947
- }[keyof Shape], true>;
948
- };
949
- }
950
- declare class Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations'], CT extends ColumnTypesBase = DefaultColumnTypes> implements Query {
951
- adapter: Adapter;
952
- queryBuilder: Db;
953
- table: Table;
954
- shape: Shape;
955
- columnTypes: CT;
956
- whereQueryBuilder: typeof WhereQueryBuilder;
957
- onQueryBuilder: typeof OnQueryBuilder;
958
- constructor(adapter: Adapter, queryBuilder: Db, table: Table, shape: Shape, columnTypes: CT, transactionStorage: AsyncLocalStorage<AdapterBase>, options: DbTableOptions);
959
- [inspect.custom](): string;
960
- }
961
- type DbResult<CT extends ColumnTypesBase> = Db<string, Record<string, never>, Query['relations'], ColumnTypesBase extends CT ? DefaultColumnTypes : CT> & {
962
- <Table extends string, Shape extends ColumnsShape = ColumnsShape>(table: Table, shape?: ((t: ColumnTypesBase extends CT ? DefaultColumnTypes : CT) => Shape) | Shape, options?: DbTableOptions): Db<Table, Shape>;
963
- adapter: Adapter;
964
- close: Adapter['close'];
965
- };
966
- declare const createDb: <CT extends Record<string, orchid_core.AnyColumnTypeCreator>>({ log, logger, columnTypes: ctOrFn, snakeCase, nowSQL, ...options }: DbOptions<CT>) => DbResult<CT>;
967
-
968
- type WithArgsOptions = Omit<WithOptions, 'columns'> & {
969
- columns?: boolean | string[];
970
- };
971
- type WithArgs = [string, ColumnsShapeBase, RawExpression] | [string, WithArgsOptions, ColumnsShapeBase, RawExpression] | [string, Query | ((qb: Db) => Query)] | [string, WithArgsOptions, Query | ((qb: Db) => Query)];
972
- type WithShape<Args extends WithArgs> = Args[1] extends Query ? Args[1]['result'] : Args[1] extends (qb: Db) => Query ? ReturnType<Args[1]>['result'] : Args[2] extends Query ? Args[2]['result'] : Args[2] extends (qb: Db) => Query ? ReturnType<Args[2]>['result'] : Args[1] extends ColumnsShapeBase ? Args[1] : Args[2] extends ColumnsShapeBase ? Args[2] : Args[2] extends (t: ColumnTypes) => ColumnsShapeBase ? ReturnType<Args[2]> extends ColumnsShapeBase ? ReturnType<Args[2]> : never : never;
973
- type WithResult<T extends Query, Args extends WithArgs, Shape extends ColumnsShapeBase> = AddQueryWith<T, {
974
- table: Args[0];
975
- shape: Shape;
976
- type: ColumnShapeOutput<Shape>;
977
- }>;
978
- declare class With {
979
- with<T extends Query, Args extends WithArgs, Shape extends ColumnsShapeBase = WithShape<Args>>(this: T, ...args: Args): WithResult<T, Args, Shape>;
980
- _with<T extends Query, Args extends WithArgs, Shape extends ColumnsShapeBase = WithShape<Args>>(this: T, ...args: Args): WithResult<T, Args, Shape>;
981
- }
982
-
983
- type UnionArg<T extends Query> = (Omit<Query, 'result'> & {
984
- result: {
985
- [K in keyof T['result']]: Pick<T['result'][K], 'dataType'>;
986
- };
987
- }) | RawExpression;
988
- declare class Union {
989
- union<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
990
- _union<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
991
- unionAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
992
- _unionAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
993
- intersect<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
994
- _intersect<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
995
- intersectAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
996
- _intersectAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
997
- except<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
998
- _except<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
999
- exceptAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1000
- _exceptAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
997
+
998
+ type UnionArg<T extends Query> = (Omit<Query, 'result'> & {
999
+ result: {
1000
+ [K in keyof T['result']]: Pick<T['result'][K], 'dataType'>;
1001
+ };
1002
+ }) | RawExpression;
1003
+ declare class Union {
1004
+ union<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1005
+ _union<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1006
+ unionAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1007
+ _unionAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1008
+ intersect<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1009
+ _intersect<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1010
+ intersectAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1011
+ _intersectAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1012
+ except<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1013
+ _except<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1014
+ exceptAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1015
+ _exceptAll<T extends Query>(this: T, args: UnionArg<T>[], wrap?: boolean): T;
1001
1016
  }
1002
1017
 
1003
1018
  type JsonColumnName<T extends Pick<Query, 'selectable'>> = StringKey<{
@@ -1009,8 +1024,8 @@ type JsonPathQueryResult<T extends Query, As extends string, Type extends Column
1009
1024
  [K in As]: Type;
1010
1025
  }>;
1011
1026
  declare class Json {
1012
- json<T extends Query>(this: T, coalesce?: boolean): SetQueryReturnsValueOptional<T, StringColumn>;
1013
- _json<T extends Query>(this: T, coalesce?: boolean): SetQueryReturnsValueOptional<T, StringColumn>;
1027
+ json<T extends Query>(this: T, coalesce?: boolean): SetQueryReturnsColumnOptional<T, StringColumn>;
1028
+ _json<T extends Query>(this: T, coalesce?: boolean): SetQueryReturnsColumnOptional<T, StringColumn>;
1014
1029
  jsonSet<T extends Query, Column extends ColumnOrJsonMethod<T>, As extends string = Column extends JsonItem ? Column['__json'][1] : Column>(this: T, column: Column, path: Array<string | number>, value: unknown, options?: {
1015
1030
  as?: As;
1016
1031
  createIfMissing?: boolean;
@@ -1058,7 +1073,12 @@ declare class Json {
1058
1073
  }): JsonPathQueryResult<T, As, Type>;
1059
1074
  }
1060
1075
 
1061
- type CreateData<T extends Query, Data = SetOptional<T['inputType'], keyof T['meta']['defaults']>> = [keyof T['relations']] extends [never] ? Data : OmitBelongsToForeignKeys<T['relations'], Data> & CreateRelationData<T>;
1076
+ type CreateData<T extends Query, Data = SetOptional<{
1077
+ [K in keyof T['inputType']]: CreateColumn<T, K>;
1078
+ }, keyof T['meta']['defaults']>> = [keyof T['relations']] extends [never] ? Data : OmitBelongsToForeignKeys<T['relations'], Data> & CreateRelationData<T>;
1079
+ type CreateColumn<T extends Query, Key extends keyof T['inputType']> = T['inputType'][Key] | {
1080
+ [K in keyof Query]: K extends 'then' ? QueryThen<T['inputType'][Key]> : Query[K];
1081
+ };
1062
1082
  type OmitBelongsToForeignKeys<R extends RelationsBase, Data> = Omit<Data, {
1063
1083
  [K in keyof R]: R[K] extends BelongsToRelation ? R[K]['options']['foreignKey'] : never;
1064
1084
  }[keyof R]>;
@@ -1150,22 +1170,171 @@ type CreateCtx = {
1150
1170
  };
1151
1171
  type CreateMethodsNames = 'create' | '_create' | 'createMany' | '_createMany' | 'createRaw' | '_createRaw' | 'createFrom' | '_createFrom';
1152
1172
  declare class Create {
1173
+ /**
1174
+ * `create` will create one record.
1175
+ *
1176
+ * Each column may accept a specific value, a raw SQL, or a query that returns a single value.
1177
+ *
1178
+ * ```ts
1179
+ * const oneRecord = await db.table.create({
1180
+ * name: 'John',
1181
+ * password: '1234',
1182
+ * });
1183
+ *
1184
+ * await db.table.create({
1185
+ * // raw SQL
1186
+ * column1: db.table.sql`'John' | 'Doe'`,
1187
+ *
1188
+ * // query that returns a single value
1189
+ * // returning multiple values will result in Postgres error
1190
+ * column2: db.otherTable.get('someColumn'),
1191
+ * });
1192
+ * ```
1193
+ *
1194
+ * @param data - data for the record, may have values, raw SQL, queries, relation operations
1195
+ */
1153
1196
  create<T extends Query>(this: T, data: CreateData<T>): CreateResult<T>;
1154
1197
  _create<T extends Query>(this: T, data: CreateData<T>): CreateResult<T>;
1198
+ /**
1199
+ * `createMany` will create a batch of records.
1200
+ *
1201
+ * Each column may be set with a specific value, a raw SQL, or a query, the same as in [create](#create).
1202
+ *
1203
+ * In case one of the objects has fewer fields, the `DEFAULT` SQL keyword will be placed in its place in the `VALUES` statement.
1204
+ *
1205
+ * ```ts
1206
+ * const manyRecords = await db.table.createMany([
1207
+ * { key: 'value', otherKey: 'other value' },
1208
+ * { key: 'value' }, // default will be used for `otherKey`
1209
+ * ]);
1210
+ * ```
1211
+ *
1212
+ * @param data - data for the record, may have values, raw SQL, queries, relation operations
1213
+ */
1155
1214
  createMany<T extends Query>(this: T, data: CreateData<T>[]): CreateManyResult<T>;
1156
1215
  _createMany<T extends Query>(this: T, data: CreateData<T>[]): CreateManyResult<T>;
1216
+ /**
1217
+ * `createRaw` is for creating one record with a raw expression.
1218
+ *
1219
+ * Provided SQL will be wrapped into parens for a single `VALUES` record.
1220
+ *
1221
+ * If the table has a column with runtime defaults (defined with callbacks), the value will be appended to your SQL.
1222
+ *
1223
+ * `columns` are type-checked to contain all required columns.
1224
+ *
1225
+ * ```ts
1226
+ * const oneRecord = await db.table.createRaw({
1227
+ * columns: ['name', 'amount'],
1228
+ * values: db.table.sql`'name', random()`,
1229
+ * });
1230
+ * ```
1231
+ *
1232
+ * @param args - object with columns list and raw SQL for values
1233
+ */
1157
1234
  createRaw<T extends Query, Arg extends CreateRawData<T>>(this: T, ...args: CreateRawArgs<T, Arg>): CreateResult<T>;
1158
1235
  _createRaw<T extends Query, Arg extends CreateRawData<T>>(this: T, ...args: CreateRawArgs<T, Arg>): CreateResult<T>;
1236
+ /**
1237
+ * `createRaw` is for creating many record with raw expressions.
1238
+ *
1239
+ * Takes array of SQL expressions, each of them will be wrapped into parens for `VALUES` records.
1240
+ *
1241
+ * If the table has a column with runtime defaults (defined with callbacks), function will be called for each SQL and the value will be appended.
1242
+ *
1243
+ * `columns` are type-checked to contain all required columns.
1244
+ *
1245
+ * ```ts
1246
+ * const manyRecords = await db.table.createManyRaw({
1247
+ * columns: ['name', 'amount'],
1248
+ * values: [db.table.sql`'one', 2`, db.table.sql`'three', 4`],
1249
+ * });
1250
+ * ```
1251
+ *
1252
+ * @param args - object with columns list and array of raw SQL for values
1253
+ */
1159
1254
  createManyRaw<T extends Query, Arg extends CreateManyRawData<T>>(this: T, ...args: CreateRawArgs<T, Arg>): CreateManyResult<T>;
1160
1255
  _createManyRaw<T extends Query, Arg extends CreateManyRawData<T>>(this: T, ...args: CreateRawArgs<T, Arg>): CreateManyResult<T>;
1256
+ /**
1257
+ * This method is for creating a single record, for batch creating see `createManyFrom`.
1258
+ *
1259
+ * `createFrom` is to perform the `INSERT ... SELECT ...` SQL statement, it does select and insert in a single query.
1260
+ *
1261
+ * The first argument is a query for a **single** record, it should have `find`, `take`, or similar.
1262
+ *
1263
+ * The second optional argument is a data which will be merged with columns returned from the select query.
1264
+ *
1265
+ * The data for the second argument is the same as in [create](#create) and [createMany](#createMany).
1266
+ *
1267
+ * Columns with runtime defaults (defined with a callback) are supported here.
1268
+ * The value for such a column will be injected unless selected from a related table or provided in a data object.
1269
+ *
1270
+ * ```ts
1271
+ * const oneRecord = await db.table.createFrom(
1272
+ * // In the select, key is a related table column, value is a column to insert as
1273
+ * RelatedTable.select({ relatedId: 'id' }).findBy({ key: 'value' }),
1274
+ * // optional argument:
1275
+ * {
1276
+ * key: 'value',
1277
+ * },
1278
+ * );
1279
+ * ```
1280
+ *
1281
+ * The query above will produce such SQL:
1282
+ *
1283
+ * ```sql
1284
+ * INSERT INTO "table"("relatedId", "key")
1285
+ * SELECT "relatedTable"."id" AS "relatedId", 'value'
1286
+ * FROM "relatedTable"
1287
+ * WHERE "relatedTable"."key" = 'value'
1288
+ * LIMIT 1
1289
+ * RETURNING *
1290
+ * ```
1291
+ *
1292
+ * @param query - query to create new records from
1293
+ * @param data - additionally you can set some columns
1294
+ */
1161
1295
  createFrom<T extends Query, Q extends Query & {
1162
1296
  returnType: 'one' | 'oneOrThrow';
1163
1297
  }>(this: T, query: Q, data?: Omit<CreateData<T>, keyof Q['result']>): CreateResult<T>;
1164
1298
  _createFrom<T extends Query, Q extends Query & {
1165
1299
  returnType: 'one' | 'oneOrThrow';
1166
1300
  }>(this: T, query: Q, data?: Omit<CreateData<T>, keyof Q['result']>): CreateResult<T>;
1301
+ /**
1302
+ * Similar to `createFrom`, but intended to create many records.
1303
+ *
1304
+ * Unlike `createFrom`, it doesn't accept second argument with data, and runtime defaults cannot work with it.
1305
+ *
1306
+ * ```ts
1307
+ * const manyRecords = await db.table.createManyFrom(
1308
+ * RelatedTable.select({ relatedId: 'id' }).where({ key: 'value' }),
1309
+ * );
1310
+ * ```
1311
+ *
1312
+ * @param query - query to create new records from
1313
+ */
1167
1314
  createManyFrom<T extends Query, Q extends Query>(this: T, query: Q): CreateManyResult<T>;
1168
1315
  _createManyFrom<T extends Query, Q extends Query>(this: T, query: Q): CreateManyResult<T>;
1316
+ /**
1317
+ * `.defaults` allows setting values that will be used later in `.create`.
1318
+ *
1319
+ * Columns provided in `.defaults` are marked as optional in the following `.create`.
1320
+ *
1321
+ * Default data is the same as in [create](#create) and [createMany](#createMany),
1322
+ * so you can provide a raw SQL, or a query with a query.
1323
+ *
1324
+ * ```ts
1325
+ * // Will use firstName from defaults and lastName from create argument:
1326
+ * db.table
1327
+ * .defaults({
1328
+ * firstName: 'first name',
1329
+ * lastName: 'last name',
1330
+ * })
1331
+ * .create({
1332
+ * lastName: 'override the last name',
1333
+ * });
1334
+ * ```
1335
+ *
1336
+ * @param data - default values for `create` and `createMany` which will follow `defaults`
1337
+ */
1169
1338
  defaults<T extends Query, Data extends Partial<CreateData<T>>>(this: T, data: Data): T & {
1170
1339
  meta: {
1171
1340
  defaults: Record<keyof Data, true>;
@@ -1176,6 +1345,54 @@ declare class Create {
1176
1345
  defaults: Record<keyof Data, true>;
1177
1346
  };
1178
1347
  };
1348
+ /**
1349
+ * A modifier for creating queries that specify alternative behavior in the case of a conflict.
1350
+ * A conflict occurs when a table has a `PRIMARY KEY` or a `UNIQUE` index on a column
1351
+ * (or a composite index on a set of columns) and a row being created has the same value as a row
1352
+ * that already exists in the table in this column(s).
1353
+ * The default behavior in case of conflict is to raise an error and abort the query.
1354
+ * Using this method you can change this behavior to either silently ignore the error by using .onConflict().ignore()
1355
+ * or to update the existing row with new data (perform an "UPSERT") by using .onConflict().merge().
1356
+ *
1357
+ * ```ts
1358
+ * // leave without argument to ignore or merge on any conflict
1359
+ * Target.create(data).onConflict().ignore();
1360
+ *
1361
+ * // single column:
1362
+ * db.table.create(data).onConfict('email');
1363
+ *
1364
+ * // array of columns:
1365
+ * db.table.create(data).onConfict(['email', 'name']);
1366
+ *
1367
+ * // raw expression:
1368
+ * db.table.create(data).onConfict(db.table.sql`(email) where condition`);
1369
+ * ```
1370
+ *
1371
+ * ::: info
1372
+ * The column(s) specified by this method must either be the table's PRIMARY KEY or have a UNIQUE index on them, or the query will fail to execute.
1373
+ * When specifying multiple columns, they must be a composite PRIMARY KEY or have a composite UNIQUE index.
1374
+ *
1375
+ * You can use the db.table.sql function in onConflict.
1376
+ * It can be useful to specify a condition when you have a partial index:
1377
+ *
1378
+ * ```ts
1379
+ * db.table
1380
+ * .create({
1381
+ * email: 'ignore@example.com',
1382
+ * name: 'John Doe',
1383
+ * active: true,
1384
+ * })
1385
+ * // ignore only on email conflict and active is true.
1386
+ * .onConflict(db.table.sql`(email) where active`)
1387
+ * .ignore();
1388
+ * ```
1389
+ *
1390
+ * :::
1391
+ *
1392
+ * See the documentation on the .ignore() and .merge() methods for more details.
1393
+ *
1394
+ * @param arg - optionally provide an array of columns
1395
+ */
1179
1396
  onConflict<T extends Query, Arg extends OnConflictArg<T>>(this: T, arg?: Arg): OnConflictQueryBuilder<T, Arg>;
1180
1397
  _onConflict<T extends Query, Arg extends OnConflictArg<T> | undefined = undefined>(this: T, arg?: Arg): OnConflictQueryBuilder<T, Arg>;
1181
1398
  }
@@ -1183,17 +1400,143 @@ declare class OnConflictQueryBuilder<T extends Query, Arg extends OnConflictArg<
1183
1400
  private query;
1184
1401
  private onConflict;
1185
1402
  constructor(query: T, onConflict: Arg);
1403
+ /**
1404
+ * Available only after `.onConflict`.
1405
+ *
1406
+ * Modifies a create query, and causes it to be silently dropped without an error if a conflict occurs.
1407
+ *
1408
+ * Adds the `ON CONFLICT (columns) DO NOTHING` clause to the insert statement.
1409
+ *
1410
+ * It produces `ON CONFLICT DO NOTHING` when no `onConflict` argument provided.
1411
+ *
1412
+ * ```ts
1413
+ * db.table
1414
+ * .create({
1415
+ * email: 'ignore@example.com',
1416
+ * name: 'John Doe',
1417
+ * })
1418
+ * .onConflict('email')
1419
+ * .ignore();
1420
+ * ```
1421
+ */
1186
1422
  ignore(): T;
1423
+ /**
1424
+ * Available only after `.onConflict`.
1425
+ *
1426
+ * Modifies a create query, to turn it into an 'upsert' operation.
1427
+ *
1428
+ * Adds an `ON CONFLICT (columns) DO UPDATE` clause to the insert statement.
1429
+ *
1430
+ * When no `onConflict` argument provided,
1431
+ * it will automatically collect all table columns that have unique index and use them as a conflict target.
1432
+ *
1433
+ * ```ts
1434
+ * db.table
1435
+ * .create({
1436
+ * email: 'ignore@example.com',
1437
+ * name: 'John Doe',
1438
+ * })
1439
+ * .onConflict('email')
1440
+ * .merge();
1441
+ * ```
1442
+ *
1443
+ * This also works with batch creates:
1444
+ *
1445
+ * ```ts
1446
+ * db.table
1447
+ * .createMany([
1448
+ * { email: 'john@example.com', name: 'John Doe' },
1449
+ * { email: 'jane@example.com', name: 'Jane Doe' },
1450
+ * { email: 'alex@example.com', name: 'Alex Doe' },
1451
+ * ])
1452
+ * .onConflict('email')
1453
+ * .merge();
1454
+ * ```
1455
+ *
1456
+ * It is also possible to specify a subset of the columns to merge when a conflict occurs.
1457
+ * For example, you may want to set a `createdAt` column when creating but would prefer not to update it if the row already exists:
1458
+ *
1459
+ * ```ts
1460
+ * const timestamp = Date.now();
1461
+ *
1462
+ * db.table
1463
+ * .create({
1464
+ * email: 'ignore@example.com',
1465
+ * name: 'John Doe',
1466
+ * createdAt: timestamp,
1467
+ * updatedAt: timestamp,
1468
+ * })
1469
+ * .onConflict('email')
1470
+ * // string argument for a single column:
1471
+ * .merge('email')
1472
+ * // array of strings for multiple columns:
1473
+ * .merge(['email', 'name', 'updatedAt']);
1474
+ * ```
1475
+ *
1476
+ * It is also possible to specify data to update separately from the data to create.
1477
+ * This is useful if you want to make an update with different data than in creating.
1478
+ * For example, you may want to change a value if the row already exists:
1479
+ *
1480
+ * ```ts
1481
+ * const timestamp = Date.now();
1482
+ *
1483
+ * db.table
1484
+ * .create({
1485
+ * email: 'ignore@example.com',
1486
+ * name: 'John Doe',
1487
+ * createdAt: timestamp,
1488
+ * updatedAt: timestamp,
1489
+ * })
1490
+ * .onConflict('email')
1491
+ * .merge({
1492
+ * name: 'John Doe The Second',
1493
+ * });
1494
+ * ```
1495
+ *
1496
+ * It is also possible to add a WHERE clause to conditionally update only the matching rows:
1497
+ *
1498
+ * ```ts
1499
+ * const timestamp = Date.now();
1500
+ *
1501
+ * db.table
1502
+ * .create({
1503
+ * email: 'ignore@example.com',
1504
+ * name: 'John Doe',
1505
+ * createdAt: timestamp,
1506
+ * updatedAt: timestamp,
1507
+ * })
1508
+ * .onConflict('email')
1509
+ * .merge({
1510
+ * name: 'John Doe',
1511
+ * updatedAt: timestamp,
1512
+ * })
1513
+ * .where({ updatedAt: { lt: timestamp } });
1514
+ * ```
1515
+ *
1516
+ * `.merge` also accepts raw expression:
1517
+ *
1518
+ * ```ts
1519
+ * db.table
1520
+ * .create(data)
1521
+ * .onConflict()
1522
+ * .merge(db.table.sql`raw SQL expression`);
1523
+ * ```
1524
+ *
1525
+ * @param update - column, or array of columns, or object for new column values, or raw SQL
1526
+ */
1187
1527
  merge(update?: keyof T['shape'] | (keyof T['shape'])[] | Partial<T['inputType']> | RawExpression): T;
1188
1528
  }
1189
1529
 
1190
1530
  type UpdateData<T extends Query> = {
1191
- [K in keyof T['inputType']]?: T['inputType'][K] | RawExpression;
1531
+ [K in keyof T['inputType']]?: UpdateColumn<T, K>;
1192
1532
  } & (T['relations'] extends Record<string, Relation> ? {
1193
1533
  [K in keyof T['relations']]?: T['relations'][K] extends BelongsToRelation ? UpdateBelongsToData<T, T['relations'][K]> : T['relations'][K] extends HasOneRelation ? UpdateHasOneData<T, T['relations'][K]> : T['relations'][K] extends HasManyRelation ? UpdateHasManyData<T, T['relations'][K]> : T['relations'][K] extends HasAndBelongsToManyRelation ? UpdateHasAndBelongsToManyData<T['relations'][K]> : never;
1194
1534
  } : EmptyObject) & {
1195
1535
  __raw?: never;
1196
1536
  };
1537
+ type UpdateColumn<T extends Query, Key extends keyof T['inputType'], SubQuery = {
1538
+ [K in keyof Query]: K extends 'then' ? QueryThen<T['inputType'][Key]> : Query[K];
1539
+ }> = T['inputType'][Key] | RawExpression | SubQuery | ((q: T) => SubQuery);
1197
1540
  type UpdateBelongsToData<T extends Query, Rel extends BelongsToRelation> = {
1198
1541
  disconnect: boolean;
1199
1542
  } | {
@@ -1248,7 +1591,7 @@ type UpdateHasAndBelongsToManyData<Rel extends HasAndBelongsToManyRelation> = {
1248
1591
  create?: CreateData<Rel['nestedCreateQuery']>[];
1249
1592
  };
1250
1593
  type UpdateArg<T extends Query> = T['meta']['hasWhere'] extends true ? UpdateData<T> : never;
1251
- type UpdateRawArg<T extends Query> = T['meta']['hasWhere'] extends true ? RawExpression : never;
1594
+ type UpdateRawArgs<T extends Query> = T['meta']['hasWhere'] extends true ? [sql: RawExpression] | [TemplateStringsArray, ...unknown[]] : never;
1252
1595
  type UpdateResult<T extends Query> = T['meta']['hasSelect'] extends true ? T : SetQueryReturnsRowCount<T>;
1253
1596
  type ChangeCountArg<T extends Query> = keyof T['shape'] | Partial<Record<keyof T['shape'], number>>;
1254
1597
  type UpdateCtx = {
@@ -1259,14 +1602,173 @@ type UpdateCtx = {
1259
1602
  updateData?: Record<string, unknown>;
1260
1603
  };
1261
1604
  declare class Update {
1605
+ /**
1606
+ * `.update` takes an object with columns and values to update records.
1607
+ *
1608
+ * By default, `.update` will return a count of updated records.
1609
+ *
1610
+ * Place `.select`, `.selectAll`, or `.get` before `.update` to specify returning columns.
1611
+ *
1612
+ * You need to provide `.where`, `.findBy`, or `.find` conditions before calling `.update`.
1613
+ * To ensure that the whole table won't be updated by accident, updating without where conditions will result in TypeScript and runtime errors.
1614
+ *
1615
+ * If you need to update ALL records, use `where` method without arguments:
1616
+ *
1617
+ * ```ts
1618
+ * await db.table.where().update({ name: 'new name' });
1619
+ * ```
1620
+ *
1621
+ * If `.select` and `.where` were specified before the update it will return an array of updated records.
1622
+ *
1623
+ * If `.select` and `.take`, `.find`, or similar were specified before the update it will return one updated record.
1624
+ *
1625
+ * For a column value you can provide a specific value, raw SQL, a query object that returns a single value, or a callback with a sub-query.
1626
+ *
1627
+ * ```ts
1628
+ * // returns number of updated records by default
1629
+ * const updatedCount = await db.table
1630
+ * .where({ name: 'old name' })
1631
+ * .update({ name: 'new name' });
1632
+ *
1633
+ * // returning only `id`
1634
+ * const id = await db.table.find(1).get('id').update({ name: 'new name' });
1635
+ *
1636
+ * // `selectAll` + `find` will return a full record
1637
+ * const oneFullRecord = await db.table
1638
+ * .selectAll()
1639
+ * .find(1)
1640
+ * .update({ name: 'new name' });
1641
+ *
1642
+ * // `selectAll` + `where` will return array of full records
1643
+ * const recordsArray = await db.table
1644
+ * .select('id', 'name')
1645
+ * .where({ id: 1 })
1646
+ * .update({ name: 'new name' });
1647
+ *
1648
+ * await db.table.where({ ...conditions }).update({
1649
+ * // set the column to a specific value
1650
+ * column1: 123,
1651
+ *
1652
+ * // use raw SQL to update the column
1653
+ * column2: db.table.sql`2 + 2`,
1654
+ *
1655
+ * // use query that returns a single value
1656
+ * // returning multiple values will result in Postgres error
1657
+ * column3: db.otherTable.get('someColumn'),
1658
+ *
1659
+ * // select a single value from a related record
1660
+ * column4: (q) => q.relatedTable.get('someColumn'),
1661
+ * });
1662
+ * ```
1663
+ *
1664
+ * `null` value will set a column to `NULL`, but the `undefined` value will be ignored:
1665
+ *
1666
+ * ```ts
1667
+ * db.table.findBy({ id: 1 }).update({
1668
+ * name: null, // updates to null
1669
+ * age: undefined, // skipped, no effect
1670
+ * });
1671
+ * ```
1672
+ *
1673
+ * @param arg - data to update records with, may have specific values, raw SQL, queries, or callbacks with sub-queries.
1674
+ */
1262
1675
  update<T extends Query>(this: T, arg: UpdateArg<T>): UpdateResult<T>;
1263
1676
  _update<T extends Query>(this: T, arg: UpdateArg<T>): UpdateResult<T>;
1264
- updateRaw<T extends Query>(this: T, arg: UpdateRawArg<T>): UpdateResult<T>;
1265
- _updateRaw<T extends Query>(this: T, arg: UpdateRawArg<T>): UpdateResult<T>;
1677
+ /**
1678
+ * `updateRaw` is for updating records with raw expression.
1679
+ *
1680
+ * The behavior is the same as a regular `update` method has:
1681
+ * `find` or `where` must precede calling this method,
1682
+ * it returns an updated count by default,
1683
+ * you can customize returning data by using `select`.
1684
+ *
1685
+ * ```ts
1686
+ * const value = 'new name';
1687
+ *
1688
+ * // update with SQL template string
1689
+ * const updatedCount = await db.table.find(1).updateRaw`name = ${value}`;
1690
+ *
1691
+ * // or update with `sql` function:
1692
+ * await db.table.find(1).updateRaw(db.table.sql`name = ${value}`);
1693
+ * ```
1694
+ * @param args - raw SQL via a template string or by using a `sql` method
1695
+ */
1696
+ updateRaw<T extends Query>(this: T, ...args: UpdateRawArgs<T>): UpdateResult<T>;
1697
+ _updateRaw<T extends Query>(this: T, ...args: UpdateRawArgs<T>): UpdateResult<T>;
1698
+ /**
1699
+ * To make sure that at least one row was updated use `updateOrThrow`:
1700
+ *
1701
+ * ```ts
1702
+ * import { NotFoundError } from 'pqb';
1703
+ *
1704
+ * try {
1705
+ * // updatedCount is guaranteed to be greater than 0
1706
+ * const updatedCount = await db.table
1707
+ * .where(conditions)
1708
+ * .updateOrThrow({ name: 'name' });
1709
+ *
1710
+ * // updatedRecords is guaranteed to be a non-empty array
1711
+ * const updatedRecords = await db.table
1712
+ * .where(conditions)
1713
+ * .select('id')
1714
+ * .updateOrThrow({ name: 'name' });
1715
+ * } catch (err) {
1716
+ * if (err instanceof NotFoundError) {
1717
+ * // handle error
1718
+ * }
1719
+ * }
1720
+ * ```
1721
+ *
1722
+ * @param arg - data to update records with, may have specific values, raw SQL, queries, or callbacks with sub-queries.
1723
+ */
1266
1724
  updateOrThrow<T extends Query>(this: T, arg: UpdateArg<T>): UpdateResult<T>;
1267
1725
  _updateOrThrow<T extends Query>(this: T, arg: UpdateArg<T>): UpdateResult<T>;
1726
+ /**
1727
+ * Increments a column value by the specified amount. Optionally takes `returning` argument.
1728
+ *
1729
+ * ```ts
1730
+ * // increment numericColumn column by 1, return updated records
1731
+ * const result = await db.table
1732
+ * .selectAll()
1733
+ * .where(...conditions)
1734
+ * .increment('numericColumn');
1735
+ *
1736
+ * // increment someColumn by 5 and otherColumn by 10, return updated records
1737
+ * const result2 = await db.table
1738
+ * .selectAll()
1739
+ * .where(...conditions)
1740
+ * .increment({
1741
+ * someColumn: 5,
1742
+ * otherColumn: 10,
1743
+ * });
1744
+ * ```
1745
+ *
1746
+ * @param data - name of the column to increment, or an object with columns and values to add
1747
+ */
1268
1748
  increment<T extends Query>(this: T, data: ChangeCountArg<T>): UpdateResult<T>;
1269
1749
  _increment<T extends Query>(this: T, data: ChangeCountArg<T>): UpdateResult<T>;
1750
+ /**
1751
+ * Decrements a column value by the specified amount. Optionally takes `returning` argument.
1752
+ *
1753
+ * ```ts
1754
+ * // decrement numericColumn column by 1, return updated records
1755
+ * const result = await db.table
1756
+ * .selectAll()
1757
+ * .where(...conditions)
1758
+ * .decrement('numericColumn');
1759
+ *
1760
+ * // decrement someColumn by 5 and otherColumn by 10, return updated records
1761
+ * const result2 = await db.table
1762
+ * .selectAll()
1763
+ * .where(...conditions)
1764
+ * .decrement({
1765
+ * someColumn: 5,
1766
+ * otherColumn: 10,
1767
+ * });
1768
+ * ```
1769
+ *
1770
+ * @param data - name of the column to decrement, or an object with columns and values to subtract
1771
+ */
1270
1772
  decrement<T extends Query>(this: T, data: ChangeCountArg<T>): UpdateResult<T>;
1271
1773
  _decrement<T extends Query>(this: T, data: ChangeCountArg<T>): UpdateResult<T>;
1272
1774
  }
@@ -1275,8 +1777,59 @@ type DeleteMethodsNames = 'del' | '_del' | 'delete' | '_delete';
1275
1777
  type DeleteArgs<T extends Query> = T['meta']['hasWhere'] extends true ? [] : [never];
1276
1778
  type DeleteResult<T extends Query> = T['meta']['hasSelect'] extends true ? T : SetQueryReturnsRowCount<T>;
1277
1779
  declare class Delete {
1780
+ /**
1781
+ * Alias for `delete` method
1782
+ */
1278
1783
  del<T extends Query>(this: T, ..._args: DeleteArgs<T>): DeleteResult<T>;
1279
1784
  _del<T extends Query>(this: T, ..._args: DeleteArgs<T>): DeleteResult<T>;
1785
+ /**
1786
+ * It is aliased to `del` because `delete` is a reserved word in JavaScript.
1787
+ *
1788
+ * This method deletes one or more rows, based on other conditions specified in the query.
1789
+ *
1790
+ * By default, `.delete` will return a count of deleted records.
1791
+ *
1792
+ * Place `.select`, `.selectAll`, or `.get` before `.delete` to specify returning columns.
1793
+ *
1794
+ * Need to provide `.where`, `.findBy`, or `.find` conditions before calling `.delete`.
1795
+ * To prevent accidental deletion of all records, deleting without where will result in TypeScript and a runtime error.
1796
+ *
1797
+ * To delete all records without conditions add an empty `where`:
1798
+ *
1799
+ * ```ts
1800
+ * await db.table.where().delete();
1801
+ * ```
1802
+ *
1803
+ * ```ts
1804
+ * // deletedCount is the number of deleted records
1805
+ * const deletedCount = await db.table.where(...conditions).delete();
1806
+ *
1807
+ * // returns a single value, throws if not found
1808
+ * const id: number | undefined = await db.table
1809
+ * .findBy(...conditions)
1810
+ * .get('id')
1811
+ * .delete();
1812
+ *
1813
+ * // returns an array of records with specified columns
1814
+ * const deletedRecord = await db.table
1815
+ * .select('id', 'name', 'age')
1816
+ * .where(...conditions)
1817
+ * .delete();
1818
+ *
1819
+ * // returns an array of fully deleted records
1820
+ * const deletedUsersFull = await db.table
1821
+ * .selectAll()
1822
+ * .where(...conditions)
1823
+ * .delete();
1824
+ * ```
1825
+ *
1826
+ * `.delete` supports joining, under the hood the join is transformed to `USING` and `WHERE` statements:
1827
+ *
1828
+ * ```ts
1829
+ * // delete all users who have corresponding profile records:
1830
+ * db.table.join(Profile, 'profile.userId', 'user.id').where().delete();
1831
+ * ```
1832
+ */
1280
1833
  delete<T extends Query>(this: T, ..._args: DeleteArgs<T>): DeleteResult<T>;
1281
1834
  _delete<T extends Query>(this: T, ..._args: DeleteArgs<T>): DeleteResult<T>;
1282
1835
  }
@@ -1421,21 +1974,122 @@ type UpsertThis = WhereResult<Query> & {
1421
1974
  returnType: 'one' | 'oneOrThrow';
1422
1975
  };
1423
1976
  declare class QueryUpsertOrCreate {
1977
+ /**
1978
+ * `.upsert` tries to update one record, and it will perform create in case a record was not found.
1979
+ *
1980
+ * It will implicitly wrap queries in a transaction if it was not wrapped yet.
1981
+ *
1982
+ * `.find` or `.findBy` must precede `.upsert` because it does not work with multiple updates.
1983
+ *
1984
+ * In case more than one row was updated, it will throw `MoreThanOneRowError` and the transaction will be rolled back.
1985
+ *
1986
+ * `update` and `create` properties are accepting the same type of objects as the `update` and `create` commands.
1987
+ *
1988
+ * Not returning a value by default, place `.select` or `.selectAll` before `.upsert` to specify returning columns.
1989
+ *
1990
+ * ```ts
1991
+ * const user = await User.selectAll()
1992
+ * .find({ email: 'some@email.com' })
1993
+ * .upsert({
1994
+ * update: {
1995
+ * name: 'updated user',
1996
+ * },
1997
+ * create: {
1998
+ * email: 'some@email.com',
1999
+ * name: 'created user',
2000
+ * },
2001
+ * });
2002
+ * ```
2003
+ *
2004
+ * The data for `create` may be returned from a function, it won't be called if a record was updated:
2005
+ *
2006
+ * ```ts
2007
+ * const user = await User.selectAll()
2008
+ * .find({ email: 'some@email.com' })
2009
+ * .upsert({
2010
+ * update: {
2011
+ * name: 'updated user',
2012
+ * },
2013
+ * create: () => ({
2014
+ * email: 'some@email.com',
2015
+ * name: 'created user',
2016
+ * }),
2017
+ * });
2018
+ * ```
2019
+ *
2020
+ * @param data - `update` property for the data to update, `create` property for the data to create
2021
+ */
1424
2022
  upsert<T extends UpsertThis>(this: T, data: UpsertData<T>): UpsertResult<T>;
1425
2023
  _upsert<T extends UpsertThis>(this: T, data: UpsertData<T>): UpsertResult<T>;
2024
+ /**
2025
+ * `.orCreate` creates a record only if it was not found by conditions.
2026
+ *
2027
+ * It will implicitly wrap queries in a transaction if it was not wrapped yet.
2028
+ *
2029
+ * `.find` or `.findBy` must precede `.orCreate`.
2030
+ *
2031
+ * It is accepting the same argument as `create` commands.
2032
+ *
2033
+ * By default, it is not returning columns, place `.get`, `.select`, or `.selectAll` before `.orCreate` to specify returning columns.
2034
+ *
2035
+ * ```ts
2036
+ * const user = await User.selectAll().find({ email: 'some@email.com' }).orCreate({
2037
+ * email: 'some@email.com',
2038
+ * name: 'created user',
2039
+ * });
2040
+ * ```
2041
+ *
2042
+ * The data may be returned from a function, it won't be called if the record was found:
2043
+ *
2044
+ * ```ts
2045
+ * const user = await User.selectAll()
2046
+ * .find({ email: 'some@email.com' })
2047
+ * .orCreate(() => ({
2048
+ * email: 'some@email.com',
2049
+ * name: 'created user',
2050
+ * }));
2051
+ * ```
2052
+ *
2053
+ * @param data - the same data as for `create`, it may be returned from a callback
2054
+ */
1426
2055
  orCreate<T extends UpsertThis>(this: T, data: UpsertCreateArg<T>): UpsertResult<T>;
1427
2056
  _orCreate<T extends UpsertThis>(this: T, data: UpsertCreateArg<T>): UpsertResult<T>;
1428
2057
  }
1429
2058
 
1430
- type GetArg<T extends QueryBase> = StringKey<keyof T['selectable']> | RawExpression;
1431
- type UnwrapRaw<T extends Query, Arg extends GetArg<T>> = Arg extends RawExpression ? Arg['__column'] : Exclude<Arg, RawExpression>;
1432
- type GetResult<T extends Query, Arg extends GetArg<T>> = SetQueryReturnsValue<T, UnwrapRaw<T, Arg>>;
1433
- type GetOptionalResult<T extends Query, Arg extends GetArg<T>> = SetQueryReturnsValueOptional<T, UnwrapRaw<T, Arg>>;
2059
+ type GetArg<T extends QueryBase> = GetStringArg<T> | RawExpression;
2060
+ type GetStringArg<T extends QueryBase> = StringKey<keyof T['selectable']>;
2061
+ type GetResult<T extends Query, Arg extends GetArg<T>> = Arg extends GetStringArg<T> ? SetQueryReturnsValue<T, Arg> : Arg extends RawExpression ? SetQueryReturnsColumn<T, Arg['__column']> : never;
2062
+ type GetResultOptional<T extends Query, Arg extends GetArg<T>> = Arg extends GetStringArg<T> ? SetQueryReturnsValueOptional<T, Arg> : Arg extends RawExpression ? SetQueryReturnsColumnOptional<T, Arg['__column']> : never;
1434
2063
  declare class QueryGet {
2064
+ /**
2065
+ * `.get` returns a single value, it will add `LIMIT 1` to the query, and accepts a column name or a raw expression.
2066
+ * It will throw `NotFoundError` when not found.
2067
+ *
2068
+ * ```ts
2069
+ * import { NumberColumn } from 'pqb';
2070
+ *
2071
+ * const firstName: string = await db.table.get('name');
2072
+ *
2073
+ * const rawResult: number = await db.table.get(
2074
+ * db.table.sql((t) => t.integer())`1 + 1`,
2075
+ * );
2076
+ * ```
2077
+ *
2078
+ * @param arg - string for a column to get, or a raw SQL
2079
+ */
1435
2080
  get<T extends Query, Arg extends GetArg<T>>(this: T, arg: Arg): GetResult<T, Arg>;
1436
2081
  _get<T extends Query, Arg extends GetArg<T>>(this: T, arg: Arg): GetResult<T, Arg>;
1437
- getOptional<T extends Query, Arg extends GetArg<T>>(this: T, arg: Arg): GetOptionalResult<T, Arg>;
1438
- _getOptional<T extends Query, Arg extends GetArg<T>>(this: T, arg: Arg): GetOptionalResult<T, Arg>;
2082
+ /**
2083
+ * `.getOptional` returns a single value or undefined when not found:
2084
+ *
2085
+ * ```ts
2086
+ * const firstName: string | undefined = await db.table.getOptional('name');
2087
+ * ```
2088
+ *
2089
+ * @param arg - string for a column to get, or a raw SQL
2090
+ */
2091
+ getOptional<T extends Query, Arg extends GetArg<T>>(this: T, arg: Arg): GetResultOptional<T, Arg>;
2092
+ _getOptional<T extends Query, Arg extends GetArg<T>>(this: T, arg: Arg): GetResultOptional<T, Arg>;
1439
2093
  }
1440
2094
 
1441
2095
  type MergeQuery<T extends Query, Q extends Query, ReturnType extends QueryReturnType = QueryReturnType extends Q['returnType'] ? T['returnType'] : Q['returnType'], Result extends ColumnsShapeBase = T['meta']['hasSelect'] extends true ? Q['meta']['hasSelect'] extends true ? {
@@ -1515,27 +2169,130 @@ interface QueryMethods extends Omit<AsMethods, 'result'>, Aggregate, Select, Fro
1515
2169
  declare class QueryMethods {
1516
2170
  windows: EmptyObject;
1517
2171
  baseQuery: Query;
2172
+ /**
2173
+ * `.all` is a default behavior, that returns an array of objects:
2174
+ *
2175
+ * ```ts
2176
+ * const records = db.table
2177
+ * .take() // .take() will be overridden by .all()
2178
+ * .all();
2179
+ * ```
2180
+ */
1518
2181
  all<T extends Query>(this: T): SetQueryReturnsAll<T>;
1519
2182
  _all<T extends Query>(this: T): SetQueryReturnsAll<T>;
2183
+ /**
2184
+ * Takes a single record, adds `LIMIT 1`.
2185
+ * Throws when not found.
2186
+ *
2187
+ * ```ts
2188
+ * const result: TableType = await db.table.where({ key: 'value' }).take();
2189
+ * ```
2190
+ */
1520
2191
  take<T extends Query>(this: T): SetQueryReturnsOne<T>;
1521
2192
  _take<T extends Query>(this: T): SetQueryReturnsOne<T>;
2193
+ /**
2194
+ * Takes a single record, adds `LIMIT 1`.
2195
+ * Returns `undefined` when not found.
2196
+ *
2197
+ * ```ts
2198
+ * const result: TableType | undefined = await db.table
2199
+ * .where({ key: 'value' })
2200
+ * .takeOptional();
2201
+ * ```
2202
+ */
1522
2203
  takeOptional<T extends Query>(this: T): SetQueryReturnsOneOptional<T>;
1523
2204
  _takeOptional<T extends Query>(this: T): SetQueryReturnsOneOptional<T>;
2205
+ /**
2206
+ * `.rows` returns an array of arrays without field names:
2207
+ *
2208
+ * ```ts
2209
+ * const rows: Array<Array<number | string>> = await db.table
2210
+ * .select('id', 'name')
2211
+ * .rows();
2212
+ *
2213
+ * rows.forEach((row) => {
2214
+ * // row is array of column values
2215
+ * row.forEach((value) => {
2216
+ * // value is an id or a name
2217
+ * });
2218
+ * });
2219
+ * ```
2220
+ */
1524
2221
  rows<T extends Query>(this: T): SetQueryReturnsRows<T>;
1525
2222
  _rows<T extends Query>(this: T): SetQueryReturnsRows<T>;
2223
+ /**
2224
+ * `.pluck` returns a single array of a single selected column values:
2225
+ *
2226
+ * ```ts
2227
+ * const ids = await db.table.select('id').pluck();
2228
+ * // ids are an array of all users' id like [1, 2, 3]
2229
+ * ```
2230
+ * @param select - column name or a raw SQL
2231
+ */
1526
2232
  pluck<T extends Query, S extends Expression<T>>(this: T, select: S): SetQueryReturnsPluck<T, S>;
1527
2233
  _pluck<T extends Query, S extends Expression<T>>(this: T, select: S): SetQueryReturnsPluck<T, S>;
2234
+ /**
2235
+ * `.exec` won't parse the response at all, and returns undefined:
2236
+ *
2237
+ * ```ts
2238
+ * const nothing = await db.table.take().exec();
2239
+ * ```
2240
+ */
1528
2241
  exec<T extends Query>(this: T): SetQueryReturnsVoid<T>;
1529
2242
  _exec<T extends Query>(this: T): SetQueryReturnsVoid<T>;
1530
2243
  toSql(this: Query, options?: ToSqlOptions): Sql;
1531
2244
  distinct<T extends Query>(this: T, ...columns: Expression<T>[]): T;
1532
2245
  _distinct<T extends Query>(this: T, ...columns: Expression<T>[]): T;
2246
+ /**
2247
+ * Find a single record by the primary key (id), adds `LIMIT 1`.
2248
+ * Throws when not found.
2249
+ *
2250
+ * ```ts
2251
+ * const result: TableType = await db.table.find(123);
2252
+ * ```
2253
+ *
2254
+ * @param args - primary key value to find by
2255
+ */
1533
2256
  find<T extends Query>(this: T, ...args: FindArgs<T>): SetQueryReturnsOne<WhereResult<T>>;
1534
2257
  _find<T extends Query>(this: T, ...args: FindArgs<T>): SetQueryReturnsOne<WhereResult<T>>;
2258
+ /**
2259
+ * Find a single record by the primary key (id), adds `LIMIT 1`.
2260
+ * Returns `undefined` when not found.
2261
+ *
2262
+ * ```ts
2263
+ * const result: TableType | undefined = await db.table.find(123);
2264
+ * ```
2265
+ *
2266
+ * @param args - primary key value to find by
2267
+ */
1535
2268
  findOptional<T extends Query>(this: T, ...args: FindArgs<T>): SetQueryReturnsOneOptional<WhereResult<T>>;
1536
2269
  _findOptional<T extends Query>(this: T, ...args: FindArgs<T>): SetQueryReturnsOneOptional<WhereResult<T>>;
2270
+ /**
2271
+ * The same as `where(conditions).take()`, it will filter records and add a `LIMIT 1`.
2272
+ * Throws when not found.
2273
+ *
2274
+ * ```ts
2275
+ * const result: TableType = await db.table.findBy({
2276
+ * key: 'value',
2277
+ * });
2278
+ * ```
2279
+ *
2280
+ * @param args - `where` conditions
2281
+ */
1537
2282
  findBy<T extends Query>(this: T, ...args: WhereArg<T>[]): SetQueryReturnsOne<WhereResult<T>>;
1538
2283
  _findBy<T extends Query>(this: T, ...args: WhereArg<T>[]): SetQueryReturnsOne<WhereResult<T>>;
2284
+ /**
2285
+ * The same as `where(conditions).takeOptional()`, it will filter records and add a `LIMIT 1`.
2286
+ * Returns `undefined` when not found.
2287
+ *
2288
+ * ```ts
2289
+ * const result: TableType | undefined = await db.table.findByOptional({
2290
+ * key: 'value',
2291
+ * });
2292
+ * ```
2293
+ *
2294
+ * @param args - `where` conditions
2295
+ */
1539
2296
  findByOptional<T extends Query>(this: T, ...args: WhereArg<T>[]): SetQueryReturnsOneOptional<WhereResult<T>>;
1540
2297
  _findByOptional<T extends Query>(this: T, ...args: WhereArg<T>[]): SetQueryReturnsOneOptional<WhereResult<T>>;
1541
2298
  withSchema<T extends Query>(this: T, schema: string): T;
@@ -1552,8 +2309,8 @@ declare class QueryMethods {
1552
2309
  _limit<T extends Query>(this: T, arg: number | undefined): T;
1553
2310
  offset<T extends Query>(this: T, arg: number | undefined): T;
1554
2311
  _offset<T extends Query>(this: T, arg: number | undefined): T;
1555
- exists<T extends Query>(this: T): SetQueryReturnsValue<T, BooleanColumn>;
1556
- _exists<T extends Query>(this: T): SetQueryReturnsValue<T, BooleanColumn>;
2312
+ exists<T extends Query>(this: T): SetQueryReturnsColumn<T, BooleanColumn>;
2313
+ _exists<T extends Query>(this: T): SetQueryReturnsColumn<T, BooleanColumn>;
1557
2314
  truncate<T extends Query>(this: T, options?: {
1558
2315
  restartIdentity?: boolean;
1559
2316
  cascade?: boolean;
@@ -1650,66 +2407,66 @@ type WindowFunctionOptions<T extends Query = Query, As extends string | undefine
1650
2407
  declare class Aggregate {
1651
2408
  selectAgg<T extends Query, Func extends string, As extends string | undefined, Value extends ColumnType>(this: T, functionName: Func, arg: AggregateArg<T>, options?: AggregateOptions<T, As>): SelectAgg<T, Func, As, Value>;
1652
2409
  _selectAgg<T extends Query, Func extends string, As extends string | undefined, Value extends ColumnTypeBase>(this: T, functionName: Func, arg: AggregateArg<T>, options?: AggregateOptions<T, As>, columnType?: ColumnTypeBase): SelectAgg<T, Func, As, Value>;
1653
- count<T extends Query>(this: T, arg?: AT1<T>['count'] | '*', options?: AggregateOptions<T>): SetQueryReturnsValue<T, NumberColumn> & {
2410
+ count<T extends Query>(this: T, arg?: AT1<T>['count'] | '*', options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NumberColumn> & {
1654
2411
  isCount: true;
1655
2412
  };
1656
- _count<T extends Query>(this: T, arg?: AT1<T>['count'] | '*', options?: AggregateOptions<T>): SetQueryReturnsValue<T, NumberColumn> & {
2413
+ _count<T extends Query>(this: T, arg?: AT1<T>['count'] | '*', options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NumberColumn> & {
1657
2414
  isCount: true;
1658
2415
  };
1659
2416
  selectCount<T extends Query, As extends string | undefined = undefined>(this: T, arg?: AT1<T>['count'] | '*', options?: AggregateOptions<T, As>): SelectAgg<T, 'count', As, NumberColumn>;
1660
2417
  _selectCount<T extends Query, As extends string | undefined = undefined>(this: T, arg?: AT1<T>['count'] | '*', options?: AggregateOptions<T, As>): SelectAgg<T, 'count', As, NumberColumn>;
1661
- avg<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['avg'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
1662
- _avg<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['avg'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
2418
+ avg<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['avg'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
2419
+ _avg<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['avg'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
1663
2420
  selectAvg<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'avg', As, NullableColumn<NumberColumn>>;
1664
2421
  _selectAvg<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'avg', As, NullableColumn<NumberColumn>>;
1665
- min<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['min'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
1666
- _min<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['min'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
2422
+ min<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['min'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
2423
+ _min<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['min'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
1667
2424
  selectMin<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'min', As, NullableColumn<NumberColumn>>;
1668
2425
  _selectMin<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'min', As, NullableColumn<NumberColumn>>;
1669
- max<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['max'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
1670
- _max<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['max'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
2426
+ max<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['max'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
2427
+ _max<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['max'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
1671
2428
  selectMax<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'max', As, NullableColumn<NumberColumn>>;
1672
2429
  _selectMax<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'max', As, NullableColumn<NumberColumn>>;
1673
- sum<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['sum'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
1674
- _sum<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['sum'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
2430
+ sum<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['sum'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
2431
+ _sum<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['sum'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
1675
2432
  selectSum<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'sum', As, NullableColumn<NumberColumn>>;
1676
2433
  _selectSum<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'sum', As, NullableColumn<NumberColumn>>;
1677
- bitAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitAnd'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
1678
- _bitAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitAnd'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
2434
+ bitAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitAnd'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
2435
+ _bitAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitAnd'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
1679
2436
  selectBitAnd<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bit_and', As, NullableColumn<NumberColumn>>;
1680
2437
  _selectBitAnd<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bit_and', As, NullableColumn<NumberColumn>>;
1681
- bitOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitOr'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
1682
- _bitOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitOr'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<NumberColumn>>;
2438
+ bitOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitOr'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
2439
+ _bitOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['bitOr'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<NumberColumn>>;
1683
2440
  selectBitOr<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bit_or', As, NullableColumn<NumberColumn>>;
1684
2441
  _selectBitOr<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bit_or', As, NullableColumn<NumberColumn>>;
1685
- boolAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolAnd'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<BooleanColumn>>;
1686
- _boolAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolAnd'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<BooleanColumn>>;
2442
+ boolAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolAnd'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<BooleanColumn>>;
2443
+ _boolAnd<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolAnd'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<BooleanColumn>>;
1687
2444
  selectBoolAnd<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bool_and', As, NullableColumn<BooleanColumn>>;
1688
2445
  _selectBoolAnd<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bool_and', As, NullableColumn<BooleanColumn>>;
1689
- boolOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolOr'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<BooleanColumn>>;
1690
- _boolOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolOr'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<BooleanColumn>>;
2446
+ boolOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolOr'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<BooleanColumn>>;
2447
+ _boolOr<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['boolOr'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<BooleanColumn>>;
1691
2448
  selectBoolOr<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bool_or', As, NullableColumn<BooleanColumn>>;
1692
2449
  _selectBoolOr<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'bool_or', As, NullableColumn<BooleanColumn>>;
1693
- every<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['every'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<BooleanColumn>>;
1694
- _every<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['every'], options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<BooleanColumn>>;
2450
+ every<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['every'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<BooleanColumn>>;
2451
+ _every<T extends Query>(this: T, arg: Aggregate1ArgumentTypes<T>['every'], options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<BooleanColumn>>;
1695
2452
  selectEvery<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'every', As, NullableColumn<BooleanColumn>>;
1696
2453
  _selectEvery<T extends Query, As extends string | undefined = undefined>(this: T, arg: Expression<T>, options?: AggregateOptions<T, As>): SelectAgg<T, 'every', As, NullableColumn<BooleanColumn>>;
1697
- jsonAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1698
- _jsonAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
2454
+ jsonAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
2455
+ _jsonAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1699
2456
  selectJsonAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonAgg'], As extends string | undefined = undefined>(this: T, arg: Expr, options?: AggregateOptions<T, As>): SelectAgg<T, 'json_agg', As, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1700
2457
  _selectJsonAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonAgg'], As extends string | undefined = undefined>(this: T, arg: Expr, options?: AggregateOptions<T, As>): SelectAgg<T, 'json_agg', As, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1701
- jsonbAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonbAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1702
- _jsonbAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonbAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
2458
+ jsonbAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonbAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
2459
+ _jsonbAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonbAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1703
2460
  selectJsonbAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonbAgg'], As extends string | undefined = undefined>(this: T, arg: Expr, options?: AggregateOptions<T, As>): SelectAgg<T, 'jsonb_agg', As, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1704
2461
  _selectJsonbAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['jsonbAgg'], As extends string | undefined = undefined>(this: T, arg: Expr, options?: AggregateOptions<T, As>): SelectAgg<T, 'jsonb_agg', As, NullableColumn<ArrayColumn<ExpressionOutput<T, Expr>>>>;
1705
- xmlAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['xmlAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<StringColumn>>;
1706
- _xmlAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['xmlAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<StringColumn>>;
2462
+ xmlAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['xmlAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<StringColumn>>;
2463
+ _xmlAgg<T extends Query, Expr extends Aggregate1ArgumentTypes<T>['xmlAgg']>(this: T, arg: Expr, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<StringColumn>>;
1707
2464
  selectXmlAgg<T extends Query, As extends string | undefined = undefined>(this: T, arg: Aggregate1ArgumentTypes<T>['xmlAgg'], options?: AggregateOptions<T, As>): SelectAgg<T, 'xmlagg', As, NullableColumn<StringColumn>>;
1708
2465
  _selectXmlAgg<T extends Query, As extends string | undefined = undefined>(this: T, arg: Aggregate1ArgumentTypes<T>['xmlAgg'], options?: AggregateOptions<T, As>): SelectAgg<T, 'xmlagg', As, NullableColumn<StringColumn>>;
1709
- jsonObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ColumnType<{
2466
+ jsonObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ColumnType<{
1710
2467
  [K in keyof Obj]: ExpressionOutput<T, Obj[K]>['type'];
1711
2468
  }>>>;
1712
- _jsonObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ColumnType<{
2469
+ _jsonObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ColumnType<{
1713
2470
  [K in keyof Obj]: ExpressionOutput<T, Obj[K]>['type'];
1714
2471
  }>>>;
1715
2472
  selectJsonObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>, As extends string | undefined = undefined>(this: T, obj: Obj, options?: AggregateOptions<T, As>): SelectAgg<T, 'json_object_agg', As, NullableColumn<ColumnType<{
@@ -1718,10 +2475,10 @@ declare class Aggregate {
1718
2475
  _selectJsonObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>, As extends string | undefined = undefined>(this: T, obj: Obj, options?: AggregateOptions<T, As>): SelectAgg<T, 'json_object_agg', As, NullableColumn<ColumnType<{
1719
2476
  [K in keyof Obj]: ExpressionOutput<T, Obj[K]>['type'];
1720
2477
  }>>>;
1721
- jsonbObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ColumnType<{
2478
+ jsonbObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ColumnType<{
1722
2479
  [K in keyof Obj]: ExpressionOutput<T, Obj[K]>['type'];
1723
2480
  }>>>;
1724
- _jsonbObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<ColumnType<{
2481
+ _jsonbObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>>(this: T, obj: Obj, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<ColumnType<{
1725
2482
  [K in keyof Obj]: ExpressionOutput<T, Obj[K]>['type'];
1726
2483
  }>>>;
1727
2484
  selectJsonbObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>, As extends string | undefined = undefined>(this: T, obj: Obj, options?: AggregateOptions<T, As>): SelectAgg<T, 'jsonb_object_agg', As, NullableColumn<ColumnType<{
@@ -1730,8 +2487,8 @@ declare class Aggregate {
1730
2487
  _selectJsonbObjectAgg<T extends Query, Obj extends Record<string, Expression<T>>, As extends string | undefined = undefined>(this: T, obj: Obj, options?: AggregateOptions<T, As>): SelectAgg<T, 'jsonb_object_agg', As, NullableColumn<ColumnType<{
1731
2488
  [K in keyof Obj]: ExpressionOutput<T, Obj[K]>['type'];
1732
2489
  }>>>;
1733
- stringAgg<T extends Query>(this: T, arg: StringExpression<T>, delimiter: string, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<StringColumn>>;
1734
- _stringAgg<T extends Query>(this: T, arg: StringExpression<T>, delimiter: string, options?: AggregateOptions<T>): SetQueryReturnsValue<T, NullableColumn<StringColumn>>;
2490
+ stringAgg<T extends Query>(this: T, arg: StringExpression<T>, delimiter: string, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<StringColumn>>;
2491
+ _stringAgg<T extends Query>(this: T, arg: StringExpression<T>, delimiter: string, options?: AggregateOptions<T>): SetQueryReturnsColumn<T, NullableColumn<StringColumn>>;
1735
2492
  selectStringAgg<T extends Query, As extends string | undefined = undefined>(this: T, arg: StringExpression<T>, delimiter: string, options?: AggregateOptions<T, As>): SelectAgg<T, 'string_agg', As, NullableColumn<StringColumn>>;
1736
2493
  _selectStringAgg<T extends Query, As extends string | undefined = undefined>(this: T, arg: StringExpression<T>, delimiter: string, options?: AggregateOptions<T, As>): SelectAgg<T, 'string_agg', As, NullableColumn<StringColumn>>;
1737
2494
  }
@@ -1825,27 +2582,15 @@ type SetQueryReturnsPluck<T extends Query, S extends keyof T['selectable'] | Raw
1825
2582
  then: QueryThen<C['type'][]>;
1826
2583
  catch: QueryCatch<C['type'][]>;
1827
2584
  };
1828
- type SetQueryReturnsValueOptional<T extends Query, Arg extends Exclude<GetArg<T>, RawExpression> | ColumnTypeBase, Column extends ColumnTypeBase = Arg extends ColumnTypeBase ? Arg : Arg extends keyof T['selectable'] ? T['selectable'][Arg]['column'] : Arg extends RelationQueryBase ? Arg['result']['value'] : never> = Omit<T, 'result' | 'returnType' | 'then' | 'catch'> & {
1829
- meta: {
1830
- hasSelect: true;
1831
- };
1832
- result: {
1833
- value: Column;
1834
- };
1835
- returnType: 'value';
1836
- then: QueryThen<Column['type'] | undefined>;
1837
- catch: QueryThen<Column['type'] | undefined>;
1838
- };
1839
- type SetQueryReturnsValue<T extends Query, Arg extends Exclude<GetArg<T>, RawExpression> | ColumnTypeBase, Column extends ColumnTypeBase = Arg extends ColumnTypeBase ? Arg : Arg extends keyof T['selectable'] ? T['selectable'][Arg]['column'] : Arg extends RelationQueryBase ? Arg['result']['value'] : never> = Omit<T, 'result' | 'returnType' | 'then' | 'catch'> & {
1840
- meta: {
2585
+ type SetQueryReturnsValueOptional<T extends Query, Arg extends GetStringArg<T>> = SetQueryReturnsValue<T, Arg, 'value'>;
2586
+ type SetQueryReturnsValue<T extends Query, Arg extends GetStringArg<T>, ReturnType extends 'value' | 'valueOrThrow' = 'valueOrThrow'> = SetQueryReturnsColumn<T, Arg extends keyof T['selectable'] ? T['selectable'][Arg]['column'] : Arg extends RelationQueryBase ? Arg['result']['value'] : never, ReturnType>;
2587
+ type SetQueryReturnsColumnOptional<T extends QueryBase, Column extends ColumnTypeBase> = SetQueryReturnsColumn<T, Column, 'value'>;
2588
+ type SetQueryReturnsColumn<T extends QueryBase, Column extends ColumnTypeBase, ReturnType extends 'value' | 'valueOrThrow' = 'valueOrThrow', Data = ReturnType extends 'value' ? Column['type'] | undefined : Column['type']> = {
2589
+ [K in keyof T]: K extends 'meta' ? T['meta'] & {
1841
2590
  hasSelect: true;
1842
- };
1843
- result: {
2591
+ } : K extends 'result' ? {
1844
2592
  value: Column;
1845
- };
1846
- returnType: 'valueOrThrow';
1847
- then: QueryThen<Column['type']>;
1848
- catch: QueryCatch<Column['type']>;
2593
+ } : K extends 'returnType' ? ReturnType : K extends 'then' ? QueryThen<Data> : K extends 'catch' ? QueryCatch<Data> : T[K];
1849
2594
  };
1850
2595
  type SetQueryReturnsRowCount<T extends Query> = SetQueryReturns<T, 'rowCount'>;
1851
2596
  type SetQueryReturnsVoid<T extends Query> = SetQueryReturns<T, 'void'>;
@@ -3869,4 +4614,4 @@ declare const testTransaction: {
3869
4614
  close(arg: Arg): Promise<void>;
3870
4615
  };
3871
4616
 
3872
- export { Adapter, AdapterConfig, AdapterOptions, AddQuerySelect, AddQueryWith, AfterHook, AfterHookKey, Aggregate, Aggregate1ArgumentTypes, AggregateArg, AggregateItem, AggregateItemArg, AggregateItemOptions, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, BaseRelation, BeforeHook, BeforeHookKey, BelongsToRelation, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanExpression, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnType, ColumnTypes, ColumnsObject, ColumnsShape, CommonQueryData, CopyOptions, CopyQueryData, Create, CreateCtx, CreateData, CreateMethodsNames, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteMethodsNames, DeleteQueryData, DomainColumn, DoublePrecisionColumn, DropMode, EnumColumn, Expression, ExpressionOfType, ExpressionOutput, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, HasAndBelongsToManyRelation, HasManyRelation, HasOneRelation, Having, HavingArg, HavingArgs, HavingItem, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, JSONTypes, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinOverrides, JoinResult, JoinedParsers, JoinedShapes, Json, JsonItem, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, NumberExpression, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operators, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryArraysResult, QueryBase, QueryData, QueryError, QueryErrorName, QueryGet, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QueryUpsertOrCreate, QueryWithTable, RawSqlMethods, RealColumn, Relation, RelationQuery, RelationQueryBase, RelationQueryData, RelationsBase, Select, SelectAgg, SelectArg, SelectFunctionItem, SelectItem, SelectQueryData, Selectable, SelectableBase, SelectableFromShape, SerialColumn, SerialColumnData, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumnInfo, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, StringExpression, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSqlCtx, ToSqlOptions, Transaction, TransactionAdapter, TransactionOptions, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertCreateArg, UpsertData, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBuilder, WhereResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowFunctionOptions, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryHook, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, checkIfASimpleQuery, cloneQueryArrays, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, utils as columnUtils, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, createDb, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getRaw, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isRequiredRelationKey, jsonTypes, logColors, logParamToLogObject, makeRegexToFindInSql, makeSql, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, referencesArgsToCode, relationQueryKey, resetTableData, setQueryObjectValue, simplifyColumnDefault, testTransaction, toSql, toSqlCacheKey };
4617
+ export { Adapter, AdapterConfig, AdapterOptions, AddQuerySelect, AddQueryWith, AfterHook, AfterHookKey, Aggregate, Aggregate1ArgumentTypes, AggregateArg, AggregateItem, AggregateItemArg, AggregateItemOptions, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, BaseRelation, BeforeHook, BeforeHookKey, BelongsToRelation, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanExpression, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnType, ColumnTypes, ColumnsObject, ColumnsShape, CommonQueryData, CopyOptions, CopyQueryData, Create, CreateCtx, CreateData, CreateMethodsNames, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteMethodsNames, DeleteQueryData, DomainColumn, DoublePrecisionColumn, DropMode, EnumColumn, Expression, ExpressionOfType, ExpressionOutput, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, GetStringArg, HasAndBelongsToManyRelation, HasManyRelation, HasOneRelation, Having, HavingArg, HavingArgs, HavingItem, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, JSONTypes, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinOverrides, JoinResult, JoinedParsers, JoinedShapes, Json, JsonItem, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, NumberExpression, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operators, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryArraysResult, QueryBase, QueryData, QueryError, QueryErrorName, QueryGet, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QueryUpsertOrCreate, QueryWithTable, RawSqlMethods, RealColumn, Relation, RelationQuery, RelationQueryBase, RelationQueryData, RelationsBase, Select, SelectAgg, SelectArg, SelectFunctionItem, SelectItem, SelectQueryData, Selectable, SelectableBase, SelectableFromShape, SerialColumn, SerialColumnData, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumn, SetQueryReturnsColumnInfo, SetQueryReturnsColumnOptional, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, StringExpression, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSqlCtx, ToSqlOptions, Transaction, TransactionAdapter, TransactionOptions, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertCreateArg, UpsertData, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBuilder, WhereResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowFunctionOptions, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryHook, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, checkIfASimpleQuery, cloneQueryArrays, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, utils as columnUtils, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, createDb, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getRaw, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isRequiredRelationKey, joinSubQuery, jsonTypes, logColors, logParamToLogObject, makeRegexToFindInSql, makeSql, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, referencesArgsToCode, relationQueryKey, resetTableData, resolveSubQueryCallback, setQueryObjectValue, simplifyColumnDefault, testTransaction, toSql, toSqlCacheKey };