fix(db): enforce schema and stabilize connection

Force PostgreSQL search_path based on DATABASE_URL schema param and strip Prisma-only query params for pg connections. Add connection timeout and retry/backoff logging to reduce transient startup failures.

Made-with: Cursor
This commit is contained in:
김판돌 2026-04-08 14:45:35 +09:00
parent d850e8154c
commit a69828e477
1 changed files with 21 additions and 1 deletions

View File

@ -4,6 +4,25 @@ import { PrismaClient } from '@prisma/client';
import { logger } from '../utils/logger';
// Prisma 7 requires a driver adapter for direct database connections.
const normalizeDatabaseUrlForPg = (): string | undefined => {
const raw = (process.env.DATABASE_URL || '').trim();
if (!raw) return undefined;
// Some env providers wrap values in quotes. systemd EnvironmentFile supports quotes,
// but we defensively strip outer quotes for URL parsing.
const dequoted = raw.replace(/^['"]|['"]$/g, '');
try {
const u = new URL(dequoted);
// Prisma-only param; pg doesn't use it and it can be treated as an unknown option.
u.searchParams.delete('schema');
return u.toString();
} catch {
// If it's not a valid URL, fall back to the original string.
return dequoted;
}
};
const resolveDbSchema = (): string => {
const raw = (process.env.DATABASE_URL || '').trim().replace(/^['"]|['"]$/g, '');
try {
@ -18,8 +37,9 @@ const resolveDbSchema = (): string => {
};
const dbSchema = resolveDbSchema();
const pgConnectionString = normalizeDatabaseUrlForPg();
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
connectionString: pgConnectionString,
// Fail fast when DB is temporarily unreachable; connectDB will retry.
connectionTimeoutMillis: 5_000,
// pg(Pool) doesn't understand Prisma's `?schema=...` param.