-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.ts
More file actions
58 lines (51 loc) · 1.78 KB
/
index.ts
File metadata and controls
58 lines (51 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { PGlite } from '@electric-sql/pglite'
import { drizzle } from 'drizzle-orm/node-postgres'
import { drizzle as drizzlePGLite } from 'drizzle-orm/pglite'
import { Pool } from 'pg'
import { env } from '../lib/env.js'
import * as schema from './schema/index.js'
let db: ReturnType<typeof drizzle> | ReturnType<typeof drizzlePGLite> | null = null
let pgLiteInstance: PGlite | null = null
function shouldUsePGLite(): boolean {
if (env.PGLITE === true) return true
if (env.NODE_ENV === 'test') return true
return false
}
export async function getDb() {
if (!db)
if (shouldUsePGLite()) {
if (env.NODE_ENV === 'test') {
const g = globalThis as { __testPgliteInstance?: PGlite }
const instance = g.__testPgliteInstance
? g.__testPgliteInstance
: (await import('../../test/utils/db.js')).getTestDatabase().then(x => x.instance)
const pglite = instance instanceof PGlite ? instance : await instance
db = drizzlePGLite(pglite, { schema })
} else {
if (!pgLiteInstance) {
pgLiteInstance = new PGlite()
await pgLiteInstance.waitReady
}
db = drizzlePGLite(pgLiteInstance, { schema })
}
} else {
if (!env.DATABASE_URL) throw new Error('DATABASE_URL is required when PGLITE is false')
const pool = new Pool({ connectionString: env.DATABASE_URL })
db = drizzle(pool, { schema })
}
return db
}
/**
* Check if database is ready (initialized)
*/
export function isDbReady(): boolean {
return db !== null
}
/**
* Reset the database instance cache.
* Used in tests to ensure a fresh database connection after resetting the underlying database.
*/
export function resetDbInstance() {
db = null
// Note: pgLiteInstance is managed by test utils, don't reset it here
}