brackt/scripts/migrate.mjs
Chris Parsons f1af4b5171
Decouple database migrations from server startup (#265)
* Use Docker Compose init service pattern for database migrations

Replaces the fragile double-migration approach (server.ts startup +
drizzle-kit CLI in CI) with a one-shot migrate service in Docker Compose
that the app depends on via condition: service_completed_successfully.

- Add scripts/migrate.mjs: programmatic drizzle-orm migration (uses
  production deps, not drizzle-kit which is devOnly and absent from image)
- Dockerfile: copy scripts/ into image, remove drizzle.config.ts (only
  needed by drizzle-kit CLI)
- server.ts: remove runMigrations() entirely; migrations are now handled
  by the migrate container before the app starts
- deploy.yml: remove explicit docker run migration step; replace sleep 10
  health check with a poll loop and explicit migrate exit-code check

Production server's docker-compose.yaml needs a one-time manual update
to add the migrate service — see plan for exact config.

https://claude.ai/code/session_01ReaqH3o9NVH4QU4qE9WMMQ

* Move drizzle-kit to devDependencies; use docker compose wait in deploy

drizzle-kit is a dev-only tool (schema generation and local migrations).
Now that production migrations run via the programmatic drizzle-orm API
in the migrate init container, drizzle-kit has no runtime role.

Also replaces the polling health check loop with docker compose wait,
which blocks until the migrate service exits and returns its exit code
cleanly — no sleep or manual status inspection needed.

https://claude.ai/code/session_01ReaqH3o9NVH4QU4qE9WMMQ

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-06 00:07:36 -04:00

26 lines
804 B
JavaScript

import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
import { fileURLToPath } from "url";
import path from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
if (!process.env.DATABASE_URL) {
console.error("ERROR: DATABASE_URL is required");
process.exit(1);
}
console.log("Running database migrations...");
const client = postgres(process.env.DATABASE_URL, { max: 1 });
try {
const db = drizzle(client);
await migrate(db, { migrationsFolder: path.resolve(__dirname, "../drizzle") });
console.log("Migrations completed successfully");
} catch (err) {
console.error("Migration failed:", err);
process.exit(1);
} finally {
await client.end();
}