@zenstackhq/runtime 3.0.0-alpha.8 → 3.0.0-beta.1

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.
@@ -1,11 +1,27 @@
1
1
  import Decimal, { Decimal as Decimal$1 } from 'decimal.js';
2
- import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetFields, FieldHasDefault, GetFieldType, FieldIsOptional, NonRelationFields, RelationFields, FieldIsArray, RelationFieldType, GetField, FieldIsRelation, GetEnums, GetEnum, BuiltinType, GetModel, FieldDef, FieldIsRelationArray, FieldType, RelationInfo, DataSourceProviderType, DataSourceProvider, ProcedureDef } from '@zenstackhq/sdk/schema';
3
- import { Generated, Kysely, ExpressionBuilder, OperandExpression, SqlBool, SelectQueryBuilder, Expression, ExpressionWrapper, RootOperationNode, QueryResult, UnknownRow, OperationNode, SqliteDialectConfig, PostgresDialectConfig, KyselyConfig } from 'kysely';
2
+ import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, NonRelationFields, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, GetModel, FieldDef, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, BuiltinType, IsDelegateModel, GetModelDiscriminator, GetSubModels, FieldIsDelegateDiscriminator, FieldType, RelationInfo, FieldIsDelegateRelation, ModelDef, DataSourceProviderType, ProcedureDef } from '@zenstackhq/sdk/schema';
3
+ import { Generated, Kysely, ExpressionBuilder, OperandExpression, SqlBool, SelectQueryBuilder, Expression, ExpressionWrapper, OperationNode, RootOperationNode, QueryResult, UnknownRow, Dialect, KyselyConfig } from 'kysely';
4
4
 
5
5
  type Optional<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
6
6
  type NullableIf<T, Condition extends boolean> = Condition extends true ? T | null : T;
7
+ type _Preserve = Date | Function | Decimal | Uint8Array | JsonObject | JsonValue;
8
+ type _Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
9
+ type Simplify<T, D extends number = 6> = D extends 0 ? T : T extends object ? T extends _Preserve ? T : {
10
+ [K in keyof T]: Simplify<T[K], _Depth[D]>;
11
+ } & {} : T;
7
12
  type WrapType<T, Optional = false, Array = false> = Optional extends true ? T | null : Array extends true ? T[] : T;
8
- type MapBaseType$1<T> = T extends 'String' ? string : T extends 'Boolean' ? boolean : T extends 'Int' | 'Float' ? number : T extends 'BigInt' ? bigint : T extends 'Decimal' ? Decimal : T extends 'DateTime' ? Date : T extends 'Json' ? JsonValue : unknown;
13
+ type TypeMap = {
14
+ String: string;
15
+ Boolean: boolean;
16
+ Int: number;
17
+ Float: number;
18
+ BigInt: bigint;
19
+ Decimal: Decimal;
20
+ DateTime: Date;
21
+ Bytes: Uint8Array;
22
+ Json: JsonValue;
23
+ };
24
+ type MapBaseType$1<T extends string> = T extends keyof TypeMap ? TypeMap[T] : unknown;
9
25
  type JsonValue = string | number | boolean | null | JsonObject | JsonArray;
