From 9ffb4404d5471777d893d1607a26c8a5fd82e004 Mon Sep 17 00:00:00 2001 From: "Immanuel Daviel A. Garcia" <34188635+AlexDev404@users.noreply.github.com> Date: Sat, 7 Feb 2026 04:20:13 -0600 Subject: [PATCH 1/2] fix: Lazy-load database connection to prevent unnecessary instantiations Previously, the database connection was initialized on import, even when unused. This commit defers connection initialization until the `db` variable is first accessed, preventing redundant database connections when the module is imported. --- packages/server/src/db/index.ts | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/packages/server/src/db/index.ts b/packages/server/src/db/index.ts index e17002de96..adbf0522df 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(`[RUNTIME] 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 }; From d32c6130159afbcc78d5d8f9fbc411d28eec5ed7 Mon Sep 17 00:00:00 2001 From: "Immanuel Daviel A. Garcia" <34188635+AlexDev404@users.noreply.github.com> Date: Sat, 7 Feb 2026 04:23:37 -0600 Subject: [PATCH 2/2] Update index.ts --- packages/server/src/db/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/server/src/db/index.ts b/packages/server/src/db/index.ts index adbf0522df..967ee1d196 100644 --- a/packages/server/src/db/index.ts +++ b/packages/server/src/db/index.ts @@ -12,7 +12,7 @@ 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(`[RUNTIME] Connecting to database: ${sanitizeDbUrl(dbUrl)}`); + console.log(`[DB] Connecting to database: ${sanitizeDbUrl(dbUrl)}`); } return drizzle(postgres(dbUrl), { schema }); }