iiian / prisma-case-format Goto Github PK
View Code? Open in Web Editor NEWGive your introspected schema.prisma sane naming conventions
Home Page: https://www.npmjs.com/package/prisma-case-format
License: ISC License
Give your introspected schema.prisma sane naming conventions
Home Page: https://www.npmjs.com/package/prisma-case-format
License: ISC License
Hello folks, hope you're doing well
Thanks for creating this community tool, that's awesome! I tried this tool but I'm getting errors with fields that includes numbers, e.g:
address_line_1
address_line_2
and after executing this tool, this is generating this:
addressLine_1
addressLine_2
but I was expecting this other format instead:
addressLine1
addressLine2
Is there any option to fix this bug?
I'm trying to fix this issue from a fork in the meantime, but any help is really appreciated! <3
While testing the implementation for #45 I encountered an issue for fields mapping to a DB column with a different name (not just a different case):
@@ -73,121 +73,121 @@ model User {
/// Table required by Next-Auth
model VerificationToken {
/// Columns required by Next-Auth
identifier String
token String @unique
- expires DateTime @map("expires_at") @db.Timestamptz(3)
+ expires DateTime @db.Timestamptz(3)
@@unique([identifier, token])
@@map("verification_tokens")
}
Here the DB column is expires_at
, and the field next-auth expects is expires
, but prisma-case-format
removes the @map
.
I wouldn't expect prisma-case-format
to do anything if the name of the field is different (not just in case, but in content) to the @map
value.
Interested to see how you feel about this and if you have ideas or suggestions on how to deal with that situation.
Line 50 in fbdb03f
Call ConventionStore.fromFile
without options.usesNextAuth
.
prisma-case-format/src/convention-store.ts
Lines 84 to 92 in fbdb03f
prisma-case-format/src/convention-store.ts
Lines 99 to 104 in fbdb03f
fromFile
and fromCon
do not process usesNextAuth
. I can create a PR if possible.
Hey!
I have the following schema:
model ConfirmRequest {
type ConfirmType @map("type")
...
@@map("confirm_requests")
}
enum ConfirmType {
EMAIL
PHONE
@@map("confirm_type")
}
And I'm running CLI tool as follows:
prisma-case-format --file ./prisma/schema.prisma --map-table-case snake,plural
So, I need to keep enum
@@map
singular. Do we have any way to achieve that?
In other words, I need to manage enum
transform options separately from table ones.
Thanks for great tool!
My enums defined in PascalCase
are not mapped when running prisma-case-format --map-field-case snake --map-table-case snake
Using the example from the readme:
model house_rating {
id Int @id @default(autoincrement())
house_id String
house house @relation(fields: [house_id], references: [id])
...
}
...
model house {
id String @id @default(uuid())
house_rating house_rating[]
...
}
After running prisma-case-format --field-case pascal
I get this:
Model HouseRating {
@@map("house_rating")
Id Int @map("id") @id @default(autoincrement())
HouseId String @map("house_id")
House House @relation(fields: [HouseId], references: [Id])
}
Model House {
@@map("house")
Id String @map("id") @id @default(uuid())
HouseRating HouseRating[]
}
Issues:
model
keyword has been converted to pascal case Model
Love the tool, but concerned about using it with no LICENSE
file in the root. You do specify license: "ISC"
in package.json
but would feel better with a LICENSE in the repo. Would be grateful if you added it
Here's the text of the ISC license
Copyright <YEAR> <OWNER>
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Original model:
model Model {
id String @id @default(cuid())
columnsSingular String[]
}
After running prisma-case-format -p
:
model Model {
id String @id @default(cuid())
columnsSingulars String[] @map("columns_singulars")
}
The only way to prevent this is by adding the following to .prisma-case-format
:
Model:
field:
columnsSingular: disable
But this disables all formatting on the following field as I'd like to keep the option of mapping e.g. camel case to snake case.
Something like this would be great:
Model:
field:
columnsSingular: 'pluralize=disable'
Hi,
Is it possible to format array fields as plural names?
Kind regards,
Not clear what this error refers to, but it does not format the file.
Hi,
I found this same issue in the library https://github.com/loop-payments/prisma-lint
and that's why I tried this one for case linting of tables and field for a model of MongoDB in Prisma.
The issue is the following:
In MongoDB the id field is not Snake or Pascal case. The id
is named by convention _id
.
Example in Prisma Documentation:
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
slug String @unique
title String
body String
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
comments Comment[]
}
So the issue is that the prisma-case-format
is removing the @map("_id")
from the Prisma schema, when the idea is to keep that special mapping from id
to _id
.
This is a general rule and not something that should be added as an override table by table.
Thanks!
Hi man! Such a great work for this, had been using for a while, but I have some question and maybe some feedback,
// @case-ignore
so that it not modifying that case, why tho? because in some cases, i have table like this: SomethingABC
, if i format that, it'd be SomethingAbc
, but in this case, the ABC should still an uppercaseWhile both of these has a workaround, like just rename and remove it, but if it can be implemented in the code, it'd help the formatting more easier and faster.
Thank you!
Hi, thanks for making this handy utility! I'm working on something connecting to an existing postgres db with Prisma, and the convention used is plural table names. So what I'd like is an option to pluralize table names, so that the following prisma schema
model User {
id @id @default(autoincrement())
}
is converted to
model User {
id @id @default(autoincrement())
@@map("users")
}
instead of the existing behavior
model User {
id @id @default(autoincrement())
@@map("user")
}
Is this possible? Thanks again!
@iiian
Thanks for creating this awesome CLI utility!
It would be great if you could add the ability to skip the format of a line with a specific comment!
(ex. like prettier's // prettier-ignore
comment. https://prettier.io/docs/en/ignore.html
If there are no problems, I will create a PR!
Currently, the only way to use this tool is through the CLI.
While I love your package and I find it great, I would love for my prisma schema file to be auto formatted using this tool instead of prisma's internal formatter.
Currently, the way to automatically format the file is basically using the extension Gruntfuggly.triggertaskonsave
and run a silent task on save that runs the command. It works, but it is clunky.
I think it might be possible to create an extension that calls a cli function, but having a proper function that transforms the input into an output (without directly writing to the filesystem) would allow for the vscode.languages.registerDocumentFormattingEditProvider
to work its magic using the buffer rather than going through a terminal command.
Basically, move pretty much all of the run()
function of the cli.ts
file into an exported package, run THAT function from the cli.ts
file, which would allow this package to be used programmatically.
I'm actually quite interested in making a vscode extension that uses this package for formatting prisma files, so if you don't have the time to do it yourself, I might pick this one up :)
Prisma cli uses the schema location specified by prisma.schema
in package.json
by default, so it doesn't need to be specified explicitely when running commands. It'd be very convenient if prisma-case-format would behave in the same way.
package.json
{
"prisma": {
"schema": "models/prisma/schema.prisma"
},
}
Input
@@index([test_field(length: 191)], map: "test_field_index")
Should be converted to
@@index([testField(length: 191)], map: "test_field_index")
Hi,
On 1.3.0, prisma-case-format
command seems not installed. It was OK on 1.3.0-beta.0
Thanks,
Field name got formatted, but no @map
is generated
Original
article_id Int
Expected to be converted to
articleId Int @map("article_id")
Actual result
articleId Int
Hello, thanks for creating this awesome cli utility!
I tried applying it to a prisma schema and noticed enums are made PascalCase, however the next time I run npx prisma db pull
, those enums are reverted to snake_case
. A workaround that works is to run this utility following each time we introspect.
Our workflow is database-first using the instrospection workflow, so we make migrations separately in SQL and pull those changes into the prisma schema, so we run prisma db pull
often.
I think having this util add @@map('enum_name')
will cause the enum naming to stick as PascalCase when running prisma db pull
Would like to have an option to disable the linter for some models.
Proposal:
/* prisma-case-format-disable */
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refreshToken String?
accessToken String?
expiresAt Int?
tokenType String?
scope String?
idToken String?
sessionState String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
}
/* prisma-case-format-enable */
I came across this issue when wanting to use next-auth
For node projects and especially for those of us who want to keep the number dotfiles low, it'd be lovely if the config could alternatively be specified in package.json
. As long as Prisma doesn't offer case mapping natively, the existing config key could be used.
Use the same keys as in the .prisma-case-format
file:
{
"prisma": {
"schema": "./path/to/schema.prisma",
"seed": "tsx ./path/to/seed.ts",
"mapCase": {
"default": "table=pascal; mapTable=snake,plural; field=pascal; mapField=snake; enum=pascal; mapEnum=snake",
"override": {
"LegacyThing": "disable"
}
}
}
}
For the minimalist. This would assume Prisma's as well as DB naming conventions and just specifies the target format…
{
"prisma": {
"schema": "./path/to/schema.prisma",
"seed": "tsx ./path/to/seed.ts",
"mapCase": "snake"
},
}
…and would be equivalent to the following configs:
{
"prisma": {
"mapCase": {
"table": "snake,plural",
"field": "snake",
"enum": "snake"
}
}
}
{
"prisma": {
"mapCase": {
"table": {
"from": "pascal",
"to": "snake",
"inflect": "plural"
},
"field": {
"from": "camel",
"to": "snake"
},
"enum": {
"from": "pascal",
"to": "snake"
}
}
}
}
Prisma will sometimes represent columns as Unsupported
if the data type can not be matched up to a Prisma type. Reference here: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#unsupported
Unsupported can optionally include the name of the unsupported type with this syntax:
model Star {
id Int @id @default(autoincrement())
circle_value Unsupported("circle")?
}
However, using the --map-table-case
option with an annotated Unsupported value (("circle")
) results in output like this:
model Star {
id Int @id @default(autoincrement())
circleValue Unsupported @map("circle_value")("circle")?
@@map("stars")
}
Command I am running:
npx prisma-case-format --map-table-case=snake,plural
The Prisma formatter does not only format the schema file, but also does maintenance work on it, such as adding missing relations maps to models that specifies relations.
Currently, if there is a missing relation, this packages formats the fields, tables, etc. as per the configuration, and then formats the file using prisma's formatSchema
util, which adds the relations that are not necessarily formatted as per this package's configuration, leading the user to need to run this tool again.
Lines 36 to 43 in fbdb03f
If I fully depend on default config file with custom file
, it doesn't work.
Running the tool with prisma-case-format --file prisma/schema.prisma --pluralize
it doesn't map after the first table. Here's the source prisma schema:
generator client {
provider = "prisma-client-js"
output = "../node_modules/@generated/read"
previewFeatures = ["views"]
}
generator typegraphql {
provider = "typegraphql-prisma"
}
datasource db {
provider = "postgres"
url = env("DB_URL")
}
model goose_db_version {
id Int @id @default(autoincrement())
version_id BigInt
is_applied Boolean
tstamp DateTime? @default(now()) @db.Timestamp(6)
}
view accounts {
id String @unique @db.Uuid
created_at DateTime? @db.Timestamp(6)
name String?
updated_at DateTime? @db.Timestamp(6)
owned_by String? @db.Uuid
users users?
}
And the result of a dry run (which also matches running normally)
generator client {
provider = "prisma-client-js"
output = "../node_modules/@generated/read"
previewFeatures = ["views"]
}
generator typegraphql {
provider = "typegraphql-prisma"
}
datasource db {
provider = "postgres"
url = env("DB_URL")
}
model GooseDbVersion {
id Int @id @default(autoincrement())
versionId BigInt @map("version_id")
isApplied Boolean @map("is_applied")
tstamp DateTime? @default(now()) @db.Timestamp(6)
@@map("goose_db_version")
}
view accounts {
id String @unique @db.Uuid
created_at DateTime? @db.Timestamp(6)
name String?
updated_at DateTime? @db.Timestamp(6)
owned_by String? @db.Uuid
users users?
}
You can see from the output above that after goose_db_version
the tool ceases to convert.
Describe your request
This library does a great job at a one time conversion, however I would like to use it to maintain consistency within my schema.
For example, say I want to maintain pascalCase for columns, but always map them to snake.
model Account {
id String @id @default(cuid())
userId String
firstName String? @map("first_name") @db.Text
}
If you run prisma-case-format
nothing will change
Proposed behaviour
With the --map-field-case=snake --map-table-case=snake
flags, the schema will change. Now it is checking that each column correctly maps to the desired case.
model Account {
id String @id @default(cuid())
userId String @map("user_id")
firstName String? @map("first_name") @db.Text
@@map("account")
}
Workarounds
I tried doing two conversions, eg converting to snake and then pascal, however this created duplicate @map
on each column
This is a fantastic tool, thank you so much for making it.
It worked perfectly on our fields and model names but we did notice that it renamed our enums without creating @@map
statements so the next prisma migrate dev
tried to create a migration to rename them in the source database.
enum education_level_type {
BEGINNER
INTERMEDIATE
ADVANCED
@@schema("public")
}
became:
enum EducationLevelType {
BEGINNER
INTERMEDIATE
ADVANCED
@@schema("public")
}
Should have been:
enum EducationLevelType {
BEGINNER
INTERMEDIATE
ADVANCED
@@map("education_level_type")
@@schema("public")
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.