10
26
  type JsonObject = {
11
27
  [key: string]: JsonValue;
@@ -27,24 +43,30 @@ type XOR<T, U> = T extends object ? (U extends object ? (Without<T, U> & U) | (W
27
43
  type MaybePromise<T> = T | Promise<T>;
28
44
  type PrependParameter<Param, Func> = Func extends (...args: any[]) => infer R ? (p: Param, ...args: Parameters<Func>) => R : never;
29
45
  type OrUndefinedIf<T, Condition extends boolean> = Condition extends true ? T | undefined : T;
46
+ type UnwrapTuplePromises<T extends readonly unknown[]> = {
47
+ [K in keyof T]: Awaited<T[K]>;
48
+ };
30
49
 
31
50
  type ToKyselySchema<Schema extends SchemaDef> = {
32
51
  [Model in GetModels<Schema>]: ToKyselyTable<Schema, Model>;
33
52
  };
34
53
  type ToKysely<Schema extends SchemaDef> = Kysely<ToKyselySchema<Schema>>;
35
54
  type ToKyselyTable<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
36
- [Field in ScalarFields<Schema, Model, false> | ForeignKeyFields<Schema, Model>]: toKyselyFieldType<Schema, Model, Field>;
55
+ [Field in ScalarFields<Schema, Model, false> | ForeignKeyFields<Schema, Model> as GetModelField<Schema, Model, Field>['originModel'] extends string ? never : Field]: toKyselyFieldType<Schema, Model, Field>;
37
56
  };
38
57
  type MapBaseType<T> = T extends 'String' ? string : T extends 'Boolean' ? boolean : T extends 'Int' | 'Float' ? number : T extends 'BigInt' ? bigint : T extends 'Decimal' ? Decimal : T extends 'DateTime' ? string : unknown;
39
58
  type WrapNull<T, Null> = Null extends true ? T | null : T;
40
- type MapType$1<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetFields<Schema, Model>> = WrapNull<MapBaseType<GetFieldType<Schema, Model, Field>>, FieldIsOptional<Schema, Model, Field>>;
41
- type toKyselyFieldType<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetFields<Schema, Model>> = FieldHasDefault<Schema, Model, Field> extends true ? Generated<MapType$1<Schema, Model, Field>> : MapType$1<Schema, Model, Field>;
59
+ type MapType$1<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = WrapNull<MapBaseType<GetModelFieldType<Schema, Model, Field>>, ModelFieldIsOptional<Schema, Model, Field>>;
60
+ type toKyselyFieldType<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = FieldHasDefault<Schema, Model, Field> extends true ? Generated<MapType$1<Schema, Model, Field>> : MapType$1<Schema, Model, Field>;
42
61
 
43
- type DefaultModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Omit = undefined, Optional = false, Array = false> = WrapType<{
44
- [Key in NonRelationFields<Schema, Model> as Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key]: MapFieldType<Schema, Model, Key>;
62
+ type DefaultModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Omit = undefined, Optional = false, Array = false> = WrapType<IsDelegateModel<Schema, Model> extends true ? DelegateUnionResult<Schema, Model, GetSubModels<Schema, Model>, Omit> : {
63
+ [Key in NonRelationFields<Schema, Model> as Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key]: MapModelFieldType<Schema, Model, Key>;
45
64
  }, Optional, Array>;
65
+ type DelegateUnionResult<Schema extends SchemaDef, Model extends GetModels<Schema>, SubModel extends GetModels<Schema>, Omit = undefined> = SubModel extends string ? DefaultModelResult<Schema, SubModel, Omit> & {
66
+ [K in GetModelDiscriminator<Schema, Model>]: SubModel;
67
+ } : never;
46
68
  type ModelSelectResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Select, Omit> = {
47
- [Key in keyof Select as Select[Key] extends false | undefined ? never : Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key extends '_count' ? Select[Key] extends SelectCount<Schema, Model> ? Key : never : Key]: Key extends '_count' ? SelectCountResult<Schema, Model, Select[Key]> : Key extends NonRelationFields<Schema, Model> ? MapFieldType<Schema, Model, Key> : Key extends RelationFields<Schema, Model> ? Select[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Select[Key], FieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, Omit, FieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : never;
69
+ [Key in keyof Select as Select[Key] extends false | undefined ? never : Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key extends '_count' ? Select[Key] extends SelectCount<Schema, Model> ? Key : never : Key]: Key extends '_count' ? SelectCountResult<Schema, Model, Select[Key]> : Key extends NonRelationFields<Schema, Model> ? MapModelFieldType<Schema, Model, Key> : Key extends RelationFields<Schema, Model> ? Select[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? 'select' extends keyof Select[Key] ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Pick<Select[Key], 'select'>, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Pick<Select[Key], 'include' | 'omit'>, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, Omit, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : never;
48
70
  };
49
71
  type SelectCountResult<Schema extends SchemaDef, Model extends GetModels<Schema>, C> = C extends true ? {
50
72
  [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: number;
@@ -60,15 +82,21 @@ type ModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args
60
82
  include: infer I;
61
83
  omit?: infer O;
62
84
  } ? DefaultModelResult<Schema, Model, O> & {
63
- [Key in keyof I & RelationFields<Schema, Model> as I[Key] extends false | undefined ? never : Key]: I[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, I[Key], FieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, undefined, FieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>>;
85
+ [Key in keyof I & RelationFields<Schema, Model> as I[Key] extends false | undefined ? never : Key]: I[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, I[Key], ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, undefined, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>>;
64
86
  } : Args extends {
65
87
  omit: infer O;
66
88
  } ? DefaultModelResult<Schema, Model, O> : DefaultModelResult<Schema, Model>, Optional, Array>;
89
+ type SimplifiedModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args extends SelectIncludeOmit<Schema, Model, boolean> = {}, Optional = false, Array = false> = Simplify<ModelResult<Schema, Model, Args, Optional, Array>>;
90
+ type TypeDefResult<Schema extends SchemaDef, TypeDef extends GetTypeDefs<Schema>> = Optional<{
91
+ [Key in GetTypeDefFields<Schema, TypeDef>]: MapTypeDefFieldType<Schema, TypeDef, Key>;
92
+ }, keyof {
93
+ [Key in GetTypeDefFields<Schema, TypeDef> as TypeDefFieldIsOptional<Schema, TypeDef, Key> extends true ? Key : never]: true;
94
+ }>;
67
95
  type BatchResult = {
68
96
  count: number;
69
97
  };
70
- type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ScalarOnly extends boolean = false> = {
71
- [Key in GetFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : GetFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetFieldType<Schema, Model, Key>, FieldIsOptional<Schema, Model, Key>> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<GetFieldType<Schema, Model, Key>> : PrimitiveFilter<GetFieldType<Schema, Model, Key>, FieldIsOptional<Schema, Model, Key>>;
98
+ type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ScalarOnly extends boolean = false, WithAggregations extends boolean = false> = {
99
+ [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Key>> : GetModelFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations> : PrimitiveFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations>;
72
100
  } & {
73
101
  $expr?: (eb: ExpressionBuilder<ToKyselySchema<Schema>, Model>) => OperandExpression<SqlBool>;
74
102
  } & {
@@ -76,21 +104,26 @@ type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Scala
76
104
  OR?: WhereInput<Schema, Model, ScalarOnly>[];
77
105
  NOT?: OrArray<WhereInput<Schema, Model, ScalarOnly>>;
78
106
  };
79
- type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | {
107
+ type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | ({
80
108
  equals?: NullableIf<keyof GetEnum<Schema, T>, Nullable>;
81
109
  in?: (keyof GetEnum<Schema, T>)[];
82
110
  notIn?: (keyof GetEnum<Schema, T>)[];
83
- not?: EnumFilter<Schema, T, Nullable>;
84
- };
85
- type ArrayFilter<T extends string> = {
86
- equals?: MapBaseType$1<T>[];
87
- has?: MapBaseType$1<T>;
88
- hasEvery?: MapBaseType$1<T>[];
89
- hasSome?: MapBaseType$1<T>[];
111
+ not?: EnumFilter<Schema, T, Nullable, WithAggregations>;
112
+ } & (WithAggregations extends true ? {
113
+ _count?: NumberFilter<Schema, 'Int', false, false>;
114
+ _min?: EnumFilter<Schema, T, false, false>;
115
+ _max?: EnumFilter<Schema, T, false, false>;
116
+ } : {}));
117
+ type ArrayFilter<Schema extends SchemaDef, T extends string> = {
118
+ equals?: MapScalarType<Schema, T>[] | null;
119
+ has?: MapScalarType<Schema, T> | null;
120
+ hasEvery?: MapScalarType<Schema, T>[];
121
+ hasSome?: MapScalarType<Schema, T>[];
90
122
  isEmpty?: boolean;
91
123
  };
92
- type PrimitiveFilter<T extends string, Nullable extends boolean> = T extends 'String' ? StringFilter<Nullable> : T extends 'Int' | 'Float' | 'Decimal' | 'BigInt' ? NumberFilter<T, Nullable> : T extends 'Boolean' ? BooleanFilter<Nullable> : T extends 'DateTime' ? DateTimeFilter<Nullable> : T extends 'Json' ? 'Not implemented yet' : never;
93
- type CommonPrimitiveFilter<DataType, T extends BuiltinType, Nullable extends boolean> = {
124
+ type MapScalarType<Schema extends SchemaDef, T extends string> = T extends GetEnums<Schema> ? keyof GetEnum<Schema, T> : MapBaseType$1<T>;
125
+ type PrimitiveFilter<Schema extends SchemaDef, T extends string, Nullable extends boolean, WithAggregations extends boolean> = T extends 'String' ? StringFilter<Schema, Nullable, WithAggregations> : T extends 'Int' | 'Float' | 'Decimal' | 'BigInt' ? NumberFilter<Schema, T, Nullable, WithAggregations> : T extends 'Boolean' ? BooleanFilter<Schema, Nullable, WithAggregations> : T extends 'DateTime' ? DateTimeFilter<Schema, Nullable, WithAggregations> : T extends 'Bytes' ? BytesFilter<Schema, Nullable, WithAggregations> : T extends 'Json' ? 'Not implemented yet' : never;
126
+ type CommonPrimitiveFilter<Schema extends SchemaDef, DataType, T extends BuiltinType, Nullable extends boolean, WithAggregations extends boolean> = {
94
127
  equals?: NullableIf<DataType, Nullable>;
95
128
  in?: DataType[];
96
129
  notIn?: DataType[];
@@ -98,30 +131,53 @@ type CommonPrimitiveFilter<DataType, T extends BuiltinType, Nullable extends boo
98
131
  lte?: DataType;
99
132
  gt?: DataType;
100
133
  gte?: DataType;
101
- not?: PrimitiveFilter<T, Nullable>;
134
+ not?: PrimitiveFilter<Schema, T, Nullable, WithAggregations>;
102
135
  };
103
- type StringFilter<Nullable extends boolean> = NullableIf<string, Nullable> | (CommonPrimitiveFilter<string, 'String', Nullable> & {
136
+ type StringFilter<Schema extends SchemaDef, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<string, Nullable> | (CommonPrimitiveFilter<Schema, string, 'String', Nullable, WithAggregations> & {
104
137
  contains?: string;
105
138
  startsWith?: string;
106
139
  endsWith?: string;
140
+ } & (WithAggregations extends true ? {
141
+ _count?: NumberFilter<Schema, 'Int', false, false>;
142
+ _min?: StringFilter<Schema, false, false>;
143
+ _max?: StringFilter<Schema, false, false>;
144
+ } : {}) & (ProviderSupportsCaseSensitivity<Schema> extends true ? {
107
145
  mode?: 'default' | 'insensitive';
108
- });
109
- type NumberFilter<T extends 'Int' | 'Float' | 'Decimal' | 'BigInt', Nullable extends boolean> = NullableIf<number | bigint, Nullable> | CommonPrimitiveFilter<number, T, Nullable>;
110
- type DateTimeFilter<Nullable extends boolean> = NullableIf<Date | string, Nullable> | CommonPrimitiveFilter<Date | string, 'DateTime', Nullable>;
111
- type BytesFilter<Nullable extends boolean> = NullableIf<Uint8Array | Buffer, Nullable> | {
146
+ } : {}));
147
+ type NumberFilter<Schema extends SchemaDef, T extends 'Int' | 'Float' | 'Decimal' | 'BigInt', Nullable extends boolean, WithAggregations extends boolean> = NullableIf<number | bigint, Nullable> | (CommonPrimitiveFilter<Schema, number, T, Nullable, WithAggregations> & (WithAggregations extends true ? {
148
+ _count?: NumberFilter<Schema, 'Int', false, false>;
149
+ _avg?: NumberFilter<Schema, T, false, false>;
150
+ _sum?: NumberFilter<Schema, T, false, false>;
151
+ _min?: NumberFilter<Schema, T, false, false>;
152
+ _max?: NumberFilter<Schema, T, false, false>;
153
+ } : {}));
154
+ type DateTimeFilter<Schema extends SchemaDef, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<Date | string, Nullable> | (CommonPrimitiveFilter<Schema, Date | string, 'DateTime', Nullable, WithAggregations> & (WithAggregations extends true ? {
155
+ _count?: NumberFilter<Schema, 'Int', false, false>;
156
+ _min?: DateTimeFilter<Schema, false, false>;
157
+ _max?: DateTimeFilter<Schema, false, false>;
158
+ } : {}));
159
+ type BytesFilter<Schema extends SchemaDef, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<Uint8Array | Buffer, Nullable> | ({
112
160
  equals?: NullableIf<Uint8Array, Nullable>;
113
161
  in?: Uint8Array[];
114
162
  notIn?: Uint8Array[];
115
- not?: BytesFilter<Nullable>;
116
- };
117
- type BooleanFilter<Nullable extends boolean> = NullableIf<boolean, Nullable> | {
163
+ not?: BytesFilter<Schema, Nullable, WithAggregations>;
164
+ } & (WithAggregations extends true ? {
165
+ _count?: NumberFilter<Schema, 'Int', false, false>;
166
+ _min?: BytesFilter<Schema, false, false>;
167
+ _max?: BytesFilter<Schema, false, false>;
168
+ } : {}));
169
+ type BooleanFilter<Schema extends SchemaDef, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<boolean, Nullable> | ({
118
170
  equals?: NullableIf<boolean, Nullable>;
119
- not?: BooleanFilter<Nullable>;
120
- };
171
+ not?: BooleanFilter<Schema, Nullable, WithAggregations>;
172
+ } & (WithAggregations extends true ? {
173
+ _count?: NumberFilter<Schema, 'Int', false, false>;
174
+ _min?: BooleanFilter<Schema, false, false>;
175
+ _max?: BooleanFilter<Schema, false, false>;
176
+ } : {}));
121
177
  type SortOrder = 'asc' | 'desc';
122
178
  type NullsOrder = 'first' | 'last';
123
179
  type OrderBy<Schema extends SchemaDef, Model extends GetModels<Schema>, WithRelation extends boolean, WithAggregation extends boolean> = {
124
- [Key in NonRelationFields<Schema, Model>]?: FieldIsOptional<Schema, Model, Key> extends true ? SortOrder | {
180
+ [Key in NonRelationFields<Schema, Model>]?: ModelFieldIsOptional<Schema, Model, Key> extends true ? SortOrder | {
125
181
  sort: SortOrder;
126
182
  nulls?: NullsOrder;
127
183
  } : SortOrder;
@@ -130,47 +186,41 @@ type OrderBy<Schema extends SchemaDef, Model extends GetModels<Schema>, WithRela
130
186
  _count?: SortOrder;
131
187
  } : OrderBy<Schema, RelationFieldType<Schema, Model, Key>, WithRelation, WithAggregation>;
132
188
  } : {}) & (WithAggregation extends true ? {
133
- _count?: OrderBy<Schema, Model, WithRelation, false>;
189
+ _count?: OrderBy<Schema, Model, false, false>;
190
+ _min?: MinMaxInput<Schema, Model, SortOrder>;
191
+ _max?: MinMaxInput<Schema, Model, SortOrder>;
134
192
  } & (NumericFields<Schema, Model> extends never ? {} : {
135
- _avg?: SumAvgInput<Schema, Model>;
136
- _sum?: SumAvgInput<Schema, Model>;
137
- _min?: MinMaxInput<Schema, Model>;
138
- _max?: MinMaxInput<Schema, Model>;
193
+ _avg?: SumAvgInput<Schema, Model, SortOrder>;
194
+ _sum?: SumAvgInput<Schema, Model, SortOrder>;
139
195
  }) : {});
140
196
  type WhereUniqueInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = AtLeast<{
141
197
  [Key in keyof GetModel<Schema, Model>['uniqueFields']]?: GetModel<Schema, Model>['uniqueFields'][Key] extends Pick<FieldDef, 'type'> ? MapFieldDefType<Schema, GetModel<Schema, Model>['uniqueFields'][Key]> : {
142
198
  [Key1 in keyof GetModel<Schema, Model>['uniqueFields'][Key]]: GetModel<Schema, Model>['uniqueFields'][Key][Key1] extends Pick<FieldDef, 'type'> ? MapFieldDefType<Schema, GetModel<Schema, Model>['uniqueFields'][Key][Key1]> : never;
143
199
  };
144
200
  } & WhereInput<Schema, Model>, Extract<keyof GetModel<Schema, Model>['uniqueFields'], string>>;
145
- type OmitFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
146
- [Key in NonRelationFields<Schema, Model>]?: true;
201
+ type OmitInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
202
+ [Key in NonRelationFields<Schema, Model>]?: boolean;
147
203
  };
148
204
  type SelectIncludeOmit<Schema extends SchemaDef, Model extends GetModels<Schema>, AllowCount extends boolean> = {
149
- select?: Select<Schema, Model, AllowCount, boolean>;
150
- include?: Include<Schema, Model>;
151
- omit?: OmitFields<Schema, Model>;
152
- };
153
- type Distinct<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
154
- distinct?: OrArray<NonRelationFields<Schema, Model>>;
155
- };
156
- type Cursor<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
157
- cursor?: WhereUniqueInput<Schema, Model>;
205
+ select?: SelectInput<Schema, Model, AllowCount, boolean>;
206
+ include?: IncludeInput<Schema, Model>;
207
+ omit?: OmitInput<Schema, Model>;
158
208
  };
159
- type Select<Schema extends SchemaDef, Model extends GetModels<Schema>, AllowCount extends boolean, AllowRelation extends boolean = true> = {
160
- [Key in NonRelationFields<Schema, Model>]?: true;
161
- } & (AllowRelation extends true ? Include<Schema, Model> : {}) & // relation fields
162
- (AllowCount extends true ? {
209
+ type SelectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, AllowCount extends boolean = true, AllowRelation extends boolean = true> = {
210
+ [Key in NonRelationFields<Schema, Model>]?: boolean;
211
+ } & (AllowRelation extends true ? IncludeInput<Schema, Model> : {}) & // relation fields
212
+ (AllowCount extends true ? HasToManyRelations<Schema, Model> extends true ? {
163
213
  _count?: SelectCount<Schema, Model>;
164
- } : {});
165
- type SelectCount<Schema extends SchemaDef, Model extends GetModels<Schema>> = true | {
214
+ } : {} : {});
215
+ type SelectCount<Schema extends SchemaDef, Model extends GetModels<Schema>> = boolean | {
166
216
  select: {
167
- [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: true | {
217
+ [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]?: boolean | {
168
218
  where: WhereInput<Schema, RelationFieldType<Schema, Model, Key>, false>;
169
219
  };
170
220
  };
171
221
  };
172
- type Include<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
173
- [Key in RelationFields<Schema, Model>]?: boolean | FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>, FieldIsArray<Schema, Model, Key> extends true ? true : FieldIsOptional<Schema, Model, Key> extends true ? true : false>;
222
+ type IncludeInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
223
+ [Key in RelationFields<Schema, Model>]?: boolean | FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>, FieldIsArray<Schema, Model, Key> extends true ? true : ModelFieldIsOptional<Schema, Model, Key> extends true ? true : false>;
174
224
  };
175
225
  type Subset<T, U> = {
176
226
  [key in keyof T]: key extends keyof U ? T[key] : never;
@@ -190,83 +240,94 @@ type ToManyRelationFilter<Schema extends SchemaDef, Model extends GetModels<Sche
190
240
  none?: WhereInput<Schema, RelationFieldType<Schema, Model, Field>>;
191
241
  };
192
242
  type ToOneRelationFilter<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>> & {
193
- is?: NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>>, FieldIsOptional<Schema, Model, Field>>;
194
- isNot?: NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>>, FieldIsOptional<Schema, Model, Field>>;
195
- }, FieldIsOptional<Schema, Model, Field>>;
243
+ is?: NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>>, ModelFieldIsOptional<Schema, Model, Field>>;
244
+ isNot?: NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>>, ModelFieldIsOptional<Schema, Model, Field>>;
245
+ }, ModelFieldIsOptional<Schema, Model, Field>>;
196
246
  type RelationFilter<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? ToManyRelationFilter<Schema, Model, Field> : ToOneRelationFilter<Schema, Model, Field>;
197
- type MapFieldType<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetFields<Schema, Model>> = MapFieldDefType<Schema, GetField<Schema, Model, Field>>;
198
- type MapFieldDefType<Schema extends SchemaDef, T extends Pick<FieldDef, 'type' | 'optional' | 'array'>> = WrapType<T['type'] extends GetEnums<Schema> ? keyof GetEnum<Schema, T['type']> : MapBaseType$1<T['type']>, T['optional'], T['array']>;
247
+ type MapModelFieldType<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = MapFieldDefType<Schema, GetModelField<Schema, Model, Field>>;
248
+ type MapTypeDefFieldType<Schema extends SchemaDef, TypeDef extends GetTypeDefs<Schema>, Field extends GetTypeDefFields<Schema, TypeDef>> = MapFieldDefType<Schema, GetTypeDefField<Schema, TypeDef, Field>>;
249
+ type MapFieldDefType<Schema extends SchemaDef, T extends Pick<FieldDef, 'type' | 'optional' | 'array'>> = WrapType<T['type'] extends GetEnums<Schema> ? keyof GetEnum<Schema, T['type']> : T['type'] extends GetTypeDefs<Schema> ? TypeDefResult<Schema, T['type']> & Record<string, unknown> : MapBaseType$1<T['type']>, T['optional'], T['array']>;
199
250
  type OptionalFieldsForCreate<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
200
- [Key in GetFields<Schema, Model> as FieldIsOptional<Schema, Model, Key> extends true ? Key : FieldHasDefault<Schema, Model, Key> extends true ? Key : GetField<Schema, Model, Key>['updatedAt'] extends true ? Key : FieldIsRelationArray<Schema, Model, Key> extends true ? Key : never]: GetField<Schema, Model, Key>;
251
+ [Key in GetModelFields<Schema, Model> as ModelFieldIsOptional<Schema, Model, Key> extends true ? Key : FieldHasDefault<Schema, Model, Key> extends true ? Key : FieldIsArray<Schema, Model, Key> extends true ? Key : GetModelField<Schema, Model, Key>['updatedAt'] extends true ? Key : never]: GetModelField<Schema, Model, Key>;
201
252
  };
202
- type GetRelation<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetFields<Schema, Model>> = GetField<Schema, Model, Field>['relation'];
203
- type OppositeRelation<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetFields<Schema, Model>, FT = FieldType<Schema, Model, Field>> = FT extends GetModels<Schema> ? GetRelation<Schema, Model, Field> extends RelationInfo ? GetRelation<Schema, Model, Field>['opposite'] extends GetFields<Schema, FT> ? Schema['models'][FT]['fields'][GetRelation<Schema, Model, Field>['opposite']]['relation'] : never : never : never;
204
- type OppositeRelationFields<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetFields<Schema, Model>, Opposite = OppositeRelation<Schema, Model, Field>> = Opposite extends RelationInfo ? (Opposite['fields'] extends string[] ? Opposite['fields'] : []) : [];
205
- type OppositeRelationAndFK<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetFields<Schema, Model>, FT = FieldType<Schema, Model, Field>, Relation = GetField<Schema, Model, Field>['relation'], Opposite = Relation extends RelationInfo ? Relation['opposite'] : never> = FT extends GetModels<Schema> ? Opposite extends GetFields<Schema, FT> ? Opposite | OppositeRelationFields<Schema, Model, Field>[number] : never : never;
206
- type FindArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Collection extends boolean, AllowFilter extends boolean = true> = (Collection extends true ? {
253
+ type GetRelation<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelField<Schema, Model, Field>['relation'];
254
+ type OppositeRelation<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, FT = FieldType<Schema, Model, Field>> = FT extends GetModels<Schema> ? GetRelation<Schema, Model, Field> extends RelationInfo ? GetRelation<Schema, Model, Field>['opposite'] extends GetModelFields<Schema, FT> ? Schema['models'][FT]['fields'][GetRelation<Schema, Model, Field>['opposite']]['relation'] : never : never : never;
255
+ type OppositeRelationFields<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Opposite = OppositeRelation<Schema, Model, Field>> = Opposite extends RelationInfo ? (Opposite['fields'] extends string[] ? Opposite['fields'] : []) : [];
256
+ type OppositeRelationAndFK<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, FT = FieldType<Schema, Model, Field>, Relation = GetModelField<Schema, Model, Field>['relation'], Opposite = Relation extends RelationInfo ? Relation['opposite'] : never> = FT extends GetModels<Schema> ? Opposite extends GetModelFields<Schema, FT> ? Opposite | OppositeRelationFields<Schema, Model, Field>[number] : never : never;
257
+ type FilterArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
258
+ where?: WhereInput<Schema, Model>;
259
+ };
260
+ type SortAndTakeArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
207
261
  skip?: number;
208
262
  take?: number;
209
263
  orderBy?: OrArray<OrderBy<Schema, Model, true, false>>;
210
- } : {}) & (AllowFilter extends true ? {
211
- where?: WhereInput<Schema, Model>;
212
- } : {}) & SelectIncludeOmit<Schema, Model, Collection> & Distinct<Schema, Model> & Cursor<Schema, Model>;
264
+ cursor?: WhereUniqueInput<Schema, Model>;
265
+ };
266
+ type FindArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Collection extends boolean, AllowFilter extends boolean = true> = ProviderSupportsDistinct<Schema> extends true ? (Collection extends true ? SortAndTakeArgs<Schema, Model> & {
267
+ distinct?: OrArray<NonRelationFields<Schema, Model>>;
268
+ } : {}) & (AllowFilter extends true ? FilterArgs<Schema, Model> : {}) & SelectIncludeOmit<Schema, Model, Collection> : (Collection extends true ? SortAndTakeArgs<Schema, Model> : {}) & (AllowFilter extends true ? FilterArgs<Schema, Model> : {}) & SelectIncludeOmit<Schema, Model, Collection>;
269
+ type FindManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = FindArgs<Schema, Model, true>;
270
+ type FindFirstArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = FindArgs<Schema, Model, false>;
213
271
  type FindUniqueArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
214
272
  where?: WhereUniqueInput<Schema, Model>;
215
273
  } & SelectIncludeOmit<Schema, Model, true>;
216
274
  type CreateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
217
275
  data: CreateInput<Schema, Model>;
218
- select?: Select<Schema, Model, true>;
219
- include?: Include<Schema, Model>;
220
- omit?: OmitFields<Schema, Model>;
276
+ select?: SelectInput<Schema, Model, true>;
277
+ include?: IncludeInput<Schema, Model>;
278
+ omit?: OmitInput<Schema, Model>;
221
279
  };
222
- type CreateManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = CreateManyPayload<Schema, Model>;
223
- type CreateManyAndReturnArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = CreateManyPayload<Schema, Model> & {
224
- select?: Select<Schema, Model, false, false>;
225
- omit?: OmitFields<Schema, Model>;
280
+ type CreateManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = CreateManyInput<Schema, Model>;
281
+ type CreateManyAndReturnArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = CreateManyInput<Schema, Model> & {
282
+ select?: SelectInput<Schema, Model, false, false>;
283
+ omit?: OmitInput<Schema, Model>;
226
284
  };
227
285
  type OptionalWrap<Schema extends SchemaDef, Model extends GetModels<Schema>, T extends object> = Optional<T, keyof T & OptionalFieldsForCreate<Schema, Model>>;
228
286
  type CreateScalarPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
229
- [Key in ScalarFields<Schema, Model, false>]: ScalarCreatePayload<Schema, Model, Key>;
287
+ [Key in ScalarFields<Schema, Model, false> as FieldIsDelegateDiscriminator<Schema, Model, Key> extends true ? never : Key]: ScalarCreatePayload<Schema, Model, Key>;
230
288
  }>;
231
- type ScalarCreatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends ScalarFields<Schema, Model, false>> = MapFieldType<Schema, Model, Field> | (FieldIsArray<Schema, Model, Field> extends true ? {
232
- set?: MapFieldType<Schema, Model, Field>[];
289
+ type ScalarCreatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends ScalarFields<Schema, Model, false>> = MapModelFieldType<Schema, Model, Field> | (FieldIsArray<Schema, Model, Field> extends true ? {
290
+ set?: MapModelFieldType<Schema, Model, Field>;
233
291
  } : never);
234
292
  type CreateFKPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
235
- [Key in ForeignKeyFields<Schema, Model>]: MapFieldType<Schema, Model, Key>;
293
+ [Key in ForeignKeyFields<Schema, Model>]: MapModelFieldType<Schema, Model, Key>;
236
294
  }>;
237
295
  type CreateRelationFieldPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = Omit<{
296
+ connectOrCreate?: ConnectOrCreateInput<Schema, Model, Field>;
238
297
  create?: NestedCreateInput<Schema, Model, Field>;
239
298
  createMany?: NestedCreateManyInput<Schema, Model, Field>;
240
299
  connect?: ConnectInput<Schema, Model, Field>;
241
- connectOrCreate?: ConnectOrCreateInput<Schema, Model, Field>;
242
- }, FieldIsArray<Schema, Model, Field> extends true ? never : 'createMany'>;
300
+ }, (FieldIsArray<Schema, Model, Field> extends true ? never : 'createMany') | (FieldIsDelegateRelation<Schema, Model, Field> extends true ? 'create' | 'createMany' | 'connectOrCreate' : never)>;
243
301
  type CreateRelationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
244
302
  [Key in RelationFields<Schema, Model>]: CreateRelationFieldPayload<Schema, Model, Key>;
245
303
  }>;
246
- type CreateWithFKInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = CreateScalarPayload<Schema, Model> & CreateFKPayload<Schema, Model>;
304
+ type CreateWithFKInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = CreateScalarPayload<Schema, Model> & CreateFKPayload<Schema, Model> & CreateWithNonOwnedRelationPayload<Schema, Model>;
247
305
  type CreateWithRelationInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = CreateScalarPayload<Schema, Model> & CreateRelationPayload<Schema, Model>;
306
+ type CreateWithNonOwnedRelationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
307
+ [Key in NonOwnedRelationFields<Schema, Model>]: CreateRelationFieldPayload<Schema, Model, Key>;
308
+ }>;
248
309
  type ConnectOrCreatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = {
249
310
  where: WhereUniqueInput<Schema, Model>;
250
311
  create: CreateInput<Schema, Model, Without>;
251
312
  };
252
- type CreateManyPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = {
313
+ type CreateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = {
253
314
  data: OrArray<Omit<CreateScalarPayload<Schema, Model>, Without> & Omit<CreateFKPayload<Schema, Model>, Without>>;
254
315
  skipDuplicates?: boolean;
255
316
  };
256
317
  type CreateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = XOR<Omit<CreateWithFKInput<Schema, Model>, Without>, Omit<CreateWithRelationInput<Schema, Model>, Without>>;
257
318
  type NestedCreateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<CreateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>, FieldIsArray<Schema, Model, Field>>;
258
- type NestedCreateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = CreateManyPayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
319
+ type NestedCreateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = CreateManyInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
259
320
  type UpdateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
260
321
  data: UpdateInput<Schema, Model>;
261
322
  where: WhereUniqueInput<Schema, Model>;
262
- select?: Select<Schema, Model, true>;
263
- include?: Include<Schema, Model>;
264
- omit?: OmitFields<Schema, Model>;
323
+ select?: SelectInput<Schema, Model, true>;
324
+ include?: IncludeInput<Schema, Model>;
325
+ omit?: OmitInput<Schema, Model>;
265
326
  };
266
327
  type UpdateManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = UpdateManyPayload<Schema, Model>;
267
328
  type UpdateManyAndReturnArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = UpdateManyPayload<Schema, Model> & {
268
- select?: Select<Schema, Model, false, false>;
269
- omit?: OmitFields<Schema, Model>;
329
+ select?: SelectInput<Schema, Model, false, false>;
330
+ omit?: OmitInput<Schema, Model>;
270
331
  };
271
332
  type UpdateManyPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = {
272
333
  data: OrArray<UpdateScalarInput<Schema, Model, Without>>;
@@ -277,29 +338,29 @@ type UpsertArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
277
338
  create: CreateInput<Schema, Model>;
278
339
  update: UpdateInput<Schema, Model>;
279
340
  where: WhereUniqueInput<Schema, Model>;
280
- select?: Select<Schema, Model, true>;
281
- include?: Include<Schema, Model>;
282
- omit?: OmitFields<Schema, Model>;
341
+ select?: SelectInput<Schema, Model, true>;
342
+ include?: IncludeInput<Schema, Model>;
343
+ omit?: OmitInput<Schema, Model>;
283
344
  };
284
345
  type UpdateScalarInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = Omit<{
285
- [Key in NonRelationFields<Schema, Model>]?: ScalarUpdatePayload<Schema, Model, Key>;
346
+ [Key in NonRelationFields<Schema, Model> as FieldIsDelegateDiscriminator<Schema, Model, Key> extends true ? never : Key]?: ScalarUpdatePayload<Schema, Model, Key>;
286
347
  }, Without>;
287
- type ScalarUpdatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends NonRelationFields<Schema, Model>> = MapFieldType<Schema, Model, Field> | (Field extends NumericFields<Schema, Model> ? {
288
- set?: NullableIf<number, FieldIsOptional<Schema, Model, Field>>;
348
+ type ScalarUpdatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends NonRelationFields<Schema, Model>> = MapModelFieldType<Schema, Model, Field> | (Field extends NumericFields<Schema, Model> ? {
349
+ set?: NullableIf<number, ModelFieldIsOptional<Schema, Model, Field>>;
289
350
  increment?: number;
290
351
  decrement?: number;
291
352
  multiply?: number;
292
353
  divide?: number;
293
354
  } : never) | (FieldIsArray<Schema, Model, Field> extends true ? {
294
- set?: MapFieldType<Schema, Model, Field>[];
295
- push?: OrArray<MapFieldType<Schema, Model, Field>, true>;
355
+ set?: MapModelFieldType<Schema, Model, Field>[];
356
+ push?: OrArray<MapModelFieldType<Schema, Model, Field>, true>;
296
357
  } : never);
297
358
  type UpdateRelationInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = Omit<{
298
359
  [Key in RelationFields<Schema, Model>]?: UpdateRelationFieldPayload<Schema, Model, Key>;
299
360
  }, Without>;
300
361
  type UpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = UpdateScalarInput<Schema, Model, Without> & UpdateRelationInput<Schema, Model, Without>;
301
362
  type UpdateRelationFieldPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? ToManyRelationUpdateInput<Schema, Model, Field> : ToOneRelationUpdateInput<Schema, Model, Field>;
302
- type ToManyRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = {
363
+ type ToManyRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = Omit<{
303
364
  create?: NestedCreateInput<Schema, Model, Field>;
304
365
  createMany?: NestedCreateManyInput<Schema, Model, Field>;
305
366
  connect?: ConnectInput<Schema, Model, Field>;
@@ -311,22 +372,22 @@ type ToManyRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels
311
372
  delete?: NestedDeleteInput<Schema, Model, Field>;
312
373
  deleteMany?: NestedDeleteManyInput<Schema, Model, Field>;
313
374
  set?: SetRelationInput<Schema, Model, Field>;
314
- };
315
- type ToOneRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = {
375
+ }, FieldIsDelegateRelation<Schema, Model, Field> extends true ? 'create' | 'createMany' | 'connectOrCreate' | 'upsert' : never>;
376
+ type ToOneRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = Omit<{
316
377
  create?: NestedCreateInput<Schema, Model, Field>;
317
378
  connect?: ConnectInput<Schema, Model, Field>;
318
379
  connectOrCreate?: ConnectOrCreateInput<Schema, Model, Field>;
319
380
  update?: NestedUpdateInput<Schema, Model, Field>;
320
381
  upsert?: NestedUpsertInput<Schema, Model, Field>;
321
- } & (FieldIsOptional<Schema, Model, Field> extends true ? {
382
+ } & (ModelFieldIsOptional<Schema, Model, Field> extends true ? {
322
383
  disconnect?: DisconnectInput<Schema, Model, Field>;
323
384
  delete?: NestedDeleteInput<Schema, Model, Field>;
324
- } : {});
385
+ } : {}), FieldIsDelegateRelation<Schema, Model, Field> extends true ? 'create' | 'connectOrCreate' | 'upsert' : never>;
325
386
  type DeleteArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
326
387
  where: WhereUniqueInput<Schema, Model>;
327
- select?: Select<Schema, Model, true>;
328
- include?: Include<Schema, Model>;
329
- omit?: OmitFields<Schema, Model>;
388
+ select?: SelectInput<Schema, Model, true>;
389
+ include?: IncludeInput<Schema, Model>;
390
+ omit?: OmitInput<Schema, Model>;
330
391
  };
331
392
  type DeleteManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
332
393
  where?: WhereInput<Schema, Model>;
@@ -352,20 +413,20 @@ type AggregateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> =
352
413
  orderBy?: OrArray<OrderBy<Schema, Model, true, false>>;
353
414
  } & {
354
415
  _count?: true | CountAggregateInput<Schema, Model>;
416
+ _min?: MinMaxInput<Schema, Model, true>;
417
+ _max?: MinMaxInput<Schema, Model, true>;
355
418
  } & (NumericFields<Schema, Model> extends never ? {} : {
356
- _avg?: SumAvgInput<Schema, Model>;
357
- _sum?: SumAvgInput<Schema, Model>;
358
- _min?: MinMaxInput<Schema, Model>;
359
- _max?: MinMaxInput<Schema, Model>;
419
+ _avg?: SumAvgInput<Schema, Model, true>;
420
+ _sum?: SumAvgInput<Schema, Model, true>;
360
421
  });
361
422
  type NumericFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
362
- [Key in GetFields<Schema, Model> as GetFieldType<Schema, Model, Key> extends 'Int' | 'Float' | 'BigInt' | 'Decimal' ? FieldIsArray<Schema, Model, Key> extends true ? never : Key : never]: GetField<Schema, Model, Key>;
423
+ [Key in GetModelFields<Schema, Model> as GetModelFieldType<Schema, Model, Key> extends 'Int' | 'Float' | 'BigInt' | 'Decimal' ? FieldIsArray<Schema, Model, Key> extends true ? never : Key : never]: GetModelField<Schema, Model, Key>;
363
424
  };
364
- type SumAvgInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
365
- [Key in NumericFields<Schema, Model>]?: true;
425
+ type SumAvgInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
426
+ [Key in NumericFields<Schema, Model>]?: ValueType;
366
427
  };
367
- type MinMaxInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
368
- [Key in GetFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? never : FieldIsRelation<Schema, Model, Key> extends true ? never : Key]?: true;
428
+ type MinMaxInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
429
+ [Key in GetModelFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? never : FieldIsRelation<Schema, Model, Key> extends true ? never : Key]?: ValueType;
369
430
  };
