Prisma schema

The Prisma schema file (short: schema file, Prisma schema or schema) is the main configuration file for your Prisma setup. It is typically called schema.prisma and consists of the following parts:

  • Data sources: Specify the details of the data sources Prisma should connect to (e.g. a PostgreSQL database)
  • Generators: Specifies what clients should be generated based on the data model (e.g. Prisma Client)
  • Data model definition: Specifies your application models (the shape of the data per data source) and their relations

See the Prisma schema API reference for detailed information about each section of the schema.

Whenever a prisma command is invoked, the CLI typically reads some information from the schema file, e.g.:

  • prisma generate: Reads all above mentioned information from the Prisma schema to generate the correct data source client code (e.g. Prisma Client).
  • prisma migrate save --experimental: Reads the data sources and data model definition to create a new migration.

You can also use environment variables inside the schema file to provide configuration options when a CLI command is invoked.

Example

Here is an example for a Prisma schema file that specifies a data source (PostgreSQL), a generator (Prisma Client) and a data model definition with two models (with one relation) and one enum:

datasource db {
url = env("DATABASE_URL")
provider = "postgresql"
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
email String @unique
name String?
role Role @default(USER)
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean @default(false)
title String
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
enum Role {
USER
ADMIN
}

Naming

The default name for the schema file is schema.prisma. When your schema file is named like this, the Prisma CLI will detect it automatically in the directory where you invoke the CLI command (or any of its subdirectories).

If the file is named differently, you can provide the --schema argument to the Prisma CLI with the path to the schema file, e.g.:

prisma generate --schema ./database/myschema.prisma

Syntax

The schema file is written in Prisma Schema Language (PSL). You can find a full reference for PSL in the spec.

VS Code

Syntax highlighting for PSL is available via a VS Code extension (which also lets you auto-format the contents of your Prisma schema and indicates syntax errors with red squiggly lines). Learn more about setting up Prisma in your editor.

GitHub

PSL code snippets on GitHub can be rendered with syntax highlighting as well by using the .prisma file extension or annotating fenced code blocks in Markdown with prisma:

```prisma
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
email String @unique
name String?
}
```

Prisma schema file location

The Prisma CLI looks for the Prisma schema file in the following locations, in the following order:

  1. The location specified by the --schema flag, which is available when you introspect, generate, and migrate:

    $prisma generate --schema=./alternative/schema.prisma
  2. The location specified in the package.json file (version 2.7.0 and later):

    "prisma": {
    "schema": "db/schema.prisma"
    }
  3. Default locations:

    • ./prisma/schema.prisma
    • ./schema.prisma

The Prisma CLI outputs the path of the schema file that will be used. The following example shows the terminal output for prisma introspect:

Environment variables loaded from prisma\.env
Prisma Schema loaded from prisma\schema.prisma
Introspecting based on datasource defined in prisma\schema.prisma …
✔ Introspected 4 models and wrote them into prisma\schema.prisma in 239ms
Run prisma generate to generate Prisma Client.

Using environment variables

You can use environment variables to provide configuration options when a CLI command is invoked. Environment variables allow you to:

  • Keep secrets out of the schema file
  • Improve portability of the schema file

You can use machine-specific variables, .env files, or a combination of both.

Accessing environment variables from the schema

Environment variables can be accessed using the env function:

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

In version 2.7.0 and later, you can expand variables using the format specified by dotenv-expand. This is useful when dealing with PaaS or similar products. such as Heroku):

# .env
DATABASE_URL=postgresql://test:test@localhost:5432/test
DATABASE_URL_WITH_SCHEMA=${DATABASE_URL}?schema=public

There are a few limitations with env at the moment:

  • It is not possible to use environment variables for the provider argument in datasource and generator definitions.

Using .env files

For many developer tools, it has become a good practice to define environment variables using .env files. The Prisma CLI looks for .env files, in order, in the following locations:

  1. In the root folder of your project (./.env)
  2. From the same folder as the schema specified by the --schema argument
  3. From the same folder as the schema taken from "prisma": {"schema": "/path/to/schema.prisma"} in package.json
  4. From the ./prisma folder

If a .env file is located in step #1, but additional, clashing .env variables are located in steps #2 - 4, the CLI will throw an error. For example, if you specify a DATABASE_URL variable in two different .env files, you will get the following error:

