Skip to content

Commit ac60a6a

Browse files
authored
merge dev to main (#1166)
2 parents 242ed43 + 9f89c7e commit ac60a6a

File tree

2 files changed

+112
-15
lines changed

2 files changed

+112
-15
lines changed

packages/runtime/src/enhancements/policy/handler.ts

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
537537
let createResult = await Promise.all(
538538
enumerate(args.data).map(async (item) => {
539539
if (args.skipDuplicates) {
540-
if (await this.hasDuplicatedUniqueConstraint(model, item, db)) {
540+
if (await this.hasDuplicatedUniqueConstraint(model, item, undefined, db)) {
541541
if (this.shouldLogQuery) {
542542
this.logger.info(`[policy] \`createMany\` skipping duplicate ${formatObject(item)}`);
543543
}
@@ -565,23 +565,82 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
565565
};
566566
}
567567

568-
private async hasDuplicatedUniqueConstraint(model: string, createData: any, db: Record<string, DbOperations>) {
568+
private async hasDuplicatedUniqueConstraint(
569+
model: string,
570+
createData: any,
571+
upstreamQuery: any,
572+
db: Record<string, DbOperations>
573+
) {
569574
// check unique constraint conflicts
570575
// we can't rely on try/catch/ignore constraint violation error: https://github.com/prisma/prisma/issues/20496
571576
// TODO: for simple cases we should be able to translate it to an `upsert` with empty `update` payload
572577

573578
// for each unique constraint, check if the input item has all fields set, and if so, check if
574579
// an entity already exists, and ignore accordingly
580+
575581
const uniqueConstraints = this.utils.getUniqueConstraints(model);
582+
576583
for (const constraint of Object.values(uniqueConstraints)) {
577-
if (constraint.fields.every((f) => createData[f] !== undefined)) {
578-
const uniqueFilter = constraint.fields.reduce((acc, f) => ({ ...acc, [f]: createData[f] }), {});
584+
// the unique filter used to check existence
585+
const uniqueFilter: any = {};
586+
587+
// unique constraint fields not covered yet
588+
const remainingConstraintFields = new Set<string>(constraint.fields);
589+
590+
// collect constraint fields from the create data
591+
for (const [k, v] of Object.entries<any>(createData)) {
592+
if (v === undefined) {
593+
continue;
594+
}
595+
596+
if (remainingConstraintFields.has(k)) {
597+
uniqueFilter[k] = v;
598+
remainingConstraintFields.delete(k);
599+
}
600+
}
601+
602+
// collect constraint fields from the upstream query
603+
if (upstreamQuery) {
604+
for (const [k, v] of Object.entries<any>(upstreamQuery)) {
605+
if (v === undefined) {
606+
continue;
607+
}
608+
609+
if (remainingConstraintFields.has(k)) {
610+
uniqueFilter[k] = v;
611+
remainingConstraintFields.delete(k);
612+
continue;
613+
}
614+
615+
// check if the upstream query contains a relation field which covers
616+
// a foreign key field constraint
617+
618+
const fieldInfo = requireField(this.modelMeta, model, k);
619+
if (!fieldInfo.isDataModel) {
620+
// only care about relation fields
621+
continue;
622+
}
623+
624+
// merge the upstream query into the unique filter
625+
uniqueFilter[k] = v;
626+
627+
// mark the corresponding foreign key fields as covered
628+
const fkMapping = fieldInfo.foreignKeyMapping ?? {};
629+
for (const fk of Object.values(fkMapping)) {
630+
remainingConstraintFields.delete(fk);
631+
}
632+
}
633+
}
634+
635+
if (remainingConstraintFields.size === 0) {
636+
// all constraint fields set, check existence
579637
const existing = await this.utils.checkExistence(db, model, uniqueFilter);
580638
if (existing) {
581639
return true;
582640
}
583641
}
584642
}
643+
585644
return false;
586645
}
587646

@@ -737,8 +796,8 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
737796
if (args.skipDuplicates) {
738797
// get a reversed query to include fields inherited from upstream mutation,
739798
// it'll be merged with the create payload for unique constraint checking
740-
const reversedQuery = this.utils.buildReversedQuery(context);
741-
if (await this.hasDuplicatedUniqueConstraint(model, { ...reversedQuery, ...item }, db)) {
799+
const upstreamQuery = this.utils.buildReversedQuery(context);
800+
if (await this.hasDuplicatedUniqueConstraint(model, item, upstreamQuery, db)) {
742801
if (this.shouldLogQuery) {
743802
this.logger.info(`[policy] \`createMany\` skipping duplicate ${formatObject(item)}`);
744803
}

tests/integration/tests/enhancements/with-policy/deep-nested.test.ts

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ describe('With Policy:deep nested', () => {
5252
m2 M2? @relation(fields: [m2Id], references: [id], onDelete: Cascade)
5353
m2Id Int?
5454
55+
@@unique([m2Id, value])
56+
5557
@@allow('read', true)
5658
@@allow('create', value > 20)
5759
@@allow('update', value > 21)
@@ -164,7 +166,7 @@ describe('With Policy:deep nested', () => {
164166
m4: {
165167
create: [
166168
{ id: 'm4-1', value: 22 },
167-
{ id: 'm4-2', value: 22 },
169+
{ id: 'm4-2', value: 23 },
168170
],
169171
},
170172
},
@@ -190,11 +192,11 @@ describe('With Policy:deep nested', () => {
190192
connectOrCreate: [
191193
{
192194
where: { id: 'm4-2' },
193-
create: { id: 'm4-new', value: 22 },
195+
create: { id: 'm4-new', value: 24 },
194196
},
195197
{
196198
where: { id: 'm4-3' },
197-
create: { id: 'm4-3', value: 23 },
199+
create: { id: 'm4-3', value: 25 },
198200
},
199201
],
200202
},
@@ -327,7 +329,7 @@ describe('With Policy:deep nested', () => {
327329
await db.m4.create({
328330
data: {
329331
id: 'm4-3',
330-
value: 23,
332+
value: 24,
331333
},
332334
});
333335
const r = await db.m1.update({
@@ -446,6 +448,19 @@ describe('With Policy:deep nested', () => {
446448
myId: '1',
447449
m2: {
448450
create: {
451+
id: 1,
452+
value: 2,
453+
},
454+
},
455+
},
456+
});
457+
458+
await db.m1.create({
459+
data: {
460+
myId: '2',
461+
m2: {
462+
create: {
463+
id: 2,
449464
value: 2,
450465
},
451466
},
@@ -483,9 +498,9 @@ describe('With Policy:deep nested', () => {
483498
createMany: {
484499
skipDuplicates: true,
485500
data: [
486-
{ id: 'm4-1', value: 21 },
487-
{ id: 'm4-1', value: 211 },
488-
{ id: 'm4-2', value: 22 },
501+
{ id: 'm4-1', value: 21 }, // should be created
502+
{ id: 'm4-1', value: 211 }, // should be skipped
503+
{ id: 'm4-2', value: 22 }, // should be created
489504
],
490505
},
491506
},
@@ -495,6 +510,29 @@ describe('With Policy:deep nested', () => {
495510
});
496511
await expect(db.m4.findMany()).resolves.toHaveLength(2);
497512

513+
// createMany skip duplicate with compound unique involving fk
514+
await db.m1.update({
515+
where: { myId: '2' },
516+
data: {
517+
m2: {
518+
update: {
519+
m4: {
520+
createMany: {
521+
skipDuplicates: true,
522+
data: [
523+
{ id: 'm4-3', value: 21 }, // should be created
524+
{ id: 'm4-4', value: 21 }, // should be skipped
525+
],
526+
},
527+
},
528+
},
529+
},
530+
},
531+
});
532+
const allM4 = await db.m4.findMany({ select: { value: true } });
533+
await expect(allM4).toHaveLength(3);
534+
await expect(allM4).toEqual(expect.arrayContaining([{ value: 21 }, { value: 21 }, { value: 22 }]));
535+
498536
// updateMany, filtered out by policy
499537
await db.m1.update({
500538
where: { myId: '1' },
@@ -556,7 +594,7 @@ describe('With Policy:deep nested', () => {
556594
},
557595
},
558596
});
559-
await expect(db.m4.findMany()).resolves.toHaveLength(2);
597+
await expect(db.m4.findMany()).resolves.toHaveLength(3);
560598

561599
// deleteMany, success
562600
await db.m1.update({
@@ -573,7 +611,7 @@ describe('With Policy:deep nested', () => {
573611
},
574612
},
575613
});
576-
await expect(db.m4.findMany()).resolves.toHaveLength(1);
614+
await expect(db.m4.findMany()).resolves.toHaveLength(2);
577615
});
578616

579617
it('delete', async () => {

0 commit comments

Comments
 (0)