@zenstackhq/orm 3.0.0-beta.25 → 3.0.0-beta.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  import Decimal from 'decimal.js';
2
2
  import * as _zenstackhq_schema from '@zenstackhq/schema';
3
- import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, IsDelegateModel, GetModelDiscriminator, GetSubModels, NonRelationFields, FieldDef, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, GetModel, BuiltinType, FieldIsDelegateDiscriminator, FieldType, RelationInfo, FieldIsDelegateRelation, ModelDef, DataSourceProviderType, ProcedureDef, Expression as Expression$1, LiteralExpression, ArrayExpression, FieldExpression, MemberExpression, BinaryExpression, UnaryExpression, CallExpression, ThisExpression, NullExpression } from '@zenstackhq/schema';
3
+ import { SchemaDef, BuiltinType, GetModels, FieldDef, ModelDef, DataSourceProviderType, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, GetModel, ProcedureDef, IsDelegateModel, GetModelDiscriminator, GetSubModels, NonRelationFields, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, FieldIsDelegateDiscriminator, FieldType, RelationInfo, FieldIsDelegateRelation, Expression as Expression$1, LiteralExpression, ArrayExpression, FieldExpression, MemberExpression, BinaryExpression, UnaryExpression, CallExpression, ThisExpression, NullExpression } from '@zenstackhq/schema';
4
4
  import * as kysely from 'kysely';
5
- import { 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, Kysely, Generated, ExpressionBuilder, OperandExpression, SqlBool, SelectQueryBuilder, Expression, ExpressionWrapper, QueryId, RootOperationNode, QueryResult, UnknownRow, Dialect, KyselyConfig } from 'kysely';
5
+ import { 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, Kysely, ExpressionBuilder, SelectQueryBuilder, Expression, SqlBool, ExpressionWrapper, Generated, QueryId, RootOperationNode, QueryResult, UnknownRow, Dialect, KyselyConfig, OperandExpression } from 'kysely';
6
6
 
7
7
  declare class DefaultOperationNodeVisitor extends OperationNodeVisitor {
8
8
  protected defaultVisit(node: OperationNode): void;
@@ -114,6 +114,7 @@ declare namespace kyselyUtils {
114
114
  }
115
115
 
116
116
  type Optional<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
117
+ type PartialIf<T, Condition extends boolean> = Condition extends true ? Partial<T> : T;
117
118
  type NullableIf<T, Condition extends boolean> = Condition extends true ? T | null : T;
118
119
  type _Preserve = Date | Function | Decimal | Uint8Array | JsonObject | JsonValue;
119
120
  type _Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
@@ -172,6 +173,97 @@ declare const LOGICAL_COMBINATORS: readonly ["AND", "OR", "NOT"];
172
173
  declare const AGGREGATE_OPERATORS: readonly ["_count", "_sum", "_avg", "_min", "_max"];
173
174
  type AGGREGATE_OPERATORS = (typeof AGGREGATE_OPERATORS)[number];
174
175
 
176
+ declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
177
+ protected readonly schema: Schema;
178
+ protected readonly options: ClientOptions<Schema>;
179
+ protected eb: ExpressionBuilder<any, any>;
180
+ constructor(schema: Schema, options: ClientOptions<Schema>);
181
+ transformPrimitive(value: unknown, _type: BuiltinType, _forArrayField: boolean): unknown;
182
+ transformOutput(value: unknown, _type: BuiltinType): unknown;
183
+ buildSelectModel(model: string, modelAlias: string): SelectQueryBuilder<any, any, {}>;
184
+ buildFilterSortTake(model: string, args: FindArgs<Schema, GetModels<Schema>, true>, query: SelectQueryBuilder<any, any, {}>, modelAlias: string): SelectQueryBuilder<any, any, {}>;
185
+ buildFilter(model: string, modelAlias: string, where: boolean | object | undefined): Expression<SqlBool>;
186
+ private buildCursorFilter;
187
+ private isLogicalCombinator;
188
+ protected buildCompositeFilter(model: string, modelAlias: string, key: (typeof LOGICAL_COMBINATORS)[number], payload: any): Expression<SqlBool>;
189
+ private buildRelationFilter;
190
+ private buildToOneRelationFilter;
191
+ private buildToManyRelationFilter;
192
+ private buildArrayFilter;
193
+ buildPrimitiveFilter(fieldRef: Expression<any>, fieldDef: FieldDef, payload: any): Expression<SqlBool>;
194
+ private buildLiteralFilter;
195
+ private buildStandardFilter;
196
+ private buildStringFilter;
197
+ private prepStringCasing;
198
+ private buildNumberFilter;
199
+ private buildBooleanFilter;
200
+ private buildDateTimeFilter;
201
+ private buildBytesFilter;
202
+ private buildEnumFilter;
203
+ buildOrderBy(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, orderBy: OrArray<OrderBy<Schema, GetModels<Schema>, boolean, boolean>> | undefined, negated: boolean): SelectQueryBuilder<any, any, any>;
204
+ buildSelectAllFields(model: string, query: SelectQueryBuilder<any, any, any>, omit: Record<string, boolean | undefined> | undefined | null, modelAlias: string): SelectQueryBuilder<any, any, any>;
205
+ shouldOmitField(omit: unknown, model: string, field: string): any;
206
+ protected buildModelSelect(model: GetModels<Schema>, subQueryAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>, selectAllFields: boolean): SelectQueryBuilder<any, any, {}>;
207
+ buildSelectField(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, field: string): SelectQueryBuilder<any, any, any>;
208
+ buildDelegateJoin(thisModel: string, thisModelAlias: string, otherModelAlias: string, query: SelectQueryBuilder<any, any, any>): SelectQueryBuilder<any, any, any>;
209
+ buildCountJson(model: string, eb: ExpressionBuilder<any, any>, parentAlias: string, payload: any): ExpressionWrapper<any, any, unknown>;
210
+ private negateSort;
211
+ true(): Expression<SqlBool>;
212
+ false(): Expression<SqlBool>;
213
+ isTrue(expression: Expression<SqlBool>): boolean;
214
+ isFalse(expression: Expression<SqlBool>): boolean;
215
+ and(...args: Expression<SqlBool>[]): Expression<SqlBool>;
216
+ or(...args: Expression<SqlBool>[]): Expression<SqlBool>;
217
+ not(...args: Expression<SqlBool>[]): ExpressionWrapper<any, any, SqlBool>;
218
+ fieldRef(model: string, field: string, modelAlias?: string, inlineComputedField?: boolean): any;
219
+ protected canJoinWithoutNestedSelect(modelDef: ModelDef, payload: boolean | FindArgs<Schema, GetModels<Schema>, true>): boolean;
220
+ abstract get provider(): DataSourceProviderType;
221
+ /**
222
+ * Builds selection for a relation field.
223
+ */
224
+ abstract buildRelationSelection(query: SelectQueryBuilder<any, any, any>, model: string, relationField: string, parentAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>): SelectQueryBuilder<any, any, any>;
225
+ /**
226
+ * Builds skip and take clauses.
227
+ */
228
+ abstract buildSkipTake(query: SelectQueryBuilder<any, any, any>, skip: number | undefined, take: number | undefined): SelectQueryBuilder<any, any, any>;
229
+ /**
230
+ * Builds an Kysely expression that returns a JSON object for the given key-value pairs.
231
+ */
232
+ abstract buildJsonObject(value: Record<string, Expression<unknown>>): ExpressionWrapper<any, any, unknown>;
233
+ /**
234
+ * Builds an Kysely expression that returns the length of an array.
235
+ */
236
+ abstract buildArrayLength(array: Expression<unknown>): ExpressionWrapper<any, any, number>;
237
+ /**
238
+ * Builds an array literal SQL string for the given values.
239
+ */
240
+ abstract buildArrayLiteralSQL(values: unknown[]): string;
241
+ /**
242
+ * Whether the dialect supports updating with a limit on the number of updated rows.
243
+ */
244
+ abstract get supportsUpdateWithLimit(): boolean;
245
+ /**
246
+ * Whether the dialect supports deleting with a limit on the number of deleted rows.
247
+ */
248
+ abstract get supportsDeleteWithLimit(): boolean;
249
+ /**
250
+ * Whether the dialect supports DISTINCT ON.
251
+ */
252
+ abstract get supportsDistinctOn(): boolean;
253
+ /**
254
+ * Whether the dialect support inserting with `DEFAULT` as field value.
255
+ */
256
+ abstract get supportInsertWithDefault(): boolean;
257
+ /**
258
+ * Gets the SQL column type for the given field definition.
259
+ */
260
+ abstract getFieldSqlType(fieldDef: FieldDef): string;
261
+ abstract getStringCasingBehavior(): {
262
+ supportsILike: boolean;
263
+ likeCaseSensitive: boolean;
264
+ };
265
+ }
266
+
175
267
  type ToKyselySchema<Schema extends SchemaDef> = {
176
268
  [Model in GetModels<Schema>]: ToKyselyTable<Schema, Model>;
177
269
  };
@@ -184,100 +276,353 @@ type WrapNull<T, Null> = Null extends true ? T | null : T;
184
276
  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>>;
185
277
  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>;
186
278
 
