Coder Social home page Coder Social logo

ibm / prisma-schema-transformer Goto Github PK

View Code? Open in Web Editor NEW
112.0 12.0 28.0 271 KB

Prisma ORM schema post-processor.

Home Page: https://www.npmjs.com/package/prisma-schema-transformer

License: MIT License

JavaScript 10.38% TypeScript 89.62%
prisma-schema prisma prisma2

prisma-schema-transformer's Introduction

prisma-schema-transformer

EXPERIMENTAL FOR PRISMA V3

This project utilizes the getDMMF method from @prisma/sdk to perform some post-processing work on generated Prisma schema, including the following.

  • Transform snake_case to camelCase,
  • Properly singularize or pluralize model and field name.
  • Add @updatedAt attribute to field in the event of column name is updated_at
  • Ignore models from the schema.

TODO

  • Auto generate the generator and datasource nodes.

Install

$ yarn global add prisma-schema-transformer

Usage

$ prisma-schema-transformer prisma/schema.prisma
Usage
  $ prisma-schema-transformer [options] [...args]

Specify a schema:
  $ prisma-schema-transformer ./schema.prisma

Instead of saving the result to the filesystem, you can also print it
  $ prisma-schema-transformer ./schema.prisma --print

Exclude some models from the output
  $ prisma-schema-transformer ./schema.prisma --deny knex_migrations --deny knex_migration_lock

Options:
  --print   Do not save
  --deny    Exlucde model from output
  --help    Help
  --version Version info

Motivation

Using snake_case in database and automatically transform generated Prisma schema to camelCase with @map and @@map as needed to map the new name back to the database.

There is a snippet provided by @TLadd, but I found regex a bit unreliable.

How does it work

getDMMF parses the Prisma schema file into dmmf(datamodel meta format), which we can use to do some post-processing on the Prisma internal data structure.

Deserializer

There does not seem to be a printer or a deserializer for DMMF, source. You can learn more about the implementation at deserializer.ts. It is responsible for converting a serialized Prisma schema, DMMF, back to plain text file.

It's hacky, but it works. Some test fixtures are taken from the @prisma/sdk repository for testing. We use the getDMMF method to compare the serialized structure of original and transformed Prisma schema, make sure they are identical.

Transformer

Manipulate the naming of Model and Field to follow the camelCase naming convention.

  • Model name is always singular.
  • Field name is singular by default with the execption of many-to-many relation.

License

This project is MIT licensed.

prisma-schema-transformer's People

Contributors

bathlamos avatar dependabot[bot] avatar itkach avatar michaellzc avatar reiv avatar tajnymag avatar yama-tomo avatar zyhou 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prisma-schema-transformer's Issues

`idFields` of model is undefined

I get the following error when running the script against my schema:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at /home/kpusmo/WebstormProjects/foo/node_modules/prisma-schema-transformer/dist/transformer.js:55:22
    at Object.Immer.produce (/home/kpusmo/WebstormProjects/foo/node_modules/immer/dist/immer.cjs.development.js:791:20)
    at transformModel (/home/kpusmo/WebstormProjects/foo/node_modules/prisma-schema-transformer/dist/transformer.js:53:37)
    at /home/kpusmo/WebstormProjects/foo/node_modules/prisma-schema-transformer/dist/transformer.js:83:32
    at Array.map (<anonymous>)
    at Object.dmmfModelTransformer (/home/kpusmo/WebstormProjects/foo/node_modules/prisma-schema-transformer/dist/transformer.js:83:19)
    at fixPrismaFile (/home/kpusmo/WebstormProjects/foo/node_modules/prisma-schema-transformer/dist/index.js:43:34)
    at async /home/kpusmo/WebstormProjects/foo/node_modules/prisma-schema-transformer/bin.js:56:17

My schema is:

model foo_bar {
  id      String  @id @default(uuid())
  bar_foo String
  baz     String?
}

I've added console.log(model) to transformer.js:54, and the field is actually missing from the model:

{
  name: 'foo_bar',
  isEmbedded: false,
  dbName: null,
  fields: [
    {
      name: 'id',
      kind: 'scalar',
      isList: false,
      isRequired: true,
      isUnique: false,
      isId: true,
      isReadOnly: false,
      type: 'String',
      hasDefaultValue: true,
      default: [Object],
      isGenerated: false,
      isUpdatedAt: false
    },
    {
      name: 'bar_foo',
      kind: 'scalar',
      isList: false,
      isRequired: true,
      isUnique: false,
      isId: false,
      isReadOnly: false,
      type: 'String',
      hasDefaultValue: false,
      isGenerated: false,
      isUpdatedAt: false
    },
    {
      name: 'baz',
      kind: 'scalar',
      isList: false,
      isRequired: false,
      isUnique: false,
      isId: false,
      isReadOnly: false,
      type: 'String',
      hasDefaultValue: false,
      isGenerated: false,
      isUpdatedAt: false
    }
  ],
  isGenerated: false,
  primaryKey: null,
  uniqueFields: [],
  uniqueIndexes: []
}

Am I missing something?

String[] arrays removed by transformation

Problem:

It seems that upon running npx prisma-schema-transformer, my String[] fields are being written back simply as String, which causes GraphQL queries to fail subsequently.

model App {
  app_id                   String           @id @default(dbgenerated())
  languages                String[]

  @@map("app")
}

becomes

model App {
  app_id                   String           @id @default(dbgenerated())
  languages                String

  @@map("app")
}

