Skip to content

Commit

Permalink
fix: incorrect reverse query built for to-many relation
Browse files Browse the repository at this point in the history
  • Loading branch information
ymc9 committed Nov 8, 2023
1 parent ac3206b commit d2ad3a5
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/runtime/src/enhancements/policy/policy-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@ export class PolicyUtil {
if (backLinkField.isArray && !mutating) {
// many-side of relationship, wrap with "some" query
currQuery[currField.backLink] = { some: { ...visitWhere } };
currQuery = currQuery[currField.backLink].some;
} else {
const fkMapping = where && backLinkField.isRelationOwner && backLinkField.foreignKeyMapping;

Expand Down Expand Up @@ -553,8 +554,8 @@ export class PolicyUtil {
// preserve the original structure
currQuery[currField.backLink] = { ...visitWhere };
}
currQuery = currQuery[currField.backLink];
}
currQuery = currQuery[currField.backLink];
currField = field;
}
}
Expand Down
71 changes: 71 additions & 0 deletions tests/integration/tests/regression/issue-811.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { loadSchema } from '@zenstackhq/testtools';

describe('Regression: issue 811', () => {
it('regression', async () => {
const { prisma, enhance } = await loadSchema(
`
model Membership {
id String @id @default(uuid())
role String @default('STANDARD')
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId String @unique
@@auth
@@allow('create,update,delete', auth().role == 'ADMIN')
@@allow('update', auth() == this)
@@allow('read', true)
}
model User {
id String @id @default(uuid())
profile Profile @relation(fields: [profileId], references: [id], onDelete: Cascade)
profileId String @unique
memberships Membership[]
@@allow('create,update,delete', auth().role == 'ADMIN')
@@allow('update', id == auth().userId)
@@allow('read', true)
}
model Profile {
id String @id @default(uuid())
firstName String
users User[]
@@allow('create,update,delete', auth().role == 'ADMIN')
@@allow('update', users?[id == auth().userId])
@@allow('read', true)
}
`
);

const r = await prisma.user.create({
data: {
profile: {
create: { firstName: 'Tom' },
},
memberships: {
create: { role: 'STANDARD' },
},
},
include: {
profile: true,
memberships: true,
},
});

const membershipId = r.memberships[0].id;
const userId = r.id;
const db = enhance({ id: membershipId, role: 'ADMIN', userId });

const r1 = await db.membership.update({
data: {
role: 'VIP',
user: { update: { data: { profile: { update: { data: { firstName: 'Jerry' } } } } } },
},
include: { user: { include: { profile: true } } },
where: { id: membershipId },
});

expect(r1.role).toBe('VIP');
expect(r1.user.profile.firstName).toBe('Jerry');
});
});

0 comments on commit d2ad3a5

Please sign in to comment.