Database Overview

By default, Blitz uses Prisma 2 which is a strongly typed database client.

Prisma 2 is not required for Blitz. You can use anything you want, such as Mongo, TypeORM, etc.

Read the Prisma documentation here

Add a Database Table

  1. Open db/schema.prisma and add your model(s) like as follows:
model Project {
id Int @default(autoincrement()) @id
name String
tasks Task[]
}
model Task {
id Int @default(autoincrement()) @id
name String
project Project @relation(fields: [projectId], references: [id])
projectId Int
}

If you need,

reference the Prisma Schema documentation

  1. Then run blitz db migrate in your terminal to apply the changes
  2. Now you can import db from db/index.ts and create a model like this:
    • db.project.create({data: {name: 'Hello'}})

Switch to PostgreSQL

By default, a Blitz app is created with a local SQLite database. If you want to use PostgreSQL instead, you need to perform the following steps:

  1. Open db/schema.prisma and change the db provider value from "sqlite" to "postgres" as follows:
datasource db {
provider = "postgres"
url = env("DATABASE_URL")
}
  1. In .env.local, change DATABASE_URL. For convenience, there is a commented-out PostgreSQL DATABASE_URL there already. Depending on your setup, you may need to modify the URL.
  2. Run blitz db migrate. This command will create the database (if it does not already exist) and tables based on your schema.

Run PostgreSQL database with docker-compose

One way to get a PostgreSQL database on your machine is to run PostgreSQL inside a docker container.

  1. Create a docker-compose.yml file inside the root of your project with the following content
version: "3.7"
services:
db:
image: postgres:latest
volumes:
- data:/var/lib/postgresql/data
env_file: ./.env.local #Here we are using the already existing .env.local file
ports:
- "5432:5432"
volumes:
data:
  1. Inside your .env.local file add 3 new environment variables which are required by docker
POSTGRES_USER=your_user
POSTGRES_PASSWORD=your_password
POSTGRES_DB=your_database_name

Given these values your

DATABASE_URL should look like this postgresql://your_user:your_password@localhost:5432/your_database_name

  1. Modify your package.json to run the database before the start of Blitz
"scripts": {
"start": "docker-compose up -d && blitz start",
}
  1. Run blitz db migrate to get your new database to the latest version of your migrations
Idea for improving this page?Edit it on GitHub
Bytes Newsletter