How do I stop Drizzle from trying to instantiate a connection during build time (next.js)?

Hey everyone, I've a question I can't seem to solve myself right now. I'm using next.js with tRPC and Drizzle (t3 stack, https://github.com/t3-oss/create-t3-app). I'm currently setting up my Docker configuration. I did not intend to pass the env var holding the database url to my docker builder container. As a result, Drizzle is throwing an error because it is trying to instantiate a database connection as soon as createClient is invoked, even though nothing is trying to access the database. How can I work around this? With Prisma this was not an issue, because Prisma only connects to the database if you actually call $connect / upon the first query ran. This is where the createClient is called https://github.com/t3-oss/create-t3-app/blob/main/cli/template/extras/src/server/db/index-drizzle/with-sqlite.ts. Anyone got an idea for me?
1 Reply
ShamesBond
ShamesBond3mo ago
The first thing that comes to mind is using a memoized function to get the db rather than instantiating the connection when the file is imported.
let memoizedDb: LibSQLDatabase<typeof schema>|null = null
let memoizedClient: ReturnType<typeof createClient>|null = null
export function client() {
if (memoizedClient === null) {
memoizedClient = globalForDb.client ?? createClient({ url: env.DATABASE_URL });
}
return memoizedClient;
}

export function db() {
if (memoizedDb === null) {
memoizedDb = drizzle(client, { schema });
}
return memoizedDb;
}
let memoizedDb: LibSQLDatabase<typeof schema>|null = null
let memoizedClient: ReturnType<typeof createClient>|null = null
export function client() {
if (memoizedClient === null) {
memoizedClient = globalForDb.client ?? createClient({ url: env.DATABASE_URL });
}
return memoizedClient;
}

export function db() {
if (memoizedDb === null) {
memoizedDb = drizzle(client, { schema });
}
return memoizedDb;
}
Then you just use db().select instead of db.select

Did you find this page helpful?