diff --git a/packages/server/src/db/index.ts b/packages/server/src/db/index.ts index e17002de96..967ee1d196 100644 --- a/packages/server/src/db/index.ts +++ b/packages/server/src/db/index.ts @@ -2,23 +2,28 @@ import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; import postgres from "postgres"; import { dbUrl } from "./constants"; import * as schema from "./schema"; +import { sanitizeDbUrl } from "./utils"; declare global { - var db: PostgresJsDatabase | undefined; + var db: PostgresJsDatabase | undefined; } -export let db: PostgresJsDatabase; -if (process.env.NODE_ENV === "production") { - db = drizzle(postgres(dbUrl), { - schema, - }); -} else { - if (!global.db) - global.db = drizzle(postgres(dbUrl), { - schema, - }); - - db = global.db; +function getDbInstance(): PostgresJsDatabase { + if (process.env.NODE_ENV === "production") { + // Log database connection for debugging in non-production or when DEBUG is set + if (process.env.DEBUG) { + console.log(`[DB] Connecting to database: ${sanitizeDbUrl(dbUrl)}`); + } + return drizzle(postgres(dbUrl), { schema }); + } + if (!global.db) { + if (process.env.DEBUG || process.env.NODE_ENV !== "production") { + console.log(`[RUNTIME] Connecting to database: ${sanitizeDbUrl(dbUrl)}`); + } + global.db = drizzle(postgres(dbUrl), { schema }); + } + return global.db; } +export const db: PostgresJsDatabase = getDbInstance(); export { dbUrl };