Git Product home page Git Product logo

prisma-case-format's People

Contributors

ahto avatar ebramanti avatar iiian avatar jrdnull avatar kolpakov-p avatar yiy0ung avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

prisma-case-format's Issues

Camel case not working as expected for fields with numbers

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

Retain @map annotations for fields with distinct DB column names

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.

Invalid `--uses-next-auth` cli option

const [conv, conv_err] = ConventionStore.fromFile(resolve(options.configFile));

Call ConventionStore.fromFile without options.usesNextAuth.

public static fromFile(path: string, usesNextAuth?: boolean): [ConventionStore?, Error?] {
if (!existsSync(path)) {
if (path === resolve(DEFAULT_PRISMA_CASE_FORMAT_FILE_LOCATION)) {
return ConventionStore.fromConf({});
}
return [, new Error('file does not exist: ' + path)]
}
return ConventionStore.fromConfStr(readFileSync(path).toString());
}

public static fromConf(conf: ConventionFile): [ConventionStore?, Error?] {
if (conf.uses_next_auth) {
conf = imbueWithNextAuth(conf);
}
const children: Record<string, ConventionStore> = {};
for (const entity_name in conf.override) {

fromFile and fromCon do not process usesNextAuth. I can create a PR if possible.

Any way to keep enums singular when table names are plural?

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!

Missing converting @relation fields

Hello, you've done a great job with this lib. I run it in my project, but I realize that it doesn't change the relations, as shown in the example below.
Do you have in mind upgrading this library?

image

Enums are not mapped

My enums defined in PascalCase are not mapped when running prisma-case-format --map-field-case snake --map-table-case snake

Broken output for pascal case

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:

  • incorrect indendation & formatting
  • the model keyword has been converted to pascal case Model

Add a LICENSE file

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.

Add option to ignore pluralize option per field

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'

MongoDB ID field issue

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:

https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema-typescript-mongodb

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!

Ignore Command & Excluding Enums

Hi man! Such a great work for this, had been using for a while, but I have some question and maybe some feedback,

  1. Can you make a ignore command like @ts-ignore command, maybe like // @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 uppercase
  2. Can you provide an option to ignore enum formatting? Because if i have a running table with already defined enum, then the enum is mapped to different name/format, when i try to push to the db, it shows a prompt to delete all data because the renamed enum is not detected as renamed, but as a new enum list

While 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!

Pluralize table names

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!

Allow programmatic usage of library (example: vscode formatter extension)

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 :)

[Feature request] Obtain default schema location from package.json

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"
  },
}

Some `@@index` cannot be converted

Input

@@index([test_field(length: 191)], map: "test_field_index")

Should be converted to

@@index([testField(length: 191)], map: "test_field_index")

enum definitions do not stay PascalCase when running 'prisma db pull'

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

Possibility to skip some models

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

[Feature request] Enable configuration via package.json

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.

Simple approach

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"
      }
    } 
  }
}

More sophisitcated and DRYer

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"
      }
    }
  }
}

`Unsupported` fields are parsed incorrectly

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

Run Prisma's `formatSchema` before AND after the case formatting to automatically add missing relations

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.

Doesn't map after first table

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.

Add --map-field-case / --map-table-case option

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

No @@map created for enums

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")
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.