-
-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathcontract.ts
More file actions
985 lines (927 loc) · 32.8 KB
/
Copy pathcontract.ts
File metadata and controls
985 lines (927 loc) · 32.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
import {
type FieldIsArray,
type GetModels,
type GetTypeDefs,
type ProcedureDef,
type RelationFields,
type RelationFieldType,
type SchemaDef,
} from '../schema';
import type { AnyKysely } from '../utils/kysely-utils';
import type { Simplify, UnwrapTuplePromises } from '../utils/type-utils';
import type { TRANSACTION_UNSUPPORTED_METHODS } from './constants';
import type {
AggregateArgs,
AggregateResult,
BatchResult,
CountArgs,
CountResult,
CreateArgs,
CreateManyAndReturnArgs,
CreateManyArgs,
DefaultModelResult,
DeleteArgs,
DeleteManyArgs,
ExistsArgs,
FindFirstArgs,
FindManyArgs,
FindUniqueArgs,
GroupByArgs,
GroupByResult,
OmitWhere,
ProcedureFunc,
SelectSubset,
SelectSubsetWithWhere,
SimplifiedPlainResult,
Subset,
SubsetWithWhere,
TypeDefResult,
UpdateArgs,
UpdateManyAndReturnArgs,
UpdateManyArgs,
UpsertArgs,
WhereInput,
WhereUniqueInput,
} from './crud-types';
import type { Diagnostics } from './diagnostics';
import type { ClientOptions, QueryOptions } from './options';
import type {
ExtClientMembersBase,
ExtQueryArgsBase,
ExtResultBase,
ExtResultInferenceArgs,
RuntimePlugin,
} from './plugin';
import type { ZenStackPromise } from './promise';
import type { ToKysely } from './query-builder';
import type { GetSlicedModels, GetSlicedOperations, GetSlicedProcedures, ModelAllowsCreate } from './type-utils';
import type { ZodSchemaFactory } from './zod/factory';
type TransactionUnsupportedMethods = (typeof TRANSACTION_UNSUPPORTED_METHODS)[number];
/**
* Transaction isolation levels.
*/
export enum TransactionIsolationLevel {
ReadUncommitted = 'read uncommitted',
ReadCommitted = 'read committed',
RepeatableRead = 'repeatable read',
Serializable = 'serializable',
Snapshot = 'snapshot',
}
/**
* ZenStack client interface.
*/
export type ClientContract<
Schema extends SchemaDef,
Options extends ClientOptions<Schema> = ClientOptions<Schema>,
ExtQueryArgs extends ExtQueryArgsBase = {},
ExtClientMembers extends ExtClientMembersBase = {},
ExtResult extends ExtResultBase<Schema> = {},
> = {
/**
* The schema definition.
*/
readonly $schema: Schema;
/**
* The client options.
*/
readonly $options: Options;
/**
* Executes a prepared raw query and returns the number of affected rows.
* @example
* ```
* const result = await db.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`
* ```
*/
$executeRaw(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, number>;
/**
* Executes a raw query and returns the number of affected rows.
* This method is susceptible to SQL injections.
* @example
* ```
* const result = await db.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com')
* ```
*/
$executeRawUnsafe(query: string, ...values: any[]): ZenStackPromise<Schema, number>;
/**
* Performs a prepared raw query and returns the `SELECT` data.
* @example
* ```
* const result = await db.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`
* ```
*/
$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, T>;
/**
* Performs a raw query and returns the `SELECT` data.
* This method is susceptible to SQL injections.
* @example
* ```
* const result = await db.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com')
* ```
*/
$queryRawUnsafe<T = unknown>(query: string, ...values: any[]): ZenStackPromise<Schema, T>;
/**
* The current user identity. If the client is not bound to any user context, returns `undefined`.
*/
get $auth(): AuthType<Schema> | undefined;
/**
* Returns a new client bound to the specified user identity. The original client remains unchanged.
* Pass `undefined` to return a client without any user context.
*
* @example
* ```
* const userClient = db.$setAuth({ id: 'user-id' });
* ```
*/
$setAuth(
auth: AuthType<Schema> | undefined,
): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
/**
* Returns a new client with new options applied. The original client remains unchanged.
*
* @example
* ```
* const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false });
* ```
*/
$setOptions<NewOptions extends ClientOptions<Schema>>(
options: NewOptions,
): ClientContract<Schema, NewOptions, ExtQueryArgs, ExtClientMembers, ExtResult>;
/**
* Returns a new client enabling/disabling query args validation. The original client remains unchanged.
*
* @deprecated Use {@link $setOptions} instead.
*/
$setInputValidation(enable: boolean): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
/**
* The Kysely query builder instance.
*
* @example
* ```
* db.$qb.selectFrom('User').selectAll().where('id', '=', 1).execute();
* ```
*/
readonly $qb: ToKysely<Schema>;
/**
* The raw Kysely query builder without any ZenStack enhancements.
*/
readonly $qbRaw: AnyKysely;
/**
* Starts an interactive transaction.
*
* @example
* ```
* await db.$transaction(async (tx) => {
* const user = await tx.user.update({ where: { id: 1 }, data: { name: 'Alice' } });
* const post = await tx.post.create({ data: { title: 'Hello World', authorId: user.id } });
* return { user, posts: [post] };
* ```
*/
$transaction<T>(
callback: (
tx: TransactionClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>,
) => Promise<T>,
options?: { isolationLevel?: TransactionIsolationLevel },
): Promise<T>;
/**
* Starts a sequential transaction that runs the provided operations in order.
*
* @example
* ```
* await db.$transaction([
* db.user.update({ where: { id: 1 }, data: { name: 'Alice' } }),
* db.post.create({ data: { title: 'Hello World', authorId: 1 } }),
* ]);
*/
$transaction<P extends ZenStackPromise<Schema, any>[]>(
arg: [...P],
options?: { isolationLevel?: TransactionIsolationLevel },
): Promise<UnwrapTuplePromises<P>>;
/**
* Returns a new client with the specified plugin installed. The original client remains unchanged.
*
* @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation}
*/
$use<
PluginSchema extends SchemaDef = Schema,
PluginExtQueryArgs extends ExtQueryArgsBase = {},
PluginExtClientMembers extends ExtClientMembersBase = {},
PluginExtResult extends ExtResultBase<PluginSchema> = {},
_R = {}, // auxiliary type for inferring precise typing for `PluginExtResult`
>(
plugin: RuntimePlugin<PluginSchema, PluginExtQueryArgs, PluginExtClientMembers, PluginExtResult> & {
// intersect with the `result` extension field for precise typing
result?: ExtResultInferenceArgs<Schema, _R>;
},
): ClientContract<
Schema,
Options,
ExtQueryArgs & PluginExtQueryArgs,
ExtClientMembers & PluginExtClientMembers,
ExtResult & PluginExtResult
>;
/**
* Returns a new client with the specified plugin removed. The original client remains unchanged.
*/
$unuse(pluginId: string): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
/**
* Returns a new client with all plugins removed. The original client remains unchanged.
*/
$unuseAll(): ClientContract<Schema, Options>;
/**
* Eagerly connects to the database.
*/
$connect(): Promise<void>;
/**
* Explicitly disconnects from the database.
*/
$disconnect(): Promise<void>;
/**
* Factory for creating zod schemas to validate query args.
*/
get $zod(): ZodSchemaFactory<Schema, Options, ExtQueryArgs>;
/**
* Pushes the schema to the database. For testing purposes only.
* @private
*/
$pushSchema(): Promise<void>;
/**
* Returns diagnostics information such as cache and slow query statistics.
*/
get $diagnostics(): Promise<Diagnostics>;
} & {
[Key in GetSlicedModels<Schema, Options> as Uncapitalize<Key>]: ModelOperations<
Schema,
Key,
Options,
ExtQueryArgs,
ExtResult
>;
} & ProcedureOperations<Schema, Options> &
ExtClientMembers;
/**
* The contract for a client in a transaction.
*/
export type TransactionClientContract<
Schema extends SchemaDef,
Options extends ClientOptions<Schema>,
ExtQueryArgs extends ExtQueryArgsBase,
ExtClientMembers extends ExtClientMembersBase,
ExtResult extends ExtResultBase<Schema> = {},
> = Omit<ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>, TransactionUnsupportedMethods>;
export type ProcedureOperations<
Schema extends SchemaDef,
Options extends ClientOptions<Schema> = ClientOptions<Schema>,
> =
Schema['procedures'] extends Record<string, ProcedureDef>
? {
/**
* Custom procedures.
*/
$procs: {
[Key in GetSlicedProcedures<Schema, Options>]: ProcedureFunc<Schema, Key>;
};
}
: {};
/**
* Creates a new ZenStack client instance.
*/
export interface ClientConstructor {
new <Schema extends SchemaDef, Options extends ClientOptions<Schema> = ClientOptions<Schema>>(
schema: Schema,
options: Options,
): ClientContract<Schema, Options>;
}
/**
* CRUD operations.
*/
export type CRUD = 'create' | 'read' | 'update' | 'delete';
/**
* Extended CRUD operations including 'post-update'.
*/
export type CRUD_EXT = CRUD | 'post-update';
/**
* CRUD operations.
*/
export const CRUD = ['create', 'read', 'update', 'delete'] as const;
/**
* Extended CRUD operations including 'post-update'.
*/
export const CRUD_EXT = [...CRUD, 'post-update'] as const;
// #region Model operations
type SliceOperations<
T extends Record<string, unknown>,
Schema extends SchemaDef,
Model extends GetModels<Schema>,
Options extends ClientOptions<Schema>,
> = Omit<
{
// keep only operations included by slicing options
[Key in keyof T as Key extends GetSlicedOperations<Schema, Model, Options> ? Key : never]: T[Key];
},
// exclude create operations for models that don't allow create (delegate models, required Unsupported fields)
ModelAllowsCreate<Schema, Model> extends true ? never : OperationsRequiringCreate
>;
export type AllModelOperations<
Schema extends SchemaDef,
Model extends GetModels<Schema>,
Options extends QueryOptions<Schema>,
ExtQueryArgs extends ExtQueryArgsBase,
ExtResult extends ExtResultBase<Schema> = {},
> = CommonModelOperations<Schema, Model, Options, ExtQueryArgs, ExtResult> &
// provider-specific operations
(Schema['provider']['type'] extends 'mysql'
? {}
: {
/**
* Creates multiple entities and returns them.
* @param args - create args. See {@link createMany} for input. Use
* `select` and `omit` to control the fields returned.
* @returns the created entities
*
* @example
* ```ts
* // create multiple entities and return selected fields
* await db.user.createManyAndReturn({
* data: [
* { name: 'Alex', email: 'alex@zenstack.dev' },
* { name: 'John', email: 'john@zenstack.dev' }
* ],
* select: { id: true, email: true }
* });
* ```
*/
createManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(
args?: SelectSubset<T, CreateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
/**
* Updates multiple entities and returns them.
* @param args - update args. Only scalar fields are allowed for data.
* @returns the updated entities
*
* @example
* ```ts
* // update many entities and return selected fields
* await db.user.updateManyAndReturn({
* where: { email: { endsWith: '@zenstack.dev' } },
* data: { role: 'ADMIN' },
* select: { id: true, email: true }
* }); // result: `Array<{ id: string; email: string }>`
*
* // limit the number of updated entities
* await db.user.updateManyAndReturn({
* where: { email: { endsWith: '@zenstack.dev' } },
* data: { role: 'ADMIN' },
* limit: 10
* });
* ```
*/
updateManyAndReturn<T extends OmitWhere<UpdateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args: { where?: WhereInput<Schema, Model, Options> } & SubsetWithWhere<T, OmitWhere<UpdateManyAndReturnArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
});
type CommonModelOperations<
Schema extends SchemaDef,
Model extends GetModels<Schema>,
Options extends QueryOptions<Schema>,
ExtQueryArgs extends ExtQueryArgsBase,
ExtResult extends ExtResultBase<Schema> = {},
> = {
/**
* Returns a list of entities.
* @param args - query args
* @returns a list of entities
*
* @example
* ```ts
* // find all users and return all scalar fields
* await db.user.findMany();
*
* // find all users with name 'Alex'
* await db.user.findMany({
* where: {
* name: 'Alex'
* }
* });
*
* // select fields
* await db.user.findMany({
* select: {
* name: true,
* email: true,
* }
* }); // result: `Array<{ name: string, email: string }>`
*
* // omit fields
* await db.user.findMany({
* omit: {
* name: true,
* }
* }); // result: `Array<{ id: number; email: string; ... }>`
*
* // include relations (and all scalar fields)
* await db.user.findMany({
* include: {
* posts: true,
* }
* }); // result: `Array<{ ...; posts: Post[] }>`
*
* // include relations with filter
* await db.user.findMany({
* include: {
* posts: {
* where: {
* published: true
* }
* }
* }
* });
*
* // pagination and sorting
* await db.user.findMany({
* skip: 10,
* take: 10,
* orderBy: [{ name: 'asc' }, { email: 'desc' }],
* });
*
* // pagination with cursor (https://www.prisma.io/docs/orm/prisma-client/queries/pagination#cursor-based-pagination)
* await db.user.findMany({
* cursor: { id: 10 },
* skip: 1,
* take: 10,
* orderBy: { id: 'asc' },
* });
*
* // distinct
* await db.user.findMany({
* distinct: ['name']
* });
*
* // count all relations
* await db.user.findMany({
* _count: true,
* }); // result: `{ _count: { posts: number; ... } }`
*
* // count selected relations
* await db.user.findMany({
* _count: { select: { posts: true } },
* }); // result: `{ _count: { posts: number } }`
* ```
*/
findMany<T extends OmitWhere<FindManyArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args?: { where?: WhereInput<Schema, Model, Options> } & SelectSubset<T, FindManyArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>[]>;
/**
* Returns a uniquely identified entity.
* @param args - query args
* @returns a single entity or null if not found
* @see {@link findMany}
*/
findUnique<T extends OmitWhere<FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args: { where: WhereUniqueInput<Schema, Model, Options> } & SelectSubset<T, FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
/**
* Returns a uniquely identified entity or throws `NotFoundError` if not found.
* @param args - query args
* @returns a single entity
* @see {@link findMany}
*/
findUniqueOrThrow<T extends OmitWhere<FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args: { where: WhereUniqueInput<Schema, Model, Options> } & SelectSubset<T, FindUniqueArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
/**
* Returns the first entity.
* @param args - query args
* @returns a single entity or null if not found
* @see {@link findMany}
*/
findFirst<T extends OmitWhere<FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args?: { where?: WhereInput<Schema, Model, Options> } & SelectSubset<T, FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult> | null>;
/**
* Returns the first entity or throws `NotFoundError` if not found.
* @param args - query args
* @returns a single entity
* @see {@link findMany}
*/
findFirstOrThrow<T extends OmitWhere<FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args?: { where?: WhereInput<Schema, Model, Options> } & SelectSubset<T, FindFirstArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
/**
* Creates a new entity.
* @param args - create args
* @returns the created entity
*
* @example
* ```ts
* // simple create
* await db.user.create({
* data: { name: 'Alex', email: 'alex@zenstack.dev' }
* });
*
* // nested create with relation
* await db.user.create({
* data: {
* email: 'alex@zenstack.dev',
* posts: { create: { title: 'Hello World' } }
* }
* });
*
* // you can use `select`, `omit`, and `include` to control
* // the fields returned by the query, as with `findMany`
* await db.user.create({
* data: {
* email: 'alex@zenstack.dev',
* posts: { create: { title: 'Hello World' } }
* },
* include: { posts: true }
* }); // result: `{ id: number; posts: Post[] }`
*
* // connect relations
* await db.user.create({
* data: {
* email: 'alex@zenstack.dev',
* posts: { connect: { id: 1 } }
* }
* });
*
* // connect relations, and create if not found
* await db.user.create({
* data: {
* email: 'alex@zenstack.dev',
* posts: {
* connectOrCreate: {
* where: { id: 1 },
* create: { title: 'Hello World' }
* }
* }
* }
* });
* ```
*/
create<T extends CreateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>(
args: SelectSubset<T, CreateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
/**
* Creates multiple entities. Only scalar fields are allowed.
* @param args - create args
* @returns count of created entities: `{ count: number }`
*
* @example
* ```ts
* // create multiple entities
* await db.user.createMany({
* data: [
* { name: 'Alex', email: 'alex@zenstack.dev' },
* { name: 'John', email: 'john@zenstack.dev' }
* ]
* });
*
* // skip items that cause unique constraint violation
* await db.user.createMany({
* data: [
* { name: 'Alex', email: 'alex@zenstack.dev' },
* { name: 'John', email: 'john@zenstack.dev' }
* ],
* skipDuplicates: true
* });
* ```
*/
createMany<T extends CreateManyArgs<Schema, Model, Options, ExtQueryArgs>>(
args?: SelectSubset<T, CreateManyArgs<Schema, Model, Options, ExtQueryArgs>>,
): ZenStackPromise<Schema, BatchResult>;
/**
* Updates a uniquely identified entity.
* @param args - update args. See {@link findMany} for how to control
* fields and relations returned.
* @returns the updated entity. Throws `NotFoundError` if the entity is not found.
*
* @example
* ```ts
* // update fields
* await db.user.update({
* where: { id: 1 },
* data: { name: 'Alex' }
* });
*
* // connect a relation
* await db.user.update({
* where: { id: 1 },
* data: { posts: { connect: { id: 1 } } }
* });
*
* // connect relation, and create if not found
* await db.user.update({
* where: { id: 1 },
* data: {
* posts: {
* connectOrCreate: {
* where: { id: 1 },
* create: { title: 'Hello World' }
* }
* }
* }
* });
*
* // create many related entities (only available for one-to-many relations)
* await db.user.update({
* where: { id: 1 },
* data: {
* posts: {
* createMany: {
* data: [{ title: 'Hello World' }, { title: 'Hello World 2' }],
* }
* }
* }
* });
*
* // disconnect a one-to-many relation
* await db.user.update({
* where: { id: 1 },
* data: { posts: { disconnect: { id: 1 } } }
* });
*
* // disconnect a one-to-one relation
* await db.user.update({
* where: { id: 1 },
* data: { profile: { disconnect: true } }
* });
*
* // replace a relation (only available for one-to-many relations)
* await db.user.update({
* where: { id: 1 },
* data: {
* posts: {
* set: [{ id: 1 }, { id: 2 }]
* }
* }
* });
*
* // update a relation
* await db.user.update({
* where: { id: 1 },
* data: {
* posts: {
* update: { where: { id: 1 }, data: { title: 'Hello World' } }
* }
* }
* });
*
* // upsert a relation
* await db.user.update({
* where: { id: 1 },
* data: {
* posts: {
* upsert: {
* where: { id: 1 },
* create: { title: 'Hello World' },
* update: { title: 'Hello World' }
* }
* }
* }
* });
*
* // update many related entities (only available for one-to-many relations)
* await db.user.update({
* where: { id: 1 },
* data: {
* posts: {
* updateMany: {
* where: { published: true },
* data: { title: 'Hello World' }
* }
* }
* }
* });
*
* // delete a one-to-many relation
* await db.user.update({
* where: { id: 1 },
* data: { posts: { delete: { id: 1 } } }
* });
*
* // delete a one-to-one relation
* await db.user.update({
* where: { id: 1 },
* data: { profile: { delete: true } }
* });
* ```
*/
update<T extends OmitWhere<UpdateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args: { where: WhereUniqueInput<Schema, Model, Options> } & SelectSubsetWithWhere<T, OmitWhere<UpdateArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
/**
* Updates multiple entities.
* @param args - update args. Only scalar fields are allowed for data.
* @returns count of updated entities: `{ count: number }`
*
* @example
* ```ts
* // update many entities
* await db.user.updateMany({
* where: { email: { endsWith: '@zenstack.dev' } },
* data: { role: 'ADMIN' }
* });
*
* // limit the number of updated entities
* await db.user.updateMany({
* where: { email: { endsWith: '@zenstack.dev' } },
* data: { role: 'ADMIN' },
* limit: 10
* });
*/
updateMany<T extends OmitWhere<UpdateManyArgs<Schema, Model, Options, ExtQueryArgs>>>(
args: { where?: WhereInput<Schema, Model, Options> } & SubsetWithWhere<T, OmitWhere<UpdateManyArgs<Schema, Model, Options, ExtQueryArgs>>>,
): ZenStackPromise<Schema, BatchResult>;
/**
* Creates or updates an entity.
* @param args - upsert args
* @returns the upserted entity
*
* @example
* ```ts
* // upsert an entity
* await db.user.upsert({
* // `where` clause is used to find the entity
* where: { id: 1 },
* // `create` clause is used if the entity is not found
* create: { email: 'alex@zenstack.dev', name: 'Alex' },
* // `update` clause is used if the entity is found
* update: { name: 'Alex-new' },
* // `select` and `omit` can be used to control the returned fields
* ...
* });
* ```
*/
upsert<T extends OmitWhere<UpsertArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args: { where: WhereUniqueInput<Schema, Model, Options> } & SelectSubsetWithWhere<T, OmitWhere<UpsertArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
/**
* Deletes a uniquely identifiable entity.
* @param args - delete args
* @returns the deleted entity. Throws `NotFoundError` if the entity is not found.
*
* @example
* ```ts
* // delete an entity
* await db.user.delete({
* where: { id: 1 }
* });
*
* // delete an entity and return selected fields
* await db.user.delete({
* where: { id: 1 },
* select: { id: true, email: true }
* }); // result: `{ id: string; email: string }`
* ```
*/
delete<T extends OmitWhere<DeleteArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>>(
args: { where: WhereUniqueInput<Schema, Model, Options> } & SelectSubset<T, DeleteArgs<Schema, Model, Options, ExtQueryArgs, ExtResult>>,
): ZenStackPromise<Schema, SimplifiedPlainResult<Schema, Model, T, Options, ExtResult>>;
/**
* Deletes multiple entities.
* @param args - delete args
* @returns count of deleted entities: `{ count: number }`
*
* @example
* ```ts
* // delete many entities
* await db.user.deleteMany({
* where: { email: { endsWith: '@zenstack.dev' } }
* });
*
* // limit the number of deleted entities
* await db.user.deleteMany({
* where: { email: { endsWith: '@zenstack.dev' } },
* limit: 10
* });
* ```
*/
deleteMany<T extends OmitWhere<DeleteManyArgs<Schema, Model, Options, ExtQueryArgs>>>(
args?: { where?: WhereInput<Schema, Model, Options> } & Subset<T, DeleteManyArgs<Schema, Model, Options, ExtQueryArgs>>,
): ZenStackPromise<Schema, BatchResult>;
/**
* Counts rows or field values.
* @param args - count args
* @returns `number`, or an object containing count of selected relations
*
* @example
* ```ts
* // count all
* await db.user.count();
*
* // count with a filter
* await db.user.count({ where: { email: { endsWith: '@zenstack.dev' } } });
*
* // count rows and field values
* await db.user.count({
* select: { _all: true, email: true }
* }); // result: `{ _all: number, email: number }`
*/
count<T extends CountArgs<Schema, Model, Options, ExtQueryArgs>>(
args?: Subset<T, CountArgs<Schema, Model, Options, ExtQueryArgs>>,
): ZenStackPromise<Schema, Simplify<CountResult<Schema, Model, T>>>;
/**
* Aggregates rows.
* @param args - aggregation args
* @returns an object containing aggregated values
*
* @example
* ```ts
* // aggregate rows
* await db.profile.aggregate({
* where: { email: { endsWith: '@zenstack.dev' } },
* _count: true,
* _avg: { age: true },
* _sum: { age: true },
* _min: { age: true },
* _max: { age: true }
* }); // result: `{ _count: number, _avg: { age: number }, ... }`
*/
aggregate<T extends AggregateArgs<Schema, Model, Options, ExtQueryArgs>>(
args: Subset<T, AggregateArgs<Schema, Model, Options, ExtQueryArgs>>,
): ZenStackPromise<Schema, Simplify<AggregateResult<Schema, Model, T>>>;
/**
* Groups rows by columns.
* @param args - groupBy args
* @returns an object containing grouped values
*
* @example
* ```ts
* // group by a field
* await db.profile.groupBy({
* by: 'country',
* _count: true
* }); // result: `Array<{ country: string, _count: number }>`
*
* // group by multiple fields
* await db.profile.groupBy({
* by: ['country', 'city'],
* _count: true
* }); // result: `Array<{ country: string, city: string, _count: number }>`
*
* // group by with sorting, the `orderBy` fields must be either an aggregation
* // or a field used in the `by` list
* await db.profile.groupBy({
* by: 'country',
* orderBy: { country: 'desc' }
* });
*
* // group by with having (post-aggregation filter), the fields used in `having` must
* // be either an aggregation, or a field used in the `by` list
* await db.profile.groupBy({
* by: 'country',
* having: { country: 'US', age: { _avg: { gte: 18 } } }
* });
*/
groupBy<T extends GroupByArgs<Schema, Model, Options, ExtQueryArgs>>(
args: Subset<T, GroupByArgs<Schema, Model, Options, ExtQueryArgs>>,
): ZenStackPromise<Schema, Simplify<GroupByResult<Schema, Model, T>>>;
/**
* Checks if an entity exists.
* @param args - exists args
* @returns whether a matching entity was found
*
* @example
* ```ts
* // check if a user exists
* await db.user.exists({
* where: { id: 1 },
* }); // result: `boolean`
*
* // check with a relation
* await db.user.exists({
* where: { posts: { some: { published: true } } },
* }); // result: `boolean`
*/
exists<T extends ExistsArgs<Schema, Model, Options, ExtQueryArgs>>(
args?: Subset<T, ExistsArgs<Schema, Model, Options, ExtQueryArgs>>,
): ZenStackPromise<Schema, boolean>;
};
export type OperationsRequiringCreate = 'create' | 'createMany' | 'createManyAndReturn' | 'upsert';
export type ModelOperations<
Schema extends SchemaDef,
Model extends GetModels<Schema>,
Options extends ClientOptions<Schema> = ClientOptions<Schema>,
ExtQueryArgs extends ExtQueryArgsBase = {},
ExtResult extends ExtResultBase<Schema> = {},
> = SliceOperations<AllModelOperations<Schema, Model, Options, ExtQueryArgs, ExtResult>, Schema, Model, Options>;
//#endregion
//#region Supporting types
/**
* Type for auth context that includes both scalar and relation fields.
* Relations are recursively included to allow nested auth data like { user: { profile: { ... } } }
*/
type AuthModelType<Schema extends SchemaDef, Model extends GetModels<Schema>> = Partial<
DefaultModelResult<Schema, Model>
> & {
[Key in RelationFields<Schema, Model>]?: FieldIsArray<Schema, Model, Key> extends true
? AuthModelType<Schema, RelationFieldType<Schema, Model, Key>>[]
: AuthModelType<Schema, RelationFieldType<Schema, Model, Key>>;
};
export 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>;
//#endregion