We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Automatic Migrations

So we can generate migrations based on our schema, and we can use these migrations to update our database. Doing this manually is fine for now, but as our project grows, we'll want to automate this process.

Create a MigrationConfig object that stores the path to your migrations. The path to the migrations folder is the same as the out field you set in your drizzle.config.ts:

import type { MigrationConfig } from "drizzle-orm/migrator";

const migrationConfig: MigrationConfig = {
  migrationsFolder: "./src/db/migrations",
};

Create a new DBConfig type to hold the database connection string and migration configuration. Then refactor your config object so that it contains both your APIConfig and DBConfig.

All you need to do is to create a client that will run the migrations. It should be eerily similar to the db object that we use to run our queries.

import postgres from "postgres";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import { drizzle } from "drizzle-orm/postgres-js";

const migrationClient = postgres(config.db.url, { max: 1 });
await migrate(drizzle(migrationClient), config.db.migrationConfig);

Put this at the top of your src/index.ts file – after the environment variables are loaded – and the database will be up-to-date whenever you start the server.

Run and submit the CLI tests.