187
- type DefaultModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Omit = undefined, Optional = false, Array = false> = WrapType<IsDelegateModel<Schema, Model> extends true ? DelegateUnionResult<Schema, Model, GetSubModels<Schema, Model>, Omit> : {
188
- [Key in NonRelationFields<Schema, Model> as Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key]: MapModelFieldType<Schema, Model, Key>;
189
- }, Optional, Array>;
190
- type DelegateUnionResult<Schema extends SchemaDef, Model extends GetModels<Schema>, SubModel extends GetModels<Schema>, Omit = undefined> = SubModel extends string ? DefaultModelResult<Schema, SubModel, Omit> & {
191
- [K in GetModelDiscriminator<Schema, Model>]: SubModel;
192
- } : never;
193
- type ModelSelectResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Select, Omit> = {
194
- [Key in keyof Select as Select[Key] extends false | undefined ? never : Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key extends '_count' ? Select[Key] extends SelectCount<Schema, Model> ? Key : never : Key]: Key extends '_count' ? SelectCountResult<Schema, Model, Select[Key]> : Key extends NonRelationFields<Schema, Model> ? MapModelFieldType<Schema, Model, Key> : Key extends RelationFields<Schema, Model> ? Select[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? 'select' extends keyof Select[Key] ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Pick<Select[Key], 'select'>, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Pick<Select[Key], 'include' | 'omit'>, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, Omit, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : never;
195
- };
196
- type SelectCountResult<Schema extends SchemaDef, Model extends GetModels<Schema>, C> = C extends true ? {
197
- [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: number;
198
- } : C extends {
199
- select: infer S;
200
- } ? {
201
- [Key in keyof S]: number;
202
- } : never;
203
- type ModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args = {}, Optional = false, Array = false> = WrapType<Args extends {
204
- select: infer S;
205
- omit?: infer O;
206
- } ? ModelSelectResult<Schema, Model, S, O> : Args extends {
207
- include: infer I;
208
- omit?: infer O;
209
- } ? DefaultModelResult<Schema, Model, O> & {
210
- [Key in keyof I & RelationFields<Schema, Model> as I[Key] extends false | undefined ? never : Key]: I[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, I[Key], ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, undefined, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>>;
211
- } : Args extends {
212
- omit: infer O;
213
- } ? DefaultModelResult<Schema, Model, O> : DefaultModelResult<Schema, Model>, Optional, Array>;
214
- type SimplifiedModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args = {}, Optional = false, Array = false> = Simplify<ModelResult<Schema, Model, Args, Optional, Array>>;
215
- type TypeDefResult<Schema extends SchemaDef, TypeDef extends GetTypeDefs<Schema>> = Optional<{
216
- [Key in GetTypeDefFields<Schema, TypeDef>]: MapTypeDefFieldType<Schema, TypeDef, Key>;
217
- }, keyof {
218
- [Key in GetTypeDefFields<Schema, TypeDef> as TypeDefFieldIsOptional<Schema, TypeDef, Key> extends true ? Key : never]: true;
219
- }>;
220
- type BatchResult = {
221
- count: number;
222
- };
223
- type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ScalarOnly extends boolean = false, WithAggregations extends boolean = false> = {
224
- [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Key>> : GetModelFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations> : PrimitiveFilter<GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations>;
225
- } & {
226
- $expr?: (eb: ExpressionBuilder<ToKyselySchema<Schema>, Model>) => OperandExpression<SqlBool>;
227
- } & {
228
- AND?: OrArray<WhereInput<Schema, Model, ScalarOnly>>;
229
- OR?: WhereInput<Schema, Model, ScalarOnly>[];
230
- NOT?: OrArray<WhereInput<Schema, Model, ScalarOnly>>;
231
- };
232
- type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | ({
233
- equals?: NullableIf<keyof GetEnum<Schema, T>, Nullable>;
234
- in?: (keyof GetEnum<Schema, T>)[];
235
- notIn?: (keyof GetEnum<Schema, T>)[];
236
- not?: EnumFilter<Schema, T, Nullable, WithAggregations>;
237
- } & (WithAggregations extends true ? {
238
- _count?: NumberFilter<'Int', false, false>;
239
- _min?: EnumFilter<Schema, T, false, false>;
240
- _max?: EnumFilter<Schema, T, false, false>;
241
- } : {}));
242
- type ArrayFilter<Schema extends SchemaDef, T extends string> = {
243
- equals?: MapScalarType<Schema, T>[] | null;
244
- has?: MapScalarType<Schema, T> | null;
245
- hasEvery?: MapScalarType<Schema, T>[];
246
- hasSome?: MapScalarType<Schema, T>[];
247
- isEmpty?: boolean;
279
+ type CoreCrudOperation = 'findMany' | 'findUnique' | 'findFirst' | 'create' | 'createMany' | 'createManyAndReturn' | 'update' | 'updateMany' | 'updateManyAndReturn' | 'upsert' | 'delete' | 'deleteMany' | 'count' | 'aggregate' | 'groupBy';
280
+ type AllCrudOperation = CoreCrudOperation | 'findUniqueOrThrow' | 'findFirstOrThrow';
281
+
282
+ /**
283
+ * ZenStack runtime plugin.
284
+ */
285
+ interface RuntimePlugin<Schema extends SchemaDef = SchemaDef> {
286
+ /**
287
+ * Plugin ID.
288
+ */
289
+ id: string;
290
+ /**
291
+ * Plugin display name.
292
+ */
293
+ name?: string;
294
+ /**
295
+ * Plugin description.
296
+ */
297
+ description?: string;
298
+ /**
299
+ * Custom function implementations.
300
+ */
301
+ functions?: Record<string, ZModelFunction<Schema>>;
302
+ /**
303
+ * Intercepts an ORM query.
304
+ */
305
+ onQuery?: OnQueryCallback<Schema>;
306
+ /**
307
+ * Intercepts an entity mutation.
308
+ */
309
+ onEntityMutation?: EntityMutationHooksDef<Schema>;
310
+ /**
311
+ * Intercepts a Kysely query.
312
+ */
313
+ onKyselyQuery?: OnKyselyQueryCallback<Schema>;
314
+ }
315
+ /**
316
+ * Defines a ZenStack runtime plugin.
317
+ */
318
+ declare function definePlugin<Schema extends SchemaDef>(plugin: RuntimePlugin<Schema>): RuntimePlugin<Schema>;
319
+
320
+ type OnQueryCallback<Schema extends SchemaDef> = (ctx: OnQueryHookContext<Schema>) => Promise<unknown>;
321
+ type OnQueryHookContext<Schema extends SchemaDef> = {
322
+ /**
323
+ * The model that is being queried.
324
+ */
325
+ model: GetModels<Schema>;
326
+ /**
327
+ * The operation that is being performed.
328
+ */
329
+ operation: AllCrudOperation;
330
+ /**
331
+ * The query arguments.
332
+ */
333
+ args: unknown;
334
+ /**
335
+ * The function to proceed with the original query.
336
+ * It takes the same arguments as the operation method.
337
+ *
338
+ * @param args The query arguments.
339
+ */
340
+ proceed: (args: unknown) => Promise<unknown>;
341
+ /**
342
+ * The ZenStack client that is performing the operation.
343
+ */
344
+ client: ClientContract<Schema>;
248
345
  };
249
- type MapScalarType<Schema extends SchemaDef, T extends string> = T extends GetEnums<Schema> ? keyof GetEnum<Schema, T> : MapBaseType$1<T>;
250
- type PrimitiveFilter<T extends string, Nullable extends boolean, WithAggregations extends boolean> = T extends 'String' ? StringFilter<Nullable, WithAggregations> : T extends 'Int' | 'Float' | 'Decimal' | 'BigInt' ? NumberFilter<T, Nullable, WithAggregations> : T extends 'Boolean' ? BooleanFilter<Nullable, WithAggregations> : T extends 'DateTime' ? DateTimeFilter<Nullable, WithAggregations> : T extends 'Bytes' ? BytesFilter<Nullable, WithAggregations> : T extends 'Json' ? 'Not implemented yet' : never;
251
- type CommonPrimitiveFilter<DataType, T extends BuiltinType, Nullable extends boolean, WithAggregations extends boolean> = {
252
- equals?: NullableIf<DataType, Nullable>;
253
- in?: DataType[];
254
- notIn?: DataType[];
255
- lt?: DataType;
256
- lte?: DataType;
257
- gt?: DataType;
258
- gte?: DataType;
259
- not?: PrimitiveFilter<T, Nullable, WithAggregations>;
346
+ type EntityMutationHooksDef<Schema extends SchemaDef> = {
347
+ /**
348
+ * Called before entities are mutated.
349
+ */
350
+ beforeEntityMutation?: BeforeEntityMutationCallback<Schema>;
351
+ /**
352
+ * Called after entities are mutated.
353
+ */
354
+ afterEntityMutation?: AfterEntityMutationCallback<Schema>;
355
+ /**
356
+ * Whether to run after-mutation hooks within the transaction that performs the mutation.
357
+ *
358
+ * If set to `true`, if the mutation already runs inside a transaction, the callbacks are
359
+ * executed immediately after the mutation within the transaction boundary. If the mutation
360
+ * is not running inside a transaction, a new transaction is created to run both the mutation
361
+ * and the callbacks.
362
+ *
363
+ * If set to `false`, the callbacks are executed after the mutation transaction is committed.
364
+ *
365
+ * Defaults to `false`.
366
+ */
367
+ runAfterMutationWithinTransaction?: boolean;
260
368
  };
261
- type StringFilter<Nullable extends boolean, WithAggregations extends boolean> = NullableIf<string, Nullable> | (CommonPrimitiveFilter<string, 'String', Nullable, WithAggregations> & {
262
- contains?: string;
263
- startsWith?: string;
264
- endsWith?: string;
369
+ type MutationHooksArgs<Schema extends SchemaDef> = {
265
370
  /**
266
- * Not effective for "sqlite" provider
371
+ * The model that is being mutated.
267
372
  */
268
- mode?: 'default' | 'insensitive';
269
- } & (WithAggregations extends true ? {
270
- _count?: NumberFilter<'Int', false, false>;
271
- _min?: StringFilter<false, false>;
272
- _max?: StringFilter<false, false>;
273
- } : {}));
274
- type NumberFilter<T extends 'Int' | 'Float' | 'Decimal' | 'BigInt', Nullable extends boolean, WithAggregations extends boolean> = NullableIf<number | bigint, Nullable> | (CommonPrimitiveFilter<number, T, Nullable, WithAggregations> & (WithAggregations extends true ? {
275
- _count?: NumberFilter<'Int', false, false>;
276
- _avg?: NumberFilter<T, false, false>;
277
- _sum?: NumberFilter<T, false, false>;
278
- _min?: NumberFilter<T, false, false>;
279
- _max?: NumberFilter<T, false, false>;
280
- } : {}));
373
+ model: GetModels<Schema>;
374
+ /**
375
+ * The mutation action that is being performed.
376
+ */
377
+ action: 'create' | 'update' | 'delete';
378
+ /**
379
+ * The mutation data. Only available for create and update actions.
380
+ */
381
+ queryNode: OperationNode;
382
+ /**
383
+ * A query ID that uniquely identifies the mutation operation. You can use it to correlate
384
+ * data between the before and after mutation hooks.
385
+ */
386
+ queryId: QueryId;
387
+ };
388
+ type BeforeEntityMutationCallback<Schema extends SchemaDef> = (args: PluginBeforeEntityMutationArgs<Schema>) => MaybePromise<void>;
389
+ type AfterEntityMutationCallback<Schema extends SchemaDef> = (args: PluginAfterEntityMutationArgs<Schema>) => MaybePromise<void>;
390
+ type PluginBeforeEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
391
+ /**
392
+ * Loads the entities that are about to be mutated. The db operation that loads the entities is executed
393
+ * within the same transaction context as the mutation.
394
+ */
395
+ loadBeforeMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
396
+ /**
397
+ * The ZenStack client you can use to perform additional operations. The database operations initiated
398
+ * from this client are executed within the same transaction as the mutation if the mutation is running
399
+ * inside a transaction.
400
+ *
401
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
402
+ */
403
+ client: ClientContract<Schema>;
404
+ };
405
+ type PluginAfterEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
406
+ /**
407
+ * Loads the entities that have been mutated.
408
+ */
409
+ loadAfterMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
410
+ /**
411
+ * The ZenStack client you can use to perform additional operations.
412
+ * See {@link EntityMutationHooksDef.runAfterMutationWithinTransaction} for detailed transaction behavior.
413
+ *
414
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
415
+ */
416
+ client: ClientContract<Schema>;
417
+ };
418
+ type OnKyselyQueryArgs<Schema extends SchemaDef> = {
419
+ schema: SchemaDef;
420
+ client: ClientContract<Schema>;
421
+ query: RootOperationNode;
422
+ proceed: ProceedKyselyQueryFunction;
423
+ };
424
+ type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise<QueryResult<any>>;
425
+ type OnKyselyQueryCallback<Schema extends SchemaDef> = (args: OnKyselyQueryArgs<Schema>) => Promise<QueryResult<UnknownRow>>;
426
+
427
+ type ZModelFunctionContext<Schema extends SchemaDef> = {
428
+ /**
429
+ * ZenStack client instance
430
+ */
431
+ client: ClientContract<Schema>;
432
+ /**
433
+ * Database dialect
434
+ */
435
+ dialect: BaseCrudDialect<Schema>;
436
+ /**
437
+ * The containing model name
438
+ */
439
+ model: GetModels<Schema>;
440
+ /**
441
+ * The alias name that can be used to refer to the containing model
442
+ */
443
+ modelAlias: string;
444
+ /**
445
+ * The CRUD operation being performed
446
+ */
447
+ operation: CRUD_EXT;
448
+ };
449
+ type ZModelFunction<Schema extends SchemaDef> = (eb: ExpressionBuilder<ToKyselySchema<Schema>, keyof ToKyselySchema<Schema>>, args: Expression<any>[], context: ZModelFunctionContext<Schema>) => Expression<unknown>;
450
+ /**
451
+ * ZenStack client options.
452
+ */
453
+ type ClientOptions<Schema extends SchemaDef> = {
454
+ /**
455
+ * Kysely dialect.
456
+ */
457
+ dialect: Dialect;
458
+ /**
459
+ * Custom function definitions.
460
+ */
461
+ functions?: Record<string, ZModelFunction<Schema>>;
462
+ /**
463
+ * Plugins.
464
+ */
465
+ plugins?: RuntimePlugin<Schema>[];
466
+ /**
467
+ * Logging configuration.
468
+ */
469
+ log?: KyselyConfig['log'];
470
+ /**
471
+ * Whether to automatically fix timezone for `DateTime` fields returned by node-pg. Defaults
472
+ * to `true`.
473
+ *
474
+ * Node-pg has a terrible quirk that it interprets the date value as local timezone (as a
475
+ * `Date` object) although for `DateTime` field the data in DB is stored in UTC.
476
+ * @see https://github.com/brianc/node-postgres/issues/429
477
+ */
478
+ fixPostgresTimezone?: boolean;
479
+ /**
480
+ * Whether to enable input validations expressed with attributes like `@email`, `@regex`,
481
+ * `@@validate`, etc. Defaults to `true`.
482
+ */
483
+ validateInput?: boolean;
484
+ /**
485
+ * Options for omitting fields in ORM query results.
486
+ */
487
+ omit?: OmitOptions<Schema>;
488
+ /**
489
+ * Whether to allow overriding omit settings at query time. Defaults to `true`. When set to
490
+ * `false`, an `omit` clause that sets field to `false` (not omitting) will trigger a validation
491
+ * error.
492
+ */
493
+ allowQueryTimeOmitOverride?: boolean;
494
+ } & (HasComputedFields<Schema> extends true ? {
495
+ /**
496
+ * Computed field definitions.
497
+ */
498
+ computedFields: ComputedFieldsOptions<Schema>;
499
+ } : {}) & (HasProcedures<Schema> extends true ? {
500
+ /**
501
+ * Custom procedure definitions.
502
+ */
503
+ procedures: ProceduresOptions<Schema>;
504
+ } : {});
505
+ /**
506
+ * Options for omitting fields in ORM query results.
507
+ */
508
+ type OmitOptions<Schema extends SchemaDef> = {
509
+ [Model in GetModels<Schema>]?: {
510
+ [Field in GetModelFields<Schema, Model> as Field extends ScalarFields<Schema, Model> ? Field : never]?: boolean;
511
+ };
512
+ };
513
+ type ComputedFieldsOptions<Schema extends SchemaDef> = {
514
+ [Model in GetModels<Schema> as 'computedFields' extends keyof GetModel<Schema, Model> ? Model : never]: {
515
+ [Field in keyof Schema['models'][Model]['computedFields']]: PrependParameter<ExpressionBuilder<ToKyselySchema<Schema>, Model>, Schema['models'][Model]['computedFields'][Field]>;
516
+ };
517
+ };
518
+ type HasComputedFields<Schema extends SchemaDef> = string extends GetModels<Schema> ? false : keyof ComputedFieldsOptions<Schema> extends never ? false : true;
519
+ type ProceduresOptions<Schema extends SchemaDef> = Schema extends {
520
+ procedures: Record<string, ProcedureDef>;
521
+ } ? {
522
+ [Key in keyof Schema['procedures']]: PrependParameter<ClientContract<Schema>, ProcedureFunc<Schema, Schema['procedures'][Key]>>;
523
+ } : {};
524
+ type HasProcedures<Schema extends SchemaDef> = Schema extends {
525
+ procedures: Record<string, ProcedureDef>;
526
+ } ? true : false;
527
+
528
+ type DefaultModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema> = ClientOptions<Schema>, Omit = undefined, Optional = false, Array = false> = WrapType<IsDelegateModel<Schema, Model> extends true ? DelegateUnionResult<Schema, Model, Options, GetSubModels<Schema, Model>, Omit> : {
529
+ [Key in NonRelationFields<Schema, Model> as ShouldOmitField<Schema, Model, Options, Key, Omit> extends true ? never : Key]: MapModelFieldType<Schema, Model, Key>;
530
+ }, Optional, Array>;
531
+ type ShouldOmitField<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<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>;
532
+ 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;
533
+ type OptionsLevelOmit<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Options extends ClientOptions<Schema>> = Model extends keyof Options['omit'] ? Field extends keyof Options['omit'][Model] ? Options['omit'][Model][Field] extends boolean ? Options['omit'][Model][Field] : undefined : undefined : undefined;
534
+ type SchemaLevelOmit<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelField<Schema, Model, Field>['omit'] extends true ? true : false;
535
+ type DelegateUnionResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema>, SubModel extends GetModels<Schema>, Omit = undefined> = SubModel extends string ? DefaultModelResult<Schema, SubModel, Options, Omit> & {
536
+ [K in GetModelDiscriminator<Schema, Model>]: SubModel;
537
+ } : never;
538
+ type ModelSelectResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema>, Select, Omit> = {
539
+ [Key in keyof Select as Select[Key] extends false | undefined ? never : Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key extends '_count' ? Select[Key] extends SelectCount<Schema, Model> ? Key : never : Key]: Key extends '_count' ? SelectCountResult<Schema, Model, Select[Key]> : Key extends NonRelationFields<Schema, Model> ? MapModelFieldType<Schema, Model, Key> : Key extends RelationFields<Schema, Model> ? Select[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? 'select' extends keyof Select[Key] ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Options, Pick<Select[Key], 'select'>, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Options, Pick<Select[Key], 'include' | 'omit'>, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, Options, Omit, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : never;
540
+ };
541
+ type SelectCountResult<Schema extends SchemaDef, Model extends GetModels<Schema>, C> = C extends true ? {
542
+ [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: number;
543
+ } : C extends {
544
+ select: infer S;
545
+ } ? {
546
+ [Key in keyof S]: number;
547
+ } : never;
548
+ type ModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema> = ClientOptions<Schema>, Args = {}, Optional = false, Array = false> = WrapType<Args extends {
549
+ select: infer S;
550
+ omit?: infer O;
551
+ } ? ModelSelectResult<Schema, Model, Options, S, O> : Args extends {
552
+ include: infer I;
553
+ omit?: infer O;
554
+ } ? DefaultModelResult<Schema, Model, Options, O> & {
555
+ [Key in keyof I & RelationFields<Schema, Model> as I[Key] extends false | undefined ? never : Key]: I[Key] extends FindArgs<Schema, RelationFieldType<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> ? ModelResult<Schema, RelationFieldType<Schema, Model, Key>, Options, I[Key], ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>> : DefaultModelResult<Schema, RelationFieldType<Schema, Model, Key>, Options, undefined, ModelFieldIsOptional<Schema, Model, Key>, FieldIsArray<Schema, Model, Key>>;
556
+ } : Args extends {
557
+ omit: infer O;
558
+ } ? DefaultModelResult<Schema, Model, Options, O> : DefaultModelResult<Schema, Model, Options>, Optional, Array>;
559
+ type SimplifiedModelResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema>, Args = {}, Optional = false, Array = false> = Simplify<ModelResult<Schema, Model, Options, Args, Optional, Array>>;
560
+ type TypeDefResult<Schema extends SchemaDef, TypeDef extends GetTypeDefs<Schema>, Partial extends boolean = false> = PartialIf<Optional<{
561
+ [Key in GetTypeDefFields<Schema, TypeDef>]: MapFieldDefType<Schema, GetTypeDefField<Schema, TypeDef, Key>, Partial>;
562
+ }, Partial extends true ? never : keyof {
563
+ [Key in GetTypeDefFields<Schema, TypeDef> as TypeDefFieldIsOptional<Schema, TypeDef, Key> extends true ? Key : never]: true;
564
+ }>, Partial> & Record<string, unknown>;
565
+ type BatchResult = {
566
+ count: number;
567
+ };
568
+ type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ScalarOnly extends boolean = false, WithAggregations extends boolean = false> = {
569
+ [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Key>> : GetModelFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations> : PrimitiveFilter<GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations>;
570
+ } & {
571
+ $expr?: (eb: ExpressionBuilder<ToKyselySchema<Schema>, Model>) => OperandExpression<SqlBool>;
572
+ } & {
573
+ AND?: OrArray<WhereInput<Schema, Model, ScalarOnly>>;
574
+ OR?: WhereInput<Schema, Model, ScalarOnly>[];
575
+ NOT?: OrArray<WhereInput<Schema, Model, ScalarOnly>>;
576
+ };
577
+ type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | ({
578
+ equals?: NullableIf<keyof GetEnum<Schema, T>, Nullable>;
579
+ in?: (keyof GetEnum<Schema, T>)[];
580
+ notIn?: (keyof GetEnum<Schema, T>)[];
581
+ not?: EnumFilter<Schema, T, Nullable, WithAggregations>;
582
+ } & (WithAggregations extends true ? {
583
+ _count?: NumberFilter<'Int', false, false>;
584
+ _min?: EnumFilter<Schema, T, false, false>;
585
+ _max?: EnumFilter<Schema, T, false, false>;
586
+ } : {}));
587
+ type ArrayFilter<Schema extends SchemaDef, T extends string> = {
588
+ equals?: MapScalarType<Schema, T>[] | null;
589
+ has?: MapScalarType<Schema, T> | null;
590
+ hasEvery?: MapScalarType<Schema, T>[];
591
+ hasSome?: MapScalarType<Schema, T>[];
592
+ isEmpty?: boolean;
593
+ };
594
+ type MapScalarType<Schema extends SchemaDef, T extends string> = T extends GetEnums<Schema> ? keyof GetEnum<Schema, T> : MapBaseType$1<T>;
595
+ type PrimitiveFilter<T extends string, Nullable extends boolean, WithAggregations extends boolean> = T extends 'String' ? StringFilter<Nullable, WithAggregations> : T extends 'Int' | 'Float' | 'Decimal' | 'BigInt' ? NumberFilter<T, Nullable, WithAggregations> : T extends 'Boolean' ? BooleanFilter<Nullable, WithAggregations> : T extends 'DateTime' ? DateTimeFilter<Nullable, WithAggregations> : T extends 'Bytes' ? BytesFilter<Nullable, WithAggregations> : T extends 'Json' ? 'Not implemented yet' : never;
596
+ type CommonPrimitiveFilter<DataType, T extends BuiltinType, Nullable extends boolean, WithAggregations extends boolean> = {
597
+ equals?: NullableIf<DataType, Nullable>;
598
+ in?: DataType[];
599
+ notIn?: DataType[];
600
+ lt?: DataType;
601
+ lte?: DataType;
602
+ gt?: DataType;
603
+ gte?: DataType;
604
+ not?: PrimitiveFilter<T, Nullable, WithAggregations>;
605
+ };
606
+ type StringFilter<Nullable extends boolean, WithAggregations extends boolean> = NullableIf<string, Nullable> | (CommonPrimitiveFilter<string, 'String', Nullable, WithAggregations> & {
607
+ contains?: string;
608
+ startsWith?: string;
609
+ endsWith?: string;
610
+ /**
611
+ * Not effective for "sqlite" provider
612
+ */
613
+ mode?: 'default' | 'insensitive';
614
+ } & (WithAggregations extends true ? {
615
+ _count?: NumberFilter<'Int', false, false>;
616
+ _min?: StringFilter<false, false>;
617
+ _max?: StringFilter<false, false>;
618
+ } : {}));
619
+ type NumberFilter<T extends 'Int' | 'Float' | 'Decimal' | 'BigInt', Nullable extends boolean, WithAggregations extends boolean> = NullableIf<number | bigint, Nullable> | (CommonPrimitiveFilter<number, T, Nullable, WithAggregations> & (WithAggregations extends true ? {
620
+ _count?: NumberFilter<'Int', false, false>;
621
+ _avg?: NumberFilter<T, false, false>;
622
+ _sum?: NumberFilter<T, false, false>;
623
+ _min?: NumberFilter<T, false, false>;
624
+ _max?: NumberFilter<T, false, false>;
625
+ } : {}));
281
626
  type DateTimeFilter<Nullable extends boolean, WithAggregations extends boolean> = NullableIf<Date | string, Nullable> | (CommonPrimitiveFilter<Date | string, 'DateTime', Nullable, WithAggregations> & (WithAggregations extends true ? {
282
627
  _count?: NumberFilter<'Int', false, false>;
283
628
  _min?: DateTimeFilter<false, false>;
@@ -371,8 +716,7 @@ type ToOneRelationFilter<Schema extends SchemaDef, Model extends GetModels<Schem
371
716
  }, ModelFieldIsOptional<Schema, Model, Field>>;
372
717
  type RelationFilter<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? ToManyRelationFilter<Schema, Model, Field> : ToOneRelationFilter<Schema, Model, Field>;
373
718
  type MapModelFieldType<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = MapFieldDefType<Schema, GetModelField<Schema, Model, Field>>;
374
- type MapTypeDefFieldType<Schema extends SchemaDef, TypeDef extends GetTypeDefs<Schema>, Field extends GetTypeDefFields<Schema, TypeDef>> = MapFieldDefType<Schema, GetTypeDefField<Schema, TypeDef, Field>>;
375
- type MapFieldDefType<Schema extends SchemaDef, T extends Pick<FieldDef, 'type' | 'optional' | 'array'>> = WrapType<T['type'] extends GetEnums<Schema> ? keyof GetEnum<Schema, T['type']> : T['type'] extends GetTypeDefs<Schema> ? TypeDefResult<Schema, T['type']> & Record<string, unknown> : MapBaseType$1<T['type']>, T['optional'], T['array']>;
719
+ 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']>;
376
720
  type OptionalFieldsForCreate<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
377
721
  [Key in GetModelFields<Schema, Model> as ModelFieldIsOptional<Schema, Model, Key> extends true ? Key : FieldHasDefault<Schema, Model, Key> extends true ? Key : FieldIsArray<Schema, Model, Key> extends true ? Key : GetModelField<Schema, Model, Key>['updatedAt'] extends true ? Key : never]: GetModelField<Schema, Model, Key>;
378
722
  };
@@ -491,464 +835,143 @@ type ToOneRelationUpdateInput<Schema extends SchemaDef, Model extends GetModels<
491
835
  update?: NestedUpdateInput<Schema, Model, Field>;
492
836
  upsert?: NestedUpsertInput<Schema, Model, Field>;
493
837
  } & (ModelFieldIsOptional<Schema, Model, Field> extends true ? {
494
- disconnect?: DisconnectInput<Schema, Model, Field>;
495
- delete?: NestedDeleteInput<Schema, Model, Field>;
496
- } : {}), FieldIsDelegateRelation<Schema, Model, Field> extends true ? 'create' | 'connectOrCreate' | 'upsert' : never>;
497
- type DeleteArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
498
- where: WhereUniqueInput<Schema, Model>;
499
- } & SelectIncludeOmit<Schema, Model, true>;
500
- type DeleteManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
501
- where?: WhereInput<Schema, Model>;
502
- limit?: number;
503
- };
504
- type CountArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<FindArgs<Schema, Model, true>, 'select' | 'include' | 'distinct' | 'omit'> & {
505
- select?: CountAggregateInput<Schema, Model> | true;
506
- };
507
- type CountAggregateInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
508
- [Key in NonRelationFields<Schema, Model>]?: true;
509
- } & {
510
- _all?: true;
511
- };
512
- type CountResult<Schema extends SchemaDef, _Model extends GetModels<Schema>, Args> = Args extends {
513
- select: infer S;
514
- } ? S extends true ? number : {
515
- [Key in keyof S]: number;
516
- } : number;
517
- type AggregateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
518
- where?: WhereInput<Schema, Model>;
519
- skip?: number;
520
- take?: number;
521
- orderBy?: OrArray<OrderBy<Schema, Model, true, false>>;
522
- } & {
523
- _count?: true | CountAggregateInput<Schema, Model>;
524
- _min?: MinMaxInput<Schema, Model, true>;
525
- _max?: MinMaxInput<Schema, Model, true>;
526
- } & (NumericFields<Schema, Model> extends never ? {} : {
527
- _avg?: SumAvgInput<Schema, Model, true>;
528
- _sum?: SumAvgInput<Schema, Model, true>;
529
- });
530
- type NumericFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
531
- [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>;
532
- };
533
- type SumAvgInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
534
- [Key in NumericFields<Schema, Model>]?: ValueType;
535
- };
536
- type MinMaxInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
537
- [Key in GetModelFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? never : FieldIsRelation<Schema, Model, Key> extends true ? never : Key]?: ValueType;
538
- };
539
- type AggregateResult<Schema extends SchemaDef, _Model extends GetModels<Schema>, Args> = (Args extends {
540
- _count: infer Count;
541
- } ? {
542
- _count: AggCommonOutput<Count>;
543
- } : {}) & (Args extends {
544
- _sum: infer Sum;
545
- } ? {
546
- _sum: AggCommonOutput<Sum>;
547
- } : {}) & (Args extends {
548
- _avg: infer Avg;
549
- } ? {
550
- _avg: AggCommonOutput<Avg>;
551
- } : {}) & (Args extends {
552
- _min: infer Min;
553
- } ? {
554
- _min: AggCommonOutput<Min>;
555
- } : {}) & (Args extends {
556
- _max: infer Max;
557
- } ? {
558
- _max: AggCommonOutput<Max>;
559
- } : {});
560
- type AggCommonOutput<Input> = Input extends true ? number : Input extends {} ? {
561
- [Key in keyof Input]: number;
562
- } : never;
563
- type GroupByHaving<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<WhereInput<Schema, Model, true, true>, '$expr'>;
564
- type GroupByArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
565
- where?: WhereInput<Schema, Model>;
566
- orderBy?: OrArray<OrderBy<Schema, Model, false, true>>;
567
- by: NonRelationFields<Schema, Model> | NonEmptyArray<NonRelationFields<Schema, Model>>;
568
- having?: GroupByHaving<Schema, Model>;
569
- take?: number;
570
- skip?: number;
571
- _count?: true | CountAggregateInput<Schema, Model>;
572
- _min?: MinMaxInput<Schema, Model, true>;
573
- _max?: MinMaxInput<Schema, Model, true>;
574
- } & (NumericFields<Schema, Model> extends never ? {} : {
575
- _avg?: SumAvgInput<Schema, Model, true>;
576
- _sum?: SumAvgInput<Schema, Model, true>;
577
- });
578
- type GroupByResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args extends {
579
- by: unknown;
580
- }> = Array<{
581
- [Key in NonRelationFields<Schema, Model> as Key extends ValueOfPotentialTuple<Args['by']> ? Key : never]: MapModelFieldType<Schema, Model, Key>;
582
- } & (Args extends {
583
- _count: infer Count;
584
- } ? {
585
- _count: AggCommonOutput<Count>;
586
- } : {}) & (Args extends {
587
- _avg: infer Avg;
588
- } ? {
589
- _avg: AggCommonOutput<Avg>;
590
- } : {}) & (Args extends {
591
- _sum: infer Sum;
592
- } ? {
593
- _sum: AggCommonOutput<Sum>;
594
- } : {}) & (Args extends {
595
- _min: infer Min;
596
- } ? {
597
- _min: AggCommonOutput<Min>;
598
- } : {}) & (Args extends {
599
- _max: infer Max;
600
- } ? {
601
- _max: AggCommonOutput<Max>;
602
- } : {})>;
603
- type ConnectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>> : WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
604
- type ConnectOrCreateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<ConnectOrCreatePayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>> : ConnectOrCreatePayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
605
- type DisconnectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>, true> : boolean | WhereInput<Schema, RelationFieldType<Schema, Model, Field>>;
606
- type SetRelationInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>>;
607
- type NestedUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<{
608
- where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
609
- data: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
610
- }, true> : XOR<{
611
- where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
612
- data: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
613
- }, UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>>;
614
- type NestedUpsertInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<{
615
- where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
616
- create: CreateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
617
- update: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
618
- }, FieldIsArray<Schema, Model, Field>>;
619
- type NestedUpdateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<UpdateManyPayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>>;
620
- type NestedDeleteInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>, true> : boolean | WhereInput<Schema, RelationFieldType<Schema, Model, Field>>;
621
- type NestedDeleteManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<WhereInput<Schema, RelationFieldType<Schema, Model, Field>, true>>;
622
- type NonOwnedRelationFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
623
- [Key in RelationFields<Schema, Model> as GetModelField<Schema, Model, Key>['relation'] extends {
624
- references: unknown[];
625
- } ? never : Key]: true;
626
- };
627
- type HasToManyRelations<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
628
- [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: true;
629
- } extends never ? false : true;
630
- type ProviderSupportsDistinct<Schema extends SchemaDef> = Schema['provider']['type'] extends 'postgresql' ? true : false;
631
-
632
- declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
633
- protected readonly schema: Schema;
634
- protected readonly options: ClientOptions<Schema>;
635
- protected eb: ExpressionBuilder<any, any>;
636
- constructor(schema: Schema, options: ClientOptions<Schema>);
637
- transformPrimitive(value: unknown, _type: BuiltinType, _forArrayField: boolean): unknown;
638
- transformOutput(value: unknown, _type: BuiltinType): unknown;
639
- buildSelectModel(model: string, modelAlias: string): SelectQueryBuilder<any, any, {}>;
640
- buildFilterSortTake(model: string, args: FindArgs<Schema, GetModels<Schema>, true>, query: SelectQueryBuilder<any, any, {}>, modelAlias: string): SelectQueryBuilder<any, any, {}>;
641
- buildFilter(model: string, modelAlias: string, where: boolean | object | undefined): Expression<SqlBool>;
642
- private buildCursorFilter;
643
- private isLogicalCombinator;
644
- protected buildCompositeFilter(model: string, modelAlias: string, key: (typeof LOGICAL_COMBINATORS)[number], payload: any): Expression<SqlBool>;
645
- private buildRelationFilter;
646
- private buildToOneRelationFilter;
647
- private buildToManyRelationFilter;
648
- private buildArrayFilter;
649
- buildPrimitiveFilter(fieldRef: Expression<any>, fieldDef: FieldDef, payload: any): Expression<SqlBool>;
650
- private buildLiteralFilter;
651
- private buildStandardFilter;
652
- private buildStringFilter;
653
- private prepStringCasing;
654
- private buildNumberFilter;
655
- private buildBooleanFilter;
656
- private buildDateTimeFilter;
657
- private buildBytesFilter;
658
- private buildEnumFilter;
659
- buildOrderBy(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, orderBy: OrArray<OrderBy<Schema, GetModels<Schema>, boolean, boolean>> | undefined, negated: boolean): SelectQueryBuilder<any, any, any>;
660
- buildSelectAllFields(model: string, query: SelectQueryBuilder<any, any, any>, omit: Record<string, boolean | undefined> | undefined | null, modelAlias: string): SelectQueryBuilder<any, any, any>;
661
- protected buildModelSelect(model: GetModels<Schema>, subQueryAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>, selectAllFields: boolean): SelectQueryBuilder<any, any, {}>;
662
- buildSelectField(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, field: string): SelectQueryBuilder<any, any, any>;
663
- buildDelegateJoin(thisModel: string, thisModelAlias: string, otherModelAlias: string, query: SelectQueryBuilder<any, any, any>): SelectQueryBuilder<any, any, any>;
664
- buildCountJson(model: string, eb: ExpressionBuilder<any, any>, parentAlias: string, payload: any): ExpressionWrapper<any, any, unknown>;
665
- private negateSort;
666
- true(): Expression<SqlBool>;
667
- false(): Expression<SqlBool>;
668
- isTrue(expression: Expression<SqlBool>): boolean;
669
- isFalse(expression: Expression<SqlBool>): boolean;
670
- and(...args: Expression<SqlBool>[]): Expression<SqlBool>;
671
- or(...args: Expression<SqlBool>[]): Expression<SqlBool>;
672
- not(...args: Expression<SqlBool>[]): ExpressionWrapper<any, any, SqlBool>;
673
- fieldRef(model: string, field: string, modelAlias?: string, inlineComputedField?: boolean): any;
674
- protected canJoinWithoutNestedSelect(modelDef: ModelDef, payload: boolean | FindArgs<Schema, GetModels<Schema>, true>): boolean;
675
- abstract get provider(): DataSourceProviderType;
676
- /**
677
- * Builds selection for a relation field.
678
- */
679
- abstract buildRelationSelection(query: SelectQueryBuilder<any, any, any>, model: string, relationField: string, parentAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>): SelectQueryBuilder<any, any, any>;
680
- /**
681
- * Builds skip and take clauses.
682
- */
683
- abstract buildSkipTake(query: SelectQueryBuilder<any, any, any>, skip: number | undefined, take: number | undefined): SelectQueryBuilder<any, any, any>;
684
- /**
685
- * Builds an Kysely expression that returns a JSON object for the given key-value pairs.
686
- */
687
- abstract buildJsonObject(value: Record<string, Expression<unknown>>): ExpressionWrapper<any, any, unknown>;
688
- /**
689
- * Builds an Kysely expression that returns the length of an array.
690
- */
691
- abstract buildArrayLength(array: Expression<unknown>): ExpressionWrapper<any, any, number>;
692
- /**
693
- * Builds an array literal SQL string for the given values.
694
- */
695
- abstract buildArrayLiteralSQL(values: unknown[]): string;
696
- /**
697
- * Whether the dialect supports updating with a limit on the number of updated rows.
698
- */
699
- abstract get supportsUpdateWithLimit(): boolean;
700
- /**
701
- * Whether the dialect supports deleting with a limit on the number of deleted rows.
702
- */
703
- abstract get supportsDeleteWithLimit(): boolean;
704
- /**
705
- * Whether the dialect supports DISTINCT ON.
706
- */
707
- abstract get supportsDistinctOn(): boolean;
708
- /**
709
- * Whether the dialect support inserting with `DEFAULT` as field value.
710
- */
711
- abstract get supportInsertWithDefault(): boolean;
712
- /**
713
- * Gets the SQL column type for the given field definition.
714
- */
715
- abstract getFieldSqlType(fieldDef: FieldDef): string;
716
- abstract getStringCasingBehavior(): {
717
- supportsILike: boolean;
718
- likeCaseSensitive: boolean;
719
- };
720
- }
721
-
722
- type CoreCrudOperation = 'findMany' | 'findUnique' | 'findFirst' | 'create' | 'createMany' | 'createManyAndReturn' | 'update' | 'updateMany' | 'updateManyAndReturn' | 'upsert' | 'delete' | 'deleteMany' | 'count' | 'aggregate' | 'groupBy';
723
- type AllCrudOperation = CoreCrudOperation | 'findUniqueOrThrow' | 'findFirstOrThrow';
724
-
725
- /**
726
- * ZenStack runtime plugin.
727
- */
728
- interface RuntimePlugin<Schema extends SchemaDef = SchemaDef> {
729
- /**
730
- * Plugin ID.
731
- */
732
- id: string;
733
- /**
734
- * Plugin display name.
735
- */
736
- name?: string;
737
- /**
738
- * Plugin description.
739
- */
740
- description?: string;
741
- /**
742
- * Custom function implementations.
743
- */
744
- functions?: Record<string, ZModelFunction<Schema>>;
745
- /**
746
- * Intercepts an ORM query.
747
- */
748
- onQuery?: OnQueryCallback<Schema>;
749
- /**
750
- * Intercepts an entity mutation.
751
- */
752
- onEntityMutation?: EntityMutationHooksDef<Schema>;
753
- /**
754
- * Intercepts a Kysely query.
755
- */
756
- onKyselyQuery?: OnKyselyQueryCallback<Schema>;
757
- }
758
- /**
759
- * Defines a ZenStack runtime plugin.
760
- */
761
- declare function definePlugin<Schema extends SchemaDef>(plugin: RuntimePlugin<Schema>): RuntimePlugin<Schema>;
762
-
763
- type OnQueryCallback<Schema extends SchemaDef> = (ctx: OnQueryHookContext<Schema>) => Promise<unknown>;
764
- type OnQueryHookContext<Schema extends SchemaDef> = {
765
- /**
766
- * The model that is being queried.
767
- */
768
- model: GetModels<Schema>;
769
- /**
770
- * The operation that is being performed.
771
- */
772
- operation: AllCrudOperation;
773
- /**
774
- * The query arguments.
775
- */
776
- args: unknown;
777
- /**
778
- * The function to proceed with the original query.
779
- * It takes the same arguments as the operation method.
780
- *
781
- * @param args The query arguments.
782
- */
783
- proceed: (args: unknown) => Promise<unknown>;
784
- /**
785
- * The ZenStack client that is performing the operation.
786
- */
787
- client: ClientContract<Schema>;
788
- };
789
- type EntityMutationHooksDef<Schema extends SchemaDef> = {
790
- /**
791
- * Called before entities are mutated.
792
- */
793
- beforeEntityMutation?: BeforeEntityMutationCallback<Schema>;
794
- /**
795
- * Called after entities are mutated.
796
- */
797
- afterEntityMutation?: AfterEntityMutationCallback<Schema>;
798
- /**
799
- * Whether to run after-mutation hooks within the transaction that performs the mutation.
800
- *
801
- * If set to `true`, if the mutation already runs inside a transaction, the callbacks are
802
- * executed immediately after the mutation within the transaction boundary. If the mutation
803
- * is not running inside a transaction, a new transaction is created to run both the mutation
804
- * and the callbacks.
805
- *
806
- * If set to `false`, the callbacks are executed after the mutation transaction is committed.
807
- *
808
- * Defaults to `false`.
809
- */
810
- runAfterMutationWithinTransaction?: boolean;
811
- };
812
- type MutationHooksArgs<Schema extends SchemaDef> = {
813
- /**
814
- * The model that is being mutated.
815
- */
816
- model: GetModels<Schema>;
817
- /**
818
- * The mutation action that is being performed.
819
- */
820
- action: 'create' | 'update' | 'delete';
821
- /**
822
- * The mutation data. Only available for create and update actions.
823
- */
824
- queryNode: OperationNode;
825
- /**
826
- * A query ID that uniquely identifies the mutation operation. You can use it to correlate
827
- * data between the before and after mutation hooks.
828
- */
829
- queryId: QueryId;
838
+ disconnect?: DisconnectInput<Schema, Model, Field>;
839
+ delete?: NestedDeleteInput<Schema, Model, Field>;
840
+ } : {}), FieldIsDelegateRelation<Schema, Model, Field> extends true ? 'create' | 'connectOrCreate' | 'upsert' : never>;
841
+ type DeleteArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
842
+ where: WhereUniqueInput<Schema, Model>;
843
+ } & SelectIncludeOmit<Schema, Model, true>;
844
+ type DeleteManyArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
845
+ where?: WhereInput<Schema, Model>;
846
+ limit?: number;
830
847
  };
