75 lines
2.2 KiB
JavaScript
75 lines
2.2 KiB
JavaScript
// Usage: node scripts/test-db-connection.mjs
|
|
// Reads DATABASE_URL from the environment or .env.local (never hardcode hosts/passwords).
|
|
|
|
import { existsSync, readFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import pg from "pg";
|
|
|
|
const { Client } = pg;
|
|
|
|
if (!process.env.DATABASE_URL) {
|
|
const envPath = path.resolve(
|
|
path.dirname(fileURLToPath(import.meta.url)),
|
|
"..",
|
|
".env.local",
|
|
);
|
|
if (existsSync(envPath)) {
|
|
for (const line of readFileSync(envPath, "utf8").split(/\r?\n/)) {
|
|
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
|
|
if (match && !(match[1] in process.env)) {
|
|
process.env[match[1]] = match[2];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!process.env.DATABASE_URL) {
|
|
console.error("CONNECTION_FAIL");
|
|
console.error("DATABASE_URL is not set. Copy .env.example → .env.local and fill it in.");
|
|
process.exit(1);
|
|
}
|
|
|
|
const client = new Client({
|
|
connectionString: process.env.DATABASE_URL,
|
|
connectionTimeoutMillis: 10000,
|
|
});
|
|
|
|
try {
|
|
await client.connect();
|
|
const info = await client.query(`
|
|
SELECT
|
|
version() AS version,
|
|
current_database() AS database,
|
|
current_user AS username,
|
|
pg_encoding_to_char(encoding) AS encoding
|
|
FROM pg_database
|
|
WHERE datname = current_database()
|
|
`);
|
|
console.log("CONNECTION_OK");
|
|
console.log(JSON.stringify(info.rows[0], null, 2));
|
|
|
|
const migrations = await client.query(
|
|
"SELECT version, applied_at FROM schema_migrations ORDER BY version",
|
|
).catch(() => ({ rows: [] }));
|
|
console.log("migrations_applied:", migrations.rows.length);
|
|
if (migrations.rows.length) {
|
|
console.log(JSON.stringify(migrations.rows.map((r) => r.version), null, 2));
|
|
}
|
|
|
|
const tables = await client.query(`
|
|
SELECT table_schema, table_name
|
|
FROM information_schema.tables
|
|
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
|
|
ORDER BY 1, 2
|
|
`);
|
|
console.log("tables_count:", tables.rows.length);
|
|
console.log(JSON.stringify(tables.rows, null, 2));
|
|
} catch (error) {
|
|
console.error("CONNECTION_FAIL");
|
|
console.error(error instanceof Error ? error.message : error);
|
|
process.exitCode = 1;
|
|
} finally {
|
|
await client.end().catch(() => {});
|
|
}
|