370
431
  type AggregateResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args extends AggregateArgs<Schema, Model>> = (Args extends {
371
432
  _count: infer Count;
@@ -391,22 +452,23 @@ type AggregateResult<Schema extends SchemaDef, Model extends GetModels<Schema>,
391
452
  type AggCommonOutput<Input> = Input extends true ? number : Input extends {} ? {
392
453
  [Key in keyof Input]: number;
393
454
  } : never;
455
+ type GroupByHaving<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<WhereInput<Schema, Model, true, true>, '$expr'>;
394
456
  type GroupByArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
395
457
  where?: WhereInput<Schema, Model>;
396
458
  orderBy?: OrArray<OrderBy<Schema, Model, false, true>>;
397
459
  by: NonRelationFields<Schema, Model> | NonEmptyArray<NonRelationFields<Schema, Model>>;
398
- having?: WhereInput<Schema, Model, true>;
460
+ having?: GroupByHaving<Schema, Model>;
399
461
  take?: number;
400
462
  skip?: number;
401
463
  _count?: true | CountAggregateInput<Schema, Model>;
464
+ _min?: MinMaxInput<Schema, Model, true>;
465
+ _max?: MinMaxInput<Schema, Model, true>;
402
466
  } & (NumericFields<Schema, Model> extends never ? {} : {
403
- _avg?: SumAvgInput<Schema, Model>;
404
- _sum?: SumAvgInput<Schema, Model>;
405
- _min?: MinMaxInput<Schema, Model>;
406
- _max?: MinMaxInput<Schema, Model>;
467
+ _avg?: SumAvgInput<Schema, Model, true>;
468
+ _sum?: SumAvgInput<Schema, Model, true>;
407
469
  });
408
470
  type GroupByResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args extends GroupByArgs<Schema, Model>> = Array<{
409
- [Key in NonRelationFields<Schema, Model> as Key extends ValueOfPotentialTuple<Args['by']> ? Key : never]: MapFieldType<Schema, Model, Key>;
471
+ [Key in NonRelationFields<Schema, Model> as Key extends ValueOfPotentialTuple<Args['by']> ? Key : never]: MapModelFieldType<Schema, Model, Key>;
410
472
  } & (Args extends {
411
473
  _count: infer Count;
412
474
  } ? {
@@ -440,31 +502,51 @@ type NestedUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>
440
502
  data: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
441
503
  }, UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>>;
442
504
  type NestedUpsertInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<{
443
- where: WhereUniqueInput<Schema, Model>;
505
+ where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
444
506
  create: CreateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
445
507
  update: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
446
508
  }, FieldIsArray<Schema, Model, Field>>;
447
509
  type NestedUpdateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<UpdateManyPayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>>;
448
510
  type NestedDeleteInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>, true> : boolean | WhereInput<Schema, RelationFieldType<Schema, Model, Field>>;
449
511
  type NestedDeleteManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<WhereInput<Schema, RelationFieldType<Schema, Model, Field>, true>>;
512
+ type NonOwnedRelationFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
513
+ [Key in RelationFields<Schema, Model> as GetModelField<Schema, Model, Key>['relation'] extends {
514
+ references: unknown[];
515
+ } ? never : Key]: true;
516
+ };
517
+ type HasToManyRelations<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
518
+ [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: true;
519
+ } extends never ? false : true;
520
+ type ProviderSupportsCaseSensitivity<Schema extends SchemaDef> = Schema['provider']['type'] extends 'postgresql' ? true : false;
521
+ type ProviderSupportsDistinct<Schema extends SchemaDef> = Schema['provider']['type'] extends 'postgresql' ? true : false;
450
522
 
451
523
  type AuthType<Schema extends SchemaDef> = string extends GetModels<Schema> ? Record<string, unknown> : Schema['authType'] extends GetModels<Schema> ? Partial<ModelResult<Schema, Schema['authType']>> : never;
452
524
 
525
+ /**
526
+ * Client API methods that are not supported in transactions.
527
+ */
528
+ declare const TRANSACTION_UNSUPPORTED_METHODS: readonly ["$transaction", "$disconnect", "$use"];
529
+ /**
530
+ * Logical combinators used in filters.
531
+ */
532
+ declare const LOGICAL_COMBINATORS: readonly ["AND", "OR", "NOT"];
533
+
453
534
  declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
454
535
  protected readonly schema: Schema;
455
536
  protected readonly options: ClientOptions<Schema>;
456
537
  constructor(schema: Schema, options: ClientOptions<Schema>);
457
- abstract get provider(): DataSourceProviderType;
458
- transformPrimitive(value: unknown, _type: BuiltinType): unknown;
459
- abstract buildRelationSelection(query: SelectQueryBuilder<any, any, any>, model: string, relationField: string, parentAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>): SelectQueryBuilder<any, any, any>;
460
- abstract buildSkipTake(query: SelectQueryBuilder<any, any, any>, skip: number | undefined, take: number | undefined): SelectQueryBuilder<any, any, any>;
538
+ transformPrimitive(value: unknown, _type: BuiltinType, _forArrayField: boolean): unknown;
539
+ buildSelectModel(eb: ExpressionBuilder<any, any>, model: string, modelAlias: string): SelectQueryBuilder<any, any, {}>;
540
+ buildFilterSortTake(model: GetModels<Schema>, args: FindArgs<Schema, GetModels<Schema>, true>, query: SelectQueryBuilder<any, any, {}>, modelAlias: string): SelectQueryBuilder<any, any, {}>;
461
541
  buildFilter(eb: ExpressionBuilder<any, any>, model: string, modelAlias: string, where: boolean | object | undefined): Expression<SqlBool>;
462
- protected buildCompositeFilter(eb: ExpressionBuilder<any, any>, model: string, modelAlias: string, key: 'AND' | 'OR' | 'NOT', payload: any): Expression<SqlBool>;
542
+ private buildCursorFilter;
543
+ private isLogicalCombinator;
544
+ protected buildCompositeFilter(eb: ExpressionBuilder<any, any>, model: string, modelAlias: string, key: (typeof LOGICAL_COMBINATORS)[number], payload: any): Expression<SqlBool>;
463
545
  private buildRelationFilter;
464
546
  private buildToOneRelationFilter;
465
547
  private buildToManyRelationFilter;
466
548
  private buildArrayFilter;
467
- buildPrimitiveFilter(eb: ExpressionBuilder<any, any>, model: string, modelAlias: string, field: string, fieldDef: FieldDef, payload: any): Expression<SqlBool>;
549
+ buildPrimitiveFilter(eb: ExpressionBuilder<any, any>, fieldRef: Expression<any>, fieldDef: FieldDef, payload: any): Expression<SqlBool>;
468
550
  private buildLiteralFilter;
469
551
  private buildStandardFilter;
470
552
  private buildStringFilter;
@@ -475,6 +557,11 @@ declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
475
557
  private buildBytesFilter;
476
558
  private buildEnumFilter;
477
559
  buildOrderBy(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, orderBy: OrArray<OrderBy<Schema, GetModels<Schema>, boolean, boolean>> | undefined, useDefaultIfEmpty: boolean, negated: boolean): SelectQueryBuilder<any, any, any>;
560
+ buildSelectAllFields(model: string, query: SelectQueryBuilder<any, any, any>, omit: Record<string, boolean | undefined> | undefined, modelAlias: string): SelectQueryBuilder<any, any, any>;
561
+ protected buildModelSelect(eb: ExpressionBuilder<any, any>, model: GetModels<Schema>, subQueryAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>, selectAllFields: boolean): SelectQueryBuilder<any, any, {}>;
562
+ buildSelectField(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, field: string): SelectQueryBuilder<any, any, any>;
563
+ buildDelegateJoin(thisModel: string, thisModelAlias: string, otherModelAlias: string, query: SelectQueryBuilder<any, any, any>): SelectQueryBuilder<any, any, any>;
564
+ buildCountJson(model: string, eb: ExpressionBuilder<any, any>, parentAlias: string, payload: any): ExpressionWrapper<any, any, unknown>;
478
565
  private negateSort;
479
566
  true(eb: ExpressionBuilder<any, any>): Expression<SqlBool>;
480
567
  false(eb: ExpressionBuilder<any, any>): Expression<SqlBool>;
@@ -483,6 +570,17 @@ declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
483
570
  protected and(eb: ExpressionBuilder<any, any>, ...args: Expression<SqlBool>[]): Expression<SqlBool>;
484
571
  protected or(eb: ExpressionBuilder<any, any>, ...args: Expression<SqlBool>[]): Expression<SqlBool>;
485
572
  protected not(eb: ExpressionBuilder<any, any>, ...args: Expression<SqlBool>[]): ExpressionWrapper<any, any, SqlBool>;
573
+ fieldRef(model: string, field: string, eb: ExpressionBuilder<any, any>, modelAlias?: string, inlineComputedField?: boolean): ExpressionWrapper<any, any, unknown>;
574
+ protected canJoinWithoutNestedSelect(modelDef: ModelDef, payload: boolean | FindArgs<Schema, GetModels<Schema>, true>): boolean;
575
+ abstract get provider(): DataSourceProviderType;
576
+ /**
577
+ * Builds selection for a relation field.
578
+ */
579
+ abstract buildRelationSelection(query: SelectQueryBuilder<any, any, any>, model: string, relationField: string, parentAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>): SelectQueryBuilder<any, any, any>;
580
+ /**
581
+ * Builds skip and take clauses.
582
+ */
583
+ abstract buildSkipTake(query: SelectQueryBuilder<any, any, any>, skip: number | undefined, take: number | undefined): SelectQueryBuilder<any, any, any>;
486
584
  /**
487
585
  * Builds an Kysely expression that returns a JSON object for the given key-value pairs.
488
586
  */
@@ -507,154 +605,157 @@ declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
507
605
  * Whether the dialect supports DISTINCT ON.
508
606
  */
509
607
  abstract get supportsDistinctOn(): boolean;
608
+ /**
609
+ * Whether the dialect support inserting with `DEFAULT` as field value.
610
+ */
611
+ abstract get supportInsertWithDefault(): boolean;
510
612
  }