831
- type BeforeEntityMutationCallback<Schema extends SchemaDef> = (args: PluginBeforeEntityMutationArgs<Schema>) => MaybePromise<void>;
832
- type AfterEntityMutationCallback<Schema extends SchemaDef> = (args: PluginAfterEntityMutationArgs<Schema>) => MaybePromise<void>;
833
- type PluginBeforeEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
834
- /**
835
- * Loads the entities that are about to be mutated. The db operation that loads the entities is executed
836
- * within the same transaction context as the mutation.
837
- */
838
- loadBeforeMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
839
- /**
840
- * The ZenStack client you can use to perform additional operations. The database operations initiated
841
- * from this client are executed within the same transaction as the mutation if the mutation is running
842
- * inside a transaction.
843
- *
844
- * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
845
- */
846
- client: ClientContract<Schema>;
848
+ type CountArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<FindArgs<Schema, Model, true>, 'select' | 'include' | 'distinct' | 'omit'> & {
849
+ select?: CountAggregateInput<Schema, Model> | true;
847
850
  };
848
- type PluginAfterEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
849
- /**
850
- * Loads the entities that have been mutated.
851
- */
852
- loadAfterMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
853
- /**
854
- * The ZenStack client you can use to perform additional operations.
855
- * See {@link EntityMutationHooksDef.runAfterMutationWithinTransaction} for detailed transaction behavior.
856
- *
857
- * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
858
- */
859
- client: ClientContract<Schema>;
851
+ type CountAggregateInput<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
852
+ [Key in NonRelationFields<Schema, Model>]?: true;
853
+ } & {
854
+ _all?: true;
860
855
  };
