@danielhritcu/zenstack-orm 3.5.4

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +34 -0
  3. package/dist/dialects/mysql.cjs +31 -0
  4. package/dist/dialects/mysql.cjs.map +1 -0
  5. package/dist/dialects/mysql.d.cts +1 -0
  6. package/dist/dialects/mysql.d.ts +1 -0
  7. package/dist/dialects/mysql.js +6 -0
  8. package/dist/dialects/mysql.js.map +1 -0
  9. package/dist/dialects/postgres.cjs +31 -0
  10. package/dist/dialects/postgres.cjs.map +1 -0
  11. package/dist/dialects/postgres.d.cts +1 -0
  12. package/dist/dialects/postgres.d.ts +1 -0
  13. package/dist/dialects/postgres.js +6 -0
  14. package/dist/dialects/postgres.js.map +1 -0
  15. package/dist/dialects/sql.js.cjs +108 -0
  16. package/dist/dialects/sql.js.cjs.map +1 -0
  17. package/dist/dialects/sql.js.d.cts +32 -0
  18. package/dist/dialects/sql.js.d.ts +32 -0
  19. package/dist/dialects/sql.js.js +83 -0
  20. package/dist/dialects/sql.js.js.map +1 -0
  21. package/dist/dialects/sqlite.cjs +31 -0
  22. package/dist/dialects/sqlite.cjs.map +1 -0
  23. package/dist/dialects/sqlite.d.cts +1 -0
  24. package/dist/dialects/sqlite.d.ts +1 -0
  25. package/dist/dialects/sqlite.js +6 -0
  26. package/dist/dialects/sqlite.js.map +1 -0
  27. package/dist/helpers.cjs +31 -0
  28. package/dist/helpers.cjs.map +1 -0
  29. package/dist/helpers.d.cts +1 -0
  30. package/dist/helpers.d.ts +1 -0
  31. package/dist/helpers.js +6 -0
  32. package/dist/helpers.js.map +1 -0
  33. package/dist/index.cjs +10630 -0
  34. package/dist/index.cjs.map +1 -0
  35. package/dist/index.d.cts +3377 -0
  36. package/dist/index.d.ts +3377 -0
  37. package/dist/index.js +10580 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/schema.cjs +25 -0
  40. package/dist/schema.cjs.map +1 -0
  41. package/dist/schema.d.cts +2 -0
  42. package/dist/schema.d.ts +2 -0
  43. package/dist/schema.js +3 -0
  44. package/dist/schema.js.map +1 -0
  45. package/package.json +156 -0