511
613
 
512
- type CrudOperation = 'findMany' | 'findUnique' | 'findFirst' | 'create' | 'createMany' | 'createManyAndReturn' | 'update' | 'updateMany' | 'updateManyAndReturn' | 'upsert' | 'delete' | 'deleteMany' | 'count' | 'aggregate' | 'groupBy';
614
+ type CoreCrudOperation = 'findMany' | 'findUnique' | 'findFirst' | 'create' | 'createMany' | 'createManyAndReturn' | 'update' | 'updateMany' | 'updateManyAndReturn' | 'upsert' | 'delete' | 'deleteMany' | 'count' | 'aggregate' | 'groupBy';
615
+ type AllCrudOperation = CoreCrudOperation | 'findUniqueOrThrow' | 'findFirstOrThrow';
513
616
 
514
617
  /**
515
- * The result of the hooks interception filter.
618
+ * ZenStack runtime plugin.
516
619
  */
517
- type MutationInterceptionFilterResult = {
518
- /**
519
- * Whether to intercept the mutation or not.
520
- */
521
- intercept: boolean;
620
+ interface RuntimePlugin<Schema extends SchemaDef = SchemaDef> {
522
621
  /**
523
- * Whether to use a transaction for the mutation.
622
+ * Plugin ID.
524
623
  */
525
- useTransactionForMutation?: boolean;
624
+ id: string;
526
625
  /**
527
- * Whether entities should be loaded before the mutation.
626
+ * Plugin display name.
528
627
  */
529
- loadBeforeMutationEntity?: boolean;
628
+ name?: string;
530
629
  /**
531
- * Whether entities should be loaded after the mutation.
630
+ * Plugin description.
532
631
  */
533
- loadAfterMutationEntity?: boolean;
534
- };
535
- type MutationHooksArgs<Schema extends SchemaDef> = {
632
+ description?: string;
536
633
  /**
537
- * The model that is being mutated.
634
+ * Intercepts an ORM query.
538
635
  */
539
- model: GetModels<Schema>;
636
+ onQuery?: OnQueryCallback<Schema>;
540
637
  /**
541
- * The mutation action that is being performed.
638
+ * Intercepts an entity mutation.
542
639
  */
543
- action: 'create' | 'update' | 'delete';
640
+ onEntityMutation?: EntityMutationHooksDef<Schema>;
544
641
  /**
545
- * The mutation data. Only available for create and update actions.
642
+ * Intercepts a Kysely query.
546
643
  */
547
- queryNode: OperationNode;
548
- };
549
- type PluginBeforeEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
550
- entities?: Record<string, unknown>[];
551
- };
552
- type PluginAfterEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
553
- beforeMutationEntities?: Record<string, unknown>[];
554
- afterMutationEntities?: Record<string, unknown>[];
555
- };
556
- type OnKyselyQueryTransactionCallback = (proceed: ProceedKyselyQueryFunction) => Promise<QueryResult<any>>;
557
- type OnKyselyQueryTransaction = (callback: OnKyselyQueryTransactionCallback) => Promise<QueryResult<any>>;
558
- type OnKyselyQueryArgs<Schema extends SchemaDef> = {
559
- kysely: ToKysely<Schema>;
560
- schema: SchemaDef;
561
- client: ClientContract<Schema>;
562
- query: RootOperationNode;
563
- proceed: ProceedKyselyQueryFunction;
564
- transaction: OnKyselyQueryTransaction;
565
- };
566
- type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise<QueryResult<any>>;
644
+ onKyselyQuery?: OnKyselyQueryCallback<Schema>;
645
+ }
567
646
  /**
568
- * ZenStack runtime plugin.
647
+ * Defines a ZenStack runtime plugin.
569
648
  */
