Skip to content

Commit 9584f3c

Browse files
Merge pull request #554 from simstudioai/fix/global-conn
fix(global conn): make db connection global to not reinstatiate on every import
2 parents 7089985 + 9239954 commit 9584f3c

1 file changed

Lines changed: 16 additions & 9 deletions

File tree

apps/sim/db/index.ts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
1-
import { drizzle } from 'drizzle-orm/postgres-js'
1+
import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'
22
import postgres from 'postgres'
33
import { env } from '@/lib/env'
4+
import * as schema from './schema'
45

56
// In production, use the Vercel-generated POSTGRES_URL
67
// In development, use the direct DATABASE_URL
78
const connectionString = env.POSTGRES_URL ?? env.DATABASE_URL
89

9-
// Disable prefetch as it is not supported for "Transaction" pool mode
10-
const client = postgres(connectionString, {
11-
prepare: false,
12-
idle_timeout: 30, // Keep connections alive for 30 seconds when idle
13-
connect_timeout: 30, // Timeout after 30 seconds when connecting
14-
})
10+
const drizzleClient = drizzle(
11+
postgres(connectionString, {
12+
prepare: false, // Disable prefetch as it is not supported for "Transaction" pool mode
13+
idle_timeout: 30, // Keep connections alive for 30 seconds when idle
14+
connect_timeout: 30, // Timeout after 30 seconds when connecting
15+
}),
16+
{ schema }
17+
)
1518

16-
// Export the database client (never null)
17-
export const db = drizzle(client)
19+
declare global {
20+
var database: PostgresJsDatabase<typeof schema> | undefined
21+
}
22+
23+
export const db = global.database || drizzleClient
24+
if (process.env.NODE_ENV !== 'production') global.database = db

0 commit comments

Comments
 (0)