-
-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathdelegate.ts
More file actions
1481 lines (1258 loc) · 54.9 KB
/
delegate.ts
File metadata and controls
1481 lines (1258 loc) · 54.9 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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
import deepmerge, { type ArrayMergeOptions } from 'deepmerge';
import { isPlainObject } from 'is-plain-object';
import { lowerCaseFirst } from 'lower-case-first';
import traverse from 'traverse';
import { DELEGATE_AUX_RELATION_PREFIX } from '../../constants';
import {
FieldInfo,
ModelInfo,
NestedWriteVisitor,
clone,
enumerate,
getIdFields,
getModelInfo,
isDelegateModel,
resolveField,
} from '../../cross';
import type { CrudContract, DbClientContract, EnhancementContext } from '../../types';
import type { InternalEnhancementOptions } from './create-enhancement';
import { Logger } from './logger';
import { DefaultPrismaProxyHandler, makeProxy } from './proxy';
import { QueryUtils } from './query-utils';
import { formatObject, prismaClientValidationError } from './utils';
export function withDelegate<DbClient extends object>(
prisma: DbClient,
options: InternalEnhancementOptions,
context: EnhancementContext | undefined
): DbClient {
return makeProxy(
prisma,
options.modelMeta,
(_prisma, model) => new DelegateProxyHandler(_prisma as DbClientContract, model, options, context),
'delegate'
);
}
export class DelegateProxyHandler extends DefaultPrismaProxyHandler {
private readonly logger: Logger;
private readonly queryUtils: QueryUtils;
constructor(
prisma: DbClientContract,
model: string,
options: InternalEnhancementOptions,
private readonly context: EnhancementContext | undefined
) {
super(prisma, model, options);
this.logger = new Logger(prisma);
this.queryUtils = new QueryUtils(prisma, this.options);
}
// #region find
override findFirst(args: any): Promise<unknown> {
return this.doFind(this.prisma, this.model, 'findFirst', args);
}
override findFirstOrThrow(args: any): Promise<unknown> {
return this.doFind(this.prisma, this.model, 'findFirstOrThrow', args);
}
override findUnique(args: any): Promise<unknown> {
return this.doFind(this.prisma, this.model, 'findUnique', args);
}
override findUniqueOrThrow(args: any): Promise<unknown> {
return this.doFind(this.prisma, this.model, 'findUniqueOrThrow', args);
}
override async findMany(args: any): Promise<unknown[]> {
return this.doFind(this.prisma, this.model, 'findMany', args);
}
private async doFind(
db: CrudContract,
model: string,
method: 'findFirst' | 'findFirstOrThrow' | 'findUnique' | 'findUniqueOrThrow' | 'findMany',
args: any
) {
if (!this.involvesDelegateModel(model)) {
return super[method](args);
}
args = args ? clone(args) : {};
this.injectWhereHierarchy(model, args?.where);
await this.injectSelectIncludeHierarchy(model, args);
// discriminator field is needed during post process to determine the
// actual concrete model type
this.ensureDiscriminatorSelection(model, args);
if (args.orderBy) {
// `orderBy` may contain fields from base types
enumerate(args.orderBy).forEach((item) => this.injectWhereHierarchy(model, item));
}
if (this.options.logPrismaQuery) {
this.logger.info(`[delegate] \`${method}\` ${this.getModelName(model)}: ${formatObject(args)}`);
}
const entity = await db[model][method](args);
if (Array.isArray(entity)) {
return entity.map((item) => this.assembleHierarchy(model, item));
} else {
return this.assembleHierarchy(model, entity);
}
}
private ensureDiscriminatorSelection(model: string, args: any) {
const modelInfo = getModelInfo(this.options.modelMeta, model);
if (!modelInfo?.discriminator) {
return;
}
if (args.select && typeof args.select === 'object') {
args.select[modelInfo.discriminator] = true;
return;
}
if (args.omit && typeof args.omit === 'object') {
args.omit[modelInfo.discriminator] = false;
return;
}
}
private injectWhereHierarchy(model: string, where: any) {
if (!where || !isPlainObject(where)) {
return;
}
Object.entries(where).forEach(([field, value]) => {
if (['AND', 'OR', 'NOT'].includes(field)) {
// recurse into logical group
enumerate(value).forEach((item) => this.injectWhereHierarchy(model, item));
return;
}
const fieldInfo = resolveField(this.options.modelMeta, model, field);
if (!fieldInfo?.inheritedFrom) {
// not an inherited field, inject and continue
if (fieldInfo?.isDataModel) {
this.injectWhereHierarchy(fieldInfo.type, value);
}
return;
}
let base = this.getBaseModel(model);
let target = where;
while (base) {
const baseRelationName = this.makeAuxRelationName(base);
// prepare base layer where
let thisLayer: any;
if (target[baseRelationName]) {
thisLayer = target[baseRelationName];
} else {
thisLayer = target[baseRelationName] = {};
}
if (base.name === fieldInfo.inheritedFrom) {
if (fieldInfo.isDataModel) {
this.injectWhereHierarchy(base.name, value);
}
thisLayer[field] = value;
delete where[field];
break;
} else {
target = thisLayer;
base = this.getBaseModel(base.name);
}
}
});
}
private async injectSelectIncludeHierarchy(model: string, args: any) {
if (!args || typeof args !== 'object') {
return;
}
// there're two cases where we need to inject polymorphic base hierarchy for fields
// defined in base models
// 1. base fields mentioned in select/include clause
// { select: { fieldFromBase: true } } => { select: { delegate_aux_[Base]: { fieldFromBase: true } } }
// 2. base fields mentioned in _count select/include clause
// { select: { _count: { select: { fieldFromBase: true } } } } => { select: { delegate_aux_[Base]: { select: { _count: { select: { fieldFromBase: true } } } } } }
//
// Note that although structurally similar, we need to correctly deal with different injection location of the "delegate_aux" hierarchy
// selectors for the above two cases
const selectors = [
// regular select: { select: { field: true } }
(payload: any) => ({ data: payload.select, kind: 'select' as const, isCount: false }),
// regular include: { include: { field: true } }
(payload: any) => ({ data: payload.include, kind: 'include' as const, isCount: false }),
// select _count: { select: { _count: { select: { field: true } } } }
(payload: any) => ({
data: payload.select?._count?.select,
kind: 'select' as const,
isCount: true,
}),
// include _count: { include: { _count: { select: { field: true } } } }
(payload: any) => ({
data: payload.include?._count?.select,
kind: 'include' as const,
isCount: true,
}),
];
for (const selector of selectors) {
const { data, kind, isCount } = selector(args);
if (!data || typeof data !== 'object') {
continue;
}
for (const [field, value] of Object.entries<any>(data)) {
const fieldInfo = resolveField(this.options.modelMeta, model, field);
if (!fieldInfo) {
continue;
}
if (this.isDelegateOrDescendantOfDelegate(fieldInfo?.type) && value) {
// delegate model, recursively inject hierarchy
if (data[field]) {
if (data[field] === true) {
// make sure the payload is an object
data[field] = {};
}
await this.injectSelectIncludeHierarchy(fieldInfo.type, data[field]);
}
}
// refetch the field select/include value because it may have been
// updated during injection
const fieldValue = data[field];
if (fieldValue !== undefined) {
if (fieldValue.orderBy) {
// `orderBy` may contain fields from base types
enumerate(fieldValue.orderBy).forEach((item) =>
this.injectWhereHierarchy(fieldInfo.type, item)
);
}
let injected = false;
if (!isCount) {
// regular select/include injection
injected = await this.injectBaseFieldSelect(model, field, fieldValue, args, kind);
if (injected) {
// if injected, remove the field from the original payload
delete data[field];
}
} else {
// _count select/include injection, inject into an empty payload and then merge to the proper location
const injectTarget = { [kind]: {} };
injected = await this.injectBaseFieldSelect(model, field, fieldValue, injectTarget, kind, true);
if (injected) {
// if injected, remove the field from the original payload
delete data[field];
if (Object.keys(data).length === 0) {
// if the original "_count" payload becomes empty, remove it
delete args[kind]['_count'];
}
// finally merge the injection into the original payload
const merged = deepmerge(args[kind], injectTarget[kind]);
args[kind] = merged;
}
}
if (!injected && fieldInfo.isDataModel) {
let nextValue = fieldValue;
if (nextValue === true) {
// make sure the payload is an object
data[field] = nextValue = {};
}
await this.injectSelectIncludeHierarchy(fieldInfo.type, nextValue);
}
}
}
}
if (!args.select) {
// include base models upwards
this.injectBaseIncludeRecursively(model, args);
// include sub models downwards
await this.injectConcreteIncludeRecursively(model, args);
}
}
private async buildSelectIncludeHierarchy(model: string, args: any, includeConcreteFields = true) {
args = clone(args);
const selectInclude: any = this.extractSelectInclude(args) || {};
if (selectInclude.select && typeof selectInclude.select === 'object') {
Object.entries(selectInclude.select).forEach(([field, value]) => {
if (value) {
if (this.injectBaseFieldSelect(model, field, value, selectInclude, 'select')) {
delete selectInclude.select[field];
}
}
});
} else if (selectInclude.include && typeof selectInclude.include === 'object') {
Object.entries(selectInclude.include).forEach(([field, value]) => {
if (value) {
if (this.injectBaseFieldSelect(model, field, value, selectInclude, 'include')) {
delete selectInclude.include[field];
}
}
});
}
if (!selectInclude.select) {
this.injectBaseIncludeRecursively(model, selectInclude);
if (includeConcreteFields) {
await this.injectConcreteIncludeRecursively(model, selectInclude);
}
}
return selectInclude;
}
private injectBaseFieldSelect(
model: string,
field: string,
value: any,
selectInclude: any,
context: 'select' | 'include',
forCount = false // if the injection is for a "{ _count: { select: { field: true } } }" payload
) {
const fieldInfo = resolveField(this.options.modelMeta, model, field);
if (!fieldInfo?.inheritedFrom) {
return false;
}
let base = this.getBaseModel(model);
let target = selectInclude;
while (base) {
const baseRelationName = this.makeAuxRelationName(base);
// prepare base layer select/include
let thisLayer: any;
if (target.include) {
thisLayer = target.include;
} else if (target.select) {
thisLayer = target.select;
} else {
thisLayer = target.select = {};
}
if (base.name === fieldInfo.inheritedFrom) {
if (!thisLayer[baseRelationName]) {
thisLayer[baseRelationName] = { [context]: {} };
}
if (forCount) {
// { _count: { select: { field: true } } } => { delegate_aux_[Base]: { select: { _count: { select: { field: true } } } } }
if (
!thisLayer[baseRelationName][context]['_count'] ||
typeof thisLayer[baseRelationName][context] !== 'object'
) {
thisLayer[baseRelationName][context]['_count'] = {};
}
thisLayer[baseRelationName][context]['_count'] = deepmerge(
thisLayer[baseRelationName][context]['_count'],
{ select: { [field]: value } }
);
} else {
// { select: { field: true } } => { delegate_aux_[Base]: { select: { field: true } } }
thisLayer[baseRelationName][context][field] = value;
}
break;
} else {
if (!thisLayer[baseRelationName]) {
thisLayer[baseRelationName] = { select: {} };
}
target = thisLayer[baseRelationName];
base = this.getBaseModel(base.name);
}
}
return true;
}
private injectBaseIncludeRecursively(model: string, selectInclude: any) {
const base = this.getBaseModel(model);
if (!base) {
return;
}
const baseRelationName = this.makeAuxRelationName(base);
if (selectInclude.select) {
selectInclude.include = { [baseRelationName]: {}, ...selectInclude.select };
delete selectInclude.select;
} else {
selectInclude.include = { [baseRelationName]: {}, ...selectInclude.include };
}
this.injectBaseIncludeRecursively(base.name, selectInclude.include[baseRelationName]);
}
private async injectConcreteIncludeRecursively(model: string, selectInclude: any) {
const modelInfo = getModelInfo(this.options.modelMeta, model);
if (!modelInfo) {
return;
}
// get sub models of this model
const subModels = Object.values(this.options.modelMeta.models).filter((m) =>
m.baseTypes?.includes(modelInfo.name)
);
for (const subModel of subModels) {
// include sub model relation field
const subRelationName = this.makeAuxRelationName(subModel);
// create a payload to include the sub model relation
const includePayload = await this.createConcreteRelationIncludePayload(subModel.name);
if (selectInclude.select) {
selectInclude.include = { [subRelationName]: includePayload, ...selectInclude.select };
delete selectInclude.select;
} else {
selectInclude.include = { [subRelationName]: includePayload, ...selectInclude.include };
}
await this.injectConcreteIncludeRecursively(subModel.name, selectInclude.include[subRelationName]);
}
}
private async createConcreteRelationIncludePayload(model: string) {
let result: any = {};
if (this.options.processIncludeRelationPayload) {
// use the callback in options to process the include payload, so enhancements
// like 'policy' can do extra work (e.g., inject policy rules)
// TODO: this causes both delegate base's policy rules and concrete model's rules to be injected,
// which is not wrong but redundant
await this.options.processIncludeRelationPayload(this.prisma, model, result, this.options, this.context);
const properSelectIncludeHierarchy = await this.buildSelectIncludeHierarchy(model, result, false);
result = { ...result, ...properSelectIncludeHierarchy };
}
return result;
}
// #endregion
// #region create
override async create(args: any) {
if (!args) {
throw prismaClientValidationError(this.prisma, this.options.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'data field is required in query argument'
);
}
this.sanitizeMutationPayload(args.data);
if (isDelegateModel(this.options.modelMeta, this.model)) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
`Model "${this.model}" is a delegate and cannot be created directly`
);
}
if (!this.involvesDelegateModel(this.model)) {
return super.create(args);
}
return this.doCreate(this.prisma, this.model, args);
}
private sanitizeMutationPayload(data: any) {
if (!data) {
return;
}
const prisma = this.prisma;
const prismaModule = this.options.prismaModule;
traverse(data).forEach(function () {
if (this.key?.startsWith(DELEGATE_AUX_RELATION_PREFIX)) {
throw prismaClientValidationError(
prisma,
prismaModule,
`Auxiliary relation field "${this.key}" cannot be set directly`
);
}
});
}
override createMany(args: { data: any; skipDuplicates?: boolean }): Promise<{ count: number }> {
if (!args) {
throw prismaClientValidationError(this.prisma, this.options.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'data field is required in query argument'
);
}
this.sanitizeMutationPayload(args.data);
if (!this.involvesDelegateModel(this.model)) {
return super.createMany(args);
}
if (this.isDelegateOrDescendantOfDelegate(this.model) && args.skipDuplicates) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'`createMany` with `skipDuplicates` set to true is not supported for delegated models'
);
}
// `createMany` doesn't support nested create, which is needed for creating entities
// inheriting a delegate base, so we need to convert it to a regular `create` here.
// Note that the main difference is `create` doesn't support `skipDuplicates` as
// `createMany` does.
return this.queryUtils.transaction(this.prisma, async (tx) => {
const r = await Promise.all(
enumerate(args.data).map(async (item) => {
return this.doCreate(tx, this.model, { data: item });
})
);
return { count: r.length };
});
}
override createManyAndReturn(args: { data: any; select?: any; skipDuplicates?: boolean }): Promise<unknown[]> {
if (!args) {
throw prismaClientValidationError(this.prisma, this.options.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'data field is required in query argument'
);
}
this.sanitizeMutationPayload(args.data);
if (!this.involvesDelegateModel(this.model)) {
return super.createManyAndReturn(args);
}
if (this.isDelegateOrDescendantOfDelegate(this.model) && args.skipDuplicates) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'`createManyAndReturn` with `skipDuplicates` set to true is not supported for delegated models'
);
}
// `createManyAndReturn` doesn't support nested create, which is needed for creating entities
// inheriting a delegate base, so we need to convert it to a regular `create` here.
// Note that the main difference is `create` doesn't support `skipDuplicates` as
// `createManyAndReturn` does.
return this.queryUtils.transaction(this.prisma, async (tx) => {
const r = await Promise.all(
enumerate(args.data).map(async (item) => {
return this.doCreate(tx, this.model, { data: item, select: args.select });
})
);
return r;
});
}
private async doCreate(db: CrudContract, model: string, args: any) {
args = clone(args);
await this.injectCreateHierarchy(model, args);
await this.injectSelectIncludeHierarchy(model, args);
if (this.options.logPrismaQuery) {
this.logger.info(`[delegate] \`create\` ${this.getModelName(model)}: ${formatObject(args)}`);
}
const result = await db[model].create(args);
return this.assembleHierarchy(model, result);
}
private async injectCreateHierarchy(model: string, args: any) {
const visitor = new NestedWriteVisitor(this.options.modelMeta, {
create: (model, args, _context) => {
this.doProcessCreatePayload(model, args);
},
createMany: (model, args, context) => {
// `createMany` doesn't support nested create, which is needed for creating entities
// inheriting a delegate base, so we need to convert it to a regular `create` here.
// Note that the main difference is `create` doesn't support `skipDuplicates` as
// `createMany` does.
if (this.isDelegateOrDescendantOfDelegate(model)) {
if (args.skipDuplicates) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'`createMany` with `skipDuplicates` set to true is not supported for delegated models'
);
}
// convert to regular `create`
let createPayload = context.parent.create ?? [];
if (!Array.isArray(createPayload)) {
createPayload = [createPayload];
}
for (const item of enumerate(args.data)) {
this.doProcessCreatePayload(model, item);
createPayload.push(item);
}
context.parent.create = createPayload;
delete context.parent['createMany'];
}
},
});
await visitor.visit(model, 'create', args);
}
private doProcessCreatePayload(model: string, args: any) {
if (!args) {
return;
}
this.ensureBaseCreateHierarchy(model, args);
for (const [field, value] of Object.entries(args)) {
const fieldInfo = resolveField(this.options.modelMeta, model, field);
if (fieldInfo?.inheritedFrom) {
this.injectBaseFieldData(model, fieldInfo, value, args, 'create');
delete args[field];
}
}
}
// ensure the full nested "create" structure is created for base types
private ensureBaseCreateHierarchy(model: string, args: any) {
let curr = args;
let base = this.getBaseModel(model);
let sub = this.getModelInfo(model);
const hasDelegateBase = !!base;
while (base) {
const baseRelationName = this.makeAuxRelationName(base);
if (!curr[baseRelationName]) {
curr[baseRelationName] = {};
}
if (!curr[baseRelationName].create) {
curr[baseRelationName].create = {};
if (base.discriminator) {
// set discriminator field
curr[baseRelationName].create[base.discriminator] = sub.name;
}
}
// Look for base id field assignments in the current level, and push
// them down to the base level
for (const idField of getIdFields(this.options.modelMeta, base.name)) {
if (curr[idField.name] !== undefined) {
curr[baseRelationName].create[idField.name] = curr[idField.name];
delete curr[idField.name];
}
}
curr = curr[baseRelationName].create;
sub = base;
base = this.getBaseModel(base.name);
}
if (hasDelegateBase) {
// A delegate base model creation is added, this can be incompatible if
// the user-provided payload assigns foreign keys directly, because Prisma
// doesn't permit mixed "checked" and "unchecked" fields in a payload.
//
// {
// delegate_aux_base: { ... },
// [fkField]: value // <- this is not compatible
// }
//
// We need to convert foreign key assignments to `connect`.
this.fkAssignmentToConnect(model, args);
}
}
// convert foreign key assignments to `connect` payload
// e.g.: { authorId: value } -> { author: { connect: { id: value } } }
private fkAssignmentToConnect(model: string, args: any) {
const keysToDelete: string[] = [];
for (const [key, value] of Object.entries(args)) {
if (value === undefined) {
continue;
}
const fieldInfo = this.queryUtils.getModelField(model, key);
if (
!fieldInfo?.inheritedFrom && // fields from delegate base are handled outside
fieldInfo?.isForeignKey
) {
const relationInfo = this.queryUtils.getRelationForForeignKey(model, key);
if (relationInfo) {
// turn { [fk]: value } into { [relation]: { connect: { [id]: value } } }
const relationName = relationInfo.relation.name;
if (!args[relationName]) {
args[relationName] = {};
}
if (!args[relationName].connect) {
args[relationName].connect = {};
}
if (!(relationInfo.idField in args[relationName].connect)) {
args[relationName].connect[relationInfo.idField] = value;
keysToDelete.push(key);
}
}
}
}
keysToDelete.forEach((key) => delete args[key]);
}
// inject field data that belongs to base type into proper nesting structure
private injectBaseFieldData(
model: string,
fieldInfo: FieldInfo,
value: unknown,
args: any,
mode: 'create' | 'update'
) {
let base = this.getBaseModel(model);
let curr = args;
while (base) {
if (base.discriminator === fieldInfo.name) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
`fields "${fieldInfo.name}" is a discriminator and cannot be set directly`
);
}
const baseRelationName = this.makeAuxRelationName(base);
if (!curr[baseRelationName]) {
curr[baseRelationName] = {};
}
if (!curr[baseRelationName][mode]) {
curr[baseRelationName][mode] = {};
}
curr = curr[baseRelationName][mode];
if (fieldInfo.inheritedFrom === base.name) {
curr[fieldInfo.name] = value;
break;
}
base = this.getBaseModel(base.name);
}
}
// #endregion
// #region update
override update(args: any): Promise<unknown> {
if (!args) {
throw prismaClientValidationError(this.prisma, this.options.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'data field is required in query argument'
);
}
this.sanitizeMutationPayload(args.data);
if (!this.involvesDelegateModel(this.model)) {
return super.update(args);
}
return this.queryUtils.transaction(this.prisma, (tx) => this.doUpdate(tx, this.model, args));
}
override async updateMany(args: any): Promise<{ count: number }> {
if (!args) {
throw prismaClientValidationError(this.prisma, this.options.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'data field is required in query argument'
);
}
this.sanitizeMutationPayload(args.data);
if (!this.involvesDelegateModel(this.model)) {
return super.updateMany(args);
}
const simpleUpdateMany = Object.keys(args.data).every((key) => {
// check if the `data` clause involves base fields
const fieldInfo = resolveField(this.options.modelMeta, this.model, key);
return !fieldInfo?.inheritedFrom;
});
return this.queryUtils.transaction(this.prisma, (tx) =>
this.doUpdateMany(tx, this.model, args, simpleUpdateMany)
);
}
override async upsert(args: any): Promise<unknown> {
if (!args) {
throw prismaClientValidationError(this.prisma, this.options.prismaModule, 'query argument is required');
}
if (!args.where) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'where field is required in query argument'
);
}
this.sanitizeMutationPayload(args.update);
this.sanitizeMutationPayload(args.create);
if (isDelegateModel(this.options.modelMeta, this.model)) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
`Model "${this.model}" is a delegate and doesn't support upsert`
);
}
if (!this.involvesDelegateModel(this.model)) {
return super.upsert(args);
}
args = clone(args);
this.injectWhereHierarchy(this.model, (args as any)?.where);
await this.injectSelectIncludeHierarchy(this.model, args);
if (args.create) {
this.doProcessCreatePayload(this.model, args.create);
}
if (args.update) {
this.doProcessUpdatePayload(this.model, args.update);
}
if (this.options.logPrismaQuery) {
this.logger.info(`[delegate] \`upsert\` ${this.getModelName(this.model)}: ${formatObject(args)}`);
}
const result = await this.prisma[this.model].upsert(args);
return this.assembleHierarchy(this.model, result);
}
private async doUpdate(db: CrudContract, model: string, args: any): Promise<unknown> {
args = clone(args);
await this.injectUpdateHierarchy(db, model, args);
await this.injectSelectIncludeHierarchy(model, args);
if (this.options.logPrismaQuery) {
this.logger.info(`[delegate] \`update\` ${this.getModelName(model)}: ${formatObject(args)}`);
}
const result = await db[model].update(args);
return this.assembleHierarchy(model, result);
}
private async doUpdateMany(
db: CrudContract,
model: string,
args: any,
simpleUpdateMany: boolean
): Promise<{ count: number }> {
if (simpleUpdateMany) {
// do a direct `updateMany`
args = clone(args);
await this.injectUpdateHierarchy(db, model, args);
if (this.options.logPrismaQuery) {
this.logger.info(`[delegate] \`updateMany\` ${this.getModelName(model)}: ${formatObject(args)}`);
}
return db[model].updateMany(args);
} else {
// translate to plain `update` for nested write into base fields
const findArgs = {
where: clone(args.where),
select: this.queryUtils.makeIdSelection(model),
};
await this.injectUpdateHierarchy(db, model, findArgs);
if (this.options.logPrismaQuery) {
this.logger.info(
`[delegate] \`updateMany\` find candidates: ${this.getModelName(model)}: ${formatObject(findArgs)}`
);
}
const entities = await db[model].findMany(findArgs);
const updatePayload = { data: clone(args.data), select: this.queryUtils.makeIdSelection(model) };
await this.injectUpdateHierarchy(db, model, updatePayload);
const result = await Promise.all(
entities.map((entity) => {
const updateArgs = {
where: entity,
...updatePayload,
};
if (this.options.logPrismaQuery) {
this.logger.info(
`[delegate] \`updateMany\` update: ${this.getModelName(model)}: ${formatObject(updateArgs)}`
);
}
return db[model].update(updateArgs);
})
);
return { count: result.length };
}
}
private async injectUpdateHierarchy(db: CrudContract, model: string, args: any) {
const visitor = new NestedWriteVisitor(this.options.modelMeta, {
update: (model, args, _context) => {
this.injectWhereHierarchy(model, (args as any)?.where);
this.doProcessUpdatePayload(model, (args as any)?.data);
},
updateMany: async (model, args, context) => {
let simpleUpdateMany = Object.keys(args.data).every((key) => {
// check if the `data` clause involves base fields
const fieldInfo = resolveField(this.options.modelMeta, model, key);
return !fieldInfo?.inheritedFrom;
});
if (simpleUpdateMany) {
// check if the `where` clause involves base fields
simpleUpdateMany = Object.keys(args.where || {}).every((key) => {
const fieldInfo = resolveField(this.options.modelMeta, model, key);
return !fieldInfo?.inheritedFrom;
});
}
if (simpleUpdateMany) {
this.injectWhereHierarchy(model, (args as any)?.where);
this.doProcessUpdatePayload(model, (args as any)?.data);
} else {
const where = await this.queryUtils.buildReversedQuery(db, context, false, false);
await this.queryUtils.transaction(db, async (tx) => {
await this.doUpdateMany(tx, model, { ...args, where }, simpleUpdateMany);
});
delete context.parent['updateMany'];
}
},
upsert: (model, args, _context) => {
this.injectWhereHierarchy(model, (args as any)?.where);
if (args.create) {
this.doProcessCreatePayload(model, (args as any)?.create);
}
if (args.update) {
this.doProcessUpdatePayload(model, (args as any)?.update);
}
},
create: (model, args, _context) => {
if (isDelegateModel(this.options.modelMeta, model)) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
`Model "${model}" is a delegate and cannot be created directly`
);
}
this.doProcessCreatePayload(model, args);
},
createMany: (model, args, _context) => {
if (args.skipDuplicates) {
throw prismaClientValidationError(
this.prisma,
this.options.prismaModule,
'`createMany` with `skipDuplicates` set to true is not supported for delegated models'
);
}
for (const item of enumerate(args?.data)) {