pqb 0.71.0 → 0.71.2

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
@@ -714,7 +714,7 @@ declare namespace TableData {
714
714
  name?: string;
715
715
  }
716
716
  export interface ColumnIndex {
717
- options: Index.ColumnArg & Index.Options;
717
+ options: Index.ColumnOptionsData;
718
718
  }
719
719
  export interface ColumnExclude extends ColumnIndex {
720
720
  with: string;
@@ -765,7 +765,11 @@ declare namespace TableData {
765
765
  order?: string;
766
766
  weight?: SearchWeight;
767
767
  }
768
- export interface UniqueOptionsArg<Name extends string = string> {
768
+ /**
769
+ * Controls when Postgres checks a unique constraint.
770
+ */
771
+ export type UniqueDeferrable = false | 'immediate' | 'deferred';
772
+ export interface BaseUniqueOptionsArg<Name extends string = string> {
769
773
  name?: Name;
770
774
  nullsNotDistinct?: boolean;
771
775
  using?: string;
@@ -775,23 +779,45 @@ declare namespace TableData {
775
779
  where?: string;
776
780
  dropMode?: DropMode;
777
781
  }
778
- export interface OptionsArg extends UniqueOptionsArg {
782
+ export interface UniqueOptionsArg<Name extends string = string> extends BaseUniqueOptionsArg<Name> {
783
+ /**
784
+ * Makes this unique definition a deferrable Postgres constraint.
785
+ */
786
+ deferrable?: UniqueDeferrable;
787
+ }
788
+ export interface NonUniqueIndexOptionsArg<Name extends string = string> extends BaseUniqueOptionsArg<Name> {
789
+ unique?: false;
790
+ deferrable?: never;
791
+ }
792
+ export interface UniqueIndexOptionsArg<Name extends string = string> extends UniqueOptionsArg<Name> {
793
+ unique: true;
794
+ }
795
+ export type OptionsArg<Name extends string = string> = NonUniqueIndexOptionsArg<Name> | UniqueIndexOptionsArg<Name>;
796
+ export type TsVectorArg = OptionsArg & TsVectorOptions;
797
+ export interface Options extends UniqueOptionsArg, TsVectorOptions {
779
798
  unique?: boolean;
780
799
  }
781
- export interface TsVectorArg extends OptionsArg, TsVectorOptions {}
782
- export type Options = TsVectorArg;
783
800
  export interface UniqueColumnArg<Name extends string = string> extends ColumnOptions, UniqueOptionsArg<Name> {
784
801
  expression?: string;
785
802
  }
786
- export interface ColumnArg extends UniqueColumnArg {
787
- unique?: boolean;
803
+ export interface NonUniqueColumnArg<Name extends string = string> extends ColumnOptions, BaseUniqueOptionsArg<Name> {
804
+ expression?: string;
805
+ unique?: false;
806
+ deferrable?: never;
807
+ }
808
+ export interface UniqueIndexColumnArg<Name extends string = string> extends UniqueColumnArg<Name> {
809
+ unique: true;
788
810
  }
811
+ export interface ColumnOptionsData extends ColumnOptions, Options {
812
+ expression?: string;
813
+ }
814
+ export type ColumnArg<Name extends string = string> = NonUniqueColumnArg<Name> | UniqueIndexColumnArg<Name>;
789
815
  interface TsVectorOptions {
790
816
  language?: string;
791
817
  languageColumn?: string;
792
818
  tsVector?: boolean;
793
819
  }
794
- export interface TsVectorColumnArg extends ColumnArg, TsVectorOptions {}
820
+ export type TsVectorColumnArg = ColumnArg & TsVectorOptions;
795
821
  export interface ExpressionOptions extends ColumnOptions {
796
822
  expression: string;
797
823
  }
@@ -5335,11 +5361,11 @@ interface DbSqlQuery {
5335
5361
  */
5336
5362
  getOptional<T>(...args: SQLQueryArgs): Promise<T | undefined>;
5337
5363
  }
5338
- interface RawSqlBase extends Expression {
5364
+ interface RawSqlBase<T extends Column.Pick.QueryColumn = Column.Pick.QueryColumn> extends Expression<T> {
5339
5365
  _sql: string | TemplateLiteralArgs;
5340
5366
  _values?: RawSQLValues;
5341
5367
  }
5342
- interface RawSql<T extends Column.Pick.QueryColumn, ColumnTypes> extends Expression<T>, RawSqlBase, ExpressionTypeMethod {}
5368
+ interface RawSql<T extends Column.Pick.QueryColumn, ColumnTypes> extends Expression<T>, RawSqlBase<T>, ExpressionTypeMethod {}
5343
5369
  declare class RawSql<T extends Column.Pick.QueryColumn = Column.Pick.QueryColumn, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>> extends Expression<T> {
5344
5370
  result: {
5345
5371
  value: T;
@@ -5893,6 +5919,250 @@ declare const Operators: {
5893
5919
  json: OperatorsJson;
5894
5920
  array: OperatorsArray<unknown>;
5895
5921
  };
5922
+ interface ColumnsShape {
5923
+ [K: string]: Column;
5924
+ }
5925
+ declare namespace ColumnsShape {
5926
+ export type DefaultSelectKeys<S extends Column.QueryColumnsInit> = { [K in keyof S]: S[K]['data']['explicitSelect'] extends true | undefined ? never : K }[keyof S];
5927
+ export type DefaultOutput<Set extends Column.QueryColumnsInit> = { [K in DefaultSelectKeys<Set>]: Set[K]['__outputType'] };
5928
+ export type Input<Shape extends Column.QueryColumnsInit, AppReadOnly = { [K in keyof Shape]: Shape[K]['data']['appReadOnly'] extends true ? K : never }[keyof Shape], Optional extends keyof Shape = { [K in keyof Shape]: Shape[K]['data']['optional'] extends true ? K : never }[keyof Shape]> = { [K in Exclude<keyof Shape, AppReadOnly | Optional>]: Shape[K]['__inputType'] } & { [K in Exclude<Optional, AppReadOnly>]?: Shape[K]['__inputType'] };
5929
+ export type InputPartial<Shape extends Column.QueryColumnsInit> = { [K in keyof Shape]?: Shape[K]['__inputType'] };
5930
+ export type Output<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
5931
+ export type DefaultSelectOutput<Shape extends Column.QueryColumnsInit> = { [K in { [K in keyof Shape]: Shape[K]['data']['explicitSelect'] extends true | undefined ? never : K }[keyof Shape]]: Shape[K]['__outputType'] };
5932
+ export interface MapToObjectColumn<Shape extends Column.QueryColumns> {
5933
+ dataType: 'object';
5934
+ __type: { [K in keyof Shape]: Shape[K]['__type'] };
5935
+ __outputType: ShallowSimplify<ObjectOutput<Shape>>;
5936
+ __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] };
5937
+ operators: OperatorsAny;
5938
+ }
5939
+ export interface MapToNullableObjectColumn<Shape extends Column.QueryColumns> {
5940
+ dataType: 'object';
5941
+ __type: { [K in keyof Shape]: Shape[K]['__type'] };
5942
+ __outputType: ShallowSimplify<ObjectOutput<Shape>> | undefined;
5943
+ __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] } | null;
5944
+ operators: OperatorsAny;
5945
+ }
5946
+ export interface MapToPluckColumn<Shape extends Column.QueryColumns> {
5947
+ dataType: 'array';
5948
+ __type: Shape['pluck']['__type'][];
5949
+ __outputType: Shape['pluck']['__outputType'][];
5950
+ __queryType: Shape['pluck']['__queryType'][];
5951
+ operators: OperatorsAny;
5952
+ }
5953
+ export interface MapToObjectArrayColumn<Shape extends Column.QueryColumns> {
5954
+ dataType: 'array';
5955
+ __type: { [K in keyof Shape]: Shape[K]['__type'] }[];
5956
+ __outputType: ShallowSimplify<ObjectOutput<Shape>>[];
5957
+ __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] }[];
5958
+ operators: OperatorsAny;
5959
+ }
5960
+ type ObjectOutput<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
5961
+ export {};
5962
+ }
5963
+ interface SelectSelf extends PickQuerySelectable, PickQueryHasSelect, PickQueryDefaultSelect, PickQueryShape, PickQueryRelations, PickQueryResult, PickQueryReturnType, PickQueryWithData {}
5964
+ type SelectArgs<T extends SelectSelf> = ('*' | keyof T['__selectable'])[];
5965
+ interface SubQueryAddition<T extends PickQueryWithData> extends IsSubQuery {
5966
+ withData: T['withData'];
5967
+ }
5968
+ type SelectAsFnArg<T extends PickQueryRelationsWithData> = EmptyObject extends T['relations'] ? T : { [K in keyof T['relations'] | keyof T]: K extends keyof T['relations'] ? RelationQueryMaybeSingle<T['relations'][K]> & SubQueryAddition<T> : K extends keyof T ? T[K] : never };
5969
+ interface SelectAsArg<T extends SelectSelf> {
5970
+ [K: string]: keyof T['__selectable'] | Expression | ((q: SelectAsFnArg<T>) => unknown);
5971
+ }
5972
+ type SelectAsFnReturnType = {
5973
+ result: Column.QueryColumns;
5974
+ returnType: Exclude<QueryReturnType, 'rows'>;
5975
+ } | Expression;
5976
+ interface SelectAsCheckReturnTypes {
5977
+ [K: string]: PropertyKey | Expression | ((q: never) => SelectAsFnReturnType);
5978
+ }
5979
+ type SelectReturnType<T extends PickQueryReturnType> = T['returnType'] extends 'valueOrThrow' ? 'oneOrThrow' : T extends 'value' ? 'one' : T['returnType'] extends 'pluck' ? 'all' : T['returnType'];
5980
+ type SelectResult<T extends SelectSelf, Columns extends PropertyKey[]> = { [K in keyof T]: K extends '__hasSelect' ? true : K extends 'result' ? { [K in '*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number] as T['__selectable'][K]['as']]: T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown) : K extends 'returnType' ? SelectReturnType<T> : K extends 'then' ? QueryThenByReturnType<SelectReturnType<T>, { [K in '*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number] as T['__selectable'][K]['as']]: T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown)> : T[K] };
5981
+ type SelectResultObj<T extends SelectSelf, Obj> = Obj extends SelectAsCheckReturnTypes ? { [K in keyof T]: K extends '__hasSelect' ? true : K extends '__selectable' ? T['__selectable'] & SelectAsSelectable<Obj> : K extends 'result' ? { [K in T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? keyof Obj | keyof T['result'] : keyof Obj]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : K extends keyof T['result'] ? T['result'][K] : never } : K extends 'returnType' ? SelectReturnType<T> : K extends 'then' ? QueryThenByReturnType<SelectReturnType<T>, { [K in T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? keyof Obj | keyof T['result'] : keyof Obj]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : K extends keyof T['result'] ? T['result'][K] : never }> : T[K] } : `Invalid return type of ${{ [K in keyof Obj]: Obj[K] extends ((...args: any[]) => any) ? ReturnType<Obj[K]> extends SelectAsFnReturnType ? never : K : never }[keyof Obj] & string}`;
5982
+ type SelectResultColumnsAndObj<T extends SelectSelf, Columns extends PropertyKey[], Obj> = { [K in keyof T]: K extends '__hasSelect' ? true : K extends '__selectable' ? T['__selectable'] & SelectAsSelectable<Obj> : K extends 'result' ? // Combine previously selected items, all columns if * was provided,
5983
+ { [K in ('*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number]) | keyof Obj as K extends Columns[number] ? T['__selectable'][K]['as'] : K]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown) : K extends 'returnType' ? SelectReturnType<T> : K extends 'then' ? QueryThenByReturnType<SelectReturnType<T>, { [K in ('*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number]) | keyof Obj as K extends Columns[number] ? T['__selectable'][K]['as'] : K]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown)> : T[K] };
5984
+ interface AllowedRelationOneQueryForSelectable extends IsSubQuery {
5985
+ result: Column.QueryColumns;
5986
+ returnType: 'value' | 'valueOrThrow' | 'one' | 'oneOrThrow';
5987
+ }
5988
+ type SelectAsSelectable<Obj> = UnionToIntersection<{ [K in keyof Obj]: Obj[K] extends ((q: never) => infer R extends AllowedRelationOneQueryForSelectable) ? { [C in R['returnType'] extends 'value' | 'valueOrThrow' ? K : keyof R['result'] as R['returnType'] extends 'value' | 'valueOrThrow' ? K : `${K & string}.${C & string}`]: {
5989
+ as: C;
5990
+ column: R['returnType'] extends 'value' | 'valueOrThrow' ? R['result']['value'] : R['result'][C & keyof R['result']];
5991
+ } } : never }[keyof Obj]>;
5992
+ type SelectAsValueResult<T extends SelectSelf, Arg> = Arg extends keyof T['__selectable'] ? T['__selectable'][Arg]['column'] : Arg extends Expression ? Arg['result']['value'] : Arg extends ((q: never) => IsQuery) ? SelectSubQueryResult<ReturnType<Arg>> : Arg extends ((q: never) => Expression) ? ReturnType<Arg>['result']['value'] : Arg extends ((q: never) => IsQuery | Expression) ? SelectSubQueryResult<Exclude<ReturnType<Arg>, Expression>> | Exclude<ReturnType<Arg>, IsQuery>['result']['value'] : never;
5993
+ type SelectSubQueryResult<Arg extends SelectSelf> = Arg['returnType'] extends undefined | 'all' ? ColumnsShape.MapToObjectArrayColumn<Arg['result']> : Arg['returnType'] extends 'value' | 'valueOrThrow' ? Arg['result']['value'] : Arg['returnType'] extends 'pluck' ? ColumnsShape.MapToPluckColumn<Arg['result']> : Arg['returnType'] extends 'one' ? ColumnsShape.MapToNullableObjectColumn<Arg['result']> : ColumnsShape.MapToObjectColumn<Arg['result']>;
5994
+ declare function _querySelect<T extends SelectSelf, Columns extends SelectArgs<T>>(q: T, columns: Columns): SelectResult<T, Columns>;
5995
+ declare function _querySelect<T extends SelectSelf, Obj extends SelectAsArg<T>>(q: T, obj: Obj): SelectResultObj<T, Obj>;
5996
+ declare function _querySelect<T extends SelectSelf, Columns extends SelectArgs<T>, Obj extends SelectAsArg<T>>(q: T, args: [...columns: Columns, obj: Obj]): SelectResultColumnsAndObj<T, Columns, Obj>;
5997
+ declare class Select {
5998
+ /**
5999
+ * Takes a list of columns to be selected, and by default, the query builder will select all columns of the table.
6000
+ *
6001
+ * The last argument can be an object. Keys of the object are column aliases, value can be a column name, sub-query, or raw SQL expression.
6002
+ *
6003
+ * ```ts
6004
+ * import { sql } from './baseTable'
6005
+ *
6006
+ * // select columns of the table:
6007
+ * db.table.select('id', 'name', { idAlias: 'id' });
6008
+ *
6009
+ * // accepts columns with table names:
6010
+ * db.table.select('user.id', 'user.name', { nameAlias: 'user.name' });
6011
+ *
6012
+ * // table name may refer to the current table or a joined table:
6013
+ * db.table
6014
+ * .join(db.message, 'authorId', 'user.id')
6015
+ * .select('user.name', 'message.text', { textAlias: 'message.text' });
6016
+ *
6017
+ * // select value from the sub-query,
6018
+ * // this sub-query should return a single record and a single column:
6019
+ * db.table.select({
6020
+ * subQueryResult: Otherdb.table.select('column').take(),
6021
+ * });
6022
+ *
6023
+ * // select raw SQL value, specify the returning type via <generic> syntax:
6024
+ * db.table.select({
6025
+ * raw: sql<number>`1 + 2`,
6026
+ * });
6027
+ *
6028
+ * // select raw SQL value, the resulting type can be set by providing a column type in such way:
6029
+ * db.table.select({
6030
+ * raw: sql`1 + 2`.type((t) => t.integer()),
6031
+ * });
6032
+ *
6033
+ * // same raw SQL query as above, but the sql is returned from a callback
6034
+ * db.table.select({
6035
+ * raw: () => sql`1 + 2`.type((t) => t.integer()),
6036
+ * });
6037
+ * ```
6038
+ *
6039
+ * When you use the ORM and defined relations, `select` can also accept callbacks with related table queries:
6040
+ *
6041
+ * ```ts
6042
+ * await db.author.select({
6043
+ * allBooks: (q) => q.books,
6044
+ * firstBook: (q) => q.books.order({ createdAt: 'ASC' }).take(),
6045
+ * booksCount: (q) => q.books.count(),
6046
+ * });
6047
+ * ```
6048
+ *
6049
+ * When you're selecting a relation that's connected via `belongsTo` or `hasOne`, it becomes available to use in `order` or in `where`:
6050
+ *
6051
+ * ```ts
6052
+ * // select books with their authors included, order by author name and filter by author column:
6053
+ * await db.books
6054
+ * .select({
6055
+ * author: (q) => q.author,
6056
+ * })
6057
+ * .order('author.name')
6058
+ * .where({ 'author.isPopular': true });
6059
+ * ```
6060
+ */
6061
+ select<T extends SelectSelf, Columns extends SelectArgs<T>>(this: T, ...args: Columns): SelectResult<T, Columns>;
6062
+ select<T extends SelectSelf, Obj extends SelectAsArg<T>>(this: T, obj: Obj): SelectResultObj<T, Obj>;
6063
+ select<T extends SelectSelf, Columns extends SelectArgs<T>, Obj extends SelectAsArg<T>>(this: T, ...args: [...columns: Columns, obj: Obj]): SelectResultColumnsAndObj<T, Columns, Obj>;
6064
+ /**
6065
+ * When querying the table or creating records, all columns are selected by default,
6066
+ * but updating and deleting queries are returning affected row counts by default.
6067
+ *
6068
+ * Use `selectAll` to select all columns. If the `.select` method was applied before it will be discarded.
6069
+ *
6070
+ * ```ts
6071
+ * const selectFull = await db.table
6072
+ * .select('id', 'name') // discarded by `selectAll`
6073
+ * .selectAll();
6074
+ *
6075
+ * const updatedFull = await db.table.selectAll().where(conditions).update(data);
6076
+ *
6077
+ * const deletedFull = await db.table.selectAll().where(conditions).delete();
6078
+ * ```
6079
+ */
6080
+ selectAll<T extends SelectSelf>(this: T): SelectResult<T, ['*']>;
6081
+ }
6082
+ type SelectItem = string | SelectAs | Expression | undefined;
6083
+ interface SelectAs {
6084
+ selectAs: SelectAsValue;
6085
+ }
6086
+ interface SelectAsValue {
6087
+ [K: string]: string | Query | Expression | undefined;
6088
+ }
6089
+ declare const getShapeFromSelect: (q: IsQuery, isSubQuery?: boolean) => Column.QueryColumns;
6090
+ type QueryDataTransform = QueryDataTransformFn | {
6091
+ map: (record: unknown, index: number, array: unknown) => unknown;
6092
+ thisArg?: unknown;
6093
+ };
6094
+ interface QueryDataTransformFn {
6095
+ (data: unknown, queryData: unknown): unknown;
6096
+ }
6097
+ /**
6098
+ * See `transform` query method.
6099
+ * This helper applies all transform functions to a result.
6100
+ *
6101
+ * @param queryData - query data
6102
+ * @param returnType - return type of the query, for proper `map` handling
6103
+ * @param fns - array of transform functions, can be undefined
6104
+ * @param result - query result to transform
6105
+ */
6106
+ declare class QueryTransform {
6107
+ /**
6108
+ * Transform the result of the query right after loading it.
6109
+ *
6110
+ * `transform` method should be called in the last order, other methods can't be chained after calling it.
6111
+ *
6112
+ * It is meant to transform the whole result of a query, for transforming individual records consider using {@link QueryMap.map}.
6113
+ *
6114
+ * The [hooks](/guide/hooks.html) that are going to run after the query will receive the query result **before** transferring.
6115
+ *
6116
+ * Consider the following example of a cursor-based pagination by `id`:
6117
+ *
6118
+ * ```ts
6119
+ * const lastId: number | undefined = req.query.cursor;
6120
+ *
6121
+ * type Result = {
6122
+ * nodes: { id: number; text: string }[];
6123
+ * cursor?: number;
6124
+ * };
6125
+ *
6126
+ * // result is only for demo, it will be inferred
6127
+ * const posts: Result = await db.post
6128
+ * .select('id', 'text')
6129
+ * .where({ id: { lt: lastId } })
6130
+ * .order({ id: 'DESC' })
6131
+ * .limit(100)
6132
+ * .transform((nodes) => ({ nodes, cursor: nodes.at(-1)?.id }));
6133
+ * ```
6134
+ *
6135
+ * You can also use the `tranform` on nested sub-queries:
6136
+ *
6137
+ * ```ts
6138
+ * type Result = {
6139
+ * nodes: {
6140
+ * id: number;
6141
+ * text: string;
6142
+ * comments: { nodes: { id: number; text: string }[]; cursor?: number };
6143
+ * }[];
6144
+ * cursor?: number;
6145
+ * };
6146
+ *
6147
+ * const postsWithComments: Result = await db.post
6148
+ * .select('id', 'text')
6149
+ * .select({
6150
+ * comments: (q) =>
6151
+ * q.comments
6152
+ * .select('id', 'text')
6153
+ * .transform((nodes) => ({ nodes, cursor: nodes.at(-1)?.id })),
6154
+ * })
6155
+ * .transform((nodes) => ({ nodes, cursor: nodes.at(-1)?.id }));
6156
+ * ```
6157
+ *
6158
+ * @param fn - function to transform query result with
6159
+ */
6160
+ transform<T extends IsQuery, Result>(this: T, fn: (input: T extends {
6161
+ then: QueryThen<infer Data>;
6162
+ } ? Data : never, queryData: QueryData) => Result): { [K in keyof T]: K extends 'returnType' ? 'valueOrThrow' : K extends 'result' ? {
6163
+ value: Column.Pick.QueryColumnOfType<Result>;
6164
+ } : K extends 'then' ? QueryThen<Result> : T[K] };
6165
+ }
5896
6166
  type SelectableOrExpression<T extends PickQuerySelectable = PickQuerySelectable, C extends Column.Pick.QueryColumn = Column.Pick.QueryColumn> = '*' | keyof T['__selectable'] | Expression<C>;
