Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions packages/server/src/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof schema> | undefined;
var db: PostgresJsDatabase<typeof schema> | undefined;
}

export let db: PostgresJsDatabase<typeof schema>;
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<typeof schema> {
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<typeof schema> = getDbInstance();
export { dbUrl };