pqb 0.69.0 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2109,12 +2109,6 @@ interface JoinCallback<T extends PickQuerySelectableShapeRelationsWithDataAs, Ar
2109
2109
  (q: JoinQueryBuilder<T, JoinArgToQuery<T, Arg>>): IsQuery;
2110
2110
  }
2111
2111
  type JoinCallbackArgs<T extends PickQuerySelectableShapeRelationsWithDataAs, Arg extends JoinFirstArg<T>> = [cb?: JoinCallback<T, Arg> | true];
2112
- /**
2113
- * Type of {@link QueryJoin.join} query method.
2114
- */
2115
- interface JoinQueryMethod {
2116
- <T extends PickQuerySelectableResultRelationsWithDataReturnTypeShapeAs, Arg extends JoinFirstArg<T>, Cb extends JoinCallbackArgs<T, Arg>>(this: T, arg: Arg, ...args: Cb | JoinArgs<T, Arg>): JoinResultFromArgs<T, Arg, Cb, true, true>;
2117
- }
2118
2112
  declare class QueryJoin {
2119
2113
  /**
2120
2114
  * ## Select relation
@@ -2981,172 +2975,6 @@ interface AggregateOptions<T extends PickQuerySelectableResultRelationsWindows>
2981
2975
  over?: Over<T>;
2982
2976
  }
2983
2977
  type Over<T extends PickQuerySelectableResultWindows> = keyof T['windows'] | WindowArgDeclaration<T>;
2984
- interface ColumnsShape {
2985
- [K: string]: Column;
2986
- }
2987
- declare namespace ColumnsShape {
2988
- export type DefaultSelectKeys<S extends Column.QueryColumnsInit> = { [K in keyof S]: S[K]['data']['explicitSelect'] extends true | undefined ? never : K }[keyof S];
2989
- export type DefaultOutput<Set extends Column.QueryColumnsInit> = { [K in DefaultSelectKeys<Set>]: Set[K]['__outputType'] };
2990
- 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'] };
2991
- export type InputPartial<Shape extends Column.QueryColumnsInit> = { [K in keyof Shape]?: Shape[K]['__inputType'] };
2992
- export type Output<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
2993
- 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'] };
2994
- export interface MapToObjectColumn<Shape extends Column.QueryColumns> {
2995
- dataType: 'object';
2996
- __type: { [K in keyof Shape]: Shape[K]['__type'] };
2997
- __outputType: ShallowSimplify<ObjectOutput<Shape>>;
2998
- __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] };
2999
- operators: OperatorsAny;
3000
- }
3001
- export interface MapToNullableObjectColumn<Shape extends Column.QueryColumns> {
3002
- dataType: 'object';
3003
- __type: { [K in keyof Shape]: Shape[K]['__type'] };
3004
- __outputType: ShallowSimplify<ObjectOutput<Shape>> | undefined;
3005
- __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] } | null;
3006
- operators: OperatorsAny;
3007
- }
3008
- export interface MapToPluckColumn<Shape extends Column.QueryColumns> {
3009
- dataType: 'array';
3010
- __type: Shape['pluck']['__type'][];
3011
- __outputType: Shape['pluck']['__outputType'][];
3012
- __queryType: Shape['pluck']['__queryType'][];
3013
- operators: OperatorsAny;
3014
- }
3015
- export interface MapToObjectArrayColumn<Shape extends Column.QueryColumns> {
3016
- dataType: 'array';
3017
- __type: { [K in keyof Shape]: Shape[K]['__type'] }[];
3018
- __outputType: ShallowSimplify<ObjectOutput<Shape>>[];
3019
- __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] }[];
3020
- operators: OperatorsAny;
3021
- }
3022
- type ObjectOutput<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
3023
- export {};
3024
- }
3025
- interface SelectSelf extends PickQuerySelectable, PickQueryHasSelect, PickQueryDefaultSelect, PickQueryShape, PickQueryRelations, PickQueryResult, PickQueryReturnType, PickQueryWithData {}
3026
- type SelectArgs<T extends SelectSelf> = ('*' | keyof T['__selectable'])[];
3027
- interface SubQueryAddition<T extends PickQueryWithData> extends IsSubQuery {
3028
- withData: T['withData'];
3029
- }
3030
- 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 };
3031
- interface SelectAsArg<T extends SelectSelf> {
3032
- [K: string]: keyof T['__selectable'] | Expression | ((q: SelectAsFnArg<T>) => unknown);
3033
- }
3034
- type SelectAsFnReturnType = {
3035
- result: Column.QueryColumns;
3036
- returnType: Exclude<QueryReturnType, 'rows'>;
3037
- } | Expression;
3038
- interface SelectAsCheckReturnTypes {
3039
- [K: string]: PropertyKey | Expression | ((q: never) => SelectAsFnReturnType);
3040
- }
3041
- type SelectReturnType<T extends PickQueryReturnType> = T['returnType'] extends 'valueOrThrow' ? 'oneOrThrow' : T extends 'value' ? 'one' : T['returnType'] extends 'pluck' ? 'all' : T['returnType'];
3042
- 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] };
3043
- 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}`;
3044
- 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,
3045
- { [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] };
3046
- interface AllowedRelationOneQueryForSelectable extends IsSubQuery {
3047
- result: Column.QueryColumns;
3048
- returnType: 'value' | 'valueOrThrow' | 'one' | 'oneOrThrow';
3049
- }
3050
- 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}`]: {
3051
- as: C;
3052
- column: R['returnType'] extends 'value' | 'valueOrThrow' ? R['result']['value'] : R['result'][C & keyof R['result']];
3053
- } } : never }[keyof Obj]>;
3054
- 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;
3055
- 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']>;
3056
- declare function _querySelect<T extends SelectSelf, Columns extends SelectArgs<T>>(q: T, columns: Columns): SelectResult<T, Columns>;
3057
- declare function _querySelect<T extends SelectSelf, Obj extends SelectAsArg<T>>(q: T, obj: Obj): SelectResultObj<T, Obj>;
3058
- 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>;
3059
- declare class Select {
3060
- /**
3061
- * Takes a list of columns to be selected, and by default, the query builder will select all columns of the table.
3062
- *
3063
- * 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.
3064
- *
3065
- * ```ts
3066
- * import { sql } from './baseTable'
3067
- *
3068
- * // select columns of the table:
3069
- * db.table.select('id', 'name', { idAlias: 'id' });
3070
- *
3071
- * // accepts columns with table names:
3072
- * db.table.select('user.id', 'user.name', { nameAlias: 'user.name' });
3073
- *
3074
- * // table name may refer to the current table or a joined table:
3075
- * db.table
3076
- * .join(db.message, 'authorId', 'user.id')
3077
- * .select('user.name', 'message.text', { textAlias: 'message.text' });
3078
- *
3079
- * // select value from the sub-query,
3080
- * // this sub-query should return a single record and a single column:
3081
- * db.table.select({
3082
- * subQueryResult: Otherdb.table.select('column').take(),
3083
- * });
3084
- *
3085
- * // select raw SQL value, specify the returning type via <generic> syntax:
3086
- * db.table.select({
3087
- * raw: sql<number>`1 + 2`,
3088
- * });
3089
- *
3090
- * // select raw SQL value, the resulting type can be set by providing a column type in such way:
3091
- * db.table.select({
3092
- * raw: sql`1 + 2`.type((t) => t.integer()),
3093
- * });
3094
- *
3095
- * // same raw SQL query as above, but the sql is returned from a callback
3096
- * db.table.select({
3097
- * raw: () => sql`1 + 2`.type((t) => t.integer()),
3098
- * });
3099
- * ```
3100
- *
3101
- * When you use the ORM and defined relations, `select` can also accept callbacks with related table queries:
3102
- *
3103
- * ```ts
3104
- * await db.author.select({
3105
- * allBooks: (q) => q.books,
3106
- * firstBook: (q) => q.books.order({ createdAt: 'ASC' }).take(),
3107
- * booksCount: (q) => q.books.count(),
3108
- * });
3109
- * ```
3110
- *
3111
- * When you're selecting a relation that's connected via `belongsTo` or `hasOne`, it becomes available to use in `order` or in `where`:
3112
- *
3113
- * ```ts
3114
- * // select books with their authors included, order by author name and filter by author column:
3115
- * await db.books
3116
- * .select({
3117
- * author: (q) => q.author,
3118
- * })
3119
- * .order('author.name')
3120
- * .where({ 'author.isPopular': true });
3121
- * ```
3122
- */
3123
- select<T extends SelectSelf, Columns extends SelectArgs<T>>(this: T, ...args: Columns): SelectResult<T, Columns>;
3124
- select<T extends SelectSelf, Obj extends SelectAsArg<T>>(this: T, obj: Obj): SelectResultObj<T, Obj>;
3125
- select<T extends SelectSelf, Columns extends SelectArgs<T>, Obj extends SelectAsArg<T>>(this: T, ...args: [...columns: Columns, obj: Obj]): SelectResultColumnsAndObj<T, Columns, Obj>;
3126
- /**
3127
- * When querying the table or creating records, all columns are selected by default,
3128
- * but updating and deleting queries are returning affected row counts by default.
3129
- *
3130
- * Use `selectAll` to select all columns. If the `.select` method was applied before it will be discarded.
3131
- *
3132
- * ```ts
3133
- * const selectFull = await db.table
3134
- * .select('id', 'name') // discarded by `selectAll`
3135
- * .selectAll();
3136
- *
3137
- * const updatedFull = await db.table.selectAll().where(conditions).update(data);
3138
- *
3139
- * const deletedFull = await db.table.selectAll().where(conditions).delete();
3140
- * ```
3141
- */
3142
- selectAll<T extends SelectSelf>(this: T): SelectResult<T, ['*']>;
3143
- }
3144
- interface QueryGetSelf extends PickQuerySelectable, PickQueryRelationsWithData {}
3145
- type GetArg<T extends QueryGetSelf> = GetStringArg<T> | Expression | ((q: SelectAsFnArg<T>) => Expression | Query.Pick.SingleValueResult);
3146
- type GetStringArg<T extends PickQuerySelectable> = keyof T['__selectable'] & string;
3147
- type ResolveGetArgColumn<Arg> = Arg extends Expression ? Arg['result']['value'] : Arg extends ((q: never) => infer R) ? R extends Expression ? R['result']['value'] : R extends Query.Pick.SingleValueResult ? R['result']['value'] : never : never;
3148
- type GetResult<T extends QueryGetSelf, Arg extends GetArg<T>> = Arg extends string ? SetQueryReturnsValueOrThrow<T, Arg> : SetQueryReturnsColumnOrThrow<T, ResolveGetArgColumn<Arg>>;
3149
- type GetResultOptional<T extends QueryGetSelf, Arg extends GetArg<T>> = Arg extends string ? SetQueryReturnsValueOptional<T, Arg> : SetQueryReturnsColumnOptional<T, ResolveGetArgColumn<Arg>>;
3150
2978
  type HeadlineSearchArg<T extends PickQueryTsQuery> = Exclude<T['__tsQuery'], undefined>;
