fix(db): honor DATABASE_URL schema for pg Pool and PrismaPg

node-postgres ignores Prisma's ?schema= query param, so connections
defaulted to public. Parse the schema from the URL, set search_path on
the pool, and pass schema to PrismaPg (see prisma/prisma#28611).

Made-with: Cursor
This commit is contained in:
mineseo-kim 2026-04-09 09:45:10 +09:00
parent f317be9eab
commit ca9413e665
1 changed files with 28 additions and 3 deletions

View File

@ -1,11 +1,36 @@
import type { PoolConfig } from 'pg';
import { Pool } from 'pg'; import { Pool } from 'pg';
import { PrismaPg } from '@prisma/adapter-pg'; import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from '@prisma/client';
import { env } from '../config/env';
import { logger } from '../utils/logger'; import { logger } from '../utils/logger';
// Prisma 7 requires a driver adapter for direct database connections. /**
const pool = new Pool({ connectionString: process.env.DATABASE_URL }); * `?schema=` in DATABASE_URL is a Prisma URL extension. node-postgres does not apply it,
const adapter = new PrismaPg(pool); * so connections default to `search_path=public`. PrismaPg also needs an explicit schema
* option in some setups (see prisma/prisma#28611).
*/
function createPgPoolConfig(connectionString: string): { poolConfig: PoolConfig; prismaSchema?: string } {
if (!connectionString) {
return { poolConfig: { connectionString: '' } };
}
try {
const url = new URL(connectionString);
const schema = url.searchParams.get('schema')?.trim();
const poolConfig: PoolConfig = { connectionString };
if (schema) {
const escaped = schema.replace(/"/g, '""');
poolConfig.options = `-c search_path="${escaped}"`;
}
return { poolConfig, prismaSchema: schema || undefined };
} catch {
return { poolConfig: { connectionString } };
}
}
const { poolConfig, prismaSchema } = createPgPoolConfig(env.DATABASE_URL);
const pool = new Pool(poolConfig);
const adapter = prismaSchema ? new PrismaPg(pool, { schema: prismaSchema }) : new PrismaPg(pool);
export const prisma = new PrismaClient({ export const prisma = new PrismaClient({
adapter, adapter,