71 lines
1.7 KiB
JavaScript
71 lines
1.7 KiB
JavaScript
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { Client } from "pg";
|
|
|
|
function loadEnvFileIfNeeded() {
|
|
if (process.env.DATABASE_URL) return;
|
|
|
|
const envPath = path.join(process.cwd(), ".env");
|
|
if (!fs.existsSync(envPath)) return;
|
|
|
|
const text = fs.readFileSync(envPath, "utf8");
|
|
for (const rawLine of text.split("\n")) {
|
|
const line = rawLine.trim();
|
|
if (!line || line.startsWith("#")) continue;
|
|
const idx = line.indexOf("=");
|
|
if (idx === -1) continue;
|
|
|
|
const key = line.slice(0, idx).trim();
|
|
const value = line.slice(idx + 1).trim();
|
|
if (!process.env[key]) process.env[key] = value;
|
|
}
|
|
}
|
|
|
|
const migrationsDir = path.join(
|
|
path.dirname(fileURLToPath(import.meta.url)),
|
|
"..",
|
|
"migrations",
|
|
);
|
|
|
|
function listSqlFiles(dir) {
|
|
if (!fs.existsSync(dir)) return [];
|
|
|
|
return fs
|
|
.readdirSync(dir)
|
|
.filter((file) => file.endsWith(".sql"))
|
|
.sort((a, b) => a.localeCompare(b));
|
|
}
|
|
|
|
async function main() {
|
|
loadEnvFileIfNeeded();
|
|
|
|
const url = process.env.DATABASE_URL;
|
|
if (!url) {
|
|
console.error("DATABASE_URL is not set. Add it to .env or your environment.");
|
|
process.exit(1);
|
|
}
|
|
|
|
const client = new Client({ connectionString: url });
|
|
await client.connect();
|
|
|
|
try {
|
|
const files = listSqlFiles(migrationsDir);
|
|
for (const file of files) {
|
|
const fullPath = path.join(migrationsDir, file);
|
|
const sql = fs.readFileSync(fullPath, "utf8");
|
|
console.log(`Applying ${fullPath}`);
|
|
await client.query(sql);
|
|
}
|
|
console.log("Migrations applied successfully");
|
|
} finally {
|
|
await client.end();
|
|
}
|
|
}
|
|
|
|
main().catch((error) => {
|
|
console.error("Migration failed.");
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|