diff --git a/packages/schema/src/plugins/access-policy/policy-guard-generator.ts b/packages/schema/src/plugins/access-policy/policy-guard-generator.ts index 6cd602ea6..9acb3f37c 100644 --- a/packages/schema/src/plugins/access-policy/policy-guard-generator.ts +++ b/packages/schema/src/plugins/access-policy/policy-guard-generator.ts @@ -3,6 +3,7 @@ import { DataModelAttribute, DataModelField, DataModelFieldAttribute, + Enum, Expression, MemberAccessExpr, Model, @@ -39,6 +40,7 @@ import { getPrismaClientImportSpec, hasAttribute, hasValidationAttributes, + isEnumFieldReference, isForeignKeyField, isFromStdlib, isFutureExpr, @@ -87,7 +89,7 @@ export default class PolicyGenerator { // import enums const prismaImport = getPrismaClientImportSpec(model, output); - for (const e of model.declarations.filter((d) => isEnum(d))) { + for (const e of model.declarations.filter((d) => isEnum(d) && this.isEnumReferenced(model, d))) { sf.addImportDeclaration({ namedImports: [{ name: e.name }], moduleSpecifier: prismaImport, @@ -155,6 +157,20 @@ export default class PolicyGenerator { } } + private isEnumReferenced(model: Model, decl: Enum): unknown { + return streamAllContents(model).some((node) => { + if (isDataModelField(node) && node.type.reference?.ref === decl) { + // referenced as field type + return true; + } + if (isEnumFieldReference(node) && node.target.ref?.$container === decl) { + // enum field is referenced + return true; + } + return false; + }); + } + private getPolicyExpressions(target: DataModel | DataModelField, kind: PolicyKind, operation: PolicyOperationKind) { const attributes = target.attributes as (DataModelAttribute | DataModelFieldAttribute)[]; const attrName = isDataModel(target) ? `@@${kind}` : `@${kind}`; diff --git a/tests/integration/tests/regression/issue-674.test.ts b/tests/integration/tests/regression/issue-674.test.ts new file mode 100644 index 000000000..db8be80d7 --- /dev/null +++ b/tests/integration/tests/regression/issue-674.test.ts @@ -0,0 +1,16 @@ +import { loadSchema } from '@zenstackhq/testtools'; + +describe('Regression: issue 674', () => { + it('regression', async () => { + await loadSchema( + ` +model Foo { + id Int @id +} + +enum MyUnUsedEnum { ABC CDE @@map('my_unused_enum') } + `, + { provider: 'postgresql', dbUrl: 'env("DATABASE_URL")', pushDb: false } + ); + }); +});