Skip to content

Commit

Permalink
fix: duplicated zod schema imported when there're multiple fields wit…
Browse files Browse the repository at this point in the history
…h an enum type (zenstackhq#633)
  • Loading branch information
ymc9 authored Aug 15, 2023
1 parent 4776685 commit 4b70853
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 158 deletions.
6 changes: 5 additions & 1 deletion packages/schema/src/plugins/zod/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,14 @@ async function generateModelSchema(model: DataModel, project: Project, output: s
}

// import enum schemas
const importedEnumSchemas = new Set<string>();
for (const field of fields) {
if (field.type.reference?.ref && isEnum(field.type.reference?.ref)) {
const name = upperCaseFirst(field.type.reference?.ref.name);
writer.writeLine(`import { ${name}Schema } from '../enums/${name}.schema';`);
if (!importedEnumSchemas.has(name)) {
writer.writeLine(`import { ${name}Schema } from '../enums/${name}.schema';`);
importedEnumSchemas.add(name);
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions packages/testtools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
"@zenstackhq/runtime": "workspace:*",
"@zenstackhq/sdk": "workspace:*",
"json5": "^2.2.3",
"pg": "^8.11.1",
"tmp": "^0.2.1",
"zenstack": "workspace:*"
},
"devDependencies": {
"@types/node": "^18.0.0",
"@types/pg": "^8.10.2",
"@types/tmp": "^0.2.3",
"copyfiles": "^2.4.1",
"rimraf": "^3.0.2",
Expand Down
16 changes: 16 additions & 0 deletions packages/testtools/src/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Pool } from 'pg';

const USERNAME = 'postgres';
const PASSWORD = 'abc123';

export async function createPostgresDb(db: string) {
const pool = new Pool({ user: USERNAME, password: PASSWORD });
await pool.query(`DROP DATABASE IF EXISTS "${db}";`);
await pool.query(`CREATE DATABASE "${db}";`);
return `postgresql://${USERNAME}:${PASSWORD}@localhost:5432/${db}`;
}

export async function dropPostgresDb(db: string) {
const pool = new Pool({ user: USERNAME, password: PASSWORD });
await pool.query(`DROP DATABASE IF EXISTS "${db}";`);
}
1 change: 1 addition & 0 deletions packages/testtools/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './schema';
export * from './db';
33 changes: 11 additions & 22 deletions packages/testtools/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,11 @@ export function getWorkspaceNpmCacheFolder(start: string) {
return root ? path.join(root, '.npmcache') : './.npmcache';
}

const MODEL_PRELUDE = `
function makePrelude(options: SchemaLoadOptions) {
return `
datasource db {
provider = 'sqlite'
url = 'file:./test.db'
provider = '${options.provider}'
url = '${options.dbUrl}'
}
generator js {
Expand All @@ -83,26 +84,10 @@ generator js {
plugin zod {
provider = '@core/zod'
modelOnly = true
modelOnly = ${!options.fullZod}
}
`;

const MODEL_PRELUDE_FULL_ZOD = `
datasource db {
provider = 'sqlite'
url = 'file:./test.db'
}
generator js {
provider = 'prisma-client-js'
previewFeatures = ['clientExtensions']
}
plugin zod {
provider = '@core/zod'
modelOnly = false
}
`;

export type SchemaLoadOptions = {
addPrelude?: boolean;
Expand All @@ -112,6 +97,8 @@ export type SchemaLoadOptions = {
compile?: boolean;
customSchemaFilePath?: string;
logPrismaQuery?: boolean;
provider?: 'sqlite' | 'postgresql';
dbUrl?: string;
};

const defaultOptions: SchemaLoadOptions = {
Expand All @@ -121,6 +108,8 @@ const defaultOptions: SchemaLoadOptions = {
extraDependencies: [],
compile: false,
logPrismaQuery: false,
provider: 'sqlite',
dbUrl: 'file:./test.db',
};

export async function loadSchemaFromFile(schemaFile: string, options?: SchemaLoadOptions) {
Expand Down Expand Up @@ -164,7 +153,7 @@ export async function loadSchema(schema: string, options?: SchemaLoadOptions) {
zmodelPath = path.join(projectRoot, fileName);
if (opt.addPrelude) {
// plugin need to be added after import statement
fileContent = `${fileContent}\n${opt.fullZod ? MODEL_PRELUDE_FULL_ZOD : MODEL_PRELUDE}`;
fileContent = `${fileContent}\n${makePrelude(opt)}`;
}
}

Expand All @@ -174,7 +163,7 @@ export async function loadSchema(schema: string, options?: SchemaLoadOptions) {
});
} else {
schema = schema.replaceAll('$projectRoot', projectRoot);
const content = opt.addPrelude ? `${opt.fullZod ? MODEL_PRELUDE_FULL_ZOD : MODEL_PRELUDE}\n${schema}` : schema;
const content = opt.addPrelude ? `${makePrelude(opt)}\n${schema}` : schema;
if (opt.customSchemaFilePath) {
zmodelPath = path.join(projectRoot, opt.customSchemaFilePath);
fs.mkdirSync(path.dirname(zmodelPath), { recursive: true });
Expand Down
49 changes: 10 additions & 39 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,44 +1,33 @@
import { loadSchema } from '@zenstackhq/testtools';
import { loadSchema, createPostgresDb, dropPostgresDb } from '@zenstackhq/testtools';
import path from 'path';
import { Pool } from 'pg';

const DB_NAME = 'field-comparison';

describe('WithPolicy: field comparison tests', () => {
let origDir: string;
let dbUrl: string;
let prisma: any;

const pool = new Pool({ user: 'postgres', password: 'abc123' });

beforeAll(async () => {
origDir = path.resolve('.');
});

beforeEach(async () => {
await pool.query(`DROP DATABASE IF EXISTS "${DB_NAME}";`);
await pool.query(`CREATE DATABASE "${DB_NAME}";`);
dbUrl = await createPostgresDb(DB_NAME);
});

afterEach(async () => {
process.chdir(origDir);
if (prisma) {
await prisma.$disconnect();
prisma = undefined;
}
await pool.query(`DROP DATABASE IF EXISTS "${DB_NAME}";`);
await dropPostgresDb(DB_NAME);
process.chdir(origDir);
});

it('field comparison success with input check', async () => {
const r = await loadSchema(
`
datasource db {
provider = 'postgresql'
url = 'postgres://postgres:abc123@localhost:5432/${DB_NAME}'
}
generator js {
provider = 'prisma-client-js'
}
model Model {
id String @id @default(uuid())
x Int
Expand All @@ -48,7 +37,7 @@ describe('WithPolicy: field comparison tests', () => {
@@allow('read', true)
}
`,
{ addPrelude: false }
{ provider: 'postgresql', dbUrl }
);

prisma = r.prisma;
Expand All @@ -60,15 +49,6 @@ describe('WithPolicy: field comparison tests', () => {
it('field comparison success with policy check', async () => {
const r = await loadSchema(
`
datasource db {
provider = 'postgresql'
url = 'postgres://postgres:abc123@localhost:5432/${DB_NAME}'
}
generator js {
provider = 'prisma-client-js'
}
model Model {
id String @id @default(uuid())
x Int @default(0)
Expand All @@ -78,7 +58,7 @@ describe('WithPolicy: field comparison tests', () => {
@@allow('read', true)
}
`,
{ addPrelude: false }
{ provider: 'postgresql', dbUrl }
);

prisma = r.prisma;
Expand All @@ -90,15 +70,6 @@ describe('WithPolicy: field comparison tests', () => {
it('field in operator success with input check', async () => {
const r = await loadSchema(
`
datasource db {
provider = 'postgresql'
url = 'postgres://postgres:abc123@localhost:5432/${DB_NAME}'
}
generator js {
provider = 'prisma-client-js'
}
model Model {
id String @id @default(uuid())
x String
Expand All @@ -108,7 +79,7 @@ describe('WithPolicy: field comparison tests', () => {
@@allow('read', x in y)
}
`,
{ addPrelude: false }
{ provider: 'postgresql', dbUrl }
);

prisma = r.prisma;
Expand All @@ -120,15 +91,6 @@ describe('WithPolicy: field comparison tests', () => {
it('field in operator success with policy check', async () => {
const r = await loadSchema(
`
datasource db {
provider = 'postgresql'
url = 'postgres://postgres:abc123@localhost:5432/${DB_NAME}'
}
generator js {
provider = 'prisma-client-js'
}
model Model {
id String @id @default(uuid())
x String @default('x')
Expand All @@ -138,7 +100,7 @@ describe('WithPolicy: field comparison tests', () => {
@@allow('read', x in y)
}
`,
{ addPrelude: false }
{ provider: 'postgresql', dbUrl }
);

prisma = r.prisma;
Expand Down
Loading

0 comments on commit 4b70853

Please sign in to comment.