5897
6167
  type SelectableOrExpressions<T extends PickQuerySelectable = PickQuerySelectable, C extends Column.Pick.QueryColumn = Column.Pick.QueryColumn> = ('*' | keyof T['__selectable'] | Expression<C>)[];
5898
6168
  type ExpressionOutput<T extends PickQuerySelectable, Expr extends SelectableOrExpression<T>> = Expr extends keyof T['__selectable'] ? T['__selectable'][Expr]['column'] : Expr extends Expression ? Expr['result']['value'] : never;
@@ -5903,6 +6173,7 @@ interface ExpressionData extends HasBeforeAndBeforeSet {
5903
6173
  before?: QueryBeforeHook[];
5904
6174
  dynamicBefore?: boolean;
5905
6175
  getColumn?: Column;
6176
+ transform?: QueryDataTransform[];
5906
6177
  }
5907
6178
  declare abstract class Expression<T extends Column.Pick.QueryColumn = Column.Pick.QueryColumn> {
5908
6179
  abstract result: {
@@ -5913,6 +6184,23 @@ declare abstract class Expression<T extends Column.Pick.QueryColumn = Column.Pic
5913
6184
  kind: 'select';
5914
6185
  };
5915
6186
  toSQL(ctx: ToSqlValues, quotedAs?: string): string;
6187
+ /**
6188
+ * Transform the expression value after loading it.
6189
+ *
6190
+ * It is meant to transform expressions selected by a query.
6191
+ *
6192
+ * @param fn - function to transform expression value with
6193
+ */
6194
+ transform<Self extends {
6195
+ result: {
6196
+ value: Column.Pick.QueryColumn;
6197
+ };
6198
+ q: ExpressionData;
6199
+ }, Result>(this: Self, fn: (input: Self['result']['value']['__type'], queryData: ExpressionData) => Result): Omit<Self, 'result'> & {
6200
+ result: {
6201
+ value: Column.Pick.QueryColumnOfType<Result>;
6202
+ };
6203
+ };
5916
6204
  abstract makeSQL(ctx: ToSqlValues, quotedAs?: string): string;
5917
6205
  }