Error Message:

Just for reference, the error I received was:

{
  "errors": [
    {
      "message": "\nInvalid `prisma.app.findFirst()` invocation in\n/opt/app/prisma/generated/type-graphql/resolvers/crud/App/AppCrudResolver.ts:33:27\n\n\n  Attempted to serialize scalar '[String(\"EN\")]' with incompatible type 'String'",
    }
  ],
  ...
}

Workaround:

Running npx prisma introspect again helped me to write the types back as they were.
However, since they were re-added, I had to remove my knex migration tables manually.

@@index 's are removed

It seems like the transformer removes @@indexes.

model ads_clicks {
  id       Int      @default(autoincrement()) @id
  ad_id    Int?
  datetime DateTime
  @@index([ad_id], name: "IDX_BA7A601F4F34D596")
}

Transform to

model AdsClick {
  id       Int      @id @default(autoincrement())
  adId     Int?     @map("ad_id")
  datetime DateTime
  @@map("ads_clicks")
}

Every table throws error: 'error: No such argument.'

Newly installed prisma dependency and after pull from existing db

  -->  schema.prisma:188
   |
187 |
188 |   @@index([show_id], map: "place_show_id")
   |
error: No such argument.
  -->  schema.prisma:189
   |
188 |   @@index([show_id], map: "place_show_id")
189 |   @@index([tag_id], map: "place_tag_id")
   |

You could turn this into a generator

Hi @ExiaSR , this is an awesome project!

You might not be aware of it, but we have a generator architecture in Prisma, which allows you to hook into the generate step.

It might be interesting for you to do the schema transformation on every generate.

Here is an example: https://github.com/timsuchanek/minimal-generator

It could, of course, be, that you want to run prisma-schema-transformer as a one-of thing, then it doesn't make sense. But I just wanted to make you aware, that this option exists.

Unhandled Exception: Unsupporter field attribute

Given this schema:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model addresses {
  city_name     String
  id            Int           @default(autoincrement()) @id
  street_name   String
  street_number String
  zip           String
  biographies   biographies[]
}

model biographies {
  address_id Int?
  email      String?
  full_name  String
  id         Int        @default(autoincrement()) @id
  addresses  addresses? @relation(fields: [address_id], references: [id])
  users      users[]
}

model company_settings {
  id      Int    @id
  locale  String @default("en")
  logo_id Int
  name    String
  files   files  @relation(fields: [logo_id], references: [id])
}

model contract_assignees {
  contract_id Int
  user_id     Int

  @@id([user_id, contract_id])
}

model contracts {
  code                                       String
  id                                         Int    @default(autoincrement()) @id
  made_by_id                                 Int
  responsible_user_id                        Int
  users_contracts_made_by_idTousers          users  @relation("contracts_made_by_idTousers", fields: [made_by_id], references: [id])
  users_contracts_responsible_user_idTousers users  @relation("contracts_responsible_user_idTousers", fields: [responsible_user_id], references: [id])
}

model files {
  hash             String
  id               Int                @default(autoincrement()) @id
  name             String
  uploaded_by_id   Int
  users            users              @relation(fields: [uploaded_by_id], references: [id])
  company_settings company_settings[]
}

model preferences {
  id               Int     @default(autoincrement()) @id
  preferred_locale String  @default("en")
  users            users[]
}

model users {
  biography_id                                   Int
  id                                             Int         @default(autoincrement()) @id
  password_hash                                  String
  preferences_id                                 Int
  username                                       String
  biographies                                    biographies @relation(fields: [biography_id], references: [id])
  preferences                                    preferences @relation(fields: [preferences_id], references: [id])
  contracts_contracts_made_by_idTousers          contracts[] @relation("contracts_made_by_idTousers")
  contracts_contracts_responsible_user_idTousers contracts[] @relation("contracts_responsible_user_idTousers")
  files                                          files[]
}

I get this process output when trying to do anything with the above schema:

(node:18084) UnhandledPromiseRejectionWarning: Error: Unsupporter field attribute en
    at Object.default (REDACTED_PATH_TO_REPO\node_modules\prisma-schema-transformer\dist\deserializer.js:19:19)
    at REDACTED_PATH_TO_REPO\node_modules\prisma-schema-transformer\dist\deserializer.js:39:75
    at Array.map (<anonymous>)
    at handleAttributes (REDACTED_PATH_TO_REPO\node_modules\prisma-schema-transformer\dist\deserializer.js:39:43)
    at REDACTED_PATH_TO_REPO\node_modules\prisma-schema-transformer\dist\deserializer.js:53:65
    at Array.map (<anonymous>)
    at handleFields (REDACTED_PATH_TO_REPO\node_modules\prisma-schema-transformer\dist\deserializer.js:50:10)
    at deserializeModel (REDACTED_PATH_TO_REPO\node_modules\prisma-schema-transformer\dist\deserializer.js:72:3)
    at REDACTED_PATH_TO_REPO\node_modules\prisma-schema-transformer\dist\deserializer.js:82:32
    at Array.map (<anonymous>)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18084) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled
-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:18084) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the
 Node.js process with a non-zero exit code.
Done in 1.05s.

It seems the transformer fails on handling of default string values of columns.

@db.<Type> removed

Im new to Prisma so I'm not sure how this affects things, but after transformation the db specific types are not present.
Additional info: I'm using Postgres

Expected:
addressId String @id @db.Uuid @map("address_id")

Actual:
addressId String @id @map("address_id")

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.