DEV Community

Cover image for Drizzle SQLite Setup: One Schema, No Drift
Saiful Islam
Saiful Islam

Posted on

Drizzle SQLite Setup: One Schema, No Drift

Drizzle SQLite Setup: One Schema, No Drift

A five-folder Drizzle layout that kills schema drift and mystery rows — and why the config reads a directory instead of a file.

The Problem

You add a user_events table, generate a migration, restart, and get no such table: user_events. Local worked last week because you ran raw SQL by hand. Here is the bug hiding in plain sight:

// drizzle.config.ts
export default defineConfig({
  schema: "./src/db/schemas/index.ts", // hand-maintained barrel
  out: "migrations",
  dialect: "sqlite",
  dbCredentials: { url: "./local.db" },
});
Enter fullscreen mode Exit fullscreen mode
src/db/schemas/table/user/userEvent.table.ts   <- new file, never re-exported
$ pnpm db:generate
No schema changes detected
$ pnpm dev
SqliteError: no such table: user_events
Enter fullscreen mode Exit fullscreen mode

Three fixes you try first:

  1. Add the missing export * to the barrel. It works now; the next new table repeats the bug.
  2. Import the table directly from the entry file. Drizzle Kit follows imports it can see. A file nobody imports stays invisible.
  3. Paste CREATE TABLE into migrations/0001_x.sql. The database catches up, TypeScript does not, and the next generate sees a difference again.

You need one definition that both TypeScript and the database trust, but a barrel file is a manual list and a hand-edited migration is a second source of truth.

The resolution is a config that points at a directory, plus barrels that re-export everything in two hops:

// drizzle.config.ts
export default defineConfig({
  schema: "./src/db/schemas/**",
  out: "migrations",
  dialect: "sqlite",
  dbCredentials: { url: "./local.db" },
});

// src/db/schemas/index.ts
export * from "./enums/db-enums";
export * from "./table";
Enter fullscreen mode Exit fullscreen mode

The Mental Model

