Drizzle foundations
Open SQLite with Drizzle
Create one database module that owns the SQLite connection and exports the Drizzle client used by the rest of the application.
8 minute lesson
The database client should have one obvious home. This keeps connection setup out of every query file.
Load the database filename from the environment and fail immediately when it is missing. Then pass the filename to the Node SQLite Drizzle driver. The returned db object builds queries and sends them through the underlying SQLite connection.
import 'dotenv/config'
import { drizzle } from 'drizzle-orm/node-sqlite'
if (!process.env.DB_FILE_NAME) {
throw new Error('DB_FILE_NAME is required')
}
export const db = drizzle(process.env.DB_FILE_NAME)
A local file is convenient, but it is still state. Two tests that share it can affect each other. Later we will create isolated temporary databases for tests and keep production connection choices outside query code.
Do not place an untrusted request value into the database filename. The environment controls infrastructure; users control data passed to queries.
Run the module once with DB_FILE_NAME present and once without it. Save the created file and the startup failure, then confirm the file is ignored by Git.
Lesson completed