570
- interface RuntimePlugin<Schema extends SchemaDef = SchemaDef> {
649
+ declare function definePlugin<Schema extends SchemaDef>(plugin: RuntimePlugin<Schema>): RuntimePlugin<Schema>;
650
+
651
+ type OnQueryCallback<Schema extends SchemaDef> = (ctx: OnQueryHookContext<Schema>) => Promise<unknown>;
652
+ type OnQueryHookContext<Schema extends SchemaDef> = {
571
653
  /**
572
- * Plugin ID.
654
+ * The model that is being queried.
573
655
  */
574
- id: string;
656
+ model: GetModels<Schema>;
575
657
  /**
576
- * Plugin display name.
658
+ * The operation that is being performed.
577
659
  */
578
- name?: string;
660
+ operation: AllCrudOperation;
579
661
  /**
580
- * Plugin description.
662
+ * The query arguments.
581
663
  */
582
- description?: string;
664
+ args: unknown;
583
665
  /**
584
- * Intercepts an ORM query.
666
+ * The function to proceed with the original query.
667
+ * It takes the same arguments as the operation method.
668
+ *
669
+ * @param args The query arguments.
585
670
  */
586
- onQuery?: OnQueryHooks<Schema>;
671
+ proceed: (args: unknown) => Promise<unknown>;
587
672
  /**
588
- * Intercepts a Kysely query.
673
+ * The ZenStack client that is performing the operation.
589
674
  */
590
- onKyselyQuery?: (args: OnKyselyQueryArgs<Schema>) => Promise<QueryResult<UnknownRow>>;
675
+ client: ClientContract<Schema>;
676
+ };
677
+ type EntityMutationHooksDef<Schema extends SchemaDef> = {
591
678
  /**
592
- * This callback determines whether a mutation should be intercepted, and if so,
593
- * what data should be loaded before and after the mutation.
679
+ * Called before entities are mutated.
594
680
  */
595
- mutationInterceptionFilter?: (args: MutationHooksArgs<Schema>) => MaybePromise<MutationInterceptionFilterResult>;
681
+ beforeEntityMutation?: BeforeEntityMutationCallback<Schema>;
596
682
  /**
597
- * Called before an entity is mutated.
598
- * @param args.entity Only available if `loadBeforeMutationEntity` is set to true in the
599
- * return value of {@link RuntimePlugin.mutationInterceptionFilter}.
683
+ * Called after entities are mutated.
600
684
  */
601
- beforeEntityMutation?: (args: PluginBeforeEntityMutationArgs<Schema>) => MaybePromise<void>;
685
+ afterEntityMutation?: AfterEntityMutationCallback<Schema>;
602
686
  /**
603
- * Called after an entity is mutated.
604
- * @param args.beforeMutationEntity Only available if `loadBeforeMutationEntity` is set to true in the
605
- * return value of {@link RuntimePlugin.mutationInterceptionFilter}.
606
- * @param args.afterMutationEntity Only available if `loadAfterMutationEntity` is set to true in the
607
- * return value of {@link RuntimePlugin.mutationInterceptionFilter}.
687
+ * Whether to run after-mutation hooks within the transaction that performs the mutation.
688
+ *
689
+ * If set to `true`, if the mutation already runs inside a transaction, the callbacks are
690
+ * executed immediately after the mutation within the transaction boundary. If the mutation
691
+ * is not running inside a transaction, a new transaction is created to run both the mutation
692
+ * and the callbacks.
693
+ *
694
+ * If set to `false`, the callbacks are executed after the mutation transaction is committed.
695
+ *
696
+ * Defaults to `false`.
608
697
  */
609
- afterEntityMutation?: (args: PluginAfterEntityMutationArgs<Schema>) => MaybePromise<void>;
610
- }
611
- type OnQueryHooks<Schema extends SchemaDef = SchemaDef> = {
612
- [Model in GetModels<Schema> as Uncapitalize<Model>]?: OnQueryOperationHooks<Schema, Model>;
613
- } & {
614
- $allModels?: OnQueryOperationHooks<Schema, GetModels<Schema>>;
615
- };
616
- type OnQueryOperationHooks<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
617
- [Operation in keyof ModelOperations<Schema, Model>]?: (ctx: OnQueryHookContext<Schema, Model, Operation>) => ReturnType<ModelOperations<Schema, Model>[Operation]>;
618
- } & {
619
- $allOperations?: (ctx: {
620
- model: Model;
621
- operation: CrudOperation;
622
- args: unknown;
623
- query: (args: unknown) => Promise<unknown>;
624
- }) => MaybePromise<unknown>;
698
+ runAfterMutationWithinTransaction?: boolean;
625
699
  };
