Production 환경에서의 DB 자동 Migration 구현

This commit is contained in:
static
2025-01-20 19:15:15 +09:00
parent ce329891ae
commit 803110606b
10 changed files with 58 additions and 23 deletions

View File

@@ -1,10 +1,11 @@
import { Kysely, PostgresDialect } from "kysely";
import { Pool } from "pg";
import { Kysely, PostgresDialect, Migrator } from "kysely";
import pg from "pg";
import env from "$lib/server/loadenv";
import migrations from "./migrations";
import type { Database } from "./schema";
const dialect = new PostgresDialect({
pool: new Pool({
pool: new pg.Pool({
host: env.database.host,
port: env.database.port,
user: env.database.user,
@@ -15,6 +16,32 @@ const dialect = new PostgresDialect({
const db = new Kysely<Database>({ dialect });
// TODO: Migration
export const migrateDB = async () => {
if (env.nodeEnv !== "production") return;
const migrator = new Migrator({
db,
provider: {
async getMigrations() {
return migrations;
},
},
});
const { error, results } = await migrator.migrateToLatest();
if (error) {
const migration = results?.find(({ status }) => status === "Error");
if (migration) {
console.error(`Migration "${migration.migrationName}" failed.`);
}
console.error(error);
process.exit(1);
}
if (results?.length === 0) {
console.log("Database is up-to-date.");
} else {
console.log("Database migration completed.");
}
};
export default db;