From af8d9936285c697ff45700115eba83b5debdf9ad Mon Sep 17 00:00:00 2001 From: Thomas Hallock Date: Tue, 7 Oct 2025 08:41:06 -0500 Subject: [PATCH] fix: lazy-load database connection to prevent build-time access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor db/index.ts to use lazy initialization via Proxy pattern. This prevents the database from being accessed at module import time, which was causing Next.js build failures in CI/CD environments where no database file exists. The database connection is now created only when first accessed at runtime, allowing static site generation to complete successfully. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- apps/web/src/db/index.ts | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/apps/web/src/db/index.ts b/apps/web/src/db/index.ts index 36a443ae..4cedec7d 100644 --- a/apps/web/src/db/index.ts +++ b/apps/web/src/db/index.ts @@ -7,17 +7,44 @@ import * as schema from './schema' * * Creates a singleton SQLite connection with Drizzle ORM. * Enables foreign key constraints (required for cascading deletes). + * + * IMPORTANT: The database connection is lazy-loaded to avoid accessing + * the database at module import time, which would cause build failures + * when the database doesn't exist (e.g., in CI/CD environments). */ const databaseUrl = process.env.DATABASE_URL || './data/sqlite.db' -const sqlite = new Database(databaseUrl) +let _sqlite: Database.Database | null = null +let _db: ReturnType> | null = null -// Enable foreign keys (SQLite requires explicit enable) -sqlite.pragma('foreign_keys = ON') +/** + * Get the database connection (lazy-loaded singleton) + * Only creates the connection when first accessed at runtime + */ +function getDb() { + if (!_db) { + _sqlite = new Database(databaseUrl) -// Enable WAL mode for better concurrency -sqlite.pragma('journal_mode = WAL') + // Enable foreign keys (SQLite requires explicit enable) + _sqlite.pragma('foreign_keys = ON') + + // Enable WAL mode for better concurrency + _sqlite.pragma('journal_mode = WAL') + + _db = drizzle(_sqlite, { schema }) + } + return _db +} + +/** + * Database client instance + * Uses a Proxy to lazy-load the connection on first access + */ +export const db = new Proxy({} as ReturnType>, { + get(_target, prop) { + return getDb()[prop as keyof ReturnType>] + } +}) -export const db = drizzle(sqlite, { schema }) export { schema }