You are trying to load env variables which are already present in your project root .env
Root: C:\Prisma\Sandbox\mssql\.env
Prisma: ./prisma/.env
Env Conflicts:
DATABASE_URL
You can fix this by removing the .env file from "./prisma/.env" and move its contents to your .env file at the root "C:\Prisma\Sandbox\mssql\.env"
The following table describes where the Prisma CLI looks for the `.env` file:
**Command** | **Schema file location** | **`.env` file locations checked, in order** |
:---------------------------------------------- | :------------------------------------------------------------------------------ | :--------------------------------------------- |
`prisma [command]` | `./prisma/schema.prisma` | `./.env`<br />`./prisma/.env` |
`prisma [command] --schema=./a/b/schema.prisma` | `./a/b/schema.prisma` | `./.env`<br />`./a/b/.env`<br />`./prisma/.env` |
`prisma [command]` | `"prisma": {"schema": "/path/to/schema.prisma"}` | `.env`<br /> `./path/to/schema/.env`<br />`./prisma/.env` |
`prisma [command]` | No schema (for example, when running `prisma introspect` in an empty directory) | `./.env`<br />`./prisma/.env` |
Any environment variables defined in that `.env` file will automatically be loaded when running a Prisma CLI command.
> **Warning**: Do not commit your `.env` files into version control.
Refer to the `dotenv` documentation for information about [what happens if an environment variable is defined in two places](https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set).
#### Example: Set the `DATABASE_URL` environment variable in an `.env` file
It is common to load your database connection URL from an environment variable:
```prisma
// schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

You can set the DATABASE_URL in your .env file:

# .env
DATABASE_URL=postgresql://test:test@localhost:5432/test?schema=public

When you run a command that needs access the database defined via the datasource block (for example, prisma introspect), the Prisma CLI automatically loads the DATABASE_URL environment variables from the .env file and makes it available to the CLI.

Using environment variables in your code

If you want environment variables to be evaluated at runtime, you need to load them manually in your application code (for example, by using dotenv):

import * as dotenv from 'dotenv'
dotenv.config() // Load the environment variables
console.log(`The connection URL is ${process.env.DATABASE_URL}`)

Manage .env files manually

You can use dotenv-cli if you want to:

  • Use multiple .env files
  • Use .env files from a location that the Prisma CLI does not check by default

Via command line

  1. Install dotenv-cli:

    npm install -g dotenv-cli
  2. Create a file - for example, .env3 - in your project's root folder.

  3. To use the .env3 file, you can use dotenv when you run any Prisma command and specify which .env file to use. The following example uses a file named .env3:

    dotenv -e .env3 -- npx prisma introspect

Note: dotenv doesn't pass the flags to the Prisma command by default, this is why the command includes two dashes -- before prisma, making it possible to use flags like --force, --schema or --experimental.

Via application code

  1. Add dotenv to your project:

    npm install dotenv
  2. Create a file - for example, .env3 - in your project's root folder.

  3. To use the .env3 file, include a reference to dotenv at the top of your project's entry file.

    import { config } from 'dotenv'
    config({ path: '.env3' })

Comments

There are two types of comments that are supported in the schema file:

  • // comment: This comment is for the reader's clarity and is not present in the abstract syntax tree (AST) of the schema file.
  • /// comment: These comments will show up in the abstract syntax tree (AST) of the schema file, either as descriptions to AST nodes or as free-floating comments. Tools can then use these comments to provide additional information.

Here are some different examples:

/// This comment will get attached to the `User` node in the AST
model User {
/// This comment will get attached to the `id` node in the AST
id Int @default(autoincrement())
// This comment is just for you
weight Float /// This comment gets attached to the `weight` node
}
// This comment is just for you. It will not
// show up in the AST.
/// This is a free-floating comment that will show up
/// in the AST as a `Comment` node, but is not attached
/// to any other node. We can use these for documentation
/// in the same way that godoc.org works.
model Customer {}

Auto formatting

Similar to tools like gofmt and prettier, PSL syntax ships with a formatter for .prisma files. The formatter can be enabled in the VS Code extension.

Like gofmt and unlike prettier, there are no options for configuration here. There is exactly one way to format a prisma file.

Learn more about the formatting rules in the spec.

In this section

Edit this page on GitHub