5918
6206
  declare const isExpression: (arg: unknown) => arg is Expression;
@@ -6265,174 +6553,6 @@ declare class QueryTransaction {
6265
6553
  */
6266
6554
  recoverable<T>(this: T): T;
6267
6555
  }
6268
- interface ColumnsShape {
6269
- [K: string]: Column;
6270
- }
6271
- declare namespace ColumnsShape {
6272
- export type DefaultSelectKeys<S extends Column.QueryColumnsInit> = { [K in keyof S]: S[K]['data']['explicitSelect'] extends true | undefined ? never : K }[keyof S];
6273
- export type DefaultOutput<Set extends Column.QueryColumnsInit> = { [K in DefaultSelectKeys<Set>]: Set[K]['__outputType'] };
6274
- export type Input<Shape extends Column.QueryColumnsInit, AppReadOnly = { [K in keyof Shape]: Shape[K]['data']['appReadOnly'] extends true ? K : never }[keyof Shape], Optional extends keyof Shape = { [K in keyof Shape]: Shape[K]['data']['optional'] extends true ? K : never }[keyof Shape]> = { [K in Exclude<keyof Shape, AppReadOnly | Optional>]: Shape[K]['__inputType'] } & { [K in Exclude<Optional, AppReadOnly>]?: Shape[K]['__inputType'] };
6275
- export type InputPartial<Shape extends Column.QueryColumnsInit> = { [K in keyof Shape]?: Shape[K]['__inputType'] };
6276
- export type Output<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
6277
- export type DefaultSelectOutput<Shape extends Column.QueryColumnsInit> = { [K in { [K in keyof Shape]: Shape[K]['data']['explicitSelect'] extends true | undefined ? never : K }[keyof Shape]]: Shape[K]['__outputType'] };
6278
- export interface MapToObjectColumn<Shape extends Column.QueryColumns> {
6279
- dataType: 'object';
6280
- __type: { [K in keyof Shape]: Shape[K]['__type'] };
6281
- __outputType: ShallowSimplify<ObjectOutput<Shape>>;
6282
- __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] };
6283
- operators: OperatorsAny;
6284
- }
6285
- export interface MapToNullableObjectColumn<Shape extends Column.QueryColumns> {
6286
- dataType: 'object';
6287
- __type: { [K in keyof Shape]: Shape[K]['__type'] };
6288
- __outputType: ShallowSimplify<ObjectOutput<Shape>> | undefined;
6289
- __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] } | null;
6290
- operators: OperatorsAny;
6291
- }
6292
- export interface MapToPluckColumn<Shape extends Column.QueryColumns> {
6293
- dataType: 'array';
6294
- __type: Shape['pluck']['__type'][];
6295
- __outputType: Shape['pluck']['__outputType'][];
6296
- __queryType: Shape['pluck']['__queryType'][];
6297
- operators: OperatorsAny;
6298
- }
6299
- export interface MapToObjectArrayColumn<Shape extends Column.QueryColumns> {
6300
- dataType: 'array';
6301
- __type: { [K in keyof Shape]: Shape[K]['__type'] }[];
6302
- __outputType: ShallowSimplify<ObjectOutput<Shape>>[];
6303
- __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] }[];
6304
- operators: OperatorsAny;
6305
- }
6306
- type ObjectOutput<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
6307
- export {};
6308
- }
6309
- interface SelectSelf extends PickQuerySelectable, PickQueryHasSelect, PickQueryDefaultSelect, PickQueryShape, PickQueryRelations, PickQueryResult, PickQueryReturnType, PickQueryWithData {}
6310
- type SelectArgs<T extends SelectSelf> = ('*' | keyof T['__selectable'])[];
6311
- interface SubQueryAddition<T extends PickQueryWithData> extends IsSubQuery {
6312
- withData: T['withData'];
6313
- }
6314
- type SelectAsFnArg<T extends PickQueryRelationsWithData> = EmptyObject extends T['relations'] ? T : { [K in keyof T['relations'] | keyof T]: K extends keyof T['relations'] ? RelationQueryMaybeSingle<T['relations'][K]> & SubQueryAddition<T> : K extends keyof T ? T[K] : never };
6315
- interface SelectAsArg<T extends SelectSelf> {
6316
- [K: string]: keyof T['__selectable'] | Expression | ((q: SelectAsFnArg<T>) => unknown);
6317
- }
6318
- type SelectAsFnReturnType = {
6319
- result: Column.QueryColumns;
6320
- returnType: Exclude<QueryReturnType, 'rows'>;
6321
- } | Expression;
6322
- interface SelectAsCheckReturnTypes {
6323
- [K: string]: PropertyKey | Expression | ((q: never) => SelectAsFnReturnType);
6324
- }
6325
- type SelectReturnType<T extends PickQueryReturnType> = T['returnType'] extends 'valueOrThrow' ? 'oneOrThrow' : T extends 'value' ? 'one' : T['returnType'] extends 'pluck' ? 'all' : T['returnType'];
6326
- type SelectResult<T extends SelectSelf, Columns extends PropertyKey[]> = { [K in keyof T]: K extends '__hasSelect' ? true : K extends 'result' ? { [K in '*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number] as T['__selectable'][K]['as']]: T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown) : K extends 'returnType' ? SelectReturnType<T> : K extends 'then' ? QueryThenByReturnType<SelectReturnType<T>, { [K in '*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number] as T['__selectable'][K]['as']]: T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown)> : T[K] };
6327
- type SelectResultObj<T extends SelectSelf, Obj> = Obj extends SelectAsCheckReturnTypes ? { [K in keyof T]: K extends '__hasSelect' ? true : K extends '__selectable' ? T['__selectable'] & SelectAsSelectable<Obj> : K extends 'result' ? { [K in T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? keyof Obj | keyof T['result'] : keyof Obj]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : K extends keyof T['result'] ? T['result'][K] : never } : K extends 'returnType' ? SelectReturnType<T> : K extends 'then' ? QueryThenByReturnType<SelectReturnType<T>, { [K in T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? keyof Obj | keyof T['result'] : keyof Obj]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : K extends keyof T['result'] ? T['result'][K] : never }> : T[K] } : `Invalid return type of ${{ [K in keyof Obj]: Obj[K] extends ((...args: any[]) => any) ? ReturnType<Obj[K]> extends SelectAsFnReturnType ? never : K : never }[keyof Obj] & string}`;
6328
- type SelectResultColumnsAndObj<T extends SelectSelf, Columns extends PropertyKey[], Obj> = { [K in keyof T]: K extends '__hasSelect' ? true : K extends '__selectable' ? T['__selectable'] & SelectAsSelectable<Obj> : K extends 'result' ? // Combine previously selected items, all columns if * was provided,
6329
- { [K in ('*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number]) | keyof Obj as K extends Columns[number] ? T['__selectable'][K]['as'] : K]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown) : K extends 'returnType' ? SelectReturnType<T> : K extends 'then' ? QueryThenByReturnType<SelectReturnType<T>, { [K in ('*' extends Columns[number] ? Exclude<Columns[number], '*'> | T['__defaultSelect'] : Columns[number]) | keyof Obj as K extends Columns[number] ? T['__selectable'][K]['as'] : K]: K extends keyof Obj ? SelectAsValueResult<T, Obj[K]> : T['__selectable'][K]['column'] } & (T['__hasSelect'] extends (T['returnType'] extends 'value' | 'valueOrThrow' ? never : true) ? Omit<T['result'], Columns[number]> : unknown)> : T[K] };
6330
- interface AllowedRelationOneQueryForSelectable extends IsSubQuery {
6331
- result: Column.QueryColumns;
6332
- returnType: 'value' | 'valueOrThrow' | 'one' | 'oneOrThrow';
6333
- }
6334
- type SelectAsSelectable<Obj> = UnionToIntersection<{ [K in keyof Obj]: Obj[K] extends ((q: never) => infer R extends AllowedRelationOneQueryForSelectable) ? { [C in R['returnType'] extends 'value' | 'valueOrThrow' ? K : keyof R['result'] as R['returnType'] extends 'value' | 'valueOrThrow' ? K : `${K & string}.${C & string}`]: {
6335
- as: C;
6336
- column: R['returnType'] extends 'value' | 'valueOrThrow' ? R['result']['value'] : R['result'][C & keyof R['result']];
6337
- } } : never }[keyof Obj]>;
6338
- type SelectAsValueResult<T extends SelectSelf, Arg> = Arg extends keyof T['__selectable'] ? T['__selectable'][Arg]['column'] : Arg extends Expression ? Arg['result']['value'] : Arg extends ((q: never) => IsQuery) ? SelectSubQueryResult<ReturnType<Arg>> : Arg extends ((q: never) => Expression) ? ReturnType<Arg>['result']['value'] : Arg extends ((q: never) => IsQuery | Expression) ? SelectSubQueryResult<Exclude<ReturnType<Arg>, Expression>> | Exclude<ReturnType<Arg>, IsQuery>['result']['value'] : never;
6339
- type SelectSubQueryResult<Arg extends SelectSelf> = Arg['returnType'] extends undefined | 'all' ? ColumnsShape.MapToObjectArrayColumn<Arg['result']> : Arg['returnType'] extends 'value' | 'valueOrThrow' ? Arg['result']['value'] : Arg['returnType'] extends 'pluck' ? ColumnsShape.MapToPluckColumn<Arg['result']> : Arg['returnType'] extends 'one' ? ColumnsShape.MapToNullableObjectColumn<Arg['result']> : ColumnsShape.MapToObjectColumn<Arg['result']>;
6340
- declare function _querySelect<T extends SelectSelf, Columns extends SelectArgs<T>>(q: T, columns: Columns): SelectResult<T, Columns>;
6341
- declare function _querySelect<T extends SelectSelf, Obj extends SelectAsArg<T>>(q: T, obj: Obj): SelectResultObj<T, Obj>;
6342
- declare function _querySelect<T extends SelectSelf, Columns extends SelectArgs<T>, Obj extends SelectAsArg<T>>(q: T, args: [...columns: Columns, obj: Obj]): SelectResultColumnsAndObj<T, Columns, Obj>;
6343
- declare class Select {
6344
- /**
6345
- * Takes a list of columns to be selected, and by default, the query builder will select all columns of the table.
6346
- *
6347
- * The last argument can be an object. Keys of the object are column aliases, value can be a column name, sub-query, or raw SQL expression.
6348
- *
6349
- * ```ts
6350
- * import { sql } from './baseTable'
6351
- *
6352
- * // select columns of the table:
6353
- * db.table.select('id', 'name', { idAlias: 'id' });
6354
- *
6355
- * // accepts columns with table names:
6356
- * db.table.select('user.id', 'user.name', { nameAlias: 'user.name' });
6357
- *
6358
- * // table name may refer to the current table or a joined table:
6359
- * db.table
6360
- * .join(db.message, 'authorId', 'user.id')
6361
- * .select('user.name', 'message.text', { textAlias: 'message.text' });
6362
- *
6363
- * // select value from the sub-query,
6364
- * // this sub-query should return a single record and a single column:
6365
- * db.table.select({
6366
- * subQueryResult: Otherdb.table.select('column').take(),
6367
- * });
6368
- *
6369
- * // select raw SQL value, specify the returning type via <generic> syntax:
6370
- * db.table.select({
6371
- * raw: sql<number>`1 + 2`,
6372
- * });
6373
- *
6374
- * // select raw SQL value, the resulting type can be set by providing a column type in such way:
6375
- * db.table.select({
6376
- * raw: sql`1 + 2`.type((t) => t.integer()),
6377
- * });
6378
- *
6379
- * // same raw SQL query as above, but the sql is returned from a callback
6380
- * db.table.select({
6381
- * raw: () => sql`1 + 2`.type((t) => t.integer()),
6382
- * });
6383
- * ```
6384
- *
6385
- * When you use the ORM and defined relations, `select` can also accept callbacks with related table queries:
6386
- *
6387
- * ```ts
6388
- * await db.author.select({
6389
- * allBooks: (q) => q.books,
6390
- * firstBook: (q) => q.books.order({ createdAt: 'ASC' }).take(),
6391
- * booksCount: (q) => q.books.count(),
6392
- * });
6393
- * ```
6394
- *
6395
- * When you're selecting a relation that's connected via `belongsTo` or `hasOne`, it becomes available to use in `order` or in `where`:
6396
- *
6397
- * ```ts
6398
- * // select books with their authors included, order by author name and filter by author column:
6399
- * await db.books
6400
- * .select({
6401
- * author: (q) => q.author,
6402
- * })
6403
- * .order('author.name')
6404
- * .where({ 'author.isPopular': true });
6405
- * ```
6406
- */
6407
- select<T extends SelectSelf, Columns extends SelectArgs<T>>(this: T, ...args: Columns): SelectResult<T, Columns>;
6408
- select<T extends SelectSelf, Obj extends SelectAsArg<T>>(this: T, obj: Obj): SelectResultObj<T, Obj>;
6409
- select<T extends SelectSelf, Columns extends SelectArgs<T>, Obj extends SelectAsArg<T>>(this: T, ...args: [...columns: Columns, obj: Obj]): SelectResultColumnsAndObj<T, Columns, Obj>;
6410
- /**
6411
- * When querying the table or creating records, all columns are selected by default,
6412
- * but updating and deleting queries are returning affected row counts by default.
6413
- *
6414
- * Use `selectAll` to select all columns. If the `.select` method was applied before it will be discarded.
6415
- *
6416
- * ```ts
6417
- * const selectFull = await db.table
6418
- * .select('id', 'name') // discarded by `selectAll`
6419
- * .selectAll();
6420
- *
6421
- * const updatedFull = await db.table.selectAll().where(conditions).update(data);
6422
- *
6423
- * const deletedFull = await db.table.selectAll().where(conditions).delete();
6424
- * ```
6425
- */
6426
- selectAll<T extends SelectSelf>(this: T): SelectResult<T, ['*']>;
6427
- }
6428
- type SelectItem = string | SelectAs | Expression | undefined;
6429
- interface SelectAs {
6430
- selectAs: SelectAsValue;
6431
- }
6432
- interface SelectAsValue {
6433
- [K: string]: string | Query | Expression | undefined;
6434
- }
6435
- declare const getShapeFromSelect: (q: IsQuery, isSubQuery?: boolean) => Column.QueryColumns;
6436
6556
  type AfterHook<Select extends PropertyKey[], Shape extends Column.QueryColumns> = QueryAfterHook<{ [K in Select[number]]: K extends keyof Shape ? Shape[K]['__outputType'] : never }[]>;
6437
6557
  type HookSelectArg<T extends PickQueryShape> = (keyof T['shape'] & string)[];
6438
6558
  declare const _hookSelectColumns: (query: Query, columns: string[], asFn: (as: string[]) => void) => void;
@@ -7597,7 +7717,7 @@ declare abstract class Column {
7597
7717
  data: Column['data'];
7598
7718
  dataType: string;
7599
7719
  }>(this: T, ...args: [options?: TableData.Index.TsVectorColumnArg]): T;
7600
- unique<T extends Column.Pick.Data, const Options extends TableData.Index.ColumnArg>(this: T, ...args: [options?: Options]): T & Column.Modifiers.IsUnique<Options['name'] & string>;
7720
+ unique<T extends Column.Pick.Data, const Options extends TableData.Index.UniqueColumnArg>(this: T, ...args: [options?: Options]): T & Column.Modifiers.IsUnique<Options['name'] & string>;
7601
7721
  /**
7602
7722
  * Add [EXCLUDE constraint](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-EXCLUDE) to the column.
7603
7723
  *
@@ -8795,82 +8915,6 @@ interface QueryComputedArg<ColumnTypes, Shape extends Column.QueryColumns> exten
8795
8915
  column: Column.Pick.QueryColumn;
8796
8916
  } };
8797
8917
  }
8798
- type QueryDataTransform = QueryDataTransformFn | {
8799
- map: (record: unknown, index: number, array: unknown) => unknown;
8800
- thisArg?: unknown;
8801
- };
8802
- interface QueryDataTransformFn {
8803
- (data: unknown, queryData: unknown): unknown;
8804
- }
8805
- /**
8806
- * See `transform` query method.
8807
- * This helper applies all transform functions to a result.
8808
- *
8809
- * @param queryData - query data
8810
- * @param returnType - return type of the query, for proper `map` handling
8811
- * @param fns - array of transform functions, can be undefined
8812
- * @param result - query result to transform
8813
- */
8814
- declare class QueryTransform {
8815
- /**
8816
- * Transform the result of the query right after loading it.
8817
- *
8818
- * `transform` method should be called in the last order, other methods can't be chained after calling it.
8819
- *
8820
- * It is meant to transform the whole result of a query, for transforming individual records consider using {@link QueryMap.map}.
8821
- *
8822
- * The [hooks](/guide/hooks.html) that are going to run after the query will receive the query result **before** transferring.
8823
- *
8824
- * Consider the following example of a cursor-based pagination by `id`:
8825
- *
8826
- * ```ts
8827
- * const lastId: number | undefined = req.query.cursor;
8828
- *
8829
- * type Result = {
8830
- * nodes: { id: number; text: string }[];
8831
- * cursor?: number;
8832
- * };
8833
- *
8834
- * // result is only for demo, it will be inferred
8835
- * const posts: Result = await db.post
8836
- * .select('id', 'text')
8837
- * .where({ id: { lt: lastId } })
8838
- * .order({ id: 'DESC' })
8839
- * .limit(100)
8840
- * .transform((nodes) => ({ nodes, cursor: nodes.at(-1)?.id }));
8841
- * ```
8842
- *
8843
- * You can also use the `tranform` on nested sub-queries:
8844
- *
8845
- * ```ts
8846
- * type Result = {
8847
- * nodes: {
8848
- * id: number;
8849
- * text: string;
8850
- * comments: { nodes: { id: number; text: string }[]; cursor?: number };
8851
- * }[];
8852
- * cursor?: number;
8853
- * };
8854
- *
8855
- * const postsWithComments: Result = await db.post
8856
- * .select('id', 'text')
8857
- * .select({
8858
- * comments: (q) =>
8859
- * q.comments
8860
- * .select('id', 'text')
8861
- * .transform((nodes) => ({ nodes, cursor: nodes.at(-1)?.id })),
8862
- * })
8863
- * .transform((nodes) => ({ nodes, cursor: nodes.at(-1)?.id }));
8864
- * ```
8865
- *
8866
- * @param fn - function to transform query result with
8867
- */
8868
- transform<T extends IsQuery, Result>(this: T, fn: (input: T extends {
8869
- then: QueryThen<infer Data>;
8870
- } ? Data : never, queryData: QueryData) => Result): { [K in keyof T]: K extends 'returnType' ? 'valueOrThrow' : K extends 'result' ? {
8871
- value: Column.Pick.QueryColumnOfType<Result>;
8872
- } : K extends 'then' ? QueryThen<Result> : T[K] };
8873
- }
8874
8918
  type WhereItem = {
8875
8919
  [K: string]: unknown | {
8876
8920
  [K: string]: unknown | SubQueryForSql | Expression;