@zenstackhq/runtime 3.0.0-alpha.2 → 3.0.0-alpha.21

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