fix: lazy-load database connection to prevent build-time access
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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<typeof drizzle<typeof schema>> | 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<typeof drizzle<typeof schema>>, {
|
||||
get(_target, prop) {
|
||||
return getDb()[prop as keyof ReturnType<typeof drizzle<typeof schema>>]
|
||||
}
|
||||
})
|
||||
|
||||
export const db = drizzle(sqlite, { schema })
|
||||
export { schema }
|
||||
|
||||
Reference in New Issue
Block a user