861
- type OnKyselyQueryArgs<Schema extends SchemaDef> = {
862
- schema: SchemaDef;
863
- client: ClientContract<Schema>;
864
- query: RootOperationNode;
865
- proceed: ProceedKyselyQueryFunction;
856
+ type CountResult<Schema extends SchemaDef, _Model extends GetModels<Schema>, Args> = Args extends {
857
+ select: infer S;
858
+ } ? S extends true ? number : {
859
+ [Key in keyof S]: number;
860
+ } : number;
861
+ type AggregateArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
862
+ where?: WhereInput<Schema, Model>;
863
+ skip?: number;
864
+ take?: number;
865
+ orderBy?: OrArray<OrderBy<Schema, Model, true, false>>;
866
+ } & {
867
+ _count?: true | CountAggregateInput<Schema, Model>;
868
+ _min?: MinMaxInput<Schema, Model, true>;
869
+ _max?: MinMaxInput<Schema, Model, true>;
870
+ } & (NumericFields<Schema, Model> extends never ? {} : {
871
+ _avg?: SumAvgInput<Schema, Model, true>;
872
+ _sum?: SumAvgInput<Schema, Model, true>;
873
+ });
874
+ type NumericFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
875
+ [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>;
866
876
  };
867
- type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise<QueryResult<any>>;
868
- type OnKyselyQueryCallback<Schema extends SchemaDef> = (args: OnKyselyQueryArgs<Schema>) => Promise<QueryResult<UnknownRow>>;
869
-
870
- type ZModelFunctionContext<Schema extends SchemaDef> = {
871
- /**
872
- * ZenStack client instance
873
- */
874
- client: ClientContract<Schema>;
875
- /**
876
- * Database dialect
877
- */
878
- dialect: BaseCrudDialect<Schema>;
879
- /**
880
- * The containing model name
881
- */
882
- model: GetModels<Schema>;
883
- /**
884
- * The alias name that can be used to refer to the containing model
885
- */
886
- modelAlias: string;
887
- /**
888
- * The CRUD operation being performed
889
- */
890
- operation: CRUD_EXT;
877
+ type SumAvgInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
878
+ [Key in NumericFields<Schema, Model>]?: ValueType;
891
879
  };
