Schema Migrations with Drizzle
Drizzle is a TypeScript ORM that supports Postgres, MySQL, and SQLite. It also has a CLI, drizzle-kit
, for managing migrations and few other things.
This guide will show you how to use Drizzle Kit CLI to manage your schema migrations. We are going to assume that you already have a project set up with your
favorite Typescript framework.
Start from example project
Clone our example project and install dependencies:
This will install drizzle-kit
, drizzle-orm
, dotenv
, and pg-node
- all of which are needed for this guide. pg-node
can be replaced with another postgres client like postgres.js
.
To run this example, you’ll need a .env file with a DATABASE_URL environment variable set to a postgres database. You can copy the connection string from your Nile database home page.
Configure Drizzle
Drizzle kit is configured via a drizzle.config.ts
file, which you can find in the root of the example project.
Here’s an example drizzle.config.ts
file. You’ll need to set:
- The
schema
field to the path to your schema file - The
out
field to the path where you want to store your migrations - The
dialect
field topostgresql
for Nile databases - The
dbCredentials
field with your database credentials
Define Your Schema
In code-first schema management, you define your schema as Typescript objects, and then use the Drizzle Kit CLI to generate migrations.
Create your schema in src/db/schema.ts
. Note that we include the built-in tenants
table that Nile automatically provisions:
Generate and Run Migrations
Generate your first migration using Drizzle Kit:
You should see output like:
Then run the migration:
Seed and Query Data
Now you can write code to insert and query data. Here’s an example (src/index.ts
):
Run the example:
You should see output showing the created tenant and todo:
Make Schema Changes
To add new columns, update your schema file. For example, to add a due date:
Generate and run a new migration:
This will generate a migration file like: