games_app/backend/src/db/test-connection.ts
2026-06-29 15:01:23 +02:00

70 lines
2.6 KiB
TypeScript

/**
* Database connection smoke test.
* Verifies DATABASE_URL credentials before running migrations.
* Run: npm run db:test
*/
declare const __dirname: string;
import dotenv from 'dotenv';
import path from 'path';
import { Pool } from 'pg';
const backendRoot = path.resolve(__dirname, '..', '..');
const repoRoot = path.resolve(__dirname, '..', '..', '..');
[path.join(backendRoot, '.env'), path.join(repoRoot, '.env')].forEach((envPath) => {
dotenv.config({ path: envPath });
});
/**
* Connects to PostgreSQL using DATABASE_URL and prints the connected user and database.
* Exits with code 1 and actionable hints on auth or connection errors.
*/
async function main() {
const url = process.env.DATABASE_URL;
if (!url || !url.trim()) {
console.error('DATABASE_URL is not set in .env');
process.exit(1);
}
const safeUrl = url.replace(/:([^:@]+)@/, ':****@');
console.log('Connecting with:', safeUrl);
try {
const parsed = new URL(url);
const passwordFromEnv = process.env.DATABASE_PASSWORD;
const passwordFromUrl = parsed.password ? decodeURIComponent(parsed.password) : '';
const password = typeof passwordFromEnv === 'string' && passwordFromEnv !== '' ? passwordFromEnv : passwordFromUrl;
const pool = new Pool({
host: parsed.hostname,
port: parsed.port ? parseInt(parsed.port, 10) : 5432,
database: parsed.pathname?.slice(1) || 'crypto_wallet',
user: parsed.username || 'postgres',
password: typeof password === 'string' ? password : '',
connectionTimeoutMillis: 5000,
});
const client = await pool.connect();
const r = await client.query('SELECT current_user, current_database()');
client.release();
await pool.end();
console.log('OK Connected as', r.rows[0].current_user, 'to database', r.rows[0].current_database);
process.exit(0);
} catch (err: unknown) {
const e = err as { code?: string; message?: string };
console.error('Connection failed:', e.message);
if (e.code === '28P01') {
console.error('\n--- Password authentication failed ---');
console.error('Try setting the password separately (no URL encoding needed):');
console.error(' DATABASE_URL=postgresql://postgres@localhost:5432/crypto_wallet');
console.error(' DATABASE_PASSWORD=your_postgres_password');
console.error('Or put the password in the URL; if it has @ # % : / encode them (e.g. @ → %40).');
}
if (e.code === 'ECONNREFUSED') {
console.error('\n--- Connection refused ---');
console.error('PostgreSQL is not running or not listening on the host/port in DATABASE_URL.');
}
process.exit(1);
}
}
main();