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 dev
: 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)
- A data model definition with two models (with one relation) and one
enum
- A native data type attribute on the
title
field of thePost
model because it does not use the defaultString
mapping (varchar(255)
instead oftext
)
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 @uniquename String?role Role @default(USER)posts Post[]}model Post {id Int @id @default(autoincrement())createdAt DateTime @default(now())updatedAt DateTime @updatedAtpublished Boolean @default(false)title String @db.VarChar(255)author User? @relation(fields: [authorId], references: [id])authorId Int?}enum Role {USERADMIN}
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).
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
:
```prismamodel User {id Int @id @default(autoincrement())createdAt DateTime @default(now())email String @uniquename String?}```
Prisma schema file location
The Prisma CLI looks for the Prisma schema file in the following locations, in the following order:
The location specified by the
--schema
flag, which is available when youintrospect
,generate
, andmigrate
:$prisma generate --schema=./alternative/schema.prismaThe location specified in the
package.json
file (version 2.7.0 and later):"prisma": {"schema": "db/schema.prisma"}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/.envPrisma Schema loaded from prisma/schema.prismaIntrospecting based on datasource defined in prisma/schema.prisma …✔ Introspected 4 models and wrote them into prisma/schema.prisma in 239msRun 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):
# .envDATABASE_URL=postgresql://test:test@localhost:5432/testDATABASE_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 indatasource
andgenerator
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:
- In the root folder of your project (
./.env
) - From the same folder as the schema specified by the
--schema
argument - From the same folder as the schema taken from
"prisma": {"schema": "/path/to/schema.prisma"}
inpackage.json
- 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:
Error: There is a conflict between env vars in .env and prisma/.envConflicting env vars:DATABASE_URLWe suggest to move the contents of prisma/.env to .env to consolidate your env vars.
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 ./prisma/.env |
prisma [command] --schema=./a/b/schema.prisma | ./a/b/schema.prisma | ./.env ./a/b/.env ./prisma/.env |
prisma [command] | "prisma": {"schema": "/path/to/schema.prisma"} | .env ./path/to/schema/.env ./prisma/.env |
prisma [command] | No schema (for example, when running prisma introspect in an empty directory) | ./.env ./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.
Example: Set the DATABASE_URL
environment variable in an .env
file
It is common to load your database connection URL from an environment variable:
// schema.prismadatasource db {provider = "postgresql"url = env("DATABASE_URL")}
You can set the DATABASE_URL
in your .env
file:
# .envDATABASE_URL=postgresql://test:test@localhost:5432/test?schema=public
When you run a command that needs access to 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 variablesconsole.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
Install
dotenv-cli
:npm install -g dotenv-cliCreate a file - for example,
.env3
- in your project's root folder.To use the
.env3
file, you can usedotenv
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
--
beforeprisma
, making it possible to use flags like--force
,--schema
or--preview-feature
.
Via application code
Add dotenv to your project:
npm install dotenvCreate a file - for example,
.env3
- in your project's root folder.To use the
.env3
file, include a reference todotenv
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 ASTmodel User {/// This comment will get attached to the `id` node in the ASTid Int @default(autoincrement())// This comment is just for youweight 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.