mirror your GitHub repos to tangled.org automatically
1import { neon } from '@neondatabase/serverless'
2import { drizzle as drizzleNeon } from 'drizzle-orm/neon-http'
3import * as schema from '../db/schema'
4
5export type Db = ReturnType<typeof drizzleNeon<typeof schema>>
6
7let _db: Db | undefined
8
9/**
10 * Override the DB returned by `useDb()`. Tests inject a PGlite-backed Drizzle
11 * instance with the same schema. Production code never calls this.
12 */
13export function setDb(db: Db) {
14 _db = db
15}
16
17/** Clear the cached DB so the next `useDb()` reconstructs from runtime config. */
18export function clearDb() {
19 _db = undefined
20}
21
22export function useDb(): Db {
23 if (_db) return _db
24 const { databaseUrl } = useRuntimeConfig()
25 if (!databaseUrl) {
26 throw new Error('NUXT_DATABASE_URL is not set')
27 }
28 const client = neon(databaseUrl)
29 _db = drizzleNeon(client, { schema })
30 return _db
31}
32
33export { schema }