3151
2979
  interface HeadlineParams<T extends PickQuerySelectable> {
3152
2980
  text?: SelectableOrExpressionOfType<T, Column.Pick.QueryColumnOfType<string>>;
@@ -3483,16 +3311,6 @@ interface AggregateArgTypes {
3483
3311
  }
3484
3312
  interface AggregateMethods extends SearchAggregateMethods {}
3485
3313
  declare class AggregateMethods {
3486
- /**
3487
- * Use `exists()` to check if there is at least one record-matching condition.
3488
- *
3489
- * It will discard previous `select` statements if any. Returns a boolean.
3490
- *
3491
- * ```ts
3492
- * const exists: boolean = await db.table.where(...conditions).exists();
3493
- * ```
3494
- */
3495
- exists<T extends QueryGetSelf>(this: T): SetQueryReturnsColumnOrThrow<T, BooleanQueryColumn>;
3496
3314
  /**
3497
3315
  * Count records with the `count` function:
3498
3316
  *
@@ -5143,7 +4961,8 @@ interface QueryInternal<SinglePrimaryKey = any, UniqueColumns = any, UniqueColum
5143
4961
  */
5144
4962
  nestedCreateBatchMax: number;
5145
4963
  }
5146
- type ShapeColumnPrimaryKeys<Shape extends Column.QueryColumnsInit> = { [K in { [K in keyof Shape]: Shape[K]['data']['primaryKey'] extends string ? K : never }[keyof Shape]]: UniqueQueryTypeOrExpression<Shape[K]['__queryType']> };
4964
+ type ShapeHasPrimaryKeys<Shape extends Column.QueryColumnsInit> = { [K in keyof Shape]: Shape[K]['data']['primaryKey'] extends string ? K : never }[keyof Shape];
4965
+ type TablePrimaryKeys<Shape extends Column.QueryColumnsInit> = ShapeHasPrimaryKeys<Shape> extends never ? never : { [K in ShapeHasPrimaryKeys<Shape>]: UniqueQueryTypeOrExpression<Shape[K]['__queryType']> };
5147
4966
  type ShapeUniqueColumns<Shape extends Column.QueryColumnsInit> = { [K in keyof Shape]: Shape[K]['data']['unique'] extends string ? { [C in K]: UniqueQueryTypeOrExpression<Shape[K]['__queryType']> } : never }[keyof Shape];
5148
4967
  type UniqueConstraints<Shape extends Column.QueryColumnsInit> = { [K in keyof Shape]: Shape[K]['data']['primaryKey'] extends string ? string extends Shape[K]['data']['primaryKey'] ? never : Shape[K]['data']['primaryKey'] : Shape[K]['data']['unique'] extends string ? string extends Shape[K]['data']['unique'] ? never : Shape[K]['data']['unique'] : never }[keyof Shape];
5149
4968
  type NoPrimaryKeyOption = 'error' | 'warning' | 'ignore';
@@ -5232,7 +5051,7 @@ type DbTableOptionScopes<Table extends string | undefined, Shape extends Column.
5232
5051
  interface QueryBuilder extends Query.NotReadOnlyQuery {
5233
5052
  returnType: undefined;
5234
5053
  }
5235
- declare class Db<Table extends string | undefined = undefined, Shape extends Column.QueryColumnsInit = Column.QueryColumnsInit, PrimaryKeys = never, UniqueColumns = never, UniqueColumnTuples = never, UniqueConstraints = never, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>, ShapeWithComputed extends Column.QueryColumnsInit = Shape, Scopes extends RecordUnknown | undefined = EmptyObject, DefaultSelect extends keyof Shape = keyof Shape, ReadOnly extends true | undefined = undefined, Materialized extends true | undefined = undefined> extends QueryMethods<ColumnTypes> implements Query {
5054
+ declare class Db<Table extends string | undefined = undefined, Shape extends Column.QueryColumnsInit = Column.QueryColumnsInit, Data extends MaybeArray<TableDataItem> = never, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>, ReadOnly extends true | undefined = undefined, Options = never> extends QueryMethods<ColumnTypes> implements Query {
5236
5055
  adapterNotInTransaction: Adapter;
5237
5056
  qb: QueryBuilder;
5238
5057
  table: Table;
@@ -5240,19 +5059,21 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
5240
5059
  q: QueryData;
5241
5060
  __isQuery: true;
5242
5061
  __as: Table & string;
5243
- __selectable: SelectableFromShape<ShapeWithComputed, Table>;
5062
+ __selectable: SelectableFromShape<ComputedColumnsFromOptions<Shape, Options>, Table>;
5244
5063
  __readOnly: ReadOnly;
5245
- __materialized: Materialized;
5064
+ __materialized: Options extends {
5065
+ materialized: true;
5066
+ } ? true : undefined;
5246
5067
  __hasSelect: boolean;
5247
5068
  __hasWhere: boolean;
5248
5069
  __defaults: { [K in { [K in keyof Shape]: unknown extends Shape[K]['data']['default'] ? never : K }[keyof Shape]]: true };
5249
- __scopes: { [K in keyof Scopes]: true };
5250
- __defaultSelect: DefaultSelect;
5070
+ __scopes: { [K in keyof MapTableScopesOption<Options>]: true };
5071
+ __defaultSelect: ColumnsShape.DefaultSelectKeys<Shape>;
5251
5072
  baseQuery: Query;
5252
5073
  columns: (keyof Shape)[];
5253
5074
  __outputType: ColumnsShape.DefaultSelectOutput<Shape>;
5254
5075
  __inputType: ColumnsShape.Input<Shape>;
5255
- result: { [K in DefaultSelect]: Shape[K] };
5076
+ result: { [K in ColumnsShape.DefaultSelectKeys<Shape>]: Shape[K] };
5256
5077
  returnType: undefined;
5257
5078
  then: QueryThenShallowSimplifyArr<ColumnsShape.DefaultOutput<Shape>>;
5258
5079
  windows: EmptyObject;
@@ -5262,10 +5083,10 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
5262
5083
  relationQueries: EmptyObject;
5263
5084
  withData: EmptyObject;
5264
5085
  error: new (message: string, length: number, name: QueryErrorName) => QueryError<this>;
5265
- internal: QueryInternal<{ [K in keyof PrimaryKeys]: (keyof PrimaryKeys extends K ? never : keyof PrimaryKeys) extends never ? PrimaryKeys[K] : never }[keyof PrimaryKeys], PrimaryKeys | UniqueColumns, { [K in keyof Shape]: Shape[K]['data']['unique'] extends string ? K : never }[keyof Shape] | keyof PrimaryKeys, UniqueColumnTuples, UniqueConstraints>;
5086
+ internal: QueryInternal<TablePrimaryKeys<Shape> extends never ? never : { [K in keyof TablePrimaryKeys<Shape>]: (keyof TablePrimaryKeys<Shape> extends K ? never : keyof TablePrimaryKeys<Shape>) extends never ? TablePrimaryKeys<Shape>[K] : never }[keyof TablePrimaryKeys<Shape>], TablePrimaryKeys<Shape> | ShapeUniqueColumns<Shape> | TableDataItemsUniqueColumns<Shape, Data>, { [K in keyof Shape]: Shape[K]['data']['unique'] extends string ? K : never }[keyof Shape] | keyof TablePrimaryKeys<Shape>, TableDataItemsUniqueColumnTuples<Shape, Data>, UniqueConstraints<Shape> | TableDataItemsUniqueConstraints<Data>>;
5266
5087
  catch: QueryCatch;
5267
- shape: ShapeWithComputed;
5268
- constructor(adapterNotInTransaction: Adapter, qb: QueryBuilder, table: Table | undefined, shape: ShapeWithComputed, columnTypes: ColumnTypes, asyncStorage: AsyncLocalStorage<AsyncState>, options: DbTableOptions<ColumnTypes, Table, ShapeWithComputed>, tableData?: TableData, viewData?: QueryInternal['viewData']);
5088
+ shape: ComputedColumnsFromOptions<Shape, Options>;
5089
+ constructor(adapterNotInTransaction: Adapter, qb: QueryBuilder, table: Table | undefined, shape: ComputedColumnsFromOptions<Shape, Options>, columnTypes: ColumnTypes, asyncStorage: AsyncLocalStorage<AsyncState>, options: DbTableOptions<ColumnTypes, Table, ComputedColumnsFromOptions<Shape, Options>>, tableData?: TableData, viewData?: QueryInternal['viewData']);
5269
5090
  /**
5270
5091
  * When in transaction, returns a db adapter object for the transaction,
5271
5092
  * returns a default adapter object otherwise.
@@ -5334,7 +5155,9 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
5334
5155
  queryArrays<R extends any[] = any[]>(...args: SQLQueryArgs): Promise<QueryResult<R>>;
5335
5156
  }
5336
5157
  interface DbTableConstructor<ColumnTypes> {
5337
- <Table extends string, Shape extends Column.QueryColumnsInit, Data extends MaybeArray<TableDataItem>, Options extends DbTableOptions<ColumnTypes, Table, Shape>>(table: Table, shape?: ((t: ColumnTypes) => Shape) | Shape, tableData?: TableDataFn<Shape, Data>, options?: Options): Db<Table, Shape, keyof ShapeColumnPrimaryKeys<Shape> extends never ? never : ShapeColumnPrimaryKeys<Shape>, ShapeUniqueColumns<Shape> | TableDataItemsUniqueColumns<Shape, Data>, TableDataItemsUniqueColumnTuples<Shape, Data>, UniqueConstraints<Shape> | TableDataItemsUniqueConstraints<Data>, ColumnTypes, Shape & ComputedColumnsFromOptions<Options['computed']>, MapTableScopesOption<Options>, ColumnsShape.DefaultSelectKeys<Shape>, Options['readOnly'] extends true ? true : undefined, Options['materialized'] extends true ? true : undefined>;
5158
+ <Table extends string, Shape extends Column.QueryColumnsInit, Data extends MaybeArray<TableDataItem>, Options extends DbTableOptions<ColumnTypes, Table, Shape> | undefined>(table: Table, shape?: ((t: ColumnTypes) => Shape) | Shape, tableData?: TableDataFn<Shape, Data>, options?: Options): Db<Table, Shape, Data, ColumnTypes, Options extends {
5159
+ readOnly: true;
5160
+ } ? true : undefined, Options>;
5338
5161
  }
5339
5162
  interface DbSqlMethod<ColumnTypes> {
5340
5163
  <T>(...args: StaticSQLArgs): RawSql<Column.Pick.QueryColumnOfType<T>, ColumnTypes>;
@@ -5352,7 +5175,7 @@ type MapTableScopesOption<T> = T extends {
5352
5175
  } ? {
5353
5176
  nonDeleted: unknown;
5354
5177
  } : EmptyObject;
5355
- interface DbResult<ColumnTypes> extends Db<undefined, EmptyObject, never, never, never, never, ColumnTypes, never, never>, DbTableConstructor<ColumnTypes> {
5178
+ interface DbResult<ColumnTypes> extends Db<undefined, EmptyObject, never, ColumnTypes, never, never>, DbTableConstructor<ColumnTypes> {
5356
5179
  adapterNotInTransaction: Adapter;
5357
5180
  adapter: Adapter;
5358
5181
  close: Adapter['close'];
@@ -6438,6 +6261,166 @@ declare class QueryTransaction {
6438
6261
  */
6439
6262
  recoverable<T>(this: T): T;
6440
6263
  }
6264
+ interface ColumnsShape {
6265
+ [K: string]: Column;
6266
+ }
6267
+ declare namespace ColumnsShape {
6268
+ export type DefaultSelectKeys<S extends Column.QueryColumnsInit> = { [K in keyof S]: S[K]['data']['explicitSelect'] extends true | undefined ? never : K }[keyof S];
6269
+ export type DefaultOutput<Set extends Column.QueryColumnsInit> = { [K in DefaultSelectKeys<Set>]: Set[K]['__outputType'] };
6270
+ 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'] };
6271
+ export type InputPartial<Shape extends Column.QueryColumnsInit> = { [K in keyof Shape]?: Shape[K]['__inputType'] };
6272
+ export type Output<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
6273
+ 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'] };
6274
+ export interface MapToObjectColumn<Shape extends Column.QueryColumns> {
6275
+ dataType: 'object';
6276
+ __type: { [K in keyof Shape]: Shape[K]['__type'] };
6277
+ __outputType: ShallowSimplify<ObjectOutput<Shape>>;
6278
+ __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] };
6279
+ operators: OperatorsAny;
6280
+ }
6281
+ export interface MapToNullableObjectColumn<Shape extends Column.QueryColumns> {
6282
+ dataType: 'object';
6283
+ __type: { [K in keyof Shape]: Shape[K]['__type'] };
6284
+ __outputType: ShallowSimplify<ObjectOutput<Shape>> | undefined;
6285
+ __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] } | null;
6286
+ operators: OperatorsAny;
6287
+ }
6288
+ export interface MapToPluckColumn<Shape extends Column.QueryColumns> {
6289
+ dataType: 'array';
6290
+ __type: Shape['pluck']['__type'][];
6291
+ __outputType: Shape['pluck']['__outputType'][];
6292
+ __queryType: Shape['pluck']['__queryType'][];
6293
+ operators: OperatorsAny;
6294
+ }
6295
+ export interface MapToObjectArrayColumn<Shape extends Column.QueryColumns> {
6296
+ dataType: 'array';
6297
+ __type: { [K in keyof Shape]: Shape[K]['__type'] }[];
6298
+ __outputType: ShallowSimplify<ObjectOutput<Shape>>[];
6299
+ __queryType: { [K in keyof Shape]: Shape[K]['__queryType'] }[];
6300
+ operators: OperatorsAny;
6301
+ }
6302
+ type ObjectOutput<Shape extends Column.QueryColumns> = { [K in keyof Shape]: Shape[K]['__outputType'] };
6303
+ export {};
6304
+ }
6305
+ interface SelectSelf extends PickQuerySelectable, PickQueryHasSelect, PickQueryDefaultSelect, PickQueryShape, PickQueryRelations, PickQueryResult, PickQueryReturnType, PickQueryWithData {}
6306
+ type SelectArgs<T extends SelectSelf> = ('*' | keyof T['__selectable'])[];
6307
+ interface SubQueryAddition<T extends PickQueryWithData> extends IsSubQuery {
6308
+ withData: T['withData'];
6309
+ }
6310
+ 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 };
6311
+ interface SelectAsArg<T extends SelectSelf> {
6312
+ [K: string]: keyof T['__selectable'] | Expression | ((q: SelectAsFnArg<T>) => unknown);
6313
+ }
6314
+ type SelectAsFnReturnType = {
6315
+ result: Column.QueryColumns;
6316
+ returnType: Exclude<QueryReturnType, 'rows'>;
6317
+ } | Expression;
6318
+ interface SelectAsCheckReturnTypes {
6319
+ [K: string]: PropertyKey | Expression | ((q: never) => SelectAsFnReturnType);
6320
+ }
6321
+ type SelectReturnType<T extends PickQueryReturnType> = T['returnType'] extends 'valueOrThrow' ? 'oneOrThrow' : T extends 'value' ? 'one' : T['returnType'] extends 'pluck' ? 'all' : T['returnType'];
6322
+ 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] };
6323
+ 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}`;
6324
+ 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,
6325
+ { [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] };
6326
+ interface AllowedRelationOneQueryForSelectable extends IsSubQuery {
6327
+ result: Column.QueryColumns;
6328
+ returnType: 'value' | 'valueOrThrow' | 'one' | 'oneOrThrow';
6329
+ }
6330
+ 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}`]: {
6331
+ as: C;
6332
+ column: R['returnType'] extends 'value' | 'valueOrThrow' ? R['result']['value'] : R['result'][C & keyof R['result']];
6333
+ } } : never }[keyof Obj]>;
6334
+ 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;
6335
+ 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']>;
6336
+ declare function _querySelect<T extends SelectSelf, Columns extends SelectArgs<T>>(q: T, columns: Columns): SelectResult<T, Columns>;
6337
+ declare function _querySelect<T extends SelectSelf, Obj extends SelectAsArg<T>>(q: T, obj: Obj): SelectResultObj<T, Obj>;
6338
+ 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>;
6339
+ declare class Select {
6340
+ /**
6341
+ * Takes a list of columns to be selected, and by default, the query builder will select all columns of the table.
6342
+ *
6343
+ * 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.
6344
+ *
6345
+ * ```ts
6346
+ * import { sql } from './baseTable'
6347
+ *
6348
+ * // select columns of the table:
6349
+ * db.table.select('id', 'name', { idAlias: 'id' });
6350
+ *
6351
+ * // accepts columns with table names:
6352
+ * db.table.select('user.id', 'user.name', { nameAlias: 'user.name' });
6353
+ *
6354
+ * // table name may refer to the current table or a joined table:
6355
+ * db.table
6356
+ * .join(db.message, 'authorId', 'user.id')
6357
+ * .select('user.name', 'message.text', { textAlias: 'message.text' });
6358
+ *
6359
+ * // select value from the sub-query,
6360
+ * // this sub-query should return a single record and a single column:
6361
+ * db.table.select({
6362
+ * subQueryResult: Otherdb.table.select('column').take(),
6363
+ * });
6364
+ *
6365
+ * // select raw SQL value, specify the returning type via <generic> syntax:
6366
+ * db.table.select({
6367
+ * raw: sql<number>`1 + 2`,
6368
+ * });
6369
+ *
6370
+ * // select raw SQL value, the resulting type can be set by providing a column type in such way:
6371
+ * db.table.select({
6372
+ * raw: sql`1 + 2`.type((t) => t.integer()),
6373
+ * });
6374
+ *
6375
+ * // same raw SQL query as above, but the sql is returned from a callback
6376
+ * db.table.select({
6377
+ * raw: () => sql`1 + 2`.type((t) => t.integer()),
6378
+ * });
6379
+ * ```
6380
+ *
6381
+ * When you use the ORM and defined relations, `select` can also accept callbacks with related table queries:
6382
+ *
6383
+ * ```ts
6384
+ * await db.author.select({
6385
+ * allBooks: (q) => q.books,
6386
+ * firstBook: (q) => q.books.order({ createdAt: 'ASC' }).take(),
6387
+ * booksCount: (q) => q.books.count(),
6388
+ * });
6389
+ * ```
6390
+ *
6391
+ * When you're selecting a relation that's connected via `belongsTo` or `hasOne`, it becomes available to use in `order` or in `where`:
6392
+ *
6393
+ * ```ts
6394
+ * // select books with their authors included, order by author name and filter by author column:
6395
+ * await db.books
6396
+ * .select({
6397
+ * author: (q) => q.author,
6398
+ * })
6399
+ * .order('author.name')
6400
+ * .where({ 'author.isPopular': true });
6401
+ * ```
6402
+ */
6403
+ select<T extends SelectSelf, Columns extends SelectArgs<T>>(this: T, ...args: Columns): SelectResult<T, Columns>;
6404
+ select<T extends SelectSelf, Obj extends SelectAsArg<T>>(this: T, obj: Obj): SelectResultObj<T, Obj>;
6405
+ select<T extends SelectSelf, Columns extends SelectArgs<T>, Obj extends SelectAsArg<T>>(this: T, ...args: [...columns: Columns, obj: Obj]): SelectResultColumnsAndObj<T, Columns, Obj>;
6406
+ /**
6407
+ * When querying the table or creating records, all columns are selected by default,
6408
+ * but updating and deleting queries are returning affected row counts by default.
6409
+ *
6410
+ * Use `selectAll` to select all columns. If the `.select` method was applied before it will be discarded.
6411
+ *
6412
+ * ```ts
6413
+ * const selectFull = await db.table
6414
+ * .select('id', 'name') // discarded by `selectAll`
6415
+ * .selectAll();
6416
+ *
6417
+ * const updatedFull = await db.table.selectAll().where(conditions).update(data);
6418
+ *
6419
+ * const deletedFull = await db.table.selectAll().where(conditions).delete();
6420
+ * ```
6421
+ */
6422
+ selectAll<T extends SelectSelf>(this: T): SelectResult<T, ['*']>;
6423
+ }
6441
6424
  type SelectItem = string | SelectAs | Expression | undefined;
