|
| 1 | +// Production migration runner for the `trigger_dashboard_agent` schema. |
| 2 | +// |
| 3 | +// Runs under plain `node migrate.mjs` in the built image: `drizzle-orm` and |
| 4 | +// `postgres` are runtime dependencies, so this needs no `drizzle-kit`, `tsx`, |
| 5 | +// or build step (keeps the image lean). The OSS container runs this from its |
| 6 | +// entrypoint; cloud runs it out-of-band against its own database. |
| 7 | +import { dirname, join } from "node:path"; |
| 8 | +import { fileURLToPath } from "node:url"; |
| 9 | +import { drizzle } from "drizzle-orm/postgres-js"; |
| 10 | +import { migrate } from "drizzle-orm/postgres-js/migrator"; |
| 11 | +import postgres from "postgres"; |
| 12 | + |
| 13 | +// Cloud points at the dedicated dashboard-agent database; OSS falls back to the |
| 14 | +// main DATABASE_URL (tables still land in the `trigger_dashboard_agent` schema). |
| 15 | +const connectionString = process.env.DASHBOARD_AGENT_DATABASE_URL ?? process.env.DATABASE_URL; |
| 16 | + |
| 17 | +if (!connectionString) { |
| 18 | + console.error( |
| 19 | + "[dashboard-agent-db] DASHBOARD_AGENT_DATABASE_URL / DATABASE_URL not set; cannot migrate." |
| 20 | + ); |
| 21 | + process.exit(1); |
| 22 | +} |
| 23 | + |
| 24 | +// Prisma-style URLs carry `?schema=...`; postgres.js forwards unknown query |
| 25 | +// params as server startup config and Postgres rejects `schema`. Our tables are |
| 26 | +// schema-qualified, so the param is unnecessary — drop it. |
| 27 | +function normalizeConnectionString(value) { |
| 28 | + try { |
| 29 | + const url = new URL(value); |
| 30 | + url.searchParams.delete("schema"); |
| 31 | + return url.toString(); |
| 32 | + } catch { |
| 33 | + return value; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +const migrationsFolder = join(dirname(fileURLToPath(import.meta.url)), "drizzle"); |
| 38 | +const sql = postgres(normalizeConnectionString(connectionString), { |
| 39 | + max: 1, |
| 40 | + prepare: false, |
| 41 | + // Silence the "schema/relation already exists, skipping" notices the journal's |
| 42 | + // idempotent CREATE IF NOT EXISTS emits on every re-run, so restart logs stay clean. |
| 43 | + onnotice: () => {}, |
| 44 | +}); |
| 45 | + |
| 46 | +try { |
| 47 | + // Journal lives in Drizzle's default `drizzle` schema (matching `drizzle-kit |
| 48 | + // migrate`, so dev and deploy track migrations the same way). It must not be |
| 49 | + // our data schema: the first migration runs `CREATE SCHEMA |
| 50 | + // "trigger_dashboard_agent"`, which would collide with the journal schema the |
| 51 | + // migrator pre-creates. The dashboard agent is the only Drizzle user of its |
| 52 | + // database, so the `drizzle` schema stays exclusively ours. |
| 53 | + await migrate(drizzle(sql), { migrationsFolder }); |
| 54 | + console.log("[dashboard-agent-db] migrations complete"); |
| 55 | +} finally { |
| 56 | + await sql.end(); |
| 57 | +} |
0 commit comments