brick.ts

Database Management & Migrations

Configure SQLite and PostgreSQL databases, development sync, and production migrations with brick db.

llms.txt

Brick-TS provides database configuration handles for SQLite and PostgreSQL, with development table synchronization and production migrations through brick db, which wraps Drizzle Kit.

Minimal Example

Configure an in-memory SQLite database for local development and test:

src/database.ts
import { defineDatabase, sqliteTable, syncSchema, text } from "@brickkit/core";

export const users = sqliteTable("users", {
  id: text("id")
    .primaryKey()
    .$defaultFn(() => crypto.randomUUID()),
  email: text("email").notNull().unique(),
});

// Configure SQLite database handle
export const database = defineDatabase({
  tables: { users },
});

// Dev/test only: explicitly sync SQLite schema
syncSchema({ users }, database.getDb());

Schema

These columns match the Drizzle tables in the example. Defaults marked as application defaults run in Drizzle, rather than in SQL.

Table Name: users

FieldTypeDescription
idtextRow identifier. PK Default: crypto.randomUUID() (application)
emailtextUnique email address. Unique

Configuring Databases (defineDatabase)

defineDatabase creates a lazy, typed database handle. Connections are opened only when requested by services or runtime actions.

1. SQLite Configuration

The default database engine in Brick-TS is sqlite, running on Bun's high-performance native SQLite client (bun:sqlite):

src/db/sqlite.ts
import { defineDatabase } from "@brickkit/core";
import { users, posts } from "./schema";

export const sqliteDb = defineDatabase({
  engine: "sqlite", // default
  filename: "./data/app.db", // Omit for in-memory :memory:
  wal: true, // Enable Write-Ahead Logging (default true)
  foreignKeys: true, // Enforce foreign key constraints (default true)
  tables: { users, posts },
});

2. PostgreSQL Configuration

Connect to PostgreSQL using the PostgresJS driver:

src/db/postgres.ts
import { defineDatabase, defineSecret } from "@brickkit/core";
import { users, posts } from "./schema";

export const postgresDb = defineDatabase({
  engine: "postgres",
  url: defineSecret("DATABASE_URL"), // Resolves from environment variable
  ssl: process.env.NODE_ENV === "production",
  tables: { users, posts },
});

Database Configuration Options Table

OptionEngineDefaultDescription
engineAll"sqlite""sqlite" or "postgres".
tablesAllundefinedRecord or array of Drizzle tables registered with the handle.
filenameSQLite":memory:"Path to SQLite file on disk. Parent directories are created automatically.
walSQLitetrueEnables Write-Ahead Logging for high-concurrency performance.
foreignKeysSQLitetrueEnforces SQLite foreign key constraints.
urlPostgresundefinedPostgreSQL connection string URL (postgres://...) or SecretRef. Falls back to DATABASE_URL when omitted.
sslPostgresundefinedSSL mode or certificate configuration.

Development Schema Synchronization (syncSchema)

For local development and unit tests, syncSchema creates the declared tables that do not exist yet. It never changes a table that exists:

src/setup.ts
import { syncSchema } from "@brickkit/core";
import { usersService } from "./services/users";

// SQLite: runs CREATE TABLE IF NOT EXISTS for each table, synchronously.
syncSchema(usersService);

On PostgreSQL, syncSchema returns a promise. It uses Drizzle Kit's programmatic API to write the DDL for the missing tables, with their enums, indexes and foreign keys, and applies it in one transaction. drizzle-kit is an optional peer dependency of @brickkit/core (it comes with @brickkit/cli); without it, syncSchema throws and points you to brick db push:

test/setup.ts
await syncSchema(database.tables, database.getDb());

Explicit Development Helper: syncSchema is an explicit development and test utility. Brick-TS never alters database schema automatically at server boot. Do not call syncSchema in production environments.

Production Schema Migrations (brick db)

In production, change the schema with migrations. brick db wraps Drizzle Kit and reads the tables from your app, so it needs no drizzle.config.ts and no schema file:

# 1. Generate migration SQL from the schema changes since the last migration
brick db generate --name add_users

# 2. Apply pending migrations to the database the app is configured for
brick db migrate

It covers every table Brick knows on each database: the tables passed to defineDatabase, resource tables, plugin tables and the outbox table. Each database gets a subfolder of the migrations folder (drizzle/ by default), named after the database, in Drizzle Kit's layout, so drizzle-kit and Drizzle's migrator read it too. To apply migrations from code, call migrateDatabase(database, "./drizzle/<name>").

On a development database, brick db push applies the changes directly without migration files, and refuses changes that drop data unless you pass --force.

This workflow gives you full version control, rollback inspection, and zero runtime lock-in.

Tables owned by plugins

A plugin made with definePlugin can own tables (such as page_comments). Brick adds them to the host service's database, so syncSchema creates them, database.tables lists them, and brick db generate includes them in migrations. See Owned tables.

Secondary Indexes and Search Optimizations

Brick-TS provides explicit opt-in helpers for secondary indexes and search (no indexes are created automatically — call these yourself):

  • Secondary B-Tree Indexes: ensureResourceIndexes(db, table, { sortFields, ownerField }) creates indexes on hot lookup and sorting paths. Pass searchFields on PostgreSQL to also add pg_trgm GIN indexes for fast substring matching. It returns a promise: await it on PostgreSQL. A statement that fails (a read-only replica, no right to create pg_trgm) logs a warning and the rest still run.
  • SQLite FTS5 Full-Text Search: ensureSQLiteFts(db, table, searchCols) builds an FTS5 sidecar virtual table with sync triggers for rapid text search queries.