892
- type ZModelFunction<Schema extends SchemaDef> = (eb: ExpressionBuilder<ToKyselySchema<Schema>, keyof ToKyselySchema<Schema>>, args: Expression<any>[], context: ZModelFunctionContext<Schema>) => Expression<unknown>;
893
- /**
894
- * ZenStack client options.
895
- */
896
- type ClientOptions<Schema extends SchemaDef> = {
897
- /**
898
- * Kysely dialect.
899
- */
900
- dialect: Dialect;
901
- /**
902
- * Custom function definitions.
903
- */
904
- functions?: Record<string, ZModelFunction<Schema>>;
905
- /**
906
- * Plugins.
907
- */
908
- plugins?: RuntimePlugin<Schema>[];
909
- /**
910
- * Logging configuration.
911
- */
912
- log?: KyselyConfig['log'];
913
- /**
914
- * Whether to automatically fix timezone for `DateTime` fields returned by node-pg. Defaults
915
- * to `true`.
916
- *
917
- * Node-pg has a terrible quirk that it interprets the date value as local timezone (as a
918
- * `Date` object) although for `DateTime` field the data in DB is stored in UTC.
919
- * @see https://github.com/brianc/node-postgres/issues/429
920
- */
921
- fixPostgresTimezone?: boolean;
922
- /**
923
- * Whether to enable input validations expressed with attributes like `@email`, `@regex`,
924
- * `@@validate`, etc. Defaults to `true`.
925
- */
926
- validateInput?: boolean;
927
- } & (HasComputedFields<Schema> extends true ? {
928
- /**
929
- * Computed field definitions.
930
- */
931
- computedFields: ComputedFieldsOptions<Schema>;
932
- } : {}) & (HasProcedures<Schema> extends true ? {
933
- /**
934
- * Custom procedure definitions.
935
- */
936
- procedures: ProceduresOptions<Schema>;
937
- } : {});
938
- type ComputedFieldsOptions<Schema extends SchemaDef> = {
939
- [Model in GetModels<Schema> as 'computedFields' extends keyof GetModel<Schema, Model> ? Model : never]: {
940
- [Field in keyof Schema['models'][Model]['computedFields']]: PrependParameter<ExpressionBuilder<ToKyselySchema<Schema>, Model>, Schema['models'][Model]['computedFields'][Field]>;
941
- };
880
+ type MinMaxInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ValueType> = {
881
+ [Key in GetModelFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? never : FieldIsRelation<Schema, Model, Key> extends true ? never : Key]?: ValueType;
942
882
  };
943
- type HasComputedFields<Schema extends SchemaDef> = string extends GetModels<Schema> ? false : keyof ComputedFieldsOptions<Schema> extends never ? false : true;
944
- type ProceduresOptions<Schema extends SchemaDef> = Schema extends {
945
- procedures: Record<string, ProcedureDef>;
883
+ type AggregateResult<Schema extends SchemaDef, _Model extends GetModels<Schema>, Args> = (Args extends {
884
+ _count: infer Count;
946
885
  } ? {
947
- [Key in keyof Schema['procedures']]: PrependParameter<ClientContract<Schema>, ProcedureFunc<Schema, Schema['procedures'][Key]>>;
948
- } : {};
949
- type HasProcedures<Schema extends SchemaDef> = Schema extends {
950
- procedures: Record<string, ProcedureDef>;
951
- } ? true : false;
886
+ _count: AggCommonOutput<Count>;
887
+ } : {}) & (Args extends {
888
+ _sum: infer Sum;
889
+ } ? {
890
+ _sum: AggCommonOutput<Sum>;
891
+ } : {}) & (Args extends {
892
+ _avg: infer Avg;
893
+ } ? {
894
+ _avg: AggCommonOutput<Avg>;
895
+ } : {}) & (Args extends {
896
+ _min: infer Min;
897
+ } ? {
898
+ _min: AggCommonOutput<Min>;
899
+ } : {}) & (Args extends {
900
+ _max: infer Max;
901
+ } ? {
902
+ _max: AggCommonOutput<Max>;
903
+ } : {});
904
+ type AggCommonOutput<Input> = Input extends true ? number : Input extends {} ? {
905
+ [Key in keyof Input]: number;
906
+ } : never;
907
+ type GroupByHaving<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<WhereInput<Schema, Model, true, true>, '$expr'>;
908
+ type GroupByArgs<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
909
+ where?: WhereInput<Schema, Model>;
910
+ orderBy?: OrArray<OrderBy<Schema, Model, false, true>>;
911
+ by: NonRelationFields<Schema, Model> | NonEmptyArray<NonRelationFields<Schema, Model>>;
912
+ having?: GroupByHaving<Schema, Model>;
913
+ take?: number;
914
+ skip?: number;
915
+ _count?: true | CountAggregateInput<Schema, Model>;
916
+ _min?: MinMaxInput<Schema, Model, true>;
917
+ _max?: MinMaxInput<Schema, Model, true>;
918
+ } & (NumericFields<Schema, Model> extends never ? {} : {
919
+ _avg?: SumAvgInput<Schema, Model, true>;
920
+ _sum?: SumAvgInput<Schema, Model, true>;
921
+ });
922
+ type GroupByResult<Schema extends SchemaDef, Model extends GetModels<Schema>, Args extends {
923
+ by: unknown;
924
+ }> = Array<{
925
+ [Key in NonRelationFields<Schema, Model> as Key extends ValueOfPotentialTuple<Args['by']> ? Key : never]: MapModelFieldType<Schema, Model, Key>;
926
+ } & (Args extends {
927
+ _count: infer Count;
928
+ } ? {
929
+ _count: AggCommonOutput<Count>;
930
+ } : {}) & (Args extends {
931
+ _avg: infer Avg;
932
+ } ? {
933
+ _avg: AggCommonOutput<Avg>;
934
+ } : {}) & (Args extends {
935
+ _sum: infer Sum;
936
+ } ? {
937
+ _sum: AggCommonOutput<Sum>;
938
+ } : {}) & (Args extends {
939
+ _min: infer Min;
940
+ } ? {
941
+ _min: AggCommonOutput<Min>;
942
+ } : {}) & (Args extends {
943
+ _max: infer Max;
944
+ } ? {
945
+ _max: AggCommonOutput<Max>;
946
+ } : {})>;
947
+ type ConnectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>> : WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
948
+ type ConnectOrCreateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<ConnectOrCreatePayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>> : ConnectOrCreatePayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
949
+ type DisconnectInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>, true> : boolean | WhereInput<Schema, RelationFieldType<Schema, Model, Field>>;
950
+ type SetRelationInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>>;
951
+ type NestedUpdateInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<{
952
+ where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
953
+ data: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
954
+ }, true> : XOR<{
955
+ where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
956
+ data: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
957
+ }, UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>>;
958
+ type NestedUpsertInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<{
959
+ where: WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>;
960
+ create: CreateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
961
+ update: UpdateInput<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>;
962
+ }, FieldIsArray<Schema, Model, Field>>;
963
+ type NestedUpdateManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<UpdateManyPayload<Schema, RelationFieldType<Schema, Model, Field>, OppositeRelationAndFK<Schema, Model, Field>>>;
964
+ type NestedDeleteInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = FieldIsArray<Schema, Model, Field> extends true ? OrArray<WhereUniqueInput<Schema, RelationFieldType<Schema, Model, Field>>, true> : boolean | WhereInput<Schema, RelationFieldType<Schema, Model, Field>>;
965
+ type NestedDeleteManyInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends RelationFields<Schema, Model>> = OrArray<WhereInput<Schema, RelationFieldType<Schema, Model, Field>, true>>;
966
+ type NonOwnedRelationFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
967
+ [Key in RelationFields<Schema, Model> as GetModelField<Schema, Model, Key>['relation'] extends {
968
+ references: unknown[];
969
+ } ? never : Key]: true;
970
+ };
971
+ type HasToManyRelations<Schema extends SchemaDef, Model extends GetModels<Schema>> = keyof {
972
+ [Key in RelationFields<Schema, Model> as FieldIsArray<Schema, Model, Key> extends true ? Key : never]: true;
973
+ } extends never ? false : true;
974
+ type ProviderSupportsDistinct<Schema extends SchemaDef> = Schema['provider']['type'] extends 'postgresql' ? true : false;
952
975
 
