Skip to content

Latest commit

 

History

History
174 lines (125 loc) · 7.53 KB

databases.md

File metadata and controls

174 lines (125 loc) · 7.53 KB

Databases

Mailflare uses Cloudflare D1 by default, with nothing to configure. Set DATABASE_URL to use SQLite, PostgreSQL or MySQL elsewhere.

Prerequisites

  • An empty database and user. Mailflare creates the tables.
  • To move existing data, a backup first.

Use another database

  1. Set the variables:

    Variable Purpose
    DATABASE_URL Connection string. Unset means D1 (Workers) or a local SQLite file (self-hosted).
    DATABASE_DRIVER Optional. Overrides the driver guessed from the URL.
    DATABASE_AUTH_TOKEN Token for Turso / libSQL
  2. On Cloudflare, add them as Worker variables or secrets. They must exist before the app starts.

    npx wrangler secret put DATABASE_URL

    Self-hosted, put them in .env.docker.

  3. Finish /setup, or restart the self-hosted app.

Connection strings

Database DATABASE_URL Notes
Cloudflare D1 unset Default. Migrate with npm run db:migrate:remote or Admin → Settings.
Turso / libSQL libsql://my-db.turso.io + DATABASE_AUTH_TOKEN Workers and Node
SQLite file file:./data/mailflare.db Node only. The self-hosted default is already a file in DATA_DIR.
Bun SQLite file:./mailflare.db + DATABASE_DRIVER=bun-sqlite Bun only
PostgreSQL postgres://user:pass@host:5432/db Add ?sslmode=require if TLS is required
Supabase Pooler or direct URL from the dashboard Use the transaction pooler on Workers
Neon / Vercel Postgres postgres://…neon.tech/db?sslmode=require HTTP driver, detected by hostname; DATABASE_DRIVER=node-postgres uses TCP
Prisma Postgres postgres://…@db.prisma.io:5432/postgres?sslmode=require Search is indexed. On Workers use pooled.db.prisma.io, or connections run out.
postgres.js Any postgres:// URL + DATABASE_DRIVER=postgres-js
PGlite (embedded) pglite://./data/pg or pglite://memory Node only; for development and tests
MySQL / MariaDB / TiDB mysql://user:pass@host:3306/db TLS automatic on TiDB Cloud; ?ssl=true forces it
PlanetScale mysql://user:pass@aws.connect.psdb.cloud/db HTTP driver, detected by hostname
Hyperdrive (Workers) DATABASE_DRIVER=node-postgres or mysql2, plus a HYPERDRIVE binding The binding's URL is used if DATABASE_URL is unset

Drivers

A dialect is the SQL variant. A driver is the library that connects.

Dialect DATABASE_DRIVER values Services
SQLite d1 (default), libsql, better-sqlite3, bun-sqlite D1, Turso, local file
PostgreSQL node-postgres, postgres-js, neon, pglite Supabase, Neon, Vercel Postgres, Prisma Postgres, RDS, Cloud SQL, self-hosted
MySQL mysql2, planetscale MySQL 8, MariaDB 11, TiDB, PlanetScale, Aurora

Aliases such as pg, postgres, supabase, vercel, turso, mysql, tidb and mariadb work. SingleStore and other databases are not supported.

Move to another database

  1. In Admin → Backups, take a backup.
  2. Point DATABASE_URL at a new, empty database.
  3. Finish setup.
  4. Restore the backup.

Backups work across databases. Mail files stay in object storage.

Differences between databases

Foreign keys, the JMAP change log, mailbox revisions, the calendar and contacts (CalDAV/CardDAV) change log, trash dates and seed data work on all three.

Warning: TiDB and PlanetScale have no triggers, so both change logs and trash date tracking are unavailable. Calendar and contacts sync needs MySQL, MariaDB or PostgreSQL.

Area SQLite / D1 PostgreSQL MySQL / MariaDB
Search Full-text index, prefix and field matching Unindexed substring scan; faster with pg_trgm if it can be created Unindexed substring scan
Rebuild search index (Admin) Yes Not needed Not needed
Duplicate-send guard (agent_send_approvals) Partial unique index Partial unique index Plain index; a status check still prevents double sends
Large messages indexes Full Full Trimmed to 3072 bytes; conversation view is slower on very large mailboxes
One assistant job per mailbox Atomic Atomic Small race window
Batch atomicity Atomic Atomic Data changes only; a failed migration can leave earlier statements applied
Neon HTTP driver – Batches are not atomic; use node-postgres –

Other notes:

  • Search: large mailboxes search faster on SQLite/D1, or PostgreSQL with pg_trgm.
  • Connections: self-hosted uses a pool. Workers open one connection per query, so use Hyperdrive, a pooler, or an HTTP driver (neon, planetscale, libsql).
  • Letter case: MySQL ignores case by default, so two accounts whose emails differ only by case conflict.
  • Reserved words: in your own MySQL migrations, quote key, read, repeat, change and similar.

Examples

Docker Compose with PostgreSQL

  1. Add this under services: in your Compose file:

      db:
        image: postgres:17
        restart: unless-stopped
        environment:
          POSTGRES_USER: mailflare
          POSTGRES_PASSWORD: change-me
          POSTGRES_DB: mailflare
        volumes:
          - mailflare-db:/var/lib/postgresql/data
  2. Add mailflare-db: under the top-level volumes:.

  3. Set this in .env.docker:

    DATABASE_URL=postgres://mailflare:change-me@db:5432/mailflare

Run from source

DATABASE_URL=postgres://postgres:pw@127.0.0.1:5432/mailflare npm run dev:node

Test a database

db:smoke applies the migrations and runs the queries the app needs. Set MAILFLARE_DB_DIALECT to match the URL.

# PostgreSQL without a server
MAILFLARE_DB_DIALECT=postgres npm run db:smoke -- pglite://memory

# Real servers
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=pw -e POSTGRES_DB=mailflare postgres:17
docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=pw -e MYSQL_DATABASE=mailflare mysql:8.4
MAILFLARE_DB_DIALECT=postgres npm run db:smoke -- postgres://postgres:pw@127.0.0.1:5432/mailflare
MAILFLARE_DB_DIALECT=mysql npm run db:smoke -- mysql://root:pw@127.0.0.1:3306/mailflare

Migrations

For contributors. Migrations are SQL files, applied from Admin → Settings, /api/setup/prepare, or at self-hosted startup.

Dialect Directory History table
SQLite drizzle/migrations d1_migrations
PostgreSQL drizzle/migrations-pg mailflare_migrations
MySQL drizzle/migrations-mysql mailflare_migrations

PostgreSQL and MySQL start from 0000_baseline.sql plus 0001_triggers_and_seeds.sql (hand-written triggers and seed rows).

After changing src/db/schema/index.ts, create all three:

npm run db:generate        # SQLite
npm run db:generate:pg     # PostgreSQL
npm run db:generate:mysql  # MySQL
npm run db:bundle          # bundles the app applies

tests/database-dialects.test.mjs fails if the dialects differ or a bundle is stale.

In code, getDb(env) and env.DB work on every database: env.DB is an adapter with the D1 interface. Timestamps are whole seconds in a bigint; booleans are tinyint(1) on MySQL.

Troubleshooting

Problem Cause Fix
Workers uses the wrong database type Variable set too late Set DATABASE_URL as a variable or secret
"Too many connections" on Workers One connection per query Use a pooler or HTTP driver
Search is slow No search index Enable pg_trgm, or use SQLite/D1

Related