How to split Prisma Model into separate file?
Asked Answered
S

6

18

I'm learning Prisma ORM from video tutorials and official docs. They are explain and write All model code in one file called schema.prisma. It's ok but, when application grow it became messy. So, how should I separate my Model definition into separate file?

Sanctified answered 17/2, 2022 at 18:34 Comment(0)
S
2

Starting from Prisma 5.15 this can be done without any external tools, please see the following blog post.

Sample project

Briefly, all you need to do is:

  1. In your schema.prisma file - make sure you have this feature enabled as follows:

    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["prismaSchemaFolder"]
    }
    
  2. Create a dir named schema under your prisma directory

  3. Move your schema.prisma file into that directory. You should now be able to create more .prisma files in there and define your models. It all gets hooked up automatically, no need to import anything.

Silvas answered 7/7 at 13:8 Comment(0)
M
10

At this point in time Prisma doesn't support file segmentation. I can recommend 3 solutions though.

Option 1: Prismix

Prismix utilizes models and enums to create relations across files for your Prisma schema via a prismix configuration file.

{
  "mixers": [
    {
        "input": [
            "base.prisma",
            "./modules/auth/auth.prisma", 
            "./modules/posts/posts.prisma",
        ],
        "output": "prisma/schema.prisma"
    }
  ]
}

Placing this inside of a prismix.config.json file which will define how you'd like to merge your Prisma segmentations.

Option 2: Schemix

Schemix Utilizes Typescript configurations to handle schema segmenting.

For example:

// _schema.ts
import { createSchema } from "schemix";

export const PrismaSchema = createSchema({
  datasource: {
    provider: "postgresql",
    url: {
      env: "DATABASE_URL"
    },
  },
  generator: {
    provider: "prisma-client-js",
  },
});

export const UserModel = PrismaSchema.createModel("User");

import "./models/User.model";

PrismaSchema.export("./", "schema");

Inside of User.model

// models/User.model.ts

import { UserModel, PostModel, PostTypeEnum } from "../_schema";

UserModel
  .string("id", { id: true, default: { uuid: true } })
  .int("registrantNumber", { default: { autoincrement: true } })
  .boolean("isBanned", { default: false })
  .relation("posts", PostModel, { list: true })
  .raw('@@map("service_user")');

This will then generate your prisma/schema.prisma containing your full schema. I used only one database as an example (taken from documentation) but you should get the point.

Option 3: Cat -> Generate

Segmenting your schema into chunk part filenames and run:

cat *.part.prisma > schema.prisma
yarn prisma generate

Most of these if not all of them are referenced here in the currently Open issue regarding support for Prisma schema file segmentation https://github.com/prisma/prisma/issues/2377

Microsporangium answered 29/6, 2022 at 3:0 Comment(0)
R
4

This is not yet possible with Prisma. See this outstanding issue for possible workarounds https://github.com/prisma/prisma/issues/2377.

Reply answered 17/2, 2022 at 23:7 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Vally
P
4

prisma-import is a relatively recent solution and, in my opinion, the best one. It has its own branch of the Prisma VSCode extension for a nice workflow, using import statements analogous to JS imports.

Perspective answered 7/6, 2023 at 10:43 Comment(0)
B
2

You can merge all schemas into one before generating

yarn add -g glob

// package.json
"scripts": {
  "prisma-concat": "npx ts-node prisma/concat-schemas.ts && npx prisma format",
  "generate": "yarn prisma-concat && npx prisma generate",
}
// connect-db.prisma

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

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
// prisma/concat-schemas.ts

import { appendFile, readFile, writeFile } from 'fs/promises'
import { glob } from 'glob'

const start = async () => {
  const schemaFile = 'prisma/schema.prisma'
  const connectFile = 'prisma/connect-db.prisma'
  const models = await glob('src/**/*.prisma')
  const files = [connectFile, ...models]

  await writeFile(schemaFile, '')

  await Promise.all(
    files.map(async (path) => {
      const content = await readFile(path)
      return appendFile(schemaFile, content.toString())
    }),
  )
}
start()

And run yarn generate

Bakker answered 5/5, 2023 at 13:23 Comment(0)
S
2

Starting from Prisma 5.15 this can be done without any external tools, please see the following blog post.

Sample project

Briefly, all you need to do is:

  1. In your schema.prisma file - make sure you have this feature enabled as follows:

    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["prismaSchemaFolder"]
    }
    
  2. Create a dir named schema under your prisma directory

  3. Move your schema.prisma file into that directory. You should now be able to create more .prisma files in there and define your models. It all gets hooked up automatically, no need to import anything.

Silvas answered 7/7 at 13:8 Comment(0)
L
1

Since Prisma v5.15 it is possible to split your schema into multiple files:

https://www.prisma.io/blog/organize-your-prisma-schema-with-multi-file-support

As I know it is currently in preview feature (10.07.2024)

Loose answered 10/7 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.