Git Product home page Git Product logo

prisma-case-format's Introduction

prisma-case-format

prisma introspect names its model 1:1 with your database's conventions. Most of the time that is probably fine, however you may want or need different conventions in the generated client library. prisma-case-format makes it simple and direct to get the case conventions you want, applied across an entire schema.prisma with optional overrides per model or field.

Use Cases

As a one-time migration assistant

Did prisma introspect on your huge database schema mis-case all your tables & fields? Is it wrecking your hope of using duck-types? Use --dry-run in combination with --(map)?-(table|field|enum)-case to figure out which case conventions are correct for your project. Once things look correct, drop the flag to save changes to the specified --file, which is your local root schema.prisma by default.

As a dedicated linter for your schema.prisma

prisma-case-format aims to be idempotent, so you can use it to confirm that case conventions in your schema.prisma have not accidentally drifted. prisma-case-format can be applied on-commit or on-push, either in a git commit-hook package or as a CI/CD step. Use --dry-run to diff changes with the original file, or backup the original and compare to the edit.

With NextAuth.js

If your team is using NextAuth.js, you may have encountered an issue where prisma-case-format steam rolls the strict data contract expected by the NextAuth.js integration. Specify the --uses-next-auth flag in order to protect your NextAuth.js tables from your specified conventions.

With varying conventions

If you inherited or were forced to produce a database schema that has deviations in case conventions, prisma-case-format can ensure these conventions remain stable. See the config file section below.

Usage

❯ prisma-case-format --help
Usage: prisma-case-format [options]

Give your schema.prisma sane naming conventions

Options:
  -f, --file <file>                cwd-relative path to `schema.prisma` file (default: "schema.prisma")
  -c, --config-file <cfgFile>      cwd-relative path to `.prisma-case-format` config file (default: ".prisma-case-format")
  -D, --dry-run                    print changes to console, rather than back to file (default: false)
  --table-case <tableCase>         case convention for table names (SEE BOTTOM) (default: "pascal")
  --field-case <fieldCase>         case convention for field names (default: "camel")
  --enum-case <enumCase>           case convention for enum names. In case of not declared, uses value of “--table-case”. (default: "pascal")
  --map-table-case <mapTableCase>  case convention for @@map() annotations (SEE BOTTOM)
  --map-field-case <mapFieldCase>  case convention for @map() annotations
  --map-enum-case <mapEnumCase>    case convention for @map() annotations of enums.  In case of not declared, uses value of “--map-table-case”.
  -p, --pluralize                  optionally pluralize array type fields (default: false)
  --uses-next-auth                 guarantee next-auth models (Account, User, Session, etc) uphold their data-contracts
  -V, --version                    hint: you have v2.1.0
  -h, --help                       display help for command
-------------------------
Supported case conventions: ["pascal", "camel", "snake"].
Additionally, append ',plural' after any case-convention selection to mark case convention as pluralized.
> For instance:
  --map-table-case=snake,plural

will append `@@map("users")` to `model User`.
Append ',singular' after any case-convention selection to mark case convention as singularized.
> For instance, 
  --map-table-case=snake,singular

will append `@@map("user")` to `model Users`

Deviant case conventions altogether:
> If one or more of your models or fields needs to opt out of case conventions, either to be a fixed name or to disable it,
use the `.prisma-case-format` file and read the documentation on "deviant name mappings".

Example

// schema.prisma before
...
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[]
  ...
}
...
❯ prisma-case-format
✨ Done.
// schema.prisma after
...
model HouseRating {
  id       Int    @id @default(autoincrement())
  houseId  String @map("house_id")
  house    House  @relation(fields: [houseId], references: [id])
  ...

  @@map("house_rating")
}
...
model House {
  id           String        @id @default(uuid())
  houseRating HouseRating[]
  ...

  @@map("house")
}
...

Drift Protection

prisma-case-format lets you manage three case conventions: table, field, and enum.

table

model Example { // <- controlled by `--table-case`
  id     String @id
  value1 String @map("value_1")
  @@map("example") // <- controlled by `--map-table-case`
}

Table conventions are controlled by the --table-case & --map-table-case flags. --table-case specifies the case convention for the models in the generated prisma client library. --map-table-case will manage the database name case convention. table args manage models & views.

field

model Example {
  id     String @id
  // r-- controlled by `--field-case`
  // |                   r-- controlled by `--map-field-case`
  // v                   v
  value1 String @map("value_1")
}

Field conventions are controlled by the --field-case & --map-field-case flags. --field-case specifies the case convention for the fields in models within the generated prisma client library. --map-field-case will manage the case convention for the field in the database. field args do not apply to enums.

enum

enum Example { // <- controlled by  --enum-case
  Value1
  Value2
  @@map("example") // <- controlled by  --map-enum-case
}

Enum conventions are controlled by the --enum-case & --map-enum-case flags. --enum-case specifies the case convention for the enums in the generated prisma client library. --map-enum-case will manage the case convention for the enum within the database. enum args do not apply to enum values, just the model & database names.

Config file

prisma-case-format supports a config file, which primarily exists as a means to override case conventions per model or per field. This can be especially useful if you are coming from an existing database that doesn't have perfect naming convention consistency. For example, some of your model fields are snake_case, others are camelCase.

