Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

List enum values should be typed as strings #108

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/angry-rivers-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"prisma-kysely": minor
---

Make enum array values actually be strings
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haha, please update this so it mentions that this might have breaking behavior for people that have added their own array parsers etc.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Will do

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,6 @@
],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true
}
},
"packageManager": "[email protected]+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove this :D

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will remove, was added automatically by corepack. Worth noting though that locking down the package manager (and subsequently having corepack automatically use the right package manager version) is not a bad idea - perhaps we can re-add in another PR?

}
15 changes: 13 additions & 2 deletions src/__test__/e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,27 @@ test(
await fs.writeFile(
"./prisma/schema.prisma",
`datasource db {
provider = "sqlite"
url = "file:./dev.db"
provider = "postgresql"
url = "env(DATABASE_URL)"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this shouldn't actually work in CI since we're not running a PG server there. Either we skip this in the e2e test or we need to set up a PG server to test against. The server URL should be hard-coded in the test as well so it's deterministic.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it - the reason I changed it is because enum arrays are not supported in SQLite so prisma wouldn't generate the schema during the test run. Will have more of a think about this. Perhaps skipping it would be ok

}

generator kysely {
provider = "node ./dist/bin.js"
}

enum TestEnum {
FOO
BAR
}

model TestUser {
id String @id
name String
age Int
rating Float
updatedAt DateTime
sprockets Sprocket[]
abc TestEnum[]
}

model Sprocket {
Expand All @@ -66,6 +72,9 @@ test(
B: string;
};`)
).toBeTruthy();

expect(generatedSource.includes(`abc: EnumArray<TestEnum>;`)).toBeTruthy();

expect(
generatedSource.includes("_SprocketToTestUser: SprocketToTestUser")
).toBeTruthy();
Expand Down Expand Up @@ -164,8 +173,10 @@ test(
const typeFile = await fs.readFile("./prisma/generated/types.ts", {
encoding: "utf-8",
});

expect(typeFile).not.toContain("export const");
expect(typeFile).toContain(`import type { TestEnum } from "./enums";`);
expect(typeFile.includes(`abc: TestEnum`)).toBeTruthy();

const enumFile = await fs.readFile("./prisma/generated/enums.ts", {
encoding: "utf-8",
Expand Down
4 changes: 3 additions & 1 deletion src/helpers/generateFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export const generateFile = (
export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>
? ColumnType<S, I | undefined, U>
: ColumnType<T, T | undefined, T>;
export type Timestamp = ColumnType<Date, Date | string, Date | string>;`;
export type Timestamp = ColumnType<Date, Date | string, Date | string>;
export type EnumArrayInner<T extends string, All extends string> = T extends infer Single extends string ? T | \`\${Single},\${Exclude<All, Single>}\` : never
export type EnumArray<T extends string> = '{}' | \`{\${EnumArrayInner<T, T>}}\`;`;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

having this always would throw ts error for unused variable, maybe would be good to add this conditionaly.


if (withEnumImport) {
const enumImportStatement = `import type { ${withEnumImport.names.join(
Expand Down
39 changes: 39 additions & 0 deletions src/helpers/generateModel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,42 @@ test("it respects camelCase option", () => {
userName: string | null;
};`);
});

test("it respects enum array values", () => {
const model = generateModel(
{
name: "User",
fields: [
{
name: "permissions",
isId: false,
isGenerated: false,
kind: "enum",
type: "UserPermissions",
hasDefaultValue: false,
isList: true,
isReadOnly: false,
isRequired: true,
isUnique: false,
},
],
primaryKey: null,
uniqueFields: [],
uniqueIndexes: [],
dbName: null,
},
{
databaseProvider: "postgresql",
fileName: "env(DATABASE_URL)",
enumFileName: "",
camelCase: true,
readOnlyIds: false,
}
);

const source = stringifyTsNode(model.definition);

expect(source).toEqual(`export type User = {
permissions: EnumArray<UserPermissions>;
};`);
});
23 changes: 18 additions & 5 deletions src/helpers/generateModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,29 @@ export const generateModel = (model: DMMF.Model, config: Config) => {
const dbName = typeof field.dbName === "string" ? field.dbName : null;

if (field.kind === "enum") {
const type = field.isList
? ts.factory.createTypeReferenceNode(
ts.factory.createIdentifier("EnumArray"),
[
ts.factory.createTypeReferenceNode(
ts.factory.createIdentifier(field.type),
undefined
),
]
)
: ts.factory.createTypeReferenceNode(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this ts.factory.createTypeReferenceNode( can also be reused above to improve readability.

ts.factory.createIdentifier(field.type),
undefined
);

return generateField({
isId: field.isId,
name: normalizeCase(dbName || field.name, config),
type: ts.factory.createTypeReferenceNode(
ts.factory.createIdentifier(field.type),
undefined
),
type,
nullable: !field.isRequired,
generated: isGenerated,
list: field.isList,
// Enum list values are handled as strings, so we don't need to wrap them in a list
list: false,
documentation: field.documentation,
config,
});
Expand Down
Loading