25.09.2023 в 17:56
Иван Белов
База данных Seeding с помощью Drizzle ORM
В этом посте предполагается использование PostgreSQL для базы данных. Дополнительную информацию о том, как подключиться к вашей базе данных, см. в orm.drizzle.team/docs/overview.
Настройка
Dependencies
npm i drizzle-orm pg dotenv
npm i -D drizzle-kit @types/pg esbuild-register @faker-js/faker
Переменные среды
# .env.development
DATABASE_URL=postgres://user:pass@127.0.0.1:5432/db
Конфигурация Drizzle
// 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 }),
});
Скрипты
// 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"
}
}
Миграции и 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