953
976
  /**
954
977
  * A promise that only executes when it's awaited or .then() is called.
@@ -975,12 +998,15 @@ declare enum TransactionIsolationLevel {
975
998
  /**
976
999
  * ZenStack client interface.
977
1000
  */
978
- type ClientContract<Schema extends SchemaDef> = {
1001
+ type ClientContract<Schema extends SchemaDef, Options extends ClientOptions<Schema> = ClientOptions<Schema>> = {
1002
+ /**
1003
+ * The schema definition.
1004
+ */
979
1005
  readonly $schema: Schema;
980
1006
  /**
981
1007
  * The client options.
982
1008
  */
983
- readonly $options: ClientOptions<Schema>;
1009
+ readonly $options: Options;
984
1010
  /**
985
1011
  * Executes a prepared raw query and returns the number of affected rows.
986
1012
  * @example
@@ -1022,12 +1048,22 @@ type ClientContract<Schema extends SchemaDef> = {
1022
1048
  /**
1023
1049
  * Sets the current user identity.
1024
1050
  */
1025
- $setAuth(auth: AuthType<Schema> | undefined): ClientContract<Schema>;
1051
+ $setAuth(auth: AuthType<Schema> | undefined): ClientContract<Schema, Options>;
1052
+ /**
1053
+ * Returns a new client with new options applied.
1054
+ * @example
1055
+ * ```
1056
+ * const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false });
1057
+ * ```
1058
+ */
1059
+ $setOptions<Options extends ClientOptions<Schema>>(options: Options): ClientContract<Schema, Options>;
1026
1060
  /**
1027
1061
  * Returns a new client enabling/disabling input validations expressed with attributes like
1028
1062
  * `@email`, `@regex`, `@@validate`, etc.
1063
+ *
1064
+ * @deprecated Use `$setOptions` instead.
1029
1065
  */
1030
- $setInputValidation(enable: boolean): ClientContract<Schema>;
1066
+ $setInputValidation(enable: boolean): ClientContract<Schema, Options>;
1031
1067
  /**
1032
1068
  * The Kysely query builder instance.
1033
1069
  */
@@ -1039,7 +1075,7 @@ type ClientContract<Schema extends SchemaDef> = {
1039
1075
  /**
1040
1076
  * Starts an interactive transaction.
1041
1077
  */
1042
- $transaction<T>(callback: (tx: Omit<ClientContract<Schema>, TransactionUnsupportedMethods>) => Promise<T>, options?: {
1078
+ $transaction<T>(callback: (tx: Omit<ClientContract<Schema, Options>, TransactionUnsupportedMethods>) => Promise<T>, options?: {
1043
1079
  isolationLevel?: TransactionIsolationLevel;
1044
1080
  }): Promise<T>;
1045
1081
  /**
@@ -1051,15 +1087,15 @@ type ClientContract<Schema extends SchemaDef> = {
1051
1087
  /**
1052
1088
  * Returns a new client with the specified plugin installed.
1053
1089
  */
1054
- $use(plugin: RuntimePlugin<Schema>): ClientContract<Schema>;
1090
+ $use(plugin: RuntimePlugin<Schema>): ClientContract<Schema, Options>;
1055
1091
  /**
1056
1092
  * Returns a new client with the specified plugin removed.
1057
1093
  */
1058
- $unuse(pluginId: string): ClientContract<Schema>;
1094
+ $unuse(pluginId: string): ClientContract<Schema, Options>;
1059
1095
  /**
1060
1096
  * Returns a new client with all plugins removed.
1061
1097
  */
1062
- $unuseAll(): ClientContract<Schema>;
1098
+ $unuseAll(): ClientContract<Schema, Options>;
1063
1099
  /**
1064
1100
  * Eagerly connects to the database.
1065
1101
  */
@@ -1074,12 +1110,12 @@ type ClientContract<Schema extends SchemaDef> = {
1074
1110
  */
1075
1111
  $pushSchema(): Promise<void>;
1076
1112
  } & {
1077
- [Key in GetModels<Schema> as Uncapitalize<Key>]: ModelOperations<Schema, Key>;
1113
+ [Key in GetModels<Schema> as Uncapitalize<Key>]: ModelOperations<Schema, Key, Options>;
1078
1114
  } & Procedures<Schema>;
1079
1115
  /**
1080
1116
  * The contract for a client in a transaction.
1081
1117
  */
1082
- type TransactionClientContract<Schema extends SchemaDef> = Omit<ClientContract<Schema>, TransactionUnsupportedMethods>;
1118
+ type TransactionClientContract<Schema extends SchemaDef, Options extends ClientOptions<Schema>> = Omit<ClientContract<Schema, Options>, TransactionUnsupportedMethods>;
1083
1119
  type _TypeMap = {
1084
1120
  String: string;
1085
1121
  Int: number;
@@ -1107,7 +1143,7 @@ type MapProcedureParams<Schema extends SchemaDef, Params> = {
1107
1143
  * Creates a new ZenStack client instance.
1108
1144
  */
1109
1145
  interface ClientConstructor {
1110
- new <Schema extends SchemaDef>(schema: Schema, options: ClientOptions<Schema>): ClientContract<Schema>;
1146
+ new <Schema extends SchemaDef, Options extends ClientOptions<Schema>>(schema: Schema, options: Options): ClientContract<Schema, Options>;
1111
1147
  }
1112
1148
  /**
1113
1149
  * CRUD operations.
@@ -1125,7 +1161,7 @@ type CRUD_EXT = CRUD | 'post-update';
1125
1161
  * Extended CRUD operations including 'post-update'.
1126
1162
  */
1127
1163
  declare const CRUD_EXT: readonly ["create", "read", "update", "delete", "post-update"];
1128
- type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
1164
+ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema>> = {
1129
1165
  /**
1130
1166
  * Returns a list of entities.
1131
1167
  * @param args - query args
@@ -1207,35 +1243,35 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1207
1243
  * }); // result: `{ _count: { posts: number } }`
1208
1244
  * ```
1209
1245
  */
1210
- findMany<T extends FindManyArgs<Schema, Model>>(args?: SelectSubset<T, FindManyArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>[]>;
1246
+ findMany<T extends FindManyArgs<Schema, Model>>(args?: SelectSubset<T, FindManyArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>[]>;
1211
1247
  /**
1212
1248
  * Returns a uniquely identified entity.
1213
1249
  * @param args - query args
1214
1250
  * @returns a single entity or null if not found
1215
1251
  * @see {@link findMany}
1216
1252
  */
1217
- findUnique<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T> | null>;
1253
+ findUnique<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T> | null>;
1218
1254
  /**
1219
1255
  * Returns a uniquely identified entity or throws `NotFoundError` if not found.
1220
1256
  * @param args - query args
1221
1257
  * @returns a single entity
1222
1258
  * @see {@link findMany}
1223
1259
  */
1224
- findUniqueOrThrow<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>>;
1260
+ findUniqueOrThrow<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>>;
1225
1261
  /**
1226
1262
  * Returns the first entity.
1227
1263
  * @param args - query args
1228
1264
  * @returns a single entity or null if not found
1229
1265
  * @see {@link findMany}
1230
1266
  */
1231
- findFirst<T extends FindFirstArgs<Schema, Model>>(args?: SelectSubset<T, FindFirstArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T> | null>;
1267
+ findFirst<T extends FindFirstArgs<Schema, Model>>(args?: SelectSubset<T, FindFirstArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T> | null>;
1232
1268
  /**
1233
1269
  * Returns the first entity or throws `NotFoundError` if not found.
1234
1270
  * @param args - query args
1235
1271
  * @returns a single entity
1236
1272
  * @see {@link findMany}
1237
1273
  */
1238
- findFirstOrThrow<T extends FindFirstArgs<Schema, Model>>(args?: SelectSubset<T, FindFirstArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>>;
1274
+ findFirstOrThrow<T extends FindFirstArgs<Schema, Model>>(args?: SelectSubset<T, FindFirstArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>>;
1239
1275
  /**
1240
1276
  * Creates a new entity.
1241
1277
  * @param args - create args
@@ -1288,7 +1324,7 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1288
1324
  * });
1289
1325
  * ```
1290
1326
  */
1291
- create<T extends CreateArgs<Schema, Model>>(args: SelectSubset<T, CreateArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>>;
1327
+ create<T extends CreateArgs<Schema, Model>>(args: SelectSubset<T, CreateArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>>;
1292
1328
  /**
1293
1329
  * Creates multiple entities. Only scalar fields are allowed.
1294
1330
  * @param args - create args
@@ -1333,7 +1369,7 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1333
1369
  * });
1334
1370
  * ```
1335
1371
  */
1336
- createManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>[]>;
1372
+ createManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>[]>;
1337
1373
  /**
1338
1374
  * Updates a uniquely identified entity.
1339
1375
  * @param args - update args. See {@link findMany} for how to control
@@ -1451,7 +1487,7 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1451
1487
  * });
1452
1488
  * ```
1453
1489
  */
1454
- update<T extends UpdateArgs<Schema, Model>>(args: SelectSubset<T, UpdateArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>>;
1490
+ update<T extends UpdateArgs<Schema, Model>>(args: SelectSubset<T, UpdateArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>>;
1455
1491
  /**
1456
1492
  * Updates multiple entities.
1457
1493
  * @param args - update args. Only scalar fields are allowed for data.
@@ -1495,7 +1531,7 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1495
1531
  * });
1496
1532
  * ```
1497
1533
  */
1498
- updateManyAndReturn<T extends UpdateManyAndReturnArgs<Schema, Model>>(args: Subset<T, UpdateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>[]>;
1534
+ updateManyAndReturn<T extends UpdateManyAndReturnArgs<Schema, Model>>(args: Subset<T, UpdateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>[]>;
1499
1535
  /**
1500
1536
  * Creates or updates an entity.
1501
1537
  * @param args - upsert args
@@ -1516,7 +1552,7 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1516
1552
  * });
1517
1553
  * ```
1518
1554
  */
1519
- upsert<T extends UpsertArgs<Schema, Model>>(args: SelectSubset<T, UpsertArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>>;
1555
+ upsert<T extends UpsertArgs<Schema, Model>>(args: SelectSubset<T, UpsertArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>>;
1520
1556
  /**
1521
1557
  * Deletes a uniquely identifiable entity.
1522
1558
  * @param args - delete args
@@ -1536,7 +1572,7 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1536
1572
  * }); // result: `{ id: string; email: string }`
1537
1573
  * ```
1538
1574
  */
1539
- delete<T extends DeleteArgs<Schema, Model>>(args: SelectSubset<T, DeleteArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, T>>;
1575
+ delete<T extends DeleteArgs<Schema, Model>>(args: SelectSubset<T, DeleteArgs<Schema, Model>>): ZenStackPromise<Schema, SimplifiedModelResult<Schema, Model, Options, T>>;
1540
1576
  /**
1541
1577
  * Deletes multiple entities.
1542
1578
  * @param args - delete args
@@ -1630,15 +1666,15 @@ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema
1630
1666
  groupBy<T extends GroupByArgs<Schema, Model>>(args: Subset<T, GroupByArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<GroupByResult<Schema, Model, T>>>;
1631
1667
  };
1632
1668
  type OperationsIneligibleForDelegateModels = 'create' | 'createMany' | 'createManyAndReturn' | 'upsert';
1633
- type ModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<AllModelOperations<Schema, Model>, IsDelegateModel<Schema, Model> extends true ? OperationsIneligibleForDelegateModels : never>;
1669
+ type ModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>, Options extends ClientOptions<Schema> = ClientOptions<Schema>> = Omit<AllModelOperations<Schema, Model, Options>, IsDelegateModel<Schema, Model> extends true ? OperationsIneligibleForDelegateModels : never>;
1634
1670
  /**
1635
1671
  * Type for auth context that includes both scalar and relation fields.
1636
1672
  * Relations are recursively included to allow nested auth data like { user: { profile: { ... } } }
1637
1673
  */
1638
- type AuthModelType<Schema extends SchemaDef, Model extends GetModels<Schema>> = Partial<DefaultModelResult<Schema, Model>> & {
1674
+ type AuthModelType<Schema extends SchemaDef, Model extends GetModels<Schema>> = Partial<DefaultModelResult<Schema, Model, ClientOptions<Schema>>> & {
1639
1675
  [Key in RelationFields<Schema, Model>]?: FieldIsArray<Schema, Model, Key> extends true ? AuthModelType<Schema, RelationFieldType<Schema, Model, Key>>[] : AuthModelType<Schema, RelationFieldType<Schema, Model, Key>>;
1640
1676
  };
1641
- type AuthType<Schema extends SchemaDef> = string extends GetModels<Schema> ? Record<string, unknown> : Schema['authType'] extends GetModels<Schema> ? AuthModelType<Schema, Schema['authType']> : never;
1677
+ 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>;
1642
1678
 
1643
1679
  /**
1644
1680
  * ZenStack ORM client.
@@ -1760,7 +1796,7 @@ declare function fieldHasDefaultValue(fieldDef: FieldDef): boolean | undefined;
1760
1796
  declare function isEnum(schema: SchemaDef, type: string): boolean;
1761
1797
  declare function getEnum(schema: SchemaDef, type: string): _zenstackhq_schema.EnumDef | undefined;
1762
1798
  declare function buildJoinPairs(schema: SchemaDef, model: string, modelAlias: string, relationField: string, relationModelAlias: string): [string, string][];
1763
- declare function makeDefaultOrderBy<Schema extends SchemaDef>(schema: SchemaDef, model: string): OrderBy<Schema, Extract<keyof Schema["models"], string>, true, false>[];
1799
+ declare function makeDefaultOrderBy<Schema extends SchemaDef>(schema: SchemaDef, model: string): OrderBy<Schema, GetModels<Schema>, true, false>[];
1764
1800
  declare function getManyToManyRelation(schema: SchemaDef, model: string, field: string): {
1765
1801
  parentFkName: string;
1766
1802
  parentPKName: string;
@@ -1834,23 +1870,38 @@ declare namespace queryUtils {
1834
1870
  export { 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_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_makeDefaultOrderBy as makeDefaultOrderBy, queryUtils_requireField as requireField, queryUtils_requireIdFields as requireIdFields, queryUtils_requireModel as requireModel, queryUtils_stripAlias as stripAlias };
1835
1871
  }
1836
1872
 
1873
+ type VisitResult = void | {
1874
+ abort: true;
1875
+ };
1837
1876
  declare class ExpressionVisitor {
1838
- visit(expr: Expression$1): void;
1839
- protected visitLiteral(_e: LiteralExpression): void;
1840
- protected visitArray(e: ArrayExpression): void;
1841
- protected visitField(_e: FieldExpression): void;
1842
- protected visitMember(e: MemberExpression): void;
1843
- protected visitBinary(e: BinaryExpression): void;
1844
- protected visitUnary(e: UnaryExpression): void;
1845
- protected visitCall(e: CallExpression): void;
1846
- protected visitThis(_e: ThisExpression): void;
1847
- protected visitNull(_e: NullExpression): void;
1877
+ visit(expr: Expression$1): VisitResult;
1878
+ protected visitLiteral(_e: LiteralExpression): VisitResult;
1879
+ protected visitArray(e: ArrayExpression): VisitResult;
1880
+ protected visitField(_e: FieldExpression): VisitResult;
1881
+ protected visitMember(e: MemberExpression): VisitResult;
1882
+ protected visitBinary(e: BinaryExpression): VisitResult;
1883
+ protected visitUnary(e: UnaryExpression): VisitResult;
1884
+ protected visitCall(e: CallExpression): VisitResult;
1885
+ protected visitThis(_e: ThisExpression): VisitResult;
1886
+ protected visitNull(_e: NullExpression): VisitResult;
1887
+ }
1888
+ declare class MatchingExpressionVisitor extends ExpressionVisitor {
1889
+ private predicate;
1890
+ private found;
1891
+ constructor(predicate: (expr: Expression$1) => boolean);
1892
+ find(expr: Expression$1): boolean;
1893
+ visit(expr: Expression$1): void | {
1894
+ readonly abort: true;
1895
+ };
1848
1896
  }
1849
1897
 
1850
1898
  type schemaUtils_ExpressionVisitor = ExpressionVisitor;
1851
1899
  declare const schemaUtils_ExpressionVisitor: typeof ExpressionVisitor;
1900
+ type schemaUtils_MatchingExpressionVisitor = MatchingExpressionVisitor;
1901
+ declare const schemaUtils_MatchingExpressionVisitor: typeof MatchingExpressionVisitor;
1902
+ type schemaUtils_VisitResult = VisitResult;
1852
1903
  declare namespace schemaUtils {
1853
- export { schemaUtils_ExpressionVisitor as ExpressionVisitor };
1904
+ export { schemaUtils_ExpressionVisitor as ExpressionVisitor, schemaUtils_MatchingExpressionVisitor as MatchingExpressionVisitor, type schemaUtils_VisitResult as VisitResult };
1854
1905
  }
1855
1906
 
1856
- export { type AfterEntityMutationCallback, type AggregateArgs, type AggregateResult, type AllModelOperations, type AuthType, BaseCrudDialect, type BatchResult, type BeforeEntityMutationCallback, type BooleanFilter, type BytesFilter, CRUD, CRUD_EXT, type ClientConstructor, type ClientContract, type ClientOptions, type ComputedFieldsOptions, type CountArgs, type CountResult, type CreateArgs, type CreateInput, type CreateManyAndReturnArgs, type CreateManyArgs, type CreateManyInput, type CoreCrudOperation as CrudOperation, type DateTimeFilter, type DefaultModelResult, type DeleteArgs, type DeleteManyArgs, type EntityMutationHooksDef, type FindArgs, type FindFirstArgs, type FindManyArgs, type FindUniqueArgs, type GroupByArgs, type GroupByResult, type HasComputedFields, type HasProcedures, type IncludeInput, type JsonArray, type JsonObject, type JsonValue, kyselyUtils as KyselyUtils, type ModelOperations, type ModelResult, type NullsOrder, type NumberFilter, ORMError, ORMErrorReason, type OmitInput, type OnKyselyQueryArgs, type OnKyselyQueryCallback, type OperationsIneligibleForDelegateModels, type OrderBy, type PluginAfterEntityMutationArgs, type PluginBeforeEntityMutationArgs, type ProcedureFunc, type Procedures, type ProceduresOptions, type ProceedKyselyQueryFunction, queryUtils as QueryUtils, RejectedByPolicyReason, type RuntimePlugin, schemaUtils as SchemaUtils, type SelectIncludeOmit, type SelectInput, type SelectSubset, type SimplifiedModelResult, type SortOrder, type StringFilter, type Subset, type ToKysely, type TransactionClientContract, TransactionIsolationLevel, type TypeDefResult, type UpdateArgs, type UpdateInput, type UpdateManyAndReturnArgs, type UpdateManyArgs, type UpsertArgs, type WhereInput, type WhereUniqueInput, type ZModelFunction, type ZModelFunctionContext, ZenStackClient, type ZenStackPromise, definePlugin, getCrudDialect };
1907
+ export { type AfterEntityMutationCallback, type AggregateArgs, type AggregateResult, type AllModelOperations, type AuthType, BaseCrudDialect, type BatchResult, type BeforeEntityMutationCallback, type BooleanFilter, type BytesFilter, CRUD, CRUD_EXT, type ClientConstructor, type ClientContract, type ClientOptions, type ComputedFieldsOptions, type CountArgs, type CountResult, type CreateArgs, type CreateInput, type CreateManyAndReturnArgs, type CreateManyArgs, type CreateManyInput, type CoreCrudOperation as CrudOperation, type DateTimeFilter, type DefaultModelResult, type DeleteArgs, type DeleteManyArgs, type EntityMutationHooksDef, type FindArgs, type FindFirstArgs, type FindManyArgs, type FindUniqueArgs, type GroupByArgs, type GroupByResult, type HasComputedFields, type HasProcedures, type IncludeInput, type JsonArray, type JsonObject, type JsonValue, kyselyUtils as KyselyUtils, type ModelOperations, type ModelResult, type NullsOrder, type NumberFilter, ORMError, ORMErrorReason, type OmitInput, type OmitOptions, type OnKyselyQueryArgs, type OnKyselyQueryCallback, type OperationsIneligibleForDelegateModels, type OrderBy, type PluginAfterEntityMutationArgs, type PluginBeforeEntityMutationArgs, type ProcedureFunc, type Procedures, type ProceduresOptions, type ProceedKyselyQueryFunction, queryUtils as QueryUtils, RejectedByPolicyReason, type RuntimePlugin, schemaUtils as SchemaUtils, type SelectIncludeOmit, type SelectInput, type SelectSubset, type SimplifiedModelResult, type SortOrder, type StringFilter, type Subset, type ToKysely, type TransactionClientContract, TransactionIsolationLevel, type TypeDefResult, type UpdateArgs, type UpdateInput, type UpdateManyAndReturnArgs, type UpdateManyArgs, type UpsertArgs, type WhereInput, type WhereUniqueInput, type ZModelFunction, type ZModelFunctionContext, ZenStackClient, type ZenStackPromise, definePlugin, getCrudDialect };