Skip to content

Commit a5c110b

Browse files
authored
fix: don't import unused enum when generating policy guards (#686)
1 parent 7a04ce5 commit a5c110b

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

packages/schema/src/plugins/access-policy/policy-guard-generator.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
DataModelAttribute,
44
DataModelField,
55
DataModelFieldAttribute,
6+
Enum,
67
Expression,
78
MemberAccessExpr,
89
Model,
@@ -39,6 +40,7 @@ import {
3940
getPrismaClientImportSpec,
4041
hasAttribute,
4142
hasValidationAttributes,
43+
isEnumFieldReference,
4244
isForeignKeyField,
4345
isFromStdlib,
4446
isFutureExpr,
@@ -87,7 +89,7 @@ export default class PolicyGenerator {
8789

8890
// import enums
8991
const prismaImport = getPrismaClientImportSpec(model, output);
90-
for (const e of model.declarations.filter((d) => isEnum(d))) {
92+
for (const e of model.declarations.filter((d) => isEnum(d) && this.isEnumReferenced(model, d))) {
9193
sf.addImportDeclaration({
9294
namedImports: [{ name: e.name }],
9395
moduleSpecifier: prismaImport,
@@ -155,6 +157,20 @@ export default class PolicyGenerator {
155157
}
156158
}
157159

160+
private isEnumReferenced(model: Model, decl: Enum): unknown {
161+
return streamAllContents(model).some((node) => {
162+
if (isDataModelField(node) && node.type.reference?.ref === decl) {
163+
// referenced as field type
164+
return true;
165+
}
166+
if (isEnumFieldReference(node) && node.target.ref?.$container === decl) {
167+
// enum field is referenced
168+
return true;
169+
}
170+
return false;
171+
});
172+
}
173+
158174
private getPolicyExpressions(target: DataModel | DataModelField, kind: PolicyKind, operation: PolicyOperationKind) {
159175
const attributes = target.attributes as (DataModelAttribute | DataModelFieldAttribute)[];
160176
const attrName = isDataModel(target) ? `@@${kind}` : `@${kind}`;
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { loadSchema } from '@zenstackhq/testtools';
2+
3+
describe('Regression: issue 674', () => {
4+
it('regression', async () => {
5+
await loadSchema(
6+
`
7+
model Foo {
8+
id Int @id
9+
}
10+
11+
enum MyUnUsedEnum { ABC CDE @@map('my_unused_enum') }
12+
`,
13+
{ provider: 'postgresql', dbUrl: 'env("DATABASE_URL")', pushDb: false }
14+
);
15+
});
16+
});

0 commit comments

Comments
 (0)