6442
6425
  interface SelectAs {
6443
6426
  selectAs: SelectAsValue;
@@ -8749,11 +8732,13 @@ declare const getColumnBaseType: (column: Column.Pick.Data, domainsMap: DbStruct
8749
8732
  interface ColumnDataComputedProp extends ColumnDataSelectSqlProp {
8750
8733
  computed?: Expression;
8751
8734
  }
8752
- type ComputedColumnsFromOptions<T extends ComputedOptionsFactory<never, never> | undefined> = T extends ((...args: any[]) => infer R extends ComputedOptionsConfig) ? { [K in keyof R]: R[K] extends QueryOrExpression<unknown> ? R[K]['result']['value'] : R[K] extends (() => {
8735
+ type ComputedColumnsFromOptions<Shape, Options> = Options extends {
8736
+ computed: (...args: any) => infer R;
8737
+ } ? { [K in (keyof Shape | keyof R) & string]: K extends keyof Shape ? Shape[K] : K extends keyof R ? R[K] extends QueryOrExpression<unknown> ? R[K]['result']['value'] : R[K] extends (() => {
8753
8738
  result: {
8754
8739
  value: infer Value extends Column.Pick.QueryColumn;
8755
8740
  };
8756
- }) ? Value : never } : EmptyObject;
8741
+ }) ? Value : never : never } : Shape;
8757
8742
  interface ComputedOptionsConfig {
8758
8743
  [K: string]: QueryOrExpression<unknown> | ReturnsQueryOrExpression<unknown>;
8759
8744
  }
@@ -9837,6 +9822,12 @@ declare class QueryUpsert {
9837
9822
  */
9838
9823
  upsert<T extends UpsertThis, Update extends UpdateData<T>>(this: T, data: UpsertData<T, Update>): UpsertResult<T>;
9839
9824
  }
9825
+ interface QueryGetSelf extends PickQuerySelectable, PickQueryRelationsWithData {}
9826
+ type GetArg<T extends QueryGetSelf> = GetStringArg<T> | Expression | ((q: SelectAsFnArg<T>) => Expression | Query.Pick.SingleValueResult);
9827
+ type GetStringArg<T extends PickQuerySelectable> = keyof T['__selectable'] & string;
9828
+ type ResolveGetArgColumn<Arg> = Arg extends Expression ? Arg['result']['value'] : Arg extends ((q: never) => infer R) ? R extends Expression ? R['result']['value'] : R extends Query.Pick.SingleValueResult ? R['result']['value'] : never : never;
9829
+ type GetResult<T extends QueryGetSelf, Arg extends GetArg<T>> = Arg extends string ? SetQueryReturnsValueOrThrow<T, Arg> : SetQueryReturnsColumnOrThrow<T, ResolveGetArgColumn<Arg>>;
9830
+ type GetResultOptional<T extends QueryGetSelf, Arg extends GetArg<T>> = Arg extends string ? SetQueryReturnsValueOptional<T, Arg> : SetQueryReturnsColumnOptional<T, ResolveGetArgColumn<Arg>>;
9840
9831
  declare class QueryGet {
9841
9832
  /**
9842
9833
  * `.get` returns a single value, adds `LIMIT 1` to the query, and accepts a column name or a raw SQL expression.
@@ -10118,6 +10109,28 @@ declare class QueryTruncate {
10118
10109
  cascade?: boolean;
10119
10110
  }): SetQueryReturnsVoid<T>;
10120
10111
  }
10112
+ declare class QueryExistsMethods {
10113
+ /**
10114
+ * Use `exists()` to check if there is at least one record-matching condition.
10115
+ *
10116
+ * It will discard previous `select` statements if any. Returns a boolean.
10117
+ *
10118
+ * ```ts
10119
+ * const exists: boolean = await db.table.where(...conditions).exists();
10120
+ * ```
10121
+ */
10122
+ exists<T extends QueryGetSelf>(this: T): SetQueryReturnsColumnOrThrow<T, BooleanQueryColumn>;
10123
+ /**
10124
+ * Use `notExists()` to check if there are no matching records.
10125
+ *
10126
+ * It will discard previous `select` statements if any. Returns a boolean.
10127
+ *
10128
+ * ```ts
10129
+ * const exists: boolean = await db.table.where(...conditions).notExists();
10130
+ * ```
10131
+ */
10132
+ notExists<T extends QueryGetSelf>(this: T): SetQueryReturnsColumnOrThrow<T, BooleanQueryColumn>;
10133
+ }
10121
10134
  type GroupArgs<T extends PickQueryResult> = ({ [K in keyof T['result']]: T['result'][K]['dataType'] extends 'array' | 'object' | 'runtimeComputed' ? never : K }[keyof T['result']] | Expression)[];
10122
10135
  interface QueryHelperQuery<T extends PickQuerySelectableShapeAs> extends MergeQueryArg {
10123
10136
  returnType: QueryReturnType;
@@ -10156,7 +10169,7 @@ interface NarrowPluckTypeResult<T extends PickQueryResultReturnType, Narrow> ext
10156
10169
  }
10157
10170
  type QueryIfResult<T extends PickQueryResultReturnType, R extends PickQueryResult> = { [K in keyof T]: K extends 'result' ? { [K in keyof T['result'] | keyof R['result']]: K extends keyof T['result'] ? K extends keyof R['result'] ? R['result'][K] | T['result'][K] : T['result'][K] : Column.Modifiers.QueryColumnToOptional<R['result'][K]> } : K extends 'then' ? QueryIfResultThen<T, R> : T[K] };
10158
10171
  type QueryIfResultThen<T extends PickQueryResultReturnType, R extends PickQueryResult> = T['returnType'] extends undefined | 'all' ? QueryThenShallowSimplifyArr<{ [K in keyof T['result']]: K extends keyof R['result'] ? T['result'][K]['__outputType'] | R['result'][K]['__outputType'] : T['result'][K]['__outputType'] } & { [K in keyof R['result'] as K extends keyof T['result'] ? never : K]?: R['result'][K]['__outputType'] }> : T['returnType'] extends 'one' ? QueryThenShallowSimplifyOptional<{ [K in keyof T['result']]: K extends keyof R['result'] ? T['result'][K]['__outputType'] | R['result'][K]['__outputType'] : T['result'][K]['__outputType'] } & { [K in keyof R['result'] as K extends keyof T['result'] ? never : K]?: R['result'][K]['__outputType'] }> : T['returnType'] extends 'oneOrThrow' ? QueryThenShallowSimplify<{ [K in keyof T['result']]: K extends keyof R['result'] ? T['result'][K]['__outputType'] | R['result'][K]['__outputType'] : T['result'][K]['__outputType'] } & { [K in keyof R['result'] as K extends keyof T['result'] ? never : K]?: R['result'][K]['__outputType'] }> : T['returnType'] extends 'value' ? QueryThen<T['result']['value']['__outputType'] | R['result']['value']['__outputType'] | undefined> : T['returnType'] extends 'valueOrThrow' ? QueryThen<T['result']['value']['__outputType'] | R['result']['value']['__outputType']> : T['returnType'] extends 'rows' ? QueryThen<(T['result'][keyof T['result']]['__outputType'] | R['result'][keyof R['result']]['__outputType'])[][]> : T['returnType'] extends 'pluck' ? QueryThen<(T['result']['pluck']['__outputType'] | R['result']['pluck']['__outputType'])[]> : QueryThen<void>;
10159
- interface QueryMethods<ColumnTypes> extends QueryClone, QueryAsMethods, AggregateMethods, QueryDistinct, Select, FromMethods, QueryJoin, QueryLimitOffset, CteQuery, Union, QueryJsonMethods, QueryCreate, QueryCreateFrom, QueryUpdate, QueryDelete, QueryStorage, QueryTransaction, QueryTruncate, For, Where, SearchMethods, Clear, Having, QueryCatchers, QueryLog, QueryOrder, QueryWithSchema, QueryHooks, QueryUpsert, QueryOrCreate, QueryGet, QueryPluck, MergeQueryMethods, QuerySql<ColumnTypes>, QueryTransform, QueryMap, QueryScope, SoftDeleteMethods, QueryExpressions, QueryWrap, QueryWindow {}
10172
+ interface QueryMethods<ColumnTypes> extends QueryClone, QueryAsMethods, AggregateMethods, QueryDistinct, Select, FromMethods, QueryJoin, QueryLimitOffset, CteQuery, Union, QueryJsonMethods, QueryCreate, QueryCreateFrom, QueryUpdate, QueryDelete, QueryStorage, QueryTransaction, QueryTruncate, For, Where, SearchMethods, Clear, Having, QueryCatchers, QueryLog, QueryOrder, QueryWithSchema, QueryHooks, QueryUpsert, QueryOrCreate, QueryGet, QueryPluck, MergeQueryMethods, QuerySql<ColumnTypes>, QueryTransform, QueryMap, QueryScope, SoftDeleteMethods, QueryExpressions, QueryWrap, QueryWindow, QueryExistsMethods {}
10160
10173
  declare class QueryMethods<ColumnTypes> {
10161
10174
  /**
10162
10175
  * `.all` is a default behavior, that returns an array of objects:
@@ -10219,6 +10232,15 @@ declare class QueryMethods<ColumnTypes> {
10219
10232
  * ```
10220
10233
  */
10221
10234
  exec<T>(this: T): SetQueryReturnsVoid<T>;
10235
+ /**
10236
+ * For relation selects, `require` changes LEFT JOIN LATERAL to JOIN LATERAL.
10237
+ *
10238
+ * ```ts
10239
+ * // only the records that have `related` will be loaded:
10240
+ * await db.table.select({ related: (q) => q.related.required() });
10241
+ * ```
10242
+ */
10243
+ require<T extends PickQueryResultReturnType>(this: T): QueryRequire<T>;
10222
10244
  /**
10223
10245
  * Call `toSQL` on a query to get an object with a `text` SQL string and a `values` array of binding values:
10224
10246
  *
@@ -10407,7 +10429,7 @@ declare class QueryMethods<ColumnTypes> {
10407
10429
  * // all the following queries will resolve into empty arrays
10408
10430
  *
10409
10431
  * await db.user.select({
10410
- * pets: (q) => q.pets.join().none(),
10432
+ * pets: (q) => q.pets.require().none(),
10411
10433
  * });
10412
10434
  *
10413
10435
  * await db.user.join((q) => q.pets.none());
@@ -10479,7 +10501,7 @@ declare class QueryMethods<ColumnTypes> {
10479
10501
  *
10480
10502
  * @param fn - helper function
10481
10503
  */
10482
- makeHelper<T extends PickQuerySelectableShapeAs, Args extends unknown[], Result extends MergeQueryArg>(this: T, fn: (q: T, ...args: Args) => Result): QueryHelper<T, Args, Result>;
10504
+ makeHelper<T extends PickQuerySelectableShapeAs, Args extends unknown[], Result extends MergeQueryArg | Expression>(this: T, fn: (q: T, ...args: Args) => Result): QueryHelper<T, Args, Result>;
10483
10505
  /**
10484
10506
  * `useHelper` allows to use {@link makeHelper} in different queries:
10485
10507
  *
@@ -10688,6 +10710,9 @@ declare namespace Query {
10688
10710
  type Args<T extends Order.ArgThis> = Order.Args<T>;
10689
10711
  }
10690
10712
  namespace Pick {
10713
+ interface ReturnType {
10714
+ returnType: QueryReturnType;
10715
+ }
10691
10716
  interface SingleValueResult {
10692
10717
  result: {
10693
10718
  value: Column.Pick.OutputType;
@@ -10708,6 +10733,7 @@ type SetQueryReturnsAll<T extends PickQueryResult> = { [K in keyof T]: K extends
10708
10733
  type SetQueryReturnsAllResult<T extends PickQueryResult, Result extends Column.QueryColumns> = { [K in keyof T]: K extends 'returnType' ? 'all' : K extends 'result' ? Result : K extends 'then' ? QueryThenShallowSimplifyArr<T['result']> : T[K] } & QueryHasWhere;
10709
10734
  type QueryTakeOptional<T extends PickQueryResultReturnType> = T['returnType'] extends 'value' | 'pluck' | 'void' ? T : T['returnType'] extends 'valueOrThrow' ? { [K in keyof T]: K extends 'returnType' ? 'value' : K extends 'then' ? QueryThen<T['result']['value']['__outputType'] | undefined> : T[K] } : { [K in keyof T]: K extends 'returnType' ? 'one' : K extends 'then' ? QueryThenShallowSimplifyOptional<ColumnsShape.Output<T['result']>> : T[K] };
10710
10735
  type QueryManyTakeOptional<T extends PickQueryResultReturnType> = { [K in keyof T]: K extends 'returnType' ? 'one' : K extends 'then' ? QueryThenShallowSimplifyOptional<ColumnsShape.Output<T['result']>> : T[K] };
10736
+ type QueryRequire<T extends PickQueryResultReturnType> = T['returnType'] extends QueryReturnTypeAll | 'valueOrThrow' | 'pluck' | 'void' ? T : T['returnType'] extends 'value' ? { [K in keyof T]: K extends 'returnType' ? 'valueOrThrow' : K extends 'then' ? QueryThen<Exclude<T['result']['value']['__outputType'], undefined>> : T[K] } : { [K in keyof T]: K extends 'returnType' ? 'oneOrThrow' : K extends 'then' ? QueryThenShallowSimplify<ColumnsShape.Output<T['result']>> : T[K] };
10711
10737
  type QueryTake<T extends PickQueryResultReturnType> = T['returnType'] extends 'valueOrThrow' | 'pluck' | 'void' ? T : T['returnType'] extends 'value' ? { [K in keyof T]: K extends 'returnType' ? 'valueOrThrow' : K extends 'then' ? QueryThen<Exclude<T['result']['value']['__outputType'], undefined>> : T[K] } : { [K in keyof T]: K extends 'returnType' ? 'oneOrThrow' : K extends 'then' ? QueryThenShallowSimplify<ColumnsShape.Output<T['result']>> : T[K] };
10712
10738
  type QueryManyTake<T extends PickQueryResultReturnType> = { [K in keyof T]: K extends 'returnType' ? 'oneOrThrow' : K extends 'then' ? QueryThenShallowSimplify<ColumnsShape.Output<T['result']>> : T[K] };
10713
10739
  type SetQueryReturnsOne<T extends PickQueryResult> = { [K in keyof T]: K extends 'returnType' ? 'oneOrThrow' : K extends 'then' ? QueryThenShallowSimplify<ColumnsShape.Output<T['result']>> : T[K] };
@@ -11113,4 +11139,4 @@ declare const testTransaction: {
11113
11139
  */
11114
11140
  close(arg: Arg$1): Promise<void>;
11115
11141
  };
11116
- export { type Adapter, AdapterClass, type AdapterConfigBase, type AdapterParams, type AdapterSchemaConfigOptions, type AfterCommitStandaloneHook, type AfterHook, ArrayColumn, type ArrayColumnValue, type ArrayData, type AsyncState, type BaseNumberData, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, type ColumnSchemaConfig, type ColumnSchemaGetterColumns, type ColumnSchemaGetterTableClass, type ColumnToCodeCtx, type ColumnTypeSchemaArg, type ColumnsByType, type ColumnsShape, type ComputedColumnsFromOptions, type ComputedOptionsConfig, type ComputedOptionsFactory, type CreateCtx, type CreateData, type CreateManyMethodsNames, type CreateMethodsNames, type CreateSelf, CustomTypeColumn, DateBaseColumn, DateColumn, type DateColumnData, DateTimeBaseClass, DateTimeTzBaseClass, Db, type DbDomainArg, type DbExtension, type DbOptions, type DbResult, type DbSharedOptions, type DbSqlMethod, type DbStructureDomainsMap, type DbTableOptionScopes, type DbTableOptions, DecimalColumn, type DecimalColumnData, type DefaultColumnTypes, type DefaultPrivileges, type DefaultSchemaConfig, type DeleteMethodsNames, DomainColumn, DoublePrecisionColumn, type DriverAdapter, DynamicRawSQL, type EmptyObject, type EmptyTuple, EnumColumn, Expression, type ExpressionData, type FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinQueryMethod, type JoinedShapes, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, type MapTableScopesOption, type MaybeArray, type MaybePromise, type MergeQuery, MoneyColumn, type NoPrimaryKeyOption, type NonUniqDataItem, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, type NumberColumnData, Operators, type OperatorsArray, type OperatorsJson, type OperatorsOrdinalText, type OperatorsText, OrchidOrmInternalError, type Ord, PathColumn, type PickQueryInputType, type PickQueryInternal, type PickQueryQ, type PickQueryRelations, type PickQuerySelectableRelations, type PickQueryShape, PointColumn, PolygonColumn, PostgisGeographyPointColumn, type Query, type QueryAfterHook, type QueryBeforeActionHook, type QueryBeforeHook, type QueryData, QueryError, type QueryHasWhere, type QueryHelperResult, QueryHookUtils, QueryHooks, type QueryInternal, type QueryLogObject, type QueryLogOptions, type QueryLogger, type QueryManyTake, type QueryManyTakeOptional, type QueryOrExpression, type QueryResult, type QueryResultRow, type QueryReturnType, type QuerySchema, type QueryScopes, RawSql, type RawSqlBase, RealColumn, type RecordKeyTrue, type RecordOptionalString, type RecordString, type RecordStringOrNumber, type RecordUnknown, type RefreshMaterializedViewOptions, type RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeColumnPrimaryKeys, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, type StorageOptions, StringColumn, type StringData, type TableData, type TableDataFn, type TableDataInput, type TableDataItem, type TableDataItemsUniqueColumnTuples, type TableDataItemsUniqueColumns, type TableDataItemsUniqueConstraints, type TableDataMethods, type TemplateLiteralArgs, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, type Timestamps, type ToSQLCtx, type ToSqlValues, type TransactionAdapter, TransactionAdapterClass, type TransactionOptions, TsQueryColumn, TsVectorColumn, UUIDColumn, type UniqueConstraints, type UniqueTableDataItem, UnknownColumn, type UpdateData, type UpsertData, type UpsertThis, VarCharColumn, VirtualColumn, type WhereArg, XMLColumn, _appendQuery, _appendQueryOnUpsertCreate, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, queryToSql, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, rawSqlToSql, referencesArgsToCode, refreshMaterializedView, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, sqlToRawSql, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
11142
+ export { type Adapter, AdapterClass, type AdapterConfigBase, type AdapterParams, type AdapterSchemaConfigOptions, type AfterCommitStandaloneHook, type AfterHook, ArrayColumn, type ArrayColumnValue, type ArrayData, type AsyncState, type BaseNumberData, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, type ColumnSchemaConfig, type ColumnSchemaGetterColumns, type ColumnSchemaGetterTableClass, type ColumnToCodeCtx, type ColumnTypeSchemaArg, type ColumnsByType, type ColumnsShape, type ComputedColumnsFromOptions, type ComputedOptionsConfig, type ComputedOptionsFactory, type CreateCtx, type CreateData, type CreateManyMethodsNames, type CreateMethodsNames, type CreateSelf, CustomTypeColumn, DateBaseColumn, DateColumn, type DateColumnData, DateTimeBaseClass, DateTimeTzBaseClass, Db, type DbDomainArg, type DbExtension, type DbOptions, type DbResult, type DbSharedOptions, type DbSqlMethod, type DbStructureDomainsMap, type DbTableOptionScopes, type DbTableOptions, DecimalColumn, type DecimalColumnData, type DefaultColumnTypes, type DefaultPrivileges, type DefaultSchemaConfig, type DeleteMethodsNames, DomainColumn, DoublePrecisionColumn, type DriverAdapter, DynamicRawSQL, type EmptyObject, type EmptyTuple, EnumColumn, Expression, type ExpressionData, type FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinedShapes, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, type MapTableScopesOption, type MaybeArray, type MaybePromise, type MergeQuery, MoneyColumn, type NoPrimaryKeyOption, type NonUniqDataItem, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, type NumberColumnData, Operators, type OperatorsArray, type OperatorsJson, type OperatorsOrdinalText, type OperatorsText, OrchidOrmInternalError, type Ord, PathColumn, type PickQueryInputType, type PickQueryInternal, type PickQueryQ, type PickQueryRelations, type PickQuerySelectableRelations, type PickQueryShape, PointColumn, PolygonColumn, PostgisGeographyPointColumn, type Query, type QueryAfterHook, type QueryBeforeActionHook, type QueryBeforeHook, type QueryData, QueryError, type QueryHasWhere, type QueryHelperResult, QueryHookUtils, QueryHooks, type QueryInternal, type QueryLogObject, type QueryLogOptions, type QueryLogger, type QueryManyTake, type QueryManyTakeOptional, type QueryOrExpression, type QueryResult, type QueryResultRow, type QueryReturnType, type QuerySchema, type QueryScopes, RawSql, type RawSqlBase, RealColumn, type RecordKeyTrue, type RecordOptionalString, type RecordString, type RecordStringOrNumber, type RecordUnknown, type RefreshMaterializedViewOptions, type RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, type StorageOptions, StringColumn, type StringData, type TableData, type TableDataFn, type TableDataInput, type TableDataItem, type TableDataItemsUniqueColumnTuples, type TableDataItemsUniqueColumns, type TableDataItemsUniqueConstraints, type TableDataMethods, type TemplateLiteralArgs, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, type Timestamps, type ToSQLCtx, type ToSqlValues, type TransactionAdapter, TransactionAdapterClass, type TransactionOptions, TsQueryColumn, TsVectorColumn, UUIDColumn, type UniqueConstraints, type UniqueTableDataItem, UnknownColumn, type UpdateData, type UpsertData, type UpsertThis, VarCharColumn, VirtualColumn, type WhereArg, XMLColumn, _appendQuery, _appendQueryOnUpsertCreate, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, queryToSql, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, rawSqlToSql, referencesArgsToCode, refreshMaterializedView, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, sqlToRawSql, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };