11import { sql } from "drizzle-orm" ;
22import { drizzle } from "drizzle-orm/node-postgres" ;
33import { err , ok , type Result } from "neverthrow" ;
4- import { cache } from "react" ;
54import type { Database } from "@/drizzle/types" ;
65import * as schema from "../../drizzle/schema" ;
76import { getOwner } from "./useOwner" ;
87
8+ const dbInstances = new Map < string , Database > ( ) ;
9+
910export function getDatabaseName ( ownerId : string ) : Result < string , string > {
1011 if ( ! ownerId . startsWith ( "org_" ) && ! ownerId . startsWith ( "user_" ) ) {
1112 return err ( "Invalid owner ID" ) ;
1213 }
1314 return ok ( ownerId . toLowerCase ( ) . replace ( / / g, "_" ) ) ;
1415}
1516
16- export const database = cache ( async ( ) : Promise < Database > = > {
17+ export async function database ( ) : Promise < Database > {
1718 const { ownerId } = await getOwner ( ) ;
1819 if ( ! ownerId ) {
1920 throw new Error ( "Owner ID not found" ) ;
2021 }
2122
2223 return getDatabaseForOwner ( ownerId ) ;
23- } ) ;
24+ }
2425
2526export async function getDatabaseForOwner ( ownerId : string ) : Promise < Database > {
2627 const databaseName = getDatabaseName ( ownerId ) . match (
@@ -31,10 +32,18 @@ export async function getDatabaseForOwner(ownerId: string): Promise<Database> {
3132 ) ;
3233
3334 const sslMode = process . env . DATABASE_SSL === "true" ? "?sslmode=require" : "" ;
35+ const connectionString = `${ process . env . DATABASE_URL } /${ databaseName } ${ sslMode } ` ;
3436
35- return drizzle ( `${ process . env . DATABASE_URL } /${ databaseName } ${ sslMode } ` , {
36- schema,
37- } ) ;
37+ if ( ! dbInstances . has ( ownerId ) ) {
38+ dbInstances . set (
39+ ownerId ,
40+ drizzle ( connectionString , {
41+ schema,
42+ } ) ,
43+ ) ;
44+ }
45+
46+ return dbInstances . get ( ownerId ) ! ;
3847}
3948
4049export async function deleteDatabase ( ownerId : string ) {
0 commit comments