626
- type OnQueryHookContext<Schema extends SchemaDef, Model extends GetModels<Schema>, Operation extends keyof ModelOperations<Schema, Model>> = {
700
+ type MutationHooksArgs<Schema extends SchemaDef> = {
627
701
  /**
628
- * The model that is being queried.
702
+ * The model that is being mutated.
629
703
  */
630
- model: Model;
704
+ model: GetModels<Schema>;
631
705
  /**
632
- * The operation that is being performed.
706
+ * The mutation action that is being performed.
633
707
  */
634
- operation: Operation;
708
+ action: 'create' | 'update' | 'delete';
635
709
  /**
636
- * The query arguments.
710
+ * The mutation data. Only available for create and update actions.
637
711
  */
638
- args: Parameters<ModelOperations<Schema, Model>[Operation]>[0];
712
+ queryNode: OperationNode;
639
713
  /**
640
- * The query function to proceed with the original query.
641
- * It takes the same arguments as the operation method.
714
+ * A query ID that uniquely identifies the mutation operation. You can use it to correlate
715
+ * data between the before and after mutation hooks.
716
+ */
717
+ queryId: string;
718
+ };
719
+ type BeforeEntityMutationCallback<Schema extends SchemaDef> = (args: PluginBeforeEntityMutationArgs<Schema>) => MaybePromise<void>;
720
+ type AfterEntityMutationCallback<Schema extends SchemaDef> = (args: PluginAfterEntityMutationArgs<Schema>) => MaybePromise<void>;
721
+ type PluginBeforeEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
722
+ /**
723
+ * Loads the entities that are about to be mutated. The db operation that loads the entities is executed
724
+ * within the same transaction context as the mutation.
725
+ */
726
+ loadBeforeMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
727
+ /**
728
+ * The ZenStack client you can use to perform additional operations. The database operations initiated
729
+ * from this client are executed within the same transaction as the mutation if the mutation is running
730
+ * inside a transaction.
642
731
  *
643
- * @param args The query arguments.
644
- * @param tx Optional transaction client to use for the query.
732
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
645
733
  */
646
- query: (args: Parameters<ModelOperations<Schema, Model>[Operation]>[0], tx?: ClientContract<Schema>) => ReturnType<ModelOperations<Schema, Model>[Operation]>;
734
+ client: ClientContract<Schema>;
735
+ };
736
+ type PluginAfterEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
647
737
  /**
648
- * The ZenStack client that is performing the operation.
738
+ * Loads the entities that have been mutated.
739
+ */
740
+ loadAfterMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
741
+ /**
742
+ * The ZenStack client you can use to perform additional operations.
743
+ * See {@link EntityMutationHooksDef.runAfterMutationWithinTransaction} for detailed transaction behavior.
744
+ *
745
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
649
746
  */
650
747
  client: ClientContract<Schema>;
651
748
  };
652
- /**
653
- * Defines a ZenStack runtime plugin.
654
- */
655
- declare function definePlugin<Schema extends SchemaDef>(plugin: RuntimePlugin<Schema>): RuntimePlugin<Schema>;
749
+ type OnKyselyQueryArgs<Schema extends SchemaDef> = {
750
+ kysely: ToKysely<Schema>;
751
+ schema: SchemaDef;
752
+ client: ClientContract<Schema>;
753
+ query: RootOperationNode;
754
+ proceed: ProceedKyselyQueryFunction;
755
+ };
756
+ type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise<QueryResult<any>>;
757
+ type OnKyselyQueryCallback<Schema extends SchemaDef> = (args: OnKyselyQueryArgs<Schema>) => Promise<QueryResult<UnknownRow>>;
656
758
 
