-
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathbase.ts
More file actions
2635 lines (2354 loc) · 100 KB
/
base.ts
File metadata and controls
2635 lines (2354 loc) · 100 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
import { createId as cuid2 } from '@paralleldrive/cuid2';
import { clone, enumerate, invariant, isPlainObject } from '@zenstackhq/common-helpers';
import { default as cuid1 } from 'cuid';
import {
createQueryId,
DeleteResult,
expressionBuilder,
sql,
UpdateResult,
type Compilable,
type ExpressionBuilder,
type IsolationLevel,
type QueryResult,
type SelectQueryBuilder,
} from 'kysely';
import { nanoid } from 'nanoid';
import { match } from 'ts-pattern';
import { ulid } from 'ulid';
import * as uuid from 'uuid';
import type { BuiltinType, Expression, FieldDef } from '../../../schema';
import { ExpressionUtils, type GetModels, type ModelDef, type SchemaDef } from '../../../schema';
import type { AnyKysely } from '../../../utils/kysely-utils';
import { extractFields, fieldsToSelectObject } from '../../../utils/object-utils';
import { NUMERIC_FIELD_TYPES } from '../../constants';
import { TransactionIsolationLevel, type ClientContract, type CRUD } from '../../contract';
import type { FindArgs, SelectIncludeOmit, WhereInput } from '../../crud-types';
import {
createDBQueryError,
createInternalError,
createInvalidInputError,
createNotFoundError,
createNotSupportedError,
ORMError,
ORMErrorReason,
} from '../../errors';
import type { ToKysely } from '../../query-builder';
import {
ensureArray,
extractIdFields,
flattenCompoundUniqueFilters,
getDiscriminatorField,
getField,
getIdValues,
getManyToManyRelation,
getModel,
getRelationForeignKeyFieldPairs,
isForeignKeyField,
isRelationField,
isScalarField,
requireField,
requireIdFields,
requireModel,
} from '../../query-utils';
import { getCrudDialect } from '../dialects';
import type { BaseCrudDialect } from '../dialects/base-dialect';
import { InputValidator } from '../validator';
/**
* List of core CRUD operations. It excludes the 'orThrow' variants.
*/
export const CoreCrudOperations = [
'findMany',
'findUnique',
'findFirst',
'create',
'createMany',
'createManyAndReturn',
'update',
'updateMany',
'updateManyAndReturn',
'upsert',
'delete',
'deleteMany',
'count',
'aggregate',
'groupBy',
'exists',
] as const;
/**
* List of core CRUD operations. It excludes the 'orThrow' variants.
*/
export type CoreCrudOperations = (typeof CoreCrudOperations)[number];
/**
* List of core read operations. It excludes the 'orThrow' variants.
*/
export const CoreReadOperations = [
'findMany',
'findUnique',
'findFirst',
'count',
'aggregate',
'groupBy',
'exists',
] as const;
/**
* List of core read operations. It excludes the 'orThrow' variants.
*/
export type CoreReadOperations = (typeof CoreReadOperations)[number];
/**
* List of core write operations.
*/
export const CoreWriteOperations = [
'create',
'createMany',
'createManyAndReturn',
'update',
'updateMany',
'updateManyAndReturn',
'upsert',
'delete',
'deleteMany',
] as const;
/**
* List of core write operations.
*/
export type CoreWriteOperations = (typeof CoreWriteOperations)[number];
/**
* List of core create operations.
*/
export const CoreCreateOperations = ['create', 'createMany', 'createManyAndReturn', 'upsert'] as const;
/**
* List of core create operations.
*/
export type CoreCreateOperations = (typeof CoreCreateOperations)[number];
/**
* List of core update operations.
*/
export const CoreUpdateOperations = ['update', 'updateMany', 'updateManyAndReturn', 'upsert'] as const;
/**
* List of core update operations.
*/
export type CoreUpdateOperations = (typeof CoreUpdateOperations)[number];
/**
* List of core delete operations.
*/
export const CoreDeleteOperations = ['delete', 'deleteMany'] as const;
/**
* List of core delete operations.
*/
export type CoreDeleteOperations = (typeof CoreDeleteOperations)[number];
/**
* List of all CRUD operations, including 'orThrow' variants.
*/
export const AllCrudOperations = [...CoreCrudOperations, 'findUniqueOrThrow', 'findFirstOrThrow'] as const;
/**
* List of all CRUD operations, including 'orThrow' variants.
*/
export type AllCrudOperations = (typeof AllCrudOperations)[number];
/**
* List of all read operations, including 'orThrow' variants.
*/
export const AllReadOperations = [...CoreReadOperations, 'findUniqueOrThrow', 'findFirstOrThrow'] as const;
/**
* List of all read operations, including 'orThrow' variants.
*/
export type AllReadOperations = (typeof AllReadOperations)[number];
/**
* List of all write operations - simply an alias of CoreWriteOperations.
*/
export const AllWriteOperations = CoreWriteOperations;
/**
* List of all write operations - simply an alias of CoreWriteOperations.
*/
export type AllWriteOperations = CoreWriteOperations;
// context for nested relation operations
export type FromRelationContext = {
// the model where the relation field is defined
model: string;
// the relation field name
field: string;
// the parent entity's id fields and values
ids: any;
// for relations owned by model, record the parent updates needed after the relation is processed
parentUpdates: Record<string, unknown>;
};
export abstract class BaseOperationHandler<Schema extends SchemaDef> {
protected readonly dialect: BaseCrudDialect<Schema>;
constructor(
protected readonly client: ClientContract<Schema>,
protected readonly model: GetModels<Schema>,
protected readonly inputValidator: InputValidator<Schema>,
) {
this.dialect = getCrudDialect(this.schema, this.client.$options);
}
protected get schema() {
return this.client.$schema;
}
protected get options() {
return this.client.$options;
}
protected get kysely(): AnyKysely {
return this.client.$qb;
}
abstract handle(operation: CoreCrudOperations, args: any): Promise<unknown>;
withClient(client: ClientContract<Schema>) {
return new (this.constructor as new (...args: any[]) => this)(client, this.model, this.inputValidator);
}
// TODO: this is not clean, needs a better solution
protected get hasPolicyEnabled() {
return this.options.plugins?.some((plugin) => plugin.constructor.name === 'PolicyPlugin');
}
protected requireModel(model: string) {
return requireModel(this.schema, model);
}
protected getModel(model: string) {
return getModel(this.schema, model);
}
protected requireField(model: string, field: string) {
return requireField(this.schema, model, field);
}
protected getField(model: string, field: string) {
return getField(this.schema, model, field);
}
protected async exists(
kysely: ToKysely<Schema>,
model: GetModels<Schema>,
filter: any,
): Promise<unknown | undefined> {
return this.readUnique(kysely, model, {
where: filter,
select: this.makeIdSelect(model),
});
}
protected async existsNonUnique(kysely: ToKysely<Schema>, model: GetModels<Schema>, filter: any): Promise<boolean> {
const query = kysely
.selectNoFrom((eb) =>
eb
.exists(
this.dialect
.buildSelectModel(model, model)
.select(sql.lit(1).as('_'))
.where(() => this.dialect.buildFilter(model, model, filter)),
)
.as('$exists'),
)
.modifyEnd(this.makeContextComment({ model, operation: 'read' }));
let result: { $exists: number | boolean }[] = [];
const compiled = kysely.getExecutor().compileQuery(query.toOperationNode(), createQueryId());
try {
const r = await kysely.getExecutor().executeQuery(compiled);
result = r.rows as { $exists: number | boolean }[];
} catch (err) {
throw createDBQueryError(`Failed to execute query: ${err}`, err, compiled.sql, compiled.parameters);
}
return !!result[0]?.$exists;
}
protected async read(
kysely: AnyKysely,
model: string,
args: FindArgs<Schema, GetModels<Schema>, any, true> | undefined,
): Promise<any[]> {
// table
let query = this.dialect.buildSelectModel(model, model);
if (args) {
query = this.dialect.buildFilterSortTake(model, args, query, model);
}
// select
if (args && 'select' in args && args.select) {
// select is mutually exclusive with omit
query = this.buildFieldSelection(model, query, args.select, model);
} else {
// include all scalar fields except those in omit
query = this.dialect.buildSelectAllFields(model, query, (args as any)?.omit, model);
}
// include
if (args && 'include' in args && args.include) {
// note that 'omit' is handled above already
query = this.buildFieldSelection(model, query, args.include, model);
}
query = query.modifyEnd(this.makeContextComment({ model, operation: 'read' }));
let result: any[] = [];
const compiled = kysely.getExecutor().compileQuery(query.toOperationNode(), createQueryId());
try {
const r = await kysely.getExecutor().executeQuery(compiled);
result = r.rows;
} catch (err) {
throw createDBQueryError(`Failed to execute query: ${err}`, err, compiled.sql, compiled.parameters);
}
return result;
}
protected async readUnique(kysely: AnyKysely, model: string, args: FindArgs<Schema, GetModels<Schema>, any, true>) {
const result = await this.read(kysely, model, { ...args, take: 1 });
return result[0] ?? null;
}
private buildFieldSelection(
model: string,
query: SelectQueryBuilder<any, any, any>,
selectOrInclude: Record<string, any>,
parentAlias: string,
) {
let result = query;
for (const [field, payload] of Object.entries(selectOrInclude)) {
if (!payload) {
continue;
}
if (field === '_count') {
result = this.buildCountSelection(result, model, parentAlias, payload);
continue;
}
const fieldDef = this.requireField(model, field);
if (!fieldDef.relation) {
// scalar field
result = this.dialect.buildSelectField(result, model, parentAlias, field);
} else {
if (!fieldDef.array && !fieldDef.optional && payload.where) {
throw createInternalError(`Field "${field}" does not support filtering`, model);
}
if (fieldDef.originModel) {
result = this.dialect.buildRelationSelection(
result,
fieldDef.originModel,
field,
fieldDef.originModel,
payload,
);
} else {
// regular relation
result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
}
}
}
return result;
}
private buildCountSelection(
query: SelectQueryBuilder<any, any, any>,
model: string,
parentAlias: string,
payload: any,
) {
return query.select((eb) => this.dialect.buildCountJson(model, eb, parentAlias, payload).as('_count'));
}
protected async create(
kysely: AnyKysely,
model: string,
data: any,
fromRelation?: FromRelationContext,
creatingForDelegate = false,
returnFields?: readonly string[],
): Promise<unknown> {
const modelDef = this.requireModel(model);
// additional validations
if (modelDef.isDelegate && !creatingForDelegate) {
throw createNotSupportedError(`Model "${model}" is a delegate and cannot be created directly.`);
}
let createFields: any = {};
let updateParent: ((entity: any) => void) | undefined = undefined;
let m2m: ReturnType<typeof getManyToManyRelation> = undefined;
if (fromRelation) {
m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
if (!m2m) {
// many-to-many relations are handled after create
const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(
this.schema,
fromRelation?.model ?? '',
fromRelation?.field ?? '',
);
if (!ownedByModel) {
// assign fks from parent
const parentFkFields = await this.buildFkAssignments(
kysely,
fromRelation.model,
fromRelation.field,
fromRelation.ids,
);
Object.assign(createFields, parentFkFields);
} else {
// record parent fk update after entity is created
updateParent = (entity) => {
for (const { fk, pk } of keyPairs) {
fromRelation.parentUpdates[fk] = entity[pk];
}
};
}
}
}
// process the create and handle relations
const postCreateRelations: Record<string, object> = {};
for (const [field, value] of Object.entries(data)) {
const fieldDef = this.requireField(model, field);
if (isScalarField(this.schema, model, field) || isForeignKeyField(this.schema, model, field)) {
if (
fieldDef.array &&
value &&
typeof value === 'object' &&
'set' in value &&
Array.isArray(value.set)
) {
// deal with nested "set" for scalar lists
createFields[field] = this.dialect.transformInput(value.set, fieldDef.type as BuiltinType, true);
} else {
createFields[field] = this.dialect.transformInput(
value,
fieldDef.type as BuiltinType,
!!fieldDef.array,
);
}
} else {
const subM2M = getManyToManyRelation(this.schema, model, field);
if (!subM2M && fieldDef.relation?.fields && fieldDef.relation?.references) {
const fkValues = await this.processOwnedRelationForCreate(kysely, fieldDef, value);
for (let i = 0; i < fieldDef.relation.fields.length; i++) {
createFields[fieldDef.relation.fields[i]!] = fkValues[fieldDef.relation.references[i]!];
}
} else {
const subPayload = value;
if (subPayload && typeof subPayload === 'object') {
postCreateRelations[field] = subPayload;
}
}
}
}
// create delegate base model entity
if (modelDef.baseModel) {
const baseCreateResult = await this.processBaseModelCreate(kysely, modelDef.baseModel, createFields, model);
createFields = baseCreateResult.remainingFields;
}
const updatedData = this.fillGeneratedAndDefaultValues(modelDef, createFields);
// return id fields if no returnFields specified
returnFields = returnFields ?? requireIdFields(this.schema, model);
let createdEntity: any;
if (this.dialect.supportsReturning) {
const query = kysely
.insertInto(model)
.$if(Object.keys(updatedData).length === 0, (qb) =>
qb
// case for `INSERT INTO ... DEFAULT VALUES` syntax
.$if(this.dialect.supportsInsertDefaultValues, () => qb.defaultValues())
// case for `INSERT INTO ... VALUES ({})` syntax
.$if(!this.dialect.supportsInsertDefaultValues, () => qb.values({})),
)
.$if(Object.keys(updatedData).length > 0, (qb) => qb.values(updatedData))
.returning(returnFields as any)
.modifyEnd(
this.makeContextComment({
model,
operation: 'create',
}),
);
createdEntity = await this.executeQueryTakeFirst(kysely, query, 'create');
} else {
// Fallback for databases that don't support RETURNING (e.g., MySQL)
const insertQuery = kysely
.insertInto(model)
.$if(Object.keys(updatedData).length === 0, (qb) =>
qb
// case for `INSERT INTO ... DEFAULT VALUES` syntax
.$if(this.dialect.supportsInsertDefaultValues, () => qb.defaultValues())
// case for `INSERT INTO ... VALUES ({})` syntax
.$if(!this.dialect.supportsInsertDefaultValues, () => qb.values({})),
)
.$if(Object.keys(updatedData).length > 0, (qb) => qb.values(updatedData))
.modifyEnd(
this.makeContextComment({
model,
operation: 'create',
}),
);
const insertResult = await this.executeQuery(kysely, insertQuery, 'create');
// Build WHERE clause to find the inserted record
const idFields = requireIdFields(this.schema, model);
const idValues: Record<string, any> = {};
for (const idField of idFields) {
if (insertResult.insertId !== undefined && insertResult.insertId !== null) {
const fieldDef = this.requireField(model, idField);
if (this.isAutoIncrementField(fieldDef)) {
// auto-generated id value
idValues[idField] = insertResult.insertId;
continue;
}
}
if (updatedData[idField] !== undefined) {
// ID was provided in the insert
idValues[idField] = updatedData[idField];
} else {
throw createInternalError(
`Cannot determine ID field "${idField}" value for created model "${model}"`,
);
}
}
// for dialects that don't support RETURNING, the outside logic will always
// read back the created record, we just return the id fields here
createdEntity = idValues;
}
if (Object.keys(postCreateRelations).length > 0) {
// process nested creates that need to happen after the current entity is created
for (const [field, subPayload] of Object.entries(postCreateRelations)) {
await this.processNoneOwnedRelationForCreate(kysely, model, field, subPayload, createdEntity);
}
}
if (fromRelation && m2m) {
// connect many-to-many relation
await this.handleManyToManyRelation(
kysely,
'connect',
fromRelation.model,
fromRelation.field,
fromRelation.ids,
m2m.otherModel,
m2m.otherField,
createdEntity,
m2m.joinTable,
);
}
// finally update parent if needed
if (updateParent) {
updateParent(createdEntity);
}
return createdEntity;
}
private isAutoIncrementField(fieldDef: FieldDef) {
return (
fieldDef.default &&
ExpressionUtils.isCall(fieldDef.default) &&
fieldDef.default.function === 'autoincrement'
);
}
private async processBaseModelCreate(kysely: ToKysely<Schema>, model: string, createFields: any, forModel: string) {
const thisCreateFields: any = {};
const remainingFields: any = {};
Object.entries(createFields).forEach(([field, value]) => {
const fieldDef = this.getField(model, field);
if (fieldDef) {
thisCreateFields[field] = value;
} else {
remainingFields[field] = value;
}
});
const discriminatorField = getDiscriminatorField(this.schema, model);
invariant(discriminatorField, `Base model "${model}" must have a discriminator field`);
thisCreateFields[discriminatorField] = forModel;
// create base model entity
const baseEntity: any = await this.create(
kysely,
model as GetModels<Schema>,
thisCreateFields,
undefined,
true,
);
// copy over id fields from base model
const idValues = extractIdFields(baseEntity, this.schema, model);
Object.assign(remainingFields, idValues);
return { baseEntity, remainingFields };
}
private async buildFkAssignments(kysely: AnyKysely, model: string, relationField: string, entity: any) {
const parentFkFields: any = {};
invariant(relationField, 'parentField must be defined if parentModel is defined');
invariant(entity, 'parentEntity must be defined if parentModel is defined');
const { keyPairs } = getRelationForeignKeyFieldPairs(this.schema, model, relationField);
for (const pair of keyPairs) {
if (!(pair.pk in entity)) {
// the relation may be using a non-id field as fk, so we read in-place
// to fetch that field
const extraRead = await this.readUnique(kysely, model, {
where: entity,
select: { [pair.pk]: true },
} as any);
if (!extraRead) {
throw createInternalError(`Field "${pair.pk}" not found in parent created data`, model);
} else {
// update the parent entity
Object.assign(entity, extraRead);
}
}
Object.assign(parentFkFields, {
[pair.fk]: (entity as any)[pair.pk],
});
}
return parentFkFields;
}
private async handleManyToManyRelation<Action extends 'connect' | 'disconnect'>(
kysely: AnyKysely,
action: Action,
leftModel: string,
leftField: string,
leftEntity: any,
rightModel: string,
rightField: string,
rightEntity: any,
joinTable: string,
): Promise<Action extends 'connect' ? UpdateResult | undefined : DeleteResult | undefined> {
const sortedRecords = [
{
model: leftModel,
field: leftField,
entity: leftEntity,
},
{
model: rightModel,
field: rightField,
entity: rightEntity,
},
].sort((a, b) =>
// the implicit m2m join table's "A", "B" fk fields' order is determined
// by model name's sort order, and when identical (for self-relations),
// field name's sort order
a.model !== b.model ? a.model.localeCompare(b.model) : a.field.localeCompare(b.field),
);
const firstIds = requireIdFields(this.schema, sortedRecords[0]!.model);
const secondIds = requireIdFields(this.schema, sortedRecords[1]!.model);
invariant(firstIds.length === 1, 'many-to-many relation must have exactly one id field');
invariant(secondIds.length === 1, 'many-to-many relation must have exactly one id field');
// Prisma's convention for many-to-many: fk fields are named "A" and "B"
if (action === 'connect') {
const result = await kysely
.insertInto(joinTable as any)
.values({
A: sortedRecords[0]!.entity[firstIds[0]!],
B: sortedRecords[1]!.entity[secondIds[0]!],
} as any)
// case for `INSERT IGNORE` or `ON CONFLICT DO NOTHING` syntax
.$if(this.dialect.insertIgnoreMethod === 'onConflict', (qb) =>
qb.onConflict((oc) => oc.columns(['A', 'B'] as any).doNothing()),
)
// case for `INSERT IGNORE` syntax
.$if(this.dialect.insertIgnoreMethod === 'ignore', (qb) => qb.ignore())
.execute();
return result[0] as any;
} else {
const eb = expressionBuilder<any, any>();
const result = await kysely
.deleteFrom(joinTable as any)
.where(eb(`${joinTable}.A`, '=', sortedRecords[0]!.entity[firstIds[0]!]))
.where(eb(`${joinTable}.B`, '=', sortedRecords[1]!.entity[secondIds[0]!]))
.execute();
return result[0] as any;
}
}
private resetManyToManyRelation(kysely: AnyKysely, model: string, field: string, parentIds: any) {
invariant(Object.keys(parentIds).length === 1, 'parentIds must have exactly one field');
const parentId = Object.values(parentIds)[0]!;
const m2m = getManyToManyRelation(this.schema, model, field);
invariant(m2m, 'not a many-to-many relation');
const eb = expressionBuilder<any, any>();
return kysely
.deleteFrom(m2m.joinTable as any)
.where(eb(`${m2m.joinTable}.${m2m.parentFkName}`, '=', parentId))
.execute();
}
private async processOwnedRelationForCreate(kysely: ToKysely<Schema>, relationField: FieldDef, payload: any) {
if (!payload) {
return;
}
let result: any;
const relationModel = relationField.type as GetModels<Schema>;
for (const [action, subPayload] of Object.entries<any>(payload)) {
if (!subPayload) {
continue;
}
switch (action) {
case 'create': {
const created = await this.create(kysely, relationModel, subPayload);
// extract id fields and return as foreign key values
result = getIdValues(this.schema, relationField.type, created);
break;
}
case 'connect': {
const referencedPkFields = relationField.relation!.references!;
invariant(referencedPkFields, 'relation must have fields info');
const extractedFks = extractFields(subPayload, referencedPkFields);
if (Object.keys(extractedFks).length === referencedPkFields.length) {
// payload contains all referenced pk fields, we can
// directly use it to connect the relation
result = extractedFks;
} else {
// read the relation entity and fetch the referenced pk fields
const relationEntity = await this.readUnique(kysely, relationModel, {
where: subPayload,
select: fieldsToSelectObject(referencedPkFields) as any,
});
if (!relationEntity) {
throw createNotFoundError(
relationModel,
`Could not find the entity to connect for the relation "${relationField.name}"`,
);
}
result = relationEntity;
}
break;
}
case 'connectOrCreate': {
const found = await this.exists(kysely, relationModel, subPayload.where);
if (!found) {
// create
const created = await this.create(kysely, relationModel, subPayload.create);
result = getIdValues(this.schema, relationField.type, created);
} else {
// connect
result = found;
}
break;
}
default:
throw createInvalidInputError(`Invalid relation action: ${action}`);
}
}
return result;
}
private async processNoneOwnedRelationForCreate(
kysely: AnyKysely,
contextModel: string,
relationFieldName: string,
payload: any,
parentEntity: any,
) {
const relationFieldDef = this.requireField(contextModel, relationFieldName);
const relationModel = relationFieldDef.type as GetModels<Schema>;
const fromRelationContext: FromRelationContext = {
model: contextModel,
field: relationFieldName,
ids: parentEntity,
parentUpdates: {},
};
for (const [action, subPayload] of Object.entries<any>(payload)) {
if (!subPayload) {
continue;
}
switch (action) {
case 'create': {
// create with a parent entity
for (const item of enumerate(subPayload)) {
await this.create(kysely, relationModel, item, fromRelationContext);
}
break;
}
case 'createMany': {
invariant(relationFieldDef.array, 'relation must be an array for createMany');
await this.createMany(
kysely,
relationModel,
subPayload as { data: any; skipDuplicates: boolean },
false,
fromRelationContext,
);
break;
}
case 'connect': {
await this.connectRelation(kysely, relationModel, subPayload, fromRelationContext);
break;
}
case 'connectOrCreate': {
for (const item of enumerate(subPayload)) {
const found = await this.exists(kysely, relationModel, item.where);
if (!found) {
await this.create(kysely, relationModel, item.create, fromRelationContext);
} else {
await this.connectRelation(kysely, relationModel, found, fromRelationContext);
}
}
break;
}
default:
throw createInvalidInputError(`Invalid relation action: ${action}`);
}
}
}
protected async createMany<
ReturnData extends boolean,
Result = ReturnData extends true ? unknown[] : { count: number },
>(
kysely: ToKysely<Schema>,
model: GetModels<Schema>,
input: { data: any; skipDuplicates?: boolean },
returnData: ReturnData,
fromRelation?: FromRelationContext,
fieldsToReturn?: readonly string[],
): Promise<Result> {
if (!input.data || (Array.isArray(input.data) && input.data.length === 0)) {
// nothing todo
return returnData ? ([] as Result) : ({ count: 0 } as Result);
}
const modelDef = this.requireModel(model);
const relationKeyPairs: { fk: string; pk: string }[] = [];
if (fromRelation) {
const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(
this.schema,
fromRelation.model,
fromRelation.field,
);
if (ownedByModel) {
throw createInvalidInputError('incorrect relation hierarchy for createMany', model);
}
relationKeyPairs.push(...keyPairs);
}
let createData = enumerate(input.data).map((item) => {
const newItem: any = {};
for (const [name, value] of Object.entries(item)) {
const fieldDef = this.requireField(model, name);
invariant(!fieldDef.relation, 'createMany does not support relations');
newItem[name] = this.dialect.transformInput(value, fieldDef.type as BuiltinType, !!fieldDef.array);
}
if (fromRelation) {
for (const { fk, pk } of relationKeyPairs) {
newItem[fk] = fromRelation.ids[pk];
}
}
return this.fillGeneratedAndDefaultValues(modelDef, newItem);
});
if (!this.dialect.supportsDefaultAsFieldValue) {
// if the dialect doesn't support `DEFAULT` as insert field values,
// we need to double check if data rows have mismatching fields, and
// if so, make sure all fields have default value filled if not provided
const allPassedFields = createData.reduce((acc, item) => {
Object.keys(item).forEach((field) => {
if (!acc.includes(field)) {
acc.push(field);
}
});
return acc;
}, [] as string[]);
for (const item of createData) {
if (Object.keys(item).length === allPassedFields.length) {
continue;
}
for (const field of allPassedFields) {
if (!(field in item)) {
const fieldDef = this.requireField(model, field);
if (
fieldDef.default !== undefined &&
fieldDef.default !== null &&
typeof fieldDef.default !== 'object'
) {
item[field] = this.dialect.transformInput(
fieldDef.default,
fieldDef.type as BuiltinType,
!!fieldDef.array,
);
}
}
}
}
}
if (modelDef.baseModel) {
if (input.skipDuplicates) {
// TODO: simulate createMany with create in this case
throw createNotSupportedError('"skipDuplicates" options is not supported for polymorphic models');
}
// create base hierarchy
const baseCreateResult = await this.processBaseModelCreateMany(
kysely,
modelDef.baseModel,
createData,
!!input.skipDuplicates,
model,
);
createData = baseCreateResult.remainingFieldRows;
}
const query = kysely
.insertInto(model)
.values(createData)
.$if(!!input.skipDuplicates, (qb) =>
qb
// case for `INSERT ... ON CONFLICT DO NOTHING` syntax
.$if(this.dialect.insertIgnoreMethod === 'onConflict', () => qb.onConflict((oc) => oc.doNothing()))
// case for `INSERT IGNORE` syntax
.$if(this.dialect.insertIgnoreMethod === 'ignore', () => qb.ignore()),
)
.modifyEnd(
this.makeContextComment({
model,
operation: 'create',
}),
);
if (!returnData) {
const result = await this.executeQuery(kysely, query, 'createMany');
return { count: Number(result.numAffectedRows) } as Result;
} else {
fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
if (this.dialect.supportsReturning) {
const result = await query.returning(fieldsToReturn as any).execute();
return result as Result;
} else {
// Fallback for databases that don't support RETURNING (e.g., MySQL)
// For createMany without RETURNING, we can't reliably get all inserted records
// especially with auto-increment IDs. The best we can do is return the count.
// If users need the created records, they should use multiple create() calls
// or the application should query after insertion.
throw createNotSupportedError(
`\`createManyAndReturn\` is not supported for ${this.dialect.provider}. ` +
`Use multiple \`create\` calls or query the records after insertion.`,
);
}
}
}
private async processBaseModelCreateMany(
kysely: ToKysely<Schema>,
model: string,
createRows: any[],
skipDuplicates: boolean,
forModel: GetModels<Schema>,
) {