patternjavascriptdrizzleTip
Drizzle ORM setup with better-sqlite3 and type-safe queries
Viewed 1 times
drizzlesqlitebetter-sqlite3schemamigratordrizzle-kittype inferencesetup
Error Messages
Problem
Setting up Drizzle ORM correctly with SQLite requires understanding the schema definition pattern, the db instance initialization, and how to run migrations without the Prisma-style CLI flow.
Solution
Define tables with drizzle-orm/sqlite-core type helpers. Initialize the db with drizzle(connection). Use drizzle-kit for schema diffing and migration generation. Run migrations with migrate() from drizzle-orm/better-sqlite3/migrator.
Why
Drizzle is a SQL-first ORM where the schema IS the query builder type system — there is no separate runtime schema inference. Getting the initialization right ensures full TypeScript type inference on all query results.
Gotchas
- Drizzle schemas must be exported from a single file pointed to by drizzle.config.ts for the CLI to work
- Using db.run() vs db.get() vs db.all() matters — run() for mutations, get() for single row, all() for arrays
- Drizzle migrations are SQL files — inspect them before applying in production
- Relations in Drizzle are query-level constructs, not enforced at the schema level (use foreignKey() for DB constraints)
Code Snippets
Minimal Drizzle + better-sqlite3 setup
// schema.ts
import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
email: text('email').notNull().unique(),
name: text('name'),
});
// db.ts
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import * as schema from './schema';
const sqlite = new Database('app.db');
sqlite.pragma('journal_mode = WAL');
sqlite.pragma('busy_timeout = 5000');
export const db = drizzle(sqlite, { schema });
// query
const allUsers = db.select().from(schema.users).all();Revisions (0)
No revisions yet.