657
- type DialectConfig<Provider extends DataSourceProvider> = Provider['type'] extends 'sqlite' ? Optional<SqliteDialectConfig, 'database'> : Provider['type'] extends 'postgresql' ? Optional<PostgresDialectConfig, 'pool'> : never;
658
759
  type ZModelFunctionContext<Schema extends SchemaDef> = {
659
760
  dialect: BaseCrudDialect<Schema>;
660
761
  model: GetModels<Schema>;
@@ -666,9 +767,9 @@ type ZModelFunction<Schema extends SchemaDef> = (eb: ExpressionBuilder<ToKyselyS
666
767
  */
667
768
  type ClientOptions<Schema extends SchemaDef> = {
668
769
  /**
669
- * Database dialect configuration.
770
+ * Kysely dialect.
670
771
  */
671
- dialectConfig: DialectConfig<Schema['provider']>;
772
+ dialect: Dialect;
672
773
  /**
673
774
  * Custom function definitions.
674
775
  */
@@ -707,6 +808,28 @@ type HasProcedures<Schema extends SchemaDef> = Schema extends {
707
808
  procedures: Record<string, ProcedureDef>;
708
809
  } ? true : false;
709
810
 
811
+ /**
812
+ * A promise that only executes when it's awaited or .then() is called.
813
+ */
814
+ type ZenStackPromise<Schema extends SchemaDef, T> = Promise<T> & {
815
+ /**
816
+ * @private
817
+ * Callable to get a plain promise.
818
+ */
819
+ cb: (txClient?: ClientContract<Schema>) => Promise<T>;
820
+ };
821
+
822
+ type TransactionUnsupportedMethods = (typeof TRANSACTION_UNSUPPORTED_METHODS)[number];
823
+ /**
824
+ * Transaction isolation levels.
825
+ */
826
+ declare enum TransactionIsolationLevel {
827
+ ReadUncommitted = "read uncommitted",
828
+ ReadCommitted = "read committed",
829
+ RepeatableRead = "repeatable read",
830
+ Serializable = "serializable",
831
+ Snapshot = "snapshot"
832
+ }
710
833
  /**
711
834
  * ZenStack client interface.
712
835
  */
@@ -720,36 +843,36 @@ type ClientContract<Schema extends SchemaDef> = {
720
843
  * Executes a prepared raw query and returns the number of affected rows.
721
844
  * @example
722
845
  * ```
723
- * const result = await client.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`
846
+ * const result = await db.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`
724
847
  * ```
725
848
  */
726
- $executeRaw(query: TemplateStringsArray, ...values: any[]): Promise<number>;
849
+ $executeRaw(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, number>;
727
850
  /**
728
851
  * Executes a raw query and returns the number of affected rows.
729
852
  * This method is susceptible to SQL injections.
730
853
  * @example
731
854
  * ```
732
- * const result = await client.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com')
855
+ * const result = await db.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com')
733
856
  * ```
734
857
  */
735
- $executeRawUnsafe(query: string, ...values: any[]): Promise<number>;
858
+ $executeRawUnsafe(query: string, ...values: any[]): ZenStackPromise<Schema, number>;
736
859
  /**
737
860
  * Performs a prepared raw query and returns the `SELECT` data.
738
861
  * @example
739
862
  * ```
740
- * const result = await client.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`
863
+ * const result = await db.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`
741
864
  * ```
742
865
  */
743
- $queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]): Promise<T>;
866
+ $queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, T>;
744
867
  /**
745
868
  * Performs a raw query and returns the `SELECT` data.
746
869
  * This method is susceptible to SQL injections.
747
870
  * @example
748
871
  * ```
749
- * const result = await client.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com')
872
+ * const result = await db.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com')
750
873
  * ```
751
874
  */
752
- $queryRawUnsafe<T = unknown>(query: string, ...values: any[]): Promise<T>;
875
+ $queryRawUnsafe<T = unknown>(query: string, ...values: any[]): ZenStackPromise<Schema, T>;
753
876
  /**
754
877
  * The current user identity.
755
878
  */
@@ -767,9 +890,17 @@ type ClientContract<Schema extends SchemaDef> = {
767
890
  */
768
891
  readonly $qbRaw: ToKysely<any>;
769
892
  /**
770
- * Starts a transaction.
893
+ * Starts an interactive transaction.
894
+ */
895
+ $transaction<T>(callback: (tx: Omit<ClientContract<Schema>, TransactionUnsupportedMethods>) => Promise<T>, options?: {
896
+ isolationLevel?: TransactionIsolationLevel;
897
+ }): Promise<T>;
898
+ /**
899
+ * Starts a sequential transaction.
771
900
  */
772
- $transaction<T>(callback: (tx: ClientContract<Schema>) => Promise<T>): Promise<T>;
901
+ $transaction<P extends ZenStackPromise<Schema, any>[]>(arg: [...P], options?: {
902
+ isolationLevel?: TransactionIsolationLevel;
903
+ }): Promise<UnwrapTuplePromises<P>>;
773
904
  /**
774
905
  * Returns a new client with the specified plugin installed.
775
906
  */
@@ -827,7 +958,7 @@ interface ClientConstructor {
827
958
  * CRUD operations.
828
959
  */
829
960
  type CRUD = 'create' | 'read' | 'update' | 'delete';
830
- interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>> {
961
+ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
831
962
  /**
832
963
  * Returns a list of entities.
833
964
  * @param args - query args
@@ -836,17 +967,17 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
836
967
  * @example
837
968
  * ```ts
838
969
  * // find all users and return all scalar fields
839
- * await client.user.findMany();
970
+ * await db.user.findMany();
840
971
  *
841
972
  * // find all users with name 'Alex'
842
- * await client.user.findMany({
973
+ * await db.user.findMany({
843
974
  * where: {
844
975
  * name: 'Alex'
845
976
  * }
846
977
  * });
847
978
  *
848
979
  * // select fields
849
- * await client.user.findMany({
980
+ * await db.user.findMany({
850
981
  * select: {
851
982
  * name: true,
852
983
  * email: true,
@@ -854,21 +985,21 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
854
985
  * }); // result: `Array<{ name: string, email: string }>`
855
986
  *
856
987
  * // omit fields
857
- * await client.user.findMany({
988
+ * await db.user.findMany({
858
989
  * omit: {
859
990
  * name: true,
860
991
  * }
861
992
  * }); // result: `Array<{ id: number; email: string; ... }>`
862
993
  *
863
994
  * // include relations (and all scalar fields)
864
- * await client.user.findMany({
995
+ * await db.user.findMany({
865
996
  * include: {
866
997
  * posts: true,
867
998
  * }
868
999
  * }); // result: `Array<{ ...; posts: Post[] }>`
869
1000
  *
870
1001
  * // include relations with filter
871
- * await client.user.findMany({
1002
+ * await db.user.findMany({
872
1003
  * include: {
873
1004
  * posts: {
874
1005
  * where: {
@@ -879,14 +1010,14 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
879
1010
  * });
880
1011
  *
881
1012
  * // pagination and sorting
882
- * await client.user.findMany({
1013
+ * await db.user.findMany({
883
1014
  * skip: 10,
884
1015
  * take: 10,
885
1016
  * orderBy: [{ name: 'asc' }, { email: 'desc' }],
886
1017
  * });
887
1018
  *
888
1019
  * // pagination with cursor (https://www.prisma.io/docs/orm/prisma-client/queries/pagination#cursor-based-pagination)
889
- * await client.user.findMany({
1020
+ * await db.user.findMany({
890
1021
  * cursor: { id: 10 },
891
1022
  * skip: 1,
892
1023
  * take: 10,
@@ -894,50 +1025,50 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
894
1025
  * });
895
1026
  *
896
1027
  * // distinct
897
- * await client.user.findMany({
1028
+ * await db.user.findMany({
898
1029
  * distinct: ['name']
899
1030
  * });
900
1031
  *
901
1032
  * // count all relations
902
- * await client.user.findMany({
1033
+ * await db.user.findMany({
903
1034
  * _count: true,
904
1035
  * }); // result: `{ _count: { posts: number; ... } }`
905
1036
  *
906
1037
  * // count selected relations
907
- * await client.user.findMany({
1038
+ * await db.user.findMany({
908
1039
  * _count: { select: { posts: true } },
909
1040
  * }); // result: `{ _count: { posts: number } }`
910
1041
  * ```
911
1042
  */
912
- findMany<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): Promise<ModelResult<Schema, Model, T>[]>;
1043
+ findMany<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>[]>;
913
1044
  /**
914
1045
  * Returns a uniquely identified entity.
915
1046
  * @param args - query args
916
1047
  * @returns a single entity or null if not found
917
1048
  * @see {@link findMany}
918
1049
  */
919
- findUnique<T extends FindUniqueArgs<Schema, Model>>(args?: SelectSubset<T, FindUniqueArgs<Schema, Model>>): Promise<ModelResult<Schema, Model, T> | null>;
1050
+ findUnique<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>> | null>;
920
1051
  /**
921
1052
  * Returns a uniquely identified entity or throws `NotFoundError` if not found.
922
1053
  * @param args - query args
923
1054
  * @returns a single entity
924
1055
  * @see {@link findMany}
925
1056
  */
926
- findUniqueOrThrow<T extends FindUniqueArgs<Schema, Model>>(args?: SelectSubset<T, FindUniqueArgs<Schema, Model>>): Promise<ModelResult<Schema, Model, T>>;
1057
+ findUniqueOrThrow<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
927
1058
  /**
928
1059
  * Returns the first entity.
929
1060
  * @param args - query args
930
1061
  * @returns a single entity or null if not found
931
1062
  * @see {@link findMany}
932
1063
  */
933
- findFirst<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): Promise<ModelResult<Schema, Model, T> | null>;
1064
+ findFirst<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>> | null>;
934
1065
  /**
935
1066
  * Returns the first entity or throws `NotFoundError` if not found.
936
1067
  * @param args - query args
937
1068
  * @returns a single entity
938
1069
  * @see {@link findMany}
939
1070
  */
940
- findFirstOrThrow<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): Promise<ModelResult<Schema, Model, T>>;
1071
+ findFirstOrThrow<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
941
1072
  /**
942
1073
  * Creates a new entity.
943
1074
  * @param args - create args
@@ -946,12 +1077,12 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
946
1077
  * @example
947
1078
  * ```ts
948
1079
  * // simple create
949
- * await client.user.create({
1080
+ * await db.user.create({
950
1081
  * data: { name: 'Alex', email: 'alex@zenstack.dev' }
951
1082
  * });
952
1083
  *
953
1084
  * // nested create with relation
954
- * await client.user.create({
1085
+ * await db.user.create({
955
1086
  * data: {
956
1087
  * email: 'alex@zenstack.dev',
957
1088
  * posts: { create: { title: 'Hello World' } }
@@ -960,7 +1091,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
960
1091
  *
961
1092
  * // you can use `select`, `omit`, and `include` to control
962
1093
  * // the fields returned by the query, as with `findMany`
963
- * await client.user.create({
1094
+ * await db.user.create({
964
1095
  * data: {
965
1096
  * email: 'alex@zenstack.dev',
966
1097
  * posts: { create: { title: 'Hello World' } }
@@ -969,7 +1100,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
969
1100
  * }); // result: `{ id: number; posts: Post[] }`
970
1101
  *
971
1102
  * // connect relations
972
- * await client.user.create({
1103
+ * await db.user.create({
973
1104
  * data: {
974
1105
  * email: 'alex@zenstack.dev',
975
1106
  * posts: { connect: { id: 1 } }
@@ -977,7 +1108,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
977
1108
  * });
978
1109
  *
979
1110
  * // connect relations, and create if not found
980
- * await client.user.create({
1111
+ * await db.user.create({
981
1112
  * data: {
982
1113
  * email: 'alex@zenstack.dev',
983
1114
  * posts: {
@@ -990,7 +1121,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
990
1121
  * });
991
1122
  * ```
992
1123
  */
993
- create<T extends CreateArgs<Schema, Model>>(args: SelectSubset<T, CreateArgs<Schema, Model>>): Promise<ModelResult<Schema, Model, T>>;
1124
+ create<T extends CreateArgs<Schema, Model>>(args: SelectSubset<T, CreateArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
994
1125
  /**
995
1126
  * Creates multiple entities. Only scalar fields are allowed.
996
1127
  * @param args - create args
@@ -999,7 +1130,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
999
1130
  * @example
1000
1131
  * ```ts
1001
1132
  * // create multiple entities
1002
- * await client.user.createMany({
1133
+ * await db.user.createMany({
1003
1134
  * data: [
1004
1135
  * { name: 'Alex', email: 'alex@zenstack.dev' },
1005
1136
  * { name: 'John', email: 'john@zenstack.dev' }
@@ -1007,7 +1138,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1007
1138
  * });
1008
1139
  *
1009
1140
  * // skip items that cause unique constraint violation
1010
- * await client.user.createMany({
1141
+ * await db.user.createMany({
1011
1142
  * data: [
1012
1143
  * { name: 'Alex', email: 'alex@zenstack.dev' },
1013
1144
  * { name: 'John', email: 'john@zenstack.dev' }
@@ -1016,7 +1147,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1016
1147
  * });
1017
1148
  * ```
1018
1149
  */
1019
- createMany<T extends CreateManyArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyArgs<Schema, Model>>): Promise<BatchResult>;
1150
+ createMany<T extends CreateManyArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyArgs<Schema, Model>>): ZenStackPromise<Schema, BatchResult>;
1020
1151
  /**
1021
1152
  * Creates multiple entities and returns them.
1022
1153
  * @param args - create args. See {@link createMany} for input. Use
@@ -1026,7 +1157,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1026
1157
  * @example
1027
1158
  * ```ts
1028
1159
  * // create multiple entities and return selected fields
1029
- * await client.user.createManyAndReturn({
1160
+ * await db.user.createManyAndReturn({
1030
1161
  * data: [
1031
1162
  * { name: 'Alex', email: 'alex@zenstack.dev' },
1032
1163
  * { name: 'John', email: 'john@zenstack.dev' }
@@ -1035,7 +1166,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1035
1166
  * });
1036
1167
  * ```
1037
1168
  */
1038
- createManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyAndReturnArgs<Schema, Model>>): Promise<ModelResult<Schema, Model, T>[]>;
1169
+ createManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>[]>;
1039
1170
  /**
1040
1171
  * Updates a uniquely identified entity.
1041
1172
  * @param args - update args. See {@link findMany} for how to control
@@ -1045,19 +1176,19 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1045
1176
  * @example
1046
1177
  * ```ts
1047
1178
  * // update fields
1048
- * await client.user.update({
1179
+ * await db.user.update({
1049
1180
  * where: { id: 1 },
1050
1181
  * data: { name: 'Alex' }
1051
1182
  * });
1052
1183
  *
1053
1184
  * // connect a relation
1054
- * await client.user.update({
1185
+ * await db.user.update({
1055
1186
  * where: { id: 1 },
1056
1187
  * data: { posts: { connect: { id: 1 } } }
1057
1188
  * });
1058
1189
  *
1059
1190
  * // connect relation, and create if not found
1060
- * await client.user.update({
1191
+ * await db.user.update({
1061
1192
  * where: { id: 1 },
1062
1193
  * data: {
1063
1194
  * posts: {
@@ -1070,7 +1201,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1070
1201
  * });
1071
1202
  *
1072
1203
  * // create many related entities (only available for one-to-many relations)
1073
- * await client.user.update({
1204
+ * await db.user.update({
1074
1205
  * where: { id: 1 },
1075
1206
  * data: {
1076
1207
  * posts: {
@@ -1082,19 +1213,19 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1082
1213
  * });
1083
1214
  *
1084
1215
  * // disconnect a one-to-many relation
1085
- * await client.user.update({
1216
+ * await db.user.update({
1086
1217
  * where: { id: 1 },
1087
1218
  * data: { posts: { disconnect: { id: 1 } } }
1088
1219
  * });
1089
1220
  *
1090
1221
  * // disconnect a one-to-one relation
1091
- * await client.user.update({
1222
+ * await db.user.update({
1092
1223
  * where: { id: 1 },
1093
1224
  * data: { profile: { disconnect: true } }
1094
1225
  * });
1095
1226
  *
1096
1227
  * // replace a relation (only available for one-to-many relations)
1097
- * await client.user.update({
1228
+ * await db.user.update({
1098
1229
  * where: { id: 1 },
1099
1230
  * data: {
1100
1231
  * posts: {
@@ -1104,7 +1235,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1104
1235
  * });
1105
1236
  *
1106
1237
  * // update a relation
1107
- * await client.user.update({
1238
+ * await db.user.update({
1108
1239
  * where: { id: 1 },
1109
1240
  * data: {
1110
1241
  * posts: {
@@ -1114,7 +1245,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1114
1245
  * });
1115
1246
  *
1116
1247
  * // upsert a relation
1117
- * await client.user.update({
1248
+ * await db.user.update({
1118
1249
  * where: { id: 1 },
1119
1250
  * data: {
1120
1251
  * posts: {
@@ -1128,7 +1259,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1128
1259
  * });
1129
1260
  *
1130
1261
  * // update many related entities (only available for one-to-many relations)
1131
- * await client.user.update({
1262
+ * await db.user.update({
1132
1263
  * where: { id: 1 },
1133
1264
  * data: {
1134
1265
  * posts: {
@@ -1141,19 +1272,19 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1141
1272
  * });
1142
1273
  *
1143
1274
  * // delete a one-to-many relation
1144
- * await client.user.update({
1275
+ * await db.user.update({
1145
1276
  * where: { id: 1 },
1146
1277
  * data: { posts: { delete: { id: 1 } } }
1147
1278
  * });
1148
1279
  *
1149
1280
  * // delete a one-to-one relation
1150
- * await client.user.update({
1281
+ * await db.user.update({
1151
1282
  * where: { id: 1 },
1152
1283
  * data: { profile: { delete: true } }
1153
1284
  * });
1154
1285
  * ```
1155
1286
  */
1156
- update<T extends UpdateArgs<Schema, Model>>(args: SelectSubset<T, UpdateArgs<Schema, Model>>): Promise<ModelResult<Schema, Model, T>>;
1287
+ update<T extends UpdateArgs<Schema, Model>>(args: SelectSubset<T, UpdateArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
1157
1288
  /**
1158
1289
  * Updates multiple entities.
1159
1290
  * @param args - update args. Only scalar fields are allowed for data.
@@ -1162,19 +1293,19 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1162
1293
  * @example
1163
1294
  * ```ts
1164
1295
  * // update many entities
1165
- * await client.user.updateMany({
1296
+ * await db.user.updateMany({
1166
1297
  * where: { email: { endsWith: '@zenstack.dev' } },
1167
1298
  * data: { role: 'ADMIN' }
1168
1299
  * });
1169
1300
  *
1170
1301
  * // limit the number of updated entities
1171
- * await client.user.updateMany({
1302
+ * await db.user.updateMany({
1172
1303
  * where: { email: { endsWith: '@zenstack.dev' } },
1173
1304
  * data: { role: 'ADMIN' },
1174
1305
  * limit: 10
1175
1306
  * });
1176
1307
  */
1177
- updateMany<T extends UpdateManyArgs<Schema, Model>>(args: Subset<T, UpdateManyArgs<Schema, Model>>): Promise<BatchResult>;
1308
+ updateMany<T extends UpdateManyArgs<Schema, Model>>(args: Subset<T, UpdateManyArgs<Schema, Model>>): ZenStackPromise<Schema, BatchResult>;
1178
1309
  /**
1179
1310
  * Updates multiple entities and returns them.
1180
1311
  * @param args - update args. Only scalar fields are allowed for data.
@@ -1183,21 +1314,21 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1183
1314
  * @example
1184
1315
  * ```ts
1185
1316
  * // update many entities and return selected fields
1186
- * await client.user.updateManyAndReturn({
1317
+ * await db.user.updateManyAndReturn({
1187
1318
  * where: { email: { endsWith: '@zenstack.dev' } },
1188
1319
  * data: { role: 'ADMIN' },
1189
1320
  * select: { id: true, email: true }
1190
1321
  * }); // result: `Array<{ id: string; email: string }>`
1191
1322
  *
1192
1323
  * // limit the number of updated entities
1193
- * await client.user.updateManyAndReturn({
1324
+ * await db.user.updateManyAndReturn({
1194
1325
  * where: { email: { endsWith: '@zenstack.dev' } },
1195
1326
  * data: { role: 'ADMIN' },
1196
1327
  * limit: 10
1197
1328
  * });
1198
1329
  * ```
1199
1330
  */
1200
- updateManyAndReturn<T extends UpdateManyAndReturnArgs<Schema, Model>>(args: Subset<T, UpdateManyAndReturnArgs<Schema, Model>>): Promise<ModelResult<Schema, Model, T>[]>;
1331
+ updateManyAndReturn<T extends UpdateManyAndReturnArgs<Schema, Model>>(args: Subset<T, UpdateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>[]>;
1201
1332
  /**
1202
1333
  * Creates or updates an entity.
1203
1334
  * @param args - upsert args
@@ -1206,7 +1337,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1206
1337
  * @example
1207
1338
  * ```ts
1208
1339
  * // upsert an entity
1209
- * await client.user.upsert({
1340
+ * await db.user.upsert({
1210
1341
  * // `where` clause is used to find the entity
1211
1342
  * where: { id: 1 },
1212
1343
  * // `create` clause is used if the entity is not found
@@ -1218,7 +1349,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1218
1349
  * });
1219
1350
  * ```
1220
1351
  */
1221
- upsert<T extends UpsertArgs<Schema, Model>>(args: SelectSubset<T, UpsertArgs<Schema, Model>>): Promise<ModelResult<Schema, Model, T>>;
1352
+ upsert<T extends UpsertArgs<Schema, Model>>(args: SelectSubset<T, UpsertArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
1222
1353
  /**
1223
1354
  * Deletes a uniquely identifiable entity.
1224
1355
  * @param args - delete args
@@ -1227,18 +1358,18 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1227
1358
  * @example
1228
1359
  * ```ts
1229
1360
  * // delete an entity
1230
- * await client.user.delete({
1361
+ * await db.user.delete({
1231
1362
  * where: { id: 1 }
1232
1363
  * });
1233
1364
  *
1234
1365
  * // delete an entity and return selected fields
1235
- * await client.user.delete({
1366
+ * await db.user.delete({
1236
1367
  * where: { id: 1 },
1237
1368
  * select: { id: true, email: true }
1238
1369
  * }); // result: `{ id: string; email: string }`
1239
1370
  * ```
1240
1371
  */
1241
- delete<T extends DeleteArgs<Schema, Model>>(args: SelectSubset<T, DeleteArgs<Schema, Model>>): Promise<ModelResult<Schema, Model>>;
1372
+ delete<T extends DeleteArgs<Schema, Model>>(args: SelectSubset<T, DeleteArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
1242
1373
  /**
1243
1374
  * Deletes multiple entities.
1244
1375
  * @param args - delete args
@@ -1247,18 +1378,18 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1247
1378
  * @example
1248
1379
  * ```ts
1249
1380
  * // delete many entities
1250
- * await client.user.deleteMany({
1381
+ * await db.user.deleteMany({
1251
1382
  * where: { email: { endsWith: '@zenstack.dev' } }
1252
1383
  * });
1253
1384
  *
1254
1385
  * // limit the number of deleted entities
1255
- * await client.user.deleteMany({
1386
+ * await db.user.deleteMany({
1256
1387
  * where: { email: { endsWith: '@zenstack.dev' } },
1257
1388
  * limit: 10
1258
1389
  * });
1259
1390
  * ```
1260
1391
  */
1261
- deleteMany<T extends DeleteManyArgs<Schema, Model>>(args?: Subset<T, DeleteManyArgs<Schema, Model>>): Promise<BatchResult>;
1392
+ deleteMany<T extends DeleteManyArgs<Schema, Model>>(args?: Subset<T, DeleteManyArgs<Schema, Model>>): ZenStackPromise<Schema, BatchResult>;
1262
1393
  /**
1263
1394
  * Counts rows or field values.
1264
1395
  * @param args - count args
@@ -1267,17 +1398,17 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1267
1398
  * @example
1268
1399
  * ```ts
1269
1400
  * // count all
1270
- * await client.user.count();
1401
+ * await db.user.count();
1271
1402
  *
1272
1403
  * // count with a filter
1273
- * await client.user.count({ where: { email: { endsWith: '@zenstack.dev' } } });
1404
+ * await db.user.count({ where: { email: { endsWith: '@zenstack.dev' } } });
1274
1405
  *
1275
1406
  * // count rows and field values
1276
- * await client.user.count({
1407
+ * await db.user.count({
1277
1408
  * select: { _all: true, email: true }
1278
1409
  * }); // result: `{ _all: number, email: number }`
1279
1410
  */
1280
- count<T extends CountArgs<Schema, Model>>(args?: Subset<T, CountArgs<Schema, Model>>): Promise<CountResult<Schema, Model, T>>;
1411
+ count<T extends CountArgs<Schema, Model>>(args?: Subset<T, CountArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<CountResult<Schema, Model, T>>>;
1281
1412
  /**
1282
1413
  * Aggregates rows.
1283
1414
  * @param args - aggregation args
@@ -1286,7 +1417,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1286
1417
  * @example
1287
1418
  * ```ts
1288
1419
  * // aggregate rows
1289
- * await client.profile.aggregate({
1420
+ * await db.profile.aggregate({
1290
1421
  * where: { email: { endsWith: '@zenstack.dev' } },
1291
1422
  * _count: true,
1292
1423
  * _avg: { age: true },
@@ -1295,7 +1426,7 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1295
1426
  * _max: { age: true }
1296
1427
  * }); // result: `{ _count: number, _avg: { age: number }, ... }`
1297
1428
  */
1298
- aggregate<T extends AggregateArgs<Schema, Model>>(args: Subset<T, AggregateArgs<Schema, Model>>): Promise<AggregateResult<Schema, Model, T>>;
1429
+ aggregate<T extends AggregateArgs<Schema, Model>>(args: Subset<T, AggregateArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<AggregateResult<Schema, Model, T>>>;
1299
1430
  /**
1300
1431
  * Groups rows by columns.
1301
1432
  * @param args - groupBy args
@@ -1304,31 +1435,33 @@ interface ModelOperations<Schema extends SchemaDef, Model extends GetModels<Sche
1304
1435
  * @example
1305
1436
  * ```ts
1306
1437
  * // group by a field
1307
- * await client.profile.groupBy({
1438
+ * await db.profile.groupBy({
1308
1439
  * by: 'country',
1309
1440
  * _count: true
1310
1441
  * }); // result: `Array<{ country: string, _count: number }>`
1311
1442
  *
1312
1443
  * // group by multiple fields
1313
- * await client.profile.groupBy({
1444
+ * await db.profile.groupBy({
1314
1445
  * by: ['country', 'city'],
1315
1446
  * _count: true
1316
1447
  * }); // result: `Array<{ country: string, city: string, _count: number }>`
1317
1448
  *
1318
- * // group by with sorting, the `orderBy` fields must be in the `by` list
1319
- * await client.profile.groupBy({
1449
+ * // group by with sorting, the `orderBy` fields must be either an aggregation
1450
+ * // or a field used in the `by` list
1451
+ * await db.profile.groupBy({
1320
1452
  * by: 'country',
1321
1453
  * orderBy: { country: 'desc' }
1322
1454
  * });
1323
1455
  *
1324
- * // group by with having (post-aggregation filter), the `having` fields must
1325
- * // be in the `by` list
1326
- * await client.profile.groupBy({
1456
+ * // group by with having (post-aggregation filter), the fields used in `having` must
1457
+ * // be either an aggregation, or a field used in the `by` list
1458
+ * await db.profile.groupBy({
1327
1459
  * by: 'country',
1328
- * having: { country: 'US' }
1460
+ * having: { country: 'US', age: { _avg: { gte: 18 } } }
1329
1461
  * });
1330
1462
  */
1331
- groupBy<T extends GroupByArgs<Schema, Model>>(args: Subset<T, GroupByArgs<Schema, Model>>): Promise<GroupByResult<Schema, Model, T>>;
1332
- }
1463
+ groupBy<T extends GroupByArgs<Schema, Model>>(args: Subset<T, GroupByArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<GroupByResult<Schema, Model, T>>>;
1464
+ };
1465
+ type ModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<AllModelOperations<Schema, Model>, IsDelegateModel<Schema, Model> extends true ? 'create' | 'createMany' | 'createManyAndReturn' | 'upsert' : never>;
1333
1466
 
1334
- export { type UpdateRelationInput as A, type BatchResult as B, type ClientConstructor as C, type DateTimeFilter as D, type UpdateInput as E, type FindArgs as F, type DeleteArgs as G, type DeleteManyArgs as H, type CountArgs as I, type CountAggregateInput as J, type CountResult as K, type AggregateArgs as L, type ModelResult as M, type NumberFilter as N, type OrderBy as O, type AggregateResult as P, type GroupByArgs as Q, type GroupByResult as R, type StringFilter as S, type ToKysely as T, type UpdateArgs as U, type RuntimePlugin as V, type WhereInput as W, type OnKyselyQueryArgs as X, type ClientContract as a, type ClientOptions as b, type CommonPrimitiveFilter as c, definePlugin as d, type BytesFilter as e, type BooleanFilter as f, type SortOrder as g, type NullsOrder as h, type WhereUniqueInput as i, type SelectIncludeOmit as j, type Subset as k, type SelectSubset as l, type MapFieldType as m, type OptionalFieldsForCreate as n, type OppositeRelationFields as o, type OppositeRelationAndFK as p, type FindUniqueArgs as q, type CreateArgs as r, type CreateManyArgs as s, type CreateManyAndReturnArgs as t, type CreateManyPayload as u, type CreateInput as v, type UpdateManyArgs as w, type UpdateManyAndReturnArgs as x, type UpsertArgs as y, type UpdateScalarInput as z };
1467
+ export { type DeleteArgs as A, type BatchResult as B, type ClientConstructor as C, type DateTimeFilter as D, type DeleteManyArgs as E, type FindArgs as F, type CountArgs as G, type CountResult as H, type IncludeInput as I, type JsonArray as J, type AggregateArgs as K, type AggregateResult as L, type ModelResult as M, type NumberFilter as N, type OrderBy as O, type GroupByArgs as P, type GroupByResult as Q, type RuntimePlugin as R, type SimplifiedModelResult as S, type ToKysely as T, type UpdateArgs as U, type OnKyselyQueryArgs as V, type WhereInput as W, type ZenStackPromise as Z, type JsonObject as a, type JsonValue as b, type ClientContract as c, type ClientOptions as d, definePlugin as e, type TypeDefResult as f, type StringFilter as g, type BytesFilter as h, type BooleanFilter as i, type SortOrder as j, type NullsOrder as k, type WhereUniqueInput as l, type OmitInput as m, type SelectIncludeOmit as n, type SelectInput as o, type Subset as p, type SelectSubset as q, type FindManyArgs as r, type FindFirstArgs as s, type FindUniqueArgs as t, type CreateArgs as u, type CreateManyArgs as v, type CreateManyAndReturnArgs as w, type UpdateManyArgs as x, type UpdateManyAndReturnArgs as y, type UpsertArgs as z };