114 lines
4.1 KiB
TypeScript
114 lines
4.1 KiB
TypeScript
/**
|
|
* Apply one `drizzle/*.sql` migration to the database in DATABASE_URL.
|
|
*
|
|
* bun scripts/apply-migration.ts drizzle/0007_node_metrics.sql # 预演,只读
|
|
* bun scripts/apply-migration.ts drizzle/0007_node_metrics.sql --commit # 真正执行
|
|
*
|
|
* Why this exists: there is no migration runner in this repo — `deploy.sh` never
|
|
* touches the schema, and the devbox has no `psql`, so the seven migrations
|
|
* before this one were applied by hand. That is fine until it isn't: a hand-run
|
|
* DDL has no dry run, no transaction, and no record of whether it already ran.
|
|
*
|
|
* Dry run is the DEFAULT and is strictly read-only: it prints the statements and
|
|
* queries information_schema to report which of the tables/indexes involved
|
|
* already exist. `--commit` is the only path that writes, and it wraps the whole
|
|
* file in a single transaction so a half-applied migration is not a state this
|
|
* can leave behind.
|
|
*
|
|
* Applying it is a production write. Per CLAUDE.md that is the operator's call,
|
|
* not something an agent runs on its own initiative.
|
|
*/
|
|
|
|
import { readFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
import pg from "pg";
|
|
|
|
const args = process.argv.slice(2);
|
|
const COMMIT = args.includes("--commit");
|
|
const file = args.find((a) => !a.startsWith("--"));
|
|
|
|
if (!file) {
|
|
console.error("用法: bun scripts/apply-migration.ts <drizzle/xxxx.sql> [--commit]");
|
|
process.exit(2);
|
|
}
|
|
|
|
const raw = process.env.DATABASE_URL;
|
|
if (!raw) {
|
|
console.error("DATABASE_URL 未设置(见 .env)");
|
|
process.exit(2);
|
|
}
|
|
|
|
const sql = readFileSync(path.resolve(file), "utf8");
|
|
|
|
/** Statement-ish split, for the summary only — the file is executed as one blob. */
|
|
const statements = sql
|
|
.split(/;\s*$/m)
|
|
.map((s) => s.replace(/^\s*--.*$/gm, "").trim())
|
|
.filter(Boolean);
|
|
|
|
// Same URL parsing as db_client.ts: an IPv6 literal must reach pg as a plain
|
|
// `host`, or it tries to resolve the bracketed string as a hostname.
|
|
const u = new URL(raw);
|
|
const pool = new pg.Pool({
|
|
host: u.hostname.replace(/^\[|\]$/g, ""),
|
|
port: u.port ? Number(u.port) : 5432,
|
|
user: decodeURIComponent(u.username),
|
|
password: decodeURIComponent(u.password),
|
|
database: u.pathname.replace(/^\//, ""),
|
|
connectionTimeoutMillis: 30_000,
|
|
});
|
|
|
|
// Never echo the URL itself — it carries the production password.
|
|
console.log(`[migrate] ${file}`);
|
|
console.log(`[migrate] 目标库 ${u.pathname.replace(/^\//, "")} @ ${u.hostname}`);
|
|
console.log(`[migrate] ${statements.length} 条语句\n`);
|
|
for (const s of statements) {
|
|
console.log(` ${s.split("\n").map((l) => l.trim()).filter(Boolean).join(" ").slice(0, 110)}`);
|
|
}
|
|
|
|
const tables = [...sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?"?([\w.]+)"?/gi)].map((m) => m[1]);
|
|
const indexes = [...sql.matchAll(/CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?"?([\w.]+)"?/gi)].map((m) => m[1]);
|
|
|
|
try {
|
|
console.log(`\n[migrate] 当前库状态:`);
|
|
for (const t of tables) {
|
|
const r = await pool.query("SELECT to_regclass($1) AS oid", [t]);
|
|
console.log(` 表 ${t.padEnd(24)} ${r.rows[0].oid ? "已存在" : "不存在"}`);
|
|
}
|
|
for (const i of indexes) {
|
|
const r = await pool.query("SELECT to_regclass($1) AS oid", [i]);
|
|
console.log(` 索引 ${i.padEnd(24)} ${r.rows[0].oid ? "已存在" : "不存在"}`);
|
|
}
|
|
|
|
if (!COMMIT) {
|
|
console.log(`\n[migrate] \x1b[33m预演模式,未写入任何东西\x1b[0m`);
|
|
console.log(`[migrate] 确认无误后加 --commit 执行`);
|
|
process.exit(0);
|
|
}
|
|
|
|
console.log(`\n[migrate] \x1b[31m执行中(单个事务)\x1b[0m …`);
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("BEGIN");
|
|
await client.query(sql);
|
|
await client.query("COMMIT");
|
|
console.log(`[migrate] \x1b[32m已提交\x1b[0m`);
|
|
} catch (err) {
|
|
await client.query("ROLLBACK");
|
|
throw err;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
|
|
console.log(`\n[migrate] 复核:`);
|
|
for (const t of [...tables, ...indexes]) {
|
|
const r = await pool.query("SELECT to_regclass($1) AS oid", [t]);
|
|
console.log(` ${t.padEnd(24)} ${r.rows[0].oid ? "✓ 存在" : "✗ 仍然缺失"}`);
|
|
}
|
|
} catch (err) {
|
|
console.error(`\n[migrate] 失败: ${(err as Error).message}`);
|
|
process.exitCode = 1;
|
|
} finally {
|
|
await pool.end();
|
|
}
|