Treat the folder as a switchboard.

  • Identity: every table file is a labeled jack; the schemas/** glob is the patch list the electrician reads.
  • Update timing: drizzle-kit generate prints a dated work order (a SQL migration). It never touches a live wire.
  • Read timing: the client plugs into the same panel at request time, and db.query follows the patch cables you declared as relations.

Two consequences: a table missing from the patch list is invisible to generation, and only the dated work orders ever change the physical database. Your TypeScript types are labels on the panel, not electricity.

If the jack is not on the panel, the electrician wires around it.

How to Use It

Install the pieces:

pnpm add drizzle-orm drizzle-zod zod @libsql/client
pnpm add -D drizzle-kit drizzle-dbml-generator tsx
Enter fullscreen mode Exit fullscreen mode

File tree:

src/
└── db/
    ├── clients/
    │   ├── drizzle-client.ts
    │   └── drizzle-client.mock.ts
    ├── generators/
    │   ├── dbml-generator.ts
    │   └── sql-generator.ts
    ├── schemas/
    │   ├── index.ts
    │   ├── enums/
    │   │   ├── db-enums.ts
    │   │   ├── enum-values.ts
    │   │   └── zod-db-enums.ts
    │   └── table/
    │       ├── index.ts
    │       └── verification.table.ts
    ├── seed/
    │   ├── clearAll.ts
    │   ├── seed.config.ts
    │   └── verification.seed.ts
    └── utils/
        ├── chunk-by-params.ts
        ├── db-utils.ts
        └── escapeLike.ts
drizzle.config.ts
Enter fullscreen mode Exit fullscreen mode

Imports below use @/. Swap in whatever alias your project uses.

drizzle.config.ts:

import { defineConfig } from "drizzle-kit";

export default defineConfig({
  schema: "./src/db/schemas/**",
  out: "migrations",
  dialect: "sqlite",
  dbCredentials: {
    url: "./local.db",
  },
});
Enter fullscreen mode Exit fullscreen mode

src/db/utils/db-utils.ts — one place decides how every column behaves:

import { sql } from "drizzle-orm";
import { integer, real, text } from "drizzle-orm/sqlite-core";

export const db_date = (name: string) =>
  integer(name, { mode: "timestamp_ms" });

export const db_id = text("id")
  .primaryKey()
  .$defaultFn(() => crypto.randomUUID())
  .notNull();

export const db_created_at = db_date("created_at")
  .notNull()
  .default(sql`(unixepoch() * 1000)`);

export const db_updated_at = db_date("updated_at")
  .notNull()
  .default(sql`(unixepoch() * 1000)`)
  .$onUpdate(() => new Date());

export const db_bool = (name: string) => integer(name, { mode: "boolean" });
export const db_money = (name: string) => real(name);
Enter fullscreen mode Exit fullscreen mode

src/db/schemas/enums/enum-values.ts — the list, not a string union typed twice:

export const ROLES = ["USER", "ADMIN", "SUPER_ADMIN"] as const;
export const PERMISSION_LEVEL = ["system", "self"] as const;
export const ACTION_TYPE = [
  "create",
  "read",
  "list",
  "update",
  "delete",
  "manage",
  "export",
] as const;
Enter fullscreen mode Exit fullscreen mode

src/db/schemas/enums/db-enums.ts and src/db/schemas/enums/zod-db-enums.ts:

import { text } from "drizzle-orm/sqlite-core";
import { ROLES } from "./enum-values";

export const RoleEnum = (name: string) => text(name, { enum: ROLES });
Enter fullscreen mode Exit fullscreen mode
import z from "zod";
import { ACTION_TYPE, PERMISSION_LEVEL, ROLES } from "./enum-values";

export const RoleEnumSchema = z.enum(ROLES);
export type RoleEnumType = z.infer<typeof RoleEnumSchema>;
export const ActionTypeEnumSchema = z.enum(ACTION_TYPE);
export type ActionTypeEnumType = z.infer<typeof ActionTypeEnumSchema>;
export const PermissionLevelEnumSchema = z.enum(PERMISSION_LEVEL);
export type PermissionLevelEnumType = z.infer<typeof PermissionLevelEnumSchema>;
Enter fullscreen mode Exit fullscreen mode

src/db/schemas/table/verification.table.ts — table, Zod schemas, and inferred types in one file:

import {
  db_created_at,
  db_date,
  db_id,
  db_updated_at,
} from "@/db/utils/db-utils";
import { sqliteTable, text } from "drizzle-orm/sqlite-core";
import {
  createInsertSchema,
  createSelectSchema,
  createUpdateSchema,
} from "drizzle-zod";
import z from "zod";

export const VerificationTable = sqliteTable("verifications", {
  id: db_id,
  identifier: text("identifier").notNull(),
  value: text("value").notNull(),
  expiresAt: db_date("expires_at").notNull(),
  createdAt: db_created_at,
  updatedAt: db_updated_at,
});

export const insertVerificationSchema = createInsertSchema(
  VerificationTable,
).omit({ id: true, createdAt: true, updatedAt: true });
export const selectVerificationSchema = createSelectSchema(VerificationTable, {
  id: z.uuid(),
});
export const updateVerificationSchema = createUpdateSchema(
  VerificationTable,
).omit({ id: true, createdAt: true, updatedAt: true });

export type VerificationDataModel = typeof VerificationTable.$inferSelect;
export type InsertVerification = z.infer<typeof insertVerificationSchema>;
export type SelectVerification = z.infer<typeof selectVerificationSchema>;
Enter fullscreen mode Exit fullscreen mode

src/db/schemas/index.ts and src/db/schemas/table/index.ts:

export * from "./enums/db-enums";
export * from "./table";
Enter fullscreen mode Exit fullscreen mode
export * from "./verification.table";
Enter fullscreen mode Exit fullscreen mode

src/db/clients/drizzle-client.ts and its test double:

import { createClient } from "@libsql/client";
import { drizzle, type LibSQLDatabase } from "drizzle-orm/libsql";

import * as schema from "@/db/schemas";

export type DatabaseType = LibSQLDatabase<typeof schema>;

export function createDrizzleClient(url = "file:./local.db"): DatabaseType {
  return drizzle(createClient({ url }), { schema });
}
Enter fullscreen mode Exit fullscreen mode
import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql";

import * as schema from "@/db/schemas";
import type { DatabaseType } from "./drizzle-client";

export function createMockDrizzleClient(): DatabaseType {
  return drizzle(createClient({ url: ":memory:" }), { schema });
}
Enter fullscreen mode Exit fullscreen mode

src/db/generators/dbml-generator.ts and src/db/generators/sql-generator.ts — one in-process, one via the CLI:

import { join } from "node:path";
import { sqliteGenerate } from "drizzle-dbml-generator";

import * as schema from "@/db/schemas";

sqliteGenerate({
  schema,
  out: join(process.cwd(), "schema.dbml"),
  relational: true,
});
Enter fullscreen mode Exit fullscreen mode
import { exec } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";

const execAsync = promisify(exec);

async function main() {
  const { stdout } = await execAsync("pnpm drizzle-kit export --sql");
  if (!stdout.trim()) throw new Error("No SQL output from drizzle-kit export");
  await writeFile(join(process.cwd(), "full-schema.sql"), stdout, "utf-8");
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
Enter fullscreen mode Exit fullscreen mode

src/db/utils/chunk-by-params.ts and src/db/utils/escapeLike.ts:

const MAX_BOUND_PARAMS = 999;

type PendingQuery<T> = PromiseLike<T> & { toSQL(): { params: unknown[] } };

export function chunkByParams<T>(rows: T[], paramsPerRow: number): T[][] {
  const size = Math.max(1, Math.floor(MAX_BOUND_PARAMS / paramsPerRow));
  return Array.from({ length: Math.ceil(rows.length / size) }, (_, index) =>
    rows.slice(index * size, (index + 1) * size),
  );
}

export async function insertChunkedReturning<T, R>(
  rows: T[],
  build: (chunk: T[]) => PendingQuery<R[]>,
): Promise<R[]> {
  if (!rows.length) return [];
  const query = build(rows);
  if (rows.length === 1 || query.toSQL().params.length <= MAX_BOUND_PARAMS) {
    return query;
  }
  const mid = Math.ceil(rows.length / 2);
  return [
    ...(await insertChunkedReturning(rows.slice(0, mid), build)),
    ...(await insertChunkedReturning(rows.slice(mid), build)),
  ];
}
Enter fullscreen mode Exit fullscreen mode
export function escapeLike(input: string): string {
  return input.replace(/[\\%_]/g, (ch) => `\\${ch}`);
}
Enter fullscreen mode Exit fullscreen mode

src/db/seed/seed.config.ts, src/db/seed/verification.seed.ts, and src/db/seed/clearAll.ts:

export const seedConfigs = { targets: { verifications: 3 } };
Enter fullscreen mode Exit fullscreen mode
import type { DatabaseType } from "@/db/clients/drizzle-client";
import type { InsertVerification, VerificationDataModel } from "@/db/schemas";
import { VerificationTable } from "@/db/schemas";

export const verificationData: Array<InsertVerification> = [
  {
    identifier: "email:ada@example.com",
    value: "token-a",
    expiresAt: new Date(),
  },
  {
    identifier: "email:grace@example.com",
    value: "token-b",
    expiresAt: new Date(),
  },
];

export async function seedVerifications(
  db: DatabaseType,
): Promise<VerificationDataModel[]> {
  return db.insert(VerificationTable).values(verificationData).returning();
}
Enter fullscreen mode Exit fullscreen mode
import type { DatabaseType } from "@/db/clients/drizzle-client";
import { VerificationTable } from "@/db/schemas";

export async function clearAll(db: DatabaseType) {
  await db.delete(VerificationTable);
}
Enter fullscreen mode Exit fullscreen mode

package.json scripts:

{
  "scripts": {
    "db:generate": "drizzle-kit generate",
    "db:migrate": "drizzle-kit migrate",
    "db:studio": "drizzle-kit studio",
    "db:generate-dbml": "tsx ./src/db/generators/dbml-generator.ts",
    "db:generate-sql": "tsx ./src/db/generators/sql-generator.ts",
    "db:generate-full": "pnpm db:generate && pnpm db:generate-dbml && pnpm db:generate-sql"
  }
}
Enter fullscreen mode Exit fullscreen mode

Pattern 1: A typed query with no second schema

import { eq } from "drizzle-orm";
import { createDrizzleClient } from "@/db/clients/drizzle-client";
import { VerificationTable } from "@/db/schemas";

const db = createDrizzleClient();
const row = await db.query.VerificationTable.findFirst({
  where: eq(VerificationTable.identifier, "email:ada@example.com"),
});
if (!row) throw new Error("missing verification");
console.log(row.expiresAt instanceof Date);
Enter fullscreen mode Exit fullscreen mode

The same table object supplies the SQL names, the query builder, and the return type.

Pattern 2: Seed rows without hitting the parameter ceiling

import type { DatabaseType } from "@/db/clients/drizzle-client";
import { VerificationTable, type InsertVerification } from "@/db/schemas";
import { insertChunkedReturning } from "@/db/utils/chunk-by-params";

export async function seedSafely(db: DatabaseType, rows: InsertVerification[]) {
  return insertChunkedReturning(rows, (chunk) =>
    db.insert(VerificationTable).values(chunk).returning(),
  );
}
Enter fullscreen mode Exit fullscreen mode

A thousand rows become several statements, each under the budget, and you keep the returned IDs.

Pattern 3: Tests against a real in-memory database

import { expect, test } from "vitest";
import { createMockDrizzleClient } from "@/db/clients/drizzle-client.mock";
import { VerificationTable } from "@/db/schemas";

test("a fresh client is empty and accepts a row", async () => {
  const db = createMockDrizzleClient();
  expect(await db.select().from(VerificationTable)).toEqual([]);
  await db.insert(VerificationTable).values({
    identifier: "email:ada@example.com",
    value: "token",
    expiresAt: new Date(),
  });
  expect(await db.select().from(VerificationTable)).toHaveLength(1);
});
Enter fullscreen mode Exit fullscreen mode

You exercise real SQLite semantics without a database server or a fixture file.

❌ Do not call db.insert(table).values(thousandsOfRows) directly — one oversized statement fails partway and leaves a half-seeded database.

When to Use It

Reach for this layout only when all three are true:

  • Your data fits SQLite and is written by one process on one machine.
  • You want table definitions, inferred types, and validation derived from a single file.
  • You can ship generated .sql files with your code and apply them yourself.
Situation Better tool
Browser-only storage IndexedDB
Multi-writer service across regions Hosted Postgres
Database-enforced enum types Postgres enums or a CHECK constraint
One-off CSV script with no schema Raw SQL client
Managed auth UI and schema Auth provider's own tables
Migrations applied by a platform CLI That platform's migration path

Smell test: if you cannot name where the list of applied migrations lives, you have a folder of SQL, not a migration strategy.

How It Works Under the Hood

  1. The glob is the contract. schema: "./src/db/schemas/**" makes Kit load every file under schemas, so a new table is seen without editing a barrel. The barrels still matter at runtime: drizzle(client, { schema }) needs one namespace object.
  2. Defaults are split by who evaluates them. db_id uses $defaultFn(() => crypto.randomUUID()), supplied by JavaScript. db_created_at uses .default(sql\(unixepoch() * 1000)), supplied by SQLite. Raw SQL and Drizzle inserts therefore agree on timestamps.
  3. timestamp_ms changes the type. integer(name, { mode: "timestamp_ms" }) stores milliseconds and returns Date. Passing a number to a gte on that column silently produces nonsense.
  4. Relations are declared, not discovered. Matching relationName values on both sides let db.query join. Without them, plain SQL still works but nested reads turn into N+1 queries.
  5. Chunking is measured, not guessed. insertChunkedReturning inspects toSQL().params and recursively halves until the statement fits 999 parameters. The cost is several round trips and no single atomic batch.
  6. Both generators read the same panel. DBML generation walks the schema object in-process; SQL generation shells out to drizzle-kit export. db:generate-full runs generate first so the exported SQL cannot be older than the migration folder.
Phase What exists Who reads it Failure if skipped
1. Define *.table.ts Kit and client nothing to generate
2. Generate config glob migrations/*.sql stale schema
3. Apply SQL work order local.db no such column
4. Seed typed client rows FK violation
5. Query client and schema typed rows any leaks through
6. Diagram schema object .dbml, .sql stale documentation

In a server-rendered React app, create the client on the server and never import a file-path client into a browser module: file:./local.db does not resolve in a browser bundle. Return rows through your server's data layer.

Drizzle Kit gives you generate, migrate, studio, and export. It does not give you a seed runner, a validation layer, or diagrams. These folders fill those gaps; that is a limitation of the built-ins, not a rival philosophy.

Conclusion

One schema folder, one config glob, and a handful of scripts buy you a database TypeScript can reason about. The cost is discipline: every new table must be discoverable, every migration generated, every seed within the statement budget.

  • Point the config at schemas/**, never at one hand-maintained file.
  • Derive validators from tables and override only the fields with custom rules.
  • Generate SQL and DBML from the same schema so documentation cannot drift.

Keep this setup while you own the apply step. When a platform takes that job, hand it the same SQL and let it keep its own ledger.

Top comments (0)