Hasibur Rahman
Hasibur Rahman

Reputation: 873

How to split Prisma Model into separate file?

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?

Upvotes: 21

Views: 27263

Answers (6)

profidash_98
profidash_98

Reputation: 349

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)

Upvotes: 3

Stas Parshin
Stas Parshin

Reputation: 1693

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.

Upvotes: 8

marc-eggers
marc-eggers

Reputation: 51

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.

Upvotes: 5

Kiritushka
Kiritushka

Reputation: 1140

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

Upvotes: 3

Ryan Dennler
Ryan Dennler

Reputation: 279

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

Upvotes: 12

Austin Crim
Austin Crim

Reputation: 1277

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

Upvotes: 4

Related Questions