By default, this file is located at .prisma-case-format. The file is expected to be yaml internally. The following section details the config file format.

Config file format

Property: default?: string:

An alternative to specifying the commandline arguments. The format is a simple ;-delimited list, white space allowed.

Example:
default: 'table=pascal; mapTable=snake; field=pascal; mapField=snake; enum=pascal; mapEnum=pascal'
uses_next_auth: false

Property: override?: Dictionary<string, { default?: string, field?: Field }>

Type: Field=Dictionary<string, string>

Controls overrides on a per-model & per-field basis. Works for models, views and enums, in the same scope as the table/field/enum argument groups when running in commandline mode. Each key in override & subkey in field is allowed to be a regex, in which case it will attempt to match based on the specified pattern. This can be useful if you have several fields with prefixes or suffixes.

Example
default: 'table=pascal; mapTable=snake; field=pascal; mapField=snake; enum=pascal; mapEnum=pascal'
override: 
  MyTable: 
    # don't fret about case convention here; 
    # prisma-case-format considers "MyTable" to be equivalent to "my_table" & "myTable"
    default: 'table=snake;mapTable=camel;field=snake;mapField=snake;enum=snake;mapEnum=snake'
    field:
      # same here. this is equivalent to "foo_field_on_my_table"
      fooFieldOnMyTable: 'field=pascal;mapField=pascal'
      'my_prefix.*': 'mapField=pascal;' # inherits field=snake from `MyTable.default`

Results in:

model my_table {
  id                String @id
  FooFieldOnMyTable Integer
  my_prefix_prop_a  Json       @map("MyPrefixPropA")

  @@map("myTable")
}

Disabling case convention management

The .prisma-case-format file supports specifying that a particular model or field has its case convention management "disabled". This is achieved by setting the key under override or subkey under field to 'disable'.

Example:
default: ...
override:
  mYTaBlE: 'disable' # skip convention management for this table
  ...
  YourTable:
    default: '...'
    field:
      unmanaged_property: 'disable' # skip convention management for this field

Results in:

model mYTaBlE {
  nowican                       String  @id
  cAnFAlL_iNtO_UtTeR__DiSrePaiR String  @map("lol")
  iN_T0T4L_p34C3                Integer @map("great")

  @map("myspace")
}

The other tables surrounding mYTaBlE will remain managed.

Deviant name mappings

In some cases, some users will want to let certain model or field names deviate out of using case-conventions. Primarily, this is useful if you're inheriting ill-named tables in an at least partialy database-first workflow. Overriding case-convention use on a specific target name can be achieved in a .prisma-case-format file by using the syntax map(Table|Field|Enum)=!<name>, where <name> is your precise case-sensitive name that you want to map.

Example
default: ...
override:
  MyAmazingModel:
    default: 'mapTable=!Amaze_o'
    field:
      fuzz: 'mapField=!fizz_buzz'
  MySuperDuperEnum:
    default: 'mapTable=!myenum'

Results in:

model MyAmazingModel {
  id Int @id
  fuzz String @map("fizz_buzz")

  @@map("Amaze_o")
}

enum MySuperDuperEnum {
  Opt1
  Opt2

  @@map("myenum")
}

Property: uses_next_auth?: boolean

If =true, then the models added by NextAuth.js will not have their case conventions rewritten by user's selected case conventions, preserving the expected contract. If you are not using NextAuth.js, it is suggested to keep this unspecified or false. This property is equivalent to the following configuration:

uses_next_auth: false
default: ...
override:
  Account:
    default: 'table=pascal; mapTable=pascal;'
    field:
      id:                'field=camel; mapField=camel'
      userId:            'field=camel; mapField=camel'
      type:              'field=camel; mapField=camel'
      provider:          'field=camel; mapField=camel'
      providerAccountId: 'field=camel; mapField=camel'
      refresh_token:     'field=snake; mapField=snake'
      access_token:      'field=snake; mapField=snake'
      expires_at:        'field=snake; mapField=snake'
      token_type:        'field=snake; mapField=snake'
      scope:             'field=snake; mapField=snake'
      id_token:          'field=snake; mapField=snake'
      session_state:     'field=snake; mapField=snake'
      user:              'field=snake; mapField=snake'
  Session:
    default: 'table=pascal; mapTable=pascal; field=camel; mapField=camel'
  User:
    default: 'table=pascal; mapTable=pascal; field=camel; mapField=camel'
  VerificationToken:
    default: 'table=pascal; mapTable=pascal; field=camel; mapField=camel'

Note that if uses_next_auth: true and your overrides section contains conflicting specifications for any of the above model names (Account, Session, User, or VerificationToken), uses_next_auth will blow away your configuration rules for those models and use the above rules.

Pluralization

Supply the -p or --pluralize argument to get array pluralizations.

❯ prisma-case-format -p
✨ Done.
// schema.prisma after pluralization
...
model House {
  ...
  houseRatings HouseRating[]
  ownerContacts String[] @map("owner_contact")
  ...
}
...

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

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

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.

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

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!

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

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!

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.

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.

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!

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'

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

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

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

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

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.

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

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!

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

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.

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

`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

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

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

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.