How to create data migrations with Drizzle ORM?

4.3k Views Asked by At

I can use Drizzle kit to create and run schema changes to my database, but I don't know how to make data migrations with it. I've got experience from Django where you can manually create migration files which also support custom Python code. There you can run whatever code/SQL etc. to insert data in to the db. It also makes sure that the (data) migration is being run only once.

How can I achieve this with Drizzle? The drizzle-kit generate:pg checks only for schema changes so I can't add only data with it.

2

There are 2 best solutions below

1
On

you probably got this resolved but you need to run this script

node -r esbuild-register src/db/index.ts

and in the index.ts file, have somethine like this :

import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';

console.log(process.env.DATABASE_URL);
const connectionString = process.env.DATABASE_URL || '';
const migrationsClient = postgres(connectionString, {
    max: 1,
});
const db = drizzle(migrationsClient);
migrate(db, { migrationsFolder: 'drizzle' });

2
On

Try this from the doc.

drizzle-kit generate:pg --custom