CHAPTER 2Prisma Schema
The schema is stored in prisma/schema.prisma
, and has 3 sections:
datasource
: which database type and URL to connect to.generator
: one or more generators (including theprisma-client-js
, which is the default).model
: the data model, comprised of all entity definitions, along with their relations.
The Datasource
The datasource
section includes the provider
, and url
, which select which database to use and what is its connection URL.
datasource db {
provider = "postgres"
url = "postgresql://user:passwd@host:port/db?schema=public"
}
Value | Database |
---|---|
"sqlite" | SQLite |
"postgres" | PostgreSQL |
"mysql" | MySQL |
"sqlserver" | SQL Server |
"cockroachdb" | CockroachDB |
"mongodb" | MongoDB |
Environment Variables
Usually we don't want to reveal sensitive information, so the url
can be taken from an environtment variable by using the env(...)
function:
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
SQLite
For SQLite, the URL is actually a file path:
datasource db {
provider = "mongodb"
url = "file:../dev.db"
}
Generators
The generator
section specifies one or more generators, which produce code of any kind taking the schema as input. They can be thought as "compilers" for the schema.
generator client {
provider = "prisma-client-js"
}
The provider
property defines which type of generator is used (currently only prisma-client-js
is available). But many other community-made generators exist.
For instance, to produce DBML output you could install a package called prisma-dbml-generator
, and then add an extra generator
section:
generator dbml {
provider = "prisma-dbml-generator"
}
And it will produce a schema.dbml
file in the prisma/dbml
directory.
The output
property defines which directory to save the output to (the default value for the Prisma Client is typically good enough).
Introspection
If you project didn't start with Prisma, you can still use it since Prisma can read your tables and generate the code for you.
If you have configured a datasource
that points to an already created Database, simply doing:
bunx prisma db pull
will connect to the database, pull the information and construct a viable schema.prisma
from that. It is not perfect, but it works in most cases.