Table of Contents

<--   Back

Seeding Database With Drizzle ORM


Database

This post assume using PostgreSQL for database, check orm.drizzle.team/docs/overview for more information how to connnect to your database.

Setup

Dependencies

npm i drizzle-orm pg dotenv
npm i -D drizzle-kit @types/pg esbuild-register @faker-js/faker

You can replace esbuild-register to tsx for running TypeScript without compile to JavaScript, more information in Scripts section.

Environment Variables

.env.development
DATABASE_URL=postgres://user:pass@127.0.0.1:5432/db

Drizzle Config

drizzle.config.ts
import type { Config } from "drizzle-kit";
import * as dotenv from "dotenv";
dotenv.config({ path: "./.env.development" });
 
if (!("DATABASE_URL" in process.env))
	throw new Error("DATABASE_URL not found on .env.development");
 
export default {
	schema: "./src/db/schema.ts",
	out: "./src/db/migrations",
	driver: "pg",
	dbCredentials: {
		connectionString: process.env.DATABASE_URL,
	},
	strict: true,
} satisfies Config;

Schema

src/db/schema.ts
import { pgTable, serial, text, varchar } from "drizzle-orm/pg-core";
 
export const users = pgTable("users", {
	id: serial("id").primaryKey(),
	username: text("username"),
	email: varchar("email", { length: 256 }),
});

Scripts

package.json
{
	"scripts": {
		"drizzle:generate": "drizzle-kit generate:pg",
		"drizzle:push": "drizzle-kit push:pg",
		"drizzle:seed": "node --loader esbuild-register/loader -r esbuild-register ./src/db/seed.ts"
	}
}

For some reason if your use esbuild-register and had an error, you can try use tsx instead:

{
	"scripts": {
		"drizzle:seed": "tsx ./src/db/seed.ts"
	}
}

Credit to deadcoder0904 [Comment].

Migrations & Push

npm run drizzle:generate
npm run drizzle:push

Seed

src/db/seed.ts
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import { users } from "./schema.ts";
import { faker } from "@faker-js/faker";
import * as dotenv from "dotenv";
dotenv.config({ path: "./.env.development" });
 
if (!("DATABASE_URL" in process.env))
	throw new Error("DATABASE_URL not found on .env.development");
 
const main = async () => {
	const client = new Pool({
		connectionString: process.env.DATABASE_URL,
	});
	const db = drizzle(client);
	const data: (typeof users.$inferInsert)[] = [];
 
	for (let i = 0; i < 20; i++) {
		data.push({
			username: faker.internet.userName(),
			email: faker.internet.email(),
		});
	}
 
	console.log("Seed start");
	await db.insert(users).values(data);
	console.log("Seed done");
};
 
main();
npm run drizzle:seed

Open GitHub Discussions