84 lines
2.5 KiB
TypeScript
84 lines
2.5 KiB
TypeScript
import { config } from "dotenv";
|
|
import { sql } from "drizzle-orm";
|
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
|
import postgres from "postgres";
|
|
import { readFileSync, readdirSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
|
|
config({
|
|
path: ".env.local",
|
|
});
|
|
|
|
function assertMigrationJournalIsConsistent() {
|
|
const migrationsDir = join(process.cwd(), "lib/db/migrations");
|
|
const journalPath = join(migrationsDir, "meta", "_journal.json");
|
|
const journal = JSON.parse(readFileSync(journalPath, "utf8")) as {
|
|
entries: { tag: string }[];
|
|
};
|
|
|
|
const tags = new Set(journal.entries.map((entry) => entry.tag));
|
|
const sqlFiles = readdirSync(migrationsDir)
|
|
.filter((file) => file.endsWith(".sql"))
|
|
.map((file) => file.slice(0, -4));
|
|
const sqlSet = new Set(sqlFiles);
|
|
|
|
const extraSqlFiles = sqlFiles.filter((tag) => !tags.has(tag));
|
|
const missingSqlFiles = Array.from(tags).filter((tag) => !sqlSet.has(tag));
|
|
|
|
if (extraSqlFiles.length === 0 && missingSqlFiles.length === 0) {
|
|
return;
|
|
}
|
|
|
|
const details = [
|
|
extraSqlFiles.length > 0
|
|
? `extra sql files not in journal: ${extraSqlFiles.join(", ")}`
|
|
: null,
|
|
missingSqlFiles.length > 0
|
|
? `journal entries missing sql files: ${missingSqlFiles.join(", ")}`
|
|
: null,
|
|
]
|
|
.filter(Boolean)
|
|
.join(" | ");
|
|
|
|
throw new Error(
|
|
`Migration journal mismatch. Keep lib/db/migrations/*.sql in sync with meta/_journal.json. ${details}`
|
|
);
|
|
}
|
|
|
|
const runMigrate = async () => {
|
|
if (!process.env.POSTGRES_URL) {
|
|
throw new Error("POSTGRES_URL is not defined");
|
|
}
|
|
|
|
const connection = postgres(process.env.POSTGRES_URL, { max: 1 });
|
|
const db = drizzle(connection);
|
|
|
|
console.log("⏳ Running migrations...");
|
|
|
|
const start = Date.now();
|
|
assertMigrationJournalIsConsistent();
|
|
await migrate(db, { migrationsFolder: "./lib/db/migrations" });
|
|
await db.execute(sql`
|
|
ALTER TABLE "AiProvider" DROP CONSTRAINT IF EXISTS "AiProvider_type_check";
|
|
`);
|
|
await db.execute(sql`
|
|
ALTER TABLE "AiProvider"
|
|
ADD CONSTRAINT "AiProvider_type_check"
|
|
CHECK (type IN (
|
|
'alibaba', 'openai', 'custom', 'local', 'gemini',
|
|
'huanke-gemini', 'qianwen-video', 'volcano-vision', 'volcano-video', 'alibaba-image', 'ruxa-image', 'fal-image', 'fal-video', 'zhipu'
|
|
));
|
|
`);
|
|
const end = Date.now();
|
|
|
|
console.log("✅ Migrations completed in", end - start, "ms");
|
|
process.exit(0);
|
|
};
|
|
|
|
runMigrate().catch((err) => {
|
|
console.error("❌ Migration failed");
|
|
console.error(err);
|
|
process.exit(1);
|
|
});
|