From ca2a314a927053703e4dbc76542499159b8bf6a8 Mon Sep 17 00:00:00 2001 From: Yiming Date: Mon, 26 Feb 2024 17:03:41 -0800 Subject: [PATCH] fix: foreign key constraint ambiguity in generated delegate prisma schema (#1060) --- .../src/plugins/prisma/schema-generator.ts | 5 ++ .../with-delegate/regressions.test.ts | 53 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 tests/integration/tests/enhancements/with-delegate/regressions.test.ts diff --git a/packages/schema/src/plugins/prisma/schema-generator.ts b/packages/schema/src/plugins/prisma/schema-generator.ts index ed997ed51..9a8ccb0eb 100644 --- a/packages/schema/src/plugins/prisma/schema-generator.ts +++ b/packages/schema/src/plugins/prisma/schema-generator.ts @@ -456,6 +456,11 @@ export class PrismaSchemaGenerator { new PrismaFieldAttribute('@relation', [ new PrismaAttributeArg('fields', args), new PrismaAttributeArg('references', args), + // generate a `map` argument for foreign key constraint disambiguation + new PrismaAttributeArg( + 'map', + new PrismaAttributeArgValue('String', `${relationField.name}_fk`) + ), ]) ); } else { diff --git a/tests/integration/tests/enhancements/with-delegate/regressions.test.ts b/tests/integration/tests/enhancements/with-delegate/regressions.test.ts new file mode 100644 index 000000000..77166e275 --- /dev/null +++ b/tests/integration/tests/enhancements/with-delegate/regressions.test.ts @@ -0,0 +1,53 @@ +import { loadSchema } from '@zenstackhq/testtools'; + +describe('Regression tests', () => { + it('FK Constraint Ambiguity', async () => { + const schema = ` + model User { + id String @id @default(cuid()) + name String + + userRankings UserRanking[] + userFavorites UserFavorite[] + } + + model Entity { + id String @id @default(cuid()) + name String + type String + userRankings UserRanking[] + userFavorites UserFavorite[] + + @@delegate(type) + } + + model Person extends Entity { + } + + model Studio extends Entity { + } + + + model UserRanking { + id String @id @default(cuid()) + rank Int + + entityId String + entity Entity @relation(fields: [entityId], references: [id], onUpdate: NoAction) + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction) + } + + model UserFavorite { + id String @id @default(cuid()) + + entityId String + entity Entity @relation(fields: [entityId], references: [id], onUpdate: NoAction) + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction) + } + `; + + await loadSchema(schema, { pushDb: false, provider: 'postgresql' }); + }); +});