@@ -0,0 +1,3377 @@
1
+ import * as _zenstackhq_schema from '@zenstackhq/schema';
2
+ import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, NonRelationFields, GetModel, ProcedureDef, BuiltinType, FieldDef, ModelDef, DataSourceProviderType, IsDelegateModel, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, GetTypeDefFieldType, TypeDefFieldIsArray, UpdatedAtInfo, FieldIsDelegateDiscriminator, FieldType, RelationInfo, Expression as Expression$1, LiteralExpression, ArrayExpression, FieldExpression, MemberExpression, BinaryExpression, UnaryExpression, CallExpression, BindingExpression, ThisExpression, NullExpression } from '@zenstackhq/schema';
3
+ import * as kysely from 'kysely';
4
+ import { Kysely, OperationNodeVisitor, OperationNode, SelectQueryNode, SelectionNode, ColumnNode, AliasNode, TableNode, FromNode, ReferenceNode, AndNode, OrNode, ValueListNode, ParensNode, JoinNode, RawNode, WhereNode, InsertQueryNode, DeleteQueryNode, ReturningNode, CreateTableNode, AddColumnNode, ColumnDefinitionNode, DropTableNode, OrderByNode, OrderByItemNode, GroupByNode, GroupByItemNode, UpdateQueryNode, ColumnUpdateNode, LimitNode, OffsetNode, OnConflictNode, OnDuplicateKeyNode, CheckConstraintNode, DataTypeNode, SelectAllNode, IdentifierNode, SchemableIdentifierNode, ValueNode, PrimitiveValueListNode, OperatorNode, CreateIndexNode, DropIndexNode, ListNode, PrimaryKeyConstraintNode, UniqueConstraintNode, ReferencesNode, WithNode, CommonTableExpressionNode, CommonTableExpressionNameNode, HavingNode, CreateSchemaNode, DropSchemaNode, AlterTableNode, DropColumnNode, RenameColumnNode, AlterColumnNode, ModifyColumnNode, AddConstraintNode, DropConstraintNode, ForeignKeyConstraintNode, CreateViewNode, DropViewNode, GeneratedNode, DefaultValueNode, OnNode, ValuesNode, SelectModifierNode, CreateTypeNode, DropTypeNode, ExplainNode, DefaultInsertValueNode, AggregateFunctionNode, OverNode, PartitionByNode, PartitionByItemNode, SetOperationNode, BinaryOperationNode, UnaryOperationNode, UsingNode, FunctionNode, CaseNode, WhenNode, JSONReferenceNode, JSONPathNode, JSONPathLegNode, JSONOperatorChainNode, TupleNode, MergeQueryNode, MatchedNode, AddIndexNode, CastNode, FetchNode, TopNode, OutputNode, RenameConstraintNode, RefreshMaterializedViewNode, OrActionNode, CollateNode, Generated, QueryId, RootOperationNode, QueryResult, UnknownRow, Dialect, ExpressionBuilder, Expression, KyselyConfig, OperandExpression, SelectQueryBuilder, SqlBool, AliasableExpression, ExpressionWrapper } from 'kysely';
5
+ import Decimal from 'decimal.js';
6
+ import { ZodType } from 'zod';
7
+
8
+ declare class DefaultOperationNodeVisitor extends OperationNodeVisitor {
9
+ protected defaultVisit(node: OperationNode): void;
10
+ protected visitSelectQuery(node: SelectQueryNode): void;
11
+ protected visitSelection(node: SelectionNode): void;
12
+ protected visitColumn(node: ColumnNode): void;
13
+ protected visitAlias(node: AliasNode): void;
14
+ protected visitTable(node: TableNode): void;
15
+ protected visitFrom(node: FromNode): void;
16
+ protected visitReference(node: ReferenceNode): void;
17
+ protected visitAnd(node: AndNode): void;
18
+ protected visitOr(node: OrNode): void;
19
+ protected visitValueList(node: ValueListNode): void;
20
+ protected visitParens(node: ParensNode): void;
21
+ protected visitJoin(node: JoinNode): void;
22
+ protected visitRaw(node: RawNode): void;
23
+ protected visitWhere(node: WhereNode): void;
24
+ protected visitInsertQuery(node: InsertQueryNode): void;
25
+ protected visitDeleteQuery(node: DeleteQueryNode): void;
26
+ protected visitReturning(node: ReturningNode): void;
27
+ protected visitCreateTable(node: CreateTableNode): void;
28
+ protected visitAddColumn(node: AddColumnNode): void;
29
+ protected visitColumnDefinition(node: ColumnDefinitionNode): void;
30
+ protected visitDropTable(node: DropTableNode): void;
31
+ protected visitOrderBy(node: OrderByNode): void;
32
+ protected visitOrderByItem(node: OrderByItemNode): void;
33
+ protected visitGroupBy(node: GroupByNode): void;
34
+ protected visitGroupByItem(node: GroupByItemNode): void;
35
+ protected visitUpdateQuery(node: UpdateQueryNode): void;
36
+ protected visitColumnUpdate(node: ColumnUpdateNode): void;
37
+ protected visitLimit(node: LimitNode): void;
38
+ protected visitOffset(node: OffsetNode): void;
39
+ protected visitOnConflict(node: OnConflictNode): void;
40
+ protected visitOnDuplicateKey(node: OnDuplicateKeyNode): void;
41
+ protected visitCheckConstraint(node: CheckConstraintNode): void;
42
+ protected visitDataType(node: DataTypeNode): void;
43
+ protected visitSelectAll(node: SelectAllNode): void;
44
+ protected visitIdentifier(node: IdentifierNode): void;
45
+ protected visitSchemableIdentifier(node: SchemableIdentifierNode): void;
46
+ protected visitValue(node: ValueNode): void;
47
+ protected visitPrimitiveValueList(node: PrimitiveValueListNode): void;
48
+ protected visitOperator(node: OperatorNode): void;
49
+ protected visitCreateIndex(node: CreateIndexNode): void;
50
+ protected visitDropIndex(node: DropIndexNode): void;
51
+ protected visitList(node: ListNode): void;
52
+ protected visitPrimaryKeyConstraint(node: PrimaryKeyConstraintNode): void;
53
+ protected visitUniqueConstraint(node: UniqueConstraintNode): void;
54
+ protected visitReferences(node: ReferencesNode): void;
55
+ protected visitWith(node: WithNode): void;
56
+ protected visitCommonTableExpression(node: CommonTableExpressionNode): void;
57
+ protected visitCommonTableExpressionName(node: CommonTableExpressionNameNode): void;
58
+ protected visitHaving(node: HavingNode): void;
59
+ protected visitCreateSchema(node: CreateSchemaNode): void;
60
+ protected visitDropSchema(node: DropSchemaNode): void;
61
+ protected visitAlterTable(node: AlterTableNode): void;
62
+ protected visitDropColumn(node: DropColumnNode): void;
63
+ protected visitRenameColumn(node: RenameColumnNode): void;
64
+ protected visitAlterColumn(node: AlterColumnNode): void;
65
+ protected visitModifyColumn(node: ModifyColumnNode): void;
66
+ protected visitAddConstraint(node: AddConstraintNode): void;
67
+ protected visitDropConstraint(node: DropConstraintNode): void;
68
+ protected visitForeignKeyConstraint(node: ForeignKeyConstraintNode): void;
69
+ protected visitCreateView(node: CreateViewNode): void;
70
+ protected visitDropView(node: DropViewNode): void;
71
+ protected visitGenerated(node: GeneratedNode): void;
72
+ protected visitDefaultValue(node: DefaultValueNode): void;
73
+ protected visitOn(node: OnNode): void;
74
+ protected visitValues(node: ValuesNode): void;
75
+ protected visitSelectModifier(node: SelectModifierNode): void;
76
+ protected visitCreateType(node: CreateTypeNode): void;
77
+ protected visitDropType(node: DropTypeNode): void;
78
+ protected visitExplain(node: ExplainNode): void;
79
+ protected visitDefaultInsertValue(node: DefaultInsertValueNode): void;
80
+ protected visitAggregateFunction(node: AggregateFunctionNode): void;
81
+ protected visitOver(node: OverNode): void;
82
+ protected visitPartitionBy(node: PartitionByNode): void;
83
+ protected visitPartitionByItem(node: PartitionByItemNode): void;
84
+ protected visitSetOperation(node: SetOperationNode): void;
85
+ protected visitBinaryOperation(node: BinaryOperationNode): void;
86
+ protected visitUnaryOperation(node: UnaryOperationNode): void;
87
+ protected visitUsing(node: UsingNode): void;
88
+ protected visitFunction(node: FunctionNode): void;
89
+ protected visitCase(node: CaseNode): void;
90
+ protected visitWhen(node: WhenNode): void;
91
+ protected visitJSONReference(node: JSONReferenceNode): void;
92
+ protected visitJSONPath(node: JSONPathNode): void;
93
+ protected visitJSONPathLeg(node: JSONPathLegNode): void;
94
+ protected visitJSONOperatorChain(node: JSONOperatorChainNode): void;
95
+ protected visitTuple(node: TupleNode): void;
96
+ protected visitMergeQuery(node: MergeQueryNode): void;
97
+ protected visitMatched(node: MatchedNode): void;
98
+ protected visitAddIndex(node: AddIndexNode): void;
99
+ protected visitCast(node: CastNode): void;
100
+ protected visitFetch(node: FetchNode): void;
101
+ protected visitTop(node: TopNode): void;
102
+ protected visitOutput(node: OutputNode): void;
103
+ protected visitRenameConstraint(node: RenameConstraintNode): void;
104
+ protected visitRefreshMaterializedView(node: RefreshMaterializedViewNode): void;
105
+ protected visitOrAction(node: OrActionNode): void;
106
+ protected visitCollate(node: CollateNode): void;
107
+ }
108
+ type AnyKysely = Kysely<any>;
109
+
110
+ type kyselyUtils_AnyKysely = AnyKysely;
111
+ type kyselyUtils_DefaultOperationNodeVisitor = DefaultOperationNodeVisitor;
112
+ declare const kyselyUtils_DefaultOperationNodeVisitor: typeof DefaultOperationNodeVisitor;
113
+ declare namespace kyselyUtils {
114
+ export { type kyselyUtils_AnyKysely as AnyKysely, kyselyUtils_DefaultOperationNodeVisitor as DefaultOperationNodeVisitor };
115
+ }
116
+
117
+ type JsonValue = string | number | boolean | JsonObject | JsonArray;
118
+ type JsonObject = {
119
+ [key: string]: JsonValue | null;
120
+ };
121
+ type JsonArray = ReadonlyArray<JsonValue | null>;
122
+ type JsonNullValues = DbNull | JsonNull | AnyNull;
123
+ declare class DbNullClass {
124
+ private __brand;
125
+ }
126
+ declare const DbNull: DbNullClass;
127
+ type DbNull = typeof DbNull;
128
+ declare class JsonNullClass {
129
+ private __brand;
130
+ }
131
+ declare const JsonNull: JsonNullClass;
132
+ type JsonNull = typeof JsonNull;
133
+ declare class AnyNullClass {
134
+ private __brand;
135
+ }
136
+ declare const AnyNull: AnyNullClass;
137
+ type AnyNull = typeof AnyNull;
138
+
139
+ type Optional<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
140
+ type PartialIf<T, Condition extends boolean> = Condition extends true ? Partial<T> : T;
141
+ type NullableIf<T, Condition extends boolean> = Condition extends true ? T | null : T;
142
+ type _Preserve = Date | Function | Decimal | Uint8Array | JsonObject | JsonValue;
143
+ type _Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
144
+ type Simplify<T, D extends number = 6> = D extends 0 ? T : T extends object ? T extends _Preserve ? T : {
145
+ [K in keyof T]: Simplify<T[K], _Depth[D]>;
146
+ } & {} : T;
147
+ type WrapType<T, Optional = false, Array = false> = Array extends true ? Optional extends true ? T[] | null : T[] : Optional extends true ? T | null : T;
148
+ type TypeMap = {
149
+ String: string;
150
+ Boolean: boolean;
151
+ Int: number;
152
+ Float: number;
153
+ BigInt: bigint;
154
+ Decimal: Decimal;
155
+ DateTime: Date;
156
+ Bytes: Uint8Array;
157
+ Json: JsonValue;
158
+ Null: null;
159
+ Object: Record<string, unknown>;
160
+ Any: unknown;
161
+ Unsupported: unknown;
162
+ Void: void;
163
+ Undefined: undefined;
164
+ };
165
+ type MapBaseType$1<T extends string> = T extends keyof TypeMap ? TypeMap[T] : unknown;
166
+ type OrArray<T, IF extends boolean = true> = IF extends true ? T | T[] : T;
167
+ type NonEmptyArray<T> = [T, ...T[]];
168
+ type ValueOfPotentialTuple<T> = T extends unknown[] ? T[number] : T;
169
+ type NoExpand<T> = T extends unknown ? T : never;
170
+ type AtLeast<O extends object, K extends string> = NoExpand<O extends unknown ? (K extends keyof O ? {
171
+ [P in K]: O[P];
172
+ } & O : O) | ({
173
+ [P in keyof O as P extends K ? K : never]-?: O[P];
174
+ } & O) : never>;
175
+ type Without<T, U> = {
176
+ [P in Exclude<keyof T, keyof U>]?: never;
177
+ };
178
+ type XOR<T, U> = T extends object ? (U extends object ? (Without<T, U> & U) | (Without<U, T> & T) : U) : T;
179
+ type MaybePromise<T> = T | Promise<T>;
180
+ type OrUndefinedIf<T, Condition extends boolean> = Condition extends true ? T | undefined : T;
181
+ type UnwrapTuplePromises<T extends readonly unknown[]> = {
182
+ [K in keyof T]: Awaited<T[K]>;
183
+ };
184
+
185
+ /**
186
+ * Client API methods that are not supported in transactions.
187
+ */
188
+ declare const TRANSACTION_UNSUPPORTED_METHODS: readonly ["$transaction", "$connect", "$disconnect", "$use"];
189
+ /**
190
+ * Logical combinators used in filters.
191
+ */
192
+ declare const LOGICAL_COMBINATORS: readonly ["AND", "OR", "NOT"];
193
+ /**
194
+ * Aggregation operators.
195
+ */
196
+ declare const AggregateOperators: readonly ["_count", "_sum", "_avg", "_min", "_max"];
197
+ type AggregateOperators = (typeof AggregateOperators)[number];
198
+ /**
199
+ * Mapping of filter operators to their corresponding filter kind categories.
200
+ */
201
+ declare const FILTER_PROPERTY_TO_KIND: {
202
+ readonly equals: "Equality";
203
+ readonly not: "Equality";
204
+ readonly in: "Equality";
205
+ readonly notIn: "Equality";
206
+ readonly lt: "Range";
207
+ readonly lte: "Range";
208
+ readonly gt: "Range";
209
+ readonly gte: "Range";
210
+ readonly between: "Range";
211
+ readonly contains: "Like";
212
+ readonly startsWith: "Like";
213
+ readonly endsWith: "Like";
214
+ readonly mode: "Like";
215
+ readonly is: "Relation";
216
+ readonly isNot: "Relation";
217
+ readonly some: "Relation";
218
+ readonly every: "Relation";
219
+ readonly none: "Relation";
220
+ readonly path: "Json";
221
+ readonly string_contains: "Json";
222
+ readonly string_starts_with: "Json";
223
+ readonly string_ends_with: "Json";
224
+ readonly array_contains: "Json";
225
+ readonly array_starts_with: "Json";
226
+ readonly array_ends_with: "Json";
227
+ readonly has: "List";
228
+ readonly hasEvery: "List";
229
+ readonly hasSome: "List";
230
+ readonly isEmpty: "List";
231
+ };
232
+ /**
233
+ * Mapping of filter operators to their corresponding filter kind categories.
234
+ */
235
+ type FilterPropertyToKind = typeof FILTER_PROPERTY_TO_KIND;
236
+
237
+ type ToKyselySchema<Schema extends SchemaDef> = {
238
+ [Model in GetModels<Schema>]: ToKyselyTable<Schema, Model>;
239
+ };
240
+ type ToKysely<Schema extends SchemaDef> = Kysely<ToKyselySchema<Schema>>;
241
+ type ToKyselyTable<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
242
+ [Field in ScalarFields<Schema, Model, false> | ForeignKeyFields<Schema, Model> as GetModelField<Schema, Model, Field>['originModel'] extends string ? never : Field]: toKyselyFieldType<Schema, Model, Field>;
243
+ };
244
+ 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;
245
+ type WrapNull<T, Null> = Null extends true ? T | null : T;
246
+ 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>>;
247
+ 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>;
248
+
249
+ type AllowedExtQueryArgKeys = CoreCrudOperations | '$create' | '$read' | '$update' | '$delete' | '$all';
250
+ /**
251
+ * Base shape of plugin-extended query args.
252
+ */
253
+ type ExtQueryArgsBase = {
254
+ [K in AllowedExtQueryArgKeys]?: object;
255
+ };
256
+ /**
257
+ * Base type for plugin-extended client members (methods and properties).
258
+ * Member names should start with '$' to avoid model name conflicts.
259
+ */
260
+ type ExtClientMembersBase = Record<string, unknown>;
261
+ /**
262
+ * Base shape of plugin-extended result fields.
263
+ * Keyed by model name, each value maps field names to their definitions.
264
+ * `needs` keys are constrained to non-relation fields of the corresponding model.
265
+ */
266
+ type ExtResultBase<Schema extends SchemaDef = SchemaDef> = {
267
+ [M in GetModels<Schema> as Uncapitalize<M>]?: Record<string, {
268
+ needs: Partial<Record<NonRelationFields<Schema, M>, true>>;
269
+ compute: (...args: any[]) => any;
270
+ }>;
271
+ };
272
+ /**
273
+ * Mapped type that provides per-field contextual typing for `compute` callbacks
274
+ * based on the `needs` declaration. Uses a separate type parameter `R_` that captures
275
+ * the needs shape (model → field → { neededField: true }), then links each field's
276
+ * `compute` parameter to exactly the keys declared in its `needs`.
277
+ */
278
+ type ExtResultInferenceArgs<Schema extends SchemaDef, R_> = {
279
+ [K in keyof R_ & string]: {
280
+ [P in keyof R_[K]]?: {
281
+ needs?: {
282
+ [F in keyof R_[K][P]]: F extends NonRelationFields<Schema, ModelNameFromKey<Schema, K>> ? true : never;
283
+ } & Partial<Record<NonRelationFields<Schema, ModelNameFromKey<Schema, K>>, true>>;
284
+ compute: (data: ExtResultComputeData<Schema, ModelNameFromKey<Schema, K>, R_[K][P]>) => unknown;
285
+ };
286
+ };
287
+ };
288
+ /**
289
+ * Reverse-maps an uncapitalized key back to the original model name in the schema.
290
+ * E.g., for a schema with model `myModel`, the key `myModel` maps back to `myModel`
291
+ * (not `MyModel` as `Capitalize` would produce).
292
+ */
293
+ type ModelNameFromKey<Schema extends SchemaDef, K extends string> = {
294
+ [M in GetModels<Schema>]: Uncapitalize<M> extends K ? M : never;
295
+ }[GetModels<Schema>];
296
+ /**
297
+ * Maps the needs shape `S` to an object with actual schema field types.
298
+ * For each key in `S` that is a valid non-relation field of model `M`,
299
+ * resolves the TypeScript type from the schema field definition.
300
+ */
301
+ type ExtResultComputeData<Schema extends SchemaDef, M extends GetModels<Schema>, S> = {
302
+ [F in keyof S & GetModelFields<Schema, M>]: MapModelFieldType<Schema, M, F>;
303
+ };
304
+ /**
305
+ * ZenStack runtime plugin.
306
+ */
307
+ interface RuntimePlugin<Schema extends SchemaDef, ExtQueryArgs extends ExtQueryArgsBase, ExtClientMembers extends Record<string, unknown>, ExtResult extends ExtResultBase<Schema>> {
308
+ /**
309
+ * Plugin ID.
310
+ */
311
+ id: string;
312
+ /**
313
+ * Plugin display name.
314
+ */
315
+ name?: string;
316
+ /**
317
+ * Plugin description.
318
+ */
319
+ description?: string;
320
+ /**
321
+ * Custom function implementations.
322
+ * @private
323
+ */
324
+ functions?: Record<string, ZModelFunction<Schema>>;
325
+ /**
326
+ * Intercepts an ORM query.
327
+ */
328
+ onQuery?: OnQueryCallback<Schema>;
329
+ /**
330
+ * Intercepts a procedure invocation.
331
+ */
332
+ onProcedure?: OnProcedureCallback<Schema>;
333
+ /**
334
+ * Intercepts an entity mutation.
335
+ */
336
+ onEntityMutation?: EntityMutationHooksDef<Schema>;
337
+ /**
338
+ * Intercepts a Kysely query.
339
+ */
340
+ onKyselyQuery?: OnKyselyQueryCallback<Schema>;
341
+ /**
342
+ * Extended query args configuration.
343
+ */
344
+ queryArgs?: {
345
+ [K in keyof ExtQueryArgs]: ZodType<ExtQueryArgs[K]>;
346
+ };
347
+ /**
348
+ * Extended client members (methods and properties).
349
+ */
350
+ client?: ExtClientMembers;
351
+ /**
352
+ * Extended result fields on query results.
353
+ * Keyed by model name, each value defines computed fields with `needs` and `compute`.
354
+ */
355
+ result?: ExtResult;
356
+ }
357
+ type AnyPlugin = RuntimePlugin<any, any, any, any>;
358
+ /**
359
+ * Defines a ZenStack runtime plugin based on type of the given schema.
360
+ *
361
+ * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation}
362
+ *
363
+ * @example
364
+ * ```typescript
365
+ * definePlugin(schema, {
366
+ * id: 'my-plugin',
367
+ * result: {
368
+ * user: {
369
+ * fullName: {
370
+ * needs: { firstName: true, lastName: true },
371
+ * compute: (user) => `${user.firstName} ${user.lastName}`,
372
+ * },
373
+ * },
374
+ * },
375
+ * });
376
+ * ```
377
+ */
378
+ declare function definePlugin<Schema extends SchemaDef, const ExtQueryArgs extends ExtQueryArgsBase = {}, const ExtClientMembers extends Record<string, unknown> = {}, const ExtResult extends ExtResultBase<Schema> = {}, R_ = {}>(schema: Schema, plugin: RuntimePlugin<Schema, ExtQueryArgs, ExtClientMembers, ExtResult> & {
379
+ result?: ExtResultInferenceArgs<Schema, R_>;
380
+ }): RuntimePlugin<Schema, ExtQueryArgs, ExtClientMembers, ExtResult>;
381
+ /**
382
+ * Defines a ZenStack runtime plugin.
383
+ *
384
+ * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation}
385
+ *
386
+ * @example
387
+ * ```typescript
388
+ * definePlugin(schema, {
389
+ * id: 'my-plugin',
390
+ * result: {
391
+ * user: {
392
+ * fullName: {
393
+ * needs: { firstName: true, lastName: true },
394
+ * compute: (user) => `${user.firstName} ${user.lastName}`,
395
+ * },
396
+ * },
397
+ * },
398
+ * });
399
+ * ```
400
+ * */
401
+ declare function definePlugin<Schema extends SchemaDef, const ExtQueryArgs extends ExtQueryArgsBase = {}, const ExtClientMembers extends Record<string, unknown> = {}, const ExtResult extends ExtResultBase<Schema> = {}>(plugin: RuntimePlugin<Schema, ExtQueryArgs, ExtClientMembers, ExtResult>): RuntimePlugin<Schema, ExtQueryArgs, ExtClientMembers, ExtResult>;
402
+ type OnProcedureCallback<Schema extends SchemaDef> = (ctx: OnProcedureHookContext<Schema>) => Promise<unknown>;
403
+ type OnProcedureHookContext<Schema extends SchemaDef> = {
404
+ /**
405
+ * The procedure name.
406
+ */
407
+ name: string;
408
+ /**
409
+ * Whether the procedure is a mutation.
410
+ */
411
+ mutation: boolean;
412
+ /**
413
+ * Procedure invocation input (envelope).
414
+ *
415
+ * The canonical shape is `{ args?: Record<string, unknown> }`.
416
+ * When a procedure has required params, `args` is required.
417
+ */
418
+ input: unknown;
419
+ /**
420
+ * Continues the invocation. The input passed here is forwarded to the next handler.
421
+ */
422
+ proceed: (input: unknown) => Promise<unknown>;
423
+ /**
424
+ * The ZenStack client that is invoking the procedure.
425
+ */
426
+ client: ClientContract<Schema>;
427
+ };
428
+ type OnQueryCallback<Schema extends SchemaDef> = (ctx: OnQueryHookContext<Schema>) => Promise<unknown>;
429
+ type OnQueryHookContext<Schema extends SchemaDef> = {
430
+ /**
431
+ * The model that is being queried.
432
+ */
433
+ model: GetModels<Schema>;
434
+ /**
435
+ * The operation that is being performed.
436
+ */
437
+ operation: AllCrudOperations;
438
+ /**
439
+ * The query arguments.
440
+ */
441
+ args: Record<string, unknown> | undefined;
442
+ /**
443
+ * The function to proceed with the original query.
444
+ * It takes the same arguments as the operation method.
445
+ *
446
+ * @param args The query arguments.
447
+ */
448
+ proceed: (args: Record<string, unknown> | undefined) => Promise<unknown>;
449
+ /**
450
+ * The ZenStack client that is performing the operation.
451
+ */
452
+ client: ClientContract<Schema>;
453
+ };
454
+ type EntityMutationHooksDef<Schema extends SchemaDef> = {
455
+ /**
456
+ * Called before entities are mutated.
457
+ */
458
+ beforeEntityMutation?: BeforeEntityMutationCallback<Schema>;
459
+ /**
460
+ * Called after entities are mutated.
461
+ */
462
+ afterEntityMutation?: AfterEntityMutationCallback<Schema>;
463
+ /**
464
+ * Whether to run after-mutation hooks within the transaction that performs the mutation.
465
+ *
466
+ * If set to `true`, if the mutation already runs inside a transaction, the callbacks are
467
+ * executed immediately after the mutation within the transaction boundary. If the mutation
468
+ * is not running inside a transaction, a new transaction is created to run both the mutation
469
+ * and the callbacks.
470
+ *
471
+ * If set to `false`, the callbacks are executed after the mutation transaction is committed.
472
+ *
473
+ * Defaults to `false`.
474
+ */
475
+ runAfterMutationWithinTransaction?: boolean;
476
+ };
477
+ type MutationHooksArgs<Schema extends SchemaDef> = {
478
+ /**
479
+ * The model that is being mutated.
480
+ */
481
+ model: GetModels<Schema>;
482
+ /**
483
+ * The mutation action that is being performed.
484
+ */
485
+ action: 'create' | 'update' | 'delete';
486
+ /**
487
+ * The mutation data. Only available for create and update actions.
488
+ */
489
+ queryNode: OperationNode;
490
+ /**
491
+ * A query ID that uniquely identifies the mutation operation. You can use it to correlate
492
+ * data between the before and after mutation hooks.
493
+ */
494
+ queryId: QueryId;
495
+ };
496
+ type BeforeEntityMutationCallback<Schema extends SchemaDef> = (args: PluginBeforeEntityMutationArgs<Schema>) => MaybePromise<void>;
497
+ type AfterEntityMutationCallback<Schema extends SchemaDef> = (args: PluginAfterEntityMutationArgs<Schema>) => MaybePromise<void>;
498
+ type PluginBeforeEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
499
+ /**
500
+ * Loads the entities that are about to be mutated. The db operation that loads the entities is executed
501
+ * within the same transaction context as the mutation.
502
+ */
503
+ loadBeforeMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
504
+ /**
505
+ * The ZenStack client you can use to perform additional operations. The database operations initiated
506
+ * from this client are executed within the same transaction as the mutation if the mutation is running
507
+ * inside a transaction.
508
+ *
509
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
510
+ */
511
+ client: ClientContract<Schema>;
512
+ };
513
+ type PluginAfterEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
514
+ /**
515
+ * Loads the entities that have been mutated.
516
+ */
517
+ loadAfterMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
518
+ /**
519
+ * The entities before mutation. Only available if `beforeEntityMutation` hook is provided and
520
+ * the `loadBeforeMutationEntities` function is called in that hook.
521
+ */
522
+ beforeMutationEntities?: Record<string, unknown>[];
523
+ /**
524
+ * The ZenStack client you can use to perform additional operations.
525
+ * See {@link EntityMutationHooksDef.runAfterMutationWithinTransaction} for detailed transaction behavior.
526
+ *
527
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
528
+ */
529
+ client: ClientContract<Schema>;
530
+ };
531
+ type OnKyselyQueryArgs<Schema extends SchemaDef> = {
532
+ schema: SchemaDef;
533
+ client: ClientContract<Schema>;
534
+ query: RootOperationNode;
535
+ proceed: ProceedKyselyQueryFunction;
536
+ };
537
+ type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise<QueryResult<any>>;
538
+ type OnKyselyQueryCallback<Schema extends SchemaDef> = (args: OnKyselyQueryArgs<Schema>) => Promise<QueryResult<UnknownRow>>;
539
+
540
+ type ZModelFunctionContext<Schema extends SchemaDef> = {
541
+ /**
542
+ * ZenStack client instance
543
+ */
544
+ client: ClientContract<Schema>;
545
+ /**
546
+ * Database dialect
547
+ */
548
+ dialect: BaseCrudDialect<Schema>;
549
+ /**
550
+ * The containing model name
551
+ */
552
+ model: GetModels<Schema>;
553
+ /**
554
+ * The alias name that can be used to refer to the containing model
555
+ */
556
+ modelAlias: string;
557
+ /**
558
+ * The CRUD operation being performed
559
+ */
560
+ operation: CRUD_EXT;
561
+ };
562
+ type ZModelFunction<Schema extends SchemaDef> = (eb: ExpressionBuilder<ToKyselySchema<Schema>, keyof ToKyselySchema<Schema>>, args: Expression<any>[], context: ZModelFunctionContext<Schema>) => Expression<unknown>;
563
+ /**
564
+ * Options for slicing ORM client's capabilities by including/excluding certain models, operations,
565
+ * filters, etc.
566
+ */
567
+ type SlicingOptions<Schema extends SchemaDef> = {
568
+ /**
569
+ * Models to include in the client. If not specified, all models are included by default.
570
+ */
571
+ includedModels?: readonly GetModels<Schema>[];
572
+ /**
573
+ * Models to exclude from the client. Exclusion takes precedence over inclusion.
574
+ */
575
+ excludedModels?: readonly GetModels<Schema>[];
576
+ /**
577
+ * Model slicing options.
578
+ */
579
+ models?: {
580
+ [Model in GetModels<Schema> as Uncapitalize<Model>]?: ModelSlicingOptions<Schema, Model>;
581
+ } & {
582
+ /**
583
+ * Slicing options that apply to all models. Model-specific options will override these general
584
+ * options if both are specified.
585
+ */
586
+ $all?: ModelSlicingOptions<Schema, GetModels<Schema>>;
587
+ };
588
+ /**
589
+ * Procedures to include in the client. If not specified, all procedures are included by default.
590
+ */
591
+ includedProcedures?: readonly GetProcedureNames<Schema>[];
592
+ /**
593
+ * Procedures to exclude from the client. Exclusion takes precedence over inclusion.
594
+ */
595
+ excludedProcedures?: readonly GetProcedureNames<Schema>[];
596
+ };
597
+ /**
598
+ * Kinds of filter operations.
599
+ */
600
+ type FilterKind = FilterPropertyToKind[keyof FilterPropertyToKind];
601
+ /**
602
+ * Model slicing options.
603
+ */
604
+ type ModelSlicingOptions<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
605
+ /**
606
+ * ORM query operations to include for the model. If not specified, all operations are included
607
+ * by default.
608
+ */
609
+ includedOperations?: readonly AllCrudOperations[];
610
+ /**
611
+ * ORM query operations to exclude for the model. Exclusion takes precedence over inclusion.
612
+ */
613
+ excludedOperations?: readonly AllCrudOperations[];
614
+ /**
615
+ * Field-level slicing options.
616
+ */
617
+ fields?: {
618
+ [Field in GetModelFields<Schema, Model>]?: FieldSlicingOptions;
619
+ } & {
620
+ /**
621
+ * Field slicing options that apply to all fields. Field-specific options will override these
622
+ * general options if both are specified.
623
+ */
624
+ $all?: FieldSlicingOptions;
625
+ };
626
+ };
627
+ /**
628
+ * Field slicing options.
629
+ */
630
+ type FieldSlicingOptions = {
631
+ /**
632
+ * Filter kinds to include for the field. If not specified, all filter kinds are included by default.
633
+ */
634
+ includedFilterKinds?: readonly FilterKind[];
635
+ /**
636
+ * Filter kinds to exclude for the field. Exclusion takes precedence over inclusion.
637
+ */
638
+ excludedFilterKinds?: readonly FilterKind[];
639
+ };
640
+ /**
641
+ * Partial ORM client options that defines customizable behaviors.
642
+ */
643
+ type QueryOptions<Schema extends SchemaDef> = {
644
+ /**
645
+ * Options for omitting fields in ORM query results.
646
+ */
647
+ omit?: OmitConfig<Schema>;
648
+ /**
649
+ * Whether to allow overriding omit settings at query time. Defaults to `true`. When set to `false`, a
650
+ * query-time `omit` clause that sets the field to `false` (not omitting) will trigger a validation error.
651
+ */
652
+ allowQueryTimeOmitOverride?: boolean;
653
+ /**
654
+ * Options for slicing ORM client's capabilities by including/excluding certain models, operations, filters, etc.
655
+ */
656
+ slicing?: SlicingOptions<Schema>;
657
+ };
658
+ /**
659
+ * ZenStack client options.
660
+ */
661
+ type ClientOptions<Schema extends SchemaDef> = QueryOptions<Schema> & {
662
+ /**
663
+ * Kysely dialect.
664
+ */
665
+ dialect: Dialect;
666
+ /**
667
+ * Custom function definitions.
668
+ *
669
+ * @private
670
+ */
671
+ functions?: Record<string, ZModelFunction<Schema>>;
672
+ /**
673
+ * Plugins.
674
+ */
675
+ plugins?: AnyPlugin[];
676
+ /**
677
+ * Logging configuration. Extends Kysely's log config with a `'warning'` level
678
+ * for ZenStack-specific diagnostics (e.g., slow query warnings).
679
+ */
680
+ log?: KyselyConfig['log'];
681
+ /**
682
+ * Optional Kysely configuration overrides. When provided, these are merged into
683
+ * the internal Kysely instance props, allowing custom drivers, executors, or
684
+ * other Kysely config to flow through.
685
+ */
686
+ kyselyConfig?: Partial<KyselyConfig>;
687
+ /**
688
+ * Whether to automatically fix timezone for `DateTime` fields returned by node-pg. Defaults
689
+ * to `true`.
690
+ *
691
+ * Node-pg has a terrible quirk that it interprets the date value as local timezone (as a
692
+ * `Date` object) although for `DateTime` field the data in DB is stored in UTC.
693
+ * @see https://github.com/brianc/node-postgres/issues/429
694
+ */
695
+ fixPostgresTimezone?: boolean;
696
+ /**
697
+ * Whether to enable query args validation. Defaults to `true`.
698
+ *
699
+ * **USE WITH CAUTION**, as setting it to `false` will allow malformed input to pass through, causing
700
+ * incorrect SQL generation or runtime errors. If you use validation attributes like `@email`, `@regex`,
701
+ * etc., in ZModel, they will be ignored too.
702
+ */
703
+ validateInput?: boolean;
704
+ /**
705
+ * Whether to use compact alias names (e.g., "$$t1", "$$t2") when transforming ORM queries to SQL.
706
+ * Defaults to `true`.
707
+ *
708
+ * When set to `false`, original aliases are kept unless temporary aliases become too long for
709
+ * safe SQL identifier handling, in which case compact aliases are used as a fallback.
710
+ */
711
+ useCompactAliasNames?: boolean;
712
+ /**
713
+ * Whether to skip validation for whether all computed fields are properly defined.
714
+ */
715
+ skipValidationForComputedFields?: boolean;
716
+ /**
717
+ * Diagnostics related options.
718
+ */
719
+ diagnostics?: {
720
+ /**
721
+ * Threshold in milliseconds for determining slow queries. If not specified, no query will be considered slow.
722
+ */
723
+ slowQueryThresholdMs?: number;
724
+ /**
725
+ * Maximum number of slow query records to keep in memory. Defaults to `100`. When the number is exceeded, the
726
+ * entry with the lowest duration will be removed. Set to `Infinity` to keep unlimited records.
727
+ */
728
+ slowQueryMaxRecords?: number;
729
+ };
730
+ } & (HasComputedFields<Schema> extends true ? {
731
+ /**
732
+ * Computed field definitions.
733
+ */
734
+ computedFields: ComputedFieldsOptions<Schema>;
735
+ } : {}) & (HasProcedures<Schema> extends true ? {
736
+ /**
737
+ * Custom procedure definitions.
738
+ */
739
+ procedures: ProceduresOptions<Schema>;
740
+ } : {});
741
+ /**
742
+ * Config for omitting fields in ORM query results.
743
+ */
744
+ type OmitConfig<Schema extends SchemaDef> = {
745
+ [Model in GetModels<Schema> as Uncapitalize<Model>]?: {
746
+ [Field in GetModelFields<Schema, Model> as Field extends ScalarFields<Schema, Model> ? Field : never]?: boolean;
747
+ };
748
+ };
749
+ type ComputedFieldsOptions<Schema extends SchemaDef> = {
750
+ [Model in GetModels<Schema> as 'computedFields' extends keyof GetModel<Schema, Model> ? Uncapitalize<Model> : never]: {
751
+ [Field in keyof Schema['models'][Model]['computedFields']]: Schema['models'][Model]['computedFields'][Field] extends infer Func ? Func extends (...args: any[]) => infer R ? (p: ExpressionBuilder<ToKyselySchema<Schema>, Model>, ...args: Parameters<Func>) => OperandExpression<R> : never : never;
752
+ };
753
+ };
754
+ type HasComputedFields<Schema extends SchemaDef> = string extends GetModels<Schema> ? false : keyof ComputedFieldsOptions<Schema> extends never ? false : true;
755
+ type ProceduresOptions<Schema extends SchemaDef> = Schema extends {
756
+ procedures: Record<string, ProcedureDef>;
757
+ } ? {
758
+ [Key in GetProcedureNames<Schema>]: ProcedureHandlerFunc<Schema, Key>;
759
+ } : {};
760
+ type HasProcedures<Schema extends SchemaDef> = Schema extends {
761
+ procedures: Record<string, ProcedureDef>;
762
+ } ? true : false;
763
+ /**
764
+ * Extracts QueryOptions from an object with '$options' property.
765
+ */
766
+ type GetQueryOptions<T extends {
767
+ $options: any;
768
+ }> = T['$options'];
769
+
770
+ declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
771
+ protected readonly schema: Schema;
772
+ protected readonly options: ClientOptions<Schema>;
773
+ protected eb: ExpressionBuilder<any, any>;
774
+ constructor(schema: Schema, options: ClientOptions<Schema>);
775
+ /**
776
+ * Whether the dialect supports updating with a limit on the number of updated rows.
777
+ */
778
+ abstract get supportsUpdateWithLimit(): boolean;
779
+ /**
780
+ * Whether the dialect supports deleting with a limit on the number of deleted rows.
781
+ */
782
+ abstract get supportsDeleteWithLimit(): boolean;
783
+ /**
784
+ * Whether the dialect supports DISTINCT ON.
785
+ */
786
+ abstract get supportsDistinctOn(): boolean;
787
+ /**
788
+ * Whether the dialect support inserting with `DEFAULT` as field value.
789
+ */
790
+ abstract get supportsDefaultAsFieldValue(): boolean;
791
+ /**
792
+ * Whether the dialect supports the RETURNING clause in INSERT/UPDATE/DELETE statements.
793
+ */
794
+ abstract get supportsReturning(): boolean;
795
+ /**
796
+ * Whether the dialect supports `INSERT INTO ... DEFAULT VALUES` syntax.
797
+ */
798
+ abstract get supportsInsertDefaultValues(): boolean;
799
+ /**
800
+ * How to perform insert ignore operation.
801
+ */
802
+ abstract get insertIgnoreMethod(): 'onConflict' | 'ignore';
803
+ /**
804
+ * Transforms input value before sending to database.
805
+ */
806
+ transformInput(value: unknown, _type: BuiltinType, _forArrayField: boolean): unknown;
807
+ /**
808
+ * Transforms output value received from database.
809
+ */
810
+ transformOutput(value: unknown, _type: BuiltinType, _array: boolean): unknown;
811
+ buildSelectModel(model: string, modelAlias: string): SelectQueryBuilder<any, any, {}>;
812
+ buildFilterSortTake(model: string, args: FindArgs<Schema, GetModels<Schema>, any, true>, query: SelectQueryBuilder<any, any, {}>, modelAlias: string): SelectQueryBuilder<any, any, {}>;
813
+ buildFilter(model: string, modelAlias: string, where: boolean | object | undefined): Expression<SqlBool>;
814
+ private buildCursorFilter;
815
+ private isLogicalCombinator;
816
+ protected buildCompositeFilter(model: string, modelAlias: string, key: (typeof LOGICAL_COMBINATORS)[number], payload: any): Expression<SqlBool>;
817
+ private buildRelationFilter;
818
+ private buildToOneRelationFilter;
819
+ private buildToManyRelationFilter;
820
+ private buildArrayFilter;
821
+ buildPrimitiveFilter(fieldRef: Expression<any>, fieldDef: FieldDef, payload: any): any;
822
+ private buildJsonFilter;
823
+ private buildPlainJsonFilter;
824
+ private buildTypedJsonFilter;
825
+ private buildTypedJsonArrayFilter;
826
+ private buildTypeJsonNonArrayFilter;
827
+ private buildJsonValueFilterClause;
828
+ protected buildJsonEqualityFilter(lhs: Expression<any>, rhs: unknown): Expression<SqlBool>;
829
+ private buildValueFilter;
830
+ private buildStandardFilter;
831
+ private buildStringFilter;
832
+ private buildJsonStringFilter;
833
+ private escapeLikePattern;
834
+ private buildStringLike;
835
+ private prepStringCasing;
836
+ private buildNumberFilter;
837
+ private buildBooleanFilter;
838
+ private buildDateTimeFilter;
839
+ private buildBytesFilter;
840
+ private buildEnumFilter;
841
+ buildOrderBy(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, orderBy: OrArray<OrderBy<Schema, GetModels<Schema>, boolean, boolean>> | undefined, negated: boolean, take: number | undefined): SelectQueryBuilder<any, any, any>;
842
+ buildSelectAllFields(model: string, query: SelectQueryBuilder<any, any, any>, omit: Record<string, boolean | undefined> | undefined | null, modelAlias: string): SelectQueryBuilder<any, any, any>;
843
+ shouldOmitField(omit: unknown, model: string, field: string): any;
844
+ protected buildModelSelect(model: GetModels<Schema>, subQueryAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, any, true>, selectAllFields: boolean): SelectQueryBuilder<any, any, {}>;
845
+ buildSelectField(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, field: string): SelectQueryBuilder<any, any, any>;
846
+ buildDelegateJoin(thisModel: string, thisModelAlias: string, otherModelAlias: string, query: SelectQueryBuilder<any, any, any>): SelectQueryBuilder<any, any, any>;
847
+ buildCountJson(model: string, eb: ExpressionBuilder<any, any>, parentAlias: string, payload: any): AliasableExpression<unknown>;
848
+ protected negateSort(sort: SortOrder, negated: boolean): SortOrder;
849
+ true(): Expression<SqlBool>;
850
+ false(): Expression<SqlBool>;
851
+ isTrue(expression: Expression<SqlBool>): boolean;
852
+ isFalse(expression: Expression<SqlBool>): boolean;
853
+ and(...args: Expression<SqlBool>[]): Expression<SqlBool>;
854
+ or(...args: Expression<SqlBool>[]): Expression<SqlBool>;
855
+ not(...args: Expression<SqlBool>[]): ExpressionWrapper<any, any, SqlBool>;
856
+ fieldRef(model: string, field: string, modelAlias?: string, inlineComputedField?: boolean): any;
857
+ protected canJoinWithoutNestedSelect(modelDef: ModelDef, payload: boolean | FindArgs<Schema, GetModels<Schema>, any, true>): boolean;
858
+ /**
859
+ * Builds an EXISTS expression from an inner SELECT query.
860
+ * Can be overridden by dialects that need special handling (e.g., MySQL wraps
861
+ * in a derived table to avoid "can't specify target table for update in FROM clause").
862
+ */
863
+ protected buildExistsExpression(innerQuery: SelectQueryBuilder<any, any, any>): Expression<SqlBool>;
864
+ abstract get provider(): DataSourceProviderType;
865
+ /**
866
+ * Builds selection for a relation field.
867
+ */
868
+ abstract buildRelationSelection(query: SelectQueryBuilder<any, any, any>, model: string, relationField: string, parentAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, any, true>): SelectQueryBuilder<any, any, any>;
869
+ /**
870
+ * Builds skip and take clauses.
871
+ */
872
+ abstract buildSkipTake(query: SelectQueryBuilder<any, any, any>, skip: number | undefined, take: number | undefined): SelectQueryBuilder<any, any, any>;
873
+ /**
874
+ * Builds an Kysely expression that returns a JSON object for the given key-value pairs.
875
+ */
876
+ abstract buildJsonObject(value: Record<string, Expression<unknown>>): AliasableExpression<unknown>;
877
+ /**
878
+ * Builds an Kysely expression that returns the length of an array.
879
+ */
880
+ abstract buildArrayLength(array: Expression<unknown>): AliasableExpression<number>;
881
+ /**
882
+ * Builds an array value expression.
883
+ */
884
+ abstract buildArrayValue(values: Expression<unknown>[], elemType: string): AliasableExpression<unknown>;
885
+ /**
886
+ * Builds an expression that checks if an array contains a single value.
887
+ */
888
+ abstract buildArrayContains(field: Expression<unknown>, value: Expression<unknown>, elemType?: string): AliasableExpression<SqlBool>;
889
+ /**
890
+ * Builds an expression that checks if an array contains all values from another array.
891
+ */
892
+ abstract buildArrayHasEvery(field: Expression<unknown>, values: Expression<unknown>): AliasableExpression<SqlBool>;
893
+ /**
894
+ * Builds an expression that checks if an array overlaps with another array.
895
+ */
896
+ abstract buildArrayHasSome(field: Expression<unknown>, values: Expression<unknown>): AliasableExpression<SqlBool>;
897
+ /**
898
+ * Casts the given expression to an integer type.
899
+ */
900
+ abstract castInt<T extends Expression<any>>(expression: T): T;
901
+ /**
902
+ * Casts the given expression to a text type.
903
+ */
904
+ abstract castText<T extends Expression<any>>(expression: T): T;
905
+ /**
906
+ * Trims double quotes from the start and end of a text expression.
907
+ */
908
+ abstract trimTextQuotes<T extends Expression<string>>(expression: T): T;
909
+ abstract getStringCasingBehavior(): {
910
+ supportsILike: boolean;
911
+ likeCaseSensitive: boolean;
912
+ };
913
+ /**
914
+ * Builds a VALUES table and select all fields from it.
915
+ */
916
+ abstract buildValuesTableSelect(fields: FieldDef[], rows: unknown[][]): SelectQueryBuilder<any, any, any>;
917
+ /**
918
+ * Builds a binary comparison expression between two operands.
919
+ */
920
+ buildComparison(left: Expression<unknown>, _leftFieldDef: FieldDef | undefined, op: string, right: Expression<unknown>, _rightFieldDef: FieldDef | undefined): Expression<SqlBool>;
921
+ /**
922
+ * Builds a JSON path selection expression.
923
+ */
924
+ protected abstract buildJsonPathSelection(receiver: Expression<any>, path: string | undefined): Expression<any>;
925
+ /**
926
+ * Builds a JSON array filter expression.
927
+ */
928
+ protected abstract buildJsonArrayFilter(receiver: Expression<any>, operation: 'array_contains' | 'array_starts_with' | 'array_ends_with', value: unknown): Expression<SqlBool>;
929
+ /**
930
+ * Builds a JSON array exists predicate (returning if any element matches the filter).
931
+ */
932
+ protected abstract buildJsonArrayExistsPredicate(receiver: Expression<any>, buildFilter: (elem: Expression<any>) => Expression<SqlBool>): Expression<SqlBool>;
933
+ /**
934
+ * Builds an ORDER BY clause for a field with NULLS FIRST/LAST support.
935
+ */
936
+ protected abstract buildOrderByField(query: SelectQueryBuilder<any, any, any>, field: Expression<unknown>, sort: SortOrder, nulls: 'first' | 'last'): SelectQueryBuilder<any, any, any>;
937
+ }
938
+
939
+ type InputValidatorOptions = {
940
+ /**
941
+ * Whether validation is enabled. Defaults to `true`.
942
+ */
943
+ enabled?: boolean;
944
+ };
945
+ declare class InputValidator<Schema extends SchemaDef> {
946
+ private readonly client;
947
+ readonly zodFactory: ZodSchemaFactory<Schema>;
948
+ private readonly enabled;
949
+ constructor(client: ClientContract<Schema>, options?: InputValidatorOptions);
950
+ validateFindArgs(model: GetModels<Schema>, args: unknown, operation: 'findFirst' | 'findUnique' | 'findMany'): FindArgs<Schema, GetModels<Schema>, any, true> | undefined;
951
+ validateExistsArgs(model: GetModels<Schema>, args: unknown): ExistsArgs<Schema, GetModels<Schema>, any> | undefined;
952
+ validateCreateArgs(model: GetModels<Schema>, args: unknown): CreateArgs<Schema, GetModels<Schema>, any>;
953
+ validateCreateManyArgs(model: GetModels<Schema>, args: unknown): CreateManyArgs<Schema, GetModels<Schema>>;
954
+ validateCreateManyAndReturnArgs(model: GetModels<Schema>, args: unknown): CreateManyAndReturnArgs<Schema, GetModels<Schema>, any> | undefined;
955
+ validateUpdateArgs(model: GetModels<Schema>, args: unknown): UpdateArgs<Schema, GetModels<Schema>, any>;
956
+ validateUpdateManyArgs(model: GetModels<Schema>, args: unknown): UpdateManyArgs<Schema, GetModels<Schema>, any>;
957
+ validateUpdateManyAndReturnArgs(model: GetModels<Schema>, args: unknown): UpdateManyAndReturnArgs<Schema, GetModels<Schema>, any>;
958
+ validateUpsertArgs(model: GetModels<Schema>, args: unknown): UpsertArgs<Schema, GetModels<Schema>, any>;
959
+ validateDeleteArgs(model: GetModels<Schema>, args: unknown): DeleteArgs<Schema, GetModels<Schema>, any>;
960
+ validateDeleteManyArgs(model: GetModels<Schema>, args: unknown): DeleteManyArgs<Schema, GetModels<Schema>, any> | undefined;
961
+ validateCountArgs(model: GetModels<Schema>, args: unknown): CountArgs<Schema, GetModels<Schema>, any> | undefined;
962
+ validateAggregateArgs(model: GetModels<Schema>, args: unknown): AggregateArgs<Schema, GetModels<Schema>, any>;
963
+ validateGroupByArgs(model: GetModels<Schema>, args: unknown): GroupByArgs<Schema, GetModels<Schema>, any>;
964
+ validateProcedureInput(proc: string, input: unknown): unknown;
965
+ private validate;
966
+ }
967
+
968
+ /**
969
+ * List of core CRUD operations. It excludes the 'orThrow' variants.
970
+ */
971
+ declare const CoreCrudOperations: readonly ["findMany", "findUnique", "findFirst", "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany", "count", "aggregate", "groupBy", "exists"];
972
+ /**
973
+ * List of core CRUD operations. It excludes the 'orThrow' variants.
974
+ */
975
+ type CoreCrudOperations = (typeof CoreCrudOperations)[number];
976
+ /**
977
+ * List of core read operations. It excludes the 'orThrow' variants.
978
+ */
979
+ declare const CoreReadOperations: readonly ["findMany", "findUnique", "findFirst", "count", "aggregate", "groupBy", "exists"];
980
+ /**
981
+ * List of core read operations. It excludes the 'orThrow' variants.
982
+ */
983
+ type CoreReadOperations = (typeof CoreReadOperations)[number];
984
+ /**
985
+ * List of core write operations.
986
+ */
987
+ declare const CoreWriteOperations: readonly ["create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany"];
988
+ /**
989
+ * List of core write operations.
990
+ */
991
+ type CoreWriteOperations = (typeof CoreWriteOperations)[number];
992
+ /**
993
+ * List of core create operations.
994
+ */
995
+ declare const CoreCreateOperations: readonly ["create", "createMany", "createManyAndReturn", "upsert"];
996
+ /**
997
+ * List of core create operations.
998
+ */
999
+ type CoreCreateOperations = (typeof CoreCreateOperations)[number];
1000
+ /**
1001
+ * List of core update operations.
1002
+ */
1003
+ declare const CoreUpdateOperations: readonly ["update", "updateMany", "updateManyAndReturn", "upsert"];
1004
+ /**
1005
+ * List of core update operations.
1006
+ */
1007
+ type CoreUpdateOperations = (typeof CoreUpdateOperations)[number];
1008
+ /**
1009
+ * List of core delete operations.
1010
+ */
1011
+ declare const CoreDeleteOperations: readonly ["delete", "deleteMany"];
1012
+ /**
1013
+ * List of core delete operations.
1014
+ */
1015
+ type CoreDeleteOperations = (typeof CoreDeleteOperations)[number];
1016
+ /**
1017
+ * List of all CRUD operations, including 'orThrow' variants.
1018
+ */
1019
+ declare const AllCrudOperations: readonly ["findMany", "findUnique", "findFirst", "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany", "count", "aggregate", "groupBy", "exists", "findUniqueOrThrow", "findFirstOrThrow"];
1020
+ /**
1021
+ * List of all CRUD operations, including 'orThrow' variants.
1022
+ */
1023
+ type AllCrudOperations = (typeof AllCrudOperations)[number];
1024
+ /**
1025
+ * List of all read operations, including 'orThrow' variants.
1026
+ */
1027
+ declare const AllReadOperations: readonly ["findMany", "findUnique", "findFirst", "count", "aggregate", "groupBy", "exists", "findUniqueOrThrow", "findFirstOrThrow"];
1028
+ /**
1029
+ * List of all read operations, including 'orThrow' variants.
1030
+ */
1031
+ type AllReadOperations = (typeof AllReadOperations)[number];
1032
+
1033
+ /**
1034
+ * Checks if a model has any required Unsupported fields (non-optional, no default).
1035
+ * Uses raw field access since `GetModelFields` excludes Unsupported fields.
1036
+ */
1037
+ type ModelHasRequiredUnsupportedField<Schema extends SchemaDef, Model extends GetModels<Schema>> = true extends {
1038
+ [Key in Extract<keyof GetModel<Schema, Model>['fields'], string>]: GetModel<Schema, Model>['fields'][Key] extends infer F extends FieldDef ? F['type'] extends 'Unsupported' ? F['optional'] extends true ? false : 'default' extends keyof F ? false : true : false : false;
1039
+ }[Extract<keyof GetModel<Schema, Model>['fields'], string>] ? true : false;
1040
+ /**
1041
+ * Checks if a model allows create operations (not a delegate model and has no required Unsupported fields).
1042
+ */
1043
+ type ModelAllowsCreate<Schema extends SchemaDef, Model extends GetModels<Schema>> = IsDelegateModel<Schema, Model> extends true ? false : ModelHasRequiredUnsupportedField<Schema, Model> extends true ? false : true;
1044
+ type IsNever<T> = [T] extends [never] ? true : false;
1045
+ /**
1046
+ * Filters models based on slicing configuration.
1047
+ */
1048
+ type GetSlicedModels<Schema extends SchemaDef, Options extends QueryOptions<Schema>> = Options['slicing'] extends infer S ? S extends SlicingOptions<Schema> ? S['includedModels'] extends readonly GetModels<Schema>[] ? Exclude<Extract<S['includedModels'][number], GetModels<Schema>>, S['excludedModels'] extends readonly GetModels<Schema>[] ? S['excludedModels'][number] : never> : Exclude<GetModels<Schema>, S['excludedModels'] extends readonly GetModels<Schema>[] ? S['excludedModels'][number] : never> : GetModels<Schema> : GetModels<Schema>;
1049
+ /**
1050
+ * Filters query operations based on slicing configuration for a specific model.
1051
+ */
1052
+ type GetSlicedOperations<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = Options['slicing'] extends infer Slicing ? Slicing extends SlicingOptions<Schema> ? GetIncludedOperations<Slicing, Model> extends infer IO ? GetExcludedOperations<Slicing, Model> extends infer EO ? IO extends '_none_' ? never : IsNever<IO> extends false ? Exclude<IO, EO> : Exclude<AllCrudOperations, EO> : AllCrudOperations : AllCrudOperations : AllCrudOperations : AllCrudOperations;
1053
+ type GetIncludedOperations<Slicing extends SlicingOptions<any>, Model extends string> = 'models' extends keyof Slicing ? Slicing extends {
1054
+ models: infer Config;
1055
+ } ? Uncapitalize<Model> extends keyof Config ? 'includedOperations' extends keyof Config[Uncapitalize<Model>] ? Config[Uncapitalize<Model>] extends {
1056
+ includedOperations: readonly [];
1057
+ } ? '_none_' : Config[Uncapitalize<Model>] extends {
1058
+ includedOperations: readonly (infer IO)[];
1059
+ } ? IO : never : GetAllIncludedOperations<Slicing> : GetAllIncludedOperations<Slicing> : AllCrudOperations : AllCrudOperations;
1060
+ type GetAllIncludedOperations<Slicing extends SlicingOptions<any>> = 'models' extends keyof Slicing ? Slicing extends {
1061
+ models: infer Config;
1062
+ } ? '$all' extends keyof Config ? Config['$all'] extends {
1063
+ includedOperations: readonly [];
1064
+ } ? '_none_' : Config['$all'] extends {
1065
+ includedOperations: readonly (infer IO)[];
1066
+ } ? IO : AllCrudOperations : AllCrudOperations : AllCrudOperations : AllCrudOperations;
1067
+ type GetExcludedOperations<Slicing extends SlicingOptions<any>, Model extends string> = 'models' extends keyof Slicing ? Slicing extends {
1068
+ models: infer Config;
1069
+ } ? Uncapitalize<Model> extends keyof Config ? Config[Uncapitalize<Model>] extends {
1070
+ excludedOperations: readonly (infer EO)[];
1071
+ } ? EO : GetAllExcludedOperations<Slicing> : GetAllExcludedOperations<Slicing> : never : never;
1072
+ type GetAllExcludedOperations<Slicing extends SlicingOptions<any>> = 'models' extends keyof Slicing ? Slicing extends {
1073
+ models: infer M;
1074
+ } ? '$all' extends keyof M ? M['$all'] extends {
1075
+ excludedOperations: readonly (infer EO)[];
1076
+ } ? EO : never : never : never : never;
1077
+ /**
1078
+ * Filters procedures based on slicing configuration.
1079
+ */
1080
+ type GetSlicedProcedures<Schema extends SchemaDef, Options extends QueryOptions<Schema>> = Options['slicing'] extends infer S ? S extends SlicingOptions<Schema> ? S['includedProcedures'] extends readonly (infer IncludedProc)[] ? Exclude<Extract<IncludedProc, GetProcedureNames<Schema>>, S['excludedProcedures'] extends readonly (infer ExcludedProc)[] ? Extract<ExcludedProc, GetProcedureNames<Schema>> : never> : Exclude<GetProcedureNames<Schema>, S['excludedProcedures'] extends readonly (infer ExcludedProc)[] ? Extract<ExcludedProc, GetProcedureNames<Schema>> : never> : GetProcedureNames<Schema> : GetProcedureNames<Schema>;
1081
+ /**
1082
+ * Filters filter kinds for a specific field, considering field-level slicing configuration with $all fallback.
1083
+ */
1084
+ type GetSlicedFilterKindsForField<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends string, Options extends QueryOptions<Schema>> = Options extends {
1085
+ slicing: infer S;
1086
+ } ? S extends SlicingOptions<Schema> ? GetFieldIncludedFilterKinds<S, Model, Field> extends infer IFK ? GetFieldExcludedFilterKinds<S, Model, Field> extends infer EFK ? '_none_' extends IFK ? never : IsNever<IFK> extends true ? IsNever<EFK> extends true ? FilterKind : Exclude<FilterKind, EFK> : Exclude<IFK, EFK> : FilterKind : FilterKind : FilterKind : FilterKind;
1087
+ type GetIncludedFilterKindsFromModelConfig<ModelConfig, Field extends string> = ModelConfig extends {
1088
+ includedFilterKinds: readonly [];
1089
+ } ? '_none_' : 'fields' extends keyof ModelConfig ? ModelConfig['fields'] extends infer FieldsConfig ? Field extends keyof FieldsConfig ? 'includedFilterKinds' extends keyof FieldsConfig[Field] ? FieldsConfig[Field] extends {
1090
+ includedFilterKinds: readonly [];
1091
+ } ? '_none_' : FieldsConfig[Field] extends {
1092
+ includedFilterKinds: readonly (infer IFK)[];
1093
+ } ? IFK : never : GetAllFieldsIncludedFilterKinds<FieldsConfig> : GetAllFieldsIncludedFilterKinds<FieldsConfig> : never : never;
1094
+ type GetFieldIncludedFilterKinds<S extends SlicingOptions<any>, Model extends string, Field extends string> = S extends {
1095
+ models?: infer Config;
1096
+ } ? Uncapitalize<Model> extends keyof Config ? GetIncludedFilterKindsFromModelConfig<Config[Uncapitalize<Model>], Field> : '$all' extends keyof Config ? GetIncludedFilterKindsFromModelConfig<Config['$all'], Field> : never : never;
1097
+ type GetAllFieldsIncludedFilterKinds<FieldsConfig> = '$all' extends keyof FieldsConfig ? FieldsConfig['$all'] extends {
1098
+ includedFilterKinds: readonly [];
1099
+ } ? '_none_' : FieldsConfig['$all'] extends {
1100
+ includedFilterKinds: readonly (infer IFK)[];
1101
+ } ? IFK : never : never;
1102
+ type GetExcludedFilterKindsFromModelConfig<ModelConfig, Field extends string> = 'fields' extends keyof ModelConfig ? ModelConfig['fields'] extends infer FieldsConfig ? Field extends keyof FieldsConfig ? FieldsConfig[Field] extends {
1103
+ excludedFilterKinds: readonly (infer EFK)[];
1104
+ } ? EFK : GetAllFieldsExcludedFilterKinds<FieldsConfig> : GetAllFieldsExcludedFilterKinds<FieldsConfig> : never : never;
1105
+ type GetFieldExcludedFilterKinds<S extends SlicingOptions<any>, Model extends string, Field extends string> = S extends {
1106
+ models?: infer Config;
1107
+ } ? Uncapitalize<Model> extends keyof Config ? GetExcludedFilterKindsFromModelConfig<Config[Uncapitalize<Model>], Field> : '$all' extends keyof Config ? GetExcludedFilterKindsFromModelConfig<Config['$all'], Field> : never : never;
1108
+ type GetAllFieldsExcludedFilterKinds<FieldsConfig> = '$all' extends keyof FieldsConfig ? FieldsConfig['$all'] extends {
1109
+ excludedFilterKinds: readonly (infer EFK)[];
1110
+ } ? EFK : never : never;
1111
+
1112
+ type DefaultModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Omit = undefined, Options extends QueryOptions<Schema> = QueryOptions<Schema>, Optional = false, Array = false> = WrapType<{
1113
+ [Key in NonRelationFields<Schema, Model> as ShouldOmitField<Schema, Model, Options, Key, Omit> extends true ? never : Key]: MapModelFieldType<Schema, Model, Key>;
1114
+ }, Optional, Array>;
1115
+ type ShouldOmitField<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, Field extends GetModelFields<Schema, Model>, Omit> = QueryLevelOmit<Schema, Model, Field, Omit> extends boolean ? QueryLevelOmit<Schema, Model, Field, Omit> : OptionsLevelOmit<Schema, Model, Field, Options> extends boolean ? OptionsLevelOmit<Schema, Model, Field, Options> : SchemaLevelOmit<Schema, Model, Field>;
1116
+ type QueryLevelOmit<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Omit> = Field extends keyof Omit ? (Omit[Field] extends boolean ? Omit[Field] : undefined) : undefined;
1117
+ type OptionsLevelOmit<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Options extends QueryOptions<Schema>> = Uncapitalize<Model> extends keyof Options['omit'] ? Field extends keyof Options['omit'][Uncapitalize<Model>] ? Options['omit'][Uncapitalize<Model>][Field] extends boolean ? Options['omit'][Uncapitalize<Model>][Field] : undefined : undefined : undefined;
1118
+ type SchemaLevelOmit<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelField<Schema, Model, Field>['omit'] extends true ? true : false;
1119
+ type ModelSelectResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Select, Omit, Options extends QueryOptions<Schema>, ExtResult extends ExtResultBase<Schema> = {}> = {
1120
+ [Key in keyof Select as Select[Key] extends false | undefined ? never : Key extends keyof ExtractExtResult<ExtResult, Model & string> ? never : Key extends '_count' ? Select[Key] extends SelectCount<Schema, Model, Options> ? Key : never : Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key]: Key extends '_count' ? SelectCountResult<Schema, Model, Select[Key]> : Key extends NonRelationFields<Schema, Model> ? MapModelFieldType<Schema, Model, Key> : Key extends RelationFields<Schema, Model> ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Select[Key], Options, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>, ExtResult> : never;
1121
+ };
1122
+ type SelectCountResult<Schema extends SchemaDef, Model extends GetModels<Schema>, C> = C extends true ? {
1123
+ [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: number;
1124
+ } : C extends {
1125
+ select: infer S;
1126
+ } ? {
1127
+ [Key in keyof S]: number;
1128
+ } : never;
1129
+ type ModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args = {}, Options extends QueryOptions<Schema> = QueryOptions<Schema>, Optional = false, Array = false, ExtResult extends ExtResultBase<Schema> = {}> = WrapType<(Args extends {
1130
+ select: infer S extends object;
1131
+ omit?: infer O extends object;
1132
+ } & Record<string, unknown> ? ModelSelectResult<Schema, Model, S, O, Options, ExtResult> : Args extends {
1133
+ include: infer I extends object;
1134
+ omit?: infer O extends object;
1135
+ } & Record<string, unknown> ? // select all non-omitted scalar fields
1136
+ DefaultModelResult<Schema, Model, O, Options, false, false> & {
1137
+ [Key in keyof I & RelationFields<Schema, Model> as I[Key] extends false | undefined ? never : Key]: ModelResult<Schema, RelationFieldType<Schema, Model, Key>, I[Key], Options, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>, ExtResult>;
1138
+ } & ('_count' extends keyof I ? I['_count'] extends false | undefined ? {} : {
1139
+ _count: SelectCountResult<Schema, Model, I['_count']>;
1140
+ } : {}) : Args extends {
1141
+ omit: infer O;
1142
+ } & Record<string, unknown> ? DefaultModelResult<Schema, Model, O, Options, false, false> : DefaultModelResult<Schema, Model, undefined, Options, false, false>) & SelectAwareExtResult<ExtResult, Model & string, Args>, Optional, Array>;
1143
+ type SimplifiedResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args = {}, Options extends QueryOptions<Schema> = QueryOptions<Schema>, Optional = false, Array = false, ExtResult extends ExtResultBase<Schema> = {}> = Simplify<ModelResult<Schema, Model, Args, Options, Optional, Array, ExtResult>>;
1144
+ type SimplifiedPlainResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args = {}, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtResult extends ExtResultBase<Schema> = {}> = Simplify<ModelResult<Schema, Model, Args, Options, false, false, ExtResult>>;
1145
+ type TypeDefResult<Schema extends SchemaDef, TypeDef extends GetTypeDefs<Schema>, Partial extends boolean = false> = PartialIf<Optional<{
1146
+ [Key in GetTypeDefFields<Schema, TypeDef>]: MapFieldDefType<Schema, GetTypeDefField<Schema, TypeDef, Key>, Partial>;
1147
+ }, Partial extends true ? never : keyof {
1148
+ [Key in GetTypeDefFields<Schema, TypeDef> as TypeDefFieldIsOptional<Schema, TypeDef, Key> extends true ? Key : never]: true;
1149
+ }>, Partial> & Record<string, unknown>;
1150
+ type BatchResult = {
1151
+ count: number;
1152
+ };
1153
+ type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ScalarOnly extends boolean = false, WithAggregations extends boolean = false> = {
1154
+ [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: FieldFilter<Schema, Model, Key, Options, WithAggregations>;
1155
+ } & {
1156
+ $expr?: (eb: ExpressionBuilder<ToKyselySchema<Schema>, Model>) => OperandExpression<SqlBool>;
1157
+ } & {
1158
+ AND?: OrArray<WhereInput<Schema, Model, Options, ScalarOnly>>;
1159
+ OR?: WhereInput<Schema, Model, Options, ScalarOnly>[];
1160
+ NOT?: OrArray<WhereInput<Schema, Model, Options, ScalarOnly>>;
1161
+ };
1162
+ type FieldFilter<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Options extends QueryOptions<Schema>, WithAggregations extends boolean, AllowedKinds extends FilterKind = GetSlicedFilterKindsForField<Schema, Model, Field, Options>> = Field extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Field, Options, AllowedKinds> : FieldIsArray<Schema, Model, Field> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Field>, AllowedKinds> : GetModelFieldType<Schema, Model, Field> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Field>, ModelFieldIsOptional<Schema, Model, Field>, WithAggregations, AllowedKinds> : GetModelFieldType<Schema, Model, Field> extends GetTypeDefs<Schema> ? TypedJsonFilter<Schema, GetModelFieldType<Schema, Model, Field>, FieldIsArray<Schema, Model, Field>, ModelFieldIsOptional<Schema, Model, Field>, AllowedKinds> : PrimitiveFilter<GetModelFieldType<Schema, Model, Field>, ModelFieldIsOptional<Schema, Model, Field>, WithAggregations, AllowedKinds>;
1163
+ type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind> = ('Equality' extends AllowedKinds ? NullableIf<keyof GetEnum<Schema, T>, Nullable> : never) | (('Equality' extends AllowedKinds ? {
1164
+ /**
1165
+ * Checks for equality with the specified enum value.
1166
+ */
1167
+ equals?: NullableIf<keyof GetEnum<Schema, T>, Nullable>;
1168
+ /**
1169
+ * Checks if the enum value is in the specified list of values.
1170
+ */
1171
+ in?: (keyof GetEnum<Schema, T>)[];
1172
+ /**
1173
+ * Checks if the enum value is not in the specified list of values.
1174
+ */
1175
+ notIn?: (keyof GetEnum<Schema, T>)[];
1176
+ } : {}) & {
1177
+ /**
1178
+ * Builds a negated filter.
1179
+ */
1180
+ not?: EnumFilter<Schema, T, Nullable, WithAggregations, AllowedKinds>;
1181
+ } & (WithAggregations extends true ? {
1182
+ /**
1183
+ * Filters against the count of records.
1184
+ */
1185
+ _count?: NumberFilter<'Int', false, false, AllowedKinds>;
1186
+ /**
1187
+ * Filters against the minimum value.
1188
+ */
1189
+ _min?: EnumFilter<Schema, T, false, false, AllowedKinds>;
1190
+ /**
1191
+ * Filters against the maximum value.
1192
+ */
1193
+ _max?: EnumFilter<Schema, T, false, false, AllowedKinds>;
1194
+ } : {}));
1195
+ type ArrayFilter<Schema extends SchemaDef, Type extends string, AllowedKinds extends FilterKind> = ('Equality' extends AllowedKinds ? {
1196
+ /**
1197
+ * Checks if the array equals the specified array.
1198
+ */
1199
+ equals?: MapScalarType<Schema, Type>[] | null;
1200
+ } : {}) & ('List' extends AllowedKinds ? {
1201
+ /**
1202
+ * Checks if the array contains all elements of the specified array.
1203
+ */
1204
+ has?: MapScalarType<Schema, Type> | null;
1205
+ /**
1206
+ * Checks if the array contains any of the elements of the specified array.
1207
+ */
1208
+ hasEvery?: MapScalarType<Schema, Type>[];
1209
+ /**
1210
+ * Checks if the array contains some of the elements of the specified array.
1211
+ */
1212
+ hasSome?: MapScalarType<Schema, Type>[];
1213
+ /**
1214
+ * Checks if the array is empty.
1215
+ */
1216
+ isEmpty?: boolean;
1217
+ } : {});
1218
+ type MapScalarType<Schema extends SchemaDef, Type extends string> = Type extends GetEnums<Schema> ? keyof GetEnum<Schema, Type> : MapBaseType$1<Type>;
1219
+ type PrimitiveFilter<T extends string, Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind> = T extends 'String' ? StringFilter<Nullable, WithAggregations, AllowedKinds> : T extends 'Int' | 'Float' | 'Decimal' | 'BigInt' ? NumberFilter<T, Nullable, WithAggregations, AllowedKinds> : T extends 'Boolean' ? BooleanFilter<Nullable, WithAggregations, AllowedKinds> : T extends 'DateTime' ? DateTimeFilter<Nullable, WithAggregations, AllowedKinds> : T extends 'Bytes' ? BytesFilter<Nullable, WithAggregations, AllowedKinds> : T extends 'Json' ? JsonFilter<AllowedKinds> : never;
1220
+ type CommonPrimitiveFilter<DataType, T extends BuiltinType, Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind> = ('Equality' extends AllowedKinds ? {
1221
+ /**
1222
+ * Checks for equality with the specified value.
1223
+ */
1224
+ equals?: NullableIf<DataType, Nullable>;
1225
+ /**
1226
+ * Checks if the value is in the specified list of values.
1227
+ */
1228
+ in?: DataType[];
1229
+ /**
1230
+ * Checks if the value is not in the specified list of values.
1231
+ */
1232
+ notIn?: DataType[];
1233
+ } : {}) & ('Range' extends AllowedKinds ? {
1234
+ /**
1235
+ * Checks if the value is less than the specified value.
1236
+ */
1237
+ lt?: DataType;
1238
+ /**
1239
+ * Checks if the value is less than or equal to the specified value.
1240
+ */
1241
+ lte?: DataType;
1242
+ /**
1243
+ * Checks if the value is greater than the specified value.
1244
+ */
1245
+ gt?: DataType;
1246
+ /**
1247
+ * Checks if the value is greater than or equal to the specified value.
1248
+ */
1249
+ gte?: DataType;
1250
+ /**
1251
+ * Checks if the value is between the specified values (inclusive).
1252
+ */
1253
+ between?: [start: DataType, end: DataType];
1254
+ } : {}) & {
1255
+ /**
1256
+ * Builds a negated filter.
1257
+ */
1258
+ not?: PrimitiveFilter<T, Nullable, WithAggregations, AllowedKinds>;
1259
+ };
1260
+ type StringFilter<Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind = FilterKind> = ('Equality' extends AllowedKinds ? NullableIf<string, Nullable> : never) | (CommonPrimitiveFilter<string, 'String', Nullable, WithAggregations, AllowedKinds> & ('Like' extends AllowedKinds ? {
1261
+ /**
1262
+ * Checks if the string contains the specified substring.
1263
+ */
1264
+ contains?: string;
1265
+ /**
1266
+ * Checks if the string starts with the specified substring.
1267
+ */
1268
+ startsWith?: string;
1269
+ /**
1270
+ * Checks if the string ends with the specified substring.
1271
+ */
1272
+ endsWith?: string;
1273
+ /**
1274
+ * Specifies the string comparison mode. Not effective for "sqlite" provider
1275
+ */
1276
+ mode?: 'default' | 'insensitive';
1277
+ } : {}) & (WithAggregations extends true ? {
1278
+ /**
1279
+ * Filters against the count of records.
1280
+ */
1281
+ _count?: NumberFilter<'Int', false, false, AllowedKinds>;
1282
+ /**
1283
+ * Filters against the minimum value.
1284
+ */
1285
+ _min?: StringFilter<false, false, AllowedKinds>;
1286
+ /**
1287
+ * Filters against the maximum value.
1288
+ */
1289
+ _max?: StringFilter<false, false, AllowedKinds>;
1290
+ } : {}));
1291
+ type NumberFilter<T extends 'Int' | 'Float' | 'Decimal' | 'BigInt', Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind = FilterKind> = ('Equality' extends AllowedKinds ? NullableIf<number | bigint, Nullable> : never) | (CommonPrimitiveFilter<number, T, Nullable, WithAggregations, AllowedKinds> & (WithAggregations extends true ? {
1292
+ /**
1293
+ * Filters against the count of records.
1294
+ */
1295
+ _count?: NumberFilter<'Int', false, false, AllowedKinds>;
1296
+ /**
1297
+ * Filters against the average value.
1298
+ */
1299
+ _avg?: NumberFilter<T, false, false, AllowedKinds>;
1300
+ /**
1301
+ * Filters against the sum value.
1302
+ */
1303
+ _sum?: NumberFilter<T, false, false, AllowedKinds>;
1304
+ /**
1305
+ * Filters against the minimum value.
1306
+ */
1307
+ _min?: NumberFilter<T, false, false, AllowedKinds>;
1308
+ /**
1309
+ * Filters against the maximum value.
1310
+ */
1311
+ _max?: NumberFilter<T, false, false, AllowedKinds>;
1312
+ } : {}));
1313
+ type DateTimeFilter<Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind = FilterKind> = ('Equality' extends AllowedKinds ? NullableIf<Date | string, Nullable> : never) | (CommonPrimitiveFilter<Date | string, 'DateTime', Nullable, WithAggregations, AllowedKinds> & (WithAggregations extends true ? {
1314
+ /**
1315
+ * Filters against the count of records.
1316
+ */
1317
+ _count?: NumberFilter<'Int', false, false, AllowedKinds>;
1318
+ /**
1319
+ * Filters against the minimum value.
1320
+ */
1321
+ _min?: DateTimeFilter<false, false, AllowedKinds>;
1322
+ /**
1323
+ * Filters against the maximum value.
1324
+ */
1325
+ _max?: DateTimeFilter<false, false, AllowedKinds>;
1326
+ } : {}));
1327
+ type BytesFilter<Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind = FilterKind> = ('Equality' extends AllowedKinds ? NullableIf<Uint8Array | Buffer, Nullable> : never) | (('Equality' extends AllowedKinds ? {
1328
+ /**
1329
+ * Checks for equality with the specified value.
1330
+ */
1331
+ equals?: NullableIf<Uint8Array, Nullable>;
1332
+ /**
1333
+ * Checks if the value is in the specified list of values.
1334
+ */
1335
+ in?: Uint8Array[];
1336
+ /**
1337
+ * Checks if the value is not in the specified list of values.
1338
+ */
1339
+ notIn?: Uint8Array[];
1340
+ } : {}) & {
1341
+ /**
1342
+ * Builds a negated filter.
1343
+ */
1344
+ not?: BytesFilter<Nullable, WithAggregations, AllowedKinds>;
1345
+ } & (WithAggregations extends true ? {
1346
+ /**
1347
+ * Filters against the count of records.
1348
+ */
1349
+ _count?: NumberFilter<'Int', false, false, AllowedKinds>;
1350
+ /**
1351
+ * Filters against the minimum value.
1352
+ */
1353
+ _min?: BytesFilter<false, false, AllowedKinds>;
1354
+ /**
1355
+ * Filters against the maximum value.
1356
+ */
1357
+ _max?: BytesFilter<false, false, AllowedKinds>;
1358
+ } : {}));
1359
+ type BooleanFilter<Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind = FilterKind> = ('Equality' extends AllowedKinds ? NullableIf<boolean, Nullable> : never) | (('Equality' extends AllowedKinds ? {
1360
+ /**
1361
+ * Checks for equality with the specified value.
1362
+ */
1363
+ equals?: NullableIf<boolean, Nullable>;
1364
+ } : {}) & {
1365
+ /**
1366
+ * Builds a negated filter.
1367
+ */
1368
+ not?: BooleanFilter<Nullable, WithAggregations, AllowedKinds>;
1369
+ } & (WithAggregations extends true ? {
1370
+ /**
1371
+ * Filters against the count of records.
1372
+ */
1373
+ _count?: NumberFilter<'Int', false, false, AllowedKinds>;
1374
+ /**
1375
+ * Filters against the minimum value.
1376
+ */
1377
+ _min?: BooleanFilter<false, false, AllowedKinds>;
1378
+ /**
1379
+ * Filters against the maximum value.
1380
+ */
1381
+ _max?: BooleanFilter<false, false, AllowedKinds>;
1382
+ } : {}));
1383
+ type JsonFilter<AllowedKinds extends FilterKind = FilterKind> = ('Equality' extends AllowedKinds ? {
1384
+ /**
1385
+ * Checks for equality with the specified value.
1386
+ */
1387
+ equals?: JsonValue | JsonNullValues;
1388
+ /**
1389
+ * Builds a negated filter.
1390
+ */
1391
+ not?: JsonValue | JsonNullValues;
1392
+ } : {}) & ('Json' extends AllowedKinds ? {
1393
+ /**
1394
+ * JSON path to select the value to filter on. If omitted, the whole JSON value is used.
1395
+ */
1396
+ path?: string;
1397
+ /**
1398
+ * Checks if the value is a string and contains the specified substring.
1399
+ */
1400
+ string_contains?: string;
1401
+ /**
1402
+ * Checks if the value is a string and starts with the specified substring.
1403
+ */
1404
+ string_starts_with?: string;
1405
+ /**
1406
+ * Checks if the value is a string and ends with the specified substring.
1407
+ */
1408
+ string_ends_with?: string;
1409
+ /**
1410
+ * String comparison mode. Not effective for "sqlite" provider
1411
+ */
1412
+ mode?: 'default' | 'insensitive';
1413
+ /**
1414
+ * Checks if the value is an array and contains the specified value.
1415
+ */
1416
+ array_contains?: JsonValue;
1417
+ /**
1418
+ * Checks if the value is an array and starts with the specified value.
1419
+ */
1420
+ array_starts_with?: JsonValue;
1421
+ /**
1422
+ * Checks if the value is an array and ends with the specified value.
1423
+ */
1424
+ array_ends_with?: JsonValue;
1425
+ } : {});
1426
+ type TypedJsonFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = XOR<JsonFilter<AllowedKinds>, TypedJsonTypedFilter<Schema, TypeDefName, Array, Optional, AllowedKinds>>;
1427
+ type TypedJsonTypedFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = 'Json' extends AllowedKinds ? (Array extends true ? ArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds> : NonArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds>) | (Optional extends true ? null : never) : {};
1428
+ type ArrayTypedJsonFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, AllowedKinds extends FilterKind> = {
1429
+ some?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1430
+ every?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1431
+ none?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1432
+ };
1433
+ type NonArrayTypedJsonFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, AllowedKinds extends FilterKind> = {
1434
+ is?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1435
+ isNot?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1436
+ } | TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1437
+ type TypedJsonFieldsFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, AllowedKinds extends FilterKind> = {
1438
+ [Key in GetTypeDefFields<Schema, TypeDefName>]?: GetTypeDefFieldType<Schema, TypeDefName, Key> extends GetTypeDefs<Schema> ? TypedJsonFilter<Schema, GetTypeDefFieldType<Schema, TypeDefName, Key>, TypeDefFieldIsArray<Schema, TypeDefName, Key>, TypeDefFieldIsOptional<Schema, TypeDefName, Key>, AllowedKinds> : TypeDefFieldIsArray<Schema, TypeDefName, Key> extends true ? ArrayFilter<Schema, GetTypeDefFieldType<Schema, TypeDefName, Key>, AllowedKinds> : GetTypeDefFieldType<Schema, TypeDefName, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetTypeDefFieldType<Schema, TypeDefName, Key>, TypeDefFieldIsOptional<Schema, TypeDefName, Key>, false, AllowedKinds> : PrimitiveFilter<GetTypeDefFieldType<Schema, TypeDefName, Key>, TypeDefFieldIsOptional<Schema, TypeDefName, Key>, false, AllowedKinds>;
1439
+ };
1440
+ type SortOrder = 'asc' | 'desc';
1441
+ type NullsOrder = 'first' | 'last';
1442
+ type OrderBy<Schema extends SchemaDef, Model extends GetModels<Schema>, WithRelation extends boolean, WithAggregation extends boolean> = {
1443
+ [Key in NonRelationFields<Schema, Model>]?: ModelFieldIsOptional<Schema, Model, Key> extends true ? SortOrder | {
1444
+ /**
1445
+ * Sort order
1446
+ */
1447
+ sort: SortOrder;
1448
+ /**
1449
+ * Treatment of null values
1450
+ */
1451
+ nulls?: NullsOrder;
1452
+ } : SortOrder;
1453
+ } & (WithRelation extends true ? {
1454
+ [Key in RelationFields<Schema, Model>]?: FieldIsArray<Schema, Model, Key> extends true ? {
1455
+ /**
1456
+ * Sorts by the count of related records.
1457
+ */
1458
+ _count?: SortOrder;
1459
+ } : OrderBy<Schema, RelationFieldType<Schema, Model, Key>, WithRelation, WithAggregation>;
1460
+ } : {}) & (WithAggregation extends true ? {
1461
+ /**
1462
+ * Sorts by the count of records.
1463
+ */
1464
+ _count?: OrderBy<Schema, Model, false, false>;
1465
+ /**
1466
+ * Sorts by the minimum value.
1467
+ */
1468
+ _min?: MinMaxInput<Schema, Model, SortOrder>;
1469
+ /**
1470
+ * Sorts by the maximum value.
1471
+ */
1472
+ _max?: MinMaxInput<Schema, Model, SortOrder>;
1473
+ } & (NumericFields<Schema, Model> extends never ? {} : {
1474
+ /**
1475
+ * Sorts by the average value.
1476
+ */
1477
+ _avg?: SumAvgInput<Schema, Model, SortOrder>;
1478
+ /**
1479
+ * Sorts by the sum value.
1480
+ */
1481
+ _sum?: SumAvgInput<Schema, Model, SortOrder>;
1482
+ }) : {});
1483
+ type WhereUniqueInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = AtLeast<{
1484
+ [Key in keyof GetModel<Schema, Model>['uniqueFields']]?: GetModel<Schema, Model>['uniqueFields'][Key] extends Pick<FieldDef, 'type'> ? MapFieldDefType<Schema, GetModel<Schema, Model>['uniqueFields'][Key]> : {
1485
+ [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;
1486
+ };
1487
+ } & WhereInput<Schema, Model, Options>, Extract<keyof GetModel<Schema, Model>['uniqueFields'], string>>;
1488
+ type OmitInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
1489
+ [Key in NonRelationFields<Schema, Model>]?: boolean;
1490
+ };
1491
+ type SelectIncludeOmit<Schema extends SchemaDef, Model extends GetModels<Schema>, AllowCount extends boolean, Options extends QueryOptions<Schema> = QueryOptions<Schema>, AllowRelation extends boolean = true, ExtResult extends ExtResultBase<Schema> = {}> = {
1492
+ /**
1493
+ * Explicitly select fields and relations to be returned by the query.
1494
+ */
1495
+ select?: (SelectInput<Schema, Model, Options, AllowCount, AllowRelation, ExtResult> & ExtResultSelectOmitFields<ExtResult, Model & string>) | null;
1496
+ /**
1497
+ * Explicitly omit fields from the query result.
1498
+ */
1499
+ omit?: (OmitInput<Schema, Model> & ExtResultSelectOmitFields<ExtResult, Model & string>) | null;
1500
+ } & {
1501
+ [K in AllowRelation extends true ? RelationFields<Schema, Model> extends never ? never : 'include' : never]?: IncludeInput<Schema, Model, Options, AllowCount, ExtResult> | null;
1502
+ };
1503
+ type SelectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, AllowCount extends boolean = true, AllowRelation extends boolean = true, ExtResult extends ExtResultBase<Schema> = {}> = {
1504
+ [Key in NonRelationFields<Schema, Model>]?: boolean;
1505
+ } & (AllowRelation extends true ? IncludeInput<Schema, Model, Options, AllowCount, ExtResult> : {});
1506
+ type SelectCount<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = boolean | {
1507
+ /**
1508
+ * Selects specific relations to count.
1509
+ */
1510
+ select: {
1511
+ [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]?: boolean | {
1512
+ where: WhereInput<Schema, RelationFieldType<Schema, Model, Key>, Options, false>;
1513
+ };
1514
+ };
1515
+ };
1516
+ type IncludeInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, AllowCount extends boolean = true, ExtResult extends ExtResultBase<Schema> = {}> = {
1517
+ [Key in RelationFields<Schema, Model> as RelationFieldType<Schema, Model, Key> extends GetSlicedModels<Schema, Options> ? Key : never]?: boolean | FindArgs<Schema, RelationFieldType<Schema, Model, Key>, Options, FieldIsArray<Schema, Model, Key>, FieldIsArray<Schema, Model, Key> extends true ? true : ModelFieldIsOptional<Schema, Model, Key> extends true ? true : false, ExtResult>;
1518
+ } & (AllowCount extends true ? HasToManyRelations<Schema, Model> extends true ? {
1519
+ _count?: SelectCount<Schema, Model, Options>;
1520
+ } : {} : {});
1521
+ type Subset<T, U> = {
1522
+ [key in keyof T]: key extends keyof U ? T[key] : never;
1523
+ };
1524
+ type SelectSubset<T, U> = {
1525
+ [key in keyof T]: key extends keyof U ? T[key] : never;
1526
+ } & (T extends {
1527
+ select: any;
1528
+ include: any;
1529
+ } ? 'Please either choose `select` or `include`.' : T extends {
1530
+ select: any;
1531
+ omit: any;
1532
+ } ? 'Please either choose `select` or `omit`.' : {});
1533
+ type ToManyRelationFilter<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = {
1534
+ every?: WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
1535
+ some?: WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
1536
+ none?: WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
1537
+ };
1538
+ type ToOneRelationFilter<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options> & {
1539
+ /**
1540
+ * Checks if the related record matches the specified filter.
1541
+ */
1542
+ is?: NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>, ModelFieldIsOptional<Schema, Model, Field>>;
1543
+ /**
1544
+ * Checks if the related record does not match the specified filter.
1545
+ */
1546
+ isNot?: NullableIf<WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>, ModelFieldIsOptional<Schema, Model, Field>>;
1547
+ }, ModelFieldIsOptional<Schema, Model, Field>>;
1548
+ type RelationFilter<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>, AllowedKinds extends FilterKind> = 'Relation' extends AllowedKinds ? FieldIsArray<Schema, Model, Field> extends true ? ToManyRelationFilter<Schema, Model, Field, Options> : ToOneRelationFilter<Schema, Model, Field, Options> : never;
1549
+ type MapModelFieldType<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = MapFieldDefType<Schema, GetModelField<Schema, Model, Field>>;
1550
+ type MapFieldDefType<Schema extends SchemaDef, T extends Pick<FieldDef, 'type' | 'optional' | 'array'>, Partial extends boolean = false> = WrapType<T['type'] extends GetEnums<Schema> ? keyof GetEnum<Schema, T['type']> : T['type'] extends GetTypeDefs<Schema> ? TypeDefResult<Schema, T['type'], Partial> & Record<string, unknown> : MapBaseType$1<T['type']>, T['optional'], T['array']>;
1551
+ type OptionalFieldsForCreate<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
1552
+ [Key in GetModelFields<Schema, Model> as ModelFieldIsOptional<Schema, Model, Key> extends true ? Key : FieldHasDefault<Schema, Model, Key> extends true ? Key : FieldIsArray<Schema, Model, Key> extends true ? Key : GetModelField<Schema, Model, Key>['updatedAt'] extends true | UpdatedAtInfo ? Key : never]: GetModelField<Schema, Model, Key>;
1553
+ };
1554
+ type GetRelation<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelField<Schema, Model, Field>['relation'];
1555
+ 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;
1556
+ 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 readonly string[] ? Opposite['fields'] : []) : [];
1557
+ 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;
1558
+ type FilterArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = {
1559
+ /**
1560
+ * Filter conditions
1561
+ */
1562
+ where?: WhereInput<Schema, Model, Options>;
1563
+ };
1564
+ type SortAndTakeArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = {
1565
+ /**
1566
+ * Number of records to skip
1567
+ */
1568
+ skip?: number;
1569
+ /**
1570
+ * Number of records to take
1571
+ */
1572
+ take?: number;
1573
+ /**
1574
+ * Order by clauses
1575
+ */
1576
+ orderBy?: OrArray<OrderBy<Schema, Model, true, false>>;
1577
+ /**
1578
+ * Cursor for pagination
1579
+ */
1580
+ cursor?: WhereUniqueInput<Schema, Model, Options>;
1581
+ };
1582
+ type FindArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, Collection extends boolean, AllowFilter extends boolean = true, ExtResult extends ExtResultBase<Schema> = {}> = (Collection extends true ? SortAndTakeArgs<Schema, Model, Options> & (ProviderSupportsDistinct<Schema> extends true ? {
1583
+ /**
1584
+ * Distinct fields. Only supported by providers that natively support SQL "DISTINCT ON".
1585
+ */
1586
+ distinct?: OrArray<NonRelationFields<Schema, Model>>;
1587
+ } : {}) : {}) & (AllowFilter extends true ? FilterArgs<Schema, Model, Options> : {}) & SelectIncludeOmit<Schema, Model, true, Options, true, ExtResult>;
1588
+ type FindManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = FindArgs<Schema, Model, Options, true, true, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'findMany'>;
1589
+ type FindFirstArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = FindArgs<Schema, Model, Options, true, true, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'findFirst'>;
1590
+ type ExistsArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> = FilterArgs<Schema, Model, Options> & ExtractExtQueryArgs<ExtQueryArgs, 'exists'>;
1591
+ type FindUniqueArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = {
1592
+ where: WhereUniqueInput<Schema, Model, Options>;
1593
+ } & SelectIncludeOmit<Schema, Model, true, Options, true, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'findUnique'>;
1594
+ type CreateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = {
1595
+ data: CreateInput<Schema, Model, Options>;
1596
+ } & SelectIncludeOmit<Schema, Model, true, Options, true, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'create'>;
1597
+ type CreateManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, _Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> = CreateManyInput<Schema, Model> & ExtractExtQueryArgs<ExtQueryArgs, 'createMany'>;
1598
+ type CreateManyAndReturnArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = CreateManyInput<Schema, Model> & SelectIncludeOmit<Schema, Model, false, Options, false, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'createManyAndReturn'>;
1599
+ type OptionalWrap<Schema extends SchemaDef, Model extends GetModels<Schema>, T extends object> = Optional<T, keyof T & OptionalFieldsForCreate<Schema, Model>>;
1600
+ type CreateScalarPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
1601
+ [Key in ScalarFields<Schema, Model, false> as FieldIsDelegateDiscriminator<Schema, Model, Key> extends true ? never : Key]: ScalarCreatePayload<Schema, Model, Key>;
1602
+ }>;
1603
+ type ScalarCreatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends ScalarFields<Schema, Model, false>> = ScalarFieldMutationPayload<Schema, Model, Field> | (FieldIsArray<Schema, Model, Field> extends true ? {
1604
+ set?: MapModelFieldType<Schema, Model, Field>;
1605
+ } : never);
1606
+ type ScalarFieldMutationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = IsJsonField<Schema, Model, Field> extends true ? ModelFieldIsOptional<Schema, Model, Field> extends true ? JsonValue | JsonNull | DbNull : JsonValue | JsonNull : MapModelFieldType<Schema, Model, Field>;
1607
+ type IsJsonField<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends 'Json' ? true : false;
1608
+ type CreateFKPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
1609
+ [Key in ForeignKeyFields<Schema, Model>]: MapModelFieldType<Schema, Model, Key>;
1610
+ }>;
1611
+ type RelationModelAllowsCreate<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends GetModels<Schema> ? ModelAllowsCreate<Schema, GetModelFieldType<Schema, Model, Field>> : false;
1612
+ type CreateRelationFieldPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = Omit<{
1613
+ /**
1614
+ * Connects or create a related record.
1615
+ */
1616
+ connectOrCreate?: ConnectOrCreateInput<Schema, Model, Field, Options>;
1617
+ /**
1618
+ * Creates a related record.
1619
+ */
1620
+ create?: NestedCreateInput<Schema, Model, Field, Options>;
1621
+ /**
1622
+ * Creates a batch of related records.
1623
+ */
1624
+ createMany?: NestedCreateManyInput<Schema, Model, Field>;
1625
+ /**
1626
+ * Connects an existing record.
1627
+ */
1628
+ connect?: ConnectInput<Schema, Model, Field, Options>;
1629
+ }, (FieldIsArray<Schema, Model, Field> extends true ? never : 'createMany') | (RelationModelAllowsCreate<Schema, Model, Field> extends true ? never : 'create' | 'createMany' | 'connectOrCreate')>;
1630
+ type CreateRelationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = OptionalWrap<Schema, Model, {
1631
+ [Key in RelationFields<Schema, Model> as RelationFieldType<Schema, Model, Key> extends GetSlicedModels<Schema, Options> ? Key : never]: CreateRelationFieldPayload<Schema, Model, Key, Options>;
1632
+ }>;
1633
+ type CreateWithFKInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = CreateScalarPayload<Schema, Model> & CreateFKPayload<Schema, Model> & CreateWithNonOwnedRelationPayload<Schema, Model, Options>;
1634
+ type CreateWithRelationInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = CreateScalarPayload<Schema, Model> & CreateRelationPayload<Schema, Model, Options>;
1635
+ type CreateWithNonOwnedRelationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>> = OptionalWrap<Schema, Model, {
1636
+ [Key in NonOwnedRelationFields<Schema, Model> as RelationFieldType<Schema, Model, Key> extends GetSlicedModels<Schema, Options> ? Key : never]: CreateRelationFieldPayload<Schema, Model, Key, Options>;
1637
+ }>;
1638
+ type ConnectOrCreatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, Without extends string = never> = {
1639
+ /**
1640
+ * The unique filter to find an existing record to connect.
1641
+ */
1642
+ where: WhereUniqueInput<Schema, Model, Options>;
1643
+ /**
1644
+ * The data to create a new record if no existing record is found.
1645
+ */
1646
+ create: CreateInput<Schema, Model, Options, Without>;
1647
+ };
1648
+ type CreateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = {
1649
+ /**
1650
+ * The data for the records to create.
1651
+ */
1652
+ data: OrArray<Omit<CreateScalarPayload<Schema, Model>, Without> & Omit<CreateFKPayload<Schema, Model>, Without>>;
1653
+ /**
1654
+ * Specifies whether to skip creating records that would violate unique constraints.
1655
+ */
1656
+ skipDuplicates?: boolean;
1657
+ };
1658
+ type CreateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, Without extends string = never> = XOR<Omit<CreateWithFKInput<Schema, Model, Options>, Without>, Omit<CreateWithRelationInput<Schema, Model, Options>, Without>>;
1659
+ type NestedCreateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = OrArray<CreateInput<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>, FieldIsArray<Schema, Model, Field>>;
1660
+ type NestedCreateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = CreateManyInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
1661
+ type UpdateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = {
1662
+ /**
1663
+ * The data to update the record with.
1664
+ */
1665
+ data: UpdateInput<Schema, Model, Options>;
1666
+ /**
1667
+ * The unique filter to find the record to update.
1668
+ */
1669
+ where: WhereUniqueInput<Schema, Model, Options>;
1670
+ } & SelectIncludeOmit<Schema, Model, true, Options, true, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'update'>;
1671
+ type UpdateManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> = UpdateManyPayload<Schema, Model, Options> & ExtractExtQueryArgs<ExtQueryArgs, 'updateMany'>;
1672
+ type UpdateManyAndReturnArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = UpdateManyPayload<Schema, Model, Options> & SelectIncludeOmit<Schema, Model, false, Options, false, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'updateManyAndReturn'>;
1673
+ type UpdateManyPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, Without extends string = never> = {
1674
+ /**
1675
+ * The data to update the records with.
1676
+ */
1677
+ data: OrArray<UpdateScalarInput<Schema, Model, Without>>;
1678
+ /**
1679
+ * The filter to select records to update.
1680
+ */
1681
+ where?: WhereInput<Schema, Model, Options>;
1682
+ /**
1683
+ * Limit the number of records to update.
1684
+ */
1685
+ limit?: number;
1686
+ };
1687
+ type UpsertArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = {
1688
+ /**
1689
+ * The data to create the record if it doesn't exist.
1690
+ */
1691
+ create: CreateInput<Schema, Model, Options>;
1692
+ /**
1693
+ * The data to update the record with if it exists.
1694
+ */
1695
+ update: UpdateInput<Schema, Model, Options>;
1696
+ /**
1697
+ * The unique filter to find the record to update.
1698
+ */
1699
+ where: WhereUniqueInput<Schema, Model, Options>;
1700
+ } & SelectIncludeOmit<Schema, Model, true, Options, true, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'upsert'>;
1701
+ type UpdateScalarInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Without extends string = never> = Omit<{
1702
+ [Key in NonRelationFields<Schema, Model> as FieldIsDelegateDiscriminator<Schema, Model, Key> extends true ? never : Key]?: ScalarUpdatePayload<Schema, Model, Key>;
1703
+ }, Without>;
1704
+ type ScalarUpdatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends NonRelationFields<Schema, Model>> = ScalarFieldMutationPayload<Schema, Model, Field> | (Field extends NumericFields<Schema, Model> ? {
1705
+ /**
1706
+ * Sets the field to the specified value.
1707
+ */
1708
+ set?: NullableIf<number, ModelFieldIsOptional<Schema, Model, Field>>;
1709
+ /**
1710
+ * Increments the field by the specified value.
1711
+ */
1712
+ increment?: number;
1713
+ /**
1714
+ * Decrements the field by the specified value.
1715
+ */
1716
+ decrement?: number;
1717
+ /**
1718
+ * Multiplies the field by the specified value.
1719
+ */
1720
+ multiply?: number;
1721
+ /**
1722
+ * Divides the field by the specified value.
1723
+ */
1724
+ divide?: number;
1725
+ } : never) | (FieldIsArray<Schema, Model, Field> extends true ? {
1726
+ /**
1727
+ * Sets the field to the specified array.
1728
+ */
1729
+ set?: MapModelFieldType<Schema, Model, Field>[];
1730
+ /**
1731
+ * Appends the specified values to the array field.
1732
+ */
1733
+ push?: OrArray<MapModelFieldType<Schema, Model, Field>, true>;
1734
+ } : never);
1735
+ type UpdateRelationInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, Without extends string = never> = Omit<{
1736
+ [Key in RelationFields<Schema, Model> as RelationFieldType<Schema, Model, Key> extends GetSlicedModels<Schema, Options> ? Key : never]?: UpdateRelationFieldPayload<Schema, Model, Key, Options>;
1737
+ }, Without>;
1738
+ type UpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, Without extends string = never> = UpdateScalarInput<Schema, Model, Without> & UpdateRelationInput<Schema, Model, Options, Without>;
1739
+ type UpdateRelationFieldPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = FieldIsArray<Schema, Model, Field> extends true ? ToManyRelationUpdateInput<Schema, Model, Field, Options> : ToOneRelationUpdateInput<Schema, Model, Field, Options>;
1740
+ type ToManyRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = Omit<{
1741
+ /**
1742
+ * Creates related records.
1743
+ */
1744
+ create?: NestedCreateInput<Schema, Model, Field, Options>;
1745
+ /**
1746
+ * Creates a batch of related records.
1747
+ */
1748
+ createMany?: NestedCreateManyInput<Schema, Model, Field>;
1749
+ /**
1750
+ * Connects existing records.
1751
+ */
1752
+ connect?: ConnectInput<Schema, Model, Field, Options>;
1753
+ /**
1754
+ * Connects or create related records.
1755
+ */
1756
+ connectOrCreate?: ConnectOrCreateInput<Schema, Model, Field, Options>;
1757
+ /**
1758
+ * Disconnects related records.
1759
+ */
1760
+ disconnect?: DisconnectInput<Schema, Model, Field, Options>;
1761
+ /**
1762
+ * Updates related records.
1763
+ */
1764
+ update?: NestedUpdateInput<Schema, Model, Field, Options>;
1765
+ /**
1766
+ * Upserts related records.
1767
+ */
1768
+ upsert?: NestedUpsertInput<Schema, Model, Field, Options>;
1769
+ /**
1770
+ * Updates a batch of related records.
1771
+ */
1772
+ updateMany?: NestedUpdateManyInput<Schema, Model, Field, Options>;
1773
+ /**
1774
+ * Deletes related records.
1775
+ */
1776
+ delete?: NestedDeleteInput<Schema, Model, Field, Options>;
1777
+ /**
1778
+ * Deletes a batch of related records.
1779
+ */
1780
+ deleteMany?: NestedDeleteManyInput<Schema, Model, Field, Options>;
1781
+ /**
1782
+ * Sets the related records to the specified ones.
1783
+ */
1784
+ set?: SetRelationInput<Schema, Model, Field, Options>;
1785
+ }, RelationModelAllowsCreate<Schema, Model, Field> extends true ? never : 'create' | 'createMany' | 'connectOrCreate' | 'upsert'>;
1786
+ type ToOneRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = Omit<{
1787
+ /**
1788
+ * Creates a related record.
1789
+ */
1790
+ create?: NestedCreateInput<Schema, Model, Field, Options>;
1791
+ /**
1792
+ * Connects an existing record.
1793
+ */
1794
+ connect?: ConnectInput<Schema, Model, Field, Options>;
1795
+ /**
1796
+ * Connects or create a related record.
1797
+ */
1798
+ connectOrCreate?: ConnectOrCreateInput<Schema, Model, Field, Options>;
1799
+ /**
1800
+ * Updates the related record.
1801
+ */
1802
+ update?: NestedUpdateInput<Schema, Model, Field, Options>;
1803
+ /**
1804
+ * Upserts the related record.
1805
+ */
1806
+ upsert?: NestedUpsertInput<Schema, Model, Field, Options>;
1807
+ } & (ModelFieldIsOptional<Schema, Model, Field> extends true ? {
1808
+ /**
1809
+ * Disconnects the related record.
1810
+ */
1811
+ disconnect?: DisconnectInput<Schema, Model, Field, Options>;
1812
+ /**
1813
+ * Deletes the related record.
1814
+ */
1815
+ delete?: NestedDeleteInput<Schema, Model, Field, Options>;
1816
+ } : {}), RelationModelAllowsCreate<Schema, Model, Field> extends true ? never : 'create' | 'connectOrCreate' | 'upsert'>;
1817
+ type DeleteArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = {
1818
+ /**
1819
+ * The unique filter to find the record to delete.
1820
+ */
1821
+ where: WhereUniqueInput<Schema, Model, Options>;
1822
+ } & SelectIncludeOmit<Schema, Model, true, Options, true, ExtResult> & ExtractExtQueryArgs<ExtQueryArgs, 'delete'>;
1823
+ type DeleteManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> = {
1824
+ /**
1825
+ * Filter to select records to delete.
1826
+ */
1827
+ where?: WhereInput<Schema, Model, Options>;
1828
+ /**
1829
+ * Limits the number of records to delete.
1830
+ */
1831
+ limit?: number;
1832
+ } & ExtractExtQueryArgs<ExtQueryArgs, 'deleteMany'>;
1833
+ type CountArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> = Omit<FindArgs<Schema, Model, Options, true>, 'select' | 'include' | 'distinct' | 'omit'> & {
1834
+ /**
1835
+ * Selects fields to count
1836
+ */
1837
+ select?: CountAggregateInput<Schema, Model> | true;
1838
+ } & ExtractExtQueryArgs<ExtQueryArgs, 'count'>;
1839
+ type CountAggregateInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
1840
+ [Key in NonRelationFields<Schema, Model>]?: true;
1841
+ } & {
1842
+ _all?: true;
1843
+ };
1844
+ type CountResult<Schema extends SchemaDef, _Model extends GetModels<Schema>, Args> = Args extends {
1845
+ select: infer S;
1846
+ } ? S extends true ? number : {
1847
+ [Key in keyof S]: number;
1848
+ } : number;
1849
+ type AggregateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> = {
1850
+ /**
1851
+ * Filter conditions
1852
+ */
1853
+ where?: WhereInput<Schema, Model, Options>;
1854
+ /**
1855
+ * Number of records to skip for the aggregation
1856
+ */
1857
+ skip?: number;
1858
+ /**
1859
+ * Number of records to take for the aggregation
1860
+ */
1861
+ take?: number;
1862
+ /**
1863
+ * Order by clauses
1864
+ */
1865
+ orderBy?: OrArray<OrderBy<Schema, Model, true, false>>;
1866
+ } & {
1867
+ /**
1868
+ * Performs count aggregation.
1869
+ */
1870
+ _count?: true | CountAggregateInput<Schema, Model>;
1871
+ /**
1872
+ * Performs minimum value aggregation.
1873
+ */
1874
+ _min?: MinMaxInput<Schema, Model, true>;
1875
+ /**
1876
+ * Performs maximum value aggregation.
1877
+ */
1878
+ _max?: MinMaxInput<Schema, Model, true>;
1879
+ } & (NumericFields<Schema, Model> extends never ? {} : {
1880
+ /**
1881
+ * Performs average value aggregation.
1882
+ */
1883
+ _avg?: SumAvgInput<Schema, Model, true>;
1884
+ /**
1885
+ * Performs sum value aggregation.
1886
+ */
1887
+ _sum?: SumAvgInput<Schema, Model, true>;
1888
+ }) & ExtractExtQueryArgs<ExtQueryArgs, 'aggregate'>;
1889
+ type NumericFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
1890
+ [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>;
1891
+ };
1892
+ type SumAvgInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
1893
+ [Key in NumericFields<Schema, Model>]?: ValueType;
1894
+ };
1895
+ type MinMaxInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
1896
+ [Key in GetModelFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? never : FieldIsRelation<Schema, Model, Key> extends true ? never : Key]?: ValueType;
1897
+ };
1898
+ type AggregateResult<Schema extends SchemaDef, _Model extends GetModels<Schema>, Args> = (Args extends {
1899
+ _count: infer Count;
1900
+ } ? {
1901
+ /**
1902
+ * Count aggregation result
1903
+ */
1904
+ _count: AggCommonOutput<Count>;
1905
+ } : {}) & (Args extends {
1906
+ _sum: infer Sum;
1907
+ } ? {
1908
+ /**
1909
+ * Sum aggregation result
1910
+ */
1911
+ _sum: AggCommonOutput<Sum>;
1912
+ } : {}) & (Args extends {
1913
+ _avg: infer Avg;
1914
+ } ? {
1915
+ /**
1916
+ * Average aggregation result
1917
+ */
1918
+ _avg: AggCommonOutput<Avg>;
1919
+ } : {}) & (Args extends {
1920
+ _min: infer Min;
1921
+ } ? {
1922
+ /**
1923
+ * Minimum aggregation result
1924
+ */
1925
+ _min: AggCommonOutput<Min>;
1926
+ } : {}) & (Args extends {
1927
+ _max: infer Max;
1928
+ } ? {
1929
+ /**
1930
+ * Maximum aggregation result
1931
+ */
1932
+ _max: AggCommonOutput<Max>;
1933
+ } : {});
1934
+ type AggCommonOutput<Input> = Input extends true ? number : Input extends {} ? {
1935
+ [Key in keyof Input]: number;
1936
+ } : never;
1937
+ type GroupByHaving<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>> = Omit<WhereInput<Schema, Model, Options, true, true>, '$expr'>;
1938
+ type GroupByArgs<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema> = QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> = {
1939
+ /**
1940
+ * Filter conditions
1941
+ */
1942
+ where?: WhereInput<Schema, Model, Options>;
1943
+ /**
1944
+ * Order by clauses
1945
+ */
1946
+ orderBy?: OrArray<OrderBy<Schema, Model, false, true>>;
1947
+ /**
1948
+ * Fields to group by
1949
+ */
1950
+ by: NonRelationFields<Schema, Model> | NonEmptyArray<NonRelationFields<Schema, Model>>;
1951
+ /**
1952
+ * Filter conditions for the grouped records
1953
+ */
1954
+ having?: GroupByHaving<Schema, Model, Options>;
1955
+ /**
1956
+ * Number of records to take for grouping
1957
+ */
1958
+ take?: number;
1959
+ /**
1960
+ * Number of records to skip for grouping
1961
+ */
1962
+ skip?: number;
1963
+ /**
1964
+ * Performs count aggregation.
1965
+ */
1966
+ _count?: true | CountAggregateInput<Schema, Model>;
1967
+ /**
1968
+ * Performs minimum value aggregation.
1969
+ */
1970
+ _min?: MinMaxInput<Schema, Model, true>;
1971
+ /**
1972
+ * Performs maximum value aggregation.
1973
+ */
1974
+ _max?: MinMaxInput<Schema, Model, true>;
1975
+ } & (NumericFields<Schema, Model> extends never ? {} : {
1976
+ /**
1977
+ * Performs average value aggregation.
1978
+ */
1979
+ _avg?: SumAvgInput<Schema, Model, true>;
1980
+ /**
1981
+ * Performs sum value aggregation.
1982
+ */
1983
+ _sum?: SumAvgInput<Schema, Model, true>;
1984
+ }) & ExtractExtQueryArgs<ExtQueryArgs, 'groupBy'>;
1985
+ type GroupByResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args extends {
1986
+ by: unknown;
1987
+ }> = Array<{
1988
+ [Key in NonRelationFields<Schema, Model> as Key extends ValueOfPotentialTuple<Args['by']> ? Key : never]: MapModelFieldType<Schema, Model, Key>;
1989
+ } & (Args extends {
1990
+ _count: infer Count;
1991
+ } ? {
1992
+ /**
1993
+ * Count aggregation result
1994
+ */
1995
+ _count: AggCommonOutput<Count>;
1996
+ } : {}) & (Args extends {
1997
+ _avg: infer Avg;
1998
+ } ? {
1999
+ /**
2000
+ * Average aggregation result
2001
+ */
2002
+ _avg: AggCommonOutput<Avg>;
2003
+ } : {}) & (Args extends {
2004
+ _sum: infer Sum;
2005
+ } ? {
2006
+ /**
2007
+ * Sum aggregation result
2008
+ */
2009
+ _sum: AggCommonOutput<Sum>;
2010
+ } : {}) & (Args extends {
2011
+ _min: infer Min;
2012
+ } ? {
2013
+ /**
2014
+ * Minimum aggregation result
2015
+ */
2016
+ _min: AggCommonOutput<Min>;
2017
+ } : {}) & (Args extends {
2018
+ _max: infer Max;
2019
+ } ? {
2020
+ /**
2021
+ * Maximum aggregation result
2022
+ */
2023
+ _max: AggCommonOutput<Max>;
2024
+ } : {})>;
2025
+ type ConnectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>, Options>> : WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
2026
+ type ConnectOrCreateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<ConnectOrCreatePayload<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>> : ConnectOrCreatePayload<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>;
2027
+ type DisconnectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>, Options>, true> : boolean | WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
2028
+ type SetRelationInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>, Options>>;
2029
+ type NestedUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<{
2030
+ /**
2031
+ * Unique filter to select the record to update.
2032
+ */
2033
+ where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
2034
+ /**
2035
+ * The data to update the record with.
2036
+ */
2037
+ data: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>;
2038
+ }, true> : XOR<{
2039
+ /**
2040
+ * Filter to select the record to update.
2041
+ */
2042
+ where?: WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
2043
+ /**
2044
+ * The data to update the record with.
2045
+ */
2046
+ data: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>;
2047
+ }, UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>>;
2048
+ type NestedUpsertInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = OrArray<{
2049
+ /**
2050
+ * Unique filter to select the record to update.
2051
+ */
2052
+ where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
2053
+ /**
2054
+ * The data to create the record if it doesn't exist.
2055
+ */
2056
+ create: CreateInput<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>;
2057
+ /**
2058
+ * The data to update the record with if it exists.
2059
+ */
2060
+ update: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>;
2061
+ }, FieldIsArray<Schema, Model, Field>>;
2062
+ type NestedUpdateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = OrArray<UpdateManyPayload<Schema, RelationFieldType<Schema, Model, Field>, Options, OppositeRelationAndFK<Schema, Model, Field>>>;
2063
+ type NestedDeleteInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>, Options>, true> : boolean | WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options>;
2064
+ type NestedDeleteManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>, Options extends QueryOptions<Schema>> = OrArray<WhereInput<Schema, RelationFieldType<Schema, Model, Field>, Options, true>>;
2065
+ type GetProcedureNames<Schema extends SchemaDef> = Schema extends {
2066
+ procedures: Record<string, ProcedureDef>;
2067
+ } ? keyof Schema['procedures'] : never;
2068
+ type GetProcedureParams<Schema extends SchemaDef, ProcName extends GetProcedureNames<Schema>> = Schema extends {
2069
+ procedures: Record<string, ProcedureDef>;
2070
+ } ? Schema['procedures'][ProcName]['params'] : never;
2071
+ type GetProcedure<Schema extends SchemaDef, ProcName extends GetProcedureNames<Schema>> = Schema extends {
2072
+ procedures: Record<string, ProcedureDef>;
2073
+ } ? Schema['procedures'][ProcName] : never;
2074
+ type _OptionalProcedureParamNames<Params> = keyof {
2075
+ [K in keyof Params as Params[K] extends {
2076
+ optional: true;
2077
+ } ? K : never]: K;
2078
+ };
2079
+ type _RequiredProcedureParamNames<Params> = keyof {
2080
+ [K in keyof Params as Params[K] extends {
2081
+ optional: true;
2082
+ } ? never : K]: K;
2083
+ };
2084
+ type _HasRequiredProcedureParams<Params> = _RequiredProcedureParamNames<Params> extends never ? false : true;
2085
+ type MapProcedureArgsObject<Schema extends SchemaDef, Params> = Simplify<Optional<{
2086
+ [K in keyof Params]: MapProcedureParam<Schema, Params[K]>;
2087
+ }, _OptionalProcedureParamNames<Params>>>;
2088
+ type ProcedureEnvelope<Schema extends SchemaDef, ProcName extends GetProcedureNames<Schema>, Params = GetProcedureParams<Schema, ProcName>> = keyof Params extends never ? {
2089
+ args?: Record<string, never>;
2090
+ } : _HasRequiredProcedureParams<Params> extends true ? {
2091
+ args: MapProcedureArgsObject<Schema, Params>;
2092
+ } : {
2093
+ args?: MapProcedureArgsObject<Schema, Params>;
2094
+ };
2095
+ type ProcedureHandlerCtx<Schema extends SchemaDef, ProcName extends GetProcedureNames<Schema>> = {
2096
+ client: ClientContract<Schema>;
2097
+ } & ProcedureEnvelope<Schema, ProcName>;
2098
+ /**
2099
+ * Shape of a procedure's runtime function.
2100
+ */
2101
+ type ProcedureFunc<Schema extends SchemaDef, ProcName extends GetProcedureNames<Schema>> = (...args: _HasRequiredProcedureParams<GetProcedureParams<Schema, ProcName>> extends true ? [input: ProcedureEnvelope<Schema, ProcName>] : [input?: ProcedureEnvelope<Schema, ProcName>]) => MaybePromise<MapProcedureReturn<Schema, GetProcedure<Schema, ProcName>>>;
2102
+ /**
2103
+ * Signature for procedure handlers configured via client options.
2104
+ */
2105
+ type ProcedureHandlerFunc<Schema extends SchemaDef, ProcName extends GetProcedureNames<Schema>> = (ctx: ProcedureHandlerCtx<Schema, ProcName>) => MaybePromise<MapProcedureReturn<Schema, GetProcedure<Schema, ProcName>>>;
2106
+ type MapProcedureReturn<Schema extends SchemaDef, Proc> = Proc extends {
2107
+ returnType: infer R;
2108
+ } ? Proc extends {
2109
+ returnArray: true;
2110
+ } ? Array<MapType<Schema, R & string>> : MapType<Schema, R & string> : never;
2111
+ type MapProcedureParam<Schema extends SchemaDef, P> = P extends {
2112
+ type: infer U;
2113
+ } ? OrUndefinedIf<P extends {
2114
+ array: true;
2115
+ } ? Array<MapType<Schema, U & string>> : MapType<Schema, U & string>, P extends {
2116
+ optional: true;
2117
+ } ? true : false> : never;
2118
+ type NonOwnedRelationFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
2119
+ [Key in RelationFields<Schema, Model> as GetModelField<Schema, Model, Key>['relation'] extends {
2120
+ references: readonly unknown[];
2121
+ } ? never : Key]: true;
2122
+ };
2123
+ type HasToManyRelations<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
2124
+ [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: true;
2125
+ } extends never ? false : true;
2126
+ type EnumValue<Schema extends SchemaDef, Enum extends GetEnums<Schema>> = GetEnum<Schema, Enum>[keyof GetEnum<Schema, Enum>];
2127
+ type MapType<Schema extends SchemaDef, T extends string> = T extends keyof TypeMap ? TypeMap[T] : T extends GetModels<Schema> ? ModelResult<Schema, T> : T extends GetTypeDefs<Schema> ? TypeDefResult<Schema, T> : T extends GetEnums<Schema> ? EnumValue<Schema, T> : unknown;
2128
+ type ProviderSupportsDistinct<Schema extends SchemaDef> = Schema['provider']['type'] extends 'postgresql' ? true : false;
2129
+ /**
2130
+ * Extracts extended query args for a specific operation.
2131
+ */
2132
+ type ExtractExtQueryArgs<ExtQueryArgs, Operation extends CoreCrudOperations> = (Operation extends keyof ExtQueryArgs ? ExtQueryArgs[Operation] : {}) & ('$create' extends keyof ExtQueryArgs ? Operation extends CoreCreateOperations ? ExtQueryArgs['$create'] : {} : {}) & ('$read' extends keyof ExtQueryArgs ? (Operation extends CoreReadOperations ? ExtQueryArgs['$read'] : {}) : {}) & ('$update' extends keyof ExtQueryArgs ? Operation extends CoreUpdateOperations ? ExtQueryArgs['$update'] : {} : {}) & ('$delete' extends keyof ExtQueryArgs ? Operation extends CoreDeleteOperations ? ExtQueryArgs['$delete'] : {} : {}) & ('$all' extends keyof ExtQueryArgs ? ExtQueryArgs['$all'] : {});
2133
+ /**
2134
+ * Extracts extended result field types for a specific model from ExtResult.
2135
+ * Maps `{ needs, compute }` definitions to `{ fieldName: ReturnType<compute> }`.
2136
+ * When ExtResult is `{}`, this resolves to `{}` (no-op for intersection).
2137
+ */
2138
+ type ExtractExtResult<ExtResult extends ExtResultBase, Model extends string> = Uncapitalize<Model> extends keyof ExtResult ? {
2139
+ [K in keyof ExtResult[Uncapitalize<Model>]]: ExtResult[Uncapitalize<Model>][K] extends {
2140
+ compute: (...args: any[]) => infer R;
2141
+ } ? R : never;
2142
+ } : {};
2143
+ /**
2144
+ * Extracts extended result field names as optional boolean keys for use in select/omit inputs.
2145
+ * When ExtResult is `{}`, this resolves to `{}` (no-op for intersection).
2146
+ */
2147
+ type ExtResultSelectOmitFields<ExtResult extends ExtResultBase, Model extends string> = keyof ExtResult extends never ? {} : Uncapitalize<Model> extends keyof ExtResult ? {
2148
+ [K in keyof ExtResult[Uncapitalize<Model>]]?: boolean;
2149
+ } : {};
2150
+ type TruthyKeys<S, Keys extends string> = {
2151
+ [K in Keys]: K extends keyof S ? (S[K] extends false | undefined ? never : K) : never;
2152
+ }[Keys];
2153
+ /**
2154
+ * Select/omit-aware version of ExtractExtResult.
2155
+ * - If T has `select`, only includes ext result fields that are explicitly selected.
2156
+ * - If T has `omit`, excludes ext result fields that are explicitly omitted.
2157
+ * - Otherwise, includes all ext result fields.
2158
+ */
2159
+ type SelectAwareExtResult<ExtResult extends ExtResultBase, Model extends string, T> = keyof ExtResult extends never ? {} : T extends {
2160
+ select: infer S;
2161
+ } ? S extends null | undefined ? ExtractExtResult<ExtResult, Model> : Pick<ExtractExtResult<ExtResult, Model>, TruthyKeys<S, Extract<keyof S & string, keyof ExtractExtResult<ExtResult, Model>>>> : T extends {
2162
+ omit: infer O;
2163
+ } ? O extends null | undefined ? ExtractExtResult<ExtResult, Model> : Omit<ExtractExtResult<ExtResult, Model>, TruthyKeys<O, Extract<keyof O & string, keyof ExtractExtResult<ExtResult, Model>>>> : ExtractExtResult<ExtResult, Model>;
2164
+
2165
+ /**
2166
+ * Zod schema cache statistics.
2167
+ */
2168
+ interface ZodCacheStats {
2169
+ /**
2170
+ * Number of cached Zod schemas.
2171
+ */
2172
+ size: number;
2173
+ /**
2174
+ * Keys of the cached Zod schemas.
2175
+ */
2176
+ keys: string[];
2177
+ }
2178
+ /**
2179
+ * Information about a query, used for diagnostics.
2180
+ */
2181
+ interface QueryInfo {
2182
+ /**
2183
+ * Time when the query started.
2184
+ */
2185
+ startedAt: Date;
2186
+ /**
2187
+ * Duration of the query in milliseconds.
2188
+ */
2189
+ durationMs: number;
2190
+ /**
2191
+ * SQL statement of the query.
2192
+ */
2193
+ sql: string;
2194
+ }
2195
+ /**
2196
+ * ZenStackClient diagnostics.
2197
+ */
2198
+ interface Diagnostics {
2199
+ /**
2200
+ * Statistics about the Zod schemas (used for query args validation) cache.
2201
+ */
2202
+ zodCache: ZodCacheStats;
2203
+ /**
2204
+ * Slow queries.
2205
+ */
2206
+ slowQueries: QueryInfo[];
2207
+ }
2208
+
2209
+ /**
2210
+ * A promise that only executes when it's awaited or .then() is called.
2211
+ */
2212
+ type ZenStackPromise<Schema extends SchemaDef, T> = Promise<T> & {
2213
+ /**
2214
+ * @private
2215
+ * Callable to get a plain promise.
2216
+ */
2217
+ cb: (txClient?: ClientContract<Schema>) => Promise<T>;
2218
+ /**
2219
+ * Returns a new ZenStackPromise that applies the given function to the resolved value.
2220
+ */
2221
+ transform<U>(fn: (value: T) => U): ZenStackPromise<Schema, U>;
2222
+ };
2223
+ declare const ZENSTACK_QUERY_SYMBOL: unique symbol;
2224
+ declare const ZENSTACK_QUERY_KIND_SYMBOL: unique symbol;
2225
+ type ZenStackQueryKind = 'many' | 'maybeOne' | 'one';
2226
+
2227
+ type TransactionUnsupportedMethods = (typeof TRANSACTION_UNSUPPORTED_METHODS)[number];
2228
+ /**
2229
+ * Transaction isolation levels.
2230
+ */
2231
+ declare enum TransactionIsolationLevel {
2232
+ ReadUncommitted = "read uncommitted",
2233
+ ReadCommitted = "read committed",
2234
+ RepeatableRead = "repeatable read",
2235
+ Serializable = "serializable",
2236
+ Snapshot = "snapshot"
2237
+ }
2238
+ /**
2239
+ * ZenStack client interface.
2240
+ */
2241
+ type ClientContract<Schema extends SchemaDef, Options extends ClientOptions<Schema> = ClientOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtClientMembers extends ExtClientMembersBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = {
2242
+ /**
2243
+ * The schema definition.
2244
+ */
2245
+ readonly $schema: Schema;
2246
+ /**
2247
+ * The client options.
2248
+ */
2249
+ readonly $options: Options;
2250
+ /**
2251
+ * Executes a prepared raw query and returns the number of affected rows.
2252
+ * @example
2253
+ * ```
2254
+ * const result = await db.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`
2255
+ * ```
2256
+ */
2257
+ $executeRaw(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, number>;
2258
+ /**
2259
+ * Executes a raw query and returns the number of affected rows.
2260
+ * This method is susceptible to SQL injections.
2261
+ * @example
2262
+ * ```
2263
+ * const result = await db.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com')
2264
+ * ```
2265
+ */
2266
+ $executeRawUnsafe(query: string, ...values: any[]): ZenStackPromise<Schema, number>;
2267
+ /**
2268
+ * Performs a prepared raw query and returns the `SELECT` data.
2269
+ * @example
2270
+ * ```
2271
+ * const result = await db.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`
2272
+ * ```
2273
+ */
2274
+ $queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, T>;
2275
+ /**
2276
+ * Performs a raw query and returns the `SELECT` data.
2277
+ * This method is susceptible to SQL injections.
2278
+ * @example
2279
+ * ```
2280
+ * const result = await db.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com')
2281
+ * ```
2282
+ */
2283
+ $queryRawUnsafe<T = unknown>(query: string, ...values: any[]): ZenStackPromise<Schema, T>;
2284
+ /**
2285
+ * The current user identity. If the client is not bound to any user context, returns `undefined`.
2286
+ */
2287
+ get $auth(): AuthType<Schema> | undefined;
2288
+ /**
2289
+ * Returns a new client bound to the specified user identity. The original client remains unchanged.
2290
+ * Pass `undefined` to return a client without any user context.
2291
+ *
2292
+ * @example
2293
+ * ```
2294
+ * const userClient = db.$setAuth({ id: 'user-id' });
2295
+ * ```
2296
+ */
2297
+ $setAuth(auth: AuthType<Schema> | undefined): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
2298
+ /**
2299
+ * Returns a new client with new options applied. The original client remains unchanged.
2300
+ *
2301
+ * @example
2302
+ * ```
2303
+ * const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false });
2304
+ * ```
2305
+ */
2306
+ $setOptions<NewOptions extends ClientOptions<Schema>>(options: NewOptions): ClientContract<Schema, NewOptions, ExtQueryArgs, ExtClientMembers, ExtResult>;
2307
+ /**
2308
+ * Returns a new client enabling/disabling query args validation. The original client remains unchanged.
2309
+ *
2310
+ * @deprecated Use {@link $setOptions} instead.
2311
+ */
2312
+ $setInputValidation(enable: boolean): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
2313
+ /**
2314
+ * The Kysely query builder instance.
2315
+ *
2316
+ * @example
2317
+ * ```
2318
+ * db.$qb.selectFrom('User').selectAll().where('id', '=', 1).execute();
2319
+ * ```
2320
+ */
2321
+ readonly $qb: ToKysely<Schema>;
2322
+ /**
2323
+ * The raw Kysely query builder without any ZenStack enhancements.
2324
+ */
2325
+ readonly $qbRaw: AnyKysely;
2326
+ /**
2327
+ * Starts an interactive transaction.
2328
+ *
2329
+ * @example
2330
+ * ```
2331
+ * await db.$transaction(async (tx) => {
2332
+ * const user = await tx.user.update({ where: { id: 1 }, data: { name: 'Alice' } });
2333
+ * const post = await tx.post.create({ data: { title: 'Hello World', authorId: user.id } });
2334
+ * return { user, posts: [post] };
2335
+ * ```
2336
+ */
2337
+ $transaction<T>(callback: (tx: TransactionClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>) => Promise<T>, options?: {
2338
+ isolationLevel?: TransactionIsolationLevel;
2339
+ }): Promise<T>;
2340
+ /**
2341
+ * Starts a sequential transaction that runs the provided operations in order.
2342
+ *
2343
+ * @example
2344
+ * ```
2345
+ * await db.$transaction([
2346
+ * db.user.update({ where: { id: 1 }, data: { name: 'Alice' } }),
2347
+ * db.post.create({ data: { title: 'Hello World', authorId: 1 } }),
2348
+ * ]);
2349
+ */
2350
+ $transaction<P extends ZenStackPromise<Schema, any>[]>(arg: [...P], options?: {
2351
+ isolationLevel?: TransactionIsolationLevel;
2352
+ }): Promise<UnwrapTuplePromises<P>>;
2353
+ /**
2354
+ * Batches multiple read queries into a single SQL statement using lateral subqueries.
2355
+ * Currently only supported for PostgreSQL.
2356
+ *
2357
+ * @param requests - a record of batchable queries (or nested records of queries)
2358
+ * @returns a record with the same structure, where each query is replaced with its result
2359
+ *
2360
+ * @example
2361
+ * ```ts
2362
+ * const { users, postCount } = await db.$batch({
2363
+ * users: db.user.findMany(),
2364
+ * postCount: db.post.count(),
2365
+ * });
2366
+ * ```
2367
+ */
2368
+ $batch(requests: Record<string, any>): ZenStackPromise<Schema, any>;
2369
+ /**
2370
+ * Returns a new client with the specified plugin installed. The original client remains unchanged.
2371
+ *
2372
+ * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation}
2373
+ */
2374
+ $use<PluginSchema extends SchemaDef = Schema, PluginExtQueryArgs extends ExtQueryArgsBase = {}, PluginExtClientMembers extends ExtClientMembersBase = {}, PluginExtResult extends ExtResultBase<PluginSchema> = {}, _R = {}>(plugin: RuntimePlugin<PluginSchema, PluginExtQueryArgs, PluginExtClientMembers, PluginExtResult> & {
2375
+ result?: ExtResultInferenceArgs<Schema, _R>;
2376
+ }): ClientContract<Schema, Options, ExtQueryArgs & PluginExtQueryArgs, ExtClientMembers & PluginExtClientMembers, ExtResult & PluginExtResult>;
2377
+ /**
2378
+ * Returns a new client with the specified plugin removed. The original client remains unchanged.
2379
+ */
2380
+ $unuse(pluginId: string): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
2381
+ /**
2382
+ * Returns a new client with all plugins removed. The original client remains unchanged.
2383
+ */
2384
+ $unuseAll(): ClientContract<Schema, Options>;
2385
+ /**
2386
+ * Eagerly connects to the database.
2387
+ */
2388
+ $connect(): Promise<void>;
2389
+ /**
2390
+ * Explicitly disconnects from the database.
2391
+ */
2392
+ $disconnect(): Promise<void>;
2393
+ /**
2394
+ * Factory for creating zod schemas to validate query args.
2395
+ */
2396
+ get $zod(): ZodSchemaFactory<Schema, Options, ExtQueryArgs>;
2397
+ /**
2398
+ * Pushes the schema to the database. For testing purposes only.
2399
+ * @private
2400
+ */
2401
+ $pushSchema(): Promise<void>;
2402
+ /**
2403
+ * Returns diagnostics information such as cache and slow query statistics.
2404
+ */
2405
+ get $diagnostics(): Promise<Diagnostics>;
2406
+ } & {
2407
+ [Key in GetSlicedModels<Schema, Options> as Uncapitalize<Key>]: ModelOperations<Schema, Key, Options, ExtQueryArgs, ExtResult>;
2408
+ } & ProcedureOperations<Schema, Options> & ExtClientMembers;
2409
+ /**
2410
+ * The contract for a client in a transaction.
2411
+ */
2412
+ type TransactionClientContract<Schema extends SchemaDef, Options extends ClientOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase, ExtClientMembers extends ExtClientMembersBase, ExtResult extends ExtResultBase<Schema> = {}> = Omit<ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>, TransactionUnsupportedMethods>;
2413
+ type ProcedureOperations<Schema extends SchemaDef, Options extends ClientOptions<Schema> = ClientOptions<Schema>> = Schema['procedures'] extends Record<string, ProcedureDef> ? {
2414
+ /**
2415
+ * Custom procedures.
2416
+ */
2417
+ $procs: {
2418
+ [Key in GetSlicedProcedures<Schema, Options>]: ProcedureFunc<Schema, Key>;
2419
+ };
2420
+ } : {};
2421
+ /**
2422
+ * Creates a new ZenStack client instance.
2423
+ */
2424
+ interface ClientConstructor {
2425
+ new <Schema extends SchemaDef, Options extends ClientOptions<Schema> = ClientOptions<Schema>>(schema: Schema, options: Options): ClientContract<Schema, Options>;
2426
+ }
2427
+ /**
2428
+ * CRUD operations.
2429
+ */
2430
+ type CRUD = 'create' | 'read' | 'update' | 'delete';
2431
+ /**
2432
+ * CRUD operations.
2433
+ */
2434
+ declare const CRUD: readonly ["create", "read", "update", "delete"];
2435
+ /**
2436
+ * Extended CRUD operations including 'post-update'.
2437
+ */
2438
+ type CRUD_EXT = CRUD | 'post-update';
2439
+ /**
2440
+ * Extended CRUD operations including 'post-update'.
2441
+ */
2442
+ declare const CRUD_EXT: readonly ["create", "read", "update", "delete", "post-update"];
2443
+ type SliceOperations<T extends Record<string, unknown>, Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema>> = Omit<{
2444
+ [Key in keyof T as Key extends GetSlicedOperations<Schema, Model, Options> ? Key : never]: T[Key];
2445
+ }, ModelAllowsCreate<Schema, Model> extends true ? never : OperationsRequiringCreate>;
2446
+ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase, ExtResult extends ExtResultBase<Schema> = {}> = CommonModelOperations<Schema, Model, Options, ExtQueryArgs, ExtResult> & (Schema['provider']['type'] extends 'mysql' ? {} : {
2447
+ /**
2448
+ * Creates multiple entities and returns them.
2449
+ * @param args - create args. See {@link createMany} for input. Use
2450
+ * `select` and `omit` to control the fields returned.
2451
+ * @returns the created entities
2452
+ *
2453
+ * @example
2454
+ * ```ts
2455
+ * // create multiple entities and return selected fields
2456
+ * await db.user.createManyAndReturn({
2457
+ * data: [
2458
+ * { name: 'Alex', email: 'alex@zenstack.dev' },
2459
+ * { name: 'John', email: 'john@zenstack.dev' }
2460
+ * ],
2461
+ * select: { id: true, email: true }
2462
+ * });
2463
+ * ```
2464
+ */
2465
+ createManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args?: SelectSubset<T, CreateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
2466
+ /**
2467
+ * Updates multiple entities and returns them.
2468
+ * @param args - update args. Only scalar fields are allowed for data.
2469
+ * @returns the updated entities
2470
+ *
2471
+ * @example
2472
+ * ```ts
2473
+ * // update many entities and return selected fields
2474
+ * await db.user.updateManyAndReturn({
2475
+ * where: { email: { endsWith: '@zenstack.dev' } },
2476
+ * data: { role: 'ADMIN' },
2477
+ * select: { id: true, email: true }
2478
+ * }); // result: `Array<{ id: string; email: string }>`
2479
+ *
2480
+ * // limit the number of updated entities
2481
+ * await db.user.updateManyAndReturn({
2482
+ * where: { email: { endsWith: '@zenstack.dev' } },
2483
+ * data: { role: 'ADMIN' },
2484
+ * limit: 10
2485
+ * });
2486
+ * ```
2487
+ */
2488
+ updateManyAndReturn<T extends UpdateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args: Subset<T, UpdateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
2489
+ });
2490
+ type CommonModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends QueryOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase, ExtResult extends ExtResultBase<Schema> = {}> = {
2491
+ /**
2492
+ * Returns a list of entities.
2493
+ * @param args - query args
2494
+ * @returns a list of entities
2495
+ *
2496
+ * @example
2497
+ * ```ts
2498
+ * // find all users and return all scalar fields
2499
+ * await db.user.findMany();
2500
+ *
2501
+ * // find all users with name 'Alex'
2502
+ * await db.user.findMany({
2503
+ * where: {
2504
+ * name: 'Alex'
2505
+ * }
2506
+ * });
2507
+ *
2508
+ * // select fields
2509
+ * await db.user.findMany({
2510
+ * select: {
2511
+ * name: true,
2512
+ * email: true,
2513
+ * }
2514
+ * }); // result: `Array<{ name: string, email: string }>`
2515
+ *
2516
+ * // omit fields
2517
+ * await db.user.findMany({
2518
+ * omit: {
2519
+ * name: true,
2520
+ * }
2521
+ * }); // result: `Array<{ id: number; email: string; ... }>`
2522
+ *
2523
+ * // include relations (and all scalar fields)
2524
+ * await db.user.findMany({
2525
+ * include: {
2526
+ * posts: true,
2527
+ * }
2528
+ * }); // result: `Array<{ ...; posts: Post[] }>`
2529
+ *
2530
+ * // include relations with filter
2531
+ * await db.user.findMany({
2532
+ * include: {
2533
+ * posts: {
2534
+ * where: {
2535
+ * published: true
2536
+ * }
2537
+ * }
2538
+ * }
2539
+ * });
2540
+ *
2541
+ * // pagination and sorting
2542
+ * await db.user.findMany({
2543
+ * skip: 10,
2544
+ * take: 10,
2545
+ * orderBy: [{ name: 'asc' }, { email: 'desc' }],
2546
+ * });
2547
+ *
2548
+ * // pagination with cursor (https://www.prisma.io/docs/orm/prisma-client/queries/pagination#cursor-based-pagination)
2549
+ * await db.user.findMany({
2550
+ * cursor: { id: 10 },
2551
+ * skip: 1,
2552
+ * take: 10,
2553
+ * orderBy: { id: 'asc' },
2554
+ * });
2555
+ *
2556
+ * // distinct
2557
+ * await db.user.findMany({
2558
+ * distinct: ['name']
2559
+ * });
2560
+ *
2561
+ * // count all relations
2562
+ * await db.user.findMany({
2563
+ * _count: true,
2564
+ * }); // result: `{ _count: { posts: number; ... } }`
2565
+ *
2566
+ * // count selected relations
2567
+ * await db.user.findMany({
2568
+ * _count: { select: { posts: true } },
2569
+ * }); // result: `{ _count: { posts: number } }`
2570
+ * ```
2571
+ */
2572
+ findMany<T extends FindManyArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args?: SelectSubset<T, FindManyArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
2573
+ /**
2574
+ * Returns a uniquely identified entity.
2575
+ * @param args - query args
2576
+ * @returns a single entity or null if not found
2577
+ * @see {@link findMany}
2578
+ */
2579
+ findUnique<T extends FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
2580
+ /**
2581
+ * Returns a uniquely identified entity or throws `NotFoundError` if not found.
2582
+ * @param args - query args
2583
+ * @returns a single entity
2584
+ * @see {@link findMany}
2585
+ */
2586
+ findUniqueOrThrow<T extends FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
2587
+ /**
2588
+ * Returns the first entity.
2589
+ * @param args - query args
2590
+ * @returns a single entity or null if not found
2591
+ * @see {@link findMany}
2592
+ */
2593
+ findFirst<T extends FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args?: SelectSubset<T, FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
2594
+ /**
2595
+ * Returns the first entity or throws `NotFoundError` if not found.
2596
+ * @param args - query args
2597
+ * @returns a single entity
2598
+ * @see {@link findMany}
2599
+ */
2600
+ findFirstOrThrow<T extends FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args?: SelectSubset<T, FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
2601
+ /**
2602
+ * Creates a new entity.
2603
+ * @param args - create args
2604
+ * @returns the created entity
2605
+ *
2606
+ * @example
2607
+ * ```ts
2608
+ * // simple create
2609
+ * await db.user.create({
2610
+ * data: { name: 'Alex', email: 'alex@zenstack.dev' }
2611
+ * });
2612
+ *
2613
+ * // nested create with relation
2614
+ * await db.user.create({
2615
+ * data: {
2616
+ * email: 'alex@zenstack.dev',
2617
+ * posts: { create: { title: 'Hello World' } }
2618
+ * }
2619
+ * });
2620
+ *
2621
+ * // you can use `select`, `omit`, and `include` to control
2622
+ * // the fields returned by the query, as with `findMany`
2623
+ * await db.user.create({
2624
+ * data: {
2625
+ * email: 'alex@zenstack.dev',
2626
+ * posts: { create: { title: 'Hello World' } }
2627
+ * },
2628
+ * include: { posts: true }
2629
+ * }); // result: `{ id: number; posts: Post[] }`
2630
+ *
2631
+ * // connect relations
2632
+ * await db.user.create({
2633
+ * data: {
2634
+ * email: 'alex@zenstack.dev',
2635
+ * posts: { connect: { id: 1 } }
2636
+ * }
2637
+ * });
2638
+ *
2639
+ * // connect relations, and create if not found
2640
+ * await db.user.create({
2641
+ * data: {
2642
+ * email: 'alex@zenstack.dev',
2643
+ * posts: {
2644
+ * connectOrCreate: {
2645
+ * where: { id: 1 },
2646
+ * create: { title: 'Hello World' }
2647
+ * }
2648
+ * }
2649
+ * }
2650
+ * });
2651
+ * ```
2652
+ */
2653
+ create<T extends CreateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args: SelectSubset<T, CreateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
2654
+ /**
2655
+ * Creates multiple entities. Only scalar fields are allowed.
2656
+ * @param args - create args
2657
+ * @returns count of created entities: `{ count: number }`
2658
+ *
2659
+ * @example
2660
+ * ```ts
2661
+ * // create multiple entities
2662
+ * await db.user.createMany({
2663
+ * data: [
2664
+ * { name: 'Alex', email: 'alex@zenstack.dev' },
2665
+ * { name: 'John', email: 'john@zenstack.dev' }
2666
+ * ]
2667
+ * });
2668
+ *
2669
+ * // skip items that cause unique constraint violation
2670
+ * await db.user.createMany({
2671
+ * data: [
2672
+ * { name: 'Alex', email: 'alex@zenstack.dev' },
2673
+ * { name: 'John', email: 'john@zenstack.dev' }
2674
+ * ],
2675
+ * skipDuplicates: true
2676
+ * });
2677
+ * ```
2678
+ */
2679
+ createMany<T extends CreateManyArgs<Schema, Model, Options, ExtQueryArgs>>(args?: SelectSubset<T, CreateManyArgs<Schema, Model, Options, ExtQueryArgs>>): ZenStackPromise<Schema, BatchResult>;
2680
+ /**
2681
+ * Updates a uniquely identified entity.
2682
+ * @param args - update args. See {@link findMany} for how to control
2683
+ * fields and relations returned.
2684
+ * @returns the updated entity. Throws `NotFoundError` if the entity is not found.
2685
+ *
2686
+ * @example
2687
+ * ```ts
2688
+ * // update fields
2689
+ * await db.user.update({
2690
+ * where: { id: 1 },
2691
+ * data: { name: 'Alex' }
2692
+ * });
2693
+ *
2694
+ * // connect a relation
2695
+ * await db.user.update({
2696
+ * where: { id: 1 },
2697
+ * data: { posts: { connect: { id: 1 } } }
2698
+ * });
2699
+ *
2700
+ * // connect relation, and create if not found
2701
+ * await db.user.update({
2702
+ * where: { id: 1 },
2703
+ * data: {
2704
+ * posts: {
2705
+ * connectOrCreate: {
2706
+ * where: { id: 1 },
2707
+ * create: { title: 'Hello World' }
2708
+ * }
2709
+ * }
2710
+ * }
2711
+ * });
2712
+ *
2713
+ * // create many related entities (only available for one-to-many relations)
2714
+ * await db.user.update({
2715
+ * where: { id: 1 },
2716
+ * data: {
2717
+ * posts: {
2718
+ * createMany: {
2719
+ * data: [{ title: 'Hello World' }, { title: 'Hello World 2' }],
2720
+ * }
2721
+ * }
2722
+ * }
2723
+ * });
2724
+ *
2725
+ * // disconnect a one-to-many relation
2726
+ * await db.user.update({
2727
+ * where: { id: 1 },
2728
+ * data: { posts: { disconnect: { id: 1 } } }
2729
+ * });
2730
+ *
2731
+ * // disconnect a one-to-one relation
2732
+ * await db.user.update({
2733
+ * where: { id: 1 },
2734
+ * data: { profile: { disconnect: true } }
2735
+ * });
2736
+ *
2737
+ * // replace a relation (only available for one-to-many relations)
2738
+ * await db.user.update({
2739
+ * where: { id: 1 },
2740
+ * data: {
2741
+ * posts: {
2742
+ * set: [{ id: 1 }, { id: 2 }]
2743
+ * }
2744
+ * }
2745
+ * });
2746
+ *
2747
+ * // update a relation
2748
+ * await db.user.update({
2749
+ * where: { id: 1 },
2750
+ * data: {
2751
+ * posts: {
2752
+ * update: { where: { id: 1 }, data: { title: 'Hello World' } }
2753
+ * }
2754
+ * }
2755
+ * });
2756
+ *
2757
+ * // upsert a relation
2758
+ * await db.user.update({
2759
+ * where: { id: 1 },
2760
+ * data: {
2761
+ * posts: {
2762
+ * upsert: {
2763
+ * where: { id: 1 },
2764
+ * create: { title: 'Hello World' },
2765
+ * update: { title: 'Hello World' }
2766
+ * }
2767
+ * }
2768
+ * }
2769
+ * });
2770
+ *
2771
+ * // update many related entities (only available for one-to-many relations)
2772
+ * await db.user.update({
2773
+ * where: { id: 1 },
2774
+ * data: {
2775
+ * posts: {
2776
+ * updateMany: {
2777
+ * where: { published: true },
2778
+ * data: { title: 'Hello World' }
2779
+ * }
2780
+ * }
2781
+ * }
2782
+ * });
2783
+ *
2784
+ * // delete a one-to-many relation
2785
+ * await db.user.update({
2786
+ * where: { id: 1 },
2787
+ * data: { posts: { delete: { id: 1 } } }
2788
+ * });
2789
+ *
2790
+ * // delete a one-to-one relation
2791
+ * await db.user.update({
2792
+ * where: { id: 1 },
2793
+ * data: { profile: { delete: true } }
2794
+ * });
2795
+ * ```
2796
+ */
2797
+ update<T extends UpdateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args: SelectSubset<T, UpdateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
2798
+ /**
2799
+ * Updates multiple entities.
2800
+ * @param args - update args. Only scalar fields are allowed for data.
2801
+ * @returns count of updated entities: `{ count: number }`
2802
+ *
2803
+ * @example
2804
+ * ```ts
2805
+ * // update many entities
2806
+ * await db.user.updateMany({
2807
+ * where: { email: { endsWith: '@zenstack.dev' } },
2808
+ * data: { role: 'ADMIN' }
2809
+ * });
2810
+ *
2811
+ * // limit the number of updated entities
2812
+ * await db.user.updateMany({
2813
+ * where: { email: { endsWith: '@zenstack.dev' } },
2814
+ * data: { role: 'ADMIN' },
2815
+ * limit: 10
2816
+ * });
2817
+ */
2818
+ updateMany<T extends UpdateManyArgs<Schema, Model, Options, ExtQueryArgs>>(args: Subset<T, UpdateManyArgs<Schema, Model, Options, ExtQueryArgs>>): ZenStackPromise<Schema, BatchResult>;
2819
+ /**
2820
+ * Creates or updates an entity.
2821
+ * @param args - upsert args
2822
+ * @returns the upserted entity
2823
+ *
2824
+ * @example
2825
+ * ```ts
2826
+ * // upsert an entity
2827
+ * await db.user.upsert({
2828
+ * // `where` clause is used to find the entity
2829
+ * where: { id: 1 },
2830
+ * // `create` clause is used if the entity is not found
2831
+ * create: { email: 'alex@zenstack.dev', name: 'Alex' },
2832
+ * // `update` clause is used if the entity is found
2833
+ * update: { name: 'Alex-new' },
2834
+ * // `select` and `omit` can be used to control the returned fields
2835
+ * ...
2836
+ * });
2837
+ * ```
2838
+ */
2839
+ upsert<T extends UpsertArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args: SelectSubset<T, UpsertArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
2840
+ /**
2841
+ * Deletes a uniquely identifiable entity.
2842
+ * @param args - delete args
2843
+ * @returns the deleted entity. Throws `NotFoundError` if the entity is not found.
2844
+ *
2845
+ * @example
2846
+ * ```ts
2847
+ * // delete an entity
2848
+ * await db.user.delete({
2849
+ * where: { id: 1 }
2850
+ * });
2851
+ *
2852
+ * // delete an entity and return selected fields
2853
+ * await db.user.delete({
2854
+ * where: { id: 1 },
2855
+ * select: { id: true, email: true }
2856
+ * }); // result: `{ id: string; email: string }`
2857
+ * ```
2858
+ */
2859
+ delete<T extends DeleteArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(args: SelectSubset<T, DeleteArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
2860
+ /**
2861
+ * Deletes multiple entities.
2862
+ * @param args - delete args
2863
+ * @returns count of deleted entities: `{ count: number }`
2864
+ *
2865
+ * @example
2866
+ * ```ts
2867
+ * // delete many entities
2868
+ * await db.user.deleteMany({
2869
+ * where: { email: { endsWith: '@zenstack.dev' } }
2870
+ * });
2871
+ *
2872
+ * // limit the number of deleted entities
2873
+ * await db.user.deleteMany({
2874
+ * where: { email: { endsWith: '@zenstack.dev' } },
2875
+ * limit: 10
2876
+ * });
2877
+ * ```
2878
+ */
2879
+ deleteMany<T extends DeleteManyArgs<Schema, Model, Options, ExtQueryArgs>>(args?: Subset<T, DeleteManyArgs<Schema, Model, Options, ExtQueryArgs>>): ZenStackPromise<Schema, BatchResult>;
2880
+ /**
2881
+ * Counts rows or field values.
2882
+ * @param args - count args
2883
+ * @returns `number`, or an object containing count of selected relations
2884
+ *
2885
+ * @example
2886
+ * ```ts
2887
+ * // count all
2888
+ * await db.user.count();
2889
+ *
2890
+ * // count with a filter
2891
+ * await db.user.count({ where: { email: { endsWith: '@zenstack.dev' } } });
2892
+ *
2893
+ * // count rows and field values
2894
+ * await db.user.count({
2895
+ * select: { _all: true, email: true }
2896
+ * }); // result: `{ _all: number, email: number }`
2897
+ */
2898
+ count<T extends CountArgs<Schema, Model, Options, ExtQueryArgs>>(args?: Subset<T, CountArgs<Schema, Model, Options, ExtQueryArgs>>): ZenStackPromise<Schema, Simplify<CountResult<Schema, Model, T>>>;
2899
+ /**
2900
+ * Aggregates rows.
2901
+ * @param args - aggregation args
2902
+ * @returns an object containing aggregated values
2903
+ *
2904
+ * @example
2905
+ * ```ts
2906
+ * // aggregate rows
2907
+ * await db.profile.aggregate({
2908
+ * where: { email: { endsWith: '@zenstack.dev' } },
2909
+ * _count: true,
2910
+ * _avg: { age: true },
2911
+ * _sum: { age: true },
2912
+ * _min: { age: true },
2913
+ * _max: { age: true }
2914
+ * }); // result: `{ _count: number, _avg: { age: number }, ... }`
2915
+ */
2916
+ aggregate<T extends AggregateArgs<Schema, Model, Options, ExtQueryArgs>>(args: Subset<T, AggregateArgs<Schema, Model, Options, ExtQueryArgs>>): ZenStackPromise<Schema, Simplify<AggregateResult<Schema, Model, T>>>;
2917
+ /**
2918
+ * Groups rows by columns.
2919
+ * @param args - groupBy args
2920
+ * @returns an object containing grouped values
2921
+ *
2922
+ * @example
2923
+ * ```ts
2924
+ * // group by a field
2925
+ * await db.profile.groupBy({
2926
+ * by: 'country',
2927
+ * _count: true
2928
+ * }); // result: `Array<{ country: string, _count: number }>`
2929
+ *
2930
+ * // group by multiple fields
2931
+ * await db.profile.groupBy({
2932
+ * by: ['country', 'city'],
2933
+ * _count: true
2934
+ * }); // result: `Array<{ country: string, city: string, _count: number }>`
2935
+ *
2936
+ * // group by with sorting, the `orderBy` fields must be either an aggregation
2937
+ * // or a field used in the `by` list
2938
+ * await db.profile.groupBy({
2939
+ * by: 'country',
2940
+ * orderBy: { country: 'desc' }
2941
+ * });
2942
+ *
2943
+ * // group by with having (post-aggregation filter), the fields used in `having` must
2944
+ * // be either an aggregation, or a field used in the `by` list
2945
+ * await db.profile.groupBy({
2946
+ * by: 'country',
2947
+ * having: { country: 'US', age: { _avg: { gte: 18 } } }
2948
+ * });
2949
+ */
2950
+ groupBy<T extends GroupByArgs<Schema, Model, Options, ExtQueryArgs>>(args: Subset<T, GroupByArgs<Schema, Model, Options, ExtQueryArgs>>): ZenStackPromise<Schema, Simplify<GroupByResult<Schema, Model, T>>>;
2951
+ /**
2952
+ * Checks if an entity exists.
2953
+ * @param args - exists args
2954
+ * @returns whether a matching entity was found
2955
+ *
2956
+ * @example
2957
+ * ```ts
2958
+ * // check if a user exists
2959
+ * await db.user.exists({
2960
+ * where: { id: 1 },
2961
+ * }); // result: `boolean`
2962
+ *
2963
+ * // check with a relation
2964
+ * await db.user.exists({
2965
+ * where: { posts: { some: { published: true } } },
2966
+ * }); // result: `boolean`
2967
+ */
2968
+ exists<T extends ExistsArgs<Schema, Model, Options, ExtQueryArgs>>(args?: Subset<T, ExistsArgs<Schema, Model, Options, ExtQueryArgs>>): ZenStackPromise<Schema, boolean>;
2969
+ };
2970
+ type OperationsRequiringCreate = 'create' | 'createMany' | 'createManyAndReturn' | 'upsert';
2971
+ type ModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema> = ClientOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase<Schema> = {}> = SliceOperations<AllModelOperations<Schema, Model, Options, ExtQueryArgs, ExtResult>, Schema, Model, Options>;
2972
+ /**
2973
+ * Type for auth context that includes both scalar and relation fields.
2974
+ * Relations are recursively included to allow nested auth data like { user: { profile: { ... } } }
2975
+ */
2976
+ type AuthModelType<Schema extends SchemaDef, Model extends GetModels<Schema>> = Partial<DefaultModelResult<Schema, Model>> & {
2977
+ [Key in RelationFields<Schema, Model>]?: FieldIsArray<Schema, Model, Key> extends true ? AuthModelType<Schema, RelationFieldType<Schema, Model, Key>>[] : AuthModelType<Schema, RelationFieldType<Schema, Model, Key>>;
2978
+ };
2979
+ type AuthType<Schema extends SchemaDef> = Schema['authType'] extends GetModels<Schema> ? AuthModelType<Schema, Schema['authType']> : Schema['authType'] extends GetTypeDefs<Schema> ? TypeDefResult<Schema, Schema['authType'], true> : Record<string, unknown>;
2980
+
2981
+ /**
2982
+ * Create a factory for generating Zod schemas to validate ORM query inputs.
2983
+ */
2984
+ declare function createQuerySchemaFactory<Schema extends SchemaDef, Options extends ClientOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}>(client: ClientContract<Schema, Options, ExtQueryArgs>): ZodSchemaFactory<Schema, Options, ExtQueryArgs>;
2985
+ /**
2986
+ * Create a factory for generating Zod schemas to validate ORM query inputs.
2987
+ */
2988
+ declare function createQuerySchemaFactory<Schema extends SchemaDef, Options extends ClientOptions<Schema> = ClientOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}>(schema: Schema, options?: Options): ZodSchemaFactory<Schema, Options, ExtQueryArgs>;
2989
+ /**
2990
+ * Options for creating Zod schemas.
2991
+ */
2992
+ type CreateSchemaOptions = {
2993
+ /**
2994
+ * Controls the depth of relation nesting in the generated schema. Default is unlimited.
2995
+ */
2996
+ relationDepth?: number;
2997
+ };
2998
+ /**
2999
+ * Factory class responsible for creating and caching Zod schemas for ORM input validation.
3000
+ */
3001
+ declare class ZodSchemaFactory<Schema extends SchemaDef, Options extends ClientOptions<Schema> = ClientOptions<Schema>, ExtQueryArgs extends ExtQueryArgsBase = {}> {
3002
+ private readonly schemaCache;
3003
+ private readonly allFilterKinds;
3004
+ private readonly schema;
3005
+ private readonly options;
3006
+ private readonly extraValidationsEnabled;
3007
+ constructor(client: ClientContract<Schema, Options, ExtQueryArgs, any>);
3008
+ constructor(schema: Schema, options?: Options);
3009
+ private get plugins();
3010
+ /**
3011
+ * Returns model field entries, excluding Unsupported fields.
3012
+ */
3013
+ private getModelFields;
3014
+ private shouldIncludeRelations;
3015
+ private nextOptions;
3016
+ private getCache;
3017
+ private setCache;
3018
+ get cacheStats(): {
3019
+ size: number;
3020
+ keys: string[];
3021
+ };
3022
+ makeFindUniqueSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<FindUniqueArgs<Schema, Model, Options, ExtQueryArgs>>;
3023
+ makeFindFirstSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<FindFirstArgs<Schema, Model, Options, ExtQueryArgs> | undefined>;
3024
+ makeFindManySchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<FindManyArgs<Schema, Model, Options, ExtQueryArgs> | undefined>;
3025
+ private makeFindSchema;
3026
+ makeExistsSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<ExistsArgs<Schema, Model, Options, ExtQueryArgs> | undefined>;
3027
+ private makeScalarSchema;
3028
+ private makeEnumSchema;
3029
+ private makeTypeDefSchema;
3030
+ makeWhereSchema(model: string, unique: boolean, withoutRelationFields?: boolean, withAggregations?: boolean, options?: CreateSchemaOptions): ZodType;
3031
+ private makeTypedJsonFilterSchema;
3032
+ private isTypeDefType;
3033
+ private makeEnumFilterSchema;
3034
+ private makeArrayFilterSchema;
3035
+ private internalMakeArrayFilterSchema;
3036
+ private makePrimitiveFilterSchema;
3037
+ private makeJsonValueSchema;
3038
+ private makeJsonFilterSchema;
3039
+ private makeDateTimeFilterSchema;
3040
+ private makeBooleanFilterSchema;
3041
+ private makeBytesFilterSchema;
3042
+ private makeCommonPrimitiveFilterComponents;
3043
+ private makeCommonPrimitiveFilterSchema;
3044
+ private makeNumberFilterSchema;
3045
+ private makeStringFilterSchema;
3046
+ private makeStringModeSchema;
3047
+ private makeSelectSchema;
3048
+ private makeCountSelectionSchema;
3049
+ private makeRelationSelectIncludeSchema;
3050
+ private makeOmitSchema;
3051
+ private addExtResultFields;
3052
+ private makeIncludeSchema;
3053
+ private makeOrderBySchema;
3054
+ private makeDistinctSchema;
3055
+ private makeCursorSchema;
3056
+ makeCreateSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<CreateArgs<Schema, Model, Options, ExtQueryArgs>>;
3057
+ makeCreateManySchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<CreateManyArgs<Schema, Model, Options, ExtQueryArgs>>;
3058
+ makeCreateManyAndReturnSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<CreateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs>>;
3059
+ private makeCreateDataSchema;
3060
+ private makeRelationManipulationSchema;
3061
+ private makeSetDataSchema;
3062
+ private makeConnectDataSchema;
3063
+ private makeDisconnectDataSchema;
3064
+ private makeDeleteRelationDataSchema;
3065
+ private makeConnectOrCreateDataSchema;
3066
+ private makeCreateManyPayloadSchema;
3067
+ makeUpdateSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<UpdateArgs<Schema, Model, Options, ExtQueryArgs>>;
3068
+ makeUpdateManySchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<UpdateManyArgs<Schema, Model, Options, ExtQueryArgs>>;
3069
+ makeUpdateManyAndReturnSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<UpdateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs>>;
3070
+ makeUpsertSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<UpsertArgs<Schema, Model, Options, ExtQueryArgs>>;
3071
+ private makeUpdateDataSchema;
3072
+ makeDeleteSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<DeleteArgs<Schema, Model, Options, ExtQueryArgs>>;
3073
+ makeDeleteManySchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<DeleteManyArgs<Schema, Model, Options, ExtQueryArgs> | undefined>;
3074
+ makeCountSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<CountArgs<Schema, Model, Options, ExtQueryArgs> | undefined>;
3075
+ private makeCountAggregateInputSchema;
3076
+ makeAggregateSchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<AggregateArgs<Schema, Model, Options, ExtQueryArgs> | undefined>;
3077
+ private makeSumAvgInputSchema;
3078
+ private makeMinMaxInputSchema;
3079
+ makeGroupBySchema<Model extends GetModels<Schema>>(model: Model, options?: CreateSchemaOptions): ZodType<GroupByArgs<Schema, Model, Options, ExtQueryArgs>>;
3080
+ private onlyAggregationFields;
3081
+ private makeHavingSchema;
3082
+ makeProcedureParamSchema(param: {
3083
+ type: string;
3084
+ array?: boolean;
3085
+ optional?: boolean;
3086
+ }, _options?: CreateSchemaOptions): ZodType;
3087
+ private mergePluginArgsSchema;
3088
+ private getPluginExtQueryArgsSchema;
3089
+ private makeSkipSchema;
3090
+ private makeTakeSchema;
3091
+ private refineForSelectIncludeMutuallyExclusive;
3092
+ private refineForSelectOmitMutuallyExclusive;
3093
+ private refineForSelectHasTruthyField;
3094
+ private nullableIf;
3095
+ private orArray;
3096
+ private isNumericField;
3097
+ private get providerSupportsCaseSensitivity();
3098
+ /**
3099
+ * Gets the effective set of allowed FilterKind values for a specific model and field.
3100
+ * Respects the precedence: model[field] > model.$all > $all[field] > $all.$all.
3101
+ */
3102
+ private getEffectiveFilterKinds;
3103
+ /**
3104
+ * Computes the effective set of filter kinds based on inclusion and exclusion lists.
3105
+ */
3106
+ private computeFilterKinds;
3107
+ /**
3108
+ * Filters operators based on allowed filter kinds.
3109
+ */
3110
+ private trimFilterOperators;
3111
+ private createUnionFilterSchema;
3112
+ private canCreateModel;
3113
+ private isModelAllowed;
3114
+ }
3115
+
3116
+ /**
3117
+ * ZenStack ORM client.
3118
+ */
3119
+ declare const ZenStackClient: ClientConstructor;
3120
+
3121
+ declare function getCrudDialect<Schema extends SchemaDef>(schema: Schema, options: ClientOptions<Schema>): BaseCrudDialect<Schema>;
3122
+
3123
+ /**
3124
+ * Reason code for ORM errors.
3125
+ */
3126
+ declare enum ORMErrorReason {
3127
+ /**
3128
+ * ORM client configuration error.
3129
+ */
3130
+ CONFIG_ERROR = "config-error",
3131
+ /**
3132
+ * Invalid input error.
3133
+ */
3134
+ INVALID_INPUT = "invalid-input",
3135
+ /**
3136
+ * The specified record was not found.
3137
+ */
3138
+ NOT_FOUND = "not-found",
3139
+ /**
3140
+ * Operation is rejected by access policy.
3141
+ */
3142
+ REJECTED_BY_POLICY = "rejected-by-policy",
3143
+ /**
3144
+ * Error was thrown by the underlying database driver.
3145
+ */
3146
+ DB_QUERY_ERROR = "db-query-error",
3147
+ /**
3148
+ * The requested operation is not supported.
3149
+ */
3150
+ NOT_SUPPORTED = "not-supported",
3151
+ /**
3152
+ * An internal error occurred.
3153
+ */
3154
+ INTERNAL_ERROR = "internal-error"
3155
+ }
3156
+ /**
3157
+ * Reason code for policy rejection.
3158
+ */
3159
+ declare enum RejectedByPolicyReason {
3160
+ /**
3161
+ * Rejected because the operation is not allowed by policy.
3162
+ */
3163
+ NO_ACCESS = "no-access",
3164
+ /**
3165
+ * Rejected because the result cannot be read back after mutation due to policy.
3166
+ */
3167
+ CANNOT_READ_BACK = "cannot-read-back",
3168
+ /**
3169
+ * Other reasons.
3170
+ */
3171
+ OTHER = "other"
3172
+ }
3173
+ /**
3174
+ * ZenStack ORM error.
3175
+ */
3176
+ declare class ORMError extends Error {
3177
+ reason: ORMErrorReason;
3178
+ constructor(reason: ORMErrorReason, message?: string, options?: ErrorOptions);
3179
+ /**
3180
+ * The name of the model that the error pertains to.
3181
+ */
3182
+ model?: string;
3183
+ /**
3184
+ * The error code given by the underlying database driver.
3185
+ */
3186
+ dbErrorCode?: unknown;
3187
+ /**
3188
+ * The error message given by the underlying database driver.
3189
+ */
3190
+ dbErrorMessage?: string;
3191
+ /**
3192
+ * The reason code for policy rejection. Only available when `reason` is `REJECTED_BY_POLICY`.
3193
+ */
3194
+ rejectedByPolicyReason?: RejectedByPolicyReason;
3195
+ /**
3196
+ * The SQL query that was executed. Only available when `reason` is `DB_QUERY_ERROR`.
3197
+ */
3198
+ sql?: string;
3199
+ /**
3200
+ * The parameters used in the SQL query. Only available when `reason` is `DB_QUERY_ERROR`.
3201
+ */
3202
+ sqlParams?: readonly unknown[];
3203
+ }
3204
+
3205
+ declare function hasModel(schema: SchemaDef, model: string): boolean;
3206
+ declare function getModel(schema: SchemaDef, model: string): ModelDef | undefined;
3207
+ declare function getTypeDef(schema: SchemaDef, type: string): _zenstackhq_schema.TypeDefDef | undefined;
3208
+ declare function requireModel(schema: SchemaDef, model: string): ModelDef;
3209
+ declare function requireTypeDef(schema: SchemaDef, type: string): _zenstackhq_schema.TypeDefDef;
3210
+ declare function getField(schema: SchemaDef, model: string, field: string): FieldDef | undefined;
3211
+ declare function requireField(schema: SchemaDef, modelOrType: string, field: string): FieldDef;
3212
+ /**
3213
+ * Gets all model fields, by default non-relation, non-computed, non-inherited, non-unsupported fields only.
3214
+ */
3215
+ declare function getModelFields(schema: SchemaDef, model: string, options?: {
3216
+ relations?: boolean;
3217
+ computed?: boolean;
3218
+ inherited?: boolean;
3219
+ unsupported?: boolean;
3220
+ }): FieldDef[];
3221
+ /**
3222
+ * Checks if a field is of `Unsupported` type.
3223
+ */
3224
+ declare function isUnsupportedField(fieldDef: FieldDef): boolean;
3225
+ declare function getIdFields<Schema extends SchemaDef>(schema: SchemaDef, model: GetModels<Schema>): readonly string[] | undefined;
3226
+ declare function requireIdFields(schema: SchemaDef, model: string): readonly string[];
3227
+ declare function getRelationForeignKeyFieldPairs(schema: SchemaDef, model: string, relationField: string): {
3228
+ discriminatorWhere?: Record<string, unknown> | undefined;
3229
+ keyPairs: {
3230
+ fk: string;
3231
+ pk: string;
3232
+ }[];
3233
+ ownedByModel: boolean;
3234
+ };
3235
+ declare function isScalarField(schema: SchemaDef, model: string, field: string): boolean;
3236
+ declare function isForeignKeyField(schema: SchemaDef, model: string, field: string): boolean;
3237
+ declare function isRelationField(schema: SchemaDef, model: string, field: string): boolean;
3238
+ declare function isInheritedField(schema: SchemaDef, model: string, field: string): boolean;
3239
+ declare function getUniqueFields(schema: SchemaDef, model: string): ({
3240
+ name: string;
3241
+ def: FieldDef;
3242
+ } | {
3243
+ name: string;
3244
+ defs: Record<string, FieldDef>;
3245
+ })[];
3246
+ declare function getIdValues(schema: SchemaDef, model: string, data: any): Record<string, any>;
3247
+ declare function fieldHasDefaultValue(fieldDef: FieldDef): boolean | _zenstackhq_schema.UpdatedAtInfo | undefined;
3248
+ declare function isEnum(schema: SchemaDef, type: string): boolean;
3249
+ declare function getEnum(schema: SchemaDef, type: string): _zenstackhq_schema.EnumDef | undefined;
3250
+ declare function isTypeDef(schema: SchemaDef, type: string): boolean;
3251
+ declare function buildJoinPairs(schema: SchemaDef, model: string, modelAlias: string, relationField: string, relationModelAlias: string): {
3252
+ pairs: [string, string][];
3253
+ discriminatorWhere?: Record<string, unknown>;
3254
+ };
3255
+ declare function makeDefaultOrderBy(schema: SchemaDef, model: string): {
3256
+ readonly [x: string]: "asc";
3257
+ }[];
3258
+ declare function getManyToManyRelation(schema: SchemaDef, model: string, field: string): {
3259
+ parentFkName: string;
3260
+ parentPKName: string;
3261
+ otherModel: string;
3262
+ otherField: string;
3263
+ otherFkName: string;
3264
+ otherPKName: string;
3265
+ joinTable: string;
3266
+ } | undefined;
3267
+ /**
3268
+ * Convert filter like `{ id1_id2: { id1: 1, id2: 1 } }` to `{ id1: 1, id2: 1 }`
3269
+ */
3270
+ declare function flattenCompoundUniqueFilters(schema: SchemaDef, model: string, filter: unknown): any;
3271
+ declare function ensureArray<T>(value: T | T[]): T[];
3272
+ declare function extractIdFields(entity: any, schema: SchemaDef, model: string): {
3273
+ [k: string]: unknown;
3274
+ };
3275
+ declare function getDiscriminatorField(schema: SchemaDef, model: string): string | undefined;
3276
+ declare function getDelegateDescendantModels(schema: SchemaDef, model: string, collected?: Set<ModelDef>): ModelDef[];
3277
+ declare function aggregate(eb: ExpressionBuilder<any, any>, expr: Expression<any>, op: AggregateOperators): kysely.AggregateFunctionBuilder<any, any, string | number | bigint>;
3278
+ /**
3279
+ * Strips alias from the node if it exists.
3280
+ */
3281
+ declare function stripAlias(node: OperationNode): {
3282
+ alias: OperationNode;
3283
+ node: OperationNode;
3284
+ } | {
3285
+ alias: undefined;
3286
+ node: OperationNode;
3287
+ };
3288
+ /**
3289
+ * Extracts model name from an OperationNode.
3290
+ */
3291
+ declare function extractModelName(node: OperationNode): string | undefined;
3292
+ /**
3293
+ * Extracts field name from an OperationNode.
3294
+ */
3295
+ declare function extractFieldName(node: OperationNode): string | undefined;
3296
+ declare const TEMP_ALIAS_PREFIX = "$$_";
3297
+ /**
3298
+ * Create an alias name for a temporary table or column name.
3299
+ */
3300
+ declare function tmpAlias(name: string): string;
3301
+
3302
+ declare const queryUtils_TEMP_ALIAS_PREFIX: typeof TEMP_ALIAS_PREFIX;
3303
+ declare const queryUtils_aggregate: typeof aggregate;
3304
+ declare const queryUtils_buildJoinPairs: typeof buildJoinPairs;
3305
+ declare const queryUtils_ensureArray: typeof ensureArray;
3306
+ declare const queryUtils_extractFieldName: typeof extractFieldName;
3307
+ declare const queryUtils_extractIdFields: typeof extractIdFields;
3308
+ declare const queryUtils_extractModelName: typeof extractModelName;
3309
+ declare const queryUtils_fieldHasDefaultValue: typeof fieldHasDefaultValue;
3310
+ declare const queryUtils_flattenCompoundUniqueFilters: typeof flattenCompoundUniqueFilters;
3311
+ declare const queryUtils_getDelegateDescendantModels: typeof getDelegateDescendantModels;
3312
+ declare const queryUtils_getDiscriminatorField: typeof getDiscriminatorField;
3313
+ declare const queryUtils_getEnum: typeof getEnum;
3314
+ declare const queryUtils_getField: typeof getField;
3315
+ declare const queryUtils_getIdFields: typeof getIdFields;
3316
+ declare const queryUtils_getIdValues: typeof getIdValues;
3317
+ declare const queryUtils_getManyToManyRelation: typeof getManyToManyRelation;
3318
+ declare const queryUtils_getModel: typeof getModel;
3319
+ declare const queryUtils_getModelFields: typeof getModelFields;
3320
+ declare const queryUtils_getRelationForeignKeyFieldPairs: typeof getRelationForeignKeyFieldPairs;
3321
+ declare const queryUtils_getTypeDef: typeof getTypeDef;
3322
+ declare const queryUtils_getUniqueFields: typeof getUniqueFields;
3323
+ declare const queryUtils_hasModel: typeof hasModel;
3324
+ declare const queryUtils_isEnum: typeof isEnum;
3325
+ declare const queryUtils_isForeignKeyField: typeof isForeignKeyField;
3326
+ declare const queryUtils_isInheritedField: typeof isInheritedField;
3327
+ declare const queryUtils_isRelationField: typeof isRelationField;
3328
+ declare const queryUtils_isScalarField: typeof isScalarField;
3329
+ declare const queryUtils_isTypeDef: typeof isTypeDef;
3330
+ declare const queryUtils_isUnsupportedField: typeof isUnsupportedField;
3331
+ declare const queryUtils_makeDefaultOrderBy: typeof makeDefaultOrderBy;
3332
+ declare const queryUtils_requireField: typeof requireField;
3333
+ declare const queryUtils_requireIdFields: typeof requireIdFields;
3334
+ declare const queryUtils_requireModel: typeof requireModel;
3335
+ declare const queryUtils_requireTypeDef: typeof requireTypeDef;
3336
+ declare const queryUtils_stripAlias: typeof stripAlias;
3337
+ declare const queryUtils_tmpAlias: typeof tmpAlias;
3338
+ declare namespace queryUtils {
3339
+ export { queryUtils_TEMP_ALIAS_PREFIX as TEMP_ALIAS_PREFIX, queryUtils_aggregate as aggregate, queryUtils_buildJoinPairs as buildJoinPairs, queryUtils_ensureArray as ensureArray, queryUtils_extractFieldName as extractFieldName, queryUtils_extractIdFields as extractIdFields, queryUtils_extractModelName as extractModelName, queryUtils_fieldHasDefaultValue as fieldHasDefaultValue, queryUtils_flattenCompoundUniqueFilters as flattenCompoundUniqueFilters, queryUtils_getDelegateDescendantModels as getDelegateDescendantModels, queryUtils_getDiscriminatorField as getDiscriminatorField, queryUtils_getEnum as getEnum, queryUtils_getField as getField, queryUtils_getIdFields as getIdFields, queryUtils_getIdValues as getIdValues, queryUtils_getManyToManyRelation as getManyToManyRelation, queryUtils_getModel as getModel, queryUtils_getModelFields as getModelFields, queryUtils_getRelationForeignKeyFieldPairs as getRelationForeignKeyFieldPairs, queryUtils_getTypeDef as getTypeDef, queryUtils_getUniqueFields as getUniqueFields, queryUtils_hasModel as hasModel, queryUtils_isEnum as isEnum, queryUtils_isForeignKeyField as isForeignKeyField, queryUtils_isInheritedField as isInheritedField, queryUtils_isRelationField as isRelationField, queryUtils_isScalarField as isScalarField, queryUtils_isTypeDef as isTypeDef, queryUtils_isUnsupportedField as isUnsupportedField, queryUtils_makeDefaultOrderBy as makeDefaultOrderBy, queryUtils_requireField as requireField, queryUtils_requireIdFields as requireIdFields, queryUtils_requireModel as requireModel, queryUtils_requireTypeDef as requireTypeDef, queryUtils_stripAlias as stripAlias, queryUtils_tmpAlias as tmpAlias };
3340
+ }
3341
+
3342
+ type VisitResult = void | {
3343
+ abort: true;
3344
+ };
3345
+ declare class ExpressionVisitor {
3346
+ visit(expr: Expression$1): VisitResult;
3347
+ protected visitLiteral(_e: LiteralExpression): VisitResult;
3348
+ protected visitArray(e: ArrayExpression): VisitResult;
3349
+ protected visitField(_e: FieldExpression): VisitResult;
3350
+ protected visitMember(e: MemberExpression): VisitResult;
3351
+ protected visitBinary(e: BinaryExpression): VisitResult;
3352
+ protected visitUnary(e: UnaryExpression): VisitResult;
3353
+ protected visitCall(e: CallExpression): VisitResult;
3354
+ protected visitBinding(_e: BindingExpression): VisitResult;
3355
+ protected visitThis(_e: ThisExpression): VisitResult;
3356
+ protected visitNull(_e: NullExpression): VisitResult;
3357
+ }
3358
+ declare class MatchingExpressionVisitor extends ExpressionVisitor {
3359
+ private predicate;
3360
+ private found;
3361
+ constructor(predicate: (expr: Expression$1) => boolean);
3362
+ find(expr: Expression$1): boolean;
3363
+ visit(expr: Expression$1): void | {
3364
+ readonly abort: true;
3365
+ };
3366
+ }
3367
+
3368
+ type schemaUtils_ExpressionVisitor = ExpressionVisitor;
3369
+ declare const schemaUtils_ExpressionVisitor: typeof ExpressionVisitor;
3370
+ type schemaUtils_MatchingExpressionVisitor = MatchingExpressionVisitor;
3371
+ declare const schemaUtils_MatchingExpressionVisitor: typeof MatchingExpressionVisitor;
3372
+ type schemaUtils_VisitResult = VisitResult;
3373
+ declare namespace schemaUtils {
3374
+ export { schemaUtils_ExpressionVisitor as ExpressionVisitor, schemaUtils_MatchingExpressionVisitor as MatchingExpressionVisitor, type schemaUtils_VisitResult as VisitResult };
3375
+ }
3376
+
3377
+ export { type AfterEntityMutationCallback, type AggregateArgs, type AggregateResult, AllCrudOperations, type AllModelOperations, AllReadOperations, AnyNull, AnyNullClass, type AnyPlugin, type AuthType, BaseCrudDialect, type BatchResult, type BeforeEntityMutationCallback, type BooleanFilter, type BytesFilter, CRUD, CRUD_EXT, type ClientConstructor, type ClientContract, type ClientOptions, type ComputedFieldsOptions, CoreCreateOperations, CoreCrudOperations, CoreDeleteOperations, CoreReadOperations, CoreUpdateOperations, CoreWriteOperations, type CountArgs, type CountResult, type CreateArgs, type CreateInput, type CreateManyAndReturnArgs, type CreateManyArgs, type CreateManyInput, type DateTimeFilter, DbNull, DbNullClass, type DefaultModelResult, type DeleteArgs, type DeleteManyArgs, type EntityMutationHooksDef, type ExistsArgs, type ExtClientMembersBase, type ExtQueryArgsBase, type ExtResultBase, type ExtResultInferenceArgs, type ExtResultSelectOmitFields, type ExtractExtResult, type FilterKind, type FindArgs, type FindFirstArgs, type FindManyArgs, type FindUniqueArgs, type GetAllIncludedOperations, type GetIncludedOperations, type GetProcedure, type GetProcedureNames, type GetProcedureParams, type GetQueryOptions, type GetSlicedFilterKindsForField, type GetSlicedModels, type GetSlicedOperations, type GetSlicedProcedures, type GroupByArgs, type GroupByResult, type HasComputedFields, type HasProcedures, type IncludeInput, InputValidator, type JsonArray, type JsonFilter, JsonNull, JsonNullClass, type JsonNullValues, type JsonObject, type JsonValue, kyselyUtils as KyselyUtils, LOGICAL_COMBINATORS, type MapModelFieldType, type ModelAllowsCreate, type ModelHasRequiredUnsupportedField, type ModelOperations, type ModelResult, type ModelSlicingOptions, type NullsOrder, type NumberFilter, ORMError, ORMErrorReason, type OmitConfig, type OmitInput, type OnKyselyQueryArgs, type OnKyselyQueryCallback, type OnProcedureHookContext, type OperationsRequiringCreate, type OrderBy, type PluginAfterEntityMutationArgs, type PluginBeforeEntityMutationArgs, type ProcedureEnvelope, type ProcedureFunc, type ProcedureHandlerFunc, type ProcedureOperations, type ProceduresOptions, type ProceedKyselyQueryFunction, type QueryOptions, queryUtils as QueryUtils, RejectedByPolicyReason, type RuntimePlugin, schemaUtils as SchemaUtils, type SelectAwareExtResult, type SelectIncludeOmit, type SelectInput, type SelectSubset, type SimplifiedPlainResult, type SimplifiedResult, type SlicingOptions, type SortOrder, type StringFilter, type Subset, type ToKysely, type TransactionClientContract, TransactionIsolationLevel, type TypeDefResult, type TypedJsonFilter, type UpdateArgs, type UpdateInput, type UpdateManyAndReturnArgs, type UpdateManyArgs, type UpsertArgs, type WhereInput, type WhereUniqueInput, ZENSTACK_QUERY_KIND_SYMBOL, ZENSTACK_QUERY_SYMBOL, type ZModelFunction, type ZModelFunctionContext, ZenStackClient, type ZenStackPromise, type ZenStackQueryKind, createQuerySchemaFactory, definePlugin, getCrudDialect };