Email for professionals and teams
feat(db): support PostgreSQL, MySQL and libSQL alongside D1
Hieu Nguyen (Jack)7c87ea3bb0ef
diff --git a/.env.docker.example b/.env.docker.exampleindex ee49d02..d3c41a1 100644--- a/.env.docker.example+++ b/.env.docker.example@@ -4,6 +4,15 @@# Loaded by docker-compose.yml (env_file). Commented lines fall back to the# image defaults (see docs/self-hosting.md for the full reference).+# ===== Database =====+# SQLite in the data volume by default. Point at an external database instead+# (PostgreSQL, MySQL/MariaDB, libSQL/Turso); migrations run on start. See+# docs/databases.md for the drivers and what differs per database.+#DATABASE_URL=postgres://mailflare:change-me@db:5432/mailflare+#DATABASE_URL=mysql://mailflare:change-me@db:3306/mailflare+#DATABASE_URL=libsql://my-db.turso.io+#DATABASE_AUTH_TOKEN=+# ===== Basics =====# Public URL behind a reverse proxy: password-reset links, the JMAP session# and inbound webhooks all use it.diff --git a/CLAUDE.md b/CLAUDE.mdindex 472827a..e50dafa 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -9,7 +9,10 @@ npm run dev # Vite + vinext in local workerdnpm run lint # eslint (next/core-web-vitals + next/typescript)npm run build # vinext build, including the complete Worker-npm run db:generate # drizzle-kit generate from src/db/schema/index.ts+npm run db:generate # drizzle-kit generate (SQLite) from src/db/schema/index.ts+npm run db:generate:pg # same schema, PostgreSQL -> drizzle/migrations-pg+npm run db:generate:mysql # same schema, MySQL -> drizzle/migrations-mysql+npm run db:smoke -- <DATABASE_URL> [driver] # exercises migrations + query shapes on any database (MAILFLARE_DB_DIALECT must match)npm run db:migrate:local # wrangler d1 migrations apply DB --localnpm run db:migrate:remote # --remote (needs a concrete database_id in wrangler.jsonc)npm run db:seed # POST /api/seed against localhost:3000@@ -28,7 +31,7 @@ There is no test script in `package.json`; the checks under `tests/` are `node:t## Architecture-Next.js App Router APIs running on Cloudflare Workers via vinext. Drizzle ORM over D1, R2 for raw MIME, attachments, and record backups, Queues for async mail processing, a Durable Object for realtime, and a cron trigger for scheduled backups.+Next.js App Router APIs running on Cloudflare Workers via vinext. Drizzle ORM over D1 by default (or PostgreSQL, MySQL, libSQL via `DATABASE_URL`), R2 for raw MIME, attachments, and record backups, Queues for async mail processing, a Durable Object for realtime, and a cron trigger for scheduled backups.### worker.ts is the entrypoint@@ -81,11 +84,22 @@ Consequence: `CF_EMAIL_WORKER_NAME`, the deployed Worker `name`, and `services[]Auth is `CF_TOKEN` (preferred) or the legacy `CF_EMAIL` + `CF_API_KEY` pair.-### Schema and the dual-migration gotcha+### The database is D1 unless `DATABASE_URL` says otherwise-Schema lives in one file: `src/db/schema/index.ts` (21 tables). Migrations are generated into `drizzle/migrations/`. Note that `drizzle-kit generate` currently prompts interactively about a snapshot rename conflict, so recent migrations were hand-written to match the generated style.+`docs/databases.md` is the user-facing reference; this is how it works.-`npm run db:bundle` packages the SQL files for the Worker. `/api/setup/prepare` and the admin migration endpoint use the shared runner in `src/lib/migrations/service.ts`; migration files remain the only schema history to maintain. Build, deploy, preview, and development scripts generate the bundle before loading application code.+- **Selection.** `resolveDatabaseConfig` (`src/db/dialect.ts`, pure) maps `DATABASE_URL` (+ `DATABASE_DRIVER`, `DATABASE_AUTH_TOKEN`, or a `HYPERDRIVE` binding) to a dialect (`sqlite | postgres | mysql`) and driver. No URL means D1 on Workers or the better-sqlite3 file when self-hosted, exactly as before. `withDatabase(env)` (`src/db/with-database.ts`, applied next to `withStorage` in `getEnv()`, each `worker.ts` handler and the Node env) replaces `env.DB` with an `ExternalDatabase`; every caller still reads `env.DB`.+- **One schema, three dialects.** `src/db/schema/index.ts` is written against a kit (`schema/kits.ts`): `table`, `text`, `integer`, `bool`, `timestamp`, `autoId`, `index`, `uniqueIndex`, `desc`, `nowSeconds`. `schemaDialect()` picks the real builders when the module is first imported (from `process.env`, which Workers populate from vars; `MAILFLARE_DB_DIALECT` forces it for tooling), so only one dialect's tables exist per process. The exported tables are *typed* as SQLite whichever dialect is active; that is deliberate, because the app only uses query-builder calls all three share. Representation is kept identical across dialects so raw SQL stays portable: timestamps are seconds in a `bigint`, integers are `bigint`, booleans are native. MySQL needs VARCHAR for anything indexed, so `text()` there returns a recorder resolved in `table()` once the index callback shows which columns are keys; wide indexes are trimmed to InnoDB's 3072 bytes, expression key parts and `uniqueIndex().where()` degrade (see docs).+- **Drivers are executors.** `src/db/drivers/*` turn `(sql, params)` into rows, lazily importing the package (`pg`, `postgres`, `@neondatabase/serverless`, `@electric-sql/pglite` (Node only), `mysql2`, `@planetscale/database`, `@libsql/client`, better-sqlite3, bun:sqlite). `external.ts` feeds an executor to drizzle's `pg-proxy` / `mysql-proxy` / `sqlite-proxy` and to `CompatDatabase` (`d1-compat.ts`), the D1-shaped `prepare().bind().run/first/all`, `batch`, which keeps the ~25 raw `env.DB.prepare` call sites working (`?` becomes `$n` for PostgreSQL). Workers cannot reuse sockets across requests, so TCP drivers connect per query unless `shared` (Node).+- **`compat.ts` keeps the SQLite-shaped API.** It adds `db.run/all/get/values/batch` to PostgreSQL/MySQL instances, and on MySQL shims `insert().onConflictDoNothing/DoUpdate().returning()`, `update().returning()`, `delete().returning()` (ON DUPLICATE KEY UPDATE plus a select by primary key; claims rely on the affected-row count, so mysql2 keeps `FOUND_ROWS` semantics).+- **Dialect-specific SQL lives in `src/db/sql.ts`** (`insensitiveLike`, `excluded`, `greatest`, `charIndex`, `concatText`, `matchNothing`, `escapeLike`) and `src/db/introspect.ts` (`listTableNames`, `listColumnNames`, `quoteIdentifier`). New raw SQL must work on all three: no bare `0`/`1` as a boolean (`WHERE 1 = 0`), no `x = 0` on boolean columns (`NOT x` / `case when x`), no `||` for strings on MySQL, quote reserved words (`key`, `read`, `repeat`, `change`) via `sql.identifier` or drizzle columns, no `ON CONFLICT ... DO UPDATE SET col = col + 1` in raw SQL (use `onConflictDoUpdate` with `sql\`${table.col} + 1\``). Error text matching goes through `src/lib/database-errors.ts`, which knows all three vocabularies.+- **Search.** SQLite keeps the FTS5 index below; PostgreSQL and MySQL have no index and `buildSearchConditions` falls back to case-insensitive substring `LIKE` predicates (pg_trgm GIN indexes are added to PostgreSQL when the extension is allowed).++### Schema and migrations++Schema lives in one file: `src/db/schema/index.ts` (about 60 tables). Each dialect has its own migration directory and bundle: `drizzle/migrations/` (SQLite, full history, ledger `d1_migrations`), `drizzle/migrations-pg/` and `drizzle/migrations-mysql/` (a generated `0000_baseline` plus the hand-written `0001_triggers_and_seeds`, ledger `mailflare_migrations`). **A schema change needs a migration in all three**, plus its trigger/seed twin when it touches `messages`, `folders`, `mailboxes` or `mailbox_aliases`; `tests/database-dialects.test.mjs` fails when the dialects diverge or a bundle is stale. Note that `drizzle-kit generate` currently prompts interactively about a snapshot rename conflict for SQLite, so recent SQLite migrations were hand-written to match the generated style.++`npm run db:bundle` packages the SQL files for the Worker (`src/lib/migrations/bundle.json`, `bundle-postgres.json`, `bundle-mysql.json`). `/api/setup/prepare`, the admin migration endpoint and (self-hosted, non-SQLite) server start use the shared runner in `src/lib/migrations/service.ts`. PostgreSQL and MySQL bundles split only on `--> statement-breakpoint`, because function and trigger bodies contain semicolons. Build, deploy, preview, and development scripts generate the bundle before loading application code.The setup path only ever initializes an empty database — it refuses to touch one that already has tables.@@ -105,7 +119,7 @@ The app reaches every platform service through `getEnv()` (`src/lib/cloudflare.t`processRequest` memoizes the accessible mailboxes and the change scope on `ctx.memo` across read-only calls of one request; write methods run with `memo: null` because they read `oldState` and `newState` in the same call.-States are positions in a change log (`changes.ts`): the `jmap_changes_*` triggers of migration 0064 write a row per created, updated or destroyed message and per folder or mailbox change into `jmap_changes`, so `Email/changes`, `Mailbox/changes` and `Thread/changes` return real deltas (`Email/queryChanges` still answers `cannotCalculateChanges`). A state is `c1:<seq>:<access fingerprint>`; a sharing change alters the fingerprint, and the daily cron prunes rows older than 30 days and raises `jmap_change_floor`, and either makes older states answer `cannotCalculateChanges`. Like `jmap_mailbox_revisions`, these tables are derived and excluded from backups. Never write to them from application code.+States are positions in a change log (`changes.ts`): the `jmap_changes_*` triggers of migration 0064 (PostgreSQL and MySQL: `0001_triggers_and_seeds`) write a row per created, updated or destroyed message and per folder or mailbox change into `jmap_changes`, so `Email/changes`, `Mailbox/changes` and `Thread/changes` return real deltas (`Email/queryChanges` still answers `cannotCalculateChanges`). A state is `c1:<seq>:<access fingerprint>`; a sharing change alters the fingerprint, and the daily cron prunes rows older than 30 days and raises `jmap_change_floor`, and either makes older states answer `cannotCalculateChanges`. Like `jmap_mailbox_revisions`, these tables are derived and excluded from backups. Never write to them from application code.### Mobile apps: device keys and native push@@ -141,7 +155,7 @@ Optional tables are detected with `isMissingTableError` (`src/lib/database-error### Search is an FTS5 index kept by triggers-`messages_fts` (migration 0030) is an external-content FTS5 table over `messages`; three triggers in the same migration keep it in sync on insert, update and delete, so no application code touches the index. `buildSearchConditions` in `src/lib/search/conditions.ts` turns the Gmail-style grammar (`src/lib/search/query-utils.ts`) into a `rowid IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ?)` predicate plus plain column filters. Two consequences: the bootstrap SQL in `src/lib/setup/migration.ts` is split with `splitSqlStatements`, which keeps trigger bodies whole; and the backup coverage check skips `messages_fts%`, since the shadow tables are derived and repopulate on restore. `wrangler d1 export` does not work on databases with virtual tables; the app's own JSON backup is unaffected.+`messages_fts` (migration 0030) is an external-content FTS5 table over `messages` (SQLite only; other dialects use the `LIKE` fallback in `conditions.ts`); three triggers in the same migration keep it in sync on insert, update and delete, so no application code touches the index. `buildSearchConditions` in `src/lib/search/conditions.ts` turns the Gmail-style grammar (`src/lib/search/query-utils.ts`) into a `rowid IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ?)` predicate plus plain column filters. Two consequences: the bootstrap SQL in `src/lib/setup/migration.ts` is split with `splitSqlStatements`, which keeps trigger bodies whole; and the backup coverage check skips `messages_fts%`, since the shadow tables are derived and repopulate on restore. `wrangler d1 export` does not work on databases with virtual tables; the app's own JSON backup is unaffected.### Access controldiff --git a/README.md b/README.mdindex 02b5d1f..5f360fc 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@ Want to support the mailflare? <a target="_blank" href="https://store.paymug.co/Mailflare runs in your Cloudflare account. By default, Cloudflare Email Routing delivers incoming mail to the app, and Cloudflare's email service sends outgoing mail. Each domain can also receive or send through Resend or Amazon SES. Cloudflare still manages the DNS.-Your mail stays in your own D1 database, and attachments stay in your own R2, Backblaze B2 or AWS S3 bucket, whichever provider you use. See [Sending and receiving providers](docs/providers.md).+Your mail stays in your own D1 database (or PostgreSQL, MySQL or libSQL if you set `DATABASE_URL`; see [Databases](docs/databases.md)), and attachments stay in your own R2, Backblaze B2 or AWS S3 bucket, whichever provider you use. See [Sending and receiving providers](docs/providers.md).## Cost@@ -145,6 +145,7 @@ To add a language, create `public/locales/<code>.json` with the same keys as `sr## Documentation- [Deployment and configuration](docs/deployment.md)+- [Databases: D1 (default), Turso/libSQL, PostgreSQL, MySQL and more](docs/databases.md)- [Sending and receiving providers (Cloudflare, Resend, Amazon SES)](docs/providers.md)- [API and integrations](docs/api.md), including the [calendar and booking APIs](docs/api.md#calendar-and-booking)- [Email assistant and MCP](docs/email-assistant-and-mcp.md)diff --git a/docs/databases.md b/docs/databases.mdnew file mode 100644index 0000000..42d6af6--- /dev/null+++ b/docs/databases.md@@ -0,0 +1,132 @@+# Databases++Mailflare stores its data in **Cloudflare D1** by default. Nothing needs configuring for that: deploy with the `DB` binding from `wrangler.jsonc` and you are done.++Set `DATABASE_URL` to use another database instead. Every database [Drizzle ORM](https://orm.drizzle.team) supports is covered by three dialects:++| Dialect | Drivers (`DATABASE_DRIVER`) | Typical services |+| --- | --- | --- |+| SQLite | `d1` (default), `libsql`, `better-sqlite3`, `bun-sqlite` | Cloudflare D1, Turso / libSQL, a local file |+| PostgreSQL | `node-postgres`, `postgres-js`, `neon`, `pglite` | Supabase, Neon, Vercel Postgres, RDS, Cloud SQL, self-hosted, embedded PGlite |+| MySQL | `mysql2`, `planetscale` | MySQL 8, MariaDB 11, TiDB, PlanetScale, Aurora |++The driver is inferred from the URL. Set `DATABASE_DRIVER` only to override it. Names such as `pg`, `postgres`, `supabase`, `vercel`, `turso`, `mysql`, `tidb` and `mariadb` are accepted as aliases.++## Configuration++| Variable | Purpose |+| --- | --- |+| `DATABASE_URL` | Connection string. Unset means D1 (Workers) or the local SQLite file (self-hosted). |+| `DATABASE_DRIVER` | Optional driver override, see the table above. |+| `DATABASE_AUTH_TOKEN` | Auth token for libSQL / Turso. |++On Cloudflare Workers set them as Worker variables or secrets (`npx wrangler secret put DATABASE_URL`). Self-hosted, put them in the container environment (`.env.docker`).++### Per database++| Database | `DATABASE_URL` | Notes |+| --- | --- | --- |+| Cloudflare D1 | unset | Default. Apply migrations with `npm run db:migrate:remote` or from Admin → Settings. |+| Turso / libSQL | `libsql://my-db.turso.io` + `DATABASE_AUTH_TOKEN` | Runs on Workers and Node. |+| Local SQLite file | `file:./data/mailflare.db` | Node only (better-sqlite3). The self-hosted default is already a SQLite file in `DATA_DIR`. |+| Bun SQLite | `file:./mailflare.db` + `DATABASE_DRIVER=bun-sqlite` | Bun only. |+| PostgreSQL | `postgres://user:pass@host:5432/db` | node-postgres. Add `?sslmode=require` where TLS is required. |+| Supabase | the pooler or direct URL from the dashboard | node-postgres. Use the transaction pooler on Workers. |+| Neon / Vercel Postgres | `postgres://…neon.tech/db?sslmode=require` | Detected from the hostname; uses Neon's HTTP driver (works on Workers). `DATABASE_DRIVER=node-postgres` selects TCP instead. |+| postgres.js | any `postgres://` URL + `DATABASE_DRIVER=postgres-js` | |+| PGlite | `pglite://./data/pg` or `pglite://memory` | Embedded Postgres, Node only; useful for development and tests. |+| MySQL / MariaDB / TiDB | `mysql://user:pass@host:3306/db` | mysql2. TiDB Cloud hosts get TLS automatically; `?ssl=true` forces it elsewhere. |+| PlanetScale | `mysql://user:[email protected]/db` | Detected from the hostname; HTTP driver, works on Workers. |+| Hyperdrive (Workers) | `DATABASE_DRIVER=node-postgres` (or `mysql2`) and a `HYPERDRIVE` binding | The binding's connection string is used when `DATABASE_URL` is unset. |++Create an empty database (and user) first. Mailflare creates its tables.++### Workers and the schema dialect++The table definitions are built for the active dialect when the app starts, so on Workers `DATABASE_URL` (or `DATABASE_DRIVER` with a Hyperdrive binding) must be available as a variable or secret, not only at request time. Changing database means a new, empty database: use **Backups** to move data (below).++## Migrations++Migrations are plain SQL, one directory per dialect, applied by the same code everywhere (Admin → Settings, `/api/setup/prepare`, and automatically on start when self-hosted):++| Dialect | Directory | Ledger table |+| --- | --- | --- |+| SQLite | `drizzle/migrations` | `d1_migrations` |+| PostgreSQL | `drizzle/migrations-pg` | `mailflare_migrations` |+| MySQL | `drizzle/migrations-mysql` | `mailflare_migrations` |++PostgreSQL and MySQL start from a single baseline generated from the current schema (`0000_baseline.sql`), followed by `0001_triggers_and_seeds.sql` for what drizzle-kit cannot generate (seed rows and triggers). SQLite keeps its full history.++Changing the schema (`src/db/schema/index.ts`) means generating a migration for each dialect:++```bash+npm run db:generate # SQLite -> drizzle/migrations+npm run db:generate:pg # PostgreSQL -> drizzle/migrations-pg+npm run db:generate:mysql # MySQL -> drizzle/migrations-mysql+npm run db:bundle # rebuild the bundles the Worker applies+```++`tests/database-dialects.test.mjs` fails if the dialects drift apart (different tables or columns, a stale bundle, an unindexable MySQL column).++## What is the same everywhere++The application code is written once. `getDb(env)` and `env.DB` work as before: on other databases `env.DB` is an adapter with the D1 interface (`prepare`, `bind`, `batch`) over the configured driver, and the Drizzle instance is built for the right dialect. Stored values are identical across dialects: timestamps are whole seconds in a `bigint`, booleans are booleans (`tinyint(1)` on MySQL), so SQL fragments and **backups are portable**: a backup taken on D1 restores onto PostgreSQL or MySQL and back.++Also kept on every dialect: foreign keys and cascades, the JMAP change log and mailbox revisions (via triggers), automatic `trashed_at` tracking, and seed rows.++## What differs++| Area | SQLite / D1 | PostgreSQL | MySQL / MariaDB |+| --- | --- | --- | --- |+| Message search | FTS5 index, prefix and column matching | `ILIKE`-style substring scan of subject, addresses and body; accelerated by `pg_trgm` indexes when the extension can be created | Substring `LIKE` scan |+| Search index page (Admin) | Rebuild available | Not applicable (always "indexed") | Not applicable |+| `agent_send_approvals` duplicate-delivery guard | Partial unique index | Partial unique index | Plain index (MySQL has no partial indexes); the status claim still prevents double sends |+| Wide covering indexes on `messages` | Full | Full | Trimmed to fit InnoDB's 3072-byte key limit; expression keys (`coalesce(thread_id, id)`) dropped. Conversation view is slower on very large mailboxes |+| One agent job per mailbox | Atomic in the claim statement | Atomic | Checked just before the claim (small race window) |+| `batch` atomicity | Atomic | Atomic | Atomic for DML; MySQL commits DDL implicitly, so a failed migration can leave earlier statements applied |+| `neon` (HTTP) | n/a | Batches run as separate statements (the HTTP protocol has no interactive transaction); use `node-postgres` for atomic batches | n/a |++Why search is the main difference: FTS5 is an SQLite extension, PostgreSQL's equivalent (`tsvector`) and MySQL's `FULLTEXT` have different grammars and ranking, and the search syntax (`from:`, `subject:`, quoted phrases, `-term`) is translated into plain predicates on those dialects instead. That is correct but unindexed, so searches scan the messages of the mailbox being searched. For large mailboxes, D1/SQLite, or PostgreSQL with `pg_trgm`, searches faster.++Other things to know:++- **Moving between databases** is done with **Admin → Backups**: take a backup, point `DATABASE_URL` at the new empty database, finish setup, restore. Raw mail and attachments live in object storage and are unaffected.+- **Connections.** Self-hosted (Node) uses a connection pool. On Workers a TCP connection cannot outlive a request, so each query opens its own connection; put Hyperdrive (or a pooler such as Supabase's, Neon's or PlanetScale's) in front, or pick an HTTP driver (`neon`, `planetscale`, `libsql`).+- **Case sensitivity.** SQLite and PostgreSQL compare text case-sensitively; MySQL's default collations do not, so on MySQL two accounts whose emails differ only by case collide on the unique index.+- **Reserved words.** All SQL is generated with quoted identifiers; hand-written SQL in your own migrations should quote `key`, `read`, `repeat`, `change` and friends for MySQL.+- **Not covered:** SingleStore and other Drizzle dialects outside SQLite, PostgreSQL and MySQL.++## Trying it locally++```bash+# PostgreSQL without a server+npm run db:smoke -- pglite://memory++# Against 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:[email protected]:5432/mailflare+MAILFLARE_DB_DIALECT=mysql npm run db:smoke -- mysql://root:[email protected]:3306/mailflare+```++`db:smoke` applies the migrations and exercises the query shapes the app relies on (inserts, upserts, `returning`, triggers, batches, search, backups, bookings). Set `MAILFLARE_DB_DIALECT` to match the URL when running it (the app derives it from `DATABASE_URL` by itself).++Self-hosted with Docker Compose and PostgreSQL (add next to the `mailflare` service, then set `DATABASE_URL=postgres://mailflare:change-me@db:5432/mailflare` in `.env.docker`):++```yaml+ 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+```++Run the app itself against another database:++```bash+DATABASE_URL=postgres://postgres:[email protected]:5432/mailflare npm run dev:node+```diff --git a/docs/deployment.md b/docs/deployment.mdindex 767eb20..005d134 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -60,6 +60,8 @@ across deployments so existing browser subscriptions remain valid.Setup applies the committed migrations through the Worker's D1 binding before creating the first admin account.+To store data in PostgreSQL, MySQL, Turso/libSQL or another database instead of D1, set `DATABASE_URL` (and `DATABASE_DRIVER` when it cannot be inferred) as a Worker variable or secret before running setup. The same setup and **Update database** flow then applies that database's migrations. See [Databases](databases.md).+## Step 4: Connect your primary domain and create an account1. Enter a domain that already uses Cloudflare DNS on the same account as your `CF_TOKEN`.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 599e01b..bf697be 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -93,6 +93,8 @@ and the DNS page shows what to set by hand.|---|---|---|| `PORT` | `3000` | HTTP port || `DATA_DIR` | `/data` | SQLite database, blobs and backups |+| `DATABASE_URL` | unset | Use PostgreSQL, MySQL or libSQL instead of the SQLite file in `DATA_DIR`; see [Databases](databases.md). Migrations are applied on start. |+| `DATABASE_DRIVER` | inferred | Only to override the driver inferred from `DATABASE_URL` || `APP_URL` | request origin | Public URL behind a proxy || `SMTP_INBOUND_PORT` | `25` | Inbound SMTP; `0` disables || `MAIL_HOSTNAME` | `mail.<domain>` | Host the MX record points at; SMTP banner |diff --git a/drizzle.config.mysql.ts b/drizzle.config.mysql.tsnew file mode 100644index 0000000..cf840bc--- /dev/null+++ b/drizzle.config.mysql.ts@@ -0,0 +1,8 @@+import { defineConfig } from "drizzle-kit";++// Run with MAILFLARE_DB_DIALECT=mysql (the `db:generate:mysql` script does this). Also covers MariaDB and TiDB.+export default defineConfig({+ schema: "./src/db/schema/index.ts",+ out: "./drizzle/migrations-mysql",+ dialect: "mysql",+});diff --git a/drizzle.config.pg.ts b/drizzle.config.pg.tsnew file mode 100644index 0000000..6a1a106--- /dev/null+++ b/drizzle.config.pg.ts@@ -0,0 +1,9 @@+import { defineConfig } from "drizzle-kit";++// Run with MAILFLARE_DB_DIALECT=postgres so the schema module builds pgTable definitions+// (the `db:generate:pg` script does this).+export default defineConfig({+ schema: "./src/db/schema/index.ts",+ out: "./drizzle/migrations-pg",+ dialect: "postgresql",+});diff --git a/drizzle.config.ts b/drizzle.config.tsindex cbf2014..203ffd4 100644--- a/drizzle.config.ts+++ b/drizzle.config.ts@@ -1,5 +1,7 @@import { defineConfig } from "drizzle-kit";+// SQLite (D1, libSQL, better-sqlite3). PostgreSQL and MySQL have their own configs:+// drizzle.config.pg.ts and drizzle.config.mysql.ts.export default defineConfig({schema: "./src/db/schema/index.ts",out: "./drizzle/migrations",diff --git a/drizzle/migrations-mysql/0000_baseline.sql b/drizzle/migrations-mysql/0000_baseline.sqlnew file mode 100644index 0000000..bdb49ee--- /dev/null+++ b/drizzle/migrations-mysql/0000_baseline.sql@@ -0,0 +1,897 @@+CREATE TABLE `agent_chat_messages` (+ `id` varchar(191) NOT NULL,+ `conversation_id` varchar(191) NOT NULL,+ `role` varchar(64) NOT NULL,+ `content` longtext NOT NULL,+ `tool_name` longtext,+ `created_at` bigint NOT NULL,+ CONSTRAINT `agent_chat_messages_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `agent_conversations` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `title` longtext NOT NULL DEFAULT ('New conversation'),+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `agent_conversations_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `agent_draft_metadata` (+ `draft_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `origin` varchar(64) NOT NULL,+ `source_message_id` varchar(191),+ `revision` bigint NOT NULL DEFAULT 1,+ `human_edited_at` bigint,+ `scheduled_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `agent_draft_metadata_draft_id` PRIMARY KEY(`draft_id`)+);+--> statement-breakpoint+CREATE TABLE `agent_jobs` (+ `id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `source_message_id` varchar(191) NOT NULL,+ `reviewer_user_id` varchar(191) NOT NULL,+ `status` varchar(64) NOT NULL DEFAULT 'pending',+ `attempts` bigint NOT NULL DEFAULT 0,+ `next_attempt_at` bigint NOT NULL,+ `lease_until` bigint,+ `draft_id` varchar(191),+ `reason` longtext,+ `created_at` bigint NOT NULL,+ CONSTRAINT `agent_jobs_id` PRIMARY KEY(`id`),+ CONSTRAINT `agent_jobs_source_idx` UNIQUE(`mailbox_id`,`source_message_id`)+);+--> statement-breakpoint+CREATE TABLE `agent_send_approvals` (+ `id` varchar(191) NOT NULL,+ `draft_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `request_key_id` varchar(191),+ `revision` bigint NOT NULL,+ `payload_hash` longtext NOT NULL,+ `status` varchar(64) NOT NULL DEFAULT 'pending',+ `claimed_at` bigint,+ `message_id` longtext,+ `expires_at` bigint NOT NULL,+ `created_at` bigint NOT NULL,+ CONSTRAINT `agent_send_approvals_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `ai_usage` (+ `id` varchar(191) NOT NULL,+ `created_at` bigint NOT NULL,+ `provider` longtext NOT NULL,+ `model` longtext NOT NULL,+ `source` longtext NOT NULL,+ `input_tokens` bigint,+ `output_tokens` bigint,+ `cost_usd_micros` bigint,+ CONSTRAINT `ai_usage_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `api_keys` (+ `id` varchar(191) NOT NULL,+ `kind` varchar(64) NOT NULL DEFAULT 'legacy',+ `user_id` varchar(191) NOT NULL,+ `name` longtext NOT NULL,+ `prefix` longtext NOT NULL,+ `key_hash` longtext NOT NULL,+ `scopes` longtext NOT NULL,+ `mailbox_scope_enabled` boolean NOT NULL DEFAULT false,+ `created_at` bigint NOT NULL,+ `last_used_at` bigint,+ CONSTRAINT `api_keys_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `app_settings` (+ `id` varchar(191) NOT NULL,+ `app_name` longtext NOT NULL DEFAULT ('Mailflare'),+ `outbound_attachment_max_mb` bigint NOT NULL DEFAULT 25,+ `drive_storage_limit_bytes` bigint,+ `resend_api_key` longtext,+ `aws_config` longtext,+ `ses_receiving` longtext,+ `resend_webhook_id` longtext,+ `resend_webhook_secret` longtext,+ `icon_key` longtext,+ `agent_enabled` boolean NOT NULL DEFAULT true,+ `agent_provider` varchar(64),+ `agent_preset` varchar(64),+ `agent_base_url` longtext,+ `agent_api_key` longtext,+ `agent_model` longtext,+ `agent_model_rates` longtext,+ `spamhaus_dqs_key` longtext,+ `abusech_auth_key` longtext,+ `spam_domain_age_check` boolean NOT NULL DEFAULT true,+ `spam_brands` longtext,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `app_settings_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `audit_logs` (+ `id` varchar(191) NOT NULL,+ `actor_user_id` varchar(191),+ `target_user_id` varchar(191),+ `mailbox_id` varchar(191),+ `message_id` varchar(191),+ `action` longtext NOT NULL,+ `metadata` longtext,+ `created_at` bigint NOT NULL,+ CONSTRAINT `audit_logs_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `auto_reply_deliveries` (+ `id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `recipient` varchar(320) NOT NULL,+ `sent_at` bigint NOT NULL,+ CONSTRAINT `auto_reply_deliveries_id` PRIMARY KEY(`id`),+ CONSTRAINT `auto_reply_deliveries_mailbox_recipient_idx` UNIQUE(`mailbox_id`,`recipient`)+);+--> statement-breakpoint+CREATE TABLE `backup_settings` (+ `id` varchar(191) NOT NULL,+ `enabled` boolean NOT NULL DEFAULT true,+ `schedule_type` varchar(64) NOT NULL DEFAULT 'daily',+ `schedule_value` bigint,+ `retention_enabled` boolean NOT NULL DEFAULT false,+ `retention_days` bigint NOT NULL DEFAULT 30,+ `excluded_table_groups` longtext NOT NULL DEFAULT ('[]'),+ `updated_at` bigint NOT NULL,+ CONSTRAINT `backup_settings_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `backups` (+ `id` varchar(191) NOT NULL,+ `status` varchar(64) NOT NULL DEFAULT 'queued',+ `trigger` varchar(64) NOT NULL,+ `r2_key` longtext,+ `filename` longtext,+ `size` bigint,+ `error` longtext,+ `created_by_user_id` varchar(191),+ `created_at` bigint NOT NULL,+ `started_at` bigint,+ `completed_at` bigint,+ CONSTRAINT `backups_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `booking_events` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `name` longtext NOT NULL,+ `slug` varchar(191) NOT NULL DEFAULT '',+ `description` longtext NOT NULL DEFAULT (''),+ `color` longtext NOT NULL DEFAULT ('#2563eb'),+ `host_ids` longtext NOT NULL DEFAULT ('[]'),+ `duration_minutes` bigint NOT NULL,+ `location` longtext NOT NULL DEFAULT (''),+ `weekdays` longtext NOT NULL DEFAULT ('[1,2,3,4,5]'),+ `start_time` longtext NOT NULL DEFAULT ('09:00'),+ `end_time` longtext NOT NULL DEFAULT ('17:00'),+ `time_ranges` longtext NOT NULL DEFAULT ('[{"startTime":"09:00","endTime":"17:00"}]'),+ `time_zone` longtext NOT NULL DEFAULT ('UTC'),+ `enabled` boolean NOT NULL DEFAULT true,+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `booking_events_id` PRIMARY KEY(`id`),+ CONSTRAINT `booking_events_user_slug_idx` UNIQUE(`user_id`,`slug`)+);+--> statement-breakpoint+CREATE TABLE `calendar_events` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191),+ `title` longtext NOT NULL,+ `description` longtext NOT NULL DEFAULT (''),+ `location` longtext NOT NULL DEFAULT (''),+ `attendees` longtext NOT NULL DEFAULT ('[]'),+ `color` longtext NOT NULL DEFAULT ('blue'),+ `repeat` varchar(64) NOT NULL DEFAULT 'none',+ `repeat_days` longtext NOT NULL DEFAULT ('[]'),+ `repeat_anchor_day` bigint,+ `repeat_until` bigint,+ `excluded_occurrences` longtext NOT NULL DEFAULT ('[]'),+ `time_zone` longtext,+ `starts_at` bigint NOT NULL,+ `ends_at` bigint NOT NULL,+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `calendar_events_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `contacts` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `email` varchar(320) NOT NULL,+ `display_name` longtext,+ `avatar_key` longtext,+ `source` varchar(64) NOT NULL DEFAULT 'inbound',+ `blocked` boolean NOT NULL DEFAULT false,+ `remote_content_allowed` boolean NOT NULL DEFAULT false,+ `last_seen_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `contacts_id` PRIMARY KEY(`id`),+ CONSTRAINT `contacts_user_email_idx` UNIQUE(`user_id`,`email`)+);+--> statement-breakpoint+CREATE TABLE `domain_tracking_hosts` (+ `domain_id` varchar(191) NOT NULL,+ `hostname` varchar(255) NOT NULL,+ `created_at` bigint NOT NULL,+ CONSTRAINT `domain_tracking_hosts_domain_id` PRIMARY KEY(`domain_id`),+ CONSTRAINT `domain_tracking_hosts_hostname_idx` UNIQUE(`hostname`)+);+--> statement-breakpoint+CREATE TABLE `domains` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `hostname` varchar(255) NOT NULL,+ `zone_id` longtext NOT NULL,+ `status` varchar(64) NOT NULL DEFAULT 'pending',+ `routing_status` longtext,+ `sending_subdomain_tag` longtext,+ `sending_provider` varchar(64) NOT NULL DEFAULT 'none',+ `receiving_provider` varchar(64) NOT NULL DEFAULT 'cloudflare',+ `sending_requested` boolean NOT NULL DEFAULT false,+ `sending_enabled` boolean NOT NULL DEFAULT false,+ `routing_enabled` boolean NOT NULL DEFAULT false,+ `dns_skipped` boolean NOT NULL DEFAULT false,+ `created_at` bigint NOT NULL,+ CONSTRAINT `domains_id` PRIMARY KEY(`id`),+ CONSTRAINT `domains_hostname_idx` UNIQUE(`hostname`)+);+--> statement-breakpoint+CREATE TABLE `drive_items` (+ `id` varchar(191) NOT NULL,+ `owner_id` varchar(191) NOT NULL,+ `parent_id` varchar(191),+ `kind` varchar(64) NOT NULL,+ `name` longtext NOT NULL,+ `r2_key` longtext,+ `size` bigint NOT NULL DEFAULT 0,+ `content_type` longtext NOT NULL DEFAULT ('application/octet-stream'),+ `upload_id` longtext,+ `upload_part_size` bigint,+ `upload_fingerprint` longtext,+ `link_token` varchar(191),+ `trashed_at` bigint,+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `drive_items_id` PRIMARY KEY(`id`),+ CONSTRAINT `drive_items_link_token_idx` UNIQUE(`link_token`)+);+--> statement-breakpoint+CREATE TABLE `drive_shares` (+ `id` varchar(191) NOT NULL,+ `item_id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `role` varchar(64) NOT NULL DEFAULT 'view',+ `created_at` bigint NOT NULL,+ CONSTRAINT `drive_shares_id` PRIMARY KEY(`id`),+ CONSTRAINT `drive_shares_item_user_idx` UNIQUE(`item_id`,`user_id`)+);+--> statement-breakpoint+CREATE TABLE `drive_upload_parts` (+ `item_id` varchar(191) NOT NULL,+ `part_number` bigint NOT NULL,+ `etag` longtext NOT NULL,+ CONSTRAINT `drive_upload_parts_idx` UNIQUE(`item_id`,`part_number`)+);+--> statement-breakpoint+CREATE TABLE `email_templates` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `name` longtext NOT NULL,+ `subject` longtext NOT NULL DEFAULT (''),+ `text_body` longtext NOT NULL DEFAULT (''),+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `email_templates_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `folders` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `name` varchar(255) NOT NULL,+ `color` longtext NOT NULL DEFAULT ('#2563eb'),+ `created_at` bigint NOT NULL,+ CONSTRAINT `folders_id` PRIMARY KEY(`id`),+ CONSTRAINT `folders_mailbox_name_idx` UNIQUE(`mailbox_id`,`name`)+);+--> statement-breakpoint+CREATE TABLE `follow_ups` (+ `id` varchar(191) NOT NULL,+ `message_id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `due_at` bigint NOT NULL,+ `status` varchar(64) NOT NULL DEFAULT 'pending',+ `created_at` bigint NOT NULL,+ CONSTRAINT `follow_ups_id` PRIMARY KEY(`id`),+ CONSTRAINT `follow_ups_message_idx` UNIQUE(`message_id`)+);+--> statement-breakpoint+CREATE TABLE `import_jobs` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `kind` varchar(64) NOT NULL,+ `label` longtext NOT NULL,+ `status` varchar(64) NOT NULL DEFAULT 'queued',+ `total` bigint NOT NULL DEFAULT 0,+ `processed` bigint NOT NULL DEFAULT 0,+ `imported` bigint NOT NULL DEFAULT 0,+ `skipped` bigint NOT NULL DEFAULT 0,+ `spec` longtext NOT NULL,+ `cursor` longtext NOT NULL DEFAULT ('{}'),+ `errors` longtext NOT NULL DEFAULT ('[]'),+ `error_count` bigint NOT NULL DEFAULT 0,+ `error` longtext,+ `created_at` bigint NOT NULL,+ `started_at` bigint,+ `updated_at` bigint NOT NULL,+ `finished_at` bigint,+ CONSTRAINT `import_jobs_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `jmap_change_floor` (+ `id` bigint NOT NULL,+ `seq` bigint NOT NULL DEFAULT 0,+ CONSTRAINT `jmap_change_floor_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `jmap_changes` (+ `seq` bigint AUTO_INCREMENT NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `object_type` varchar(64) NOT NULL,+ `object_id` longtext NOT NULL,+ `thread_id` longtext,+ `change` varchar(64) NOT NULL,+ `created_at` bigint NOT NULL DEFAULT (unix_timestamp()),+ CONSTRAINT `jmap_changes_seq` PRIMARY KEY(`seq`)+);+--> statement-breakpoint+CREATE TABLE `jmap_mailbox_revisions` (+ `mailbox_id` varchar(191) NOT NULL,+ `revision` bigint NOT NULL DEFAULT 0,+ CONSTRAINT `jmap_mailbox_revisions_mailbox_id` PRIMARY KEY(`mailbox_id`)+);+--> statement-breakpoint+CREATE TABLE `license_settings` (+ `id` varchar(191) NOT NULL,+ `instance_id` varchar(191) NOT NULL,+ `instance_url` longtext,+ `license_key_hash` longtext,+ `plan` varchar(64) NOT NULL DEFAULT 'community',+ `state` varchar(64) NOT NULL DEFAULT 'inactive',+ `features` longtext NOT NULL DEFAULT ('[]'),+ `seat_limit` bigint DEFAULT 1,+ `activated_at` bigint,+ `validated_at` bigint,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `license_settings_id` PRIMARY KEY(`id`),+ CONSTRAINT `license_settings_instance_id_unique` UNIQUE(`instance_id`)+);+--> statement-breakpoint+CREATE TABLE `login_challenges` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `token_hash` varchar(191) NOT NULL,+ `expires_at` bigint NOT NULL,+ `created_at` bigint NOT NULL,+ CONSTRAINT `login_challenges_id` PRIMARY KEY(`id`),+ CONSTRAINT `login_challenges_token_hash_unique` UNIQUE(`token_hash`)+);+--> statement-breakpoint+CREATE TABLE `mailbox_access` (+ `id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `permission` varchar(64) NOT NULL DEFAULT 'read_only',+ `created_by_user_id` varchar(191),+ `created_at` bigint NOT NULL,+ CONSTRAINT `mailbox_access_id` PRIMARY KEY(`id`),+ CONSTRAINT `mailbox_access_mailbox_user_idx` UNIQUE(`mailbox_id`,`user_id`)+);+--> statement-breakpoint+CREATE TABLE `mailbox_agent_settings` (+ `mailbox_id` varchar(191) NOT NULL,+ `enabled` boolean NOT NULL DEFAULT false,+ `model_id` longtext,+ `auto_draft_enabled` boolean NOT NULL DEFAULT false,+ `reviewer_user_id` varchar(191),+ `instructions` longtext NOT NULL DEFAULT (''),+ `daily_limit` bigint NOT NULL DEFAULT 25,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `mailbox_agent_settings_mailbox_id` PRIMARY KEY(`mailbox_id`)+);+--> statement-breakpoint+CREATE TABLE `mailbox_aliases` (+ `id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `domain_id` varchar(191) NOT NULL,+ `local_part` varchar(191) NOT NULL,+ `created_at` bigint NOT NULL,+ CONSTRAINT `mailbox_aliases_id` PRIMARY KEY(`id`),+ CONSTRAINT `mailbox_aliases_address_idx` UNIQUE(`domain_id`,`local_part`)+);+--> statement-breakpoint+CREATE TABLE `mailboxes` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `domain_id` varchar(191) NOT NULL,+ `local_part` varchar(191) NOT NULL,+ `display_name` longtext,+ `signature` longtext,+ `auto_reply_enabled` boolean NOT NULL DEFAULT false,+ `auto_reply_subject` longtext NOT NULL DEFAULT ('Out of office'),+ `auto_reply_body` longtext NOT NULL DEFAULT (''),+ `avatar_key` longtext,+ `type` varchar(64) NOT NULL DEFAULT 'personal',+ `use_all_domains` boolean NOT NULL DEFAULT true,+ `disabled` boolean NOT NULL DEFAULT false,+ `created_at` bigint NOT NULL,+ CONSTRAINT `mailboxes_id` PRIMARY KEY(`id`),+ CONSTRAINT `mailboxes_address_idx` UNIQUE(`domain_id`,`local_part`)+);+--> statement-breakpoint+CREATE TABLE `mcp_key_mailboxes` (+ `key_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ CONSTRAINT `mcp_key_mailbox_idx` UNIQUE(`key_id`,`mailbox_id`)+);+--> statement-breakpoint+CREATE TABLE `message_attachments` (+ `id` varchar(191) NOT NULL,+ `message_id` varchar(191) NOT NULL,+ `filename` longtext NOT NULL,+ `content_type` longtext NOT NULL,+ `size` bigint NOT NULL,+ `disposition` varchar(64) NOT NULL DEFAULT 'attachment',+ `content_id` longtext,+ `r2_key` varchar(512) NOT NULL,+ `trashed_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `message_attachments_id` PRIMARY KEY(`id`),+ CONSTRAINT `message_attachments_r2_key_unique` UNIQUE(`r2_key`)+);+--> statement-breakpoint+CREATE TABLE `message_opens` (+ `id` varchar(191) NOT NULL,+ `token` varchar(191) NOT NULL,+ `opened_at` bigint NOT NULL,+ `client` longtext,+ `device` longtext,+ `country` longtext,+ `city` longtext,+ `automated` boolean NOT NULL DEFAULT false,+ CONSTRAINT `message_opens_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `message_tracking` (+ `token` varchar(191) NOT NULL,+ `message_id` varchar(191) NOT NULL,+ `open_count` bigint NOT NULL DEFAULT 0,+ `first_opened_at` bigint,+ `last_opened_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `message_tracking_token` PRIMARY KEY(`token`),+ CONSTRAINT `message_tracking_message_idx` UNIQUE(`message_id`)+);+--> statement-breakpoint+CREATE TABLE `messages` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191),+ `direction` varchar(64) NOT NULL,+ `provider_message_id` varchar(512),+ `folder_id` varchar(191),+ `from_addr` longtext NOT NULL,+ `to_addr` longtext NOT NULL,+ `cc_addr` longtext,+ `bcc_addr` longtext,+ `reply_to` longtext,+ `subject` longtext,+ `snippet` longtext,+ `text_body` longtext,+ `html_body` longtext,+ `raw_r2_key` varchar(512),+ `status` varchar(191) NOT NULL DEFAULT 'received',+ `read` boolean NOT NULL DEFAULT false,+ `starred` boolean NOT NULL DEFAULT false,+ `snoozed_until` bigint,+ `thread_id` varchar(512),+ `in_reply_to` longtext,+ `references_header` longtext,+ `spam_score` bigint,+ `spam_verdict` varchar(64),+ `spam_signals` longtext,+ `spam_analyzed_at` bigint,+ `spam_analysis_error` longtext,+ `trashed_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `messages_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `mfa_recovery_codes` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `code_hash` varchar(191) NOT NULL,+ `used_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `mfa_recovery_codes_id` PRIMARY KEY(`id`),+ CONSTRAINT `mfa_recovery_codes_code_hash_unique` UNIQUE(`code_hash`)+);+--> statement-breakpoint+CREATE TABLE `outbound_jobs` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `message_id` varchar(191),+ `status` varchar(64) NOT NULL DEFAULT 'queued',+ `payload` longtext NOT NULL,+ `error` longtext,+ `scheduled_at` bigint,+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `outbound_jobs_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `password_reset_tokens` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `token_hash` varchar(191) NOT NULL,+ `expires_at` bigint NOT NULL,+ `used_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `password_reset_tokens_id` PRIMARY KEY(`id`),+ CONSTRAINT `password_reset_tokens_token_hash_unique` UNIQUE(`token_hash`)+);+--> statement-breakpoint+CREATE TABLE `push_devices` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `api_key_id` varchar(191) NOT NULL,+ `platform` varchar(64) NOT NULL,+ `token` varchar(191) NOT NULL,+ `environment` varchar(64) NOT NULL DEFAULT 'production',+ `topic` longtext NOT NULL,+ `public_key` longtext,+ `previews` boolean NOT NULL DEFAULT true,+ `client_ref` longtext,+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `push_devices_id` PRIMARY KEY(`id`),+ CONSTRAINT `push_devices_platform_token_user_idx` UNIQUE(`platform`,`token`,`user_id`)+);+--> statement-breakpoint+CREATE TABLE `push_subscriptions` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `session_id` varchar(191) NOT NULL,+ `endpoint` varchar(512) NOT NULL,+ `p256dh` longtext NOT NULL,+ `auth` longtext NOT NULL,+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `push_subscriptions_id` PRIMARY KEY(`id`),+ CONSTRAINT `push_subscriptions_endpoint_idx` UNIQUE(`endpoint`)+);+--> statement-breakpoint+CREATE TABLE `routing_rules` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `domain_id` varchar(191) NOT NULL,+ `scope` varchar(64) NOT NULL DEFAULT 'mailbox',+ `name` longtext,+ `enabled` boolean NOT NULL DEFAULT true,+ `pattern` longtext NOT NULL,+ `match_field` varchar(64) NOT NULL DEFAULT 'email',+ `match_operator` varchar(64) NOT NULL DEFAULT 'contains',+ `match_value` longtext NOT NULL DEFAULT (''),+ `mailbox_id` varchar(191),+ `folder_id` varchar(191),+ `action` varchar(64) NOT NULL DEFAULT 'store',+ `forward_to` longtext,+ `keep_copy` boolean NOT NULL DEFAULT false,+ `reject_reason` longtext,+ `priority` bigint NOT NULL DEFAULT 0,+ `last_matched_at` bigint,+ `match_count` bigint NOT NULL DEFAULT 0,+ `created_at` bigint NOT NULL,+ CONSTRAINT `routing_rules_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `sessions` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `token_hash` varchar(191) NOT NULL,+ `expires_at` bigint NOT NULL,+ `created_at` bigint NOT NULL,+ CONSTRAINT `sessions_id` PRIMARY KEY(`id`),+ CONSTRAINT `sessions_token_hash_unique` UNIQUE(`token_hash`)+);+--> statement-breakpoint+CREATE TABLE `shared_attachment_links` (+ `id` varchar(191) NOT NULL,+ `attachment_id` varchar(191) NOT NULL,+ `expires_at` bigint NOT NULL,+ `created_at` bigint NOT NULL,+ CONSTRAINT `shared_attachment_links_id` PRIMARY KEY(`id`),+ CONSTRAINT `shared_attachment_links_attachment_id_unique` UNIQUE(`attachment_id`)+);+--> statement-breakpoint+CREATE TABLE `spam_feedback` (+ `message_id` varchar(191) NOT NULL,+ `mailbox_id` varchar(191) NOT NULL,+ `actor_user_id` varchar(191),+ `classification` varchar(64) NOT NULL,+ `training_tokens` longtext NOT NULL,+ `reputation_keys` longtext NOT NULL,+ `tokenizer_version` bigint NOT NULL DEFAULT 1,+ `created_at` bigint NOT NULL,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `spam_feedback_message_id` PRIMARY KEY(`message_id`)+);+--> statement-breakpoint+CREATE TABLE `spam_reputation` (+ `mailbox_id` varchar(191) NOT NULL,+ `type` varchar(64) NOT NULL,+ `key` varchar(191) NOT NULL,+ `messages_seen` bigint NOT NULL DEFAULT 0,+ `spam_count` bigint NOT NULL DEFAULT 0,+ `ham_count` bigint NOT NULL DEFAULT 0,+ `first_seen_at` bigint NOT NULL,+ `last_seen_at` bigint NOT NULL,+ CONSTRAINT `spam_reputation_mailbox_type_key_idx` UNIQUE(`mailbox_id`,`type`,`key`)+);+--> statement-breakpoint+CREATE TABLE `spam_token_stats` (+ `mailbox_id` varchar(191) NOT NULL,+ `token` varchar(191) NOT NULL,+ `spam_count` bigint NOT NULL DEFAULT 0,+ `ham_count` bigint NOT NULL DEFAULT 0,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `spam_token_stats_mailbox_token_idx` UNIQUE(`mailbox_id`,`token`)+);+--> statement-breakpoint+CREATE TABLE `user_compose_preferences` (+ `user_id` varchar(191) NOT NULL,+ `track_opens_default` boolean NOT NULL DEFAULT false,+ `undo_send_seconds` bigint NOT NULL DEFAULT 15,+ `updated_at` bigint NOT NULL,+ CONSTRAINT `user_compose_preferences_user_id` PRIMARY KEY(`user_id`)+);+--> statement-breakpoint+CREATE TABLE `users` (+ `id` varchar(191) NOT NULL,+ `email` varchar(320) NOT NULL,+ `reset_email` longtext,+ `forwarding_email` longtext,+ `password_hash` longtext NOT NULL,+ `name` longtext NOT NULL,+ `booking_username` varchar(191),+ `time_zone` longtext,+ `avatar_key` longtext,+ `role` varchar(64) NOT NULL DEFAULT 'user',+ `is_primary_admin` boolean NOT NULL DEFAULT false,+ `disabled` boolean NOT NULL DEFAULT false,+ `can_manage_mailboxes` boolean NOT NULL DEFAULT false,+ `can_manage_domains` boolean NOT NULL DEFAULT false,+ `can_manage_users` boolean NOT NULL DEFAULT false,+ `keyboard_shortcuts_enabled` boolean NOT NULL DEFAULT true,+ `spam_protection_enabled` boolean NOT NULL DEFAULT true,+ `trash_retention_days` bigint,+ `show_full_recipient_addresses` boolean NOT NULL DEFAULT false,+ `remote_content_mode` varchar(64) NOT NULL DEFAULT 'allow',+ `totp_secret` longtext,+ `totp_enabled` boolean NOT NULL DEFAULT false,+ `totp_confirmed_at` bigint,+ `last_sign_in_at` bigint,+ `deleted_at` bigint,+ `created_by_user_id` varchar(191),+ `created_at` bigint NOT NULL,+ CONSTRAINT `users_id` PRIMARY KEY(`id`),+ CONSTRAINT `users_email_unique` UNIQUE(`email`),+ CONSTRAINT `users_booking_username_idx` UNIQUE(`booking_username`)+);+--> statement-breakpoint+CREATE TABLE `webhook_deliveries` (+ `id` varchar(191) NOT NULL,+ `webhook_id` varchar(191) NOT NULL,+ `event_type` longtext NOT NULL,+ `payload` longtext NOT NULL,+ `status` varchar(191) NOT NULL DEFAULT 'pending',+ `attempts` bigint NOT NULL DEFAULT 0,+ `response_status` bigint,+ `error` longtext,+ `duration_ms` bigint,+ `last_attempt_at` bigint,+ `next_retry_at` bigint,+ `created_at` bigint NOT NULL,+ CONSTRAINT `webhook_deliveries_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+CREATE TABLE `webhooks` (+ `id` varchar(191) NOT NULL,+ `user_id` varchar(191) NOT NULL,+ `description` longtext,+ `url` longtext NOT NULL,+ `secret` longtext NOT NULL,+ `events` longtext NOT NULL,+ `enabled` boolean NOT NULL DEFAULT true,+ `max_attempts` bigint NOT NULL DEFAULT 5,+ `created_at` bigint NOT NULL,+ CONSTRAINT `webhooks_id` PRIMARY KEY(`id`)+);+--> statement-breakpoint+ALTER TABLE `agent_chat_messages` ADD CONSTRAINT `agent_chat_messages_conversation_id_agent_conversations_id_fk` FOREIGN KEY (`conversation_id`) REFERENCES `agent_conversations`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_conversations` ADD CONSTRAINT `agent_conversations_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_conversations` ADD CONSTRAINT `agent_conversations_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_draft_metadata` ADD CONSTRAINT `agent_draft_metadata_draft_id_messages_id_fk` FOREIGN KEY (`draft_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_draft_metadata` ADD CONSTRAINT `agent_draft_metadata_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_draft_metadata` ADD CONSTRAINT `agent_draft_metadata_source_message_id_messages_id_fk` FOREIGN KEY (`source_message_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_source_message_id_messages_id_fk` FOREIGN KEY (`source_message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_reviewer_user_id_users_id_fk` FOREIGN KEY (`reviewer_user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_draft_id_messages_id_fk` FOREIGN KEY (`draft_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_draft_id_messages_id_fk` FOREIGN KEY (`draft_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_request_key_id_api_keys_id_fk` FOREIGN KEY (`request_key_id`) REFERENCES `api_keys`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `api_keys` ADD CONSTRAINT `api_keys_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_actor_user_id_users_id_fk` FOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_target_user_id_users_id_fk` FOREIGN KEY (`target_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `auto_reply_deliveries` ADD CONSTRAINT `auto_reply_deliveries_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `backups` ADD CONSTRAINT `backups_created_by_user_id_users_id_fk` FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `booking_events` ADD CONSTRAINT `booking_events_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `calendar_events` ADD CONSTRAINT `calendar_events_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `calendar_events` ADD CONSTRAINT `calendar_events_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `contacts` ADD CONSTRAINT `contacts_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `domain_tracking_hosts` ADD CONSTRAINT `domain_tracking_hosts_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `domains` ADD CONSTRAINT `domains_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `drive_items` ADD CONSTRAINT `drive_items_owner_id_users_id_fk` FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `drive_shares` ADD CONSTRAINT `drive_shares_item_id_drive_items_id_fk` FOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `drive_shares` ADD CONSTRAINT `drive_shares_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `drive_upload_parts` ADD CONSTRAINT `drive_upload_parts_item_id_drive_items_id_fk` FOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `email_templates` ADD CONSTRAINT `email_templates_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `folders` ADD CONSTRAINT `folders_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `folders` ADD CONSTRAINT `folders_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `follow_ups` ADD CONSTRAINT `follow_ups_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `follow_ups` ADD CONSTRAINT `follow_ups_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `import_jobs` ADD CONSTRAINT `import_jobs_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `import_jobs` ADD CONSTRAINT `import_jobs_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `login_challenges` ADD CONSTRAINT `login_challenges_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailbox_access` ADD CONSTRAINT `mailbox_access_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailbox_access` ADD CONSTRAINT `mailbox_access_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailbox_access` ADD CONSTRAINT `mailbox_access_created_by_user_id_users_id_fk` FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailbox_agent_settings` ADD CONSTRAINT `mailbox_agent_settings_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailbox_agent_settings` ADD CONSTRAINT `mailbox_agent_settings_reviewer_user_id_users_id_fk` FOREIGN KEY (`reviewer_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailbox_aliases` ADD CONSTRAINT `mailbox_aliases_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailbox_aliases` ADD CONSTRAINT `mailbox_aliases_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailboxes` ADD CONSTRAINT `mailboxes_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mailboxes` ADD CONSTRAINT `mailboxes_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mcp_key_mailboxes` ADD CONSTRAINT `mcp_key_mailboxes_key_id_api_keys_id_fk` FOREIGN KEY (`key_id`) REFERENCES `api_keys`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mcp_key_mailboxes` ADD CONSTRAINT `mcp_key_mailboxes_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `message_attachments` ADD CONSTRAINT `message_attachments_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `message_opens` ADD CONSTRAINT `message_opens_token_message_tracking_token_fk` FOREIGN KEY (`token`) REFERENCES `message_tracking`(`token`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `message_tracking` ADD CONSTRAINT `message_tracking_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `messages` ADD CONSTRAINT `messages_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `messages` ADD CONSTRAINT `messages_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `messages` ADD CONSTRAINT `messages_folder_id_folders_id_fk` FOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `mfa_recovery_codes` ADD CONSTRAINT `mfa_recovery_codes_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `outbound_jobs` ADD CONSTRAINT `outbound_jobs_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `outbound_jobs` ADD CONSTRAINT `outbound_jobs_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `password_reset_tokens` ADD CONSTRAINT `password_reset_tokens_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `push_devices` ADD CONSTRAINT `push_devices_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `push_devices` ADD CONSTRAINT `push_devices_api_key_id_api_keys_id_fk` FOREIGN KEY (`api_key_id`) REFERENCES `api_keys`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `push_subscriptions` ADD CONSTRAINT `push_subscriptions_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `push_subscriptions` ADD CONSTRAINT `push_subscriptions_session_id_sessions_id_fk` FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_folder_id_folders_id_fk` FOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `sessions` ADD CONSTRAINT `sessions_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `shared_attachment_links` ADD CONSTRAINT `shared_attachment_links_attachment_id_message_attachments_id_fk` FOREIGN KEY (`attachment_id`) REFERENCES `message_attachments`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `spam_feedback` ADD CONSTRAINT `spam_feedback_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `spam_feedback` ADD CONSTRAINT `spam_feedback_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `spam_feedback` ADD CONSTRAINT `spam_feedback_actor_user_id_users_id_fk` FOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `spam_reputation` ADD CONSTRAINT `spam_reputation_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `spam_token_stats` ADD CONSTRAINT `spam_token_stats_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `user_compose_preferences` ADD CONSTRAINT `user_compose_preferences_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `users` ADD CONSTRAINT `users_created_by_user_id_users_id_fk` FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `webhook_deliveries` ADD CONSTRAINT `webhook_deliveries_webhook_id_webhooks_id_fk` FOREIGN KEY (`webhook_id`) REFERENCES `webhooks`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE `webhooks` ADD CONSTRAINT `webhooks_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+CREATE INDEX `agent_chat_messages_conversation_idx` ON `agent_chat_messages` (`conversation_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `agent_conversations_owner_idx` ON `agent_conversations` (`user_id`,`mailbox_id`,`updated_at`);--> statement-breakpoint+CREATE INDEX `agent_conversations_mailbox_idx` ON `agent_conversations` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `agent_draft_meta_source_msg_idx` ON `agent_draft_metadata` (`source_message_id`);--> statement-breakpoint+CREATE INDEX `agent_draft_metadata_mailbox_idx` ON `agent_draft_metadata` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `agent_jobs_due_idx` ON `agent_jobs` (`status`,`next_attempt_at`);--> statement-breakpoint+CREATE INDEX `agent_jobs_source_message_idx` ON `agent_jobs` (`source_message_id`);--> statement-breakpoint+CREATE INDEX `agent_jobs_draft_idx` ON `agent_jobs` (`draft_id`);--> statement-breakpoint+CREATE INDEX `agent_jobs_reviewer_idx` ON `agent_jobs` (`reviewer_user_id`);--> statement-breakpoint+CREATE INDEX `agent_send_approvals_user_idx` ON `agent_send_approvals` (`user_id`,`status`);--> statement-breakpoint+CREATE INDEX `agent_send_approvals_delivery_idx` ON `agent_send_approvals` (`draft_id`);--> statement-breakpoint+CREATE INDEX `agent_send_approvals_request_key_idx` ON `agent_send_approvals` (`request_key_id`);--> statement-breakpoint+CREATE INDEX `agent_send_approvals_mailbox_idx` ON `agent_send_approvals` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `agent_send_approvals_draft_idx` ON `agent_send_approvals` (`draft_id`);--> statement-breakpoint+CREATE INDEX `ai_usage_created_idx` ON `ai_usage` (`created_at`);--> statement-breakpoint+CREATE INDEX `api_keys_user_idx` ON `api_keys` (`user_id`);--> statement-breakpoint+CREATE INDEX `audit_logs_actor_idx` ON `audit_logs` (`actor_user_id`);--> statement-breakpoint+CREATE INDEX `audit_logs_mailbox_idx` ON `audit_logs` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `audit_logs_created_idx` ON `audit_logs` (`created_at`);--> statement-breakpoint+CREATE INDEX `audit_logs_message_id_idx` ON `audit_logs` (`message_id`);--> statement-breakpoint+CREATE INDEX `audit_logs_target_user_idx` ON `audit_logs` (`target_user_id`);--> statement-breakpoint+CREATE INDEX `auto_reply_deliveries_sent_idx` ON `auto_reply_deliveries` (`sent_at`);--> statement-breakpoint+CREATE INDEX `backups_created_idx` ON `backups` (`created_at`);--> statement-breakpoint+CREATE INDEX `backups_status_idx` ON `backups` (`status`);--> statement-breakpoint+CREATE INDEX `backups_created_by_idx` ON `backups` (`created_by_user_id`);--> statement-breakpoint+CREATE INDEX `booking_events_user_idx` ON `booking_events` (`user_id`);--> statement-breakpoint+CREATE INDEX `calendar_events_user_starts_idx` ON `calendar_events` (`user_id`,`starts_at`);--> statement-breakpoint+CREATE INDEX `calendar_events_mailbox_idx` ON `calendar_events` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `contacts_user_idx` ON `contacts` (`user_id`);--> statement-breakpoint+CREATE INDEX `domains_user_idx` ON `domains` (`user_id`);--> statement-breakpoint+CREATE INDEX `drive_items_owner_parent_idx` ON `drive_items` (`owner_id`,`parent_id`);--> statement-breakpoint+CREATE INDEX `drive_shares_user_idx` ON `drive_shares` (`user_id`);--> statement-breakpoint+CREATE INDEX `email_templates_user_idx` ON `email_templates` (`user_id`);--> statement-breakpoint+CREATE INDEX `folders_user_idx` ON `folders` (`user_id`);--> statement-breakpoint+CREATE INDEX `folders_mailbox_idx` ON `folders` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `follow_ups_status_due_idx` ON `follow_ups` (`status`,`due_at`);--> statement-breakpoint+CREATE INDEX `follow_ups_user_status_idx` ON `follow_ups` (`user_id`,`status`);--> statement-breakpoint+CREATE INDEX `import_jobs_user_idx` ON `import_jobs` (`user_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `import_jobs_status_idx` ON `import_jobs` (`status`,`updated_at`);--> statement-breakpoint+CREATE INDEX `jmap_changes_mailbox_seq_idx` ON `jmap_changes` (`mailbox_id`,`seq`);--> statement-breakpoint+CREATE INDEX `login_challenges_user_idx` ON `login_challenges` (`user_id`);--> statement-breakpoint+CREATE INDEX `mailbox_access_user_idx` ON `mailbox_access` (`user_id`);--> statement-breakpoint+CREATE INDEX `mailbox_access_mailbox_idx` ON `mailbox_access` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `mailbox_access_created_by_idx` ON `mailbox_access` (`created_by_user_id`);--> statement-breakpoint+CREATE INDEX `mailbox_agent_settings_reviewer_idx` ON `mailbox_agent_settings` (`reviewer_user_id`);--> statement-breakpoint+CREATE INDEX `mailbox_aliases_mailbox_idx` ON `mailbox_aliases` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `mailboxes_user_idx` ON `mailboxes` (`user_id`);--> statement-breakpoint+CREATE INDEX `mcp_key_mailboxes_mailbox_idx` ON `mcp_key_mailboxes` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `message_attachments_message_idx` ON `message_attachments` (`message_id`);--> statement-breakpoint+CREATE INDEX `message_opens_token_idx` ON `message_opens` (`token`,`opened_at`);--> statement-breakpoint+CREATE INDEX `messages_user_created_idx` ON `messages` (`user_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `messages_mailbox_idx` ON `messages` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `messages_folder_idx` ON `messages` (`folder_id`);--> statement-breakpoint+CREATE INDEX `messages_thread_idx` ON `messages` (`mailbox_id`,`thread_id`);--> statement-breakpoint+CREATE INDEX `messages_provider_message_idx` ON `messages` (`mailbox_id`,`provider_message_id`);--> statement-breakpoint+CREATE INDEX `messages_raw_r2_key_idx` ON `messages` (`raw_r2_key`);--> statement-breakpoint+CREATE INDEX `messages_trashed_at_idx` ON `messages` (`trashed_at`);--> statement-breakpoint+CREATE INDEX `messages_inbox_page_idx` ON `messages` (`mailbox_id`,`status`,`folder_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `messages_thread_key_idx` ON `messages` (`mailbox_id`,`status`,`folder_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `messages_mailbox_thread_key_idx` ON `messages` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `messages_nav_cover_idx` ON `messages` (`mailbox_id`,`status`,`folder_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `messages_counts_cover_idx` ON `messages` (`mailbox_id`,`folder_id`,`direction`,`status`,`read`,`starred`,`snoozed_until`);--> statement-breakpoint+CREATE INDEX `messages_conv_cover_idx` ON `messages` (`mailbox_id`,`status`,`created_at`,`id`,`snoozed_until`);--> statement-breakpoint+CREATE INDEX `mfa_recovery_codes_user_idx` ON `mfa_recovery_codes` (`user_id`);--> statement-breakpoint+CREATE INDEX `outbound_jobs_user_idx` ON `outbound_jobs` (`user_id`);--> statement-breakpoint+CREATE INDEX `outbound_jobs_message_idx` ON `outbound_jobs` (`message_id`);--> statement-breakpoint+CREATE INDEX `password_reset_tokens_user_idx` ON `password_reset_tokens` (`user_id`);--> statement-breakpoint+CREATE INDEX `push_devices_user_idx` ON `push_devices` (`user_id`);--> statement-breakpoint+CREATE INDEX `push_devices_api_key_idx` ON `push_devices` (`api_key_id`);--> statement-breakpoint+CREATE INDEX `push_subscriptions_user_idx` ON `push_subscriptions` (`user_id`);--> statement-breakpoint+CREATE INDEX `push_subscriptions_session_idx` ON `push_subscriptions` (`session_id`);--> statement-breakpoint+CREATE INDEX `routing_rules_domain_scope_idx` ON `routing_rules` (`domain_id`,`scope`,`enabled`);--> statement-breakpoint+CREATE INDEX `routing_rules_mailbox_idx` ON `routing_rules` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `routing_rules_priority_idx` ON `routing_rules` (`priority`);--> statement-breakpoint+CREATE INDEX `routing_rules_user_idx` ON `routing_rules` (`user_id`);--> statement-breakpoint+CREATE INDEX `routing_rules_folder_idx` ON `routing_rules` (`folder_id`);--> statement-breakpoint+CREATE INDEX `sessions_user_idx` ON `sessions` (`user_id`);--> statement-breakpoint+CREATE INDEX `spam_feedback_mailbox_idx` ON `spam_feedback` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `spam_feedback_actor_user_idx` ON `spam_feedback` (`actor_user_id`);--> statement-breakpoint+CREATE INDEX `spam_reputation_mailbox_idx` ON `spam_reputation` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `spam_token_stats_mailbox_idx` ON `spam_token_stats` (`mailbox_id`);--> statement-breakpoint+CREATE INDEX `users_created_by_idx` ON `users` (`created_by_user_id`);--> statement-breakpoint+CREATE INDEX `webhook_deliveries_webhook_idx` ON `webhook_deliveries` (`webhook_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `webhook_deliveries_status_idx` ON `webhook_deliveries` (`status`);--> statement-breakpoint+CREATE INDEX `webhooks_user_idx` ON `webhooks` (`user_id`);\ No newline at end of filediff --git a/drizzle/migrations-mysql/0001_triggers_and_seeds.sql b/drizzle/migrations-mysql/0001_triggers_and_seeds.sqlnew file mode 100644index 0000000..5140f64--- /dev/null+++ b/drizzle/migrations-mysql/0001_triggers_and_seeds.sql@@ -0,0 +1,100 @@+-- Objects drizzle-kit does not generate: seed rows, and the triggers that keep+-- them (and messages.trashed_at) current whichever code path writes. The SQLite twins are migrations+-- 0009, 0012, 0042, 0053 and 0064. Message search uses LIKE (see src/lib/search/conditions.ts).+INSERT IGNORE INTO backup_settings (id, enabled, schedule_type, retention_enabled, retention_days, updated_at)+VALUES ('default', false, 'daily', false, 30, unix_timestamp());--> statement-breakpoint+INSERT IGNORE INTO app_settings (id, app_name, updated_at)+VALUES ('default', 'Mailflare', unix_timestamp());--> statement-breakpoint+INSERT IGNORE INTO jmap_change_floor (id, seq) VALUES (1, 0);--> statement-breakpoint+CREATE TRIGGER messages_trashed_at_bi BEFORE INSERT ON messages FOR EACH ROW+BEGIN+ IF NEW.status IN ('trash', 'spam') THEN+ SET NEW.trashed_at = unix_timestamp();+ END IF;+END;--> statement-breakpoint+CREATE TRIGGER messages_trashed_at_bu BEFORE UPDATE ON messages FOR EACH ROW+BEGIN+ IF (NEW.status IN ('trash', 'spam')) <> (OLD.status IN ('trash', 'spam')) THEN+ SET NEW.trashed_at = IF(NEW.status IN ('trash', 'spam'), unix_timestamp(), NULL);+ END IF;+END;--> statement-breakpoint+CREATE TRIGGER messages_jmap_ai AFTER INSERT ON messages FOR EACH ROW+BEGIN+ IF NEW.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');+ END IF;+END;--> statement-breakpoint+CREATE TRIGGER messages_jmap_au AFTER UPDATE ON messages FOR EACH ROW+BEGIN+ IF NEW.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ END IF;+ IF OLD.mailbox_id IS NOT NULL AND NOT (OLD.mailbox_id <=> NEW.mailbox_id) THEN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ END IF;+ IF OLD.mailbox_id <=> NEW.mailbox_id THEN+ IF NEW.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'updated');+ END IF;+ ELSE+ IF OLD.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)+ VALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');+ END IF;+ IF NEW.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');+ END IF;+ END IF;+END;--> statement-breakpoint+CREATE TRIGGER messages_jmap_ad AFTER DELETE ON messages FOR EACH ROW+BEGIN+ IF OLD.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)+ VALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');+ END IF;+END;--> statement-breakpoint+CREATE TRIGGER folders_jmap_ai AFTER INSERT ON folders FOR EACH ROW+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (NEW.mailbox_id, 'mailbox', NEW.id, 'created');+END;--> statement-breakpoint+CREATE TRIGGER folders_jmap_au AFTER UPDATE ON folders FOR EACH ROW+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ IF NOT (OLD.mailbox_id <=> NEW.mailbox_id) THEN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');+ END IF;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`)+ VALUES (NEW.mailbox_id, 'mailbox', NEW.id, IF(OLD.mailbox_id <=> NEW.mailbox_id, 'updated', 'created'));+END;--> statement-breakpoint+CREATE TRIGGER folders_jmap_ad AFTER DELETE ON folders FOR EACH ROW+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');+END;--> statement-breakpoint+CREATE TRIGGER mailboxes_jmap_au AFTER UPDATE ON mailboxes FOR EACH ROW+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (NEW.id, 'mailbox', NEW.id, 'updated');+END;--> statement-breakpoint+CREATE TRIGGER mailbox_aliases_jmap_ai AFTER INSERT ON mailbox_aliases FOR EACH ROW+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+END;--> statement-breakpoint+CREATE TRIGGER mailbox_aliases_jmap_au AFTER UPDATE ON mailbox_aliases FOR EACH ROW+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ IF NOT (OLD.mailbox_id <=> NEW.mailbox_id) THEN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+ END IF;+END;--> statement-breakpoint+CREATE TRIGGER mailbox_aliases_jmap_ad AFTER DELETE ON mailbox_aliases FOR EACH ROW+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;+END;diff --git a/drizzle/migrations-mysql/meta/0000_snapshot.json b/drizzle/migrations-mysql/meta/0000_snapshot.jsonnew file mode 100644index 0000000..beda59b--- /dev/null+++ b/drizzle/migrations-mysql/meta/0000_snapshot.json@@ -0,0 +1,6453 @@+{+ "version": "5",+ "dialect": "mysql",+ "id": "b80e3d7b-c8bf-4112-902d-4e95811a12fb",+ "prevId": "00000000-0000-0000-0000-000000000000",+ "tables": {+ "agent_chat_messages": {+ "name": "agent_chat_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_name": {+ "name": "tool_name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "agent_chat_messages_conversation_idx": {+ "name": "agent_chat_messages_conversation_idx",+ "columns": [+ "conversation_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agent_chat_messages_conversation_id_agent_conversations_id_fk": {+ "name": "agent_chat_messages_conversation_id_agent_conversations_id_fk",+ "tableFrom": "agent_chat_messages",+ "tableTo": "agent_conversations",+ "columnsFrom": [+ "conversation_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_chat_messages_id": {+ "name": "agent_chat_messages_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_conversations": {+ "name": "agent_conversations",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('New conversation')"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "agent_conversations_owner_idx": {+ "name": "agent_conversations_owner_idx",+ "columns": [+ "user_id",+ "mailbox_id",+ "updated_at"+ ],+ "isUnique": false+ },+ "agent_conversations_mailbox_idx": {+ "name": "agent_conversations_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agent_conversations_user_id_users_id_fk": {+ "name": "agent_conversations_user_id_users_id_fk",+ "tableFrom": "agent_conversations",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_conversations_mailbox_id_mailboxes_id_fk": {+ "name": "agent_conversations_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_conversations",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_conversations_id": {+ "name": "agent_conversations_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_draft_metadata": {+ "name": "agent_draft_metadata",+ "columns": {+ "draft_id": {+ "name": "draft_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "origin": {+ "name": "origin",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_message_id": {+ "name": "source_message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "human_edited_at": {+ "name": "human_edited_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "agent_draft_meta_source_msg_idx": {+ "name": "agent_draft_meta_source_msg_idx",+ "columns": [+ "source_message_id"+ ],+ "isUnique": false+ },+ "agent_draft_metadata_mailbox_idx": {+ "name": "agent_draft_metadata_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agent_draft_metadata_draft_id_messages_id_fk": {+ "name": "agent_draft_metadata_draft_id_messages_id_fk",+ "tableFrom": "agent_draft_metadata",+ "tableTo": "messages",+ "columnsFrom": [+ "draft_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_draft_metadata_mailbox_id_mailboxes_id_fk": {+ "name": "agent_draft_metadata_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_draft_metadata",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_draft_metadata_source_message_id_messages_id_fk": {+ "name": "agent_draft_metadata_source_message_id_messages_id_fk",+ "tableFrom": "agent_draft_metadata",+ "tableTo": "messages",+ "columnsFrom": [+ "source_message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_draft_metadata_draft_id": {+ "name": "agent_draft_metadata_draft_id",+ "columns": [+ "draft_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_jobs": {+ "name": "agent_jobs",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_message_id": {+ "name": "source_message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reviewer_user_id": {+ "name": "reviewer_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "lease_until": {+ "name": "lease_until",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "draft_id": {+ "name": "draft_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "reason": {+ "name": "reason",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "agent_jobs_source_idx": {+ "name": "agent_jobs_source_idx",+ "columns": [+ "mailbox_id",+ "source_message_id"+ ],+ "isUnique": true+ },+ "agent_jobs_due_idx": {+ "name": "agent_jobs_due_idx",+ "columns": [+ "status",+ "next_attempt_at"+ ],+ "isUnique": false+ },+ "agent_jobs_source_message_idx": {+ "name": "agent_jobs_source_message_idx",+ "columns": [+ "source_message_id"+ ],+ "isUnique": false+ },+ "agent_jobs_draft_idx": {+ "name": "agent_jobs_draft_idx",+ "columns": [+ "draft_id"+ ],+ "isUnique": false+ },+ "agent_jobs_reviewer_idx": {+ "name": "agent_jobs_reviewer_idx",+ "columns": [+ "reviewer_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agent_jobs_mailbox_id_mailboxes_id_fk": {+ "name": "agent_jobs_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_jobs_source_message_id_messages_id_fk": {+ "name": "agent_jobs_source_message_id_messages_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "messages",+ "columnsFrom": [+ "source_message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_jobs_reviewer_user_id_users_id_fk": {+ "name": "agent_jobs_reviewer_user_id_users_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "users",+ "columnsFrom": [+ "reviewer_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_jobs_draft_id_messages_id_fk": {+ "name": "agent_jobs_draft_id_messages_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "messages",+ "columnsFrom": [+ "draft_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_jobs_id": {+ "name": "agent_jobs_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_send_approvals": {+ "name": "agent_send_approvals",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "draft_id": {+ "name": "draft_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "request_key_id": {+ "name": "request_key_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "payload_hash": {+ "name": "payload_hash",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "claimed_at": {+ "name": "claimed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "message_id": {+ "name": "message_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "agent_send_approvals_user_idx": {+ "name": "agent_send_approvals_user_idx",+ "columns": [+ "user_id",+ "status"+ ],+ "isUnique": false+ },+ "agent_send_approvals_delivery_idx": {+ "name": "agent_send_approvals_delivery_idx",+ "columns": [+ "draft_id"+ ],+ "isUnique": false+ },+ "agent_send_approvals_request_key_idx": {+ "name": "agent_send_approvals_request_key_idx",+ "columns": [+ "request_key_id"+ ],+ "isUnique": false+ },+ "agent_send_approvals_mailbox_idx": {+ "name": "agent_send_approvals_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ },+ "agent_send_approvals_draft_idx": {+ "name": "agent_send_approvals_draft_idx",+ "columns": [+ "draft_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agent_send_approvals_draft_id_messages_id_fk": {+ "name": "agent_send_approvals_draft_id_messages_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "messages",+ "columnsFrom": [+ "draft_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_send_approvals_mailbox_id_mailboxes_id_fk": {+ "name": "agent_send_approvals_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_send_approvals_user_id_users_id_fk": {+ "name": "agent_send_approvals_user_id_users_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_send_approvals_request_key_id_api_keys_id_fk": {+ "name": "agent_send_approvals_request_key_id_api_keys_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "api_keys",+ "columnsFrom": [+ "request_key_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_send_approvals_id": {+ "name": "agent_send_approvals_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "ai_usage": {+ "name": "ai_usage",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cost_usd_micros": {+ "name": "cost_usd_micros",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "ai_usage_created_idx": {+ "name": "ai_usage_created_idx",+ "columns": [+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "ai_usage_id": {+ "name": "ai_usage_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "api_keys": {+ "name": "api_keys",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'legacy'"+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "key_hash": {+ "name": "key_hash",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scopes": {+ "name": "scopes",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_scope_enabled": {+ "name": "mailbox_scope_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "api_keys_user_idx": {+ "name": "api_keys_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "api_keys_user_id_users_id_fk": {+ "name": "api_keys_user_id_users_id_fk",+ "tableFrom": "api_keys",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "api_keys_id": {+ "name": "api_keys_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "app_settings": {+ "name": "app_settings",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "app_name": {+ "name": "app_name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('Mailflare')"+ },+ "outbound_attachment_max_mb": {+ "name": "outbound_attachment_max_mb",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 25+ },+ "drive_storage_limit_bytes": {+ "name": "drive_storage_limit_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resend_api_key": {+ "name": "resend_api_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "aws_config": {+ "name": "aws_config",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ses_receiving": {+ "name": "ses_receiving",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resend_webhook_id": {+ "name": "resend_webhook_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resend_webhook_secret": {+ "name": "resend_webhook_secret",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "icon_key": {+ "name": "icon_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_enabled": {+ "name": "agent_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "agent_provider": {+ "name": "agent_provider",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_preset": {+ "name": "agent_preset",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_base_url": {+ "name": "agent_base_url",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_api_key": {+ "name": "agent_api_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_model": {+ "name": "agent_model",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_model_rates": {+ "name": "agent_model_rates",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spamhaus_dqs_key": {+ "name": "spamhaus_dqs_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "abusech_auth_key": {+ "name": "abusech_auth_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spam_domain_age_check": {+ "name": "spam_domain_age_check",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "spam_brands": {+ "name": "spam_brands",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "app_settings_id": {+ "name": "app_settings_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "audit_logs": {+ "name": "audit_logs",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "target_user_id": {+ "name": "target_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_logs_actor_idx": {+ "name": "audit_logs_actor_idx",+ "columns": [+ "actor_user_id"+ ],+ "isUnique": false+ },+ "audit_logs_mailbox_idx": {+ "name": "audit_logs_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ },+ "audit_logs_created_idx": {+ "name": "audit_logs_created_idx",+ "columns": [+ "created_at"+ ],+ "isUnique": false+ },+ "audit_logs_message_id_idx": {+ "name": "audit_logs_message_id_idx",+ "columns": [+ "message_id"+ ],+ "isUnique": false+ },+ "audit_logs_target_user_idx": {+ "name": "audit_logs_target_user_idx",+ "columns": [+ "target_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_logs_actor_user_id_users_id_fk": {+ "name": "audit_logs_actor_user_id_users_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "users",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "audit_logs_target_user_id_users_id_fk": {+ "name": "audit_logs_target_user_id_users_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "users",+ "columnsFrom": [+ "target_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "audit_logs_mailbox_id_mailboxes_id_fk": {+ "name": "audit_logs_mailbox_id_mailboxes_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "audit_logs_message_id_messages_id_fk": {+ "name": "audit_logs_message_id_messages_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "audit_logs_id": {+ "name": "audit_logs_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "auto_reply_deliveries": {+ "name": "auto_reply_deliveries",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "recipient": {+ "name": "recipient",+ "type": "varchar(320)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sent_at": {+ "name": "sent_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "auto_reply_deliveries_mailbox_recipient_idx": {+ "name": "auto_reply_deliveries_mailbox_recipient_idx",+ "columns": [+ "mailbox_id",+ "recipient"+ ],+ "isUnique": true+ },+ "auto_reply_deliveries_sent_idx": {+ "name": "auto_reply_deliveries_sent_idx",+ "columns": [+ "sent_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "auto_reply_deliveries_mailbox_id_mailboxes_id_fk": {+ "name": "auto_reply_deliveries_mailbox_id_mailboxes_id_fk",+ "tableFrom": "auto_reply_deliveries",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "auto_reply_deliveries_id": {+ "name": "auto_reply_deliveries_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "backup_settings": {+ "name": "backup_settings",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "schedule_type": {+ "name": "schedule_type",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'daily'"+ },+ "schedule_value": {+ "name": "schedule_value",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "retention_enabled": {+ "name": "retention_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "retention_days": {+ "name": "retention_days",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 30+ },+ "excluded_table_groups": {+ "name": "excluded_table_groups",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[]')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "backup_settings_id": {+ "name": "backup_settings_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "backups": {+ "name": "backups",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'queued'"+ },+ "trigger": {+ "name": "trigger",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "filename": {+ "name": "filename",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "size": {+ "name": "size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error": {+ "name": "error",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "backups_created_idx": {+ "name": "backups_created_idx",+ "columns": [+ "created_at"+ ],+ "isUnique": false+ },+ "backups_status_idx": {+ "name": "backups_status_idx",+ "columns": [+ "status"+ ],+ "isUnique": false+ },+ "backups_created_by_idx": {+ "name": "backups_created_by_idx",+ "columns": [+ "created_by_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "backups_created_by_user_id_users_id_fk": {+ "name": "backups_created_by_user_id_users_id_fk",+ "tableFrom": "backups",+ "tableTo": "users",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "backups_id": {+ "name": "backups_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "booking_events": {+ "name": "booking_events",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "description": {+ "name": "description",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "color": {+ "name": "color",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('#2563eb')"+ },+ "host_ids": {+ "name": "host_ids",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[]')"+ },+ "duration_minutes": {+ "name": "duration_minutes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location": {+ "name": "location",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "weekdays": {+ "name": "weekdays",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[1,2,3,4,5]')"+ },+ "start_time": {+ "name": "start_time",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('09:00')"+ },+ "end_time": {+ "name": "end_time",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('17:00')"+ },+ "time_ranges": {+ "name": "time_ranges",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[{\"startTime\":\"09:00\",\"endTime\":\"17:00\"}]')"+ },+ "time_zone": {+ "name": "time_zone",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('UTC')"+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "booking_events_user_idx": {+ "name": "booking_events_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "booking_events_user_slug_idx": {+ "name": "booking_events_user_slug_idx",+ "columns": [+ "user_id",+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "booking_events_user_id_users_id_fk": {+ "name": "booking_events_user_id_users_id_fk",+ "tableFrom": "booking_events",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "booking_events_id": {+ "name": "booking_events_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "calendar_events": {+ "name": "calendar_events",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "location": {+ "name": "location",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "attendees": {+ "name": "attendees",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[]')"+ },+ "color": {+ "name": "color",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('blue')"+ },+ "repeat": {+ "name": "repeat",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "repeat_days": {+ "name": "repeat_days",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[]')"+ },+ "repeat_anchor_day": {+ "name": "repeat_anchor_day",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "repeat_until": {+ "name": "repeat_until",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "excluded_occurrences": {+ "name": "excluded_occurrences",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[]')"+ },+ "time_zone": {+ "name": "time_zone",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "starts_at": {+ "name": "starts_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "calendar_events_user_starts_idx": {+ "name": "calendar_events_user_starts_idx",+ "columns": [+ "user_id",+ "starts_at"+ ],+ "isUnique": false+ },+ "calendar_events_mailbox_idx": {+ "name": "calendar_events_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendar_events_user_id_users_id_fk": {+ "name": "calendar_events_user_id_users_id_fk",+ "tableFrom": "calendar_events",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_events_mailbox_id_mailboxes_id_fk": {+ "name": "calendar_events_mailbox_id_mailboxes_id_fk",+ "tableFrom": "calendar_events",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "calendar_events_id": {+ "name": "calendar_events_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "contacts": {+ "name": "contacts",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "varchar(320)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "display_name": {+ "name": "display_name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "avatar_key": {+ "name": "avatar_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'inbound'"+ },+ "blocked": {+ "name": "blocked",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "remote_content_allowed": {+ "name": "remote_content_allowed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "contacts_user_email_idx": {+ "name": "contacts_user_email_idx",+ "columns": [+ "user_id",+ "email"+ ],+ "isUnique": true+ },+ "contacts_user_idx": {+ "name": "contacts_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "contacts_user_id_users_id_fk": {+ "name": "contacts_user_id_users_id_fk",+ "tableFrom": "contacts",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "contacts_id": {+ "name": "contacts_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "domain_tracking_hosts": {+ "name": "domain_tracking_hosts",+ "columns": {+ "domain_id": {+ "name": "domain_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "hostname": {+ "name": "hostname",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "domain_tracking_hosts_hostname_idx": {+ "name": "domain_tracking_hosts_hostname_idx",+ "columns": [+ "hostname"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "domain_tracking_hosts_domain_id_domains_id_fk": {+ "name": "domain_tracking_hosts_domain_id_domains_id_fk",+ "tableFrom": "domain_tracking_hosts",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "domain_tracking_hosts_domain_id": {+ "name": "domain_tracking_hosts_domain_id",+ "columns": [+ "domain_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "domains": {+ "name": "domains",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "hostname": {+ "name": "hostname",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "zone_id": {+ "name": "zone_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "routing_status": {+ "name": "routing_status",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sending_subdomain_tag": {+ "name": "sending_subdomain_tag",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sending_provider": {+ "name": "sending_provider",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "receiving_provider": {+ "name": "receiving_provider",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cloudflare'"+ },+ "sending_requested": {+ "name": "sending_requested",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "sending_enabled": {+ "name": "sending_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "routing_enabled": {+ "name": "routing_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "dns_skipped": {+ "name": "dns_skipped",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "domains_hostname_idx": {+ "name": "domains_hostname_idx",+ "columns": [+ "hostname"+ ],+ "isUnique": true+ },+ "domains_user_idx": {+ "name": "domains_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "domains_user_id_users_id_fk": {+ "name": "domains_user_id_users_id_fk",+ "tableFrom": "domains",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "domains_id": {+ "name": "domains_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "drive_items": {+ "name": "drive_items",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_id": {+ "name": "owner_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "parent_id": {+ "name": "parent_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "size": {+ "name": "size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "content_type": {+ "name": "content_type",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('application/octet-stream')"+ },+ "upload_id": {+ "name": "upload_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "upload_part_size": {+ "name": "upload_part_size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "upload_fingerprint": {+ "name": "upload_fingerprint",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "link_token": {+ "name": "link_token",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "trashed_at": {+ "name": "trashed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "drive_items_owner_parent_idx": {+ "name": "drive_items_owner_parent_idx",+ "columns": [+ "owner_id",+ "parent_id"+ ],+ "isUnique": false+ },+ "drive_items_link_token_idx": {+ "name": "drive_items_link_token_idx",+ "columns": [+ "link_token"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "drive_items_owner_id_users_id_fk": {+ "name": "drive_items_owner_id_users_id_fk",+ "tableFrom": "drive_items",+ "tableTo": "users",+ "columnsFrom": [+ "owner_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "drive_items_id": {+ "name": "drive_items_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "drive_shares": {+ "name": "drive_shares",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "item_id": {+ "name": "item_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'view'"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "drive_shares_item_user_idx": {+ "name": "drive_shares_item_user_idx",+ "columns": [+ "item_id",+ "user_id"+ ],+ "isUnique": true+ },+ "drive_shares_user_idx": {+ "name": "drive_shares_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "drive_shares_item_id_drive_items_id_fk": {+ "name": "drive_shares_item_id_drive_items_id_fk",+ "tableFrom": "drive_shares",+ "tableTo": "drive_items",+ "columnsFrom": [+ "item_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "drive_shares_user_id_users_id_fk": {+ "name": "drive_shares_user_id_users_id_fk",+ "tableFrom": "drive_shares",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "drive_shares_id": {+ "name": "drive_shares_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "drive_upload_parts": {+ "name": "drive_upload_parts",+ "columns": {+ "item_id": {+ "name": "item_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "part_number": {+ "name": "part_number",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "etag": {+ "name": "etag",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "drive_upload_parts_idx": {+ "name": "drive_upload_parts_idx",+ "columns": [+ "item_id",+ "part_number"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "drive_upload_parts_item_id_drive_items_id_fk": {+ "name": "drive_upload_parts_item_id_drive_items_id_fk",+ "tableFrom": "drive_upload_parts",+ "tableTo": "drive_items",+ "columnsFrom": [+ "item_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "email_templates": {+ "name": "email_templates",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "subject": {+ "name": "subject",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "text_body": {+ "name": "text_body",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "email_templates_user_idx": {+ "name": "email_templates_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "email_templates_user_id_users_id_fk": {+ "name": "email_templates_user_id_users_id_fk",+ "tableFrom": "email_templates",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "email_templates_id": {+ "name": "email_templates_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "folders": {+ "name": "folders",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('#2563eb')"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "folders_mailbox_name_idx": {+ "name": "folders_mailbox_name_idx",+ "columns": [+ "mailbox_id",+ "name"+ ],+ "isUnique": true+ },+ "folders_user_idx": {+ "name": "folders_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "folders_mailbox_idx": {+ "name": "folders_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "folders_user_id_users_id_fk": {+ "name": "folders_user_id_users_id_fk",+ "tableFrom": "folders",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "folders_mailbox_id_mailboxes_id_fk": {+ "name": "folders_mailbox_id_mailboxes_id_fk",+ "tableFrom": "folders",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "folders_id": {+ "name": "folders_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "follow_ups": {+ "name": "follow_ups",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "due_at": {+ "name": "due_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "follow_ups_message_idx": {+ "name": "follow_ups_message_idx",+ "columns": [+ "message_id"+ ],+ "isUnique": true+ },+ "follow_ups_status_due_idx": {+ "name": "follow_ups_status_due_idx",+ "columns": [+ "status",+ "due_at"+ ],+ "isUnique": false+ },+ "follow_ups_user_status_idx": {+ "name": "follow_ups_user_status_idx",+ "columns": [+ "user_id",+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "follow_ups_message_id_messages_id_fk": {+ "name": "follow_ups_message_id_messages_id_fk",+ "tableFrom": "follow_ups",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "follow_ups_user_id_users_id_fk": {+ "name": "follow_ups_user_id_users_id_fk",+ "tableFrom": "follow_ups",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "follow_ups_id": {+ "name": "follow_ups_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "import_jobs": {+ "name": "import_jobs",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'queued'"+ },+ "total": {+ "name": "total",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "processed": {+ "name": "processed",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "imported": {+ "name": "imported",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "skipped": {+ "name": "skipped",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "spec": {+ "name": "spec",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor": {+ "name": "cursor",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('{}')"+ },+ "errors": {+ "name": "errors",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[]')"+ },+ "error_count": {+ "name": "error_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "error": {+ "name": "error",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "import_jobs_user_idx": {+ "name": "import_jobs_user_idx",+ "columns": [+ "user_id",+ "created_at"+ ],+ "isUnique": false+ },+ "import_jobs_status_idx": {+ "name": "import_jobs_status_idx",+ "columns": [+ "status",+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "import_jobs_user_id_users_id_fk": {+ "name": "import_jobs_user_id_users_id_fk",+ "tableFrom": "import_jobs",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "import_jobs_mailbox_id_mailboxes_id_fk": {+ "name": "import_jobs_mailbox_id_mailboxes_id_fk",+ "tableFrom": "import_jobs",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "import_jobs_id": {+ "name": "import_jobs_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "jmap_change_floor": {+ "name": "jmap_change_floor",+ "columns": {+ "id": {+ "name": "id",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seq": {+ "name": "seq",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "jmap_change_floor_id": {+ "name": "jmap_change_floor_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "jmap_changes": {+ "name": "jmap_changes",+ "columns": {+ "seq": {+ "name": "seq",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "object_type": {+ "name": "object_type",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "object_id": {+ "name": "object_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "change": {+ "name": "change",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unix_timestamp())"+ }+ },+ "indexes": {+ "jmap_changes_mailbox_seq_idx": {+ "name": "jmap_changes_mailbox_seq_idx",+ "columns": [+ "mailbox_id",+ "seq"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "jmap_changes_seq": {+ "name": "jmap_changes_seq",+ "columns": [+ "seq"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "jmap_mailbox_revisions": {+ "name": "jmap_mailbox_revisions",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "jmap_mailbox_revisions_mailbox_id": {+ "name": "jmap_mailbox_revisions_mailbox_id",+ "columns": [+ "mailbox_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "license_settings": {+ "name": "license_settings",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "instance_id": {+ "name": "instance_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "instance_url": {+ "name": "instance_url",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "license_key_hash": {+ "name": "license_key_hash",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan": {+ "name": "plan",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'community'"+ },+ "state": {+ "name": "state",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'inactive'"+ },+ "features": {+ "name": "features",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('[]')"+ },+ "seat_limit": {+ "name": "seat_limit",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "activated_at": {+ "name": "activated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "validated_at": {+ "name": "validated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "license_settings_id": {+ "name": "license_settings_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "license_settings_instance_id_unique": {+ "name": "license_settings_instance_id_unique",+ "columns": [+ "instance_id"+ ]+ }+ },+ "checkConstraint": {}+ },+ "login_challenges": {+ "name": "login_challenges",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token_hash": {+ "name": "token_hash",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "login_challenges_user_idx": {+ "name": "login_challenges_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "login_challenges_user_id_users_id_fk": {+ "name": "login_challenges_user_id_users_id_fk",+ "tableFrom": "login_challenges",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "login_challenges_id": {+ "name": "login_challenges_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "login_challenges_token_hash_unique": {+ "name": "login_challenges_token_hash_unique",+ "columns": [+ "token_hash"+ ]+ }+ },+ "checkConstraint": {}+ },+ "mailbox_access": {+ "name": "mailbox_access",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "permission": {+ "name": "permission",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'read_only'"+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "mailbox_access_mailbox_user_idx": {+ "name": "mailbox_access_mailbox_user_idx",+ "columns": [+ "mailbox_id",+ "user_id"+ ],+ "isUnique": true+ },+ "mailbox_access_user_idx": {+ "name": "mailbox_access_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "mailbox_access_mailbox_idx": {+ "name": "mailbox_access_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ },+ "mailbox_access_created_by_idx": {+ "name": "mailbox_access_created_by_idx",+ "columns": [+ "created_by_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "mailbox_access_mailbox_id_mailboxes_id_fk": {+ "name": "mailbox_access_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mailbox_access",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_access_user_id_users_id_fk": {+ "name": "mailbox_access_user_id_users_id_fk",+ "tableFrom": "mailbox_access",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_access_created_by_user_id_users_id_fk": {+ "name": "mailbox_access_created_by_user_id_users_id_fk",+ "tableFrom": "mailbox_access",+ "tableTo": "users",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "mailbox_access_id": {+ "name": "mailbox_access_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "mailbox_agent_settings": {+ "name": "mailbox_agent_settings",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "model_id": {+ "name": "model_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_draft_enabled": {+ "name": "auto_draft_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "reviewer_user_id": {+ "name": "reviewer_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "instructions": {+ "name": "instructions",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "daily_limit": {+ "name": "daily_limit",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 25+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "mailbox_agent_settings_reviewer_idx": {+ "name": "mailbox_agent_settings_reviewer_idx",+ "columns": [+ "reviewer_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "mailbox_agent_settings_mailbox_id_mailboxes_id_fk": {+ "name": "mailbox_agent_settings_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mailbox_agent_settings",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_agent_settings_reviewer_user_id_users_id_fk": {+ "name": "mailbox_agent_settings_reviewer_user_id_users_id_fk",+ "tableFrom": "mailbox_agent_settings",+ "tableTo": "users",+ "columnsFrom": [+ "reviewer_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "mailbox_agent_settings_mailbox_id": {+ "name": "mailbox_agent_settings_mailbox_id",+ "columns": [+ "mailbox_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "mailbox_aliases": {+ "name": "mailbox_aliases",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain_id": {+ "name": "domain_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "local_part": {+ "name": "local_part",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "mailbox_aliases_address_idx": {+ "name": "mailbox_aliases_address_idx",+ "columns": [+ "domain_id",+ "local_part"+ ],+ "isUnique": true+ },+ "mailbox_aliases_mailbox_idx": {+ "name": "mailbox_aliases_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "mailbox_aliases_mailbox_id_mailboxes_id_fk": {+ "name": "mailbox_aliases_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mailbox_aliases",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_aliases_domain_id_domains_id_fk": {+ "name": "mailbox_aliases_domain_id_domains_id_fk",+ "tableFrom": "mailbox_aliases",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "mailbox_aliases_id": {+ "name": "mailbox_aliases_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "mailboxes": {+ "name": "mailboxes",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain_id": {+ "name": "domain_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "local_part": {+ "name": "local_part",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "display_name": {+ "name": "display_name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "signature": {+ "name": "signature",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_reply_enabled": {+ "name": "auto_reply_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "auto_reply_subject": {+ "name": "auto_reply_subject",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('Out of office')"+ },+ "auto_reply_body": {+ "name": "auto_reply_body",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "avatar_key": {+ "name": "avatar_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'personal'"+ },+ "use_all_domains": {+ "name": "use_all_domains",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "mailboxes_address_idx": {+ "name": "mailboxes_address_idx",+ "columns": [+ "domain_id",+ "local_part"+ ],+ "isUnique": true+ },+ "mailboxes_user_idx": {+ "name": "mailboxes_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "mailboxes_user_id_users_id_fk": {+ "name": "mailboxes_user_id_users_id_fk",+ "tableFrom": "mailboxes",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailboxes_domain_id_domains_id_fk": {+ "name": "mailboxes_domain_id_domains_id_fk",+ "tableFrom": "mailboxes",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "mailboxes_id": {+ "name": "mailboxes_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "mcp_key_mailboxes": {+ "name": "mcp_key_mailboxes",+ "columns": {+ "key_id": {+ "name": "key_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "mcp_key_mailbox_idx": {+ "name": "mcp_key_mailbox_idx",+ "columns": [+ "key_id",+ "mailbox_id"+ ],+ "isUnique": true+ },+ "mcp_key_mailboxes_mailbox_idx": {+ "name": "mcp_key_mailboxes_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "mcp_key_mailboxes_key_id_api_keys_id_fk": {+ "name": "mcp_key_mailboxes_key_id_api_keys_id_fk",+ "tableFrom": "mcp_key_mailboxes",+ "tableTo": "api_keys",+ "columnsFrom": [+ "key_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mcp_key_mailboxes_mailbox_id_mailboxes_id_fk": {+ "name": "mcp_key_mailboxes_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mcp_key_mailboxes",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "message_attachments": {+ "name": "message_attachments",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "filename": {+ "name": "filename",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content_type": {+ "name": "content_type",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "size": {+ "name": "size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "disposition": {+ "name": "disposition",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'attachment'"+ },+ "content_id": {+ "name": "content_id",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "trashed_at": {+ "name": "trashed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "message_attachments_message_idx": {+ "name": "message_attachments_message_idx",+ "columns": [+ "message_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "message_attachments_message_id_messages_id_fk": {+ "name": "message_attachments_message_id_messages_id_fk",+ "tableFrom": "message_attachments",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "message_attachments_id": {+ "name": "message_attachments_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "message_attachments_r2_key_unique": {+ "name": "message_attachments_r2_key_unique",+ "columns": [+ "r2_key"+ ]+ }+ },+ "checkConstraint": {}+ },+ "message_opens": {+ "name": "message_opens",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "opened_at": {+ "name": "opened_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "client": {+ "name": "client",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "device": {+ "name": "device",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "country": {+ "name": "country",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "city": {+ "name": "city",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "automated": {+ "name": "automated",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ }+ },+ "indexes": {+ "message_opens_token_idx": {+ "name": "message_opens_token_idx",+ "columns": [+ "token",+ "opened_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "message_opens_token_message_tracking_token_fk": {+ "name": "message_opens_token_message_tracking_token_fk",+ "tableFrom": "message_opens",+ "tableTo": "message_tracking",+ "columnsFrom": [+ "token"+ ],+ "columnsTo": [+ "token"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "message_opens_id": {+ "name": "message_opens_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "message_tracking": {+ "name": "message_tracking",+ "columns": {+ "token": {+ "name": "token",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "open_count": {+ "name": "open_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "first_opened_at": {+ "name": "first_opened_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_opened_at": {+ "name": "last_opened_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "message_tracking_message_idx": {+ "name": "message_tracking_message_idx",+ "columns": [+ "message_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "message_tracking_message_id_messages_id_fk": {+ "name": "message_tracking_message_id_messages_id_fk",+ "tableFrom": "message_tracking",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "message_tracking_token": {+ "name": "message_tracking_token",+ "columns": [+ "token"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "direction": {+ "name": "direction",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_message_id": {+ "name": "provider_message_id",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "folder_id": {+ "name": "folder_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "from_addr": {+ "name": "from_addr",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to_addr": {+ "name": "to_addr",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cc_addr": {+ "name": "cc_addr",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "bcc_addr": {+ "name": "bcc_addr",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "reply_to": {+ "name": "reply_to",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "subject": {+ "name": "subject",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "snippet": {+ "name": "snippet",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "text_body": {+ "name": "text_body",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "html_body": {+ "name": "html_body",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "raw_r2_key": {+ "name": "raw_r2_key",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'received'"+ },+ "read": {+ "name": "read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "starred": {+ "name": "starred",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "in_reply_to": {+ "name": "in_reply_to",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "references_header": {+ "name": "references_header",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spam_score": {+ "name": "spam_score",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spam_verdict": {+ "name": "spam_verdict",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spam_signals": {+ "name": "spam_signals",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spam_analyzed_at": {+ "name": "spam_analyzed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spam_analysis_error": {+ "name": "spam_analysis_error",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "trashed_at": {+ "name": "trashed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "messages_user_created_idx": {+ "name": "messages_user_created_idx",+ "columns": [+ "user_id",+ "created_at"+ ],+ "isUnique": false+ },+ "messages_mailbox_idx": {+ "name": "messages_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ },+ "messages_folder_idx": {+ "name": "messages_folder_idx",+ "columns": [+ "folder_id"+ ],+ "isUnique": false+ },+ "messages_thread_idx": {+ "name": "messages_thread_idx",+ "columns": [+ "mailbox_id",+ "thread_id"+ ],+ "isUnique": false+ },+ "messages_provider_message_idx": {+ "name": "messages_provider_message_idx",+ "columns": [+ "mailbox_id",+ "provider_message_id"+ ],+ "isUnique": false+ },+ "messages_raw_r2_key_idx": {+ "name": "messages_raw_r2_key_idx",+ "columns": [+ "raw_r2_key"+ ],+ "isUnique": false+ },+ "messages_trashed_at_idx": {+ "name": "messages_trashed_at_idx",+ "columns": [+ "trashed_at"+ ],+ "isUnique": false+ },+ "messages_inbox_page_idx": {+ "name": "messages_inbox_page_idx",+ "columns": [+ "mailbox_id",+ "status",+ "folder_id",+ "created_at"+ ],+ "isUnique": false+ },+ "messages_thread_key_idx": {+ "name": "messages_thread_key_idx",+ "columns": [+ "mailbox_id",+ "status",+ "folder_id",+ "created_at"+ ],+ "isUnique": false+ },+ "messages_mailbox_thread_key_idx": {+ "name": "messages_mailbox_thread_key_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ },+ "messages_nav_cover_idx": {+ "name": "messages_nav_cover_idx",+ "columns": [+ "mailbox_id",+ "status",+ "folder_id",+ "created_at"+ ],+ "isUnique": false+ },+ "messages_counts_cover_idx": {+ "name": "messages_counts_cover_idx",+ "columns": [+ "mailbox_id",+ "folder_id",+ "direction",+ "status",+ "read",+ "starred",+ "snoozed_until"+ ],+ "isUnique": false+ },+ "messages_conv_cover_idx": {+ "name": "messages_conv_cover_idx",+ "columns": [+ "mailbox_id",+ "status",+ "created_at",+ "id",+ "snoozed_until"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "messages_user_id_users_id_fk": {+ "name": "messages_user_id_users_id_fk",+ "tableFrom": "messages",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "messages_mailbox_id_mailboxes_id_fk": {+ "name": "messages_mailbox_id_mailboxes_id_fk",+ "tableFrom": "messages",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "messages_folder_id_folders_id_fk": {+ "name": "messages_folder_id_folders_id_fk",+ "tableFrom": "messages",+ "tableTo": "folders",+ "columnsFrom": [+ "folder_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "messages_id": {+ "name": "messages_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "mfa_recovery_codes": {+ "name": "mfa_recovery_codes",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "code_hash": {+ "name": "code_hash",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "used_at": {+ "name": "used_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "mfa_recovery_codes_user_idx": {+ "name": "mfa_recovery_codes_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "mfa_recovery_codes_user_id_users_id_fk": {+ "name": "mfa_recovery_codes_user_id_users_id_fk",+ "tableFrom": "mfa_recovery_codes",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "mfa_recovery_codes_id": {+ "name": "mfa_recovery_codes_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "mfa_recovery_codes_code_hash_unique": {+ "name": "mfa_recovery_codes_code_hash_unique",+ "columns": [+ "code_hash"+ ]+ }+ },+ "checkConstraint": {}+ },+ "outbound_jobs": {+ "name": "outbound_jobs",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'queued'"+ },+ "payload": {+ "name": "payload",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "error": {+ "name": "error",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "outbound_jobs_user_idx": {+ "name": "outbound_jobs_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "outbound_jobs_message_idx": {+ "name": "outbound_jobs_message_idx",+ "columns": [+ "message_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "outbound_jobs_user_id_users_id_fk": {+ "name": "outbound_jobs_user_id_users_id_fk",+ "tableFrom": "outbound_jobs",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "outbound_jobs_message_id_messages_id_fk": {+ "name": "outbound_jobs_message_id_messages_id_fk",+ "tableFrom": "outbound_jobs",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "outbound_jobs_id": {+ "name": "outbound_jobs_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "password_reset_tokens": {+ "name": "password_reset_tokens",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token_hash": {+ "name": "token_hash",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "used_at": {+ "name": "used_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "password_reset_tokens_user_idx": {+ "name": "password_reset_tokens_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "password_reset_tokens_user_id_users_id_fk": {+ "name": "password_reset_tokens_user_id_users_id_fk",+ "tableFrom": "password_reset_tokens",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "password_reset_tokens_id": {+ "name": "password_reset_tokens_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "password_reset_tokens_token_hash_unique": {+ "name": "password_reset_tokens_token_hash_unique",+ "columns": [+ "token_hash"+ ]+ }+ },+ "checkConstraint": {}+ },+ "push_devices": {+ "name": "push_devices",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "api_key_id": {+ "name": "api_key_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform": {+ "name": "platform",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "environment": {+ "name": "environment",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'production'"+ },+ "topic": {+ "name": "topic",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "public_key": {+ "name": "public_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "previews": {+ "name": "previews",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "client_ref": {+ "name": "client_ref",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "push_devices_platform_token_user_idx": {+ "name": "push_devices_platform_token_user_idx",+ "columns": [+ "platform",+ "token",+ "user_id"+ ],+ "isUnique": true+ },+ "push_devices_user_idx": {+ "name": "push_devices_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "push_devices_api_key_idx": {+ "name": "push_devices_api_key_idx",+ "columns": [+ "api_key_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "push_devices_user_id_users_id_fk": {+ "name": "push_devices_user_id_users_id_fk",+ "tableFrom": "push_devices",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "push_devices_api_key_id_api_keys_id_fk": {+ "name": "push_devices_api_key_id_api_keys_id_fk",+ "tableFrom": "push_devices",+ "tableTo": "api_keys",+ "columnsFrom": [+ "api_key_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "push_devices_id": {+ "name": "push_devices_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "push_subscriptions": {+ "name": "push_subscriptions",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "endpoint": {+ "name": "endpoint",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "p256dh": {+ "name": "p256dh",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "auth": {+ "name": "auth",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "push_subscriptions_endpoint_idx": {+ "name": "push_subscriptions_endpoint_idx",+ "columns": [+ "endpoint"+ ],+ "isUnique": true+ },+ "push_subscriptions_user_idx": {+ "name": "push_subscriptions_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "push_subscriptions_session_idx": {+ "name": "push_subscriptions_session_idx",+ "columns": [+ "session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "push_subscriptions_user_id_users_id_fk": {+ "name": "push_subscriptions_user_id_users_id_fk",+ "tableFrom": "push_subscriptions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "push_subscriptions_session_id_sessions_id_fk": {+ "name": "push_subscriptions_session_id_sessions_id_fk",+ "tableFrom": "push_subscriptions",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "push_subscriptions_id": {+ "name": "push_subscriptions_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "routing_rules": {+ "name": "routing_rules",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain_id": {+ "name": "domain_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'mailbox'"+ },+ "name": {+ "name": "name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "pattern": {+ "name": "pattern",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "match_field": {+ "name": "match_field",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'email'"+ },+ "match_operator": {+ "name": "match_operator",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'contains'"+ },+ "match_value": {+ "name": "match_value",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('')"+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "folder_id": {+ "name": "folder_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'store'"+ },+ "forward_to": {+ "name": "forward_to",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keep_copy": {+ "name": "keep_copy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "reject_reason": {+ "name": "reject_reason",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "priority": {+ "name": "priority",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_matched_at": {+ "name": "last_matched_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "match_count": {+ "name": "match_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "routing_rules_domain_scope_idx": {+ "name": "routing_rules_domain_scope_idx",+ "columns": [+ "domain_id",+ "scope",+ "enabled"+ ],+ "isUnique": false+ },+ "routing_rules_mailbox_idx": {+ "name": "routing_rules_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ },+ "routing_rules_priority_idx": {+ "name": "routing_rules_priority_idx",+ "columns": [+ "priority"+ ],+ "isUnique": false+ },+ "routing_rules_user_idx": {+ "name": "routing_rules_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "routing_rules_folder_idx": {+ "name": "routing_rules_folder_idx",+ "columns": [+ "folder_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "routing_rules_user_id_users_id_fk": {+ "name": "routing_rules_user_id_users_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "routing_rules_domain_id_domains_id_fk": {+ "name": "routing_rules_domain_id_domains_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "routing_rules_mailbox_id_mailboxes_id_fk": {+ "name": "routing_rules_mailbox_id_mailboxes_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "routing_rules_folder_id_folders_id_fk": {+ "name": "routing_rules_folder_id_folders_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "folders",+ "columnsFrom": [+ "folder_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "routing_rules_id": {+ "name": "routing_rules_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token_hash": {+ "name": "token_hash",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "sessions_user_idx": {+ "name": "sessions_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_user_id_users_id_fk": {+ "name": "sessions_user_id_users_id_fk",+ "tableFrom": "sessions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "sessions_id": {+ "name": "sessions_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "sessions_token_hash_unique": {+ "name": "sessions_token_hash_unique",+ "columns": [+ "token_hash"+ ]+ }+ },+ "checkConstraint": {}+ },+ "shared_attachment_links": {+ "name": "shared_attachment_links",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "shared_attachment_links_attachment_id_message_attachments_id_fk": {+ "name": "shared_attachment_links_attachment_id_message_attachments_id_fk",+ "tableFrom": "shared_attachment_links",+ "tableTo": "message_attachments",+ "columnsFrom": [+ "attachment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "shared_attachment_links_id": {+ "name": "shared_attachment_links_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "shared_attachment_links_attachment_id_unique": {+ "name": "shared_attachment_links_attachment_id_unique",+ "columns": [+ "attachment_id"+ ]+ }+ },+ "checkConstraint": {}+ },+ "spam_feedback": {+ "name": "spam_feedback",+ "columns": {+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "classification": {+ "name": "classification",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "training_tokens": {+ "name": "training_tokens",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reputation_keys": {+ "name": "reputation_keys",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tokenizer_version": {+ "name": "tokenizer_version",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "spam_feedback_mailbox_idx": {+ "name": "spam_feedback_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ },+ "spam_feedback_actor_user_idx": {+ "name": "spam_feedback_actor_user_idx",+ "columns": [+ "actor_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "spam_feedback_message_id_messages_id_fk": {+ "name": "spam_feedback_message_id_messages_id_fk",+ "tableFrom": "spam_feedback",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "spam_feedback_mailbox_id_mailboxes_id_fk": {+ "name": "spam_feedback_mailbox_id_mailboxes_id_fk",+ "tableFrom": "spam_feedback",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "spam_feedback_actor_user_id_users_id_fk": {+ "name": "spam_feedback_actor_user_id_users_id_fk",+ "tableFrom": "spam_feedback",+ "tableTo": "users",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "spam_feedback_message_id": {+ "name": "spam_feedback_message_id",+ "columns": [+ "message_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "spam_reputation": {+ "name": "spam_reputation",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "key": {+ "name": "key",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "messages_seen": {+ "name": "messages_seen",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "spam_count": {+ "name": "spam_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "ham_count": {+ "name": "ham_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "spam_reputation_mailbox_type_key_idx": {+ "name": "spam_reputation_mailbox_type_key_idx",+ "columns": [+ "mailbox_id",+ "type",+ "key"+ ],+ "isUnique": true+ },+ "spam_reputation_mailbox_idx": {+ "name": "spam_reputation_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "spam_reputation_mailbox_id_mailboxes_id_fk": {+ "name": "spam_reputation_mailbox_id_mailboxes_id_fk",+ "tableFrom": "spam_reputation",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "spam_token_stats": {+ "name": "spam_token_stats",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "spam_count": {+ "name": "spam_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "ham_count": {+ "name": "ham_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "spam_token_stats_mailbox_token_idx": {+ "name": "spam_token_stats_mailbox_token_idx",+ "columns": [+ "mailbox_id",+ "token"+ ],+ "isUnique": true+ },+ "spam_token_stats_mailbox_idx": {+ "name": "spam_token_stats_mailbox_idx",+ "columns": [+ "mailbox_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "spam_token_stats_mailbox_id_mailboxes_id_fk": {+ "name": "spam_token_stats_mailbox_id_mailboxes_id_fk",+ "tableFrom": "spam_token_stats",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "user_compose_preferences": {+ "name": "user_compose_preferences",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "track_opens_default": {+ "name": "track_opens_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "undo_send_seconds": {+ "name": "undo_send_seconds",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 15+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_compose_preferences_user_id_users_id_fk": {+ "name": "user_compose_preferences_user_id_users_id_fk",+ "tableFrom": "user_compose_preferences",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "user_compose_preferences_user_id": {+ "name": "user_compose_preferences_user_id",+ "columns": [+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "varchar(320)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reset_email": {+ "name": "reset_email",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "forwarding_email": {+ "name": "forwarding_email",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password_hash": {+ "name": "password_hash",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "booking_username": {+ "name": "booking_username",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "time_zone": {+ "name": "time_zone",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "avatar_key": {+ "name": "avatar_key",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'user'"+ },+ "is_primary_admin": {+ "name": "is_primary_admin",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "can_manage_mailboxes": {+ "name": "can_manage_mailboxes",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "can_manage_domains": {+ "name": "can_manage_domains",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "can_manage_users": {+ "name": "can_manage_users",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "keyboard_shortcuts_enabled": {+ "name": "keyboard_shortcuts_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "spam_protection_enabled": {+ "name": "spam_protection_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "trash_retention_days": {+ "name": "trash_retention_days",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "show_full_recipient_addresses": {+ "name": "show_full_recipient_addresses",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "remote_content_mode": {+ "name": "remote_content_mode",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'allow'"+ },+ "totp_secret": {+ "name": "totp_secret",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "totp_enabled": {+ "name": "totp_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "totp_confirmed_at": {+ "name": "totp_confirmed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_sign_in_at": {+ "name": "last_sign_in_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "users_booking_username_idx": {+ "name": "users_booking_username_idx",+ "columns": [+ "booking_username"+ ],+ "isUnique": true+ },+ "users_created_by_idx": {+ "name": "users_created_by_idx",+ "columns": [+ "created_by_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "users_created_by_user_id_users_id_fk": {+ "name": "users_created_by_user_id_users_id_fk",+ "tableFrom": "users",+ "tableTo": "users",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "users_id": {+ "name": "users_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {+ "users_email_unique": {+ "name": "users_email_unique",+ "columns": [+ "email"+ ]+ }+ },+ "checkConstraint": {}+ },+ "webhook_deliveries": {+ "name": "webhook_deliveries",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "event_type": {+ "name": "event_type",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "response_status": {+ "name": "response_status",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error": {+ "name": "error",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_retry_at": {+ "name": "next_retry_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "webhook_deliveries_webhook_idx": {+ "name": "webhook_deliveries_webhook_idx",+ "columns": [+ "webhook_id",+ "created_at"+ ],+ "isUnique": false+ },+ "webhook_deliveries_status_idx": {+ "name": "webhook_deliveries_status_idx",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "webhook_deliveries_webhook_id_webhooks_id_fk": {+ "name": "webhook_deliveries_webhook_id_webhooks_id_fk",+ "tableFrom": "webhook_deliveries",+ "tableTo": "webhooks",+ "columnsFrom": [+ "webhook_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "webhook_deliveries_id": {+ "name": "webhook_deliveries_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "webhooks": {+ "name": "webhooks",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "longtext",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "secret": {+ "name": "secret",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "events": {+ "name": "events",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "max_attempts": {+ "name": "max_attempts",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 5+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "webhooks_user_idx": {+ "name": "webhooks_user_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "webhooks_user_id_users_id_fk": {+ "name": "webhooks_user_id_users_id_fk",+ "tableFrom": "webhooks",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "webhooks_id": {+ "name": "webhooks_id",+ "columns": [+ "id"+ ]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ }+ },+ "views": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "tables": {},+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/migrations-mysql/meta/_journal.json b/drizzle/migrations-mysql/meta/_journal.jsonnew file mode 100644index 0000000..5e3295d--- /dev/null+++ b/drizzle/migrations-mysql/meta/_journal.json@@ -0,0 +1,20 @@+{+ "version": "7",+ "dialect": "mysql",+ "entries": [+ {+ "idx": 0,+ "version": "5",+ "when": 1792869792885,+ "tag": "0000_baseline",+ "breakpoints": true+ },+ {+ "idx": 1,+ "version": "5",+ "when": 1792869793885,+ "tag": "0001_triggers_and_seeds",+ "breakpoints": true+ }+ ]+}diff --git a/drizzle/migrations-pg/0000_baseline.sql b/drizzle/migrations-pg/0000_baseline.sqlnew file mode 100644index 0000000..71be271--- /dev/null+++ b/drizzle/migrations-pg/0000_baseline.sql@@ -0,0 +1,848 @@+CREATE TABLE "agent_chat_messages" (+ "id" text PRIMARY KEY NOT NULL,+ "conversation_id" text NOT NULL,+ "role" text NOT NULL,+ "content" text NOT NULL,+ "tool_name" text,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "agent_conversations" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "mailbox_id" text NOT NULL,+ "title" text DEFAULT 'New conversation' NOT NULL,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "agent_draft_metadata" (+ "draft_id" text PRIMARY KEY NOT NULL,+ "mailbox_id" text NOT NULL,+ "origin" text NOT NULL,+ "source_message_id" text,+ "revision" bigint DEFAULT 1 NOT NULL,+ "human_edited_at" bigint,+ "scheduled_at" bigint,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "agent_jobs" (+ "id" text PRIMARY KEY NOT NULL,+ "mailbox_id" text NOT NULL,+ "source_message_id" text NOT NULL,+ "reviewer_user_id" text NOT NULL,+ "status" text DEFAULT 'pending' NOT NULL,+ "attempts" bigint DEFAULT 0 NOT NULL,+ "next_attempt_at" bigint NOT NULL,+ "lease_until" bigint,+ "draft_id" text,+ "reason" text,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "agent_send_approvals" (+ "id" text PRIMARY KEY NOT NULL,+ "draft_id" text NOT NULL,+ "mailbox_id" text NOT NULL,+ "user_id" text NOT NULL,+ "request_key_id" text,+ "revision" bigint NOT NULL,+ "payload_hash" text NOT NULL,+ "status" text DEFAULT 'pending' NOT NULL,+ "claimed_at" bigint,+ "message_id" text,+ "expires_at" bigint NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "ai_usage" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" bigint NOT NULL,+ "provider" text NOT NULL,+ "model" text NOT NULL,+ "source" text NOT NULL,+ "input_tokens" bigint,+ "output_tokens" bigint,+ "cost_usd_micros" bigint+);+--> statement-breakpoint+CREATE TABLE "api_keys" (+ "id" text PRIMARY KEY NOT NULL,+ "kind" text DEFAULT 'legacy' NOT NULL,+ "user_id" text NOT NULL,+ "name" text NOT NULL,+ "prefix" text NOT NULL,+ "key_hash" text NOT NULL,+ "scopes" text NOT NULL,+ "mailbox_scope_enabled" boolean DEFAULT false NOT NULL,+ "created_at" bigint NOT NULL,+ "last_used_at" bigint+);+--> statement-breakpoint+CREATE TABLE "app_settings" (+ "id" text PRIMARY KEY NOT NULL,+ "app_name" text DEFAULT 'Mailflare' NOT NULL,+ "outbound_attachment_max_mb" bigint DEFAULT 25 NOT NULL,+ "drive_storage_limit_bytes" bigint,+ "resend_api_key" text,+ "aws_config" text,+ "ses_receiving" text,+ "resend_webhook_id" text,+ "resend_webhook_secret" text,+ "icon_key" text,+ "agent_enabled" boolean DEFAULT true NOT NULL,+ "agent_provider" text,+ "agent_preset" text,+ "agent_base_url" text,+ "agent_api_key" text,+ "agent_model" text,+ "agent_model_rates" text,+ "spamhaus_dqs_key" text,+ "abusech_auth_key" text,+ "spam_domain_age_check" boolean DEFAULT true NOT NULL,+ "spam_brands" text,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "audit_logs" (+ "id" text PRIMARY KEY NOT NULL,+ "actor_user_id" text,+ "target_user_id" text,+ "mailbox_id" text,+ "message_id" text,+ "action" text NOT NULL,+ "metadata" text,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "auto_reply_deliveries" (+ "id" text PRIMARY KEY NOT NULL,+ "mailbox_id" text NOT NULL,+ "recipient" text NOT NULL,+ "sent_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "backup_settings" (+ "id" text PRIMARY KEY NOT NULL,+ "enabled" boolean DEFAULT true NOT NULL,+ "schedule_type" text DEFAULT 'daily' NOT NULL,+ "schedule_value" bigint,+ "retention_enabled" boolean DEFAULT false NOT NULL,+ "retention_days" bigint DEFAULT 30 NOT NULL,+ "excluded_table_groups" text DEFAULT '[]' NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "backups" (+ "id" text PRIMARY KEY NOT NULL,+ "status" text DEFAULT 'queued' NOT NULL,+ "trigger" text NOT NULL,+ "r2_key" text,+ "filename" text,+ "size" bigint,+ "error" text,+ "created_by_user_id" text,+ "created_at" bigint NOT NULL,+ "started_at" bigint,+ "completed_at" bigint+);+--> statement-breakpoint+CREATE TABLE "booking_events" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "name" text NOT NULL,+ "slug" text DEFAULT '' NOT NULL,+ "description" text DEFAULT '' NOT NULL,+ "color" text DEFAULT '#2563eb' NOT NULL,+ "host_ids" text DEFAULT '[]' NOT NULL,+ "duration_minutes" bigint NOT NULL,+ "location" text DEFAULT '' NOT NULL,+ "weekdays" text DEFAULT '[1,2,3,4,5]' NOT NULL,+ "start_time" text DEFAULT '09:00' NOT NULL,+ "end_time" text DEFAULT '17:00' NOT NULL,+ "time_ranges" text DEFAULT '[{"startTime":"09:00","endTime":"17:00"}]' NOT NULL,+ "time_zone" text DEFAULT 'UTC' NOT NULL,+ "enabled" boolean DEFAULT true NOT NULL,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "calendar_events" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "mailbox_id" text,+ "title" text NOT NULL,+ "description" text DEFAULT '' NOT NULL,+ "location" text DEFAULT '' NOT NULL,+ "attendees" text DEFAULT '[]' NOT NULL,+ "color" text DEFAULT 'blue' NOT NULL,+ "repeat" text DEFAULT 'none' NOT NULL,+ "repeat_days" text DEFAULT '[]' NOT NULL,+ "repeat_anchor_day" bigint,+ "repeat_until" bigint,+ "excluded_occurrences" text DEFAULT '[]' NOT NULL,+ "time_zone" text,+ "starts_at" bigint NOT NULL,+ "ends_at" bigint NOT NULL,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "contacts" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "email" text NOT NULL,+ "display_name" text,+ "avatar_key" text,+ "source" text DEFAULT 'inbound' NOT NULL,+ "blocked" boolean DEFAULT false NOT NULL,+ "remote_content_allowed" boolean DEFAULT false NOT NULL,+ "last_seen_at" bigint,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "domain_tracking_hosts" (+ "domain_id" text PRIMARY KEY NOT NULL,+ "hostname" text NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "domains" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "hostname" text NOT NULL,+ "zone_id" text NOT NULL,+ "status" text DEFAULT 'pending' NOT NULL,+ "routing_status" text,+ "sending_subdomain_tag" text,+ "sending_provider" text DEFAULT 'none' NOT NULL,+ "receiving_provider" text DEFAULT 'cloudflare' NOT NULL,+ "sending_requested" boolean DEFAULT false NOT NULL,+ "sending_enabled" boolean DEFAULT false NOT NULL,+ "routing_enabled" boolean DEFAULT false NOT NULL,+ "dns_skipped" boolean DEFAULT false NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "drive_items" (+ "id" text PRIMARY KEY NOT NULL,+ "owner_id" text NOT NULL,+ "parent_id" text,+ "kind" text NOT NULL,+ "name" text NOT NULL,+ "r2_key" text,+ "size" bigint DEFAULT 0 NOT NULL,+ "content_type" text DEFAULT 'application/octet-stream' NOT NULL,+ "upload_id" text,+ "upload_part_size" bigint,+ "upload_fingerprint" text,+ "link_token" text,+ "trashed_at" bigint,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "drive_shares" (+ "id" text PRIMARY KEY NOT NULL,+ "item_id" text NOT NULL,+ "user_id" text NOT NULL,+ "role" text DEFAULT 'view' NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "drive_upload_parts" (+ "item_id" text NOT NULL,+ "part_number" bigint NOT NULL,+ "etag" text NOT NULL+);+--> statement-breakpoint+CREATE TABLE "email_templates" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "name" text NOT NULL,+ "subject" text DEFAULT '' NOT NULL,+ "text_body" text DEFAULT '' NOT NULL,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "folders" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "mailbox_id" text NOT NULL,+ "name" text NOT NULL,+ "color" text DEFAULT '#2563eb' NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "follow_ups" (+ "id" text PRIMARY KEY NOT NULL,+ "message_id" text NOT NULL,+ "user_id" text NOT NULL,+ "due_at" bigint NOT NULL,+ "status" text DEFAULT 'pending' NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "import_jobs" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "mailbox_id" text NOT NULL,+ "kind" text NOT NULL,+ "label" text NOT NULL,+ "status" text DEFAULT 'queued' NOT NULL,+ "total" bigint DEFAULT 0 NOT NULL,+ "processed" bigint DEFAULT 0 NOT NULL,+ "imported" bigint DEFAULT 0 NOT NULL,+ "skipped" bigint DEFAULT 0 NOT NULL,+ "spec" text NOT NULL,+ "cursor" text DEFAULT '{}' NOT NULL,+ "errors" text DEFAULT '[]' NOT NULL,+ "error_count" bigint DEFAULT 0 NOT NULL,+ "error" text,+ "created_at" bigint NOT NULL,+ "started_at" bigint,+ "updated_at" bigint NOT NULL,+ "finished_at" bigint+);+--> statement-breakpoint+CREATE TABLE "jmap_change_floor" (+ "id" bigint PRIMARY KEY NOT NULL,+ "seq" bigint DEFAULT 0 NOT NULL+);+--> statement-breakpoint+CREATE TABLE "jmap_changes" (+ "seq" bigserial PRIMARY KEY NOT NULL,+ "mailbox_id" text NOT NULL,+ "object_type" text NOT NULL,+ "object_id" text NOT NULL,+ "thread_id" text,+ "change" text NOT NULL,+ "created_at" bigint DEFAULT (extract(epoch from now())::bigint) NOT NULL+);+--> statement-breakpoint+CREATE TABLE "jmap_mailbox_revisions" (+ "mailbox_id" text PRIMARY KEY NOT NULL,+ "revision" bigint DEFAULT 0 NOT NULL+);+--> statement-breakpoint+CREATE TABLE "license_settings" (+ "id" text PRIMARY KEY NOT NULL,+ "instance_id" text NOT NULL,+ "instance_url" text,+ "license_key_hash" text,+ "plan" text DEFAULT 'community' NOT NULL,+ "state" text DEFAULT 'inactive' NOT NULL,+ "features" text DEFAULT '[]' NOT NULL,+ "seat_limit" bigint DEFAULT 1,+ "activated_at" bigint,+ "validated_at" bigint,+ "updated_at" bigint NOT NULL,+ CONSTRAINT "license_settings_instance_id_unique" UNIQUE("instance_id")+);+--> statement-breakpoint+CREATE TABLE "login_challenges" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "token_hash" text NOT NULL,+ "expires_at" bigint NOT NULL,+ "created_at" bigint NOT NULL,+ CONSTRAINT "login_challenges_token_hash_unique" UNIQUE("token_hash")+);+--> statement-breakpoint+CREATE TABLE "mailbox_access" (+ "id" text PRIMARY KEY NOT NULL,+ "mailbox_id" text NOT NULL,+ "user_id" text NOT NULL,+ "permission" text DEFAULT 'read_only' NOT NULL,+ "created_by_user_id" text,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "mailbox_agent_settings" (+ "mailbox_id" text PRIMARY KEY NOT NULL,+ "enabled" boolean DEFAULT false NOT NULL,+ "model_id" text,+ "auto_draft_enabled" boolean DEFAULT false NOT NULL,+ "reviewer_user_id" text,+ "instructions" text DEFAULT '' NOT NULL,+ "daily_limit" bigint DEFAULT 25 NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "mailbox_aliases" (+ "id" text PRIMARY KEY NOT NULL,+ "mailbox_id" text NOT NULL,+ "domain_id" text NOT NULL,+ "local_part" text NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "mailboxes" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "domain_id" text NOT NULL,+ "local_part" text NOT NULL,+ "display_name" text,+ "signature" text,+ "auto_reply_enabled" boolean DEFAULT false NOT NULL,+ "auto_reply_subject" text DEFAULT 'Out of office' NOT NULL,+ "auto_reply_body" text DEFAULT '' NOT NULL,+ "avatar_key" text,+ "type" text DEFAULT 'personal' NOT NULL,+ "use_all_domains" boolean DEFAULT true NOT NULL,+ "disabled" boolean DEFAULT false NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "mcp_key_mailboxes" (+ "key_id" text NOT NULL,+ "mailbox_id" text NOT NULL+);+--> statement-breakpoint+CREATE TABLE "message_attachments" (+ "id" text PRIMARY KEY NOT NULL,+ "message_id" text NOT NULL,+ "filename" text NOT NULL,+ "content_type" text NOT NULL,+ "size" bigint NOT NULL,+ "disposition" text DEFAULT 'attachment' NOT NULL,+ "content_id" text,+ "r2_key" text NOT NULL,+ "trashed_at" bigint,+ "created_at" bigint NOT NULL,+ CONSTRAINT "message_attachments_r2_key_unique" UNIQUE("r2_key")+);+--> statement-breakpoint+CREATE TABLE "message_opens" (+ "id" text PRIMARY KEY NOT NULL,+ "token" text NOT NULL,+ "opened_at" bigint NOT NULL,+ "client" text,+ "device" text,+ "country" text,+ "city" text,+ "automated" boolean DEFAULT false NOT NULL+);+--> statement-breakpoint+CREATE TABLE "message_tracking" (+ "token" text PRIMARY KEY NOT NULL,+ "message_id" text NOT NULL,+ "open_count" bigint DEFAULT 0 NOT NULL,+ "first_opened_at" bigint,+ "last_opened_at" bigint,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "messages" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "mailbox_id" text,+ "direction" text NOT NULL,+ "provider_message_id" text,+ "folder_id" text,+ "from_addr" text NOT NULL,+ "to_addr" text NOT NULL,+ "cc_addr" text,+ "bcc_addr" text,+ "reply_to" text,+ "subject" text,+ "snippet" text,+ "text_body" text,+ "html_body" text,+ "raw_r2_key" text,+ "status" text DEFAULT 'received' NOT NULL,+ "read" boolean DEFAULT false NOT NULL,+ "starred" boolean DEFAULT false NOT NULL,+ "snoozed_until" bigint,+ "thread_id" text,+ "in_reply_to" text,+ "references_header" text,+ "spam_score" bigint,+ "spam_verdict" text,+ "spam_signals" text,+ "spam_analyzed_at" bigint,+ "spam_analysis_error" text,+ "trashed_at" bigint,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "mfa_recovery_codes" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "code_hash" text NOT NULL,+ "used_at" bigint,+ "created_at" bigint NOT NULL,+ CONSTRAINT "mfa_recovery_codes_code_hash_unique" UNIQUE("code_hash")+);+--> statement-breakpoint+CREATE TABLE "outbound_jobs" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "message_id" text,+ "status" text DEFAULT 'queued' NOT NULL,+ "payload" text NOT NULL,+ "error" text,+ "scheduled_at" bigint,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "password_reset_tokens" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "token_hash" text NOT NULL,+ "expires_at" bigint NOT NULL,+ "used_at" bigint,+ "created_at" bigint NOT NULL,+ CONSTRAINT "password_reset_tokens_token_hash_unique" UNIQUE("token_hash")+);+--> statement-breakpoint+CREATE TABLE "push_devices" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "api_key_id" text NOT NULL,+ "platform" text NOT NULL,+ "token" text NOT NULL,+ "environment" text DEFAULT 'production' NOT NULL,+ "topic" text NOT NULL,+ "public_key" text,+ "previews" boolean DEFAULT true NOT NULL,+ "client_ref" text,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "push_subscriptions" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "session_id" text NOT NULL,+ "endpoint" text NOT NULL,+ "p256dh" text NOT NULL,+ "auth" text NOT NULL,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "routing_rules" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "domain_id" text NOT NULL,+ "scope" text DEFAULT 'mailbox' NOT NULL,+ "name" text,+ "enabled" boolean DEFAULT true NOT NULL,+ "pattern" text NOT NULL,+ "match_field" text DEFAULT 'email' NOT NULL,+ "match_operator" text DEFAULT 'contains' NOT NULL,+ "match_value" text DEFAULT '' NOT NULL,+ "mailbox_id" text,+ "folder_id" text,+ "action" text DEFAULT 'store' NOT NULL,+ "forward_to" text,+ "keep_copy" boolean DEFAULT false NOT NULL,+ "reject_reason" text,+ "priority" bigint DEFAULT 0 NOT NULL,+ "last_matched_at" bigint,+ "match_count" bigint DEFAULT 0 NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "sessions" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "token_hash" text NOT NULL,+ "expires_at" bigint NOT NULL,+ "created_at" bigint NOT NULL,+ CONSTRAINT "sessions_token_hash_unique" UNIQUE("token_hash")+);+--> statement-breakpoint+CREATE TABLE "shared_attachment_links" (+ "id" text PRIMARY KEY NOT NULL,+ "attachment_id" text NOT NULL,+ "expires_at" bigint NOT NULL,+ "created_at" bigint NOT NULL,+ CONSTRAINT "shared_attachment_links_attachment_id_unique" UNIQUE("attachment_id")+);+--> statement-breakpoint+CREATE TABLE "spam_feedback" (+ "message_id" text PRIMARY KEY NOT NULL,+ "mailbox_id" text NOT NULL,+ "actor_user_id" text,+ "classification" text NOT NULL,+ "training_tokens" text NOT NULL,+ "reputation_keys" text NOT NULL,+ "tokenizer_version" bigint DEFAULT 1 NOT NULL,+ "created_at" bigint NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "spam_reputation" (+ "mailbox_id" text NOT NULL,+ "type" text NOT NULL,+ "key" text NOT NULL,+ "messages_seen" bigint DEFAULT 0 NOT NULL,+ "spam_count" bigint DEFAULT 0 NOT NULL,+ "ham_count" bigint DEFAULT 0 NOT NULL,+ "first_seen_at" bigint NOT NULL,+ "last_seen_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "spam_token_stats" (+ "mailbox_id" text NOT NULL,+ "token" text NOT NULL,+ "spam_count" bigint DEFAULT 0 NOT NULL,+ "ham_count" bigint DEFAULT 0 NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "user_compose_preferences" (+ "user_id" text PRIMARY KEY NOT NULL,+ "track_opens_default" boolean DEFAULT false NOT NULL,+ "undo_send_seconds" bigint DEFAULT 15 NOT NULL,+ "updated_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "users" (+ "id" text PRIMARY KEY NOT NULL,+ "email" text NOT NULL,+ "reset_email" text,+ "forwarding_email" text,+ "password_hash" text NOT NULL,+ "name" text NOT NULL,+ "booking_username" text,+ "time_zone" text,+ "avatar_key" text,+ "role" text DEFAULT 'user' NOT NULL,+ "is_primary_admin" boolean DEFAULT false NOT NULL,+ "disabled" boolean DEFAULT false NOT NULL,+ "can_manage_mailboxes" boolean DEFAULT false NOT NULL,+ "can_manage_domains" boolean DEFAULT false NOT NULL,+ "can_manage_users" boolean DEFAULT false NOT NULL,+ "keyboard_shortcuts_enabled" boolean DEFAULT true NOT NULL,+ "spam_protection_enabled" boolean DEFAULT true NOT NULL,+ "trash_retention_days" bigint,+ "show_full_recipient_addresses" boolean DEFAULT false NOT NULL,+ "remote_content_mode" text DEFAULT 'allow' NOT NULL,+ "totp_secret" text,+ "totp_enabled" boolean DEFAULT false NOT NULL,+ "totp_confirmed_at" bigint,+ "last_sign_in_at" bigint,+ "deleted_at" bigint,+ "created_by_user_id" text,+ "created_at" bigint NOT NULL,+ CONSTRAINT "users_email_unique" UNIQUE("email")+);+--> statement-breakpoint+CREATE TABLE "webhook_deliveries" (+ "id" text PRIMARY KEY NOT NULL,+ "webhook_id" text NOT NULL,+ "event_type" text NOT NULL,+ "payload" text NOT NULL,+ "status" text DEFAULT 'pending' NOT NULL,+ "attempts" bigint DEFAULT 0 NOT NULL,+ "response_status" bigint,+ "error" text,+ "duration_ms" bigint,+ "last_attempt_at" bigint,+ "next_retry_at" bigint,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+CREATE TABLE "webhooks" (+ "id" text PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "description" text,+ "url" text NOT NULL,+ "secret" text NOT NULL,+ "events" text NOT NULL,+ "enabled" boolean DEFAULT true NOT NULL,+ "max_attempts" bigint DEFAULT 5 NOT NULL,+ "created_at" bigint NOT NULL+);+--> statement-breakpoint+ALTER TABLE "agent_chat_messages" ADD CONSTRAINT "agent_chat_messages_conversation_id_agent_conversations_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."agent_conversations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_conversations" ADD CONSTRAINT "agent_conversations_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_conversations" ADD CONSTRAINT "agent_conversations_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_draft_metadata" ADD CONSTRAINT "agent_draft_metadata_draft_id_messages_id_fk" FOREIGN KEY ("draft_id") REFERENCES "public"."messages"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_draft_metadata" ADD CONSTRAINT "agent_draft_metadata_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_draft_metadata" ADD CONSTRAINT "agent_draft_metadata_source_message_id_messages_id_fk" FOREIGN KEY ("source_message_id") REFERENCES "public"."messages"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_jobs" ADD CONSTRAINT "agent_jobs_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_jobs" ADD CONSTRAINT "agent_jobs_source_message_id_messages_id_fk" FOREIGN KEY ("source_message_id") REFERENCES "public"."messages"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_jobs" ADD CONSTRAINT "agent_jobs_reviewer_user_id_users_id_fk" FOREIGN KEY ("reviewer_user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_jobs" ADD CONSTRAINT "agent_jobs_draft_id_messages_id_fk" FOREIGN KEY ("draft_id") REFERENCES "public"."messages"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_send_approvals" ADD CONSTRAINT "agent_send_approvals_draft_id_messages_id_fk" FOREIGN KEY ("draft_id") REFERENCES "public"."messages"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_send_approvals" ADD CONSTRAINT "agent_send_approvals_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_send_approvals" ADD CONSTRAINT "agent_send_approvals_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_send_approvals" ADD CONSTRAINT "agent_send_approvals_request_key_id_api_keys_id_fk" FOREIGN KEY ("request_key_id") REFERENCES "public"."api_keys"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_actor_user_id_users_id_fk" FOREIGN KEY ("actor_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_target_user_id_users_id_fk" FOREIGN KEY ("target_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_message_id_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "public"."messages"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "auto_reply_deliveries" ADD CONSTRAINT "auto_reply_deliveries_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "backups" ADD CONSTRAINT "backups_created_by_user_id_users_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "booking_events" ADD CONSTRAINT "booking_events_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "contacts" ADD CONSTRAINT "contacts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "domain_tracking_hosts" ADD CONSTRAINT "domain_tracking_hosts_domain_id_domains_id_fk" FOREIGN KEY ("domain_id") REFERENCES "public"."domains"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "domains" ADD CONSTRAINT "domains_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "drive_items" ADD CONSTRAINT "drive_items_owner_id_users_id_fk" FOREIGN KEY ("owner_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "drive_shares" ADD CONSTRAINT "drive_shares_item_id_drive_items_id_fk" FOREIGN KEY ("item_id") REFERENCES "public"."drive_items"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "drive_shares" ADD CONSTRAINT "drive_shares_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "drive_upload_parts" ADD CONSTRAINT "drive_upload_parts_item_id_drive_items_id_fk" FOREIGN KEY ("item_id") REFERENCES "public"."drive_items"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "email_templates" ADD CONSTRAINT "email_templates_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "folders" ADD CONSTRAINT "folders_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "folders" ADD CONSTRAINT "folders_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "follow_ups" ADD CONSTRAINT "follow_ups_message_id_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "public"."messages"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "follow_ups" ADD CONSTRAINT "follow_ups_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "import_jobs" ADD CONSTRAINT "import_jobs_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "import_jobs" ADD CONSTRAINT "import_jobs_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "login_challenges" ADD CONSTRAINT "login_challenges_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailbox_access" ADD CONSTRAINT "mailbox_access_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailbox_access" ADD CONSTRAINT "mailbox_access_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailbox_access" ADD CONSTRAINT "mailbox_access_created_by_user_id_users_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailbox_agent_settings" ADD CONSTRAINT "mailbox_agent_settings_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailbox_agent_settings" ADD CONSTRAINT "mailbox_agent_settings_reviewer_user_id_users_id_fk" FOREIGN KEY ("reviewer_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailbox_aliases" ADD CONSTRAINT "mailbox_aliases_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailbox_aliases" ADD CONSTRAINT "mailbox_aliases_domain_id_domains_id_fk" FOREIGN KEY ("domain_id") REFERENCES "public"."domains"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailboxes" ADD CONSTRAINT "mailboxes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mailboxes" ADD CONSTRAINT "mailboxes_domain_id_domains_id_fk" FOREIGN KEY ("domain_id") REFERENCES "public"."domains"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mcp_key_mailboxes" ADD CONSTRAINT "mcp_key_mailboxes_key_id_api_keys_id_fk" FOREIGN KEY ("key_id") REFERENCES "public"."api_keys"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mcp_key_mailboxes" ADD CONSTRAINT "mcp_key_mailboxes_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "message_attachments" ADD CONSTRAINT "message_attachments_message_id_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "public"."messages"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "message_opens" ADD CONSTRAINT "message_opens_token_message_tracking_token_fk" FOREIGN KEY ("token") REFERENCES "public"."message_tracking"("token") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "message_tracking" ADD CONSTRAINT "message_tracking_message_id_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "public"."messages"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "messages" ADD CONSTRAINT "messages_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "messages" ADD CONSTRAINT "messages_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "messages" ADD CONSTRAINT "messages_folder_id_folders_id_fk" FOREIGN KEY ("folder_id") REFERENCES "public"."folders"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "mfa_recovery_codes" ADD CONSTRAINT "mfa_recovery_codes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "outbound_jobs" ADD CONSTRAINT "outbound_jobs_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "outbound_jobs" ADD CONSTRAINT "outbound_jobs_message_id_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "public"."messages"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "password_reset_tokens" ADD CONSTRAINT "password_reset_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "push_devices" ADD CONSTRAINT "push_devices_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "push_devices" ADD CONSTRAINT "push_devices_api_key_id_api_keys_id_fk" FOREIGN KEY ("api_key_id") REFERENCES "public"."api_keys"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "push_subscriptions" ADD CONSTRAINT "push_subscriptions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "push_subscriptions" ADD CONSTRAINT "push_subscriptions_session_id_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."sessions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "routing_rules" ADD CONSTRAINT "routing_rules_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "routing_rules" ADD CONSTRAINT "routing_rules_domain_id_domains_id_fk" FOREIGN KEY ("domain_id") REFERENCES "public"."domains"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "routing_rules" ADD CONSTRAINT "routing_rules_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "routing_rules" ADD CONSTRAINT "routing_rules_folder_id_folders_id_fk" FOREIGN KEY ("folder_id") REFERENCES "public"."folders"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "shared_attachment_links" ADD CONSTRAINT "shared_attachment_links_attachment_id_message_attachments_id_fk" FOREIGN KEY ("attachment_id") REFERENCES "public"."message_attachments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "spam_feedback" ADD CONSTRAINT "spam_feedback_message_id_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "public"."messages"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "spam_feedback" ADD CONSTRAINT "spam_feedback_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "spam_feedback" ADD CONSTRAINT "spam_feedback_actor_user_id_users_id_fk" FOREIGN KEY ("actor_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "spam_reputation" ADD CONSTRAINT "spam_reputation_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "spam_token_stats" ADD CONSTRAINT "spam_token_stats_mailbox_id_mailboxes_id_fk" FOREIGN KEY ("mailbox_id") REFERENCES "public"."mailboxes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "user_compose_preferences" ADD CONSTRAINT "user_compose_preferences_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "users" ADD CONSTRAINT "users_created_by_user_id_users_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "webhook_deliveries" ADD CONSTRAINT "webhook_deliveries_webhook_id_webhooks_id_fk" FOREIGN KEY ("webhook_id") REFERENCES "public"."webhooks"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "webhooks" ADD CONSTRAINT "webhooks_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+CREATE INDEX "agent_chat_messages_conversation_idx" ON "agent_chat_messages" USING btree ("conversation_id","created_at");--> statement-breakpoint+CREATE INDEX "agent_conversations_owner_idx" ON "agent_conversations" USING btree ("user_id","mailbox_id","updated_at");--> statement-breakpoint+CREATE INDEX "agent_conversations_mailbox_idx" ON "agent_conversations" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "agent_draft_meta_source_msg_idx" ON "agent_draft_metadata" USING btree ("source_message_id");--> statement-breakpoint+CREATE INDEX "agent_draft_metadata_mailbox_idx" ON "agent_draft_metadata" USING btree ("mailbox_id");--> statement-breakpoint+CREATE UNIQUE INDEX "agent_jobs_source_idx" ON "agent_jobs" USING btree ("mailbox_id","source_message_id");--> statement-breakpoint+CREATE INDEX "agent_jobs_due_idx" ON "agent_jobs" USING btree ("status","next_attempt_at");--> statement-breakpoint+CREATE INDEX "agent_jobs_source_message_idx" ON "agent_jobs" USING btree ("source_message_id");--> statement-breakpoint+CREATE INDEX "agent_jobs_draft_idx" ON "agent_jobs" USING btree ("draft_id");--> statement-breakpoint+CREATE INDEX "agent_jobs_reviewer_idx" ON "agent_jobs" USING btree ("reviewer_user_id");--> statement-breakpoint+CREATE INDEX "agent_send_approvals_user_idx" ON "agent_send_approvals" USING btree ("user_id","status");--> statement-breakpoint+CREATE UNIQUE INDEX "agent_send_approvals_delivery_idx" ON "agent_send_approvals" USING btree ("draft_id") WHERE status IN ('claimed', 'sent', 'unknown');--> statement-breakpoint+CREATE INDEX "agent_send_approvals_request_key_idx" ON "agent_send_approvals" USING btree ("request_key_id");--> statement-breakpoint+CREATE INDEX "agent_send_approvals_mailbox_idx" ON "agent_send_approvals" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "agent_send_approvals_draft_idx" ON "agent_send_approvals" USING btree ("draft_id");--> statement-breakpoint+CREATE INDEX "ai_usage_created_idx" ON "ai_usage" USING btree ("created_at");--> statement-breakpoint+CREATE INDEX "api_keys_user_idx" ON "api_keys" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "audit_logs_actor_idx" ON "audit_logs" USING btree ("actor_user_id");--> statement-breakpoint+CREATE INDEX "audit_logs_mailbox_idx" ON "audit_logs" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "audit_logs_created_idx" ON "audit_logs" USING btree ("created_at");--> statement-breakpoint+CREATE INDEX "audit_logs_message_id_idx" ON "audit_logs" USING btree ("message_id");--> statement-breakpoint+CREATE INDEX "audit_logs_target_user_idx" ON "audit_logs" USING btree ("target_user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "auto_reply_deliveries_mailbox_recipient_idx" ON "auto_reply_deliveries" USING btree ("mailbox_id","recipient");--> statement-breakpoint+CREATE INDEX "auto_reply_deliveries_sent_idx" ON "auto_reply_deliveries" USING btree ("sent_at");--> statement-breakpoint+CREATE INDEX "backups_created_idx" ON "backups" USING btree ("created_at");--> statement-breakpoint+CREATE INDEX "backups_status_idx" ON "backups" USING btree ("status");--> statement-breakpoint+CREATE INDEX "backups_created_by_idx" ON "backups" USING btree ("created_by_user_id");--> statement-breakpoint+CREATE INDEX "booking_events_user_idx" ON "booking_events" USING btree ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "booking_events_user_slug_idx" ON "booking_events" USING btree ("user_id","slug");--> statement-breakpoint+CREATE INDEX "calendar_events_user_starts_idx" ON "calendar_events" USING btree ("user_id","starts_at");--> statement-breakpoint+CREATE INDEX "calendar_events_mailbox_idx" ON "calendar_events" USING btree ("mailbox_id");--> statement-breakpoint+CREATE UNIQUE INDEX "contacts_user_email_idx" ON "contacts" USING btree ("user_id","email");--> statement-breakpoint+CREATE INDEX "contacts_user_idx" ON "contacts" USING btree ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "domain_tracking_hosts_hostname_idx" ON "domain_tracking_hosts" USING btree ("hostname");--> statement-breakpoint+CREATE UNIQUE INDEX "domains_hostname_idx" ON "domains" USING btree ("hostname");--> statement-breakpoint+CREATE INDEX "domains_user_idx" ON "domains" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "drive_items_owner_parent_idx" ON "drive_items" USING btree ("owner_id","parent_id");--> statement-breakpoint+CREATE UNIQUE INDEX "drive_items_link_token_idx" ON "drive_items" USING btree ("link_token");--> statement-breakpoint+CREATE UNIQUE INDEX "drive_shares_item_user_idx" ON "drive_shares" USING btree ("item_id","user_id");--> statement-breakpoint+CREATE INDEX "drive_shares_user_idx" ON "drive_shares" USING btree ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "drive_upload_parts_idx" ON "drive_upload_parts" USING btree ("item_id","part_number");--> statement-breakpoint+CREATE INDEX "email_templates_user_idx" ON "email_templates" USING btree ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "folders_mailbox_name_idx" ON "folders" USING btree ("mailbox_id","name");--> statement-breakpoint+CREATE INDEX "folders_user_idx" ON "folders" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "folders_mailbox_idx" ON "folders" USING btree ("mailbox_id");--> statement-breakpoint+CREATE UNIQUE INDEX "follow_ups_message_idx" ON "follow_ups" USING btree ("message_id");--> statement-breakpoint+CREATE INDEX "follow_ups_status_due_idx" ON "follow_ups" USING btree ("status","due_at");--> statement-breakpoint+CREATE INDEX "follow_ups_user_status_idx" ON "follow_ups" USING btree ("user_id","status");--> statement-breakpoint+CREATE INDEX "import_jobs_user_idx" ON "import_jobs" USING btree ("user_id","created_at");--> statement-breakpoint+CREATE INDEX "import_jobs_status_idx" ON "import_jobs" USING btree ("status","updated_at");--> statement-breakpoint+CREATE INDEX "jmap_changes_mailbox_seq_idx" ON "jmap_changes" USING btree ("mailbox_id","seq");--> statement-breakpoint+CREATE INDEX "login_challenges_user_idx" ON "login_challenges" USING btree ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "mailbox_access_mailbox_user_idx" ON "mailbox_access" USING btree ("mailbox_id","user_id");--> statement-breakpoint+CREATE INDEX "mailbox_access_user_idx" ON "mailbox_access" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "mailbox_access_mailbox_idx" ON "mailbox_access" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "mailbox_access_created_by_idx" ON "mailbox_access" USING btree ("created_by_user_id");--> statement-breakpoint+CREATE INDEX "mailbox_agent_settings_reviewer_idx" ON "mailbox_agent_settings" USING btree ("reviewer_user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "mailbox_aliases_address_idx" ON "mailbox_aliases" USING btree ("domain_id","local_part");--> statement-breakpoint+CREATE INDEX "mailbox_aliases_mailbox_idx" ON "mailbox_aliases" USING btree ("mailbox_id");--> statement-breakpoint+CREATE UNIQUE INDEX "mailboxes_address_idx" ON "mailboxes" USING btree ("domain_id","local_part");--> statement-breakpoint+CREATE INDEX "mailboxes_user_idx" ON "mailboxes" USING btree ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "mcp_key_mailbox_idx" ON "mcp_key_mailboxes" USING btree ("key_id","mailbox_id");--> statement-breakpoint+CREATE INDEX "mcp_key_mailboxes_mailbox_idx" ON "mcp_key_mailboxes" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "message_attachments_message_idx" ON "message_attachments" USING btree ("message_id");--> statement-breakpoint+CREATE INDEX "message_opens_token_idx" ON "message_opens" USING btree ("token","opened_at");--> statement-breakpoint+CREATE UNIQUE INDEX "message_tracking_message_idx" ON "message_tracking" USING btree ("message_id");--> statement-breakpoint+CREATE INDEX "messages_user_created_idx" ON "messages" USING btree ("user_id","created_at");--> statement-breakpoint+CREATE INDEX "messages_mailbox_idx" ON "messages" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "messages_folder_idx" ON "messages" USING btree ("folder_id");--> statement-breakpoint+CREATE INDEX "messages_thread_idx" ON "messages" USING btree ("mailbox_id","thread_id");--> statement-breakpoint+CREATE INDEX "messages_provider_message_idx" ON "messages" USING btree ("mailbox_id","provider_message_id");--> statement-breakpoint+CREATE INDEX "messages_raw_r2_key_idx" ON "messages" USING btree ("raw_r2_key");--> statement-breakpoint+CREATE INDEX "messages_trashed_at_idx" ON "messages" USING btree ("trashed_at");--> statement-breakpoint+CREATE INDEX "messages_inbox_page_idx" ON "messages" USING btree ("mailbox_id","status","folder_id","created_at" desc,"id" desc);--> statement-breakpoint+CREATE INDEX "messages_thread_key_idx" ON "messages" USING btree ("mailbox_id","status","folder_id",coalesce("thread_id", "id"),"created_at");--> statement-breakpoint+CREATE INDEX "messages_mailbox_thread_key_idx" ON "messages" USING btree ("mailbox_id",coalesce("thread_id", "id"));--> statement-breakpoint+CREATE INDEX "messages_nav_cover_idx" ON "messages" USING btree ("mailbox_id","status","folder_id","created_at" desc,"id" desc,"direction","read","thread_id","snoozed_until");--> statement-breakpoint+CREATE INDEX "messages_counts_cover_idx" ON "messages" USING btree ("mailbox_id","folder_id","direction","status","read","starred","snoozed_until");--> statement-breakpoint+CREATE INDEX "messages_conv_cover_idx" ON "messages" USING btree ("mailbox_id","status",coalesce("thread_id", "id"),"created_at","id","snoozed_until");--> statement-breakpoint+CREATE INDEX "mfa_recovery_codes_user_idx" ON "mfa_recovery_codes" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "outbound_jobs_user_idx" ON "outbound_jobs" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "outbound_jobs_message_idx" ON "outbound_jobs" USING btree ("message_id");--> statement-breakpoint+CREATE INDEX "password_reset_tokens_user_idx" ON "password_reset_tokens" USING btree ("user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "push_devices_platform_token_user_idx" ON "push_devices" USING btree ("platform","token","user_id");--> statement-breakpoint+CREATE INDEX "push_devices_user_idx" ON "push_devices" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "push_devices_api_key_idx" ON "push_devices" USING btree ("api_key_id");--> statement-breakpoint+CREATE UNIQUE INDEX "push_subscriptions_endpoint_idx" ON "push_subscriptions" USING btree ("endpoint");--> statement-breakpoint+CREATE INDEX "push_subscriptions_user_idx" ON "push_subscriptions" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "push_subscriptions_session_idx" ON "push_subscriptions" USING btree ("session_id");--> statement-breakpoint+CREATE INDEX "routing_rules_domain_scope_idx" ON "routing_rules" USING btree ("domain_id","scope","enabled");--> statement-breakpoint+CREATE INDEX "routing_rules_mailbox_idx" ON "routing_rules" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "routing_rules_priority_idx" ON "routing_rules" USING btree ("priority");--> statement-breakpoint+CREATE INDEX "routing_rules_user_idx" ON "routing_rules" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "routing_rules_folder_idx" ON "routing_rules" USING btree ("folder_id");--> statement-breakpoint+CREATE INDEX "sessions_user_idx" ON "sessions" USING btree ("user_id");--> statement-breakpoint+CREATE INDEX "spam_feedback_mailbox_idx" ON "spam_feedback" USING btree ("mailbox_id");--> statement-breakpoint+CREATE INDEX "spam_feedback_actor_user_idx" ON "spam_feedback" USING btree ("actor_user_id");--> statement-breakpoint+CREATE UNIQUE INDEX "spam_reputation_mailbox_type_key_idx" ON "spam_reputation" USING btree ("mailbox_id","type","key");--> statement-breakpoint+CREATE INDEX "spam_reputation_mailbox_idx" ON "spam_reputation" USING btree ("mailbox_id");--> statement-breakpoint+CREATE UNIQUE INDEX "spam_token_stats_mailbox_token_idx" ON "spam_token_stats" USING btree ("mailbox_id","token");--> statement-breakpoint+CREATE INDEX "spam_token_stats_mailbox_idx" ON "spam_token_stats" USING btree ("mailbox_id");--> statement-breakpoint+CREATE UNIQUE INDEX "users_booking_username_idx" ON "users" USING btree ("booking_username");--> statement-breakpoint+CREATE INDEX "users_created_by_idx" ON "users" USING btree ("created_by_user_id");--> statement-breakpoint+CREATE INDEX "webhook_deliveries_webhook_idx" ON "webhook_deliveries" USING btree ("webhook_id","created_at");--> statement-breakpoint+CREATE INDEX "webhook_deliveries_status_idx" ON "webhook_deliveries" USING btree ("status");--> statement-breakpoint+CREATE INDEX "webhooks_user_idx" ON "webhooks" USING btree ("user_id");\ No newline at end of filediff --git a/drizzle/migrations-pg/0001_triggers_and_seeds.sql b/drizzle/migrations-pg/0001_triggers_and_seeds.sqlnew file mode 100644index 0000000..f56b895--- /dev/null+++ b/drizzle/migrations-pg/0001_triggers_and_seeds.sql@@ -0,0 +1,126 @@+-- Objects drizzle-kit does not generate: seed rows, and the triggers that keep+-- them (and messages.trashed_at) current whichever code path writes. The SQLite twins are migrations+-- 0009, 0012, 0042, 0053 and 0064. Full-text search has no table here: PostgreSQL searches with ILIKE,+-- optionally accelerated by the pg_trgm indexes at the end.+INSERT INTO backup_settings (id, enabled, schedule_type, retention_enabled, retention_days, updated_at)+VALUES ('default', false, 'daily', false, 30, extract(epoch from now())::bigint)+ON CONFLICT DO NOTHING;--> statement-breakpoint+INSERT INTO app_settings (id, app_name, updated_at)+VALUES ('default', 'Mailflare', extract(epoch from now())::bigint)+ON CONFLICT DO NOTHING;--> statement-breakpoint+INSERT INTO jmap_change_floor (id, seq) VALUES (1, 0) ON CONFLICT DO NOTHING;--> statement-breakpoint+CREATE FUNCTION mailflare_bump_revision(target text) RETURNS void AS $$+BEGIN+ INSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (target, 1)+ ON CONFLICT (mailbox_id) DO UPDATE SET revision = jmap_mailbox_revisions.revision + 1;+END;+$$ LANGUAGE plpgsql;--> statement-breakpoint+CREATE FUNCTION mailflare_messages_trashed_at() RETURNS trigger AS $$+BEGIN+ IF TG_OP = 'INSERT' THEN+ IF NEW.status IN ('trash', 'spam') THEN+ NEW.trashed_at := extract(epoch from now())::bigint;+ END IF;+ ELSIF (NEW.status IN ('trash', 'spam')) <> (OLD.status IN ('trash', 'spam')) THEN+ NEW.trashed_at := CASE WHEN NEW.status IN ('trash', 'spam') THEN extract(epoch from now())::bigint ELSE NULL END;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;--> statement-breakpoint+CREATE TRIGGER messages_trashed_at_bi BEFORE INSERT OR UPDATE OF status ON messages+FOR EACH ROW EXECUTE FUNCTION mailflare_messages_trashed_at();--> statement-breakpoint+CREATE FUNCTION mailflare_messages_changed() RETURNS trigger AS $$+BEGIN+ IF TG_OP = 'INSERT' THEN+ IF NEW.mailbox_id IS NOT NULL THEN+ PERFORM mailflare_bump_revision(NEW.mailbox_id);+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');+ END IF;+ ELSIF TG_OP = 'UPDATE' THEN+ IF NEW.mailbox_id IS NOT NULL THEN+ PERFORM mailflare_bump_revision(NEW.mailbox_id);+ END IF;+ IF OLD.mailbox_id IS NOT NULL AND OLD.mailbox_id IS DISTINCT FROM NEW.mailbox_id THEN+ PERFORM mailflare_bump_revision(OLD.mailbox_id);+ END IF;+ IF OLD.mailbox_id IS NOT DISTINCT FROM NEW.mailbox_id THEN+ IF NEW.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'updated');+ END IF;+ ELSE+ IF OLD.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)+ VALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');+ END IF;+ IF NEW.mailbox_id IS NOT NULL THEN+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');+ END IF;+ END IF;+ ELSE+ IF OLD.mailbox_id IS NOT NULL THEN+ PERFORM mailflare_bump_revision(OLD.mailbox_id);+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)+ VALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');+ END IF;+ END IF;+ RETURN NULL;+END;+$$ LANGUAGE plpgsql;--> statement-breakpoint+CREATE TRIGGER messages_jmap_changed AFTER INSERT OR UPDATE OR DELETE ON messages+FOR EACH ROW EXECUTE FUNCTION mailflare_messages_changed();--> statement-breakpoint+CREATE FUNCTION mailflare_folders_changed() RETURNS trigger AS $$+BEGIN+ IF TG_OP = 'INSERT' THEN+ PERFORM mailflare_bump_revision(NEW.mailbox_id);+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.mailbox_id, 'mailbox', NEW.id, 'created');+ ELSIF TG_OP = 'UPDATE' THEN+ PERFORM mailflare_bump_revision(NEW.mailbox_id);+ IF OLD.mailbox_id IS DISTINCT FROM NEW.mailbox_id THEN+ PERFORM mailflare_bump_revision(OLD.mailbox_id);+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');+ END IF;+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change)+ VALUES (NEW.mailbox_id, 'mailbox', NEW.id, CASE WHEN OLD.mailbox_id IS NOT DISTINCT FROM NEW.mailbox_id THEN 'updated' ELSE 'created' END);+ ELSE+ PERFORM mailflare_bump_revision(OLD.mailbox_id);+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');+ END IF;+ RETURN NULL;+END;+$$ LANGUAGE plpgsql;--> statement-breakpoint+CREATE TRIGGER folders_jmap_changed AFTER INSERT OR UPDATE OR DELETE ON folders+FOR EACH ROW EXECUTE FUNCTION mailflare_folders_changed();--> statement-breakpoint+CREATE FUNCTION mailflare_mailboxes_changed() RETURNS trigger AS $$+BEGIN+ PERFORM mailflare_bump_revision(NEW.id);+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.id, 'mailbox', NEW.id, 'updated');+ RETURN NULL;+END;+$$ LANGUAGE plpgsql;--> statement-breakpoint+CREATE TRIGGER mailboxes_jmap_changed AFTER UPDATE ON mailboxes+FOR EACH ROW EXECUTE FUNCTION mailflare_mailboxes_changed();--> statement-breakpoint+CREATE FUNCTION mailflare_aliases_changed() RETURNS trigger AS $$+BEGIN+ IF TG_OP IN ('INSERT', 'UPDATE') THEN+ PERFORM mailflare_bump_revision(NEW.mailbox_id);+ END IF;+ IF TG_OP = 'DELETE' OR (TG_OP = 'UPDATE' AND OLD.mailbox_id IS DISTINCT FROM NEW.mailbox_id) THEN+ PERFORM mailflare_bump_revision(OLD.mailbox_id);+ END IF;+ RETURN NULL;+END;+$$ LANGUAGE plpgsql;--> statement-breakpoint+CREATE TRIGGER mailbox_aliases_jmap_changed AFTER INSERT OR UPDATE OR DELETE ON mailbox_aliases+FOR EACH ROW EXECUTE FUNCTION mailflare_aliases_changed();--> statement-breakpoint+DO $$+BEGIN+ CREATE EXTENSION IF NOT EXISTS pg_trgm;+ CREATE INDEX messages_subject_trgm_idx ON messages USING gin (lower(subject) gin_trgm_ops);+ CREATE INDEX messages_text_body_trgm_idx ON messages USING gin (lower(text_body) gin_trgm_ops);+EXCEPTION WHEN OTHERS THEN+ RAISE NOTICE 'pg_trgm is unavailable; message search will scan with ILIKE instead (%).', SQLERRM;+END;+$$;diff --git a/drizzle/migrations-pg/meta/0000_snapshot.json b/drizzle/migrations-pg/meta/0000_snapshot.jsonnew file mode 100644index 0000000..b215399--- /dev/null+++ b/drizzle/migrations-pg/meta/0000_snapshot.json@@ -0,0 +1,6955 @@+{+ "id": "b48bf275-c424-4590-8daa-631fe092e5d6",+ "prevId": "00000000-0000-0000-0000-000000000000",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.agent_chat_messages": {+ "name": "agent_chat_messages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tool_name": {+ "name": "tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_chat_messages_conversation_idx": {+ "name": "agent_chat_messages_conversation_idx",+ "columns": [+ {+ "expression": "conversation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_messages_conversation_id_agent_conversations_id_fk": {+ "name": "agent_chat_messages_conversation_id_agent_conversations_id_fk",+ "tableFrom": "agent_chat_messages",+ "tableTo": "agent_conversations",+ "columnsFrom": [+ "conversation_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_conversations": {+ "name": "agent_conversations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'New conversation'"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_conversations_owner_idx": {+ "name": "agent_conversations_owner_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_conversations_mailbox_idx": {+ "name": "agent_conversations_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_conversations_user_id_users_id_fk": {+ "name": "agent_conversations_user_id_users_id_fk",+ "tableFrom": "agent_conversations",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_conversations_mailbox_id_mailboxes_id_fk": {+ "name": "agent_conversations_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_conversations",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_draft_metadata": {+ "name": "agent_draft_metadata",+ "schema": "",+ "columns": {+ "draft_id": {+ "name": "draft_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "origin": {+ "name": "origin",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_message_id": {+ "name": "source_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "revision": {+ "name": "revision",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "human_edited_at": {+ "name": "human_edited_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_draft_meta_source_msg_idx": {+ "name": "agent_draft_meta_source_msg_idx",+ "columns": [+ {+ "expression": "source_message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_draft_metadata_mailbox_idx": {+ "name": "agent_draft_metadata_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_draft_metadata_draft_id_messages_id_fk": {+ "name": "agent_draft_metadata_draft_id_messages_id_fk",+ "tableFrom": "agent_draft_metadata",+ "tableTo": "messages",+ "columnsFrom": [+ "draft_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_draft_metadata_mailbox_id_mailboxes_id_fk": {+ "name": "agent_draft_metadata_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_draft_metadata",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_draft_metadata_source_message_id_messages_id_fk": {+ "name": "agent_draft_metadata_source_message_id_messages_id_fk",+ "tableFrom": "agent_draft_metadata",+ "tableTo": "messages",+ "columnsFrom": [+ "source_message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_jobs": {+ "name": "agent_jobs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_message_id": {+ "name": "source_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reviewer_user_id": {+ "name": "reviewer_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "lease_until": {+ "name": "lease_until",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "draft_id": {+ "name": "draft_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_jobs_source_idx": {+ "name": "agent_jobs_source_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_jobs_due_idx": {+ "name": "agent_jobs_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_jobs_source_message_idx": {+ "name": "agent_jobs_source_message_idx",+ "columns": [+ {+ "expression": "source_message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_jobs_draft_idx": {+ "name": "agent_jobs_draft_idx",+ "columns": [+ {+ "expression": "draft_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_jobs_reviewer_idx": {+ "name": "agent_jobs_reviewer_idx",+ "columns": [+ {+ "expression": "reviewer_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_jobs_mailbox_id_mailboxes_id_fk": {+ "name": "agent_jobs_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_jobs_source_message_id_messages_id_fk": {+ "name": "agent_jobs_source_message_id_messages_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "messages",+ "columnsFrom": [+ "source_message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_jobs_reviewer_user_id_users_id_fk": {+ "name": "agent_jobs_reviewer_user_id_users_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "users",+ "columnsFrom": [+ "reviewer_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_jobs_draft_id_messages_id_fk": {+ "name": "agent_jobs_draft_id_messages_id_fk",+ "tableFrom": "agent_jobs",+ "tableTo": "messages",+ "columnsFrom": [+ "draft_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_send_approvals": {+ "name": "agent_send_approvals",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "draft_id": {+ "name": "draft_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "request_key_id": {+ "name": "request_key_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "revision": {+ "name": "revision",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "payload_hash": {+ "name": "payload_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "claimed_at": {+ "name": "claimed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_send_approvals_user_idx": {+ "name": "agent_send_approvals_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_send_approvals_delivery_idx": {+ "name": "agent_send_approvals_delivery_idx",+ "columns": [+ {+ "expression": "draft_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "status IN ('claimed', 'sent', 'unknown')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_send_approvals_request_key_idx": {+ "name": "agent_send_approvals_request_key_idx",+ "columns": [+ {+ "expression": "request_key_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_send_approvals_mailbox_idx": {+ "name": "agent_send_approvals_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_send_approvals_draft_idx": {+ "name": "agent_send_approvals_draft_idx",+ "columns": [+ {+ "expression": "draft_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_send_approvals_draft_id_messages_id_fk": {+ "name": "agent_send_approvals_draft_id_messages_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "messages",+ "columnsFrom": [+ "draft_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_send_approvals_mailbox_id_mailboxes_id_fk": {+ "name": "agent_send_approvals_mailbox_id_mailboxes_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_send_approvals_user_id_users_id_fk": {+ "name": "agent_send_approvals_user_id_users_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_send_approvals_request_key_id_api_keys_id_fk": {+ "name": "agent_send_approvals_request_key_id_api_keys_id_fk",+ "tableFrom": "agent_send_approvals",+ "tableTo": "api_keys",+ "columnsFrom": [+ "request_key_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_usage": {+ "name": "ai_usage",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "cost_usd_micros": {+ "name": "cost_usd_micros",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "ai_usage_created_idx": {+ "name": "ai_usage_created_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.api_keys": {+ "name": "api_keys",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'legacy'"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key_hash": {+ "name": "key_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_scope_enabled": {+ "name": "mailbox_scope_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "api_keys_user_idx": {+ "name": "api_keys_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "api_keys_user_id_users_id_fk": {+ "name": "api_keys_user_id_users_id_fk",+ "tableFrom": "api_keys",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.app_settings": {+ "name": "app_settings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "app_name": {+ "name": "app_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'Mailflare'"+ },+ "outbound_attachment_max_mb": {+ "name": "outbound_attachment_max_mb",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 25+ },+ "drive_storage_limit_bytes": {+ "name": "drive_storage_limit_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "resend_api_key": {+ "name": "resend_api_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "aws_config": {+ "name": "aws_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ses_receiving": {+ "name": "ses_receiving",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resend_webhook_id": {+ "name": "resend_webhook_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resend_webhook_secret": {+ "name": "resend_webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "icon_key": {+ "name": "icon_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_enabled": {+ "name": "agent_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "agent_provider": {+ "name": "agent_provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_preset": {+ "name": "agent_preset",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_base_url": {+ "name": "agent_base_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_api_key": {+ "name": "agent_api_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_model": {+ "name": "agent_model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_model_rates": {+ "name": "agent_model_rates",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "spamhaus_dqs_key": {+ "name": "spamhaus_dqs_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "abusech_auth_key": {+ "name": "abusech_auth_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "spam_domain_age_check": {+ "name": "spam_domain_age_check",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "spam_brands": {+ "name": "spam_brands",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_logs": {+ "name": "audit_logs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "target_user_id": {+ "name": "target_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "audit_logs_actor_idx": {+ "name": "audit_logs_actor_idx",+ "columns": [+ {+ "expression": "actor_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_logs_mailbox_idx": {+ "name": "audit_logs_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_logs_created_idx": {+ "name": "audit_logs_created_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_logs_message_id_idx": {+ "name": "audit_logs_message_id_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_logs_target_user_idx": {+ "name": "audit_logs_target_user_idx",+ "columns": [+ {+ "expression": "target_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_logs_actor_user_id_users_id_fk": {+ "name": "audit_logs_actor_user_id_users_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "users",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "audit_logs_target_user_id_users_id_fk": {+ "name": "audit_logs_target_user_id_users_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "users",+ "columnsFrom": [+ "target_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "audit_logs_mailbox_id_mailboxes_id_fk": {+ "name": "audit_logs_mailbox_id_mailboxes_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "audit_logs_message_id_messages_id_fk": {+ "name": "audit_logs_message_id_messages_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.auto_reply_deliveries": {+ "name": "auto_reply_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "recipient": {+ "name": "recipient",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "sent_at": {+ "name": "sent_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "auto_reply_deliveries_mailbox_recipient_idx": {+ "name": "auto_reply_deliveries_mailbox_recipient_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "recipient",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "auto_reply_deliveries_sent_idx": {+ "name": "auto_reply_deliveries_sent_idx",+ "columns": [+ {+ "expression": "sent_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "auto_reply_deliveries_mailbox_id_mailboxes_id_fk": {+ "name": "auto_reply_deliveries_mailbox_id_mailboxes_id_fk",+ "tableFrom": "auto_reply_deliveries",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.backup_settings": {+ "name": "backup_settings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "schedule_type": {+ "name": "schedule_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'daily'"+ },+ "schedule_value": {+ "name": "schedule_value",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "retention_enabled": {+ "name": "retention_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "retention_days": {+ "name": "retention_days",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 30+ },+ "excluded_table_groups": {+ "name": "excluded_table_groups",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.backups": {+ "name": "backups",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "size": {+ "name": "size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "started_at": {+ "name": "started_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "backups_created_idx": {+ "name": "backups_created_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "backups_status_idx": {+ "name": "backups_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "backups_created_by_idx": {+ "name": "backups_created_by_idx",+ "columns": [+ {+ "expression": "created_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "backups_created_by_user_id_users_id_fk": {+ "name": "backups_created_by_user_id_users_id_fk",+ "tableFrom": "backups",+ "tableTo": "users",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.booking_events": {+ "name": "booking_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#2563eb'"+ },+ "host_ids": {+ "name": "host_ids",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "duration_minutes": {+ "name": "duration_minutes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "location": {+ "name": "location",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "weekdays": {+ "name": "weekdays",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[1,2,3,4,5]'"+ },+ "start_time": {+ "name": "start_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'09:00'"+ },+ "end_time": {+ "name": "end_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'17:00'"+ },+ "time_ranges": {+ "name": "time_ranges",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[{\"startTime\":\"09:00\",\"endTime\":\"17:00\"}]'"+ },+ "time_zone": {+ "name": "time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'UTC'"+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "booking_events_user_idx": {+ "name": "booking_events_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "booking_events_user_slug_idx": {+ "name": "booking_events_user_slug_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "slug",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "booking_events_user_id_users_id_fk": {+ "name": "booking_events_user_id_users_id_fk",+ "tableFrom": "booking_events",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.calendar_events": {+ "name": "calendar_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "location": {+ "name": "location",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "attendees": {+ "name": "attendees",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'blue'"+ },+ "repeat": {+ "name": "repeat",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'none'"+ },+ "repeat_days": {+ "name": "repeat_days",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "repeat_anchor_day": {+ "name": "repeat_anchor_day",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "repeat_until": {+ "name": "repeat_until",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "excluded_occurrences": {+ "name": "excluded_occurrences",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "time_zone": {+ "name": "time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "starts_at": {+ "name": "starts_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "ends_at": {+ "name": "ends_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "calendar_events_user_starts_idx": {+ "name": "calendar_events_user_starts_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "starts_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "calendar_events_mailbox_idx": {+ "name": "calendar_events_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "calendar_events_user_id_users_id_fk": {+ "name": "calendar_events_user_id_users_id_fk",+ "tableFrom": "calendar_events",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_events_mailbox_id_mailboxes_id_fk": {+ "name": "calendar_events_mailbox_id_mailboxes_id_fk",+ "tableFrom": "calendar_events",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.contacts": {+ "name": "contacts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "avatar_key": {+ "name": "avatar_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'inbound'"+ },+ "blocked": {+ "name": "blocked",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "remote_content_allowed": {+ "name": "remote_content_allowed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "contacts_user_email_idx": {+ "name": "contacts_user_email_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "contacts_user_idx": {+ "name": "contacts_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "contacts_user_id_users_id_fk": {+ "name": "contacts_user_id_users_id_fk",+ "tableFrom": "contacts",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.domain_tracking_hosts": {+ "name": "domain_tracking_hosts",+ "schema": "",+ "columns": {+ "domain_id": {+ "name": "domain_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "hostname": {+ "name": "hostname",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "domain_tracking_hosts_hostname_idx": {+ "name": "domain_tracking_hosts_hostname_idx",+ "columns": [+ {+ "expression": "hostname",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "domain_tracking_hosts_domain_id_domains_id_fk": {+ "name": "domain_tracking_hosts_domain_id_domains_id_fk",+ "tableFrom": "domain_tracking_hosts",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.domains": {+ "name": "domains",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "hostname": {+ "name": "hostname",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "zone_id": {+ "name": "zone_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "routing_status": {+ "name": "routing_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "sending_subdomain_tag": {+ "name": "sending_subdomain_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "sending_provider": {+ "name": "sending_provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'none'"+ },+ "receiving_provider": {+ "name": "receiving_provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'cloudflare'"+ },+ "sending_requested": {+ "name": "sending_requested",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "sending_enabled": {+ "name": "sending_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "routing_enabled": {+ "name": "routing_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "dns_skipped": {+ "name": "dns_skipped",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "domains_hostname_idx": {+ "name": "domains_hostname_idx",+ "columns": [+ {+ "expression": "hostname",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "domains_user_idx": {+ "name": "domains_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "domains_user_id_users_id_fk": {+ "name": "domains_user_id_users_id_fk",+ "tableFrom": "domains",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.drive_items": {+ "name": "drive_items",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "size": {+ "name": "size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'application/octet-stream'"+ },+ "upload_id": {+ "name": "upload_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "upload_part_size": {+ "name": "upload_part_size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "upload_fingerprint": {+ "name": "upload_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "link_token": {+ "name": "link_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "trashed_at": {+ "name": "trashed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "drive_items_owner_parent_idx": {+ "name": "drive_items_owner_parent_idx",+ "columns": [+ {+ "expression": "owner_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "drive_items_link_token_idx": {+ "name": "drive_items_link_token_idx",+ "columns": [+ {+ "expression": "link_token",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "drive_items_owner_id_users_id_fk": {+ "name": "drive_items_owner_id_users_id_fk",+ "tableFrom": "drive_items",+ "tableTo": "users",+ "columnsFrom": [+ "owner_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.drive_shares": {+ "name": "drive_shares",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "item_id": {+ "name": "item_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'view'"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "drive_shares_item_user_idx": {+ "name": "drive_shares_item_user_idx",+ "columns": [+ {+ "expression": "item_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "drive_shares_user_idx": {+ "name": "drive_shares_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "drive_shares_item_id_drive_items_id_fk": {+ "name": "drive_shares_item_id_drive_items_id_fk",+ "tableFrom": "drive_shares",+ "tableTo": "drive_items",+ "columnsFrom": [+ "item_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "drive_shares_user_id_users_id_fk": {+ "name": "drive_shares_user_id_users_id_fk",+ "tableFrom": "drive_shares",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.drive_upload_parts": {+ "name": "drive_upload_parts",+ "schema": "",+ "columns": {+ "item_id": {+ "name": "item_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "part_number": {+ "name": "part_number",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "etag": {+ "name": "etag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "drive_upload_parts_idx": {+ "name": "drive_upload_parts_idx",+ "columns": [+ {+ "expression": "item_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "part_number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "drive_upload_parts_item_id_drive_items_id_fk": {+ "name": "drive_upload_parts_item_id_drive_items_id_fk",+ "tableFrom": "drive_upload_parts",+ "tableTo": "drive_items",+ "columnsFrom": [+ "item_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.email_templates": {+ "name": "email_templates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "subject": {+ "name": "subject",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "text_body": {+ "name": "text_body",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "email_templates_user_idx": {+ "name": "email_templates_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "email_templates_user_id_users_id_fk": {+ "name": "email_templates_user_id_users_id_fk",+ "tableFrom": "email_templates",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.folders": {+ "name": "folders",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#2563eb'"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "folders_mailbox_name_idx": {+ "name": "folders_mailbox_name_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "folders_user_idx": {+ "name": "folders_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "folders_mailbox_idx": {+ "name": "folders_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "folders_user_id_users_id_fk": {+ "name": "folders_user_id_users_id_fk",+ "tableFrom": "folders",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "folders_mailbox_id_mailboxes_id_fk": {+ "name": "folders_mailbox_id_mailboxes_id_fk",+ "tableFrom": "folders",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.follow_ups": {+ "name": "follow_ups",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "due_at": {+ "name": "due_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "follow_ups_message_idx": {+ "name": "follow_ups_message_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "follow_ups_status_due_idx": {+ "name": "follow_ups_status_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "due_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "follow_ups_user_status_idx": {+ "name": "follow_ups_user_status_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "follow_ups_message_id_messages_id_fk": {+ "name": "follow_ups_message_id_messages_id_fk",+ "tableFrom": "follow_ups",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "follow_ups_user_id_users_id_fk": {+ "name": "follow_ups_user_id_users_id_fk",+ "tableFrom": "follow_ups",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_jobs": {+ "name": "import_jobs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "total": {+ "name": "total",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "processed": {+ "name": "processed",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "imported": {+ "name": "imported",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "skipped": {+ "name": "skipped",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "spec": {+ "name": "spec",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "cursor": {+ "name": "cursor",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'"+ },+ "errors": {+ "name": "errors",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "error_count": {+ "name": "error_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "started_at": {+ "name": "started_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "finished_at": {+ "name": "finished_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "import_jobs_user_idx": {+ "name": "import_jobs_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "import_jobs_status_idx": {+ "name": "import_jobs_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "import_jobs_user_id_users_id_fk": {+ "name": "import_jobs_user_id_users_id_fk",+ "tableFrom": "import_jobs",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "import_jobs_mailbox_id_mailboxes_id_fk": {+ "name": "import_jobs_mailbox_id_mailboxes_id_fk",+ "tableFrom": "import_jobs",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.jmap_change_floor": {+ "name": "jmap_change_floor",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "bigint",+ "primaryKey": true,+ "notNull": true+ },+ "seq": {+ "name": "seq",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.jmap_changes": {+ "name": "jmap_changes",+ "schema": "",+ "columns": {+ "seq": {+ "name": "seq",+ "type": "bigserial",+ "primaryKey": true,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "object_type": {+ "name": "object_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "object_id": {+ "name": "object_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "change": {+ "name": "change",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": "(extract(epoch from now())::bigint)"+ }+ },+ "indexes": {+ "jmap_changes_mailbox_seq_idx": {+ "name": "jmap_changes_mailbox_seq_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "seq",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.jmap_mailbox_revisions": {+ "name": "jmap_mailbox_revisions",+ "schema": "",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.license_settings": {+ "name": "license_settings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "instance_id": {+ "name": "instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "instance_url": {+ "name": "instance_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "license_key_hash": {+ "name": "license_key_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'community'"+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'inactive'"+ },+ "features": {+ "name": "features",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "seat_limit": {+ "name": "seat_limit",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "activated_at": {+ "name": "activated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "validated_at": {+ "name": "validated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "license_settings_instance_id_unique": {+ "name": "license_settings_instance_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "instance_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.login_challenges": {+ "name": "login_challenges",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "login_challenges_user_idx": {+ "name": "login_challenges_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "login_challenges_user_id_users_id_fk": {+ "name": "login_challenges_user_id_users_id_fk",+ "tableFrom": "login_challenges",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "login_challenges_token_hash_unique": {+ "name": "login_challenges_token_hash_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token_hash"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mailbox_access": {+ "name": "mailbox_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'read_only'"+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "mailbox_access_mailbox_user_idx": {+ "name": "mailbox_access_mailbox_user_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mailbox_access_user_idx": {+ "name": "mailbox_access_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mailbox_access_mailbox_idx": {+ "name": "mailbox_access_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mailbox_access_created_by_idx": {+ "name": "mailbox_access_created_by_idx",+ "columns": [+ {+ "expression": "created_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "mailbox_access_mailbox_id_mailboxes_id_fk": {+ "name": "mailbox_access_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mailbox_access",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_access_user_id_users_id_fk": {+ "name": "mailbox_access_user_id_users_id_fk",+ "tableFrom": "mailbox_access",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_access_created_by_user_id_users_id_fk": {+ "name": "mailbox_access_created_by_user_id_users_id_fk",+ "tableFrom": "mailbox_access",+ "tableTo": "users",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mailbox_agent_settings": {+ "name": "mailbox_agent_settings",+ "schema": "",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "auto_draft_enabled": {+ "name": "auto_draft_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "reviewer_user_id": {+ "name": "reviewer_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "daily_limit": {+ "name": "daily_limit",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 25+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "mailbox_agent_settings_reviewer_idx": {+ "name": "mailbox_agent_settings_reviewer_idx",+ "columns": [+ {+ "expression": "reviewer_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "mailbox_agent_settings_mailbox_id_mailboxes_id_fk": {+ "name": "mailbox_agent_settings_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mailbox_agent_settings",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_agent_settings_reviewer_user_id_users_id_fk": {+ "name": "mailbox_agent_settings_reviewer_user_id_users_id_fk",+ "tableFrom": "mailbox_agent_settings",+ "tableTo": "users",+ "columnsFrom": [+ "reviewer_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mailbox_aliases": {+ "name": "mailbox_aliases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain_id": {+ "name": "domain_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "local_part": {+ "name": "local_part",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "mailbox_aliases_address_idx": {+ "name": "mailbox_aliases_address_idx",+ "columns": [+ {+ "expression": "domain_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "local_part",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mailbox_aliases_mailbox_idx": {+ "name": "mailbox_aliases_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "mailbox_aliases_mailbox_id_mailboxes_id_fk": {+ "name": "mailbox_aliases_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mailbox_aliases",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailbox_aliases_domain_id_domains_id_fk": {+ "name": "mailbox_aliases_domain_id_domains_id_fk",+ "tableFrom": "mailbox_aliases",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mailboxes": {+ "name": "mailboxes",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain_id": {+ "name": "domain_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "local_part": {+ "name": "local_part",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "signature": {+ "name": "signature",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "auto_reply_enabled": {+ "name": "auto_reply_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "auto_reply_subject": {+ "name": "auto_reply_subject",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'Out of office'"+ },+ "auto_reply_body": {+ "name": "auto_reply_body",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "avatar_key": {+ "name": "avatar_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'personal'"+ },+ "use_all_domains": {+ "name": "use_all_domains",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "mailboxes_address_idx": {+ "name": "mailboxes_address_idx",+ "columns": [+ {+ "expression": "domain_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "local_part",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mailboxes_user_idx": {+ "name": "mailboxes_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "mailboxes_user_id_users_id_fk": {+ "name": "mailboxes_user_id_users_id_fk",+ "tableFrom": "mailboxes",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mailboxes_domain_id_domains_id_fk": {+ "name": "mailboxes_domain_id_domains_id_fk",+ "tableFrom": "mailboxes",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_key_mailboxes": {+ "name": "mcp_key_mailboxes",+ "schema": "",+ "columns": {+ "key_id": {+ "name": "key_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "mcp_key_mailbox_idx": {+ "name": "mcp_key_mailbox_idx",+ "columns": [+ {+ "expression": "key_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_key_mailboxes_mailbox_idx": {+ "name": "mcp_key_mailboxes_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "mcp_key_mailboxes_key_id_api_keys_id_fk": {+ "name": "mcp_key_mailboxes_key_id_api_keys_id_fk",+ "tableFrom": "mcp_key_mailboxes",+ "tableTo": "api_keys",+ "columnsFrom": [+ "key_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "mcp_key_mailboxes_mailbox_id_mailboxes_id_fk": {+ "name": "mcp_key_mailboxes_mailbox_id_mailboxes_id_fk",+ "tableFrom": "mcp_key_mailboxes",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.message_attachments": {+ "name": "message_attachments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "disposition": {+ "name": "disposition",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'attachment'"+ },+ "content_id": {+ "name": "content_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trashed_at": {+ "name": "trashed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "message_attachments_message_idx": {+ "name": "message_attachments_message_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "message_attachments_message_id_messages_id_fk": {+ "name": "message_attachments_message_id_messages_id_fk",+ "tableFrom": "message_attachments",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "message_attachments_r2_key_unique": {+ "name": "message_attachments_r2_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "r2_key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.message_opens": {+ "name": "message_opens",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "opened_at": {+ "name": "opened_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "client": {+ "name": "client",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "device": {+ "name": "device",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "country": {+ "name": "country",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "city": {+ "name": "city",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "automated": {+ "name": "automated",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ }+ },+ "indexes": {+ "message_opens_token_idx": {+ "name": "message_opens_token_idx",+ "columns": [+ {+ "expression": "token",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "opened_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "message_opens_token_message_tracking_token_fk": {+ "name": "message_opens_token_message_tracking_token_fk",+ "tableFrom": "message_opens",+ "tableTo": "message_tracking",+ "columnsFrom": [+ "token"+ ],+ "columnsTo": [+ "token"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.message_tracking": {+ "name": "message_tracking",+ "schema": "",+ "columns": {+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "open_count": {+ "name": "open_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "first_opened_at": {+ "name": "first_opened_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "last_opened_at": {+ "name": "last_opened_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "message_tracking_message_idx": {+ "name": "message_tracking_message_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "message_tracking_message_id_messages_id_fk": {+ "name": "message_tracking_message_id_messages_id_fk",+ "tableFrom": "message_tracking",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.messages": {+ "name": "messages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "direction": {+ "name": "direction",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_message_id": {+ "name": "provider_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "folder_id": {+ "name": "folder_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "from_addr": {+ "name": "from_addr",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "to_addr": {+ "name": "to_addr",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "cc_addr": {+ "name": "cc_addr",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "bcc_addr": {+ "name": "bcc_addr",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reply_to": {+ "name": "reply_to",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "subject": {+ "name": "subject",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "snippet": {+ "name": "snippet",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "text_body": {+ "name": "text_body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "html_body": {+ "name": "html_body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "raw_r2_key": {+ "name": "raw_r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'received'"+ },+ "read": {+ "name": "read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "starred": {+ "name": "starred",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "in_reply_to": {+ "name": "in_reply_to",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "references_header": {+ "name": "references_header",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "spam_score": {+ "name": "spam_score",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "spam_verdict": {+ "name": "spam_verdict",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "spam_signals": {+ "name": "spam_signals",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "spam_analyzed_at": {+ "name": "spam_analyzed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "spam_analysis_error": {+ "name": "spam_analysis_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "trashed_at": {+ "name": "trashed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "messages_user_created_idx": {+ "name": "messages_user_created_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_mailbox_idx": {+ "name": "messages_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_folder_idx": {+ "name": "messages_folder_idx",+ "columns": [+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_thread_idx": {+ "name": "messages_thread_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_provider_message_idx": {+ "name": "messages_provider_message_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_raw_r2_key_idx": {+ "name": "messages_raw_r2_key_idx",+ "columns": [+ {+ "expression": "raw_r2_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_trashed_at_idx": {+ "name": "messages_trashed_at_idx",+ "columns": [+ {+ "expression": "trashed_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_inbox_page_idx": {+ "name": "messages_inbox_page_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "\"created_at\" desc",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "\"id\" desc",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_thread_key_idx": {+ "name": "messages_thread_key_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "coalesce(\"thread_id\", \"id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_mailbox_thread_key_idx": {+ "name": "messages_mailbox_thread_key_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "coalesce(\"thread_id\", \"id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_nav_cover_idx": {+ "name": "messages_nav_cover_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "\"created_at\" desc",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "\"id\" desc",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "direction",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "read",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "snoozed_until",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_counts_cover_idx": {+ "name": "messages_counts_cover_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "direction",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "read",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "starred",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "snoozed_until",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_conv_cover_idx": {+ "name": "messages_conv_cover_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "coalesce(\"thread_id\", \"id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "snoozed_until",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "messages_user_id_users_id_fk": {+ "name": "messages_user_id_users_id_fk",+ "tableFrom": "messages",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "messages_mailbox_id_mailboxes_id_fk": {+ "name": "messages_mailbox_id_mailboxes_id_fk",+ "tableFrom": "messages",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "messages_folder_id_folders_id_fk": {+ "name": "messages_folder_id_folders_id_fk",+ "tableFrom": "messages",+ "tableTo": "folders",+ "columnsFrom": [+ "folder_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mfa_recovery_codes": {+ "name": "mfa_recovery_codes",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "code_hash": {+ "name": "code_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "used_at": {+ "name": "used_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "mfa_recovery_codes_user_idx": {+ "name": "mfa_recovery_codes_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "mfa_recovery_codes_user_id_users_id_fk": {+ "name": "mfa_recovery_codes_user_id_users_id_fk",+ "tableFrom": "mfa_recovery_codes",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "mfa_recovery_codes_code_hash_unique": {+ "name": "mfa_recovery_codes_code_hash_unique",+ "nullsNotDistinct": false,+ "columns": [+ "code_hash"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.outbound_jobs": {+ "name": "outbound_jobs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "outbound_jobs_user_idx": {+ "name": "outbound_jobs_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "outbound_jobs_message_idx": {+ "name": "outbound_jobs_message_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "outbound_jobs_user_id_users_id_fk": {+ "name": "outbound_jobs_user_id_users_id_fk",+ "tableFrom": "outbound_jobs",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "outbound_jobs_message_id_messages_id_fk": {+ "name": "outbound_jobs_message_id_messages_id_fk",+ "tableFrom": "outbound_jobs",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.password_reset_tokens": {+ "name": "password_reset_tokens",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "used_at": {+ "name": "used_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "password_reset_tokens_user_idx": {+ "name": "password_reset_tokens_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "password_reset_tokens_user_id_users_id_fk": {+ "name": "password_reset_tokens_user_id_users_id_fk",+ "tableFrom": "password_reset_tokens",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "password_reset_tokens_token_hash_unique": {+ "name": "password_reset_tokens_token_hash_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token_hash"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.push_devices": {+ "name": "push_devices",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "api_key_id": {+ "name": "api_key_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "platform": {+ "name": "platform",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "environment": {+ "name": "environment",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'production'"+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "public_key": {+ "name": "public_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "previews": {+ "name": "previews",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "client_ref": {+ "name": "client_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "push_devices_platform_token_user_idx": {+ "name": "push_devices_platform_token_user_idx",+ "columns": [+ {+ "expression": "platform",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "token",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "push_devices_user_idx": {+ "name": "push_devices_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "push_devices_api_key_idx": {+ "name": "push_devices_api_key_idx",+ "columns": [+ {+ "expression": "api_key_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "push_devices_user_id_users_id_fk": {+ "name": "push_devices_user_id_users_id_fk",+ "tableFrom": "push_devices",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "push_devices_api_key_id_api_keys_id_fk": {+ "name": "push_devices_api_key_id_api_keys_id_fk",+ "tableFrom": "push_devices",+ "tableTo": "api_keys",+ "columnsFrom": [+ "api_key_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.push_subscriptions": {+ "name": "push_subscriptions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint": {+ "name": "endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "p256dh": {+ "name": "p256dh",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth": {+ "name": "auth",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "push_subscriptions_endpoint_idx": {+ "name": "push_subscriptions_endpoint_idx",+ "columns": [+ {+ "expression": "endpoint",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "push_subscriptions_user_idx": {+ "name": "push_subscriptions_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "push_subscriptions_session_idx": {+ "name": "push_subscriptions_session_idx",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "push_subscriptions_user_id_users_id_fk": {+ "name": "push_subscriptions_user_id_users_id_fk",+ "tableFrom": "push_subscriptions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "push_subscriptions_session_id_sessions_id_fk": {+ "name": "push_subscriptions_session_id_sessions_id_fk",+ "tableFrom": "push_subscriptions",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.routing_rules": {+ "name": "routing_rules",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain_id": {+ "name": "domain_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'mailbox'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "pattern": {+ "name": "pattern",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "match_field": {+ "name": "match_field",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'email'"+ },+ "match_operator": {+ "name": "match_operator",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'contains'"+ },+ "match_value": {+ "name": "match_value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "folder_id": {+ "name": "folder_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'store'"+ },+ "forward_to": {+ "name": "forward_to",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "keep_copy": {+ "name": "keep_copy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "reject_reason": {+ "name": "reject_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_matched_at": {+ "name": "last_matched_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "match_count": {+ "name": "match_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "routing_rules_domain_scope_idx": {+ "name": "routing_rules_domain_scope_idx",+ "columns": [+ {+ "expression": "domain_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "enabled",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routing_rules_mailbox_idx": {+ "name": "routing_rules_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routing_rules_priority_idx": {+ "name": "routing_rules_priority_idx",+ "columns": [+ {+ "expression": "priority",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routing_rules_user_idx": {+ "name": "routing_rules_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routing_rules_folder_idx": {+ "name": "routing_rules_folder_idx",+ "columns": [+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "routing_rules_user_id_users_id_fk": {+ "name": "routing_rules_user_id_users_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "routing_rules_domain_id_domains_id_fk": {+ "name": "routing_rules_domain_id_domains_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "domains",+ "columnsFrom": [+ "domain_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "routing_rules_mailbox_id_mailboxes_id_fk": {+ "name": "routing_rules_mailbox_id_mailboxes_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "routing_rules_folder_id_folders_id_fk": {+ "name": "routing_rules_folder_id_folders_id_fk",+ "tableFrom": "routing_rules",+ "tableTo": "folders",+ "columnsFrom": [+ "folder_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.sessions": {+ "name": "sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "sessions_user_idx": {+ "name": "sessions_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "sessions_user_id_users_id_fk": {+ "name": "sessions_user_id_users_id_fk",+ "tableFrom": "sessions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "sessions_token_hash_unique": {+ "name": "sessions_token_hash_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token_hash"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.shared_attachment_links": {+ "name": "shared_attachment_links",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "shared_attachment_links_attachment_id_message_attachments_id_fk": {+ "name": "shared_attachment_links_attachment_id_message_attachments_id_fk",+ "tableFrom": "shared_attachment_links",+ "tableTo": "message_attachments",+ "columnsFrom": [+ "attachment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "shared_attachment_links_attachment_id_unique": {+ "name": "shared_attachment_links_attachment_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "attachment_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.spam_feedback": {+ "name": "spam_feedback",+ "schema": "",+ "columns": {+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "classification": {+ "name": "classification",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "training_tokens": {+ "name": "training_tokens",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reputation_keys": {+ "name": "reputation_keys",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tokenizer_version": {+ "name": "tokenizer_version",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "spam_feedback_mailbox_idx": {+ "name": "spam_feedback_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "spam_feedback_actor_user_idx": {+ "name": "spam_feedback_actor_user_idx",+ "columns": [+ {+ "expression": "actor_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "spam_feedback_message_id_messages_id_fk": {+ "name": "spam_feedback_message_id_messages_id_fk",+ "tableFrom": "spam_feedback",+ "tableTo": "messages",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "spam_feedback_mailbox_id_mailboxes_id_fk": {+ "name": "spam_feedback_mailbox_id_mailboxes_id_fk",+ "tableFrom": "spam_feedback",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "spam_feedback_actor_user_id_users_id_fk": {+ "name": "spam_feedback_actor_user_id_users_id_fk",+ "tableFrom": "spam_feedback",+ "tableTo": "users",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.spam_reputation": {+ "name": "spam_reputation",+ "schema": "",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "messages_seen": {+ "name": "messages_seen",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "spam_count": {+ "name": "spam_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "ham_count": {+ "name": "ham_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "spam_reputation_mailbox_type_key_idx": {+ "name": "spam_reputation_mailbox_type_key_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "spam_reputation_mailbox_idx": {+ "name": "spam_reputation_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "spam_reputation_mailbox_id_mailboxes_id_fk": {+ "name": "spam_reputation_mailbox_id_mailboxes_id_fk",+ "tableFrom": "spam_reputation",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.spam_token_stats": {+ "name": "spam_token_stats",+ "schema": "",+ "columns": {+ "mailbox_id": {+ "name": "mailbox_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "spam_count": {+ "name": "spam_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "ham_count": {+ "name": "ham_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "spam_token_stats_mailbox_token_idx": {+ "name": "spam_token_stats_mailbox_token_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "token",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "spam_token_stats_mailbox_idx": {+ "name": "spam_token_stats_mailbox_idx",+ "columns": [+ {+ "expression": "mailbox_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "spam_token_stats_mailbox_id_mailboxes_id_fk": {+ "name": "spam_token_stats_mailbox_id_mailboxes_id_fk",+ "tableFrom": "spam_token_stats",+ "tableTo": "mailboxes",+ "columnsFrom": [+ "mailbox_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_compose_preferences": {+ "name": "user_compose_preferences",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "track_opens_default": {+ "name": "track_opens_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "undo_send_seconds": {+ "name": "undo_send_seconds",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 15+ },+ "updated_at": {+ "name": "updated_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_compose_preferences_user_id_users_id_fk": {+ "name": "user_compose_preferences_user_id_users_id_fk",+ "tableFrom": "user_compose_preferences",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.users": {+ "name": "users",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reset_email": {+ "name": "reset_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "forwarding_email": {+ "name": "forwarding_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password_hash": {+ "name": "password_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "booking_username": {+ "name": "booking_username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "time_zone": {+ "name": "time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "avatar_key": {+ "name": "avatar_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'user'"+ },+ "is_primary_admin": {+ "name": "is_primary_admin",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "can_manage_mailboxes": {+ "name": "can_manage_mailboxes",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "can_manage_domains": {+ "name": "can_manage_domains",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "can_manage_users": {+ "name": "can_manage_users",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "keyboard_shortcuts_enabled": {+ "name": "keyboard_shortcuts_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "spam_protection_enabled": {+ "name": "spam_protection_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "trash_retention_days": {+ "name": "trash_retention_days",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "show_full_recipient_addresses": {+ "name": "show_full_recipient_addresses",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "remote_content_mode": {+ "name": "remote_content_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'allow'"+ },+ "totp_secret": {+ "name": "totp_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "totp_enabled": {+ "name": "totp_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "totp_confirmed_at": {+ "name": "totp_confirmed_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "last_sign_in_at": {+ "name": "last_sign_in_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "users_booking_username_idx": {+ "name": "users_booking_username_idx",+ "columns": [+ {+ "expression": "booking_username",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "users_created_by_idx": {+ "name": "users_created_by_idx",+ "columns": [+ {+ "expression": "created_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "users_created_by_user_id_users_id_fk": {+ "name": "users_created_by_user_id_users_id_fk",+ "tableFrom": "users",+ "tableTo": "users",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "users_email_unique": {+ "name": "users_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhook_deliveries": {+ "name": "webhook_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "response_status": {+ "name": "response_status",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "next_retry_at": {+ "name": "next_retry_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "webhook_deliveries_webhook_idx": {+ "name": "webhook_deliveries_webhook_idx",+ "columns": [+ {+ "expression": "webhook_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "webhook_deliveries_status_idx": {+ "name": "webhook_deliveries_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhook_deliveries_webhook_id_webhooks_id_fk": {+ "name": "webhook_deliveries_webhook_id_webhooks_id_fk",+ "tableFrom": "webhook_deliveries",+ "tableTo": "webhooks",+ "columnsFrom": [+ "webhook_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhooks": {+ "name": "webhooks",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "events": {+ "name": "events",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "max_attempts": {+ "name": "max_attempts",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 5+ },+ "created_at": {+ "name": "created_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "webhooks_user_idx": {+ "name": "webhooks_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhooks_user_id_users_id_fk": {+ "name": "webhooks_user_id_users_id_fk",+ "tableFrom": "webhooks",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/drizzle/migrations-pg/meta/_journal.json b/drizzle/migrations-pg/meta/_journal.jsonnew file mode 100644index 0000000..87ac2e4--- /dev/null+++ b/drizzle/migrations-pg/meta/_journal.json@@ -0,0 +1,20 @@+{+ "version": "7",+ "dialect": "postgresql",+ "entries": [+ {+ "idx": 0,+ "version": "7",+ "when": 1792869762877,+ "tag": "0000_baseline",+ "breakpoints": true+ },+ {+ "idx": 1,+ "version": "7",+ "when": 1792869763877,+ "tag": "0001_triggers_and_seeds",+ "breakpoints": true+ }+ ]+}diff --git a/env.d.ts b/env.d.tsindex 9ab2dc9..aa7667b 100644--- a/env.d.ts+++ b/env.d.ts@@ -1,5 +1,13 @@interface CloudflareEnv {DB: D1Database;+ /** Connection string for an external database (PostgreSQL, MySQL, libSQL, ...); unset keeps D1. See docs/databases.md. */+ DATABASE_URL?: string;+ /** Driver override when it cannot be inferred from DATABASE_URL (neon, postgres-js, pglite, planetscale, ...). */+ DATABASE_DRIVER?: string;+ /** Auth token for libSQL / Turso. */+ DATABASE_AUTH_TOKEN?: string;+ /** Hyperdrive binding, used as the connection string when DATABASE_URL is unset. */+ HYPERDRIVE?: { connectionString: string };EMAIL: SendEmail;BUCKET: R2Bucket;INBOUND_QUEUE: Queue<import("./src/lib/email/inbound").InboundQueueMessage>;diff --git a/package-lock.json b/package-lock.jsonindex eec4d69..4b003d4 100644--- a/package-lock.json+++ b/package-lock.json@@ -11,7 +11,10 @@"dependencies": {"@ai-sdk/openai-compatible": "^3.0.55","@ai-sdk/react": "^4.0.116",+ "@libsql/client": "^0.18.0","@modelcontextprotocol/server": "^2.1.0",+ "@neondatabase/serverless": "^1.2.0",+ "@planetscale/database": "^2.0.0","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-dropdown-menu": "^2.1.16","@radix-ui/react-label": "^2.1.8",@@ -33,12 +36,15 @@"drizzle-orm": "^0.45.2","lucide-react": "^1.16.0","mimetext": "^3.0.28",+ "mysql2": "^3.24.6","nanoid": "^5.1.16","next": "16.3.3","nodemailer": "^10.0.9","parse-srcset": "^1.0.2","parse5": "^8.0.1",+ "pg": "^8.23.1","postal-mime": "^2.7.4",+ "postgres": "^3.4.9","qrcode": "^1.5.4","react": "^19.2.6","react-dom": "^19.2.6",@@ -56,6 +62,7 @@"devDependencies": {"@cloudflare/vite-plugin": "^1.61.0","@cloudflare/workers-types": "^5.20260828.1",+ "@electric-sql/pglite-socket": "^0.2.14","@next/eslint-plugin-next": "16.3.3","@tailwindcss/postcss": "^4","@types/bcryptjs": "^2.4.6",@@ -63,6 +70,7 @@"@types/css-tree": "^3.2.0","@types/node": "^20.19.41","@types/nodemailer": "^8.0.1",+ "@types/pg": "^8.23.1","@types/qrcode": "^1.5.6","@types/react": "^19.1.7","@types/react-dom": "^19.1.7",@@ -83,6 +91,9 @@"vite": "npm:@voidzero-dev/[email protected]","vite-plus": "1.0.0","wrangler": "^4.127.1"+ },+ "optionalDependencies": {+ "@electric-sql/pglite": "^0.5.11"}},"node_modules/@ai-sdk/gateway": {@@ -585,7 +596,6 @@"cpu": ["x64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -602,7 +612,6 @@"cpu": ["arm64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -619,7 +628,6 @@"cpu": ["x64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -636,7 +644,6 @@"cpu": ["arm64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -653,7 +660,6 @@"cpu": ["x64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -850,6 +856,110 @@"dev": true,"license": "Apache-2.0"},+ "node_modules/@electric-sql/pglite": {+ "version": "0.5.11",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.5.11.tgz",+ "integrity": "sha512-SWuqsTjA4DDWqgZ05PC1RJaq8e00p5KACxbqaikDFQ8dIGA0SLRzuPniky7IW+q/c5RDNMdEXwv7mFBWIx9Hxw==",+ "devOptional": true,+ "license": "Apache-2.0"+ },+ "node_modules/@electric-sql/pglite-age": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-age/-/pglite-age-0.0.12.tgz",+ "integrity": "sha512-h3w0ZbR/thNxbRiHrakK5XOJE5bbyIGT0mknREwiE2ELCLAEVv10x3jhnIkXTU5YJ5WzTZj2NbrFcAl/iHj3XQ==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11"+ }+ },+ "node_modules/@electric-sql/pglite-pg_hashids": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-pg_hashids/-/pglite-pg_hashids-0.0.12.tgz",+ "integrity": "sha512-2vXH899hpmiKMhI1NvR9wxfyyW2SyvAMlBOwm8t02BRMpHIkXtl++fsBUTibL0TzTMAVLRFts53czelLPN0rDw==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11"+ }+ },+ "node_modules/@electric-sql/pglite-pg_ivm": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-pg_ivm/-/pglite-pg_ivm-0.0.12.tgz",+ "integrity": "sha512-I+WQ0Hb7u7ZxMmznazZ15C0T6c4OKRuKVc5LaKkPNU+Cv7/aZmqRfPOHVu4MY65HC65dU3YmxT0A+tdWHcUF8w==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11"+ }+ },+ "node_modules/@electric-sql/pglite-pg_textsearch": {+ "version": "0.0.13",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-pg_textsearch/-/pglite-pg_textsearch-0.0.13.tgz",+ "integrity": "sha512-TQX6Opop6fRkfgbZcuUDZ4UYm7x07uQ5JznVJWG9QL3H3hx3qQ1CbqG6eSHzVEjGxxFqoH+2UJs0l/XR/Y3esA==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11"+ }+ },+ "node_modules/@electric-sql/pglite-pg_uuidv7": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-pg_uuidv7/-/pglite-pg_uuidv7-0.0.12.tgz",+ "integrity": "sha512-Q+JvI5fSE0bws+qNa9hzoZEqhGFql/LjTZ5Fq1ojKx2hd99RNkLRcpDUNjqeyluCpZS5Aq/PsLjb5JBUevkXGw==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11"+ }+ },+ "node_modules/@electric-sql/pglite-pgtap": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-pgtap/-/pglite-pgtap-0.0.12.tgz",+ "integrity": "sha512-qp8jE4sx+fNoCkcyd/cL8od+Nir4hFVphSh4/vH7P3cFCH6/sayWjQas9OyzPL0JHe7XQRFquyOvgwtUzbJgXQ==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11"+ }+ },+ "node_modules/@electric-sql/pglite-pgvector": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-pgvector/-/pglite-pgvector-0.0.12.tgz",+ "integrity": "sha512-n3TJqjWI9FXwFrGhuTVMghef8SL3E6nb4lxZnxYFW3UTg/7/hMUWfz7v2y0+idWzEsQ/raRpMNCsw9zvSdC/SA==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11"+ }+ },+ "node_modules/@electric-sql/pglite-socket": {+ "version": "0.2.14",+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite-socket/-/pglite-socket-0.2.14.tgz",+ "integrity": "sha512-n7JO9FzxQHdF5oBKzovf/LuRUrEUpOgGP/tmfxmOB5lqWPySTKkCb6FBkzj7kztWGJu9eB0FoilqxvOJ+9+0fQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "pglite-server": "dist/scripts/server.js"+ },+ "peerDependencies": {+ "@electric-sql/pglite": "0.5.11",+ "@electric-sql/pglite-age": "0.0.12",+ "@electric-sql/pglite-pg_hashids": "0.0.12",+ "@electric-sql/pglite-pg_ivm": "0.0.12",+ "@electric-sql/pglite-pg_textsearch": "0.0.13",+ "@electric-sql/pglite-pg_uuidv7": "0.0.12",+ "@electric-sql/pglite-pgtap": "0.0.12",+ "@electric-sql/pglite-pgvector": "0.0.12"+ }+ },"node_modules/@emnapi/core": {"version": "1.10.0","resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",@@ -2619,6 +2729,165 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@libsql/client": {+ "version": "0.18.0",+ "resolved": "https://registry.npmjs.org/@libsql/client/-/client-0.18.0.tgz",+ "integrity": "sha512-zMCCo58vv7w27j7+cnt/GW+X6/Rih6cHZ86PKi0AxCMOqMfrVgG9OZ5lW2bDMJhSeOjsv2szH2nJF3A9l36UmA==",+ "license": "MIT",+ "dependencies": {+ "@libsql/core": "^0.18.0",+ "@libsql/hrana-client": "^0.10.0",+ "js-base64": "^3.7.5",+ "libsql": "^0.5.28",+ "promise-limit": "^2.7.0"+ }+ },+ "node_modules/@libsql/core": {+ "version": "0.18.0",+ "resolved": "https://registry.npmjs.org/@libsql/core/-/core-0.18.0.tgz",+ "integrity": "sha512-N8RR2CIpcgtbKZnXs2KVpw2lJQfinUj3I56e7qRDRpK18Hty0Rr8nr00VmFb4R/DsqOanPB/TaP3+QAQLZeXMg==",+ "license": "MIT",+ "dependencies": {+ "js-base64": "^3.7.5"+ }+ },+ "node_modules/@libsql/darwin-arm64": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/darwin-arm64/-/darwin-arm64-0.5.29.tgz",+ "integrity": "sha512-K+2RIB1OGFPYQbfay48GakLhqf3ArcbHqPFu7EZiaUcRgFcdw8RoltsMyvbj5ix2fY0HV3Q3Ioa/ByvQdaSM0A==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@libsql/darwin-x64": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/darwin-x64/-/darwin-x64-0.5.29.tgz",+ "integrity": "sha512-OtT+KFHsKFy1R5FVadr8FJ2Bb1mghtXTyJkxv0trocq7NuHntSki1eUbxpO5ezJesDvBlqFjnWaYYY516QNLhQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@libsql/hrana-client": {+ "version": "0.10.0",+ "resolved": "https://registry.npmjs.org/@libsql/hrana-client/-/hrana-client-0.10.0.tgz",+ "integrity": "sha512-OoA4EMqRAC7kn7V2P6EQqRcpZf2W+AjsNIyCizBg339Tq/aMC7sRnzs3SklderhmQWAqEzvv8A2vhxVmWpkVvw==",+ "license": "MIT",+ "dependencies": {+ "@libsql/isomorphic-ws": "^0.1.5",+ "js-base64": "^3.7.5"+ }+ },+ "node_modules/@libsql/isomorphic-ws": {+ "version": "0.1.5",+ "resolved": "https://registry.npmjs.org/@libsql/isomorphic-ws/-/isomorphic-ws-0.1.5.tgz",+ "integrity": "sha512-DtLWIH29onUYR00i0GlQ3UdcTRC6EP4u9w/h9LxpUZJWRMARk6dQwZ6Jkd+QdwVpuAOrdxt18v0K2uIYR3fwFg==",+ "license": "MIT",+ "dependencies": {+ "@types/ws": "^8.5.4",+ "ws": "^8.13.0"+ }+ },+ "node_modules/@libsql/linux-arm-gnueabihf": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/linux-arm-gnueabihf/-/linux-arm-gnueabihf-0.5.29.tgz",+ "integrity": "sha512-CD4n4zj7SJTHso4nf5cuMoWoMSS7asn5hHygsDuhRl8jjjCTT3yE+xdUvI4J7zsyb53VO5ISh4cwwOtf6k2UhQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@libsql/linux-arm-musleabihf": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/linux-arm-musleabihf/-/linux-arm-musleabihf-0.5.29.tgz",+ "integrity": "sha512-2Z9qBVpEJV7OeflzIR3+l5yAd4uTOLxklScYTwpZnkm2vDSGlC1PRlueLaufc4EFITkLKXK2MWBpexuNJfMVcg==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@libsql/linux-arm64-gnu": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/linux-arm64-gnu/-/linux-arm64-gnu-0.5.29.tgz",+ "integrity": "sha512-gURBqaiXIGGwFNEaUj8Ldk7Hps4STtG+31aEidCk5evMMdtsdfL3HPCpvys+ZF/tkOs2MWlRWoSq7SOuCE9k3w==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@libsql/linux-arm64-musl": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/linux-arm64-musl/-/linux-arm64-musl-0.5.29.tgz",+ "integrity": "sha512-fwgYZ0H8mUkyVqXZHF3mT/92iIh1N94Owi/f66cPVNsk9BdGKq5gVpoKO+7UxaNzuEH1roJp2QEwsCZMvBLpqg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@libsql/linux-x64-gnu": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/linux-x64-gnu/-/linux-x64-gnu-0.5.29.tgz",+ "integrity": "sha512-y14V0vY0nmMC6G0pHeJcEarcnGU2H6cm21ZceRkacWHvQAEhAG0latQkCtoS2njFOXiYIg+JYPfAoWKbi82rkg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@libsql/linux-x64-musl": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/linux-x64-musl/-/linux-x64-musl-0.5.29.tgz",+ "integrity": "sha512-gquqwA/39tH4pFl+J9n3SOMSymjX+6kZ3kWgY3b94nXFTwac9bnFNMffIomgvlFaC4ArVqMnOZD3nuJ3H3VO1w==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@libsql/win32-x64-msvc": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/@libsql/win32-x64-msvc/-/win32-x64-msvc-0.5.29.tgz",+ "integrity": "sha512-4/0CvEdhi6+KjMxMaVbFM2n2Z44escBRoEYpR+gZg64DdetzGnYm8mcNLcoySaDJZNaBd6wz5DNdgRmcI4hXcg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },"node_modules/@modelcontextprotocol/core": {"version": "2.1.0","resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.1.0.tgz",@@ -2666,6 +2935,21 @@"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4"}},+ "node_modules/@neon-rs/load": {+ "version": "0.0.4",+ "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.4.tgz",+ "integrity": "sha512-kTPhdZyTQxB+2wpiRcFWrDcejc4JI6tkPuS7UZCG4l6Zvc5kU/gGQ/ozvHTh1XR5tS+UlfAfGuPajjzQjCiHCw==",+ "license": "MIT"+ },+ "node_modules/@neondatabase/serverless": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@neondatabase/serverless/-/serverless-1.2.0.tgz",+ "integrity": "sha512-tnaqgixUengZQNd9ZrS3ytQfamJzLKY8QxgqWQTNHHtB+KrFQWk77JTbbpg4RD+J3qE4eO2lVytvGDX5Kj6FdQ==",+ "license": "MIT",+ "engines": {+ "node": ">=19.0.0"+ }+ },"node_modules/@next/env": {"version": "16.3.3","resolved": "https://registry.npmjs.org/@next/env/-/env-16.3.3.tgz",@@ -3889,6 +4173,15 @@"license": "MIT","optional": true},+ "node_modules/@planetscale/database": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@planetscale/database/-/database-2.0.0.tgz",+ "integrity": "sha512-4owd8kDhcpTFWOB1bSviUdlY5cf9T4QKLQbawQd0IUOc16UQXlIhE/ELGZ/FRjvVzXYAB/Ls4rfhlaW1DxJaEQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22"+ }+ },"node_modules/@polka/url": {"version": "1.0.0-next.29","resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",@@ -5269,6 +5562,18 @@"@types/node": "*"}},+ "node_modules/@types/pg": {+ "version": "8.23.1",+ "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz",+ "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==",+ "devOptional": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "pg-protocol": "*",+ "pg-types": "^2.2.0"+ }+ },"node_modules/@types/qrcode": {"version": "1.5.6","resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",@@ -5318,6 +5623,15 @@"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==","license": "MIT"},+ "node_modules/@types/ws": {+ "version": "8.18.2",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",+ "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@typescript-eslint/eslint-plugin": {"version": "8.59.4","resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.4.tgz",@@ -6842,6 +7156,15 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/aws-ssl-profiles": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",+ "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",+ "license": "MIT",+ "engines": {+ "node": ">= 6.0.0"+ }+ },"node_modules/bail": {"version": "2.0.2","resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",@@ -9052,6 +9375,15 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/generate-function": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",+ "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",+ "license": "MIT",+ "dependencies": {+ "is-property": "^1.0.2"+ }+ },"node_modules/generator-function": {"version": "2.0.1","resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz",@@ -9420,6 +9752,22 @@"url": "https://opencollective.com/unified"}},+ "node_modules/iconv-lite": {+ "version": "0.7.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/ignore": {"version": "5.3.2","resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",@@ -9806,6 +10154,12 @@"dev": true,"license": "MIT"},+ "node_modules/is-property": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",+ "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",+ "license": "MIT"+ },"node_modules/is-regex": {"version": "1.2.1","resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",@@ -10210,6 +10564,47 @@"node": ">= 0.8.0"}},+ "node_modules/libsql": {+ "version": "0.5.29",+ "resolved": "https://registry.npmjs.org/libsql/-/libsql-0.5.29.tgz",+ "integrity": "sha512-8lMP8iMgiBzzoNbAPQ59qdVcj6UaE/Vnm+fiwX4doX4Narook0a4GPKWBEv+CR8a1OwbfkgL18uBfBjWdF0Fzg==",+ "cpu": [+ "x64",+ "arm64",+ "wasm32",+ "arm"+ ],+ "license": "MIT",+ "os": [+ "darwin",+ "linux",+ "win32"+ ],+ "dependencies": {+ "@neon-rs/load": "^0.0.4",+ "detect-libc": "2.0.2"+ },+ "optionalDependencies": {+ "@libsql/darwin-arm64": "0.5.29",+ "@libsql/darwin-x64": "0.5.29",+ "@libsql/linux-arm-gnueabihf": "0.5.29",+ "@libsql/linux-arm-musleabihf": "0.5.29",+ "@libsql/linux-arm64-gnu": "0.5.29",+ "@libsql/linux-arm64-musl": "0.5.29",+ "@libsql/linux-x64-gnu": "0.5.29",+ "@libsql/linux-x64-musl": "0.5.29",+ "@libsql/win32-x64-msvc": "0.5.29"+ }+ },+ "node_modules/libsql/node_modules/detect-libc": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz",+ "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/lightningcss": {"version": "1.32.0","resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",@@ -10504,6 +10899,12 @@"dev": true,"license": "MIT"},+ "node_modules/long": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",+ "license": "Apache-2.0"+ },"node_modules/longest-streak": {"version": "3.1.0","resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",@@ -10537,6 +10938,21 @@"yallist": "^3.0.2"}},+ "node_modules/lru.min": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz",+ "integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==",+ "license": "MIT",+ "engines": {+ "bun": ">=1.0.0",+ "deno": ">=1.30.0",+ "node": ">=8.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wellwelwel"+ }+ },"node_modules/lucide-react": {"version": "1.16.0","license": "ISC",@@ -11547,7 +11963,6 @@"cpu": ["arm64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11570,7 +11985,6 @@"cpu": ["x64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11590,7 +12004,6 @@"version": "0.35.4","resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.4.tgz","integrity": "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==",- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11613,7 +12026,6 @@"cpu": ["arm64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11630,7 +12042,6 @@"cpu": ["x64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11647,7 +12058,6 @@"cpu": ["arm"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11664,7 +12074,6 @@"cpu": ["arm64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11681,7 +12090,6 @@"cpu": ["ppc64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11698,7 +12106,6 @@"cpu": ["riscv64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11715,7 +12122,6 @@"cpu": ["s390x"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11732,7 +12138,6 @@"cpu": ["x64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11749,7 +12154,6 @@"cpu": ["arm64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11766,7 +12170,6 @@"cpu": ["x64"],- "dev": true,"license": "LGPL-3.0-or-later","optional": true,"os": [@@ -11783,7 +12186,6 @@"cpu": ["arm"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11806,7 +12208,6 @@"cpu": ["arm64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11829,7 +12230,6 @@"cpu": ["ppc64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11852,7 +12252,6 @@"cpu": ["riscv64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11875,7 +12274,6 @@"cpu": ["s390x"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11898,7 +12296,6 @@"cpu": ["x64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11921,7 +12318,6 @@"cpu": ["arm64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11944,7 +12340,6 @@"cpu": ["x64"],- "dev": true,"license": "Apache-2.0","optional": true,"os": [@@ -11964,7 +12359,6 @@"version": "0.35.4","resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.4.tgz","integrity": "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==",- "dev": true,"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,"dependencies": {@@ -11984,7 +12378,6 @@"cpu": ["wasm32"],- "dev": true,"license": "Apache-2.0","optional": true,"dependencies": {@@ -12004,7 +12397,6 @@"cpu": ["arm64"],- "dev": true,"license": "Apache-2.0 AND LGPL-3.0-or-later","optional": true,"os": [@@ -12024,7 +12416,6 @@"cpu": ["ia32"],- "dev": true,"license": "Apache-2.0 AND LGPL-3.0-or-later","optional": true,"os": [@@ -12044,7 +12435,6 @@"cpu": ["x64"],- "dev": true,"license": "Apache-2.0 AND LGPL-3.0-or-later","optional": true,"os": [@@ -12248,6 +12638,39 @@"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},+ "node_modules/mysql2": {+ "version": "3.24.6",+ "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz",+ "integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==",+ "license": "MIT",+ "dependencies": {+ "aws-ssl-profiles": "^1.1.2",+ "generate-function": "^2.3.1",+ "iconv-lite": "^0.7.3",+ "long": "^5.3.2",+ "lru.min": "^1.1.4",+ "named-placeholders": "^1.1.6",+ "sql-escaper": "^1.5.1"+ },+ "engines": {+ "node": ">= 8.0"+ },+ "peerDependencies": {+ "@types/node": ">= 8"+ }+ },+ "node_modules/named-placeholders": {+ "version": "1.1.6",+ "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz",+ "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==",+ "license": "MIT",+ "dependencies": {+ "lru.min": "^1.1.0"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },"node_modules/nanoid": {"version": "5.1.16","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",@@ -12700,6 +13123,95 @@"devOptional": true,"license": "MIT"},+ "node_modules/pg": {+ "version": "8.23.1",+ "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",+ "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",+ "license": "MIT",+ "dependencies": {+ "pg-connection-string": "^2.14.1",+ "pg-pool": "^3.14.0",+ "pg-protocol": "^1.16.1",+ "pg-types": "2.2.0",+ "pgpass": "1.0.5"+ },+ "engines": {+ "node": ">= 16.0.0"+ },+ "optionalDependencies": {+ "pg-cloudflare": "^1.4.1"+ },+ "peerDependencies": {+ "pg-native": ">=3.0.1"+ },+ "peerDependenciesMeta": {+ "pg-native": {+ "optional": true+ }+ }+ },+ "node_modules/pg-cloudflare": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",+ "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/pg-connection-string": {+ "version": "2.14.1",+ "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",+ "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",+ "license": "MIT"+ },+ "node_modules/pg-int8": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",+ "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",+ "license": "ISC",+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/pg-pool": {+ "version": "3.14.0",+ "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",+ "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",+ "license": "MIT",+ "peerDependencies": {+ "pg": ">=8.0"+ }+ },+ "node_modules/pg-protocol": {+ "version": "1.16.1",+ "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",+ "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",+ "license": "MIT"+ },+ "node_modules/pg-types": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",+ "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",+ "license": "MIT",+ "dependencies": {+ "pg-int8": "1.0.1",+ "postgres-array": "~2.0.0",+ "postgres-bytea": "~1.0.0",+ "postgres-date": "~1.0.4",+ "postgres-interval": "^1.1.0"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/pgpass": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",+ "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",+ "license": "MIT",+ "dependencies": {+ "split2": "^4.1.0"+ }+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",@@ -12801,6 +13313,58 @@"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"}},+ "node_modules/postgres": {+ "version": "3.4.9",+ "resolved": "https://registry.npmjs.org/postgres/-/postgres-3.4.9.tgz",+ "integrity": "sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw==",+ "license": "Unlicense",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/porsager"+ }+ },+ "node_modules/postgres-array": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",+ "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/postgres-bytea": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",+ "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/postgres-date": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",+ "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/postgres-interval": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",+ "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",+ "license": "MIT",+ "dependencies": {+ "xtend": "^4.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/prelude-ls": {"version": "1.2.1","resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",@@ -12833,6 +13397,12 @@"dev": true,"license": "MIT"},+ "node_modules/promise-limit": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/promise-limit/-/promise-limit-2.7.0.tgz",+ "integrity": "sha512-7nJ6v5lnJsXwGprnGXga4wx6d1POjvi5Qmf1ivTRxTjH4Z/9Czja/UCMLVmB9N93GeWOU93XaFaEt6jbuoagNw==",+ "license": "ISC"+ },"node_modules/prop-types": {"version": "15.8.1","resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",@@ -13511,6 +14081,12 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },"node_modules/sass": {"version": "1.105.0","resolved": "https://registry.npmjs.org/sass/-/sass-1.105.0.tgz",@@ -13926,6 +14502,30 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/split2": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",+ "license": "ISC",+ "engines": {+ "node": ">= 10.x"+ }+ },+ "node_modules/sql-escaper": {+ "version": "1.5.2",+ "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.2.tgz",+ "integrity": "sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==",+ "license": "MIT",+ "engines": {+ "bun": ">=1.0.0",+ "deno": ">=2.0.0",+ "node": ">=12.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/mysqljs/sql-escaper?sponsor=1"+ }+ },"node_modules/srvx": {"version": "0.12.8","resolved": "https://registry.npmjs.org/srvx/-/srvx-0.12.8.tgz",@@ -15070,18 +15670,6 @@}}},- "node_modules/vite-plus/node_modules/@types/node": {- "version": "26.6.5",- "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",- "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",- "dev": true,- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "undici-types": "~8.9.0"- }- },"node_modules/vite-plus/node_modules/@vitest/browser": {"version": "5.0.1","resolved": "https://registry.npmjs.org/@vitest/browser/-/browser-5.0.1.tgz",@@ -15287,15 +15875,6 @@"node": ">=14.19.0"}},- "node_modules/vite-plus/node_modules/undici-types": {- "version": "8.9.0",- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",- "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",- "dev": true,- "license": "MIT",- "optional": true,- "peer": true- },"node_modules/vite-plus/node_modules/vitest": {"version": "5.0.1","resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.1.tgz",@@ -16041,7 +16620,6 @@"cpu": ["ppc64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16058,7 +16636,6 @@"cpu": ["arm"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16075,7 +16652,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16092,7 +16668,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16109,7 +16684,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16126,7 +16700,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16143,7 +16716,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16160,7 +16732,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16177,7 +16748,6 @@"cpu": ["arm"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16194,7 +16764,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16211,7 +16780,6 @@"cpu": ["ia32"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16228,7 +16796,6 @@"cpu": ["loong64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16245,7 +16812,6 @@"cpu": ["mips64el"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16262,7 +16828,6 @@"cpu": ["ppc64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16279,7 +16844,6 @@"cpu": ["riscv64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16296,7 +16860,6 @@"cpu": ["s390x"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16313,7 +16876,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16330,7 +16892,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16347,7 +16908,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16364,7 +16924,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16381,7 +16940,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16398,7 +16956,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16415,7 +16972,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16432,7 +16988,6 @@"cpu": ["arm64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16449,7 +17004,6 @@"cpu": ["ia32"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16466,7 +17020,6 @@"cpu": ["x64"],- "dev": true,"license": "MIT","optional": true,"os": [@@ -16522,7 +17075,6 @@"version": "8.21.0","resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz","integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",- "devOptional": true,"license": "MIT","engines": {"node": ">=10.0.0"@@ -16557,6 +17109,15 @@"dev": true,"license": "MIT"},+ "node_modules/xtend": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4"+ }+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",diff --git a/package.json b/package.jsonindex ba6d74f..97f5ee1 100644--- a/package.json+++ b/package.json@@ -17,6 +17,9 @@"push:keys": "node scripts/generate-vapid-keys.mjs","db:bundle": "node scripts/generate-migration-bundle.mjs","db:generate": "drizzle-kit generate",+ "db:generate:pg": "MAILFLARE_DB_DIALECT=postgres drizzle-kit generate --config=drizzle.config.pg.ts",+ "db:generate:mysql": "MAILFLARE_DB_DIALECT=mysql drizzle-kit generate --config=drizzle.config.mysql.ts",+ "db:smoke": "node scripts/run-ts.mjs scripts/db-smoke.ts","db:migrate:local": "wrangler d1 migrations apply DB --local","db:migrate:remote": "wrangler d1 migrations apply DB --remote","migrate": "wrangler d1 migrations apply DB",@@ -60,7 +63,10 @@"dependencies": {"@ai-sdk/openai-compatible": "^3.0.55","@ai-sdk/react": "^4.0.116",+ "@libsql/client": "^0.18.0","@modelcontextprotocol/server": "^2.1.0",+ "@neondatabase/serverless": "^1.2.0",+ "@planetscale/database": "^2.0.0","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-dropdown-menu": "^2.1.16","@radix-ui/react-label": "^2.1.8",@@ -82,12 +88,15 @@"drizzle-orm": "^0.45.2","lucide-react": "^1.16.0","mimetext": "^3.0.28",+ "mysql2": "^3.24.6","nanoid": "^5.1.16","next": "16.3.3","nodemailer": "^10.0.9","parse-srcset": "^1.0.2","parse5": "^8.0.1",+ "pg": "^8.23.1","postal-mime": "^2.7.4",+ "postgres": "^3.4.9","qrcode": "^1.5.4","react": "^19.2.6","react-dom": "^19.2.6",@@ -105,6 +114,7 @@"devDependencies": {"@cloudflare/vite-plugin": "^1.61.0","@cloudflare/workers-types": "^5.20260828.1",+ "@electric-sql/pglite-socket": "^0.2.14","@next/eslint-plugin-next": "16.3.3","@tailwindcss/postcss": "^4","@typescript-eslint/eslint-plugin": "8.59.4",@@ -114,6 +124,7 @@"@types/css-tree": "^3.2.0","@types/node": "^20.19.41","@types/nodemailer": "^8.0.1",+ "@types/pg": "^8.23.1","@types/qrcode": "^1.5.6","@types/react": "^19.1.7","@types/react-dom": "^19.1.7",@@ -139,5 +150,8 @@},"vite": "npm:@voidzero-dev/[email protected]"},- "type": "module"+ "type": "module",+ "optionalDependencies": {+ "@electric-sql/pglite": "^0.5.11"+ }}diff --git a/scripts/build-server.mjs b/scripts/build-server.mjsindex d5d3085..8359f9c 100644--- a/scripts/build-server.mjs+++ b/scripts/build-server.mjs@@ -12,7 +12,11 @@ await build({target: "node22",sourcemap: true,tsconfig: "tsconfig.json",- external: ["next", "better-sqlite3", "nodemailer", "smtp-server", "ws", "react", "react-dom"],+ external: [+ "next", "better-sqlite3", "nodemailer", "smtp-server", "ws", "react", "react-dom",+ // Database drivers, loaded only when DATABASE_URL selects them.+ "pg", "postgres", "mysql2", "@libsql/client", "@neondatabase/serverless", "@planetscale/database", "@electric-sql/pglite",+ ],alias: { "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" },banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },define: { "process.env.MAILFLARE_RUNTIME": '"node"' },diff --git a/scripts/db-smoke.ts b/scripts/db-smoke.tsnew file mode 100644index 0000000..3f7834e--- /dev/null+++ b/scripts/db-smoke.ts@@ -0,0 +1,139 @@+/**+ * Exercises the database layer against any DATABASE_URL: migrations, the query shapes the app relies on+ * (insert/select/update, returning, onConflict*, raw sql, batch), the triggers and search.+ * Run with `npm run db:smoke -- <DATABASE_URL> [driver]`; PGlite needs no server (`pglite://memory`).+ */+import { and, eq, sql } from "drizzle-orm";+import { createDb } from "@/db";+import { users, domains, mailboxes, messages, folders, jmapChanges, appSettings, webhooks, spamTokenStats, spamReputation } from "@/db/schema";+import { getDatabaseConfig } from "@/db/with-database";+import { openExternalDatabase } from "@/db/external";+import { applyPendingMigrations, getMigrationStatus } from "@/lib/migrations/service";+import { buildSearchConditions } from "@/lib/search/conditions";+import { createBookedCalendarEvents } from "@/lib/booking/create";+import { exportDatabaseRecords, restoreDatabaseRecords } from "@/lib/backups/export";+import { getSearchIndexStatus } from "@/lib/search/index-admin";+import { recordReputationObservation } from "@/lib/spam/repository";+import { isUniqueConstraintError } from "@/lib/database-errors";++const [url, driver] = process.argv.slice(2);+if (!url) throw new Error("usage: db-smoke <DATABASE_URL> [driver]");++const checks: Array<[string, boolean]> = [];+const check = (name: string, ok: boolean) => {+ checks.push([name, ok]);+ console.log(`${ok ? "ok " : "FAIL"} ${name}`);+};++const config = getDatabaseConfig({ DATABASE_URL: url, DATABASE_DRIVER: driver } as never);+const external = openExternalDatabase(config, true);+const d1 = external as unknown as D1Database;+console.log(`dialect=${config.dialect} driver=${config.driver}`);++const applied = await applyPendingMigrations(d1);+check("migrations apply", applied.ready && applied.applied.length > 0);+check("migrations idempotent", (await applyPendingMigrations(d1)).applied.length === 0 && (await getMigrationStatus(d1)).ready);++const db = createDb(d1);+const stamp = Date.now();+const userId = `usr_${stamp}`;+await db.insert(users).values({ id: userId, email: `a${stamp}@example.com`, passwordHash: "x", name: "A" });+const [user] = await db.select().from(users).where(eq(users.id, userId));+check("insert + select", user?.email === `a${stamp}@example.com` && user.createdAt instanceof Date && user.disabled === false);+check("timestamp is a recent Date", Math.abs(user.createdAt.getTime() - Date.now()) < 60_000);++await db.insert(domains).values({ id: `dom_${stamp}`, userId, hostname: `${stamp}.example.com`, zoneId: "z" });+await db.insert(mailboxes).values({ id: `mbx_${stamp}`, userId, domainId: `dom_${stamp}`, localPart: "me" });+await db.insert(messages).values({ id: `msg_${stamp}`, userId, mailboxId: `mbx_${stamp}`, direction: "inbound", fromAddr: "[email protected]", toAddr: "[email protected]", subject: "Quarterly Report", textBody: "numbers inside", status: "received" } as never);+const changes = await db.select().from(jmapChanges).where(eq(jmapChanges.mailboxId, `mbx_${stamp}`));+check("trigger wrote jmap_changes", changes.length >= 1 && changes[0].change === "created");+const revisions = await db.all<{ revision: number }>(sql`SELECT revision FROM jmap_mailbox_revisions WHERE mailbox_id = ${`mbx_${stamp}`}`);+check("trigger bumped jmap revision", Number(revisions[0]?.revision) >= 1);++await db.update(messages).set({ status: "trash" }).where(eq(messages.id, `msg_${stamp}`));+const [trashed] = await db.select({ trashedAt: messages.trashedAt, status: messages.status }).from(messages).where(eq(messages.id, `msg_${stamp}`));+check("trigger set trashed_at", trashed.status === "trash" && trashed.trashedAt instanceof Date);+await db.update(messages).set({ status: "received" }).where(eq(messages.id, `msg_${stamp}`));+const [restored] = await db.select({ trashedAt: messages.trashedAt }).from(messages).where(eq(messages.id, `msg_${stamp}`));+check("trigger cleared trashed_at", restored.trashedAt === null);++const claimed = await db.update(messages).set({ starred: true }).where(and(eq(messages.id, `msg_${stamp}`), eq(messages.starred, false))).returning({ id: messages.id });+check("update returning (claim)", claimed.length === 1 && claimed[0].id === `msg_${stamp}`);+const lost = await db.update(messages).set({ starred: true }).where(and(eq(messages.id, `msg_${stamp}`), eq(messages.starred, false))).returning({ id: messages.id });+check("update returning (lost claim)", lost.length === 0);++const inserted = await db.insert(folders).values({ id: `fld_${stamp}`, userId, mailboxId: `mbx_${stamp}`, name: "F" } as never).onConflictDoNothing().returning({ id: folders.id });+check("insert onConflictDoNothing returning", inserted.length === 1);+const duplicate = await db.insert(folders).values({ id: `fld_${stamp}`, userId, mailboxId: `mbx_${stamp}`, name: "F" } as never).onConflictDoNothing().returning({ id: folders.id });+check("insert onConflictDoNothing (duplicate)", duplicate.length === 0);++await db.insert(spamTokenStats).values({ mailboxId: `mbx_${stamp}`, token: "t", spamCount: 1, hamCount: 0, updatedAt: new Date() } as never)+ .onConflictDoUpdate({ target: [spamTokenStats.mailboxId, spamTokenStats.token], set: { spamCount: sql`${spamTokenStats.spamCount} + 1` } });+await db.insert(spamTokenStats).values({ mailboxId: `mbx_${stamp}`, token: "t", spamCount: 1, hamCount: 0, updatedAt: new Date() } as never)+ .onConflictDoUpdate({ target: [spamTokenStats.mailboxId, spamTokenStats.token], set: { spamCount: sql`${spamTokenStats.spamCount} + 1` } });+const [stat] = await db.select().from(spamTokenStats).where(eq(spamTokenStats.mailboxId, `mbx_${stamp}`));+check("upsert increments", stat?.spamCount === 2);++const [{ n }] = await db.all<{ n: number }>(sql`SELECT count(*) AS n FROM messages WHERE mailbox_id = ${`mbx_${stamp}`}`);+check("raw sql all()", Number(n) === 1);+const run = await db.run(sql`UPDATE messages SET starred = ${false} WHERE id = ${`msg_${stamp}`}`);+check("raw sql run() reports changes", (run as { meta: { changes: number } }).meta.changes === 1);++await db.batch([+ db.update(messages).set({ subject: "batched" }).where(eq(messages.id, `msg_${stamp}`)),+ db.insert(webhooks).values({ id: `wh_${stamp}`, userId, url: "https://example.com", secret: "s", events: "[]" } as never),+] as never);+const [batched] = await db.select({ subject: messages.subject }).from(messages).where(eq(messages.id, `msg_${stamp}`));+check("batch", batched.subject === "batched");++const prepared = await d1.prepare("SELECT count(*) AS n FROM messages WHERE mailbox_id = ?").bind(`mbx_${stamp}`).first<{ n: number }>();+check("D1-compatible prepare().bind().first()", Number(prepared?.n) === 1);+const batchResults = await d1.batch([d1.prepare("SELECT 1 AS one"), d1.prepare("SELECT 2 AS two")]);+check("D1-compatible batch()", batchResults.length === 2);++await db.update(messages).set({ subject: "Quarterly Report" }).where(eq(messages.id, `msg_${stamp}`));+for (const [query, expected] of [["quarterly", 1], ["subject:report", 1], ["from:[email protected] numbers", 1], ["absent-term", 0], ["-quarterly", 0]] as const) {+ const found = await db.select({ id: messages.id }).from(messages).where(and(eq(messages.mailboxId, `mbx_${stamp}`), ...buildSearchConditions(query)));+ check(`search "${query}"`, found.length === expected);+}++const env = { DB: d1 } as unknown as CloudflareEnv;+const event = { hostIds: [userId], name: "Intro", location: "Zoom", color: "blue", timeZone: "UTC" } as never;+const startsAt = new Date(Date.now() + 86_400_000).toISOString();+const endsAt = new Date(Date.now() + 86_400_000 + 1_800_000).toISOString();+check("booking inserts", (await createBookedCalendarEvents(env, event, "Guest", "[email protected]", startsAt, endsAt)) === true);+check("booking refuses a busy slot", (await createBookedCalendarEvents(env, event, "Guest", "[email protected]", startsAt, endsAt)) === false);++await recordReputationObservation(env, `mbx_${stamp}`, [{ type: "domain", key: "example.com" }, { type: "email", key: "[email protected]" }] as never);+await recordReputationObservation(env, `mbx_${stamp}`, [{ type: "domain", key: "example.com" }] as never);+const reputation = await db.select().from(spamReputation).where(and(eq(spamReputation.mailboxId, `mbx_${stamp}`), eq(spamReputation.key, "example.com")));+check("spam reputation upsert", reputation[0]?.messagesSeen === 2);++try {+ await db.insert(users).values({ id: `usr2_${stamp}`, email: `a${stamp}@example.com`, passwordHash: "x", name: "B" });+ check("unique violation throws", false);+} catch (error) {+ check("unique violation is recognised", isUniqueConstraintError(error));+}++const searchStatus = await getSearchIndexStatus(env);+check("search index status", searchStatus.messages === searchStatus.indexed && searchStatus.messages >= 1);++const backup = await exportDatabaseRecords(d1);+const exported = JSON.parse(new TextDecoder().decode(backup)) as { tables: Record<string, Array<Record<string, unknown>>> };+check("backup exports portable values", exported.tables.users.every((row) => typeof row.disabled === "number") && exported.tables.messages.length >= 1);+await restoreDatabaseRecords(d1, backup.buffer.slice(backup.byteOffset, backup.byteOffset + backup.byteLength) as ArrayBuffer);+const [afterRestore] = await db.select({ subject: messages.subject, starred: messages.starred, createdAt: messages.createdAt }).from(messages).where(eq(messages.id, `msg_${stamp}`));+check("backup restores", afterRestore?.subject === "Quarterly Report" && afterRestore.starred === false && afterRestore.createdAt instanceof Date);++const [settings] = await db.select().from(appSettings).where(eq(appSettings.id, "default"));+check("seed rows present", settings?.appName === "Mailflare");++await db.delete(users).where(eq(users.id, userId));+const remaining = await db.all<{ n: number }>(sql`SELECT count(*) AS n FROM messages WHERE user_id = ${userId}`);+check("cascade delete", Number(remaining[0].n) === 0);++await external.sqlExecutor.close?.();+const failed = checks.filter(([, ok]) => !ok);+console.log(failed.length ? `\n${failed.length} FAILED` : `\nall ${checks.length} checks passed`);+process.exit(failed.length ? 1 : 0);diff --git a/scripts/generate-migration-bundle.mjs b/scripts/generate-migration-bundle.mjsindex e4fbfaf..db5cebb 100644--- a/scripts/generate-migration-bundle.mjs+++ b/scripts/generate-migration-bundle.mjs@@ -1,8 +1,6 @@import { readFileSync, readdirSync, writeFileSync } from "node:fs";const root = new URL("../", import.meta.url);-const migrationsDirectory = new URL("drizzle/migrations/", root);-const output = new URL("src/lib/migrations/bundle.json", root);function splitSql(sql) {const tokens = sql.match(/--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|[A-Za-z_]+|;|[^\S\n]+|\n|./g) ?? [];@@ -34,12 +32,29 @@ function splitSql(sql) {return statements;}-const migrations = readdirSync(migrationsDirectory)- .filter((name) => name.endsWith(".sql"))- .sort()- .map((name) => ({- name,- statements: splitSql(readFileSync(new URL(name, migrationsDirectory), "utf8")),- }));+function readMigrations(directory, split) {+ return readdirSync(directory)+ .filter((name) => name.endsWith(".sql"))+ .sort()+ .map((name) => ({ name, statements: split(readFileSync(new URL(name, directory), "utf8")) }));+}++// PostgreSQL function bodies and MySQL trigger bodies contain semicolons, so those migrations are split only+// on the explicit breakpoint markers drizzle-kit writes (and the hand-written files copy).+function splitOnBreakpoints(sql) {+ return sql+ .split(/-->\s*statement-breakpoint/g)+ .map((statement) => statement.replace(/^\s*--[^\n]*$/gm, "").trim())+ .filter(Boolean);+}-writeFileSync(output, `${JSON.stringify({ migrations }, null, 2)}\n`);+const bundles = [+ { file: "bundle.json", directory: "drizzle/migrations/", split: splitSql },+ { file: "bundle-postgres.json", directory: "drizzle/migrations-pg/", split: splitOnBreakpoints },+ { file: "bundle-mysql.json", directory: "drizzle/migrations-mysql/", split: splitOnBreakpoints },+];++for (const { file, directory, split } of bundles) {+ const migrations = readMigrations(new URL(directory, root), split);+ writeFileSync(new URL(`src/lib/migrations/${file}`, root), `${JSON.stringify({ migrations }, null, 2)}\n`);+}diff --git a/scripts/run-ts.mjs b/scripts/run-ts.mjsnew file mode 100644index 0000000..780414e--- /dev/null+++ b/scripts/run-ts.mjs@@ -0,0 +1,27 @@+// Bundle a TypeScript script (resolving the `@/` alias) with esbuild and run it under Node.+// Usage: node scripts/run-ts.mjs scripts/db-smoke.ts [args...]+import { spawnSync } from "node:child_process";+import { mkdirSync } from "node:fs";+import { basename, resolve } from "node:path";+import { build } from "esbuild";++const [entry, ...args] = process.argv.slice(2);+if (!entry) throw new Error("usage: run-ts.mjs <script.ts> [args...]");+const root = resolve(import.meta.dirname, "..");+const outDir = resolve(root, "node_modules/.cache/run-ts");+mkdirSync(outDir, { recursive: true });+const outfile = resolve(outDir, `${basename(entry).replace(/\.ts$/, "")}.mjs`);++await build({+ entryPoints: [resolve(root, entry)],+ outfile,+ bundle: true,+ platform: "node",+ format: "esm",+ packages: "external",+ alias: { "@": resolve(root, "src") },+ logLevel: "error",+ define: { "import.meta.dirname": "undefined" },+});+const result = spawnSync(process.execPath, [outfile, ...args], { stdio: "inherit", cwd: root, env: process.env });+process.exit(result.status ?? 1);diff --git a/server/index.ts b/server/index.tsindex 00cb0e8..97a9fff 100644--- a/server/index.ts+++ b/server/index.ts@@ -10,6 +10,7 @@ import { processAgentDraftJob } from "@/lib/agent/jobs/utils";import { processOutboundQueue, type OutboundQueueMessage } from "@/lib/email/send";import { processWebhookRetry, type WebhookRetryMessage } from "@/lib/email/webhooks";import { processImportJob } from "@/lib/import/jobs";+import { applyPendingMigrations } from "@/lib/migrations/service";import { isImportJobMessage, isInboundQueueMessage, isWebhookRetryMessage } from "../worker-utils";import { createNodeRuntime } from "./runtime/env";import { applyMigrations } from "./runtime/migrate";@@ -29,7 +30,9 @@ async function main() {const { env } = runtime;globalThis.__mailflareNodeEnv = env;- const migrated = await applyMigrations(runtime.database, resolve(process.env.MIGRATIONS_DIR ?? join(process.cwd(), "drizzle", "migrations")));+ const migrated = runtime.database+ ? await applyMigrations(runtime.database, resolve(process.env.MIGRATIONS_DIR ?? join(process.cwd(), "drizzle", "migrations")))+ : (await applyPendingMigrations(env.DB)).applied;if (migrated.length) console.log(`Applied ${migrated.length} migration(s): ${migrated.join(", ")}`);runtime.inboundQueue.setConsumer(async (body) => {diff --git a/server/runtime/env.ts b/server/runtime/env.tsindex 93a6b79..529d068 100644--- a/server/runtime/env.ts+++ b/server/runtime/env.ts@@ -1,5 +1,6 @@import { mkdirSync } from "node:fs";import { join, resolve } from "node:path";+import { getDatabaseConfig, withDatabase } from "@/db/with-database";import { withStorage } from "@/lib/storage";import { openFileBucket } from "./file-bucket";import { openMailer, type Mailer, type MailerConfig } from "./mailer";@@ -32,7 +33,8 @@ export function createNodeRuntime(): NodeRuntime {const dataDir = resolve(optional("DATA_DIR") ?? "./data");mkdirSync(join(dataDir, "blobs"), { recursive: true });- const database = openSqliteDatabase(join(dataDir, "mailflare.sqlite"));+ // DATABASE_URL moves the data to PostgreSQL, MySQL or libSQL; otherwise it lives in a local SQLite file.+ const database = getDatabaseConfig({}).driver === "d1" ? openSqliteDatabase(join(dataDir, "mailflare.sqlite")) : undefined;const bucket = openFileBucket(join(dataDir, "blobs"));const mailer = openMailer(mailerConfig());const inboundQueue = openQueue("mailflare-inbound");@@ -81,13 +83,13 @@ export function createNodeRuntime(): NodeRuntime {VAPID_PRIVATE_KEY: optional("VAPID_PRIVATE_KEY"),VAPID_SUBJECT: optional("VAPID_SUBJECT"),} as unknown as CloudflareEnv;- const storageEnv = withStorage(env);+ const storageEnv = withDatabase(withStorage(env));realtime.bindEnv(storageEnv);return {env: storageEnv,dataDir,- database: database as unknown as SqliteDatabase,+ database: database as unknown as SqliteDatabase | undefined,mailer: mailer as unknown as Mailer,inboundQueue: inboundQueue as unknown as InProcessQueue,outboundQueue: outboundQueue as unknown as InProcessQueue,diff --git a/server/runtime/types.d.ts b/server/runtime/types.d.tsindex b094086..0bd3404 100644--- a/server/runtime/types.d.ts+++ b/server/runtime/types.d.ts@@ -6,7 +6,8 @@ import type { SqliteDatabase } from "./sqlite-database";export type NodeRuntime = {env: CloudflareEnv;dataDir: string;- database: SqliteDatabase;+ /** The local SQLite file; absent when DATABASE_URL selects an external database. */+ database?: SqliteDatabase;mailer: Mailer;inboundQueue: InProcessQueue;outboundQueue: InProcessQueue;diff --git a/src/app/api/accounts/create.ts b/src/app/api/accounts/create.tsindex 6569cd2..7666eb8 100644--- a/src/app/api/accounts/create.ts+++ b/src/app/api/accounts/create.ts@@ -1,4 +1,5 @@import { eq, inArray } from "drizzle-orm";+import { isUniqueConstraintError } from "@/lib/database-errors";import { NextResponse } from "next/server";import { getDb } from "@/db";import { domains, mailboxAliases, mailboxes, users } from "@/db/schema";@@ -82,8 +83,7 @@ export async function createAccountResponse(env: CloudflareEnv, adminUserId: strif (cleanup.some((result) => result.status === "rejected")) {return NextResponse.json({ error: "Account creation failed and cleanup could not finish. Check the account and Cloudflare routing before retrying." }, { status: 502 });}- const cause = error instanceof Error ? error.cause : null;- if (/UNIQUE constraint failed/i.test(`${error} ${cause}`)) {+ if (isUniqueConstraintError(error)) {return NextResponse.json({ error: "An email address is already assigned" }, { status: 409 });}return NextResponse.json({ error: "Failed to create account mailbox routing. Please try again." }, { status: 502 });diff --git a/src/app/api/admin/ai-usage/utils.ts b/src/app/api/admin/ai-usage/utils.tsindex d222aa6..ead05a4 100644--- a/src/app/api/admin/ai-usage/utils.ts+++ b/src/app/api/admin/ai-usage/utils.ts@@ -33,7 +33,7 @@ export async function GET(request: Request) {requests: sql<number>`count(*)`,inputTokens: sql<number>`coalesce(sum(${aiUsage.inputTokens}), 0)`,outputTokens: sql<number>`coalesce(sum(${aiUsage.outputTokens}), 0)`,- }).from(aiUsage).where(and(gte(aiUsage.createdAt, days[0].start), lt(aiUsage.createdAt, days[days.length - 1].end))).groupBy(sql`"date"`).orderBy(sql`"date"`);+ }).from(aiUsage).where(and(gte(aiUsage.createdAt, days[0].start), lt(aiUsage.createdAt, days[days.length - 1].end))).groupBy(sql`1`).orderBy(sql`1`);const byDate = new Map(dailyRows.map((row) => [row.date, row]));const daily = days.map(({ date }) => byDate.get(date) ?? { date, requests: 0, inputTokens: 0, outputTokens: 0 });const rows = await db.select().from(aiUsage).orderBy(desc(aiUsage.createdAt), desc(aiUsage.id)).limit(PAGE_SIZE).offset((page - 1) * PAGE_SIZE);diff --git a/src/app/api/audit-logs/route.ts b/src/app/api/audit-logs/route.tsindex e86adf6..d0199da 100644--- a/src/app/api/audit-logs/route.ts+++ b/src/app/api/audit-logs/route.ts@@ -1,5 +1,4 @@-import { desc, eq, inArray } from "drizzle-orm";-import { alias } from "drizzle-orm/sqlite-core";+import { aliasedTable, desc, eq, inArray } from "drizzle-orm";import { NextResponse } from "next/server";import { getDb } from "@/db";import { auditLogs, domains, mailboxes, users } from "@/db/schema";@@ -19,7 +18,7 @@ export async function GET(request: Request) {const url = new URL(request.url);const limit = Math.min(Number(url.searchParams.get("limit") ?? 100), 200);const db = getDb(env);- const targetUsers = alias(users, "target_users");+ const targetUsers = aliasedTable(users, "target_users");const rows = await db.select({id: auditLogs.id,diff --git a/src/app/api/booking/[eventId]/route.ts b/src/app/api/booking/[eventId]/route.tsindex f32dc12..45cf5de 100644--- a/src/app/api/booking/[eventId]/route.ts+++ b/src/app/api/booking/[eventId]/route.ts@@ -1,4 +1,5 @@import { and, eq } from "drizzle-orm";+import { isUniqueConstraintError } from "@/lib/database-errors";import { NextResponse } from "next/server";import { getDb } from "@/db";import { bookingEvents } from "@/db/schema";@@ -28,7 +29,7 @@ export async function PATCH(request: Request, { params }: BookingEventRouteConteconst [event] = await db.update(bookingEvents).set({ ...input, hostIds: JSON.stringify(hostIds), weekdays: JSON.stringify(input.weekdays), timeRanges: JSON.stringify(input.timeRanges), updatedAt: new Date() }).where(and(eq(bookingEvents.id, eventId), eq(bookingEvents.userId, user.id))).returning();return event ? NextResponse.json({ event }) : NextResponse.json({ error: "Booking event not found" }, { status: 404 });} catch (error) {- if (error instanceof Error && /UNIQUE constraint failed|booking_events_user_slug_idx/i.test(error.message)) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });+ if (isUniqueConstraintError(error)) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });throw error;}}diff --git a/src/app/api/booking/route.ts b/src/app/api/booking/route.tsindex 91e5a67..99aa90f 100644--- a/src/app/api/booking/route.ts+++ b/src/app/api/booking/route.ts@@ -1,4 +1,5 @@import { and, eq } from "drizzle-orm";+import { isUniqueConstraintError } from "@/lib/database-errors";import { NextResponse } from "next/server";import { getDb } from "@/db";import { bookingEvents, users } from "@/db/schema";@@ -40,7 +41,7 @@ export async function POST(request: Request) {const [event] = await db.insert(bookingEvents).values({ ...input, id: newId("book"), userId: user.id, hostIds: JSON.stringify(hostIds), weekdays: JSON.stringify(input.weekdays), timeRanges: JSON.stringify(input.timeRanges) }).returning();return NextResponse.json({ event });} catch (error) {- if (error instanceof Error && /UNIQUE constraint failed|booking_events_user_slug_idx/i.test(error.message)) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });+ if (isUniqueConstraintError(error)) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });throw error;}}diff --git a/src/app/api/booking/settings/route.ts b/src/app/api/booking/settings/route.tsindex acbdb46..d96f42c 100644--- a/src/app/api/booking/settings/route.ts+++ b/src/app/api/booking/settings/route.ts@@ -1,4 +1,5 @@import { eq } from "drizzle-orm";+import { isUniqueConstraintError } from "@/lib/database-errors";import { NextResponse } from "next/server";import { getDb } from "@/db";import { users } from "@/db/schema";@@ -24,7 +25,7 @@ export async function PATCH(request: Request) {await db.update(users).set({ bookingUsername: username }).where(eq(users.id, user.id));return NextResponse.json({ username });} catch (error) {- if (error instanceof Error && /UNIQUE constraint failed|users_booking_username_idx/i.test(error.message)) return NextResponse.json({ error: "This username is already taken." }, { status: 409 });+ if (isUniqueConstraintError(error)) return NextResponse.json({ error: "This username is already taken." }, { status: 409 });throw error;}}diff --git a/src/app/api/drive/items/route.ts b/src/app/api/drive/items/route.tsindex 9ce4a73..e089aa1 100644--- a/src/app/api/drive/items/route.ts+++ b/src/app/api/drive/items/route.ts@@ -9,6 +9,7 @@ import { driveTypesCondition, parseDriveCategories } from "@/lib/drive/categorieimport { listDriveAttachments } from "@/lib/drive/attachments";import { getDriveStorageLimit, getDriveStorageUsed } from "@/lib/drive/storage";import type { DriveRole } from "@/lib/drive/types";+import { escapeLike } from "@/db/sql";export async function GET(request: Request) {const auth = await authorizeDrive(request);@@ -62,7 +63,7 @@ export async function GET(request: Request) {return respond(await toDriveItemDtos(db, await withoutTrashedAncestors(db, rows), user.id), { role: "owner" });}const conditions = [eq(driveItems.ownerId, user.id), isNull(driveItems.trashedAt), isNull(driveItems.uploadId)];- if (query) conditions.push(sql`${driveItems.name} like ${`%${query.replace(/[\\%_]/g, "\\$&")}%`} escape '\\'`);+ if (query) conditions.push(sql`${driveItems.name} like ${`%${escapeLike(query)}%`} escape '!'`);else conditions.push(isNull(driveItems.parentId));if (typeFilter) conditions.push(typeFilter);const rows = await db.select().from(driveItems).where(and(...conditions)).orderBy(desc(driveItems.updatedAt)).limit(query ? 200 : 1000);diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.tsindex 85cbad6..812a781 100644--- a/src/app/api/messages/route.ts+++ b/src/app/api/messages/route.ts@@ -167,7 +167,7 @@ export async function GET(request: Request) {.select({threadId: messages.threadId,total: count(),- unread: sum(sql`case when ${messages.read} = 0 then 1 else 0 end`),+ unread: sum(sql`case when ${messages.read} then 0 else 1 end`),}).from(messages).where(and(scope, inArray(messages.threadId, threadIds), isNotNull(messages.threadId), notInArray(messages.status, ["draft", "trash"])))diff --git a/src/db/compat.ts b/src/db/compat.tsnew file mode 100644index 0000000..3780619--- /dev/null+++ b/src/db/compat.ts@@ -0,0 +1,268 @@+import { getTableColumns, inArray, sql, type SQL } from "drizzle-orm";+import type { DatabaseDialect } from "./dialect";+import type { RowMode, SqlExecutor } from "./drivers/types";++/**+ * The app is written against drizzle's SQLite API: `db.run/all/get/batch`, `onConflictDo*` and+ * `returning`. This wraps a PostgreSQL or MySQL drizzle instance so those calls keep working:+ *+ * - `run`, `all`, `get` run raw `sql` through the executor (PostgreSQL and MySQL have no such methods).+ * - `batch` runs the statements in order inside one transaction when the driver can hold one.+ * - MySQL has no `ON CONFLICT` or `RETURNING`; insert/update/delete are shimmed to ON DUPLICATE KEY+ * UPDATE and a select-by-primary-key after the write.+ */+export interface ExecutorContext {+ base: SqlExecutor;+ /** Set while a batch runs so every statement lands on the batch's connection. */+ tx: SqlExecutor | null;+}++export const currentExecutor = (ctx: ExecutorContext) => ctx.tx ?? ctx.base;++interface DrizzleLike {+ dialect: { sqlToQuery(query: SQL): { sql: string; params: unknown[] } };+ [key: string]: unknown;+}++export interface RunResult {+ success: true;+ results: unknown[];+ meta: { changes: number; last_row_id: number; rows_written: number; changed_db: boolean };+}++async function runRaw(db: DrizzleLike, ctx: ExecutorContext, query: SQL, mode: RowMode) {+ const { sql: text, params } = db.dialect.sqlToQuery(query);+ return currentExecutor(ctx).query(text, params, mode);+}++export function wrapDatabase<T extends object>(db: T, dialect: DatabaseDialect, ctx: ExecutorContext): T {+ const raw = db as unknown as DrizzleLike;++ const batch = async (queries: PromiseLike<unknown>[]) => {+ const runAll = async () => {+ const results: unknown[] = [];+ for (const query of queries) results.push(await query);+ return results;+ };+ const { base } = ctx;+ if (!base.transaction || ctx.tx) return runAll();+ return base.transaction(async (tx) => {+ ctx.tx = tx;+ try {+ return await runAll();+ } finally {+ ctx.tx = null;+ }+ });+ };++ const overrides: Record<string, unknown> = {+ async all(query: SQL) {+ return (await runRaw(raw, ctx, query, "object")).rows;+ },+ async get(query: SQL) {+ return (await runRaw(raw, ctx, query, "object")).rows[0];+ },+ async values(query: SQL) {+ return (await runRaw(raw, ctx, query, "array")).rows;+ },+ async run(query: SQL): Promise<RunResult> {+ const result = await runRaw(raw, ctx, query, "object");+ return {+ success: true,+ results: result.rows,+ meta: { changes: result.affectedRows, last_row_id: result.insertId ?? 0, rows_written: result.affectedRows, changed_db: result.affectedRows > 0 },+ };+ },+ batch,+ };++ if (dialect === "mysql") {+ overrides.insert = (table: AnyTable) => new MysqlInsertShim(raw as unknown as MysqlDb, table);+ overrides.update = (table: AnyTable) => new MysqlUpdateShim(raw as unknown as MysqlDb, table);+ overrides.delete = (table: AnyTable) => new MysqlDeleteShim(raw as unknown as MysqlDb, table);+ }++ return new Proxy(db, {+ get(target, property) {+ if (typeof property === "string" && property in overrides) return overrides[property];+ const value = Reflect.get(target, property, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+}++// ---- MySQL shims ----++type AnyTable = Parameters<typeof getTableColumns>[0];+type Row = Record<string, unknown>;+type MysqlDb = DrizzleLike & {+ insert(table: AnyTable): { values(values: unknown): { onDuplicateKeyUpdate(config: { set: Row }): PromiseLike<unknown> } & PromiseLike<unknown> };+ update(table: AnyTable): { set(values: unknown): { where(condition?: SQL): PromiseLike<unknown> } & PromiseLike<unknown> };+ delete(table: AnyTable): { where(condition?: SQL): PromiseLike<unknown> } & PromiseLike<unknown>;+ select(fields?: unknown): { from(table: AnyTable): { where(condition?: SQL): PromiseLike<Row[]> } & PromiseLike<Row[]> };+};++function affectedRows(result: unknown): number {+ const header = Array.isArray(result) ? result[0] : result;+ return Number((header as { affectedRows?: number } | undefined)?.affectedRows ?? 0);+}++function insertId(result: unknown): number {+ const header = Array.isArray(result) ? result[0] : result;+ return Number((header as { insertId?: number } | undefined)?.insertId ?? 0);+}++function primaryKey(table: AnyTable) {+ const columns = Object.values(getTableColumns(table)) as Array<{ primary: boolean; name: string; autoIncrement?: boolean }>;+ const key = columns.find((column) => column.primary);+ if (!key) throw new Error("Emulating RETURNING on MySQL needs a single-column primary key.");+ const entry = Object.entries(getTableColumns(table)).find(([, column]) => column === (key as unknown));+ return { column: key as never, property: entry?.[0] ?? "id", autoIncrement: !!key.autoIncrement };+}++async function selectByKeys(db: MysqlDb, table: AnyTable, fields: unknown, keys: unknown[]): Promise<Row[]> {+ if (keys.length === 0) return [];+ const { column } = primaryKey(table);+ const query = fields ? db.select(fields) : db.select();+ return query.from(table).where(inArray(column, keys as never));+}++class MysqlInsertShim implements PromiseLike<unknown> {+ private rows: Row[] = [];+ private conflict: { set?: Row } | null = null;+ private returningFields: unknown;+ private wantsReturning = false;++ constructor(+ private readonly db: MysqlDb,+ private readonly table: AnyTable,+ ) {}++ values(values: Row | Row[]) {+ this.rows = Array.isArray(values) ? values : [values];+ return this;+ }++ onConflictDoNothing() {+ this.conflict = {};+ return this;+ }++ onConflictDoUpdate(config: { set: Row }) {+ this.conflict = { set: config.set };+ return this;+ }++ returning(fields?: unknown) {+ this.wantsReturning = true;+ this.returningFields = fields;+ return this;+ }++ private async execute() {+ const statement = this.db.insert(this.table).values(this.rows.length === 1 ? this.rows[0] : this.rows);+ const key = this.wantsReturning ? primaryKey(this.table) : null;+ // ON DUPLICATE KEY UPDATE reports a rewritten row and a no-op the same way, so which keys already+ // existed is read first; only the others can have been inserted.+ const existing = key && this.conflict && !this.conflict.set ? new Set((await selectByKeys(this.db, this.table, { key: key.column }, this.keysOf(key, null))).map((row) => row.key)) : new Set<unknown>();+ let result: unknown;+ if (this.conflict) {+ // Assigning a column to itself is the "do nothing" form of ON DUPLICATE KEY UPDATE.+ const [property, column] = Object.entries(getTableColumns(this.table))[0];+ result = await statement.onDuplicateKeyUpdate({ set: this.conflict.set ?? { [property]: sql`${column}` } });+ } else {+ result = await statement;+ }+ if (!key) return result;+ const keys = this.keysOf(key, result).filter((value) => !existing.has(value));+ return selectByKeys(this.db, this.table, this.returningFields, keys);+ }++ private keysOf(key: ReturnType<typeof primaryKey>, result: unknown): unknown[] {+ if (key.autoIncrement && result) return this.rows.map((_, i) => insertId(result) + i);+ return this.rows.map((row) => row[key.property]).filter((value) => value !== undefined);+ }++ then<R1 = unknown, R2 = never>(onfulfilled?: ((value: unknown) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null) {+ return this.execute().then(onfulfilled, onrejected);+ }+}++class MysqlUpdateShim implements PromiseLike<unknown> {+ private values: Row = {};+ private condition?: SQL;+ private returningFields: unknown;+ private wantsReturning = false;++ constructor(+ private readonly db: MysqlDb,+ private readonly table: AnyTable,+ ) {}++ set(values: Row) {+ this.values = values;+ return this;+ }++ where(condition?: SQL) {+ this.condition = condition;+ return this;+ }++ returning(fields?: unknown) {+ this.wantsReturning = true;+ this.returningFields = fields;+ return this;+ }++ private async execute() {+ const { column } = primaryKey(this.table);+ // Rows are identified before the write, because the write may change the columns the condition reads.+ const before = this.wantsReturning ? await this.db.select({ key: column }).from(this.table).where(this.condition) : [];+ const result = await this.db.update(this.table).set(this.values).where(this.condition);+ if (!this.wantsReturning) return result;+ // A claim (`UPDATE ... WHERE status = 'pending'`) loses the race when the write matched nothing.+ if (affectedRows(result) === 0) return [];+ return selectByKeys(this.db, this.table, this.returningFields, before.map((row) => row.key));+ }++ then<R1 = unknown, R2 = never>(onfulfilled?: ((value: unknown) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null) {+ return this.execute().then(onfulfilled, onrejected);+ }+}++class MysqlDeleteShim implements PromiseLike<unknown> {+ private condition?: SQL;+ private returningFields: unknown;+ private wantsReturning = false;++ constructor(+ private readonly db: MysqlDb,+ private readonly table: AnyTable,+ ) {}++ where(condition?: SQL) {+ this.condition = condition;+ return this;+ }++ returning(fields?: unknown) {+ this.wantsReturning = true;+ this.returningFields = fields;+ return this;+ }++ private async execute() {+ if (!this.wantsReturning) return this.db.delete(this.table).where(this.condition);+ const query = this.returningFields ? this.db.select(this.returningFields) : this.db.select();+ const before = await query.from(this.table).where(this.condition);+ const result = await this.db.delete(this.table).where(this.condition);+ return affectedRows(result) === 0 ? [] : before;+ }++ then<R1 = unknown, R2 = never>(onfulfilled?: ((value: unknown) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null) {+ return this.execute().then(onfulfilled, onrejected);+ }+}+diff --git a/src/db/d1-compat.ts b/src/db/d1-compat.tsnew file mode 100644index 0000000..4cc1d7f--- /dev/null+++ b/src/db/d1-compat.ts@@ -0,0 +1,91 @@+import type { DatabaseDialect } from "./dialect";+import { normalizeParam, numberPlaceholders, type SqlExecutor } from "./drivers/types";++/**+ * A `D1Database` over any SqlExecutor, for the raw `env.DB.prepare(...)` call sites. SQL is written+ * with `?` placeholders as D1 expects; PostgreSQL gets them numbered here.+ */+type Row = Record<string, unknown>;++function meta(affectedRows: number, insertId?: number) {+ return { duration: 0, size_after: 0, rows_read: 0, rows_written: affectedRows, last_row_id: insertId ?? 0, changed_db: affectedRows > 0, changes: affectedRows };+}++export class CompatStatement {+ constructor(+ readonly db: CompatDatabase,+ readonly sql: string,+ readonly params: unknown[] = [],+ ) {}++ bind(...values: unknown[]) {+ return new CompatStatement(this.db, this.sql, values.map(normalizeParam));+ }++ /** Statements without parameters (migrations) are sent untouched, so a `?` inside a function body survives. */+ private text() {+ return this.db.dialect === "postgres" && this.params.length > 0 ? numberPlaceholders(this.sql) : this.sql;+ }++ /** @internal */+ async execute(executor: SqlExecutor) {+ return executor.query(this.text(), this.params, "object");+ }++ async run<T = Row>() {+ const result = await this.execute(this.db.executor());+ return { results: result.rows as T[], success: true as const, meta: meta(result.affectedRows, result.insertId) };+ }++ async all<T = Row>() {+ return this.run<T>();+ }++ async first<T = Row>(column?: string): Promise<T | null> {+ const result = await this.execute(this.db.executor());+ const row = result.rows[0] as Row | undefined;+ if (!row) return null;+ return (column ? row[column] : row) as T;+ }++ async raw<T = unknown[]>(): Promise<T[]> {+ return (await this.db.executor().query(this.text(), this.params, "array")).rows as T[];+ }+}++export class CompatDatabase {+ constructor(+ readonly dialect: DatabaseDialect,+ private readonly base: SqlExecutor,+ private readonly active: () => SqlExecutor | null = () => null,+ ) {}++ executor() {+ return this.active() ?? this.base;+ }++ prepare(sql: string) {+ return new CompatStatement(this, sql);+ }++ async batch<T = Row>(statements: CompatStatement[]) {+ const run = async (executor: SqlExecutor) => {+ const results: Array<{ results: T[]; success: true; meta: ReturnType<typeof meta> }> = [];+ for (const statement of statements) {+ const result = await statement.execute(executor);+ results.push({ results: result.rows as T[], success: true as const, meta: meta(result.affectedRows, result.insertId) });+ }+ return results;+ };+ return this.base.transaction ? this.base.transaction(run) : run(this.base);+ }++ async exec(sql: string) {+ const result = await this.base.query(sql, [], "object");+ return { count: 1, duration: 0, rows: result.rows };+ }++ async dump(): Promise<ArrayBuffer> {+ throw new Error("dump() is not available on external databases.");+ }+}diff --git a/src/db/dialect.ts b/src/db/dialect.tsnew file mode 100644index 0000000..3eccaf3--- /dev/null+++ b/src/db/dialect.ts@@ -0,0 +1,142 @@+/**+ * Database selection. Pure (no imports) so the schema, drizzle-kit configs, scripts and tests can+ * all use it. `DATABASE_URL` picks an external database; without it the Cloudflare D1 binding+ * (or, self-hosted, the local SQLite file) is used.+ */+export type DatabaseDialect = "sqlite" | "postgres" | "mysql";++export type DatabaseDriver =+ | "d1"+ | "libsql"+ | "better-sqlite3"+ | "bun-sqlite"+ | "node-postgres"+ | "postgres-js"+ | "neon"+ | "pglite"+ | "mysql2"+ | "planetscale";++export interface DatabaseConfig {+ dialect: DatabaseDialect;+ driver: DatabaseDriver;+ /** Connection string; `undefined` only for the D1 binding. */+ url?: string;+ authToken?: string;+}++/** Names accepted in DATABASE_DRIVER, including friendly aliases for hosted services. */+export const DRIVER_ALIASES: Record<string, DatabaseDriver> = {+ d1: "d1",+ libsql: "libsql",+ turso: "libsql",+ "better-sqlite3": "better-sqlite3",+ sqlite: "better-sqlite3",+ "bun-sqlite": "bun-sqlite",+ bun: "bun-sqlite",+ "node-postgres": "node-postgres",+ pg: "node-postgres",+ postgres: "node-postgres",+ postgresql: "node-postgres",+ supabase: "node-postgres",+ "postgres-js": "postgres-js",+ postgresjs: "postgres-js",+ neon: "neon",+ vercel: "neon",+ pglite: "pglite",+ mysql2: "mysql2",+ mysql: "mysql2",+ tidb: "mysql2",+ mariadb: "mysql2",+ planetscale: "planetscale",+};++export const DRIVER_DIALECT: Record<DatabaseDriver, DatabaseDialect> = {+ d1: "sqlite",+ libsql: "sqlite",+ "better-sqlite3": "sqlite",+ "bun-sqlite": "sqlite",+ "node-postgres": "postgres",+ "postgres-js": "postgres",+ neon: "postgres",+ pglite: "postgres",+ mysql2: "mysql",+ planetscale: "mysql",+};++function schemeOf(url: string): string {+ return /^([a-z][a-z0-9+.-]*):/i.exec(url.trim())?.[1]?.toLowerCase() ?? "";+}++function hostOf(url: string): string {+ try {+ return new URL(url.replace(/^(postgres(ql)?|mysql2?|mariadb|libsql):/i, "https:")).hostname.toLowerCase();+ } catch {+ return "";+ }+}++/** Infer the driver from a connection string when DATABASE_DRIVER is not given. */+export function inferDriver(url: string): DatabaseDriver {+ const scheme = schemeOf(url);+ const host = hostOf(url);+ if (scheme === "postgres" || scheme === "postgresql") {+ if (host.endsWith(".neon.tech") || host.endsWith(".vercel-storage.com")) return "neon";+ return "node-postgres";+ }+ if (scheme === "pglite") return "pglite";+ if (scheme === "mysql" || scheme === "mysql2" || scheme === "mariadb") {+ if (host.endsWith(".psdb.cloud") || host.endsWith(".planetscale.com")) return "planetscale";+ return "mysql2";+ }+ if (scheme === "libsql" || scheme === "wss" || scheme === "ws" || scheme === "http" || scheme === "https") return "libsql";+ if (scheme === "file" || scheme === "sqlite" || !scheme) return "better-sqlite3";+ throw new Error(`Cannot infer a database driver from DATABASE_URL scheme "${scheme}". Set DATABASE_DRIVER.`);+}++type EnvLike = Record<string, unknown> | undefined | null;++function text(env: EnvLike, key: string): string | undefined {+ const value = env?.[key];+ return typeof value === "string" && value.trim() ? value.trim() : undefined;+}++/**+ * Resolve the database from env vars. `DATABASE_URL` (or, on Workers, a Hyperdrive binding) selects an+ * external database; no URL means D1. Throws on an unsupported driver name or a driver/URL mismatch.+ */+export function resolveDatabaseConfig(env: EnvLike, hyperdriveUrl?: string): DatabaseConfig {+ const url = text(env, "DATABASE_URL") ?? hyperdriveUrl;+ const driverName = text(env, "DATABASE_DRIVER")?.toLowerCase();+ if (!url) {+ if (driverName && driverName !== "d1") throw new Error(`DATABASE_DRIVER=${driverName} needs DATABASE_URL (or a HYPERDRIVE binding).`);+ return { dialect: "sqlite", driver: "d1" };+ }+ let driver: DatabaseDriver;+ if (driverName) {+ driver = DRIVER_ALIASES[driverName];+ if (!driver) throw new Error(`Unsupported DATABASE_DRIVER "${driverName}". Supported: ${Object.keys(DRIVER_ALIASES).join(", ")}.`);+ } else {+ driver = inferDriver(url);+ }+ return { dialect: DRIVER_DIALECT[driver], driver, url, authToken: text(env, "DATABASE_AUTH_TOKEN") };+}++/**+ * The dialect the schema module builds its tables for. Read from `process.env` at import time+ * (Workers populate it from vars and secrets), with `MAILFLARE_DB_DIALECT` to force one for tooling.+ */+export function schemaDialect(): DatabaseDialect {+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;+ const forced = text(env, "MAILFLARE_DB_DIALECT");+ if (forced === "sqlite" || forced === "postgres" || forced === "mysql") return forced;+ if (forced) throw new Error(`MAILFLARE_DB_DIALECT must be sqlite, postgres or mysql, got "${forced}".`);+ const named = text(env, "DATABASE_DRIVER")?.toLowerCase();+ // A driver without a URL is the Hyperdrive case: the connection string only exists at request time.+ if (named && !text(env, "DATABASE_URL") && DRIVER_ALIASES[named]) return DRIVER_DIALECT[DRIVER_ALIASES[named]];+ try {+ return resolveDatabaseConfig(env).dialect;+ } catch {+ return "sqlite";+ }+}diff --git a/src/db/drivers/mysql.ts b/src/db/drivers/mysql.tsnew file mode 100644index 0000000..83575da--- /dev/null+++ b/src/db/drivers/mysql.ts@@ -0,0 +1,104 @@+import type { OpenOptions, SqlExecutor } from "./types";+import { lazyExecutor, normalizeParam } from "./types";++const params = (values: unknown[]) => values.map(normalizeParam);++/** TiDB Cloud and most hosted MySQL require TLS; mysql2 only turns it on when asked. */+function sslFor(url: string) {+ return /tidbcloud\.com|[?&]ssl(mode)?=(true|required|require|verify)/i.test(url) ? { minVersion: "TLSv1.2", rejectUnauthorized: true } : undefined;+}++type Queryable = {+ query(options: { sql: string; rowsAsArray?: boolean }, values: unknown[]): Promise<[unknown, unknown]>;+};++function mysqlExecutor(queryable: Queryable, transaction?: SqlExecutor["transaction"]): SqlExecutor {+ return {+ dialect: "mysql",+ async query(sql, values, mode) {+ const [result] = await queryable.query({ sql, rowsAsArray: mode === "array" }, params(values));+ if (Array.isArray(result)) return { rows: result, affectedRows: result.length };+ const header = result as { affectedRows?: number; insertId?: number };+ return { rows: [], affectedRows: header.affectedRows ?? 0, insertId: header.insertId };+ },+ transaction,+ };+}++/** mysql2: MySQL, MariaDB, TiDB, Aurora. */+export function openMysql2({ url, shared }: OpenOptions): SqlExecutor {+ return lazyExecutor("mysql", async () => {+ const mysql = await import("mysql2/promise");+ const lib = (mysql as unknown as { default?: typeof mysql }).default ?? mysql;+ const options = {+ uri: url.replace(/^mysql2:/i, "mysql:").replace(/^mariadb:/i, "mysql:"),+ ssl: sslFor(url),+ decimalNumbers: true,+ supportBigNumbers: true,+ bigNumberStrings: false,+ charset: "utf8mb4",+ timezone: "Z",+ };+ const inTransaction = async <T,>(connection: Awaited<ReturnType<typeof lib.createConnection>>, fn: (tx: SqlExecutor) => Promise<T>) => {+ await connection.beginTransaction();+ try {+ const result = await fn(mysqlExecutor(connection as unknown as Queryable));+ await connection.commit();+ return result;+ } catch (error) {+ await connection.rollback().catch(() => undefined);+ throw error;+ }+ };+ if (shared) {+ const pool = lib.createPool({ ...options, connectionLimit: 10 });+ return {+ ...mysqlExecutor(pool as unknown as Queryable, async (fn) => {+ const connection = await pool.getConnection();+ try {+ return await inTransaction(connection as never, fn);+ } finally {+ connection.release();+ }+ }),+ close: () => pool.end(),+ };+ }+ const withConnection = async <T,>(fn: (connection: Awaited<ReturnType<typeof lib.createConnection>>) => Promise<T>) => {+ const connection = await lib.createConnection(options);+ try {+ return await fn(connection);+ } finally {+ await connection.end().catch(() => undefined);+ }+ };+ return {+ dialect: "mysql",+ query: (sql, values, mode) => withConnection((connection) => mysqlExecutor(connection as unknown as Queryable).query(sql, values, mode)),+ transaction: (fn) => withConnection((connection) => inTransaction(connection, fn)),+ };+ });+}++/** PlanetScale's HTTP driver (fetch, so it runs on Workers without sockets). */+export function openPlanetScale({ url }: OpenOptions): SqlExecutor {+ return lazyExecutor("mysql", async () => {+ const { connect } = await import("@planetscale/database");+ const cast = (field: { type: string }, value: string | null) => {+ if (value === null) return null;+ if (/^(INT|UINT|YEAR|DECIMAL|FLOAT|DOUBLE)/.test(field.type)) return Number(value);+ return value;+ };+ const connection = connect({ url: url.replace(/^mysql2?:/i, "https:").replace(/^(https:\/\/[^@]*@)/, "$1"), cast } as never);+ type Tx = { execute(sql: string, values?: unknown[], options?: { as?: "array" | "object" }): Promise<{ rows: unknown[]; rowsAffected: number; insertId: string }> };+ const executorFor = (target: Tx, transaction?: SqlExecutor["transaction"]): SqlExecutor => ({+ dialect: "mysql",+ async query(sql, values, mode) {+ const result = await target.execute(sql, params(values), { as: mode === "array" ? "array" : "object" });+ return { rows: result.rows, affectedRows: result.rowsAffected, insertId: result.insertId ? Number(result.insertId) : undefined };+ },+ transaction,+ });+ return executorFor(connection as unknown as Tx, (fn) => connection.transaction((tx) => fn(executorFor(tx as unknown as Tx))));+ });+}diff --git a/src/db/drivers/postgres.ts b/src/db/drivers/postgres.tsnew file mode 100644index 0000000..2e6de48--- /dev/null+++ b/src/db/drivers/postgres.ts@@ -0,0 +1,202 @@+import type { QueryResult, RowMode, SqlExecutor, OpenOptions } from "./types";+import { lazyExecutor, normalizeParam } from "./types";++/** bigint and numeric arrive as strings by default; every count, sum and timestamp in the app is a number. */+const INT8 = 20;+const NUMERIC = 1700;++function params(values: unknown[]) {+ return values.map(normalizeParam);+}++// ---- node-postgres (also Supabase, Neon over TCP, RDS, Hyperdrive) ----++type PgQueryable = {+ query(config: { text: string; values: unknown[]; rowMode?: "array"; types?: unknown }): Promise<{ rows: unknown[]; rowCount: number | null }>;+};++function pgExecutor(queryable: PgQueryable, types: unknown, inTransaction?: <T>(fn: (tx: SqlExecutor) => Promise<T>) => Promise<T>): SqlExecutor {+ return {+ dialect: "postgres",+ async query(text, values, mode: RowMode): Promise<QueryResult> {+ const result = await queryable.query({ text, values: params(values), rowMode: mode === "array" ? "array" : undefined, types });+ return { rows: result.rows, affectedRows: result.rowCount ?? 0 };+ },+ transaction: inTransaction,+ };+}++export function openNodePostgres({ url, shared }: OpenOptions): SqlExecutor {+ return lazyExecutor("postgres", async () => {+ const pg = await import("pg");+ const { Pool, Client, types: pgTypes } = (pg as unknown as { default?: typeof pg }).default ?? pg;+ const types = {+ getTypeParser: (oid: number, format?: "text" | "binary") =>+ oid === INT8 || oid === NUMERIC ? (value: string) => Number(value) : pgTypes.getTypeParser(oid as never, format as never),+ };+ // TLS follows the connection string (`sslmode=require` etc.), as node-postgres parses it.+ const config = { connectionString: url };++ if (shared) {+ const pool = new Pool({ ...config, max: 10 });+ // An idle connection dropped by the server would otherwise crash the process with an unhandled event.+ pool.on("error", (error: Error) => console.error("Postgres pool error:", error.message));+ const run = async <T,>(fn: (tx: SqlExecutor) => Promise<T>) => {+ const client = await pool.connect();+ try {+ await client.query("BEGIN");+ const result = await fn(pgExecutor(client as unknown as PgQueryable, types));+ await client.query("COMMIT");+ return result;+ } catch (error) {+ await client.query("ROLLBACK").catch(() => undefined);+ throw error;+ } finally {+ client.release();+ }+ };+ return { ...pgExecutor(pool as unknown as PgQueryable, types, run), close: () => pool.end() };+ }++ // Workers: sockets cannot outlive the request that opened them, so connect per use (Hyperdrive pools behind this).+ const withClient = async <T,>(fn: (client: InstanceType<typeof Client>) => Promise<T>) => {+ const client = new Client({ ...config, connectionTimeoutMillis: 10_000 });+ await client.connect();+ try {+ return await fn(client);+ } finally {+ await client.end().catch(() => undefined);+ }+ };+ return {+ dialect: "postgres",+ query: (text, values, mode) => withClient((client) => pgExecutor(client as unknown as PgQueryable, types).query(text, values, mode)),+ transaction: (fn) =>+ withClient(async (client) => {+ await client.query("BEGIN");+ try {+ const result = await fn(pgExecutor(client as unknown as PgQueryable, types));+ await client.query("COMMIT");+ return result;+ } catch (error) {+ await client.query("ROLLBACK").catch(() => undefined);+ throw error;+ }+ }),+ };+ });+}++// ---- postgres.js ----++export function openPostgresJs({ url, shared }: OpenOptions): SqlExecutor {+ return lazyExecutor("postgres", async () => {+ const imported = await import("postgres");+ const postgres = (imported as unknown as { default: typeof imported.default }).default;+ const make = () =>+ postgres(url, {+ max: shared ? 10 : 1,+ prepare: false,+ onnotice: () => undefined,+ types: {+ bigint: { to: INT8, from: [INT8], serialize: (value: unknown) => String(value), parse: (value: string) => Number(value) },+ numeric: { to: NUMERIC, from: [NUMERIC], serialize: (value: unknown) => String(value), parse: (value: string) => Number(value) },+ },+ });+ type Sql = ReturnType<typeof make>;+ const executorFor = (sql: Sql | { unsafe: Sql["unsafe"] }, transaction?: SqlExecutor["transaction"]): SqlExecutor => ({+ dialect: "postgres",+ async query(text, values, mode) {+ const statement = sql.unsafe(text, params(values) as never);+ if (mode === "array") {+ const result = await statement.values();+ return { rows: result as unknown[], affectedRows: (result as { count?: number }).count ?? result.length };+ }+ const result = await statement;+ return { rows: [...result], affectedRows: (result as unknown as { count?: number }).count ?? result.length };+ },+ transaction,+ });+ if (shared) {+ const sql = make();+ return {+ ...executorFor(sql, (fn) => sql.begin((tx) => fn(executorFor(tx as unknown as Sql))) as never),+ close: () => sql.end(),+ };+ }+ return {+ dialect: "postgres",+ query: async (text, values, mode) => {+ const sql = make();+ try {+ return await executorFor(sql).query(text, values, mode);+ } finally {+ await sql.end({ timeout: 1 }).catch(() => undefined);+ }+ },+ transaction: async (fn) => {+ const sql = make();+ try {+ return (await sql.begin((tx) => fn(executorFor(tx as unknown as Sql)))) as never;+ } finally {+ await sql.end({ timeout: 1 }).catch(() => undefined);+ }+ },+ };+ });+}++// ---- Neon / Vercel Postgres over HTTP (fetch, so it runs anywhere) ----++export function openNeon({ url }: OpenOptions): SqlExecutor {+ return lazyExecutor("postgres", async () => {+ const { neon } = await import("@neondatabase/serverless");+ const sql = neon(url, { fullResults: true });+ return {+ dialect: "postgres",+ async query(text, values, mode) {+ const result = (await sql.query(text, params(values), { arrayMode: mode === "array", fullResults: true } as never)) as unknown as {+ rows: unknown[];+ rowCount: number;+ fields: Array<{ name: string; dataTypeID: number }>;+ };+ // The HTTP protocol returns bigint and numeric as strings; the app expects numbers (as the TCP drivers give).+ const numeric = result.fields.map((field, index) => (field.dataTypeID === INT8 || field.dataTypeID === NUMERIC ? [index, field.name] as const : null)).filter((entry) => entry !== null);+ if (numeric.length > 0) {+ for (const row of result.rows) {+ for (const [index, name] of numeric) {+ const cell = mode === "array" ? (row as unknown[])[index] : (row as Record<string, unknown>)[name];+ if (typeof cell !== "string") continue;+ if (mode === "array") (row as unknown[])[index] = Number(cell);+ else (row as Record<string, unknown>)[name] = Number(cell);+ }+ }+ }+ return { rows: result.rows, affectedRows: result.rowCount ?? 0 };+ },+ // The HTTP protocol has no interactive transaction; batches fall back to sequential statements.+ };+ });+}++// ---- PGlite (in-process Postgres on WASM; Node only) ----++export function openPglite({ url }: OpenOptions): SqlExecutor {+ return lazyExecutor("postgres", async () => {+ // Variable specifier: PGlite is large and Node-only, so bundlers must not pull it into the Worker.+ const name = "@electric-sql/pglite";+ const { PGlite } = (await import(/* @vite-ignore */ name)) as typeof import("@electric-sql/pglite");+ const location = url.replace(/^pglite:(\/\/)?/i, "");+ const dataDir = !location || location === "memory" || location === "memory:" ? undefined : location;+ const db = await PGlite.create(dataDir, { parsers: { [INT8]: (value: string) => Number(value), [NUMERIC]: (value: string) => Number(value) } });+ const executorFor = (target: Pick<typeof db, "query">, transaction?: SqlExecutor["transaction"]): SqlExecutor => ({+ dialect: "postgres",+ async query(text, values, mode) {+ const result = await target.query(text, params(values), { rowMode: mode === "array" ? "array" : "object" });+ return { rows: result.rows as unknown[], affectedRows: result.affectedRows ?? result.rows.length };+ },+ transaction,+ });+ return { ...executorFor(db, (fn) => db.transaction((tx) => fn(executorFor(tx as never)))), close: () => db.close() };+ });+}diff --git a/src/db/drivers/sqlite.ts b/src/db/drivers/sqlite.tsnew file mode 100644index 0000000..4944dc7--- /dev/null+++ b/src/db/drivers/sqlite.ts@@ -0,0 +1,122 @@+import type { OpenOptions, QueryResult, SqlExecutor } from "./types";+import { lazyExecutor, normalizeParam } from "./types";++const sqliteParam = (value: unknown) => {+ const normalized = normalizeParam(value);+ return typeof normalized === "boolean" ? (normalized ? 1 : 0) : normalized;+};++/** libSQL / Turso: remote (`libsql://`, `https://`) and local `file:` databases. */+export function openLibsql({ url, authToken }: OpenOptions): SqlExecutor {+ return lazyExecutor("sqlite", async () => {+ const { createClient } = await import("@libsql/client");+ const client = createClient({ url, authToken });+ type Executable = { execute(statement: { sql: string; args: unknown[] }): Promise<{ rows: Array<Record<string, unknown>>; columns: string[]; rowsAffected: number; lastInsertRowid?: bigint }> };+ const executorFor = (target: Executable, transaction?: SqlExecutor["transaction"]): SqlExecutor => ({+ dialect: "sqlite",+ async query(sql, values, mode): Promise<QueryResult> {+ const result = await target.execute({ sql, args: values.map(sqliteParam) });+ const rows = mode === "array" ? result.rows.map((row) => result.columns.map((_, i) => (row as unknown as unknown[])[i])) : result.rows.map((row) => ({ ...row }));+ return { rows, affectedRows: result.rowsAffected, insertId: result.lastInsertRowid === undefined ? undefined : Number(result.lastInsertRowid) };+ },+ transaction,+ });+ return {+ ...executorFor(client as unknown as Executable, async (fn) => {+ const tx = await client.transaction("write");+ try {+ const result = await fn(executorFor(tx as unknown as Executable));+ await tx.commit();+ return result;+ } catch (error) {+ await tx.rollback().catch(() => undefined);+ throw error;+ } finally {+ tx.close();+ }+ }),+ close: async () => client.close(),+ };+ });+}++/** A local SQLite file through better-sqlite3 (Node only). */+export function openBetterSqlite3({ url }: OpenOptions): SqlExecutor {+ return lazyExecutor("sqlite", async () => {+ const name = "better-sqlite3";+ const Database = ((await import(/* @vite-ignore */ name)) as { default: new (path: string) => import("better-sqlite3").Database }).default;+ const path = url.replace(/^(file|sqlite):(\/\/)?/i, "") || ":memory:";+ const db = new Database(path);+ db.pragma("journal_mode = WAL");+ db.pragma("foreign_keys = ON");+ return syncSqliteExecutor((sql, values, mode) => {+ const statement = db.prepare(sql);+ if (statement.reader) {+ const rows = mode === "array" ? (statement.raw(true).all(...values) as unknown[]) : (statement.raw(false).all(...values) as unknown[]);+ return { rows, affectedRows: 0 };+ }+ const info = statement.run(...values);+ return { rows: [], affectedRows: info.changes, insertId: Number(info.lastInsertRowid) };+ }, async () => void db.close());+ });+}++/** A local SQLite file through bun:sqlite (Bun runtime only). */+export function openBunSqlite({ url }: OpenOptions): SqlExecutor {+ return lazyExecutor("sqlite", async () => {+ const name = "bun:sqlite";+ const { Database } = (await import(/* @vite-ignore */ name)) as { Database: new (path: string) => BunDatabase };+ const db = new Database(url.replace(/^(file|sqlite):(\/\/)?/i, "") || ":memory:");+ db.exec("PRAGMA journal_mode = WAL");+ db.exec("PRAGMA foreign_keys = ON");+ return syncSqliteExecutor((sql, values, mode) => {+ const statement = db.query(sql);+ if (statement.columnNames.length > 0) {+ return { rows: mode === "array" ? statement.values(...values) : statement.all(...values), affectedRows: 0 };+ }+ const info = statement.run(...values);+ return { rows: [], affectedRows: info.changes, insertId: Number(info.lastInsertRowid) };+ }, async () => db.close());+ });+}++interface BunStatement {+ columnNames: string[];+ values(...params: unknown[]): unknown[];+ all(...params: unknown[]): unknown[];+ run(...params: unknown[]): { changes: number; lastInsertRowid: number | bigint };+}+interface BunDatabase {+ query(sql: string): BunStatement;+ exec(sql: string): void;+ close(): void;+}++/** In-process drivers share one connection, so a transaction is BEGIN/COMMIT around awaited statements. */+function syncSqliteExecutor(run: (sql: string, values: unknown[], mode: "array" | "object") => QueryResult, close: () => Promise<void>): SqlExecutor {+ let chain: Promise<unknown> = Promise.resolve();+ const executor: SqlExecutor = {+ dialect: "sqlite",+ async query(sql, values, mode) {+ return run(sql, values.map(sqliteParam), mode);+ },+ // One connection means one transaction at a time; later callers wait for the earlier to finish.+ transaction(fn) {+ const result = chain.then(async () => {+ run("BEGIN", [], "array");+ try {+ const value = await fn(executor);+ run("COMMIT", [], "array");+ return value;+ } catch (error) {+ run("ROLLBACK", [], "array");+ throw error;+ }+ });+ chain = result.catch(() => undefined);+ return result;+ },+ close,+ };+ return executor;+}diff --git a/src/db/drivers/types.ts b/src/db/drivers/types.tsnew file mode 100644index 0000000..ac12c13--- /dev/null+++ b/src/db/drivers/types.ts@@ -0,0 +1,96 @@+import type { DatabaseDialect } from "../dialect";++export type RowMode = "array" | "object";++export interface QueryResult {+ /** Arrays of column values (what drizzle's proxy drivers expect) or objects keyed by column name. */+ rows: unknown[];+ affectedRows: number;+ insertId?: number;+}++/**+ * The only thing a database driver has to provide. Every supported driver is a few lines that turn+ * `(sql, params)` into rows; drizzle runs on top of this through its proxy drivers, and the same executor+ * backs the D1-compatible `env.DB` used by the raw-SQL call sites.+ */+export interface SqlExecutor {+ readonly dialect: DatabaseDialect;+ query(sql: string, params: unknown[], mode: RowMode): Promise<QueryResult>;+ /** Run `fn` atomically on one connection. Absent for HTTP drivers that cannot hold a transaction open. */+ transaction?<T>(fn: (tx: SqlExecutor) => Promise<T>): Promise<T>;+ close?(): Promise<void>;+}++export interface OpenOptions {+ url: string;+ authToken?: string;+ /** Node keeps pools open between requests; Workers cannot reuse sockets across requests. */+ shared: boolean;+}++/** `?` to `$1, $2, ...` outside string literals, quoted identifiers and comments. */+export function numberPlaceholders(sql: string): string {+ let out = "";+ let index = 0;+ let i = 0;+ while (i < sql.length) {+ const ch = sql[i];+ if (ch === "'" || ch === '"') {+ const end = sql.indexOf(ch, i + 1);+ let close = end;+ // Doubled quotes are escapes inside the literal.+ while (close !== -1 && sql[close + 1] === ch) close = sql.indexOf(ch, close + 2);+ const stop = close === -1 ? sql.length : close + 1;+ out += sql.slice(i, stop);+ i = stop;+ } else if (ch === "-" && sql[i + 1] === "-") {+ const end = sql.indexOf("\n", i);+ const stop = end === -1 ? sql.length : end;+ out += sql.slice(i, stop);+ i = stop;+ } else if (ch === "?") {+ out += `$${++index}`;+ i++;+ } else {+ out += ch;+ i++;+ }+ }+ return out;+}++/** Convert values the drivers do not all accept the same way. */+export function normalizeParam(value: unknown): unknown {+ if (value === undefined) return null;+ if (value instanceof Date) return Math.floor(value.getTime() / 1000);+ if (ArrayBuffer.isView(value) && !(value instanceof Uint8Array)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);+ if (value instanceof ArrayBuffer) return new Uint8Array(value);+ return value;+}++export function toObjects(columns: string[], rows: unknown[][]): Record<string, unknown>[] {+ return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]])));+}++/** Lazily open a driver the first time it is needed so unused drivers are never imported. */+export function lazyExecutor(dialect: DatabaseDialect, open: () => Promise<SqlExecutor>): SqlExecutor {+ let pending: Promise<SqlExecutor> | undefined;+ const ready = () => (pending ??= open().catch((error) => {+ pending = undefined;+ throw error;+ }));+ return {+ dialect,+ query: async (sql, params, mode) => (await ready()).query(sql, params, mode),+ transaction: async (fn) => {+ const inner = await ready();+ if (!inner.transaction) return fn(inner);+ return inner.transaction(fn);+ },+ close: async () => {+ if (pending) await (await pending).close?.();+ pending = undefined;+ },+ };+}diff --git a/src/db/external.ts b/src/db/external.tsnew file mode 100644index 0000000..f9b55f8--- /dev/null+++ b/src/db/external.ts@@ -0,0 +1,116 @@+import { drizzle as mysqlProxy } from "drizzle-orm/mysql-proxy";+import { drizzle as pgProxy } from "drizzle-orm/pg-proxy";+import { drizzle as sqliteProxy } from "drizzle-orm/sqlite-proxy";+import { wrapDatabase, currentExecutor, type ExecutorContext } from "./compat";+import { CompatDatabase } from "./d1-compat";+import type { DatabaseConfig } from "./dialect";+import { openMysql2, openPlanetScale } from "./drivers/mysql";+import { openNeon, openNodePostgres, openPglite, openPostgresJs } from "./drivers/postgres";+import { openBetterSqlite3, openBunSqlite, openLibsql } from "./drivers/sqlite";+import type { OpenOptions, SqlExecutor } from "./drivers/types";++/**+ * A database reached through `DATABASE_URL` instead of the D1 binding. It stands in for `env.DB`: it has+ * the D1 methods (prepare/batch/exec) for raw-SQL call sites and carries the drizzle instance factory+ * `createDb` looks for.+ */+export interface ExternalDatabase extends CompatDatabase {+ readonly config: DatabaseConfig;+ readonly sqlExecutor: SqlExecutor;+ createDrizzle(schema: Record<string, unknown>): unknown;+}++export function openExecutor(config: DatabaseConfig, shared: boolean): SqlExecutor {+ const options: OpenOptions = { url: config.url ?? "", authToken: config.authToken, shared };+ switch (config.driver) {+ case "node-postgres":+ return openNodePostgres(options);+ case "postgres-js":+ return openPostgresJs(options);+ case "neon":+ return openNeon(options);+ case "pglite":+ return openPglite(options);+ case "mysql2":+ return openMysql2(options);+ case "planetscale":+ return openPlanetScale(options);+ case "libsql":+ return openLibsql(options);+ case "better-sqlite3":+ return openBetterSqlite3(options);+ case "bun-sqlite":+ return openBunSqlite(options);+ default:+ throw new Error(`No executor for database driver "${config.driver}".`);+ }+}++function withAffected(rows: unknown[], affectedRows: number) {+ Object.defineProperty(rows, "affectedRows", { value: affectedRows, enumerable: false });+ return rows;+}++function buildDrizzle(config: DatabaseConfig, ctx: ExecutorContext, schema: Record<string, unknown>) {+ const executor = () => currentExecutor(ctx);+ if (config.dialect === "postgres") {+ const db = pgProxy(+ async (sql, params, method) => {+ const result = await executor().query(sql, params, method === "all" ? "array" : "object");+ return { rows: withAffected(result.rows, result.affectedRows) as never[] };+ },+ { schema },+ );+ return wrapDatabase(db, "postgres", ctx);+ }+ if (config.dialect === "mysql") {+ const db = mysqlProxy(+ async (sql, params, method) => {+ const result = await executor().query(sql, params, method === "all" ? "array" : "object");+ if (method === "all") return { rows: result.rows as never[] };+ return { rows: [{ insertId: result.insertId ?? 0, affectedRows: result.affectedRows }] as never[], insertId: result.insertId, affectedRows: result.affectedRows };+ },+ { schema },+ );+ return wrapDatabase(db, "mysql", ctx);+ }+ const db = sqliteProxy(+ async (sql, params, method) => {+ const result = await executor().query(sql, params, "array");+ if (method === "run") return { rows: [] as never[] };+ if (method === "get") return { rows: result.rows[0] as never };+ return { rows: result.rows as never[] };+ },+ async (queries) => {+ const run = async (exec: SqlExecutor) => {+ const out: Array<{ rows: never }> = [];+ for (const query of queries) {+ const result = await exec.query(query.sql, query.params, "array");+ out.push({ rows: (query.method === "get" ? result.rows[0] : result.rows) as never });+ }+ return out;+ };+ return ctx.base.transaction ? ctx.base.transaction(run) : run(ctx.base);+ },+ { schema },+ );+ return wrapDatabase(db, "sqlite", ctx);+}++export function openExternalDatabase(config: DatabaseConfig, shared: boolean): ExternalDatabase {+ const base = openExecutor(config, shared);+ const ctx: ExecutorContext = { base, tx: null };+ const compat = new CompatDatabase(config.dialect, base, () => ctx.tx) as ExternalDatabase;+ Object.defineProperties(compat, {+ config: { value: config },+ sqlExecutor: { value: base },+ createDrizzle: {+ value: (schema: Record<string, unknown>) => buildDrizzle(config, { base, tx: null }, schema),+ },+ });+ return compat;+}++export function isExternalDatabase(value: unknown): value is ExternalDatabase {+ return !!value && typeof (value as ExternalDatabase).createDrizzle === "function";+}diff --git a/src/db/index.ts b/src/db/index.tsindex 49855d8..25d5dbd 100644--- a/src/db/index.ts+++ b/src/db/index.ts@@ -1,12 +1,23 @@import { drizzle } from "drizzle-orm/d1";import { schema } from "@/db/schema";+import { isExternalDatabase } from "./external";-export type AppDatabase = ReturnType<typeof createDb>;+export type AppDatabase = ReturnType<typeof createD1Db>;-export function createDb(d1: D1Database) {+function createD1Db(d1: D1Database) {return drizzle(d1, { schema });}+/**+ * The drizzle instance for `env.DB`. That is the D1 binding by default; when `DATABASE_URL` selects another+ * database `env.DB` is an external database (see `withDatabase`) that builds its own dialect's instance.+ * Everything is typed as SQLite, the dialect the app is written against (see compat.ts).+ */+export function createDb(d1: D1Database): AppDatabase {+ if (isExternalDatabase(d1)) return d1.createDrizzle(schema as never) as AppDatabase;+ return createD1Db(d1);+}+export function getDb(env: Pick<CloudflareEnv, "DB">) {if (!env.DB) {throw new Error("No database binding configured");diff --git a/src/db/introspect.ts b/src/db/introspect.tsnew file mode 100644index 0000000..fe30905--- /dev/null+++ b/src/db/introspect.ts@@ -0,0 +1,39 @@+import type { DatabaseDialect } from "./dialect";+import { isExternalDatabase } from "./external";++/** Schema introspection for raw `env.DB` callers (backups, setup checks), per dialect. */+export function dialectOf(db: D1Database): DatabaseDialect {+ return isExternalDatabase(db) ? db.config.dialect : "sqlite";+}++/** Names of the tables in the current schema/database. */+export async function listTableNames(db: D1Database): Promise<Set<string>> {+ const dialect = dialectOf(db);+ const sql =+ dialect === "sqlite"+ ? "SELECT name FROM sqlite_master WHERE type = 'table'"+ : dialect === "postgres"+ ? "SELECT table_name AS name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE'"+ : "SELECT table_name AS name FROM information_schema.tables WHERE table_schema = database() AND table_type = 'BASE TABLE'";+ const result = await db.prepare(sql).all<{ name?: string; NAME?: string }>();+ return new Set(result.results.map((row) => (row.name ?? row.NAME) as string));+}++/** Column names of a table, or an empty set when it does not exist. */+export async function listColumnNames(db: D1Database, table: string): Promise<Set<string>> {+ const dialect = dialectOf(db);+ if (dialect === "sqlite") {+ const result = await db.prepare(`PRAGMA table_info(${table})`).all<{ name: string }>();+ return new Set(result.results.map((column) => column.name));+ }+ const schema = dialect === "postgres" ? "current_schema()" : "database()";+ const result = await db+ .prepare(`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${schema} AND table_name = ?`)+ .bind(table)+ .all<{ name?: string; NAME?: string }>();+ return new Set(result.results.map((row) => (row.name ?? row.NAME) as string));+}++export function quoteIdentifier(dialect: DatabaseDialect, name: string): string {+ return dialect === "mysql" ? `\`${name.replaceAll("`", "``")}\`` : `"${name.replaceAll('"', '""')}"`;+}diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex ebf9069..b689d6e 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -1,6 +1,10 @@-import { sqliteTable, text, integer, index, uniqueIndex } from "drizzle-orm/sqlite-core";import { sql } from "drizzle-orm";import type { AnySQLiteColumn } from "drizzle-orm/sqlite-core";+import { kit } from "./kits";++// Written once against the dialect kit (see kits.ts): SQLite by default, PostgreSQL or MySQL when+// DATABASE_URL selects one. Everything below is typed as SQLite, which is the shape the app queries.+const { table: sqliteTable, text, integer, bool, timestamp, autoId, index, uniqueIndex, desc, nowSeconds } = kit;export const users = sqliteTable("users", {id: text("id").primaryKey(),@@ -15,31 +19,31 @@ export const users = sqliteTable("users", {role: text("role", { enum: ["admin", "user"] }).notNull().default("user"),// Exactly one account is the primary admin: the one created during setup.// They own administrator management and can hand the role to another account.- isPrimaryAdmin: integer("is_primary_admin", { mode: "boolean" }).notNull().default(false),- disabled: integer("disabled", { mode: "boolean" }).notNull().default(false),- canManageMailboxes: integer("can_manage_mailboxes", { mode: "boolean" }).notNull().default(false),+ isPrimaryAdmin: bool("is_primary_admin").notNull().default(false),+ disabled: bool("disabled").notNull().default(false),+ canManageMailboxes: bool("can_manage_mailboxes").notNull().default(false),// Capabilities the primary admin grants to other admins.- canManageDomains: integer("can_manage_domains", { mode: "boolean" }).notNull().default(false),- canManageUsers: integer("can_manage_users", { mode: "boolean" }).notNull().default(false),- keyboardShortcutsEnabled: integer("keyboard_shortcuts_enabled", { mode: "boolean" }).notNull().default(true),- spamProtectionEnabled: integer("spam_protection_enabled", { mode: "boolean" }).notNull().default(true),+ canManageDomains: bool("can_manage_domains").notNull().default(false),+ canManageUsers: bool("can_manage_users").notNull().default(false),+ keyboardShortcutsEnabled: bool("keyboard_shortcuts_enabled").notNull().default(true),+ spamProtectionEnabled: bool("spam_protection_enabled").notNull().default(true),/** Days a message may stay in Trash or Spam before the scheduled purge deletes it; null keeps it forever. */trashRetentionDays: integer("trash_retention_days"),// Off shows the mailbox only. On shows Name <mailbox> on To, Cc, and Bcc.- showFullRecipientAddresses: integer("show_full_recipient_addresses", { mode: "boolean" }).notNull().default(false),+ showFullRecipientAddresses: bool("show_full_recipient_addresses").notNull().default(false),// When the reader loads remote images and styles without being asked: always ask, only for senders not yet allowed, or always.remoteContentMode: text("remote_content_mode", { enum: ["ask", "new_sender", "allow"] }).notNull().default("allow"),// TOTP second factor. The secret is written at enrolment and only counts// once the user has proven a code from their authenticator.totpSecret: text("totp_secret"),- totpEnabled: integer("totp_enabled", { mode: "boolean" }).notNull().default(false),- totpConfirmedAt: integer("totp_confirmed_at", { mode: "timestamp" }),- lastSignInAt: integer("last_sign_in_at", { mode: "timestamp" }),+ totpEnabled: bool("totp_enabled").notNull().default(false),+ totpConfirmedAt: timestamp("totp_confirmed_at"),+ lastSignInAt: timestamp("last_sign_in_at"),// Set when an admin deletes the account. The account is also `disabled` and can be restored until the// retention window ends, after which the scheduled purge removes it and its data.- deletedAt: integer("deleted_at", { mode: "timestamp" }),+ deletedAt: timestamp("deleted_at"),createdByUserId: text("created_by_user_id").references((): AnySQLiteColumn => users.id, { onDelete: "set null" }),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [@@ -63,12 +67,12 @@ export const domains = sqliteTable(sendingSubdomainTag: text("sending_subdomain_tag"),sendingProvider: text("sending_provider", { enum: ["none", "cloudflare", "resend", "ses"] }).notNull().default("none"),receivingProvider: text("receiving_provider", { enum: ["none", "cloudflare", "resend", "ses"] }).notNull().default("cloudflare"),- sendingRequested: integer("sending_requested", { mode: "boolean" }).notNull().default(false),- sendingEnabled: integer("sending_enabled", { mode: "boolean" }).notNull().default(false),- routingEnabled: integer("routing_enabled", { mode: "boolean" }).notNull().default(false),+ sendingRequested: bool("sending_requested").notNull().default(false),+ sendingEnabled: bool("sending_enabled").notNull().default(false),+ routingEnabled: bool("routing_enabled").notNull().default(false),/** The operator skipped adding/checking DNS; set until they confirm the records exist. */- dnsSkipped: integer("dns_skipped", { mode: "boolean" }).notNull().default(false),- createdAt: integer("created_at", { mode: "timestamp" })+ dnsSkipped: bool("dns_skipped").notNull().default(false),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -91,14 +95,14 @@ export const mailboxes = sqliteTable(localPart: text("local_part").notNull(),displayName: text("display_name"),signature: text("signature"),- autoReplyEnabled: integer("auto_reply_enabled", { mode: "boolean" }).notNull().default(false),+ autoReplyEnabled: bool("auto_reply_enabled").notNull().default(false),autoReplySubject: text("auto_reply_subject").notNull().default("Out of office"),autoReplyBody: text("auto_reply_body").notNull().default(""),avatarKey: text("avatar_key"),type: text("type", { enum: ["personal", "shared"] }).notNull().default("personal"),- useAllDomains: integer("use_all_domains", { mode: "boolean" }).notNull().default(true),- disabled: integer("disabled", { mode: "boolean" }).notNull().default(false),- createdAt: integer("created_at", { mode: "timestamp" })+ useAllDomains: bool("use_all_domains").notNull().default(true),+ disabled: bool("disabled").notNull().default(false),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -116,7 +120,7 @@ export const mailboxAliases = sqliteTable(.notNull().references(() => domains.id, { onDelete: "cascade" }),localPart: text("local_part").notNull(),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -134,7 +138,7 @@ export const autoReplyDeliveries = sqliteTable(.notNull().references(() => mailboxes.id, { onDelete: "cascade" }),recipient: text("recipient").notNull(),- sentAt: integer("sent_at", { mode: "timestamp" }).notNull(),+ sentAt: timestamp("sent_at").notNull(),},(t) => [uniqueIndex("auto_reply_deliveries_mailbox_recipient_idx").on(t.mailboxId, t.recipient),@@ -156,7 +160,7 @@ export const mailboxAccess = sqliteTable(.notNull().default("read_only"),createdByUserId: text("created_by_user_id").references(() => users.id, { onDelete: "set null" }),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -181,11 +185,11 @@ export const contacts = sqliteTable(source: text("source", { enum: ["manual", "inbound", "outbound"] }).notNull().default("inbound"),- blocked: integer("blocked", { mode: "boolean" }).notNull().default(false),+ blocked: bool("blocked").notNull().default(false),// Set when the user allows remote content from this sender; "new_sender" mode loads it without asking afterwards.- remoteContentAllowed: integer("remote_content_allowed", { mode: "boolean" }).notNull().default(false),- lastSeenAt: integer("last_seen_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" })+ remoteContentAllowed: bool("remote_content_allowed").notNull().default(false),+ lastSeenAt: timestamp("last_seen_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -207,7 +211,7 @@ export const folders = sqliteTable(.references(() => mailboxes.id, { onDelete: "cascade" }),name: text("name").notNull(),color: text("color").notNull().default("#2563eb"),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -233,13 +237,13 @@ export const jmapMailboxRevisions = sqliteTable("jmap_mailbox_revisions", {export const jmapChanges = sqliteTable("jmap_changes",{- seq: integer("seq").primaryKey({ autoIncrement: true }),+ seq: autoId("seq"),mailboxId: text("mailbox_id").notNull(),objectType: text("object_type", { enum: ["email", "mailbox"] }).notNull(),objectId: text("object_id").notNull(),threadId: text("thread_id"),change: text("change", { enum: ["created", "updated", "destroyed"] }).notNull(),- createdAt: integer("created_at").notNull().default(sql`(unixepoch())`),+ createdAt: integer("created_at").notNull().default(nowSeconds),},(table) => [index("jmap_changes_mailbox_seq_idx").on(table.mailboxId, table.seq)],);@@ -260,11 +264,11 @@ export const apiKeys = sqliteTable("api_keys", {prefix: text("prefix").notNull(),keyHash: text("key_hash").notNull(),scopes: text("scopes").notNull(),- mailboxScopeEnabled: integer("mailbox_scope_enabled", { mode: "boolean" }).notNull().default(false),- createdAt: integer("created_at", { mode: "timestamp" })+ mailboxScopeEnabled: bool("mailbox_scope_enabled").notNull().default(false),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),- lastUsedAt: integer("last_used_at", { mode: "timestamp" }),+ lastUsedAt: timestamp("last_used_at"),}, (t) => [index("api_keys_user_idx").on(t.userId)]);export const messages = sqliteTable(@@ -290,9 +294,9 @@ export const messages = sqliteTable(htmlBody: text("html_body"),rawR2Key: text("raw_r2_key"),status: text("status").notNull().default("received"),- read: integer("read", { mode: "boolean" }).notNull().default(false),- starred: integer("starred", { mode: "boolean" }).notNull().default(false),- snoozedUntil: integer("snoozed_until", { mode: "timestamp" }),+ read: bool("read").notNull().default(false),+ starred: bool("starred").notNull().default(false),+ snoozedUntil: timestamp("snoozed_until"),threadId: text("thread_id"),// RFC 5322 threading headers, kept so replies land in the right conversation// and so outgoing replies can carry them on to the recipient's client.@@ -301,11 +305,11 @@ export const messages = sqliteTable(spamScore: integer("spam_score"),spamVerdict: text("spam_verdict", { enum: ["inbox", "suspicious", "spam"] }),spamSignals: text("spam_signals"),- spamAnalyzedAt: integer("spam_analyzed_at", { mode: "timestamp" }),+ spamAnalyzedAt: timestamp("spam_analyzed_at"),spamAnalysisError: text("spam_analysis_error"),/** When the message last entered Trash or Spam; maintained by triggers (migration 0053). */- trashedAt: integer("trashed_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" })+ trashedAt: timestamp("trashed_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -321,8 +325,8 @@ export const messages = sqliteTable(t.mailboxId,t.status,t.folderId,- sql`${t.createdAt} desc`,- sql`${t.id} desc`,+ desc(t.createdAt),+ desc(t.id),),index("messages_thread_key_idx").on(t.mailboxId,@@ -336,8 +340,8 @@ export const messages = sqliteTable(t.mailboxId,t.status,t.folderId,- sql`${t.createdAt} desc`,- sql`${t.id} desc`,+ desc(t.createdAt),+ desc(t.id),t.direction,t.read,t.threadId,@@ -378,7 +382,7 @@ export const spamTokenStats = sqliteTable(token: text("token").notNull(),spamCount: integer("spam_count").notNull().default(0),hamCount: integer("ham_count").notNull().default(0),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),},(t) => [uniqueIndex("spam_token_stats_mailbox_token_idx").on(t.mailboxId, t.token),@@ -395,8 +399,8 @@ export const spamReputation = sqliteTable(messagesSeen: integer("messages_seen").notNull().default(0),spamCount: integer("spam_count").notNull().default(0),hamCount: integer("ham_count").notNull().default(0),- firstSeenAt: integer("first_seen_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- lastSeenAt: integer("last_seen_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ firstSeenAt: timestamp("first_seen_at").notNull().$defaultFn(() => new Date()),+ lastSeenAt: timestamp("last_seen_at").notNull().$defaultFn(() => new Date()),},(t) => [uniqueIndex("spam_reputation_mailbox_type_key_idx").on(t.mailboxId, t.type, t.key),@@ -414,8 +418,8 @@ export const spamFeedback = sqliteTable(trainingTokens: text("training_tokens").notNull(),reputationKeys: text("reputation_keys").notNull(),tokenizerVersion: integer("tokenizer_version").notNull().default(1),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),},(t) => [index("spam_feedback_mailbox_idx").on(t.mailboxId),@@ -439,8 +443,8 @@ export const messageAttachments = sqliteTable(contentId: text("content_id"),r2Key: text("r2_key").notNull().unique(),/** Set when the attachment is moved to the Drive trash; hidden from the email until restored, purged after 30 days. */- trashedAt: integer("trashed_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" })+ trashedAt: timestamp("trashed_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -450,8 +454,8 @@ export const messageAttachments = sqliteTable(export const sharedAttachmentLinks = sqliteTable("shared_attachment_links", {id: text("id").primaryKey(),attachmentId: text("attachment_id").notNull().references(() => messageAttachments.id, { onDelete: "cascade" }).unique(),- expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ expiresAt: timestamp("expires_at").notNull(),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),});export const outboundJobs = sqliteTable("outbound_jobs", {@@ -463,11 +467,11 @@ export const outboundJobs = sqliteTable("outbound_jobs", {status: text("status", { enum: ["queued", "sending", "sent", "failed"] }).notNull().default("queued"),payload: text("payload").notNull(),error: text("error"),- scheduledAt: integer("scheduled_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" })+ scheduledAt: timestamp("scheduled_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" })+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),}, (t) => [@@ -483,9 +487,9 @@ export const messageTracking = sqliteTable(messageId: text("message_id").notNull().references(() => messages.id, { onDelete: "cascade" }),/** Opens that were not classified as automated prefetches. */openCount: integer("open_count").notNull().default(0),- firstOpenedAt: integer("first_opened_at", { mode: "timestamp" }),- lastOpenedAt: integer("last_opened_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ firstOpenedAt: timestamp("first_opened_at"),+ lastOpenedAt: timestamp("last_opened_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},(t) => [uniqueIndex("message_tracking_message_idx").on(t.messageId)],);@@ -496,7 +500,7 @@ export const domainTrackingHosts = sqliteTable({domainId: text("domain_id").primaryKey().references(() => domains.id, { onDelete: "cascade" }),hostname: text("hostname").notNull(),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},(t) => [uniqueIndex("domain_tracking_hosts_hostname_idx").on(t.hostname)],);@@ -506,12 +510,12 @@ export const messageOpens = sqliteTable({id: text("id").primaryKey(),token: text("token").notNull().references(() => messageTracking.token, { onDelete: "cascade" }),- openedAt: integer("opened_at", { mode: "timestamp" }).notNull(),+ openedAt: timestamp("opened_at").notNull(),client: text("client"),device: text("device"),country: text("country"),city: text("city"),- automated: integer("automated", { mode: "boolean" }).notNull().default(false),+ automated: bool("automated").notNull().default(false),},(t) => [index("message_opens_token_idx").on(t.token, t.openedAt)],);@@ -522,9 +526,9 @@ export const messageOpens = sqliteTable(*/export const userComposePreferences = sqliteTable("user_compose_preferences", {userId: text("user_id").primaryKey().references(() => users.id, { onDelete: "cascade" }),- trackOpensDefault: integer("track_opens_default", { mode: "boolean" }).notNull().default(false),+ trackOpensDefault: bool("track_opens_default").notNull().default(false),undoSendSeconds: integer("undo_send_seconds").notNull().default(15),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),});/**@@ -537,9 +541,9 @@ export const followUps = sqliteTable(id: text("id").primaryKey(),messageId: text("message_id").notNull().references(() => messages.id, { onDelete: "cascade" }),userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),- dueAt: integer("due_at", { mode: "timestamp" }).notNull(),+ dueAt: timestamp("due_at").notNull(),status: text("status", { enum: ["pending", "due", "replied", "dismissed"] }).notNull().default("pending"),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},(t) => [uniqueIndex("follow_ups_message_idx").on(t.messageId),@@ -556,8 +560,8 @@ export const emailTemplates = sqliteTable(name: text("name").notNull(),subject: text("subject").notNull().default(""),textBody: text("text_body").notNull().default(""),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),},(t) => [index("email_templates_user_idx").on(t.userId)],);@@ -576,13 +580,13 @@ export const calendarEvents = sqliteTable(repeat: text("repeat", { enum: ["none", "daily", "weekly", "monthly", "weekdays"] }).notNull().default("none"),repeatDays: text("repeat_days").notNull().default("[]"),repeatAnchorDay: integer("repeat_anchor_day"),- repeatUntil: integer("repeat_until", { mode: "timestamp" }),+ repeatUntil: timestamp("repeat_until"),excludedOccurrences: text("excluded_occurrences").notNull().default("[]"),timeZone: text("time_zone"),- startsAt: integer("starts_at", { mode: "timestamp" }).notNull(),- endsAt: integer("ends_at", { mode: "timestamp" }).notNull(),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ startsAt: timestamp("starts_at").notNull(),+ endsAt: timestamp("ends_at").notNull(),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),},(t) => [index("calendar_events_user_starts_idx").on(t.userId, t.startsAt),@@ -607,9 +611,9 @@ export const bookingEvents = sqliteTable(endTime: text("end_time").notNull().default("17:00"),timeRanges: text("time_ranges").notNull().default('[{"startTime":"09:00","endTime":"17:00"}]'),timeZone: text("time_zone").notNull().default("UTC"),- enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ enabled: bool("enabled").notNull().default(true),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),},(t) => [index("booking_events_user_idx").on(t.userId), uniqueIndex("booking_events_user_slug_idx").on(t.userId, t.slug)],);@@ -628,7 +632,7 @@ export const routingRules = sqliteTable(// "domain" rules run during address resolution and can catch-all, forward, or reject.scope: text("scope", { enum: ["mailbox", "domain"] }).notNull().default("mailbox"),name: text("name"),- enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),+ enabled: bool("enabled").notNull().default(true),pattern: text("pattern").notNull(),matchField: text("match_field", {enum: ["email", "content", "title", "sender", "recipient"],@@ -646,12 +650,12 @@ export const routingRules = sqliteTable(action: text("action", { enum: ["store", "forward", "reject", "spam", "trash"] }).notNull().default("store"),forwardTo: text("forward_to"),// Forward actions drop the message by default; keepCopy also delivers it to the mailbox.- keepCopy: integer("keep_copy", { mode: "boolean" }).notNull().default(false),+ keepCopy: bool("keep_copy").notNull().default(false),rejectReason: text("reject_reason"),priority: integer("priority").notNull().default(0),- lastMatchedAt: integer("last_matched_at", { mode: "timestamp" }),+ lastMatchedAt: timestamp("last_matched_at"),matchCount: integer("match_count").notNull().default(0),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -673,9 +677,9 @@ export const webhooks = sqliteTable("webhooks", {url: text("url").notNull(),secret: text("secret").notNull(),events: text("events").notNull(),- enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),+ enabled: bool("enabled").notNull().default(true),maxAttempts: integer("max_attempts").notNull().default(5),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("webhooks_user_idx").on(t.userId)]);@@ -695,9 +699,9 @@ export const webhookDeliveries = sqliteTable(responseStatus: integer("response_status"),error: text("error"),durationMs: integer("duration_ms"),- lastAttemptAt: integer("last_attempt_at", { mode: "timestamp" }),- nextRetryAt: integer("next_retry_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" })+ lastAttemptAt: timestamp("last_attempt_at"),+ nextRetryAt: timestamp("next_retry_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -713,8 +717,8 @@ export const sessions = sqliteTable("sessions", {.notNull().references(() => users.id, { onDelete: "cascade" }),tokenHash: text("token_hash").notNull().unique(),- expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),- createdAt: integer("created_at", { mode: "timestamp" })+ expiresAt: timestamp("expires_at").notNull(),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("sessions_user_idx").on(t.userId)]);@@ -736,11 +740,11 @@ export const pushDevices = sqliteTable(topic: text("topic").notNull(),/** Base64 raw P-256 public key; previews are encrypted to it. */publicKey: text("public_key"),- previews: integer("previews", { mode: "boolean" }).notNull().default(true),+ previews: bool("previews").notNull().default(true),/** The app's own id for this account; echoed in pushes so a tap opens the right account. */clientRef: text("client_ref"),- createdAt: integer("created_at", { mode: "timestamp" }).notNull(),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),+ createdAt: timestamp("created_at").notNull(),+ updatedAt: timestamp("updated_at").notNull(),},(table) => [uniqueIndex("push_devices_platform_token_user_idx").on(table.platform, table.token, table.userId),@@ -762,10 +766,10 @@ export const pushSubscriptions = sqliteTable(endpoint: text("endpoint").notNull(),p256dh: text("p256dh").notNull(),auth: text("auth").notNull(),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" })+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),},@@ -785,9 +789,9 @@ export const passwordResetTokens = sqliteTable(.notNull().references(() => users.id, { onDelete: "cascade" }),tokenHash: text("token_hash").notNull().unique(),- expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),- usedAt: integer("used_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" })+ expiresAt: timestamp("expires_at").notNull(),+ usedAt: timestamp("used_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -803,8 +807,8 @@ export const mfaRecoveryCodes = sqliteTable(.notNull().references(() => users.id, { onDelete: "cascade" }),codeHash: text("code_hash").notNull().unique(),- usedAt: integer("used_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" })+ usedAt: timestamp("used_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -822,8 +826,8 @@ export const loginChallenges = sqliteTable("login_challenges", {.notNull().references(() => users.id, { onDelete: "cascade" }),tokenHash: text("token_hash").notNull().unique(),- expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),- createdAt: integer("created_at", { mode: "timestamp" })+ expiresAt: timestamp("expires_at").notNull(),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("login_challenges_user_idx").on(t.userId)]);@@ -838,7 +842,7 @@ export const auditLogs = sqliteTable(messageId: text("message_id").references(() => messages.id, { onDelete: "set null" }),action: text("action").notNull(),metadata: text("metadata"),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),},@@ -853,15 +857,15 @@ export const auditLogs = sqliteTable(export const backupSettings = sqliteTable("backup_settings", {id: text("id").primaryKey(),- enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),+ enabled: bool("enabled").notNull().default(true),scheduleType: text("schedule_type", { enum: ["daily", "weekly", "monthly"] }).notNull().default("daily"),scheduleValue: integer("schedule_value"),- retentionEnabled: integer("retention_enabled", { mode: "boolean" }).notNull().default(false),+ retentionEnabled: bool("retention_enabled").notNull().default(false),retentionDays: integer("retention_days").notNull().default(30),excludedTableGroups: text("excluded_table_groups").notNull().default("[]"),- updatedAt: integer("updated_at", { mode: "timestamp" })+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),});@@ -880,7 +884,7 @@ export const appSettings = sqliteTable("app_settings", {resendWebhookId: text("resend_webhook_id"),resendWebhookSecret: text("resend_webhook_secret"),iconKey: text("icon_key"),- agentEnabled: integer("agent_enabled", { mode: "boolean" }).notNull().default(true),+ agentEnabled: bool("agent_enabled").notNull().default(true),agentProvider: text("agent_provider", { enum: ["cloudflare", "compatible"] }),agentPreset: text("agent_preset", { enum: ["openai", "openrouter", "groq", "custom"] }),agentBaseUrl: text("agent_base_url"),@@ -890,10 +894,10 @@ export const appSettings = sqliteTable("app_settings", {/** Spam analysis lookups; the SPAMHAUS_DQS_KEY and ABUSECH_AUTH_KEY env vars apply when these are null. */spamhausDqsKey: text("spamhaus_dqs_key"),abusechAuthKey: text("abusech_auth_key"),- spamDomainAgeCheck: integer("spam_domain_age_check", { mode: "boolean" }).notNull().default(true),+ spamDomainAgeCheck: bool("spam_domain_age_check").notNull().default(true),/** JSON: brands the administrator added for display-name impersonation checks (see src/lib/spam/settings.ts). */spamBrands: text("spam_brands"),- updatedAt: integer("updated_at", { mode: "timestamp" })+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),});@@ -910,9 +914,9 @@ export const licenseSettings = sqliteTable("license_settings", {features: text("features").notNull().default("[]"),// Account seats from Paymug's seatLimit; null is unlimited. Rows predating seats keep one.seatLimit: integer("seat_limit").default(1),- activatedAt: integer("activated_at", { mode: "timestamp" }),- validatedAt: integer("validated_at", { mode: "timestamp" }),- updatedAt: integer("updated_at", { mode: "timestamp" })+ activatedAt: timestamp("activated_at"),+ validatedAt: timestamp("validated_at"),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),});@@ -930,11 +934,11 @@ export const backups = sqliteTable(size: integer("size"),error: text("error"),createdByUserId: text("created_by_user_id").references(() => users.id, { onDelete: "set null" }),- createdAt: integer("created_at", { mode: "timestamp" })+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),- startedAt: integer("started_at", { mode: "timestamp" }),- completedAt: integer("completed_at", { mode: "timestamp" }),+ startedAt: timestamp("started_at"),+ completedAt: timestamp("completed_at"),},(t) => [index("backups_created_idx").on(t.createdAt),@@ -945,18 +949,18 @@ export const backups = sqliteTable(export const mailboxAgentSettings = sqliteTable("mailbox_agent_settings", {mailboxId: text("mailbox_id").primaryKey().references(() => mailboxes.id, { onDelete: "cascade" }),- enabled: integer("enabled", { mode: "boolean" }).notNull().default(false),+ enabled: bool("enabled").notNull().default(false),modelId: text("model_id"),- autoDraftEnabled: integer("auto_draft_enabled", { mode: "boolean" }).notNull().default(false),+ autoDraftEnabled: bool("auto_draft_enabled").notNull().default(false),reviewerUserId: text("reviewer_user_id").references(() => users.id, { onDelete: "set null" }),instructions: text("instructions").notNull().default(""),dailyLimit: integer("daily_limit").notNull().default(25),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("mailbox_agent_settings_reviewer_idx").on(t.reviewerUserId)]);export const aiUsage = sqliteTable("ai_usage", {id: text("id").primaryKey(),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),provider: text("provider").notNull(),model: text("model").notNull(),source: text("source").notNull(),@@ -970,8 +974,8 @@ export const agentConversations = sqliteTable("agent_conversations", {userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),mailboxId: text("mailbox_id").notNull().references(() => mailboxes.id, { onDelete: "cascade" }),title: text("title").notNull().default("New conversation"),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("agent_conversations_owner_idx").on(t.userId, t.mailboxId, t.updatedAt),index("agent_conversations_mailbox_idx").on(t.mailboxId),@@ -983,7 +987,7 @@ export const agentChatMessages = sqliteTable("agent_chat_messages", {role: text("role", { enum: ["user", "assistant", "tool"] }).notNull(),content: text("content").notNull(),toolName: text("tool_name"),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("agent_chat_messages_conversation_idx").on(t.conversationId, t.createdAt)]);export const agentJobs = sqliteTable("agent_jobs", {@@ -993,11 +997,11 @@ export const agentJobs = sqliteTable("agent_jobs", {reviewerUserId: text("reviewer_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),status: text("status", { enum: ["pending", "running", "completed", "skipped", "failed"] }).notNull().default("pending"),attempts: integer("attempts").notNull().default(0),- nextAttemptAt: integer("next_attempt_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- leaseUntil: integer("lease_until", { mode: "timestamp" }),+ nextAttemptAt: timestamp("next_attempt_at").notNull().$defaultFn(() => new Date()),+ leaseUntil: timestamp("lease_until"),draftId: text("draft_id").references(() => messages.id, { onDelete: "set null" }),reason: text("reason"),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [uniqueIndex("agent_jobs_source_idx").on(t.mailboxId, t.sourceMessageId),index("agent_jobs_due_idx").on(t.status, t.nextAttemptAt),@@ -1012,9 +1016,9 @@ export const agentDraftMetadata = sqliteTable("agent_draft_metadata", {origin: text("origin", { enum: ["chat", "auto", "mcp"] }).notNull(),sourceMessageId: text("source_message_id").references(() => messages.id, { onDelete: "set null" }),revision: integer("revision").notNull().default(1),- humanEditedAt: integer("human_edited_at", { mode: "timestamp" }),- scheduledAt: integer("scheduled_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ humanEditedAt: timestamp("human_edited_at"),+ scheduledAt: timestamp("scheduled_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("agent_draft_meta_source_msg_idx").on(t.sourceMessageId),index("agent_draft_metadata_mailbox_idx").on(t.mailboxId),@@ -1029,10 +1033,10 @@ export const agentSendApprovals = sqliteTable("agent_send_approvals", {revision: integer("revision").notNull(),payloadHash: text("payload_hash").notNull(),status: text("status", { enum: ["pending", "claimed", "sent", "unknown", "expired", "cancelled"] }).notNull().default("pending"),- claimedAt: integer("claimed_at", { mode: "timestamp" }),+ claimedAt: timestamp("claimed_at"),messageId: text("message_id"),- expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ expiresAt: timestamp("expires_at").notNull(),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("agent_send_approvals_user_idx").on(t.userId, t.status),uniqueIndex("agent_send_approvals_delivery_idx").on(t.draftId).where(sql`status IN ('claimed', 'sent', 'unknown')`),@@ -1063,9 +1067,9 @@ export const driveItems = sqliteTable("drive_items", {uploadPartSize: integer("upload_part_size"),uploadFingerprint: text("upload_fingerprint"),linkToken: text("link_token"),- trashedAt: integer("trashed_at", { mode: "timestamp" }),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ trashedAt: timestamp("trashed_at"),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),}, (t) => [index("drive_items_owner_parent_idx").on(t.ownerId, t.parentId),uniqueIndex("drive_items_link_token_idx").on(t.linkToken),@@ -1082,7 +1086,7 @@ export const driveShares = sqliteTable("drive_shares", {itemId: text("item_id").notNull().references(() => driveItems.id, { onDelete: "cascade" }),userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),role: text("role", { enum: ["view", "edit"] }).notNull().default("view"),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),}, (t) => [uniqueIndex("drive_shares_item_user_idx").on(t.itemId, t.userId),index("drive_shares_user_idx").on(t.userId),@@ -1107,10 +1111,10 @@ export const importJobs = sqliteTable("import_jobs", {errors: text("errors").notNull().default("[]"),errorCount: integer("error_count").notNull().default(0),error: text("error"),- createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- startedAt: integer("started_at", { mode: "timestamp" }),- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),- finishedAt: integer("finished_at", { mode: "timestamp" }),+ createdAt: timestamp("created_at").notNull().$defaultFn(() => new Date()),+ startedAt: timestamp("started_at"),+ updatedAt: timestamp("updated_at").notNull().$defaultFn(() => new Date()),+ finishedAt: timestamp("finished_at"),}, (t) => [index("import_jobs_user_idx").on(t.userId, t.createdAt), index("import_jobs_status_idx").on(t.status, t.updatedAt)]);export const schema = {diff --git a/src/db/schema/kits.ts b/src/db/schema/kits.tsnew file mode 100644index 0000000..7b88759--- /dev/null+++ b/src/db/schema/kits.ts@@ -0,0 +1,207 @@+import { sql, type SQL } from "drizzle-orm";+import * as sqlite from "drizzle-orm/sqlite-core";+import * as pg from "drizzle-orm/pg-core";+import * as mysql from "drizzle-orm/mysql-core";+import { schemaDialect, type DatabaseDialect } from "../dialect";++/**+ * The column and table constructors the schema is written against. The schema file is written once in+ * terms of this kit; the kit for the active dialect supplies the real drizzle builders.+ *+ * Representation is kept identical across dialects wherever raw SQL touches a column: timestamps are+ * whole seconds in a bigint, plain integers are bigint, booleans are native booleans (tinyint on+ * MySQL). Only SQLite typings are exposed to the rest of the app; the other kits are cast to the same+ * shape, which is safe because query building is dialect-agnostic for everything the app uses.+ */+const sqliteKit = {+ table: sqlite.sqliteTable,+ text: sqlite.text,+ integer: (name: string) => sqlite.integer(name),+ bool: (name: string) => sqlite.integer(name, { mode: "boolean" }),+ timestamp: (name: string) => sqlite.integer(name, { mode: "timestamp" }),+ autoId: (name: string) => sqlite.integer(name).primaryKey({ autoIncrement: true }),+ index: sqlite.index,+ uniqueIndex: sqlite.uniqueIndex,+ desc: (column: unknown): SQL | never => sql`${column} desc` as never,+ nowSeconds: sql`(unixepoch())` as SQL,+};++export type SchemaKit = typeof sqliteKit;++// ---- PostgreSQL ----++const pgTimestamp = pg.customType<{ data: Date; driverData: string | number }>({+ dataType: () => "bigint",+ fromDriver: (value) => new Date(Number(value) * 1000),+ toDriver: (value) => Math.floor(value.getTime() / 1000),+});++const pgKit = {+ table: pg.pgTable,+ text: (name: string, config?: { enum: readonly [string, ...string[]] }) => pg.text(name, config as never),+ integer: (name: string) => pg.bigint(name, { mode: "number" }),+ bool: (name: string) => pg.boolean(name),+ timestamp: (name: string) => pgTimestamp(name),+ autoId: (name: string) => pg.bigserial(name, { mode: "number" }).primaryKey(),+ index: pg.index,+ uniqueIndex: pg.uniqueIndex,+ desc: (column: unknown) => sql`${column} desc`,+ nowSeconds: sql`(extract(epoch from now())::bigint)` as SQL,+};++// ---- MySQL / MariaDB / TiDB ----++const mysqlTimestamp = mysql.customType<{ data: Date; driverData: string | number }>({+ dataType: () => "bigint",+ fromDriver: (value) => new Date(Number(value) * 1000),+ toDriver: (value) => Math.floor(value.getTime() / 1000),+});++/**+ * MySQL cannot index TEXT, so a text column that is a key, unique, referenced or used in an index must be a+ * VARCHAR; every other text column stays LONGTEXT. Which is which is only known once the whole table+ * (including its index callback) is seen, so `text()` returns a recorder that `table()` resolves.+ */+const KEY_LENGTH = 191;+const LONG_KEYS: Record<string, number> = {+ provider_message_id: 512,+ thread_id: 512,+ raw_r2_key: 512,+ r2_key: 512,+ endpoint: 512,+ email: 320,+ recipient: 320,+ name: 255,+ hostname: 255,+};+/** InnoDB allows 3072 bytes per index; utf8mb4 is 4 bytes per character. */+const INDEX_BYTE_BUDGET = 3000;+const KEYED_METHODS = new Set(["unique", "primaryKey", "references"]);++class MysqlTextColumn {+ private readonly calls: Array<[string, unknown[]]> = [];+ keyed = false;++ constructor(+ private readonly name: string,+ private readonly config?: { enum: readonly [string, ...string[]] },+ ) {+ return new Proxy(this, {+ get: (target, property, receiver) => {+ if (typeof property !== "string" || property in target) return Reflect.get(target, property, receiver);+ return (...args: unknown[]) => {+ target.calls.push([property, args]);+ if (KEYED_METHODS.has(property)) target.keyed = true;+ return receiver;+ };+ },+ });+ }++ materialize(keyed: boolean) {+ // The builder type changes with each chained call, so it is handled untyped here.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let builder: any;+ if (this.config) {+ builder = mysql.varchar(this.name, { length: 64, enum: this.config.enum as [string, ...string[]] });+ } else if (keyed) {+ builder = mysql.varchar(this.name, { length: LONG_KEYS[this.name] ?? KEY_LENGTH });+ } else {+ // MySQL rejects literal defaults on TEXT columns; an expression default `('x')` is allowed (8.0.13+, MariaDB).+ builder = mysql.longtext(this.name);+ const literal = builder.default.bind(builder);+ builder.default = (value: unknown) => (typeof value === "string" ? literal(sql.raw(`('${value.replace(/'/g, "''")}')`)) : literal(value));+ }+ for (const [method, args] of this.calls) builder = builder[method](...args);+ return builder;+ }+}++const mysqlText = (name: string, config?: { enum: readonly [string, ...string[]] }) => new MysqlTextColumn(name, config);++/** Columns an index callback touches; found by running it once against recording stand-ins. */+function indexedProperties(extra: ((columns: Record<string, unknown>) => unknown[]) | undefined): Set<string> {+ const touched = new Set<string>();+ if (!extra) return touched;+ extra(new Proxy({}, { get: (_, property) => (typeof property === "string" && touched.add(property), { __column: property }) }));+ return touched;+}++function mysqlTable(name: string, columns: Record<string, unknown>, extra?: (columns: Record<string, unknown>) => unknown[]) {+ const indexed = indexedProperties(extra);+ const built = Object.fromEntries(+ Object.entries(columns).map(([property, column]) => [property, column instanceof MysqlTextColumn ? column.materialize(column.keyed || indexed.has(property)) : column]),+ );+ return mysql.mysqlTable(name, built as never, extra as never);+}++function columnBytes(column: unknown): number {+ const value = column as { length?: number; getSQLType?: () => string };+ if (typeof value?.length === "number") return value.length * 4;+ return 8;+}++type MysqlIndexBuilder = ReturnType<typeof mysql.index>;++const isExpression = (column: unknown) => !!column && typeof column === "object" && "queryChunks" in (column as object);++/**+ * MySQL cannot index more than 3072 bytes, which the wide covering indexes on `messages` exceed with+ * utf8mb4 keys. Covering indexes are only an optimisation, so trailing columns are dropped to fit.+ * Expression key parts (`coalesce(thread_id, id)`) are dropped too: drizzle-kit cannot emit MySQL+ * functional index syntax.+ */+function fitColumns(columns: unknown[], keepAll: boolean): unknown[] {+ const parts = columns.filter((column) => !isExpression(column));+ if (keepAll) return parts;+ const kept: unknown[] = [];+ let used = 0;+ for (const part of parts) {+ const bytes = columnBytes(part);+ if (kept.length > 0 && used + bytes > INDEX_BYTE_BUDGET) break;+ kept.push(part);+ used += bytes;+ }+ return kept;+}++function mysqlIndex(name: string) {+ const builder = mysql.index(name);+ return {+ on: (...columns: unknown[]) => builder.on(...(fitColumns(columns, false) as Parameters<MysqlIndexBuilder["on"]>)),+ };+}++function mysqlUniqueIndex(name: string) {+ const builder = mysql.uniqueIndex(name);+ return {+ on: (...columns: unknown[]) => {+ const unique = builder.on(...(fitColumns(columns, true) as Parameters<typeof builder.on>));+ // MySQL has no partial indexes; a filtered unique index cannot be expressed, so it becomes a plain index.+ (unique as unknown as { where: (condition: unknown) => unknown }).where = () => mysql.index(name).on(...(fitColumns(columns, true) as Parameters<MysqlIndexBuilder["on"]>));+ return unique;+ },+ };+}++const mysqlKit = {+ table: mysqlTable,+ text: mysqlText,+ integer: (name: string) => mysql.bigint(name, { mode: "number" }),+ bool: (name: string) => mysql.boolean(name),+ timestamp: (name: string) => mysqlTimestamp(name),+ autoId: (name: string) => mysql.bigint(name, { mode: "number" }).primaryKey().autoincrement(),+ index: mysqlIndex,+ uniqueIndex: mysqlUniqueIndex,+ // Descending key parts are only a sort hint; MySQL builds the index ascending and scans it backwards.+ desc: (column: unknown) => column,+ nowSeconds: sql`(unix_timestamp())` as SQL,+};++export function kitFor(dialect: DatabaseDialect): SchemaKit {+ if (dialect === "postgres") return pgKit as unknown as SchemaKit;+ if (dialect === "mysql") return mysqlKit as unknown as SchemaKit;+ return sqliteKit;+}++export const kit: SchemaKit = kitFor(schemaDialect());diff --git a/src/db/sql.ts b/src/db/sql.tsnew file mode 100644index 0000000..be2e81f--- /dev/null+++ b/src/db/sql.ts@@ -0,0 +1,44 @@+import { ilike, like, sql, type AnyColumn, type SQL } from "drizzle-orm";+import { schemaDialect } from "./dialect";++/**+ * SQL that differs between SQLite, PostgreSQL and MySQL, in one place. Everything else the app writes+ * (comparisons, `coalesce`, `case`, window functions, `exists`) is common to all three.+ */+const dialect = schemaDialect();++/** `LIKE` that ignores case on every dialect: SQLite and MySQL already do, PostgreSQL needs ILIKE. */+export function insensitiveLike(column: AnyColumn | SQL, pattern: string): SQL {+ return dialect === "postgres" ? ilike(column as AnyColumn, pattern) : like(column as AnyColumn, pattern);+}++/** The value an `ON CONFLICT DO UPDATE` / `ON DUPLICATE KEY UPDATE` would have inserted. */+export function excluded(column: AnyColumn): SQL {+ const name = sql.identifier(column.name);+ return dialect === "mysql" ? sql`values(${name})` : sql`excluded.${name}`;+}++/** Scalar maximum of several values (SQLite's two-argument `max`). */+export function greatest(...values: Array<SQL | number>): SQL {+ const list = sql.join(values.map((value) => (typeof value === "number" ? sql.raw(String(value)) : value)), sql`, `);+ return dialect === "sqlite" ? sql`max(${list})` : sql`greatest(${list})`;+}++/** 1-based position of `needle` in `haystack`, 0 when absent. */+export function charIndex(haystack: AnyColumn | SQL, needle: string): SQL {+ return dialect === "postgres" ? sql`strpos(${haystack}, ${needle})` : sql`instr(${haystack}, ${needle})`;+}++/** String concatenation; `||` is logical OR on MySQL. String arguments are SQL literals, so pass constants only. */+export function concatText(...parts: Array<SQL | string>): SQL {+ const list = parts.map((part) => (typeof part === "string" ? sql.raw(`'${part.replace(/'/g, "''")}'`) : part));+ return dialect === "mysql" ? sql`concat(${sql.join(list, sql`, `)})` : sql.join(list, sql` || `);+}++/** Boolean literals for `WHERE`: PostgreSQL rejects a bare `0` or `1` there. */+export const matchNothing: SQL = sql`1 = 0`;+export const matchEverything: SQL = sql`1 = 1`;++/** `ESCAPE` character for `LIKE`: a backslash is an escape inside MySQL string literals, `!` is not. */+export const LIKE_ESCAPE = "!";+export const escapeLike = (value: string) => value.replace(/[!%_]/g, "!$&");diff --git a/src/db/with-database.ts b/src/db/with-database.tsnew file mode 100644index 0000000..79b1e07--- /dev/null+++ b/src/db/with-database.ts@@ -0,0 +1,41 @@+import { resolveDatabaseConfig, type DatabaseConfig } from "./dialect";+import { openExternalDatabase, type ExternalDatabase } from "./external";++const wrapped = new WeakMap<object, CloudflareEnv>();+const proxies = new WeakSet<object>();+const opened = new Map<string, ExternalDatabase>();++type DatabaseEnv = Partial<Pick<CloudflareEnv, "DATABASE_URL" | "DATABASE_DRIVER" | "DATABASE_AUTH_TOKEN" | "HYPERDRIVE" | "MAILFLARE_RUNTIME">>;++/** Resolve the configured database: env vars first, then process.env (self-hosted), then a Hyperdrive binding. */+export function getDatabaseConfig(env: DatabaseEnv): DatabaseConfig {+ const processEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};+ const pick = (key: "DATABASE_URL" | "DATABASE_DRIVER" | "DATABASE_AUTH_TOKEN") => (typeof env[key] === "string" && env[key]!.trim() ? env[key] : processEnv[key]);+ return resolveDatabaseConfig(+ { DATABASE_URL: pick("DATABASE_URL"), DATABASE_DRIVER: pick("DATABASE_DRIVER"), DATABASE_AUTH_TOKEN: pick("DATABASE_AUTH_TOKEN") },+ env.HYPERDRIVE?.connectionString,+ );+}++/**+ * Returns env with `DB` served by the database `DATABASE_URL` names, or env unchanged when it is unset+ * (the D1 binding on Workers, the SQLite file when self-hosted). Like `withStorage`, this is the one place+ * that decides where data lives; every caller keeps reading `env.DB`.+ */+export function withDatabase(env: CloudflareEnv): CloudflareEnv {+ if (proxies.has(env)) return env;+ const cached = wrapped.get(env);+ if (cached) return cached;+ const config = getDatabaseConfig(env);+ if (config.driver === "d1") return env;+ const key = `${config.driver}|${config.url}`;+ let database = opened.get(key);+ if (!database) {+ database = openExternalDatabase(config, env.MAILFLARE_RUNTIME === "node");+ opened.set(key, database);+ }+ const proxy = new Proxy(env, { get: (target, property) => (property === "DB" ? database : Reflect.get(target, property)) });+ wrapped.set(env, proxy);+ proxies.add(proxy);+ return proxy;+}diff --git a/src/lib/agent/jobs/utils.ts b/src/lib/agent/jobs/utils.tsindex effefad..8705b18 100644--- a/src/lib/agent/jobs/utils.ts+++ b/src/lib/agent/jobs/utils.ts@@ -1,6 +1,7 @@-import { and, desc, eq, gt, gte, lt, lte, or, sql } from "drizzle-orm";+import { and, desc, eq, gt, gte, lt, lte, ne, or, sql } from "drizzle-orm";import { generateText } from "ai";import { getDb } from "@/db";+import { schemaDialect } from "@/db/dialect";import { agentDraftMetadata, agentJobs, mailboxAgentSettings, mailboxes, messages, users } from "@/db/schema";import { getMailboxAccessLevel } from "@/lib/mailboxes/access";import { normalizeEmailAddress } from "@/lib/email/address";@@ -46,10 +47,19 @@ export async function processAgentDraftJob(env: CloudflareEnv, jobId: string) {if (!job || job.status === "completed" || job.status === "skipped" || job.status === "failed") return;const now = new Date();if (job.nextAttemptAt > now || (job.status === "running" && job.leaseUntil && job.leaseUntil > now)) return;+ // Only one job runs per mailbox. Where the statement can check that itself it does so atomically; MySQL+ // rejects a subquery on the table being updated, so there the check runs first (a narrow race window).+ const mysql = schemaDialect() === "mysql";+ const nowSeconds = Math.floor(now.getTime() / 1000);+ if (mysql) {+ const [busy] = await db.select({ id: agentJobs.id }).from(agentJobs)+ .where(and(eq(agentJobs.mailboxId, job.mailboxId), ne(agentJobs.id, jobId), eq(agentJobs.status, "running"), gt(agentJobs.leaseUntil, now))).limit(1);+ if (busy) return;+ }const claimed = await db.update(agentJobs).set({ status: "running", attempts: job.attempts + 1, leaseUntil: new Date(Date.now() + 10 * 60_000) }).where(and(eq(agentJobs.id, jobId),or(eq(agentJobs.status, "pending"), and(eq(agentJobs.status, "running"), lt(agentJobs.leaseUntil, now))),- sql`NOT EXISTS (SELECT 1 FROM agent_jobs active WHERE active.mailbox_id = ${job.mailboxId} AND active.id <> ${jobId} AND active.status = 'running' AND active.lease_until > ${Math.floor(now.getTime() / 1000)})`,+ mysql ? sql`1 = 1` : sql`NOT EXISTS (SELECT 1 FROM agent_jobs active WHERE active.mailbox_id = ${job.mailboxId} AND active.id <> ${jobId} AND active.status = 'running' AND active.lease_until > ${nowSeconds})`,)).returning({ id: agentJobs.id });if (!claimed.length) return;const skip = async (reason: string) => db.update(agentJobs).set({ status: "skipped", reason, leaseUntil: null }).where(eq(agentJobs.id, jobId));diff --git a/src/lib/auth/setup-utils.ts b/src/lib/auth/setup-utils.tsindex 8560cbf..60ea46e 100644--- a/src/lib/auth/setup-utils.ts+++ b/src/lib/auth/setup-utils.ts@@ -4,7 +4,7 @@ export function isMissingUsersTableError(error: unknown): boolean {while (current && !visited.has(current)) {visited.add(current);- if (current instanceof Error && /no such table:\s*users/i.test(current.message)) {+ if (current instanceof Error && /no such table:\s*users|relation "users" does not exist|table '[^']*\.?users' doesn't exist/i.test(current.message)) {return true;}if (typeof current !== "object" || !("cause" in current)) break;diff --git a/src/lib/backups/export.ts b/src/lib/backups/export.tsindex 37b4e1c..dff8136 100644--- a/src/lib/backups/export.ts+++ b/src/lib/backups/export.ts@@ -1,3 +1,5 @@+import { dialectOf, listColumnNames, listTableNames, quoteIdentifier } from "@/db/introspect";+import type { DatabaseDialect } from "@/db/dialect";import type { BackupTableGroupId, DatabaseBackupDocument, DatabaseBackupTable, DatabaseRecord } from "./types";import { mergeLegacyMessageBodies } from "./utils";import { BACKUP_TABLE_GROUPS, getSelectedBackupTables } from "./table-groups";@@ -21,12 +23,15 @@ export function getBackupConfigurationStatus(_env?: CloudflareEnv) {* Tables D1 manages itself, which are intentionally absent from BACKUP_TABLES.*/export const INTERNAL_TABLE_PATTERNS = ["sqlite_%", "_cf%", "messages_fts%"];+const matchesPattern = (name: string, pattern: string) => name.startsWith(pattern.replace(/%$/, ""));/*** The search index is derived data: its triggers repopulate it as messages are* restored, so it is neither exported nor part of the coverage check.*/export const INTERNAL_TABLES = ["d1_migrations",+ // The migration ledger of PostgreSQL and MySQL databases.+ "mailflare_migrations",// JMAP state counters, also derived: the jmap_messages_* triggers on// `messages` insert and bump a row per mailbox as messages are restored.// Exporting it would make restore fail, since the triggers recreate these@@ -60,24 +65,19 @@ function groupsForDocumentVersion(version: DatabaseBackupDocument["version"]): t* that omit it, and the omission only surfaces during a restore.*/export async function assertBackupTablesCoverDatabase(db: D1Database): Promise<Set<string>> {- const conditions = [- ...INTERNAL_TABLE_PATTERNS.map((pattern) => `name NOT LIKE '${pattern}'`),- ...INTERNAL_TABLES.map((name) => `name <> '${name}'`),- ].join(" AND ");- const result = await db- .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND ${conditions}`)- .all<{ name: string }>();+ const names = [...(await listTableNames(db))].filter((name) => !INTERNAL_TABLE_PATTERNS.some((pattern) => matchesPattern(name, pattern)) && !INTERNAL_TABLES.includes(name));const covered = new Set<string>(BACKUP_TABLES);- const unlisted = result.results.map((row) => row.name).filter((name) => !covered.has(name));+ const unlisted = names.filter((name) => !covered.has(name));if (unlisted.length) throw new Error(`Backup aborted: ${unlisted.join(", ")} not listed in BACKUP_TABLES. Add new tables to src/lib/backups/export.ts and assign each to a group in table-groups.ts.`);const assigned = BACKUP_TABLE_GROUPS.flatMap((group) => group.tables);const ungrouped = BACKUP_TABLES.filter((table) => assigned.filter((item) => item === table).length !== 1);const unknown = assigned.filter((table) => !covered.has(table));if (ungrouped.length || unknown.length) throw new Error(`Backup aborted: table groups are out of sync (${[...ungrouped, ...unknown].join(", ")}). Update src/lib/backups/table-groups.ts.`);- return new Set(result.results.map((row) => row.name));+ return new Set(names);}export async function exportDatabaseRecords(db: D1Database, excludedGroups: BackupTableGroupId[] = []): Promise<Uint8Array> {+ const dialect = dialectOf(db);const databaseTables = await assertBackupTablesCoverDatabase(db);const selected = getSelectedBackupTables(excludedGroups);const includedTables = BACKUP_TABLES.filter((table) => selected.has(table));@@ -89,7 +89,8 @@ export async function exportDatabaseRecords(db: D1Database, excludedGroups: Backcontinue;}const result = await db.prepare(`SELECT * FROM ${table}`).all<DatabaseRecord>();- tables[table] = result.results;+ // Backups hold SQLite-style values whichever database wrote them, so they restore anywhere.+ tables[table] = dialect === "sqlite" ? result.results : result.results.map(toPortableRecord);}const document: DatabaseBackupDocument = { format: "mailflare-database-backup", version: 2, createdAt: new Date().toISOString(), includedTables, tables };return new TextEncoder().encode(JSON.stringify(document));@@ -103,30 +104,29 @@ export async function restoreDatabaseRecords(db: D1Database, content: ArrayBuffemergeLegacyMessageBodies(document);fillMissingBackupTables(document);validateDatabaseBackup(document);- const sharedLinksTable = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'shared_attachment_links'").first<{ name: string }>();+ const dialect = dialectOf(db);+ const existing = await listTableNames(db);+ const sharedLinksTable = existing.has("shared_attachment_links");if (!sharedLinksTable && document.tables.shared_attachment_links?.length) throw new Error("Apply pending database migrations before restoring shared attachment links.");- const bookingTable = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'booking_events'").first<{ name: string }>();+ const bookingTable = existing.has("booking_events");if (!bookingTable && document.tables.booking_events?.length) throw new Error("Apply pending database migrations before restoring booking events.");// Drive migrations ship later than the backup format, so an installation can have a database without them yet.- const driveTableNames = (- await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('drive_items', 'drive_upload_parts', 'drive_shares')").all<{ name: string }>()- ).results.map((row) => row.name);+ const driveTableNames = ["drive_items", "drive_upload_parts", "drive_shares"].filter((table) => existing.has(table));if (["drive_items", "drive_upload_parts", "drive_shares"].some((table) => document.tables[table]?.length) && driveTableNames.length !== 3) throw new Error("Apply pending database migrations before restoring the Drive tables.");- const laterTableNames = (- await db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (${LATER_MIGRATION_TABLES.map(() => "?").join(", ")})`).bind(...LATER_MIGRATION_TABLES).all<{ name: string }>()- ).results.map((row) => row.name);+ const laterTableNames = LATER_MIGRATION_TABLES.filter((table) => existing.has(table));const unmigrated = LATER_MIGRATION_TABLES.filter((table) => document.tables[table]?.length && !laterTableNames.includes(table));if (unmigrated.length) throw new Error(`Apply pending database migrations before restoring ${unmigrated.join(", ")}.`);const restoreTables = BACKUP_TABLES.filter((table) => (table !== "shared_attachment_links" || sharedLinksTable) && (table !== "booking_events" || bookingTable) && (!table.startsWith("drive_") || driveTableNames.includes(table)) && (!LATER_MIGRATION_TABLES.includes(table) || laterTableNames.includes(table)));- const userColumns = new Set((await db.prepare("PRAGMA table_info(users)").all<{ name: string }>()).results.map((column) => column.name));- const bookingColumns = bookingTable ? new Set((await db.prepare("PRAGMA table_info(booking_events)").all<{ name: string }>()).results.map((column) => column.name)) : null;+ const userColumns = await listColumnNames(db, "users");+ const bookingColumns = bookingTable ? await listColumnNames(db, "booking_events") : null;for (const table of [...restoreTables].reverse()) await db.prepare(`DELETE FROM ${table}`).run();for (const table of restoreTables) {const rows = document.tables[table] ?? [];for (let index = 0; index < rows.length; index += INSERT_BATCH_SIZE) {const columns = table === "users" ? userColumns : table === "booking_events" ? bookingColumns : null;- const statements = rows.slice(index, index + INSERT_BATCH_SIZE).map((row) => createInsertStatement(db, table, row, columns));- if (statements.length > 0) await db.batch(statements);+ const statements = rows.slice(index, index + INSERT_BATCH_SIZE).map((row) => createInsertStatement(db, dialect, table, row, columns));+ // MySQL checks foreign keys per statement, so the batch suspends them for its own connection.+ if (statements.length > 0) await db.batch(dialect === "mysql" ? [db.prepare("SET FOREIGN_KEY_CHECKS = 0"), ...statements, db.prepare("SET FOREIGN_KEY_CHECKS = 1")] : statements);}}}@@ -152,11 +152,11 @@ function isDatabaseBackupDocument(value: unknown): value is DatabaseBackupDocume});}-function createInsertStatement(db: D1Database, table: DatabaseBackupTable, row: DatabaseRecord, availableColumns: Set<string> | null = null) {+function createInsertStatement(db: D1Database, dialect: DatabaseDialect, table: DatabaseBackupTable, row: DatabaseRecord, availableColumns: Set<string> | null = null) {const columns = Object.keys(row).filter((column) => !availableColumns || availableColumns.has(column));if (columns.length === 0) throw new Error(`Backup contains an invalid ${table} record`);const placeholders = columns.map(() => "?").join(", ");- const identifiers = columns.map((column) => `\`${column.replaceAll("`", "``")}\``).join(", ");+ const identifiers = columns.map((column) => quoteIdentifier(dialect, column)).join(", ");return db.prepare(`INSERT INTO ${table} (${identifiers}) VALUES (${placeholders})`).bind(...columns.map((column) => row[column]));}@@ -179,3 +179,7 @@ function validateDatabaseBackup(document: DatabaseBackupDocument): void {}}}++function toPortableRecord(row: DatabaseRecord): DatabaseRecord {+ return Object.fromEntries(Object.entries(row).map(([column, value]) => [column, typeof value === "boolean" ? (value ? 1 : 0) : value])) as DatabaseRecord;+}diff --git a/src/lib/booking/create.ts b/src/lib/booking/create.tsindex ec35b3b..7b9c1cb 100644--- a/src/lib/booking/create.ts+++ b/src/lib/booking/create.ts@@ -1,34 +1,32 @@+import { sql } from "drizzle-orm";+import { getDb } from "@/db";+import { calendarEvents } from "@/db/schema";import { newId } from "@/lib/ids";import type { BookingEventRecord } from "./types";+const COLUMNS = [+ "id", "user_id", "mailbox_id", "title", "description", "location", "attendees", "color", "repeat", "repeat_days",+ "excluded_occurrences", "time_zone", "starts_at", "ends_at", "created_at", "updated_at",+];++/**+ * Inserts one calendar event per host, but only when none of the hosts is busy, in a single statement so two+ * guests cannot take the same slot. Returns whether every host was booked.+ */export async function createBookedCalendarEvents(env: CloudflareEnv, event: BookingEventRecord, guestName: string, guestEmail: string, startsAt: string, endsAt: string, guestEmails: string[] = [], notes = ""): Promise<boolean> {const hostIds = event.hostIds;const startSeconds = Math.floor(new Date(startsAt).getTime() / 1000);const endSeconds = Math.floor(new Date(endsAt).getTime() / 1000);const nowSeconds = Math.floor(Date.now() / 1000);- const selectedHosts = hostIds.map(() => "(?, ?)").join(", ");- const hostPlaceholders = hostIds.map(() => "?").join(", ");- const result = await env.DB.prepare(`WITH requested_hosts(host_id, event_id) AS (VALUES ${selectedHosts}),- conflicts AS MATERIALIZED (SELECT COUNT(*) AS total FROM calendar_events WHERE user_id IN (${hostPlaceholders}) AND repeat = 'none' AND starts_at < ? AND ends_at > ?)- INSERT INTO calendar_events (id, user_id, mailbox_id, title, description, location, attendees, color, repeat, repeat_days, excluded_occurrences, time_zone, starts_at, ends_at, created_at, updated_at)- SELECT requested_hosts.event_id, requested_hosts.host_id, NULL, ?, ?, ?, ?, ?, 'none', '[]', '[]', ?, ?, ?, ?, ?- FROM requested_hosts CROSS JOIN conflicts- WHERE conflicts.total = 0`)- .bind(- ...hostIds.flatMap((id) => [id, newId("evt")]),- ...hostIds,- endSeconds,- startSeconds,- `${event.name} with ${guestName}`,- [`Booked by ${guestName} (${guestEmail})`, notes].filter(Boolean).join("\n\n"),- event.location,- JSON.stringify([guestEmail, ...guestEmails]),- event.color,- event.timeZone,- startSeconds,- endSeconds,- nowSeconds,- nowSeconds,- ).run();- return result.meta.changes === hostIds.length;+ const requested = sql.join(hostIds.map((id) => sql`select ${id} as host_id, ${newId("evt")} as event_id`), sql` union all `);+ const hostList = sql.join(hostIds.map((id) => sql`${id}`), sql`, `);+ const columns = sql.join(COLUMNS.map((name) => sql.identifier(name)), sql`, `);+ const description = [`Booked by ${guestName} (${guestEmail})`, notes].filter(Boolean).join("\n\n");+ const result = await getDb(env).run(sql`insert into ${calendarEvents} (${columns})+ select requested_hosts.event_id, requested_hosts.host_id, null, ${`${event.name} with ${guestName}`}, ${description}, ${event.location},+ ${JSON.stringify([guestEmail, ...guestEmails])}, ${event.color}, 'none', '[]', '[]', ${event.timeZone}, ${startSeconds}, ${endSeconds}, ${nowSeconds}, ${nowSeconds}+ from (${requested}) requested_hosts+ where (select count(*) from ${calendarEvents} busy where busy.${sql.identifier("user_id")} in (${hostList}) and busy.${sql.identifier("repeat")} = 'none'+ and busy.${sql.identifier("starts_at")} < ${endSeconds} and busy.${sql.identifier("ends_at")} > ${startSeconds}) = 0`);+ return (result as unknown as { meta: { changes: number } }).meta.changes === hostIds.length;}diff --git a/src/lib/booking/username.ts b/src/lib/booking/username.tsindex 6336c51..8adc3bc 100644--- a/src/lib/booking/username.ts+++ b/src/lib/booking/username.ts@@ -1,4 +1,5 @@import { and, eq, isNull } from "drizzle-orm";+import { isUniqueConstraintError } from "@/lib/database-errors";import { getDb } from "@/db";import { users } from "@/db/schema";import { bookingUsernameFromEmail } from "./utils";@@ -19,7 +20,7 @@ export async function ensureBookingUsername(env: CloudflareEnv, userId: string,const [assigned] = await db.select({ bookingUsername: users.bookingUsername }).from(users).where(eq(users.id, userId)).limit(1);if (assigned?.bookingUsername) return assigned.bookingUsername;} catch (error) {- if (error instanceof Error && /UNIQUE constraint failed|users_booking_username_idx/i.test(error.message)) continue;+ if (isUniqueConstraintError(error)) continue;throw error;}}diff --git a/src/lib/cloudflare.ts b/src/lib/cloudflare.tsindex 140aa5a..627b60c 100644--- a/src/lib/cloudflare.ts+++ b/src/lib/cloudflare.ts@@ -1,9 +1,10 @@import { env } from "cloudflare:workers";import { getNodeEnv } from "@/lib/runtime";+import { withDatabase } from "@/db/with-database";import { withStorage } from "@/lib/storage";export function getEnv(): CloudflareEnv {- return withStorage(getNodeEnv() ?? (env as CloudflareEnv));+ return withDatabase(withStorage(getNodeEnv() ?? (env as CloudflareEnv)));}export async function getEnvAsync(): Promise<CloudflareEnv> {diff --git a/src/lib/contacts/service.ts b/src/lib/contacts/service.tsindex f4aaa4a..d4fa7fb 100644--- a/src/lib/contacts/service.ts+++ b/src/lib/contacts/service.ts@@ -44,7 +44,7 @@ export async function upsertContactFromAddress(env: CloudflareEnv, input: ContacdisplayName,source: input.source,lastSeenAt: now,- });+ }).onConflictDoNothing(); // Two messages from a new sender can be processed at once.const avatarKey = await importGravatarAvatar(env, input.userId, email);if (avatarKey) {await db.update(contacts).set({ avatarKey }).where(eq(contacts.id, id));@@ -122,7 +122,7 @@ export async function blockContact(env: CloudflareEnv, input: BlockContactInput)source: "inbound",blocked: true,lastSeenAt: new Date(),- });+ }).onConflictDoUpdate({ target: contacts.id, set: { blocked: true } });const avatarKey = await importGravatarAvatar(env, input.userId, email);if (avatarKey) {await db.update(contacts).set({ avatarKey }).where(eq(contacts.id, contactId));diff --git a/src/lib/database-errors.ts b/src/lib/database-errors.tsindex 0e08da9..1927961 100644--- a/src/lib/database-errors.ts+++ b/src/lib/database-errors.ts@@ -1,7 +1,8 @@/*** Whether any error in the chain has a message matching `pattern`. Drizzle- * wraps driver errors as "Failed query: …" and keeps the SQLite message on- * `cause`, so checking only the outer message misses it.+ * wraps driver errors as "Failed query: …" and keeps the driver message on+ * `cause`, so checking only the outer message misses it. The patterns cover+ * SQLite/D1, PostgreSQL and MySQL wording.*/function errorChainMatches(error: unknown, pattern: RegExp): boolean {let current: unknown = error;@@ -17,14 +18,14 @@ function errorChainMatches(error: unknown, pattern: RegExp): boolean {/** The table does not exist yet, for features whose migration may not be applied. */export function isMissingTableError(error: unknown): boolean {- return errorChainMatches(error, /no such table/i);+ return errorChainMatches(error, /no such table|relation "[^"]+" does not exist|table '[^']+' doesn't exist/i);}/** A column added by a migration that may not be applied yet. */export function isMissingColumnError(error: unknown): boolean {- return errorChainMatches(error, /no such column|has no column named/i);+ return errorChainMatches(error, /no such column|has no column named|column "[^"]+" (of relation "[^"]+" )?does not exist|unknown column/i);}export function isUniqueConstraintError(error: unknown): boolean {- return errorChainMatches(error, /UNIQUE constraint failed/i);+ return errorChainMatches(error, /UNIQUE constraint failed|duplicate key value violates unique constraint|duplicate entry/i);}diff --git a/src/lib/jmap/changes.ts b/src/lib/jmap/changes.tsindex b4dc70b..f12c477 100644--- a/src/lib/jmap/changes.ts+++ b/src/lib/jmap/changes.ts@@ -1,6 +1,7 @@import { and, asc, eq, gt, inArray, sql } from "drizzle-orm";import { getDb, type AppDatabase } from "@/db";import { jmapChangeFloor, jmapChanges, messages } from "@/db/schema";+import { greatest } from "@/db/sql";import { listFoldersByMailbox, listJmapMailboxes } from "./access";import { encodeMailboxRef, SYSTEM_ROLES } from "./ids";import type { AccessibleMailbox, JmapContext } from "./types";@@ -200,7 +201,7 @@ export async function pruneJmapChanges(db: AppDatabase, now = Date.now()): Promiconst [row] = await db.all<{ seq: number | null }>(sql`SELECT max(seq) AS seq FROM jmap_changes WHERE created_at < ${cutoff}`);const floor = row?.seq ?? 0;if (!floor) return 0;- await db.run(sql`UPDATE jmap_change_floor SET seq = max(seq, ${floor}) WHERE id = 1`);+ await db.run(sql`UPDATE jmap_change_floor SET seq = ${greatest(sql`seq`, floor)} WHERE id = 1`);const deleted = await db.run(sql`DELETE FROM jmap_changes WHERE seq <= ${floor}`);return Number((deleted as { meta?: { changes?: number } }).meta?.changes ?? 0);}diff --git a/src/lib/jmap/email-query.ts b/src/lib/jmap/email-query.tsindex dab0f7f..c96b120 100644--- a/src/lib/jmap/email-query.ts+++ b/src/lib/jmap/email-query.ts@@ -1,6 +1,7 @@-import { and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, like, lt, ne, not, or, sql } from "drizzle-orm";+import { and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, ne, not, or, sql } from "drizzle-orm";import type { SQL } from "drizzle-orm";import { messageAttachments, messages } from "@/db/schema";+import { concatText, insensitiveLike as like, matchEverything, matchNothing } from "@/db/sql";import { KEYWORD_DRAFT, KEYWORD_FLAGGED, KEYWORD_SEEN } from "./constants";import { invalidArguments, unsupportedFilter } from "./errors";import { normalizeMessageId } from "@/lib/email/threading";@@ -28,7 +29,7 @@ function keywordCondition(keyword: string, present: boolean): SQL {return present ? eq(messages.status, "draft") : ne(messages.status, "draft");default:// Unknown keywords are never set, so "has" matches nothing and "not" matches all.- return present ? sql`0` : sql`1`;+ return present ? matchNothing : matchEverything;}}@@ -55,14 +56,14 @@ function headerCondition(header: string[]): SQL {switch (name) {case "message-id":if (header.length === 1) return isNotNull(messages.providerMessageId);- return value ? inArray(messages.providerMessageId, [value, `<${value}>`]) : sql`0`;+ return value ? inArray(messages.providerMessageId, [value, `<${value}>`]) : matchNothing;case "in-reply-to":if (header.length === 1) return isNotNull(messages.inReplyTo);- return value ? inArray(messages.inReplyTo, [value, `<${value}>`]) : sql`0`;+ return value ? inArray(messages.inReplyTo, [value, `<${value}>`]) : matchNothing;case "references":if (header.length === 1) return isNotNull(messages.references);// The column is the space-joined chain, so pad both sides to match whole ids only.- return value ? like(sql`' ' || coalesce(${messages.references}, '') || ' '`, `% ${likeEscape(value)} %`) : sql`0`;+ return value ? like(concatText(' ', sql`coalesce(${messages.references}, '')`, ' '), `% ${likeEscape(value)} %`) : matchNothing;default:throw unsupportedFilter(`Cannot filter on the ${header[0]} header`);}diff --git a/src/lib/jmap/mailboxes.ts b/src/lib/jmap/mailboxes.tsindex b0f9317..974c054 100644--- a/src/lib/jmap/mailboxes.ts+++ b/src/lib/jmap/mailboxes.ts@@ -33,7 +33,7 @@ async function loadCounts(ctx: JmapContext, mailboxIds: string[]): Promise<Map<sstatus: messages.status,folderId: messages.folderId,total: count(),- unread: sql<number>`sum(case when ${messages.read} = 0 and ${messages.direction} = 'inbound' then 1 else 0 end)`,+ unread: sql<number>`sum(case when not ${messages.read} and ${messages.direction} = 'inbound' then 1 else 0 end)`,}).from(messages).where(inArray(messages.mailboxId, mailboxIds))diff --git a/src/lib/migrations/bundle-mysql.json b/src/lib/migrations/bundle-mysql.jsonnew file mode 100644index 0000000..9d115eb--- /dev/null+++ b/src/lib/migrations/bundle-mysql.json@@ -0,0 +1,246 @@+{+ "migrations": [+ {+ "name": "0000_baseline.sql",+ "statements": [+ "CREATE TABLE `agent_chat_messages` (\n\t`id` varchar(191) NOT NULL,\n\t`conversation_id` varchar(191) NOT NULL,\n\t`role` varchar(64) NOT NULL,\n\t`content` longtext NOT NULL,\n\t`tool_name` longtext,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `agent_chat_messages_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `agent_conversations` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`title` longtext NOT NULL DEFAULT ('New conversation'),\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `agent_conversations_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `agent_draft_metadata` (\n\t`draft_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`origin` varchar(64) NOT NULL,\n\t`source_message_id` varchar(191),\n\t`revision` bigint NOT NULL DEFAULT 1,\n\t`human_edited_at` bigint,\n\t`scheduled_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `agent_draft_metadata_draft_id` PRIMARY KEY(`draft_id`)\n);",+ "CREATE TABLE `agent_jobs` (\n\t`id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`source_message_id` varchar(191) NOT NULL,\n\t`reviewer_user_id` varchar(191) NOT NULL,\n\t`status` varchar(64) NOT NULL DEFAULT 'pending',\n\t`attempts` bigint NOT NULL DEFAULT 0,\n\t`next_attempt_at` bigint NOT NULL,\n\t`lease_until` bigint,\n\t`draft_id` varchar(191),\n\t`reason` longtext,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `agent_jobs_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `agent_jobs_source_idx` UNIQUE(`mailbox_id`,`source_message_id`)\n);",+ "CREATE TABLE `agent_send_approvals` (\n\t`id` varchar(191) NOT NULL,\n\t`draft_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`request_key_id` varchar(191),\n\t`revision` bigint NOT NULL,\n\t`payload_hash` longtext NOT NULL,\n\t`status` varchar(64) NOT NULL DEFAULT 'pending',\n\t`claimed_at` bigint,\n\t`message_id` longtext,\n\t`expires_at` bigint NOT NULL,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `agent_send_approvals_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `ai_usage` (\n\t`id` varchar(191) NOT NULL,\n\t`created_at` bigint NOT NULL,\n\t`provider` longtext NOT NULL,\n\t`model` longtext NOT NULL,\n\t`source` longtext NOT NULL,\n\t`input_tokens` bigint,\n\t`output_tokens` bigint,\n\t`cost_usd_micros` bigint,\n\tCONSTRAINT `ai_usage_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `api_keys` (\n\t`id` varchar(191) NOT NULL,\n\t`kind` varchar(64) NOT NULL DEFAULT 'legacy',\n\t`user_id` varchar(191) NOT NULL,\n\t`name` longtext NOT NULL,\n\t`prefix` longtext NOT NULL,\n\t`key_hash` longtext NOT NULL,\n\t`scopes` longtext NOT NULL,\n\t`mailbox_scope_enabled` boolean NOT NULL DEFAULT false,\n\t`created_at` bigint NOT NULL,\n\t`last_used_at` bigint,\n\tCONSTRAINT `api_keys_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `app_settings` (\n\t`id` varchar(191) NOT NULL,\n\t`app_name` longtext NOT NULL DEFAULT ('Mailflare'),\n\t`outbound_attachment_max_mb` bigint NOT NULL DEFAULT 25,\n\t`drive_storage_limit_bytes` bigint,\n\t`resend_api_key` longtext,\n\t`aws_config` longtext,\n\t`ses_receiving` longtext,\n\t`resend_webhook_id` longtext,\n\t`resend_webhook_secret` longtext,\n\t`icon_key` longtext,\n\t`agent_enabled` boolean NOT NULL DEFAULT true,\n\t`agent_provider` varchar(64),\n\t`agent_preset` varchar(64),\n\t`agent_base_url` longtext,\n\t`agent_api_key` longtext,\n\t`agent_model` longtext,\n\t`agent_model_rates` longtext,\n\t`spamhaus_dqs_key` longtext,\n\t`abusech_auth_key` longtext,\n\t`spam_domain_age_check` boolean NOT NULL DEFAULT true,\n\t`spam_brands` longtext,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `app_settings_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `audit_logs` (\n\t`id` varchar(191) NOT NULL,\n\t`actor_user_id` varchar(191),\n\t`target_user_id` varchar(191),\n\t`mailbox_id` varchar(191),\n\t`message_id` varchar(191),\n\t`action` longtext NOT NULL,\n\t`metadata` longtext,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `audit_logs_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `auto_reply_deliveries` (\n\t`id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`recipient` varchar(320) NOT NULL,\n\t`sent_at` bigint NOT NULL,\n\tCONSTRAINT `auto_reply_deliveries_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `auto_reply_deliveries_mailbox_recipient_idx` UNIQUE(`mailbox_id`,`recipient`)\n);",+ "CREATE TABLE `backup_settings` (\n\t`id` varchar(191) NOT NULL,\n\t`enabled` boolean NOT NULL DEFAULT true,\n\t`schedule_type` varchar(64) NOT NULL DEFAULT 'daily',\n\t`schedule_value` bigint,\n\t`retention_enabled` boolean NOT NULL DEFAULT false,\n\t`retention_days` bigint NOT NULL DEFAULT 30,\n\t`excluded_table_groups` longtext NOT NULL DEFAULT ('[]'),\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `backup_settings_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `backups` (\n\t`id` varchar(191) NOT NULL,\n\t`status` varchar(64) NOT NULL DEFAULT 'queued',\n\t`trigger` varchar(64) NOT NULL,\n\t`r2_key` longtext,\n\t`filename` longtext,\n\t`size` bigint,\n\t`error` longtext,\n\t`created_by_user_id` varchar(191),\n\t`created_at` bigint NOT NULL,\n\t`started_at` bigint,\n\t`completed_at` bigint,\n\tCONSTRAINT `backups_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `booking_events` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`name` longtext NOT NULL,\n\t`slug` varchar(191) NOT NULL DEFAULT '',\n\t`description` longtext NOT NULL DEFAULT (''),\n\t`color` longtext NOT NULL DEFAULT ('#2563eb'),\n\t`host_ids` longtext NOT NULL DEFAULT ('[]'),\n\t`duration_minutes` bigint NOT NULL,\n\t`location` longtext NOT NULL DEFAULT (''),\n\t`weekdays` longtext NOT NULL DEFAULT ('[1,2,3,4,5]'),\n\t`start_time` longtext NOT NULL DEFAULT ('09:00'),\n\t`end_time` longtext NOT NULL DEFAULT ('17:00'),\n\t`time_ranges` longtext NOT NULL DEFAULT ('[{\"startTime\":\"09:00\",\"endTime\":\"17:00\"}]'),\n\t`time_zone` longtext NOT NULL DEFAULT ('UTC'),\n\t`enabled` boolean NOT NULL DEFAULT true,\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `booking_events_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `booking_events_user_slug_idx` UNIQUE(`user_id`,`slug`)\n);",+ "CREATE TABLE `calendar_events` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191),\n\t`title` longtext NOT NULL,\n\t`description` longtext NOT NULL DEFAULT (''),\n\t`location` longtext NOT NULL DEFAULT (''),\n\t`attendees` longtext NOT NULL DEFAULT ('[]'),\n\t`color` longtext NOT NULL DEFAULT ('blue'),\n\t`repeat` varchar(64) NOT NULL DEFAULT 'none',\n\t`repeat_days` longtext NOT NULL DEFAULT ('[]'),\n\t`repeat_anchor_day` bigint,\n\t`repeat_until` bigint,\n\t`excluded_occurrences` longtext NOT NULL DEFAULT ('[]'),\n\t`time_zone` longtext,\n\t`starts_at` bigint NOT NULL,\n\t`ends_at` bigint NOT NULL,\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `calendar_events_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `contacts` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`email` varchar(320) NOT NULL,\n\t`display_name` longtext,\n\t`avatar_key` longtext,\n\t`source` varchar(64) NOT NULL DEFAULT 'inbound',\n\t`blocked` boolean NOT NULL DEFAULT false,\n\t`remote_content_allowed` boolean NOT NULL DEFAULT false,\n\t`last_seen_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `contacts_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `contacts_user_email_idx` UNIQUE(`user_id`,`email`)\n);",+ "CREATE TABLE `domain_tracking_hosts` (\n\t`domain_id` varchar(191) NOT NULL,\n\t`hostname` varchar(255) NOT NULL,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `domain_tracking_hosts_domain_id` PRIMARY KEY(`domain_id`),\n\tCONSTRAINT `domain_tracking_hosts_hostname_idx` UNIQUE(`hostname`)\n);",+ "CREATE TABLE `domains` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`hostname` varchar(255) NOT NULL,\n\t`zone_id` longtext NOT NULL,\n\t`status` varchar(64) NOT NULL DEFAULT 'pending',\n\t`routing_status` longtext,\n\t`sending_subdomain_tag` longtext,\n\t`sending_provider` varchar(64) NOT NULL DEFAULT 'none',\n\t`receiving_provider` varchar(64) NOT NULL DEFAULT 'cloudflare',\n\t`sending_requested` boolean NOT NULL DEFAULT false,\n\t`sending_enabled` boolean NOT NULL DEFAULT false,\n\t`routing_enabled` boolean NOT NULL DEFAULT false,\n\t`dns_skipped` boolean NOT NULL DEFAULT false,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `domains_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `domains_hostname_idx` UNIQUE(`hostname`)\n);",+ "CREATE TABLE `drive_items` (\n\t`id` varchar(191) NOT NULL,\n\t`owner_id` varchar(191) NOT NULL,\n\t`parent_id` varchar(191),\n\t`kind` varchar(64) NOT NULL,\n\t`name` longtext NOT NULL,\n\t`r2_key` longtext,\n\t`size` bigint NOT NULL DEFAULT 0,\n\t`content_type` longtext NOT NULL DEFAULT ('application/octet-stream'),\n\t`upload_id` longtext,\n\t`upload_part_size` bigint,\n\t`upload_fingerprint` longtext,\n\t`link_token` varchar(191),\n\t`trashed_at` bigint,\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `drive_items_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `drive_items_link_token_idx` UNIQUE(`link_token`)\n);",+ "CREATE TABLE `drive_shares` (\n\t`id` varchar(191) NOT NULL,\n\t`item_id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`role` varchar(64) NOT NULL DEFAULT 'view',\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `drive_shares_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `drive_shares_item_user_idx` UNIQUE(`item_id`,`user_id`)\n);",+ "CREATE TABLE `drive_upload_parts` (\n\t`item_id` varchar(191) NOT NULL,\n\t`part_number` bigint NOT NULL,\n\t`etag` longtext NOT NULL,\n\tCONSTRAINT `drive_upload_parts_idx` UNIQUE(`item_id`,`part_number`)\n);",+ "CREATE TABLE `email_templates` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`name` longtext NOT NULL,\n\t`subject` longtext NOT NULL DEFAULT (''),\n\t`text_body` longtext NOT NULL DEFAULT (''),\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `email_templates_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `folders` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`name` varchar(255) NOT NULL,\n\t`color` longtext NOT NULL DEFAULT ('#2563eb'),\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `folders_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `folders_mailbox_name_idx` UNIQUE(`mailbox_id`,`name`)\n);",+ "CREATE TABLE `follow_ups` (\n\t`id` varchar(191) NOT NULL,\n\t`message_id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`due_at` bigint NOT NULL,\n\t`status` varchar(64) NOT NULL DEFAULT 'pending',\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `follow_ups_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `follow_ups_message_idx` UNIQUE(`message_id`)\n);",+ "CREATE TABLE `import_jobs` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`kind` varchar(64) NOT NULL,\n\t`label` longtext NOT NULL,\n\t`status` varchar(64) NOT NULL DEFAULT 'queued',\n\t`total` bigint NOT NULL DEFAULT 0,\n\t`processed` bigint NOT NULL DEFAULT 0,\n\t`imported` bigint NOT NULL DEFAULT 0,\n\t`skipped` bigint NOT NULL DEFAULT 0,\n\t`spec` longtext NOT NULL,\n\t`cursor` longtext NOT NULL DEFAULT ('{}'),\n\t`errors` longtext NOT NULL DEFAULT ('[]'),\n\t`error_count` bigint NOT NULL DEFAULT 0,\n\t`error` longtext,\n\t`created_at` bigint NOT NULL,\n\t`started_at` bigint,\n\t`updated_at` bigint NOT NULL,\n\t`finished_at` bigint,\n\tCONSTRAINT `import_jobs_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `jmap_change_floor` (\n\t`id` bigint NOT NULL,\n\t`seq` bigint NOT NULL DEFAULT 0,\n\tCONSTRAINT `jmap_change_floor_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `jmap_changes` (\n\t`seq` bigint AUTO_INCREMENT NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`object_type` varchar(64) NOT NULL,\n\t`object_id` longtext NOT NULL,\n\t`thread_id` longtext,\n\t`change` varchar(64) NOT NULL,\n\t`created_at` bigint NOT NULL DEFAULT (unix_timestamp()),\n\tCONSTRAINT `jmap_changes_seq` PRIMARY KEY(`seq`)\n);",+ "CREATE TABLE `jmap_mailbox_revisions` (\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`revision` bigint NOT NULL DEFAULT 0,\n\tCONSTRAINT `jmap_mailbox_revisions_mailbox_id` PRIMARY KEY(`mailbox_id`)\n);",+ "CREATE TABLE `license_settings` (\n\t`id` varchar(191) NOT NULL,\n\t`instance_id` varchar(191) NOT NULL,\n\t`instance_url` longtext,\n\t`license_key_hash` longtext,\n\t`plan` varchar(64) NOT NULL DEFAULT 'community',\n\t`state` varchar(64) NOT NULL DEFAULT 'inactive',\n\t`features` longtext NOT NULL DEFAULT ('[]'),\n\t`seat_limit` bigint DEFAULT 1,\n\t`activated_at` bigint,\n\t`validated_at` bigint,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `license_settings_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `license_settings_instance_id_unique` UNIQUE(`instance_id`)\n);",+ "CREATE TABLE `login_challenges` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`token_hash` varchar(191) NOT NULL,\n\t`expires_at` bigint NOT NULL,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `login_challenges_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `login_challenges_token_hash_unique` UNIQUE(`token_hash`)\n);",+ "CREATE TABLE `mailbox_access` (\n\t`id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`permission` varchar(64) NOT NULL DEFAULT 'read_only',\n\t`created_by_user_id` varchar(191),\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `mailbox_access_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `mailbox_access_mailbox_user_idx` UNIQUE(`mailbox_id`,`user_id`)\n);",+ "CREATE TABLE `mailbox_agent_settings` (\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`enabled` boolean NOT NULL DEFAULT false,\n\t`model_id` longtext,\n\t`auto_draft_enabled` boolean NOT NULL DEFAULT false,\n\t`reviewer_user_id` varchar(191),\n\t`instructions` longtext NOT NULL DEFAULT (''),\n\t`daily_limit` bigint NOT NULL DEFAULT 25,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `mailbox_agent_settings_mailbox_id` PRIMARY KEY(`mailbox_id`)\n);",+ "CREATE TABLE `mailbox_aliases` (\n\t`id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`domain_id` varchar(191) NOT NULL,\n\t`local_part` varchar(191) NOT NULL,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `mailbox_aliases_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `mailbox_aliases_address_idx` UNIQUE(`domain_id`,`local_part`)\n);",+ "CREATE TABLE `mailboxes` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`domain_id` varchar(191) NOT NULL,\n\t`local_part` varchar(191) NOT NULL,\n\t`display_name` longtext,\n\t`signature` longtext,\n\t`auto_reply_enabled` boolean NOT NULL DEFAULT false,\n\t`auto_reply_subject` longtext NOT NULL DEFAULT ('Out of office'),\n\t`auto_reply_body` longtext NOT NULL DEFAULT (''),\n\t`avatar_key` longtext,\n\t`type` varchar(64) NOT NULL DEFAULT 'personal',\n\t`use_all_domains` boolean NOT NULL DEFAULT true,\n\t`disabled` boolean NOT NULL DEFAULT false,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `mailboxes_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `mailboxes_address_idx` UNIQUE(`domain_id`,`local_part`)\n);",+ "CREATE TABLE `mcp_key_mailboxes` (\n\t`key_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\tCONSTRAINT `mcp_key_mailbox_idx` UNIQUE(`key_id`,`mailbox_id`)\n);",+ "CREATE TABLE `message_attachments` (\n\t`id` varchar(191) NOT NULL,\n\t`message_id` varchar(191) NOT NULL,\n\t`filename` longtext NOT NULL,\n\t`content_type` longtext NOT NULL,\n\t`size` bigint NOT NULL,\n\t`disposition` varchar(64) NOT NULL DEFAULT 'attachment',\n\t`content_id` longtext,\n\t`r2_key` varchar(512) NOT NULL,\n\t`trashed_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `message_attachments_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `message_attachments_r2_key_unique` UNIQUE(`r2_key`)\n);",+ "CREATE TABLE `message_opens` (\n\t`id` varchar(191) NOT NULL,\n\t`token` varchar(191) NOT NULL,\n\t`opened_at` bigint NOT NULL,\n\t`client` longtext,\n\t`device` longtext,\n\t`country` longtext,\n\t`city` longtext,\n\t`automated` boolean NOT NULL DEFAULT false,\n\tCONSTRAINT `message_opens_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `message_tracking` (\n\t`token` varchar(191) NOT NULL,\n\t`message_id` varchar(191) NOT NULL,\n\t`open_count` bigint NOT NULL DEFAULT 0,\n\t`first_opened_at` bigint,\n\t`last_opened_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `message_tracking_token` PRIMARY KEY(`token`),\n\tCONSTRAINT `message_tracking_message_idx` UNIQUE(`message_id`)\n);",+ "CREATE TABLE `messages` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191),\n\t`direction` varchar(64) NOT NULL,\n\t`provider_message_id` varchar(512),\n\t`folder_id` varchar(191),\n\t`from_addr` longtext NOT NULL,\n\t`to_addr` longtext NOT NULL,\n\t`cc_addr` longtext,\n\t`bcc_addr` longtext,\n\t`reply_to` longtext,\n\t`subject` longtext,\n\t`snippet` longtext,\n\t`text_body` longtext,\n\t`html_body` longtext,\n\t`raw_r2_key` varchar(512),\n\t`status` varchar(191) NOT NULL DEFAULT 'received',\n\t`read` boolean NOT NULL DEFAULT false,\n\t`starred` boolean NOT NULL DEFAULT false,\n\t`snoozed_until` bigint,\n\t`thread_id` varchar(512),\n\t`in_reply_to` longtext,\n\t`references_header` longtext,\n\t`spam_score` bigint,\n\t`spam_verdict` varchar(64),\n\t`spam_signals` longtext,\n\t`spam_analyzed_at` bigint,\n\t`spam_analysis_error` longtext,\n\t`trashed_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `messages_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `mfa_recovery_codes` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`code_hash` varchar(191) NOT NULL,\n\t`used_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `mfa_recovery_codes_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `mfa_recovery_codes_code_hash_unique` UNIQUE(`code_hash`)\n);",+ "CREATE TABLE `outbound_jobs` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`message_id` varchar(191),\n\t`status` varchar(64) NOT NULL DEFAULT 'queued',\n\t`payload` longtext NOT NULL,\n\t`error` longtext,\n\t`scheduled_at` bigint,\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `outbound_jobs_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `password_reset_tokens` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`token_hash` varchar(191) NOT NULL,\n\t`expires_at` bigint NOT NULL,\n\t`used_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `password_reset_tokens_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `password_reset_tokens_token_hash_unique` UNIQUE(`token_hash`)\n);",+ "CREATE TABLE `push_devices` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`api_key_id` varchar(191) NOT NULL,\n\t`platform` varchar(64) NOT NULL,\n\t`token` varchar(191) NOT NULL,\n\t`environment` varchar(64) NOT NULL DEFAULT 'production',\n\t`topic` longtext NOT NULL,\n\t`public_key` longtext,\n\t`previews` boolean NOT NULL DEFAULT true,\n\t`client_ref` longtext,\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `push_devices_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `push_devices_platform_token_user_idx` UNIQUE(`platform`,`token`,`user_id`)\n);",+ "CREATE TABLE `push_subscriptions` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`session_id` varchar(191) NOT NULL,\n\t`endpoint` varchar(512) NOT NULL,\n\t`p256dh` longtext NOT NULL,\n\t`auth` longtext NOT NULL,\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `push_subscriptions_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `push_subscriptions_endpoint_idx` UNIQUE(`endpoint`)\n);",+ "CREATE TABLE `routing_rules` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`domain_id` varchar(191) NOT NULL,\n\t`scope` varchar(64) NOT NULL DEFAULT 'mailbox',\n\t`name` longtext,\n\t`enabled` boolean NOT NULL DEFAULT true,\n\t`pattern` longtext NOT NULL,\n\t`match_field` varchar(64) NOT NULL DEFAULT 'email',\n\t`match_operator` varchar(64) NOT NULL DEFAULT 'contains',\n\t`match_value` longtext NOT NULL DEFAULT (''),\n\t`mailbox_id` varchar(191),\n\t`folder_id` varchar(191),\n\t`action` varchar(64) NOT NULL DEFAULT 'store',\n\t`forward_to` longtext,\n\t`keep_copy` boolean NOT NULL DEFAULT false,\n\t`reject_reason` longtext,\n\t`priority` bigint NOT NULL DEFAULT 0,\n\t`last_matched_at` bigint,\n\t`match_count` bigint NOT NULL DEFAULT 0,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `routing_rules_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `sessions` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`token_hash` varchar(191) NOT NULL,\n\t`expires_at` bigint NOT NULL,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `sessions_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `sessions_token_hash_unique` UNIQUE(`token_hash`)\n);",+ "CREATE TABLE `shared_attachment_links` (\n\t`id` varchar(191) NOT NULL,\n\t`attachment_id` varchar(191) NOT NULL,\n\t`expires_at` bigint NOT NULL,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `shared_attachment_links_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `shared_attachment_links_attachment_id_unique` UNIQUE(`attachment_id`)\n);",+ "CREATE TABLE `spam_feedback` (\n\t`message_id` varchar(191) NOT NULL,\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`actor_user_id` varchar(191),\n\t`classification` varchar(64) NOT NULL,\n\t`training_tokens` longtext NOT NULL,\n\t`reputation_keys` longtext NOT NULL,\n\t`tokenizer_version` bigint NOT NULL DEFAULT 1,\n\t`created_at` bigint NOT NULL,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `spam_feedback_message_id` PRIMARY KEY(`message_id`)\n);",+ "CREATE TABLE `spam_reputation` (\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`type` varchar(64) NOT NULL,\n\t`key` varchar(191) NOT NULL,\n\t`messages_seen` bigint NOT NULL DEFAULT 0,\n\t`spam_count` bigint NOT NULL DEFAULT 0,\n\t`ham_count` bigint NOT NULL DEFAULT 0,\n\t`first_seen_at` bigint NOT NULL,\n\t`last_seen_at` bigint NOT NULL,\n\tCONSTRAINT `spam_reputation_mailbox_type_key_idx` UNIQUE(`mailbox_id`,`type`,`key`)\n);",+ "CREATE TABLE `spam_token_stats` (\n\t`mailbox_id` varchar(191) NOT NULL,\n\t`token` varchar(191) NOT NULL,\n\t`spam_count` bigint NOT NULL DEFAULT 0,\n\t`ham_count` bigint NOT NULL DEFAULT 0,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `spam_token_stats_mailbox_token_idx` UNIQUE(`mailbox_id`,`token`)\n);",+ "CREATE TABLE `user_compose_preferences` (\n\t`user_id` varchar(191) NOT NULL,\n\t`track_opens_default` boolean NOT NULL DEFAULT false,\n\t`undo_send_seconds` bigint NOT NULL DEFAULT 15,\n\t`updated_at` bigint NOT NULL,\n\tCONSTRAINT `user_compose_preferences_user_id` PRIMARY KEY(`user_id`)\n);",+ "CREATE TABLE `users` (\n\t`id` varchar(191) NOT NULL,\n\t`email` varchar(320) NOT NULL,\n\t`reset_email` longtext,\n\t`forwarding_email` longtext,\n\t`password_hash` longtext NOT NULL,\n\t`name` longtext NOT NULL,\n\t`booking_username` varchar(191),\n\t`time_zone` longtext,\n\t`avatar_key` longtext,\n\t`role` varchar(64) NOT NULL DEFAULT 'user',\n\t`is_primary_admin` boolean NOT NULL DEFAULT false,\n\t`disabled` boolean NOT NULL DEFAULT false,\n\t`can_manage_mailboxes` boolean NOT NULL DEFAULT false,\n\t`can_manage_domains` boolean NOT NULL DEFAULT false,\n\t`can_manage_users` boolean NOT NULL DEFAULT false,\n\t`keyboard_shortcuts_enabled` boolean NOT NULL DEFAULT true,\n\t`spam_protection_enabled` boolean NOT NULL DEFAULT true,\n\t`trash_retention_days` bigint,\n\t`show_full_recipient_addresses` boolean NOT NULL DEFAULT false,\n\t`remote_content_mode` varchar(64) NOT NULL DEFAULT 'allow',\n\t`totp_secret` longtext,\n\t`totp_enabled` boolean NOT NULL DEFAULT false,\n\t`totp_confirmed_at` bigint,\n\t`last_sign_in_at` bigint,\n\t`deleted_at` bigint,\n\t`created_by_user_id` varchar(191),\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `users_id` PRIMARY KEY(`id`),\n\tCONSTRAINT `users_email_unique` UNIQUE(`email`),\n\tCONSTRAINT `users_booking_username_idx` UNIQUE(`booking_username`)\n);",+ "CREATE TABLE `webhook_deliveries` (\n\t`id` varchar(191) NOT NULL,\n\t`webhook_id` varchar(191) NOT NULL,\n\t`event_type` longtext NOT NULL,\n\t`payload` longtext NOT NULL,\n\t`status` varchar(191) NOT NULL DEFAULT 'pending',\n\t`attempts` bigint NOT NULL DEFAULT 0,\n\t`response_status` bigint,\n\t`error` longtext,\n\t`duration_ms` bigint,\n\t`last_attempt_at` bigint,\n\t`next_retry_at` bigint,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `webhook_deliveries_id` PRIMARY KEY(`id`)\n);",+ "CREATE TABLE `webhooks` (\n\t`id` varchar(191) NOT NULL,\n\t`user_id` varchar(191) NOT NULL,\n\t`description` longtext,\n\t`url` longtext NOT NULL,\n\t`secret` longtext NOT NULL,\n\t`events` longtext NOT NULL,\n\t`enabled` boolean NOT NULL DEFAULT true,\n\t`max_attempts` bigint NOT NULL DEFAULT 5,\n\t`created_at` bigint NOT NULL,\n\tCONSTRAINT `webhooks_id` PRIMARY KEY(`id`)\n);",+ "ALTER TABLE `agent_chat_messages` ADD CONSTRAINT `agent_chat_messages_conversation_id_agent_conversations_id_fk` FOREIGN KEY (`conversation_id`) REFERENCES `agent_conversations`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_conversations` ADD CONSTRAINT `agent_conversations_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_conversations` ADD CONSTRAINT `agent_conversations_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_draft_metadata` ADD CONSTRAINT `agent_draft_metadata_draft_id_messages_id_fk` FOREIGN KEY (`draft_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_draft_metadata` ADD CONSTRAINT `agent_draft_metadata_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_draft_metadata` ADD CONSTRAINT `agent_draft_metadata_source_message_id_messages_id_fk` FOREIGN KEY (`source_message_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_source_message_id_messages_id_fk` FOREIGN KEY (`source_message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_reviewer_user_id_users_id_fk` FOREIGN KEY (`reviewer_user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_jobs` ADD CONSTRAINT `agent_jobs_draft_id_messages_id_fk` FOREIGN KEY (`draft_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_draft_id_messages_id_fk` FOREIGN KEY (`draft_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `agent_send_approvals` ADD CONSTRAINT `agent_send_approvals_request_key_id_api_keys_id_fk` FOREIGN KEY (`request_key_id`) REFERENCES `api_keys`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `api_keys` ADD CONSTRAINT `api_keys_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_actor_user_id_users_id_fk` FOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_target_user_id_users_id_fk` FOREIGN KEY (`target_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `auto_reply_deliveries` ADD CONSTRAINT `auto_reply_deliveries_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `backups` ADD CONSTRAINT `backups_created_by_user_id_users_id_fk` FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `booking_events` ADD CONSTRAINT `booking_events_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `calendar_events` ADD CONSTRAINT `calendar_events_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `calendar_events` ADD CONSTRAINT `calendar_events_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `contacts` ADD CONSTRAINT `contacts_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `domain_tracking_hosts` ADD CONSTRAINT `domain_tracking_hosts_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `domains` ADD CONSTRAINT `domains_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `drive_items` ADD CONSTRAINT `drive_items_owner_id_users_id_fk` FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `drive_shares` ADD CONSTRAINT `drive_shares_item_id_drive_items_id_fk` FOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `drive_shares` ADD CONSTRAINT `drive_shares_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `drive_upload_parts` ADD CONSTRAINT `drive_upload_parts_item_id_drive_items_id_fk` FOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `email_templates` ADD CONSTRAINT `email_templates_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `folders` ADD CONSTRAINT `folders_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `folders` ADD CONSTRAINT `folders_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `follow_ups` ADD CONSTRAINT `follow_ups_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `follow_ups` ADD CONSTRAINT `follow_ups_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `import_jobs` ADD CONSTRAINT `import_jobs_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `import_jobs` ADD CONSTRAINT `import_jobs_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `login_challenges` ADD CONSTRAINT `login_challenges_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mailbox_access` ADD CONSTRAINT `mailbox_access_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mailbox_access` ADD CONSTRAINT `mailbox_access_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mailbox_access` ADD CONSTRAINT `mailbox_access_created_by_user_id_users_id_fk` FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `mailbox_agent_settings` ADD CONSTRAINT `mailbox_agent_settings_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mailbox_agent_settings` ADD CONSTRAINT `mailbox_agent_settings_reviewer_user_id_users_id_fk` FOREIGN KEY (`reviewer_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `mailbox_aliases` ADD CONSTRAINT `mailbox_aliases_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mailbox_aliases` ADD CONSTRAINT `mailbox_aliases_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mailboxes` ADD CONSTRAINT `mailboxes_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mailboxes` ADD CONSTRAINT `mailboxes_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mcp_key_mailboxes` ADD CONSTRAINT `mcp_key_mailboxes_key_id_api_keys_id_fk` FOREIGN KEY (`key_id`) REFERENCES `api_keys`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `mcp_key_mailboxes` ADD CONSTRAINT `mcp_key_mailboxes_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `message_attachments` ADD CONSTRAINT `message_attachments_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `message_opens` ADD CONSTRAINT `message_opens_token_message_tracking_token_fk` FOREIGN KEY (`token`) REFERENCES `message_tracking`(`token`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `message_tracking` ADD CONSTRAINT `message_tracking_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `messages` ADD CONSTRAINT `messages_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `messages` ADD CONSTRAINT `messages_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `messages` ADD CONSTRAINT `messages_folder_id_folders_id_fk` FOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `mfa_recovery_codes` ADD CONSTRAINT `mfa_recovery_codes_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `outbound_jobs` ADD CONSTRAINT `outbound_jobs_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `outbound_jobs` ADD CONSTRAINT `outbound_jobs_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `password_reset_tokens` ADD CONSTRAINT `password_reset_tokens_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `push_devices` ADD CONSTRAINT `push_devices_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `push_devices` ADD CONSTRAINT `push_devices_api_key_id_api_keys_id_fk` FOREIGN KEY (`api_key_id`) REFERENCES `api_keys`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `push_subscriptions` ADD CONSTRAINT `push_subscriptions_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `push_subscriptions` ADD CONSTRAINT `push_subscriptions_session_id_sessions_id_fk` FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_domain_id_domains_id_fk` FOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `routing_rules` ADD CONSTRAINT `routing_rules_folder_id_folders_id_fk` FOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `sessions` ADD CONSTRAINT `sessions_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `shared_attachment_links` ADD CONSTRAINT `shared_attachment_links_attachment_id_message_attachments_id_fk` FOREIGN KEY (`attachment_id`) REFERENCES `message_attachments`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `spam_feedback` ADD CONSTRAINT `spam_feedback_message_id_messages_id_fk` FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `spam_feedback` ADD CONSTRAINT `spam_feedback_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `spam_feedback` ADD CONSTRAINT `spam_feedback_actor_user_id_users_id_fk` FOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `spam_reputation` ADD CONSTRAINT `spam_reputation_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `spam_token_stats` ADD CONSTRAINT `spam_token_stats_mailbox_id_mailboxes_id_fk` FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `user_compose_preferences` ADD CONSTRAINT `user_compose_preferences_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `users` ADD CONSTRAINT `users_created_by_user_id_users_id_fk` FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE `webhook_deliveries` ADD CONSTRAINT `webhook_deliveries_webhook_id_webhooks_id_fk` FOREIGN KEY (`webhook_id`) REFERENCES `webhooks`(`id`) ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE `webhooks` ADD CONSTRAINT `webhooks_user_id_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;",+ "CREATE INDEX `agent_chat_messages_conversation_idx` ON `agent_chat_messages` (`conversation_id`,`created_at`);",+ "CREATE INDEX `agent_conversations_owner_idx` ON `agent_conversations` (`user_id`,`mailbox_id`,`updated_at`);",+ "CREATE INDEX `agent_conversations_mailbox_idx` ON `agent_conversations` (`mailbox_id`);",+ "CREATE INDEX `agent_draft_meta_source_msg_idx` ON `agent_draft_metadata` (`source_message_id`);",+ "CREATE INDEX `agent_draft_metadata_mailbox_idx` ON `agent_draft_metadata` (`mailbox_id`);",+ "CREATE INDEX `agent_jobs_due_idx` ON `agent_jobs` (`status`,`next_attempt_at`);",+ "CREATE INDEX `agent_jobs_source_message_idx` ON `agent_jobs` (`source_message_id`);",+ "CREATE INDEX `agent_jobs_draft_idx` ON `agent_jobs` (`draft_id`);",+ "CREATE INDEX `agent_jobs_reviewer_idx` ON `agent_jobs` (`reviewer_user_id`);",+ "CREATE INDEX `agent_send_approvals_user_idx` ON `agent_send_approvals` (`user_id`,`status`);",+ "CREATE INDEX `agent_send_approvals_delivery_idx` ON `agent_send_approvals` (`draft_id`);",+ "CREATE INDEX `agent_send_approvals_request_key_idx` ON `agent_send_approvals` (`request_key_id`);",+ "CREATE INDEX `agent_send_approvals_mailbox_idx` ON `agent_send_approvals` (`mailbox_id`);",+ "CREATE INDEX `agent_send_approvals_draft_idx` ON `agent_send_approvals` (`draft_id`);",+ "CREATE INDEX `ai_usage_created_idx` ON `ai_usage` (`created_at`);",+ "CREATE INDEX `api_keys_user_idx` ON `api_keys` (`user_id`);",+ "CREATE INDEX `audit_logs_actor_idx` ON `audit_logs` (`actor_user_id`);",+ "CREATE INDEX `audit_logs_mailbox_idx` ON `audit_logs` (`mailbox_id`);",+ "CREATE INDEX `audit_logs_created_idx` ON `audit_logs` (`created_at`);",+ "CREATE INDEX `audit_logs_message_id_idx` ON `audit_logs` (`message_id`);",+ "CREATE INDEX `audit_logs_target_user_idx` ON `audit_logs` (`target_user_id`);",+ "CREATE INDEX `auto_reply_deliveries_sent_idx` ON `auto_reply_deliveries` (`sent_at`);",+ "CREATE INDEX `backups_created_idx` ON `backups` (`created_at`);",+ "CREATE INDEX `backups_status_idx` ON `backups` (`status`);",+ "CREATE INDEX `backups_created_by_idx` ON `backups` (`created_by_user_id`);",+ "CREATE INDEX `booking_events_user_idx` ON `booking_events` (`user_id`);",+ "CREATE INDEX `calendar_events_user_starts_idx` ON `calendar_events` (`user_id`,`starts_at`);",+ "CREATE INDEX `calendar_events_mailbox_idx` ON `calendar_events` (`mailbox_id`);",+ "CREATE INDEX `contacts_user_idx` ON `contacts` (`user_id`);",+ "CREATE INDEX `domains_user_idx` ON `domains` (`user_id`);",+ "CREATE INDEX `drive_items_owner_parent_idx` ON `drive_items` (`owner_id`,`parent_id`);",+ "CREATE INDEX `drive_shares_user_idx` ON `drive_shares` (`user_id`);",+ "CREATE INDEX `email_templates_user_idx` ON `email_templates` (`user_id`);",+ "CREATE INDEX `folders_user_idx` ON `folders` (`user_id`);",+ "CREATE INDEX `folders_mailbox_idx` ON `folders` (`mailbox_id`);",+ "CREATE INDEX `follow_ups_status_due_idx` ON `follow_ups` (`status`,`due_at`);",+ "CREATE INDEX `follow_ups_user_status_idx` ON `follow_ups` (`user_id`,`status`);",+ "CREATE INDEX `import_jobs_user_idx` ON `import_jobs` (`user_id`,`created_at`);",+ "CREATE INDEX `import_jobs_status_idx` ON `import_jobs` (`status`,`updated_at`);",+ "CREATE INDEX `jmap_changes_mailbox_seq_idx` ON `jmap_changes` (`mailbox_id`,`seq`);",+ "CREATE INDEX `login_challenges_user_idx` ON `login_challenges` (`user_id`);",+ "CREATE INDEX `mailbox_access_user_idx` ON `mailbox_access` (`user_id`);",+ "CREATE INDEX `mailbox_access_mailbox_idx` ON `mailbox_access` (`mailbox_id`);",+ "CREATE INDEX `mailbox_access_created_by_idx` ON `mailbox_access` (`created_by_user_id`);",+ "CREATE INDEX `mailbox_agent_settings_reviewer_idx` ON `mailbox_agent_settings` (`reviewer_user_id`);",+ "CREATE INDEX `mailbox_aliases_mailbox_idx` ON `mailbox_aliases` (`mailbox_id`);",+ "CREATE INDEX `mailboxes_user_idx` ON `mailboxes` (`user_id`);",+ "CREATE INDEX `mcp_key_mailboxes_mailbox_idx` ON `mcp_key_mailboxes` (`mailbox_id`);",+ "CREATE INDEX `message_attachments_message_idx` ON `message_attachments` (`message_id`);",+ "CREATE INDEX `message_opens_token_idx` ON `message_opens` (`token`,`opened_at`);",+ "CREATE INDEX `messages_user_created_idx` ON `messages` (`user_id`,`created_at`);",+ "CREATE INDEX `messages_mailbox_idx` ON `messages` (`mailbox_id`);",+ "CREATE INDEX `messages_folder_idx` ON `messages` (`folder_id`);",+ "CREATE INDEX `messages_thread_idx` ON `messages` (`mailbox_id`,`thread_id`);",+ "CREATE INDEX `messages_provider_message_idx` ON `messages` (`mailbox_id`,`provider_message_id`);",+ "CREATE INDEX `messages_raw_r2_key_idx` ON `messages` (`raw_r2_key`);",+ "CREATE INDEX `messages_trashed_at_idx` ON `messages` (`trashed_at`);",+ "CREATE INDEX `messages_inbox_page_idx` ON `messages` (`mailbox_id`,`status`,`folder_id`,`created_at`);",+ "CREATE INDEX `messages_thread_key_idx` ON `messages` (`mailbox_id`,`status`,`folder_id`,`created_at`);",+ "CREATE INDEX `messages_mailbox_thread_key_idx` ON `messages` (`mailbox_id`);",+ "CREATE INDEX `messages_nav_cover_idx` ON `messages` (`mailbox_id`,`status`,`folder_id`,`created_at`);",+ "CREATE INDEX `messages_counts_cover_idx` ON `messages` (`mailbox_id`,`folder_id`,`direction`,`status`,`read`,`starred`,`snoozed_until`);",+ "CREATE INDEX `messages_conv_cover_idx` ON `messages` (`mailbox_id`,`status`,`created_at`,`id`,`snoozed_until`);",+ "CREATE INDEX `mfa_recovery_codes_user_idx` ON `mfa_recovery_codes` (`user_id`);",+ "CREATE INDEX `outbound_jobs_user_idx` ON `outbound_jobs` (`user_id`);",+ "CREATE INDEX `outbound_jobs_message_idx` ON `outbound_jobs` (`message_id`);",+ "CREATE INDEX `password_reset_tokens_user_idx` ON `password_reset_tokens` (`user_id`);",+ "CREATE INDEX `push_devices_user_idx` ON `push_devices` (`user_id`);",+ "CREATE INDEX `push_devices_api_key_idx` ON `push_devices` (`api_key_id`);",+ "CREATE INDEX `push_subscriptions_user_idx` ON `push_subscriptions` (`user_id`);",+ "CREATE INDEX `push_subscriptions_session_idx` ON `push_subscriptions` (`session_id`);",+ "CREATE INDEX `routing_rules_domain_scope_idx` ON `routing_rules` (`domain_id`,`scope`,`enabled`);",+ "CREATE INDEX `routing_rules_mailbox_idx` ON `routing_rules` (`mailbox_id`);",+ "CREATE INDEX `routing_rules_priority_idx` ON `routing_rules` (`priority`);",+ "CREATE INDEX `routing_rules_user_idx` ON `routing_rules` (`user_id`);",+ "CREATE INDEX `routing_rules_folder_idx` ON `routing_rules` (`folder_id`);",+ "CREATE INDEX `sessions_user_idx` ON `sessions` (`user_id`);",+ "CREATE INDEX `spam_feedback_mailbox_idx` ON `spam_feedback` (`mailbox_id`);",+ "CREATE INDEX `spam_feedback_actor_user_idx` ON `spam_feedback` (`actor_user_id`);",+ "CREATE INDEX `spam_reputation_mailbox_idx` ON `spam_reputation` (`mailbox_id`);",+ "CREATE INDEX `spam_token_stats_mailbox_idx` ON `spam_token_stats` (`mailbox_id`);",+ "CREATE INDEX `users_created_by_idx` ON `users` (`created_by_user_id`);",+ "CREATE INDEX `webhook_deliveries_webhook_idx` ON `webhook_deliveries` (`webhook_id`,`created_at`);",+ "CREATE INDEX `webhook_deliveries_status_idx` ON `webhook_deliveries` (`status`);",+ "CREATE INDEX `webhooks_user_idx` ON `webhooks` (`user_id`);"+ ]+ },+ {+ "name": "0001_triggers_and_seeds.sql",+ "statements": [+ "INSERT IGNORE INTO backup_settings (id, enabled, schedule_type, retention_enabled, retention_days, updated_at)\nVALUES ('default', false, 'daily', false, 30, unix_timestamp());",+ "INSERT IGNORE INTO app_settings (id, app_name, updated_at)\nVALUES ('default', 'Mailflare', unix_timestamp());",+ "INSERT IGNORE INTO jmap_change_floor (id, seq) VALUES (1, 0);",+ "CREATE TRIGGER messages_trashed_at_bi BEFORE INSERT ON messages FOR EACH ROW\nBEGIN\n\tIF NEW.status IN ('trash', 'spam') THEN\n\t\tSET NEW.trashed_at = unix_timestamp();\n\tEND IF;\nEND;",+ "CREATE TRIGGER messages_trashed_at_bu BEFORE UPDATE ON messages FOR EACH ROW\nBEGIN\n\tIF (NEW.status IN ('trash', 'spam')) <> (OLD.status IN ('trash', 'spam')) THEN\n\t\tSET NEW.trashed_at = IF(NEW.status IN ('trash', 'spam'), unix_timestamp(), NULL);\n\tEND IF;\nEND;",+ "CREATE TRIGGER messages_jmap_ai AFTER INSERT ON messages FOR EACH ROW\nBEGIN\n\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)\n\t\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');\n\tEND IF;\nEND;",+ "CREATE TRIGGER messages_jmap_au AFTER UPDATE ON messages FOR EACH ROW\nBEGIN\n\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tEND IF;\n\tIF OLD.mailbox_id IS NOT NULL AND NOT (OLD.mailbox_id <=> NEW.mailbox_id) THEN\n\t\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tEND IF;\n\tIF OLD.mailbox_id <=> NEW.mailbox_id THEN\n\t\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)\n\t\t\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'updated');\n\t\tEND IF;\n\tELSE\n\t\tIF OLD.mailbox_id IS NOT NULL THEN\n\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)\n\t\t\tVALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');\n\t\tEND IF;\n\t\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)\n\t\t\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');\n\t\tEND IF;\n\tEND IF;\nEND;",+ "CREATE TRIGGER messages_jmap_ad AFTER DELETE ON messages FOR EACH ROW\nBEGIN\n\tIF OLD.mailbox_id IS NOT NULL THEN\n\t\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, `change`)\n\t\tVALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');\n\tEND IF;\nEND;",+ "CREATE TRIGGER folders_jmap_ai AFTER INSERT ON folders FOR EACH ROW\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (NEW.mailbox_id, 'mailbox', NEW.id, 'created');\nEND;",+ "CREATE TRIGGER folders_jmap_au AFTER UPDATE ON folders FOR EACH ROW\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tIF NOT (OLD.mailbox_id <=> NEW.mailbox_id) THEN\n\t\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');\n\tEND IF;\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`)\n\tVALUES (NEW.mailbox_id, 'mailbox', NEW.id, IF(OLD.mailbox_id <=> NEW.mailbox_id, 'updated', 'created'));\nEND;",+ "CREATE TRIGGER folders_jmap_ad AFTER DELETE ON folders FOR EACH ROW\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');\nEND;",+ "CREATE TRIGGER mailboxes_jmap_au AFTER UPDATE ON mailboxes FOR EACH ROW\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, `change`) VALUES (NEW.id, 'mailbox', NEW.id, 'updated');\nEND;",+ "CREATE TRIGGER mailbox_aliases_jmap_ai AFTER INSERT ON mailbox_aliases FOR EACH ROW\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\nEND;",+ "CREATE TRIGGER mailbox_aliases_jmap_au AFTER UPDATE ON mailbox_aliases FOR EACH ROW\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tIF NOT (OLD.mailbox_id <=> NEW.mailbox_id) THEN\n\t\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\n\tEND IF;\nEND;",+ "CREATE TRIGGER mailbox_aliases_jmap_ad AFTER DELETE ON mailbox_aliases FOR EACH ROW\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1) ON DUPLICATE KEY UPDATE revision = revision + 1;\nEND;"+ ]+ }+ ]+}diff --git a/src/lib/migrations/bundle-postgres.json b/src/lib/migrations/bundle-postgres.jsonnew file mode 100644index 0000000..f259805--- /dev/null+++ b/src/lib/migrations/bundle-postgres.json@@ -0,0 +1,267 @@+{+ "migrations": [+ {+ "name": "0000_baseline.sql",+ "statements": [+ "CREATE TABLE \"agent_chat_messages\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"conversation_id\" text NOT NULL,\n\t\"role\" text NOT NULL,\n\t\"content\" text NOT NULL,\n\t\"tool_name\" text,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"agent_conversations\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"title\" text DEFAULT 'New conversation' NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"agent_draft_metadata\" (\n\t\"draft_id\" text PRIMARY KEY NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"origin\" text NOT NULL,\n\t\"source_message_id\" text,\n\t\"revision\" bigint DEFAULT 1 NOT NULL,\n\t\"human_edited_at\" bigint,\n\t\"scheduled_at\" bigint,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"agent_jobs\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"source_message_id\" text NOT NULL,\n\t\"reviewer_user_id\" text NOT NULL,\n\t\"status\" text DEFAULT 'pending' NOT NULL,\n\t\"attempts\" bigint DEFAULT 0 NOT NULL,\n\t\"next_attempt_at\" bigint NOT NULL,\n\t\"lease_until\" bigint,\n\t\"draft_id\" text,\n\t\"reason\" text,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"agent_send_approvals\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"draft_id\" text NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"request_key_id\" text,\n\t\"revision\" bigint NOT NULL,\n\t\"payload_hash\" text NOT NULL,\n\t\"status\" text DEFAULT 'pending' NOT NULL,\n\t\"claimed_at\" bigint,\n\t\"message_id\" text,\n\t\"expires_at\" bigint NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"ai_usage\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"provider\" text NOT NULL,\n\t\"model\" text NOT NULL,\n\t\"source\" text NOT NULL,\n\t\"input_tokens\" bigint,\n\t\"output_tokens\" bigint,\n\t\"cost_usd_micros\" bigint\n);",+ "CREATE TABLE \"api_keys\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"kind\" text DEFAULT 'legacy' NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"prefix\" text NOT NULL,\n\t\"key_hash\" text NOT NULL,\n\t\"scopes\" text NOT NULL,\n\t\"mailbox_scope_enabled\" boolean DEFAULT false NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"last_used_at\" bigint\n);",+ "CREATE TABLE \"app_settings\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"app_name\" text DEFAULT 'Mailflare' NOT NULL,\n\t\"outbound_attachment_max_mb\" bigint DEFAULT 25 NOT NULL,\n\t\"drive_storage_limit_bytes\" bigint,\n\t\"resend_api_key\" text,\n\t\"aws_config\" text,\n\t\"ses_receiving\" text,\n\t\"resend_webhook_id\" text,\n\t\"resend_webhook_secret\" text,\n\t\"icon_key\" text,\n\t\"agent_enabled\" boolean DEFAULT true NOT NULL,\n\t\"agent_provider\" text,\n\t\"agent_preset\" text,\n\t\"agent_base_url\" text,\n\t\"agent_api_key\" text,\n\t\"agent_model\" text,\n\t\"agent_model_rates\" text,\n\t\"spamhaus_dqs_key\" text,\n\t\"abusech_auth_key\" text,\n\t\"spam_domain_age_check\" boolean DEFAULT true NOT NULL,\n\t\"spam_brands\" text,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"audit_logs\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"actor_user_id\" text,\n\t\"target_user_id\" text,\n\t\"mailbox_id\" text,\n\t\"message_id\" text,\n\t\"action\" text NOT NULL,\n\t\"metadata\" text,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"auto_reply_deliveries\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"recipient\" text NOT NULL,\n\t\"sent_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"backup_settings\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"enabled\" boolean DEFAULT true NOT NULL,\n\t\"schedule_type\" text DEFAULT 'daily' NOT NULL,\n\t\"schedule_value\" bigint,\n\t\"retention_enabled\" boolean DEFAULT false NOT NULL,\n\t\"retention_days\" bigint DEFAULT 30 NOT NULL,\n\t\"excluded_table_groups\" text DEFAULT '[]' NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"backups\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"status\" text DEFAULT 'queued' NOT NULL,\n\t\"trigger\" text NOT NULL,\n\t\"r2_key\" text,\n\t\"filename\" text,\n\t\"size\" bigint,\n\t\"error\" text,\n\t\"created_by_user_id\" text,\n\t\"created_at\" bigint NOT NULL,\n\t\"started_at\" bigint,\n\t\"completed_at\" bigint\n);",+ "CREATE TABLE \"booking_events\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"slug\" text DEFAULT '' NOT NULL,\n\t\"description\" text DEFAULT '' NOT NULL,\n\t\"color\" text DEFAULT '#2563eb' NOT NULL,\n\t\"host_ids\" text DEFAULT '[]' NOT NULL,\n\t\"duration_minutes\" bigint NOT NULL,\n\t\"location\" text DEFAULT '' NOT NULL,\n\t\"weekdays\" text DEFAULT '[1,2,3,4,5]' NOT NULL,\n\t\"start_time\" text DEFAULT '09:00' NOT NULL,\n\t\"end_time\" text DEFAULT '17:00' NOT NULL,\n\t\"time_ranges\" text DEFAULT '[{\"startTime\":\"09:00\",\"endTime\":\"17:00\"}]' NOT NULL,\n\t\"time_zone\" text DEFAULT 'UTC' NOT NULL,\n\t\"enabled\" boolean DEFAULT true NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"calendar_events\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"mailbox_id\" text,\n\t\"title\" text NOT NULL,\n\t\"description\" text DEFAULT '' NOT NULL,\n\t\"location\" text DEFAULT '' NOT NULL,\n\t\"attendees\" text DEFAULT '[]' NOT NULL,\n\t\"color\" text DEFAULT 'blue' NOT NULL,\n\t\"repeat\" text DEFAULT 'none' NOT NULL,\n\t\"repeat_days\" text DEFAULT '[]' NOT NULL,\n\t\"repeat_anchor_day\" bigint,\n\t\"repeat_until\" bigint,\n\t\"excluded_occurrences\" text DEFAULT '[]' NOT NULL,\n\t\"time_zone\" text,\n\t\"starts_at\" bigint NOT NULL,\n\t\"ends_at\" bigint NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"contacts\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"email\" text NOT NULL,\n\t\"display_name\" text,\n\t\"avatar_key\" text,\n\t\"source\" text DEFAULT 'inbound' NOT NULL,\n\t\"blocked\" boolean DEFAULT false NOT NULL,\n\t\"remote_content_allowed\" boolean DEFAULT false NOT NULL,\n\t\"last_seen_at\" bigint,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"domain_tracking_hosts\" (\n\t\"domain_id\" text PRIMARY KEY NOT NULL,\n\t\"hostname\" text NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"domains\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"hostname\" text NOT NULL,\n\t\"zone_id\" text NOT NULL,\n\t\"status\" text DEFAULT 'pending' NOT NULL,\n\t\"routing_status\" text,\n\t\"sending_subdomain_tag\" text,\n\t\"sending_provider\" text DEFAULT 'none' NOT NULL,\n\t\"receiving_provider\" text DEFAULT 'cloudflare' NOT NULL,\n\t\"sending_requested\" boolean DEFAULT false NOT NULL,\n\t\"sending_enabled\" boolean DEFAULT false NOT NULL,\n\t\"routing_enabled\" boolean DEFAULT false NOT NULL,\n\t\"dns_skipped\" boolean DEFAULT false NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"drive_items\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"owner_id\" text NOT NULL,\n\t\"parent_id\" text,\n\t\"kind\" text NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"r2_key\" text,\n\t\"size\" bigint DEFAULT 0 NOT NULL,\n\t\"content_type\" text DEFAULT 'application/octet-stream' NOT NULL,\n\t\"upload_id\" text,\n\t\"upload_part_size\" bigint,\n\t\"upload_fingerprint\" text,\n\t\"link_token\" text,\n\t\"trashed_at\" bigint,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"drive_shares\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"item_id\" text NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"role\" text DEFAULT 'view' NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"drive_upload_parts\" (\n\t\"item_id\" text NOT NULL,\n\t\"part_number\" bigint NOT NULL,\n\t\"etag\" text NOT NULL\n);",+ "CREATE TABLE \"email_templates\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"subject\" text DEFAULT '' NOT NULL,\n\t\"text_body\" text DEFAULT '' NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"folders\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"color\" text DEFAULT '#2563eb' NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"follow_ups\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"message_id\" text NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"due_at\" bigint NOT NULL,\n\t\"status\" text DEFAULT 'pending' NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"import_jobs\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"kind\" text NOT NULL,\n\t\"label\" text NOT NULL,\n\t\"status\" text DEFAULT 'queued' NOT NULL,\n\t\"total\" bigint DEFAULT 0 NOT NULL,\n\t\"processed\" bigint DEFAULT 0 NOT NULL,\n\t\"imported\" bigint DEFAULT 0 NOT NULL,\n\t\"skipped\" bigint DEFAULT 0 NOT NULL,\n\t\"spec\" text NOT NULL,\n\t\"cursor\" text DEFAULT '{}' NOT NULL,\n\t\"errors\" text DEFAULT '[]' NOT NULL,\n\t\"error_count\" bigint DEFAULT 0 NOT NULL,\n\t\"error\" text,\n\t\"created_at\" bigint NOT NULL,\n\t\"started_at\" bigint,\n\t\"updated_at\" bigint NOT NULL,\n\t\"finished_at\" bigint\n);",+ "CREATE TABLE \"jmap_change_floor\" (\n\t\"id\" bigint PRIMARY KEY NOT NULL,\n\t\"seq\" bigint DEFAULT 0 NOT NULL\n);",+ "CREATE TABLE \"jmap_changes\" (\n\t\"seq\" bigserial PRIMARY KEY NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"object_type\" text NOT NULL,\n\t\"object_id\" text NOT NULL,\n\t\"thread_id\" text,\n\t\"change\" text NOT NULL,\n\t\"created_at\" bigint DEFAULT (extract(epoch from now())::bigint) NOT NULL\n);",+ "CREATE TABLE \"jmap_mailbox_revisions\" (\n\t\"mailbox_id\" text PRIMARY KEY NOT NULL,\n\t\"revision\" bigint DEFAULT 0 NOT NULL\n);",+ "CREATE TABLE \"license_settings\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"instance_id\" text NOT NULL,\n\t\"instance_url\" text,\n\t\"license_key_hash\" text,\n\t\"plan\" text DEFAULT 'community' NOT NULL,\n\t\"state\" text DEFAULT 'inactive' NOT NULL,\n\t\"features\" text DEFAULT '[]' NOT NULL,\n\t\"seat_limit\" bigint DEFAULT 1,\n\t\"activated_at\" bigint,\n\t\"validated_at\" bigint,\n\t\"updated_at\" bigint NOT NULL,\n\tCONSTRAINT \"license_settings_instance_id_unique\" UNIQUE(\"instance_id\")\n);",+ "CREATE TABLE \"login_challenges\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"token_hash\" text NOT NULL,\n\t\"expires_at\" bigint NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\tCONSTRAINT \"login_challenges_token_hash_unique\" UNIQUE(\"token_hash\")\n);",+ "CREATE TABLE \"mailbox_access\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"permission\" text DEFAULT 'read_only' NOT NULL,\n\t\"created_by_user_id\" text,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"mailbox_agent_settings\" (\n\t\"mailbox_id\" text PRIMARY KEY NOT NULL,\n\t\"enabled\" boolean DEFAULT false NOT NULL,\n\t\"model_id\" text,\n\t\"auto_draft_enabled\" boolean DEFAULT false NOT NULL,\n\t\"reviewer_user_id\" text,\n\t\"instructions\" text DEFAULT '' NOT NULL,\n\t\"daily_limit\" bigint DEFAULT 25 NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"mailbox_aliases\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"domain_id\" text NOT NULL,\n\t\"local_part\" text NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"mailboxes\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"domain_id\" text NOT NULL,\n\t\"local_part\" text NOT NULL,\n\t\"display_name\" text,\n\t\"signature\" text,\n\t\"auto_reply_enabled\" boolean DEFAULT false NOT NULL,\n\t\"auto_reply_subject\" text DEFAULT 'Out of office' NOT NULL,\n\t\"auto_reply_body\" text DEFAULT '' NOT NULL,\n\t\"avatar_key\" text,\n\t\"type\" text DEFAULT 'personal' NOT NULL,\n\t\"use_all_domains\" boolean DEFAULT true NOT NULL,\n\t\"disabled\" boolean DEFAULT false NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"mcp_key_mailboxes\" (\n\t\"key_id\" text NOT NULL,\n\t\"mailbox_id\" text NOT NULL\n);",+ "CREATE TABLE \"message_attachments\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"message_id\" text NOT NULL,\n\t\"filename\" text NOT NULL,\n\t\"content_type\" text NOT NULL,\n\t\"size\" bigint NOT NULL,\n\t\"disposition\" text DEFAULT 'attachment' NOT NULL,\n\t\"content_id\" text,\n\t\"r2_key\" text NOT NULL,\n\t\"trashed_at\" bigint,\n\t\"created_at\" bigint NOT NULL,\n\tCONSTRAINT \"message_attachments_r2_key_unique\" UNIQUE(\"r2_key\")\n);",+ "CREATE TABLE \"message_opens\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"token\" text NOT NULL,\n\t\"opened_at\" bigint NOT NULL,\n\t\"client\" text,\n\t\"device\" text,\n\t\"country\" text,\n\t\"city\" text,\n\t\"automated\" boolean DEFAULT false NOT NULL\n);",+ "CREATE TABLE \"message_tracking\" (\n\t\"token\" text PRIMARY KEY NOT NULL,\n\t\"message_id\" text NOT NULL,\n\t\"open_count\" bigint DEFAULT 0 NOT NULL,\n\t\"first_opened_at\" bigint,\n\t\"last_opened_at\" bigint,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"messages\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"mailbox_id\" text,\n\t\"direction\" text NOT NULL,\n\t\"provider_message_id\" text,\n\t\"folder_id\" text,\n\t\"from_addr\" text NOT NULL,\n\t\"to_addr\" text NOT NULL,\n\t\"cc_addr\" text,\n\t\"bcc_addr\" text,\n\t\"reply_to\" text,\n\t\"subject\" text,\n\t\"snippet\" text,\n\t\"text_body\" text,\n\t\"html_body\" text,\n\t\"raw_r2_key\" text,\n\t\"status\" text DEFAULT 'received' NOT NULL,\n\t\"read\" boolean DEFAULT false NOT NULL,\n\t\"starred\" boolean DEFAULT false NOT NULL,\n\t\"snoozed_until\" bigint,\n\t\"thread_id\" text,\n\t\"in_reply_to\" text,\n\t\"references_header\" text,\n\t\"spam_score\" bigint,\n\t\"spam_verdict\" text,\n\t\"spam_signals\" text,\n\t\"spam_analyzed_at\" bigint,\n\t\"spam_analysis_error\" text,\n\t\"trashed_at\" bigint,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"mfa_recovery_codes\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"code_hash\" text NOT NULL,\n\t\"used_at\" bigint,\n\t\"created_at\" bigint NOT NULL,\n\tCONSTRAINT \"mfa_recovery_codes_code_hash_unique\" UNIQUE(\"code_hash\")\n);",+ "CREATE TABLE \"outbound_jobs\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"message_id\" text,\n\t\"status\" text DEFAULT 'queued' NOT NULL,\n\t\"payload\" text NOT NULL,\n\t\"error\" text,\n\t\"scheduled_at\" bigint,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"password_reset_tokens\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"token_hash\" text NOT NULL,\n\t\"expires_at\" bigint NOT NULL,\n\t\"used_at\" bigint,\n\t\"created_at\" bigint NOT NULL,\n\tCONSTRAINT \"password_reset_tokens_token_hash_unique\" UNIQUE(\"token_hash\")\n);",+ "CREATE TABLE \"push_devices\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"api_key_id\" text NOT NULL,\n\t\"platform\" text NOT NULL,\n\t\"token\" text NOT NULL,\n\t\"environment\" text DEFAULT 'production' NOT NULL,\n\t\"topic\" text NOT NULL,\n\t\"public_key\" text,\n\t\"previews\" boolean DEFAULT true NOT NULL,\n\t\"client_ref\" text,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"push_subscriptions\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"session_id\" text NOT NULL,\n\t\"endpoint\" text NOT NULL,\n\t\"p256dh\" text NOT NULL,\n\t\"auth\" text NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"routing_rules\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"domain_id\" text NOT NULL,\n\t\"scope\" text DEFAULT 'mailbox' NOT NULL,\n\t\"name\" text,\n\t\"enabled\" boolean DEFAULT true NOT NULL,\n\t\"pattern\" text NOT NULL,\n\t\"match_field\" text DEFAULT 'email' NOT NULL,\n\t\"match_operator\" text DEFAULT 'contains' NOT NULL,\n\t\"match_value\" text DEFAULT '' NOT NULL,\n\t\"mailbox_id\" text,\n\t\"folder_id\" text,\n\t\"action\" text DEFAULT 'store' NOT NULL,\n\t\"forward_to\" text,\n\t\"keep_copy\" boolean DEFAULT false NOT NULL,\n\t\"reject_reason\" text,\n\t\"priority\" bigint DEFAULT 0 NOT NULL,\n\t\"last_matched_at\" bigint,\n\t\"match_count\" bigint DEFAULT 0 NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"sessions\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"token_hash\" text NOT NULL,\n\t\"expires_at\" bigint NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\tCONSTRAINT \"sessions_token_hash_unique\" UNIQUE(\"token_hash\")\n);",+ "CREATE TABLE \"shared_attachment_links\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"attachment_id\" text NOT NULL,\n\t\"expires_at\" bigint NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\tCONSTRAINT \"shared_attachment_links_attachment_id_unique\" UNIQUE(\"attachment_id\")\n);",+ "CREATE TABLE \"spam_feedback\" (\n\t\"message_id\" text PRIMARY KEY NOT NULL,\n\t\"mailbox_id\" text NOT NULL,\n\t\"actor_user_id\" text,\n\t\"classification\" text NOT NULL,\n\t\"training_tokens\" text NOT NULL,\n\t\"reputation_keys\" text NOT NULL,\n\t\"tokenizer_version\" bigint DEFAULT 1 NOT NULL,\n\t\"created_at\" bigint NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"spam_reputation\" (\n\t\"mailbox_id\" text NOT NULL,\n\t\"type\" text NOT NULL,\n\t\"key\" text NOT NULL,\n\t\"messages_seen\" bigint DEFAULT 0 NOT NULL,\n\t\"spam_count\" bigint DEFAULT 0 NOT NULL,\n\t\"ham_count\" bigint DEFAULT 0 NOT NULL,\n\t\"first_seen_at\" bigint NOT NULL,\n\t\"last_seen_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"spam_token_stats\" (\n\t\"mailbox_id\" text NOT NULL,\n\t\"token\" text NOT NULL,\n\t\"spam_count\" bigint DEFAULT 0 NOT NULL,\n\t\"ham_count\" bigint DEFAULT 0 NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"user_compose_preferences\" (\n\t\"user_id\" text PRIMARY KEY NOT NULL,\n\t\"track_opens_default\" boolean DEFAULT false NOT NULL,\n\t\"undo_send_seconds\" bigint DEFAULT 15 NOT NULL,\n\t\"updated_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"users\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"email\" text NOT NULL,\n\t\"reset_email\" text,\n\t\"forwarding_email\" text,\n\t\"password_hash\" text NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"booking_username\" text,\n\t\"time_zone\" text,\n\t\"avatar_key\" text,\n\t\"role\" text DEFAULT 'user' NOT NULL,\n\t\"is_primary_admin\" boolean DEFAULT false NOT NULL,\n\t\"disabled\" boolean DEFAULT false NOT NULL,\n\t\"can_manage_mailboxes\" boolean DEFAULT false NOT NULL,\n\t\"can_manage_domains\" boolean DEFAULT false NOT NULL,\n\t\"can_manage_users\" boolean DEFAULT false NOT NULL,\n\t\"keyboard_shortcuts_enabled\" boolean DEFAULT true NOT NULL,\n\t\"spam_protection_enabled\" boolean DEFAULT true NOT NULL,\n\t\"trash_retention_days\" bigint,\n\t\"show_full_recipient_addresses\" boolean DEFAULT false NOT NULL,\n\t\"remote_content_mode\" text DEFAULT 'allow' NOT NULL,\n\t\"totp_secret\" text,\n\t\"totp_enabled\" boolean DEFAULT false NOT NULL,\n\t\"totp_confirmed_at\" bigint,\n\t\"last_sign_in_at\" bigint,\n\t\"deleted_at\" bigint,\n\t\"created_by_user_id\" text,\n\t\"created_at\" bigint NOT NULL,\n\tCONSTRAINT \"users_email_unique\" UNIQUE(\"email\")\n);",+ "CREATE TABLE \"webhook_deliveries\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"webhook_id\" text NOT NULL,\n\t\"event_type\" text NOT NULL,\n\t\"payload\" text NOT NULL,\n\t\"status\" text DEFAULT 'pending' NOT NULL,\n\t\"attempts\" bigint DEFAULT 0 NOT NULL,\n\t\"response_status\" bigint,\n\t\"error\" text,\n\t\"duration_ms\" bigint,\n\t\"last_attempt_at\" bigint,\n\t\"next_retry_at\" bigint,\n\t\"created_at\" bigint NOT NULL\n);",+ "CREATE TABLE \"webhooks\" (\n\t\"id\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"description\" text,\n\t\"url\" text NOT NULL,\n\t\"secret\" text NOT NULL,\n\t\"events\" text NOT NULL,\n\t\"enabled\" boolean DEFAULT true NOT NULL,\n\t\"max_attempts\" bigint DEFAULT 5 NOT NULL,\n\t\"created_at\" bigint NOT NULL\n);",+ "ALTER TABLE \"agent_chat_messages\" ADD CONSTRAINT \"agent_chat_messages_conversation_id_agent_conversations_id_fk\" FOREIGN KEY (\"conversation_id\") REFERENCES \"public\".\"agent_conversations\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_conversations\" ADD CONSTRAINT \"agent_conversations_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_conversations\" ADD CONSTRAINT \"agent_conversations_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_draft_metadata\" ADD CONSTRAINT \"agent_draft_metadata_draft_id_messages_id_fk\" FOREIGN KEY (\"draft_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_draft_metadata\" ADD CONSTRAINT \"agent_draft_metadata_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_draft_metadata\" ADD CONSTRAINT \"agent_draft_metadata_source_message_id_messages_id_fk\" FOREIGN KEY (\"source_message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"agent_jobs\" ADD CONSTRAINT \"agent_jobs_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_jobs\" ADD CONSTRAINT \"agent_jobs_source_message_id_messages_id_fk\" FOREIGN KEY (\"source_message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_jobs\" ADD CONSTRAINT \"agent_jobs_reviewer_user_id_users_id_fk\" FOREIGN KEY (\"reviewer_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_jobs\" ADD CONSTRAINT \"agent_jobs_draft_id_messages_id_fk\" FOREIGN KEY (\"draft_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"agent_send_approvals\" ADD CONSTRAINT \"agent_send_approvals_draft_id_messages_id_fk\" FOREIGN KEY (\"draft_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_send_approvals\" ADD CONSTRAINT \"agent_send_approvals_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_send_approvals\" ADD CONSTRAINT \"agent_send_approvals_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"agent_send_approvals\" ADD CONSTRAINT \"agent_send_approvals_request_key_id_api_keys_id_fk\" FOREIGN KEY (\"request_key_id\") REFERENCES \"public\".\"api_keys\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"api_keys\" ADD CONSTRAINT \"api_keys_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"audit_logs\" ADD CONSTRAINT \"audit_logs_actor_user_id_users_id_fk\" FOREIGN KEY (\"actor_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"audit_logs\" ADD CONSTRAINT \"audit_logs_target_user_id_users_id_fk\" FOREIGN KEY (\"target_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"audit_logs\" ADD CONSTRAINT \"audit_logs_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"audit_logs\" ADD CONSTRAINT \"audit_logs_message_id_messages_id_fk\" FOREIGN KEY (\"message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"auto_reply_deliveries\" ADD CONSTRAINT \"auto_reply_deliveries_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"backups\" ADD CONSTRAINT \"backups_created_by_user_id_users_id_fk\" FOREIGN KEY (\"created_by_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"booking_events\" ADD CONSTRAINT \"booking_events_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"calendar_events\" ADD CONSTRAINT \"calendar_events_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"calendar_events\" ADD CONSTRAINT \"calendar_events_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"contacts\" ADD CONSTRAINT \"contacts_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"domain_tracking_hosts\" ADD CONSTRAINT \"domain_tracking_hosts_domain_id_domains_id_fk\" FOREIGN KEY (\"domain_id\") REFERENCES \"public\".\"domains\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"domains\" ADD CONSTRAINT \"domains_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"drive_items\" ADD CONSTRAINT \"drive_items_owner_id_users_id_fk\" FOREIGN KEY (\"owner_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"drive_shares\" ADD CONSTRAINT \"drive_shares_item_id_drive_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"drive_items\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"drive_shares\" ADD CONSTRAINT \"drive_shares_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"drive_upload_parts\" ADD CONSTRAINT \"drive_upload_parts_item_id_drive_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"drive_items\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"email_templates\" ADD CONSTRAINT \"email_templates_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"folders\" ADD CONSTRAINT \"folders_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"folders\" ADD CONSTRAINT \"folders_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"follow_ups\" ADD CONSTRAINT \"follow_ups_message_id_messages_id_fk\" FOREIGN KEY (\"message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"follow_ups\" ADD CONSTRAINT \"follow_ups_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"import_jobs\" ADD CONSTRAINT \"import_jobs_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"import_jobs\" ADD CONSTRAINT \"import_jobs_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"login_challenges\" ADD CONSTRAINT \"login_challenges_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mailbox_access\" ADD CONSTRAINT \"mailbox_access_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mailbox_access\" ADD CONSTRAINT \"mailbox_access_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mailbox_access\" ADD CONSTRAINT \"mailbox_access_created_by_user_id_users_id_fk\" FOREIGN KEY (\"created_by_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"mailbox_agent_settings\" ADD CONSTRAINT \"mailbox_agent_settings_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mailbox_agent_settings\" ADD CONSTRAINT \"mailbox_agent_settings_reviewer_user_id_users_id_fk\" FOREIGN KEY (\"reviewer_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"mailbox_aliases\" ADD CONSTRAINT \"mailbox_aliases_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mailbox_aliases\" ADD CONSTRAINT \"mailbox_aliases_domain_id_domains_id_fk\" FOREIGN KEY (\"domain_id\") REFERENCES \"public\".\"domains\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mailboxes\" ADD CONSTRAINT \"mailboxes_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mailboxes\" ADD CONSTRAINT \"mailboxes_domain_id_domains_id_fk\" FOREIGN KEY (\"domain_id\") REFERENCES \"public\".\"domains\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mcp_key_mailboxes\" ADD CONSTRAINT \"mcp_key_mailboxes_key_id_api_keys_id_fk\" FOREIGN KEY (\"key_id\") REFERENCES \"public\".\"api_keys\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"mcp_key_mailboxes\" ADD CONSTRAINT \"mcp_key_mailboxes_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"message_attachments\" ADD CONSTRAINT \"message_attachments_message_id_messages_id_fk\" FOREIGN KEY (\"message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"message_opens\" ADD CONSTRAINT \"message_opens_token_message_tracking_token_fk\" FOREIGN KEY (\"token\") REFERENCES \"public\".\"message_tracking\"(\"token\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"message_tracking\" ADD CONSTRAINT \"message_tracking_message_id_messages_id_fk\" FOREIGN KEY (\"message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"messages\" ADD CONSTRAINT \"messages_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"messages\" ADD CONSTRAINT \"messages_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"messages\" ADD CONSTRAINT \"messages_folder_id_folders_id_fk\" FOREIGN KEY (\"folder_id\") REFERENCES \"public\".\"folders\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"mfa_recovery_codes\" ADD CONSTRAINT \"mfa_recovery_codes_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"outbound_jobs\" ADD CONSTRAINT \"outbound_jobs_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"outbound_jobs\" ADD CONSTRAINT \"outbound_jobs_message_id_messages_id_fk\" FOREIGN KEY (\"message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"password_reset_tokens\" ADD CONSTRAINT \"password_reset_tokens_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"push_devices\" ADD CONSTRAINT \"push_devices_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"push_devices\" ADD CONSTRAINT \"push_devices_api_key_id_api_keys_id_fk\" FOREIGN KEY (\"api_key_id\") REFERENCES \"public\".\"api_keys\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"push_subscriptions\" ADD CONSTRAINT \"push_subscriptions_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"push_subscriptions\" ADD CONSTRAINT \"push_subscriptions_session_id_sessions_id_fk\" FOREIGN KEY (\"session_id\") REFERENCES \"public\".\"sessions\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"routing_rules\" ADD CONSTRAINT \"routing_rules_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"routing_rules\" ADD CONSTRAINT \"routing_rules_domain_id_domains_id_fk\" FOREIGN KEY (\"domain_id\") REFERENCES \"public\".\"domains\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"routing_rules\" ADD CONSTRAINT \"routing_rules_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"routing_rules\" ADD CONSTRAINT \"routing_rules_folder_id_folders_id_fk\" FOREIGN KEY (\"folder_id\") REFERENCES \"public\".\"folders\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"sessions\" ADD CONSTRAINT \"sessions_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"shared_attachment_links\" ADD CONSTRAINT \"shared_attachment_links_attachment_id_message_attachments_id_fk\" FOREIGN KEY (\"attachment_id\") REFERENCES \"public\".\"message_attachments\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"spam_feedback\" ADD CONSTRAINT \"spam_feedback_message_id_messages_id_fk\" FOREIGN KEY (\"message_id\") REFERENCES \"public\".\"messages\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"spam_feedback\" ADD CONSTRAINT \"spam_feedback_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"spam_feedback\" ADD CONSTRAINT \"spam_feedback_actor_user_id_users_id_fk\" FOREIGN KEY (\"actor_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"spam_reputation\" ADD CONSTRAINT \"spam_reputation_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"spam_token_stats\" ADD CONSTRAINT \"spam_token_stats_mailbox_id_mailboxes_id_fk\" FOREIGN KEY (\"mailbox_id\") REFERENCES \"public\".\"mailboxes\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"user_compose_preferences\" ADD CONSTRAINT \"user_compose_preferences_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"users\" ADD CONSTRAINT \"users_created_by_user_id_users_id_fk\" FOREIGN KEY (\"created_by_user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE set null ON UPDATE no action;",+ "ALTER TABLE \"webhook_deliveries\" ADD CONSTRAINT \"webhook_deliveries_webhook_id_webhooks_id_fk\" FOREIGN KEY (\"webhook_id\") REFERENCES \"public\".\"webhooks\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "ALTER TABLE \"webhooks\" ADD CONSTRAINT \"webhooks_user_id_users_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE cascade ON UPDATE no action;",+ "CREATE INDEX \"agent_chat_messages_conversation_idx\" ON \"agent_chat_messages\" USING btree (\"conversation_id\",\"created_at\");",+ "CREATE INDEX \"agent_conversations_owner_idx\" ON \"agent_conversations\" USING btree (\"user_id\",\"mailbox_id\",\"updated_at\");",+ "CREATE INDEX \"agent_conversations_mailbox_idx\" ON \"agent_conversations\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"agent_draft_meta_source_msg_idx\" ON \"agent_draft_metadata\" USING btree (\"source_message_id\");",+ "CREATE INDEX \"agent_draft_metadata_mailbox_idx\" ON \"agent_draft_metadata\" USING btree (\"mailbox_id\");",+ "CREATE UNIQUE INDEX \"agent_jobs_source_idx\" ON \"agent_jobs\" USING btree (\"mailbox_id\",\"source_message_id\");",+ "CREATE INDEX \"agent_jobs_due_idx\" ON \"agent_jobs\" USING btree (\"status\",\"next_attempt_at\");",+ "CREATE INDEX \"agent_jobs_source_message_idx\" ON \"agent_jobs\" USING btree (\"source_message_id\");",+ "CREATE INDEX \"agent_jobs_draft_idx\" ON \"agent_jobs\" USING btree (\"draft_id\");",+ "CREATE INDEX \"agent_jobs_reviewer_idx\" ON \"agent_jobs\" USING btree (\"reviewer_user_id\");",+ "CREATE INDEX \"agent_send_approvals_user_idx\" ON \"agent_send_approvals\" USING btree (\"user_id\",\"status\");",+ "CREATE UNIQUE INDEX \"agent_send_approvals_delivery_idx\" ON \"agent_send_approvals\" USING btree (\"draft_id\") WHERE status IN ('claimed', 'sent', 'unknown');",+ "CREATE INDEX \"agent_send_approvals_request_key_idx\" ON \"agent_send_approvals\" USING btree (\"request_key_id\");",+ "CREATE INDEX \"agent_send_approvals_mailbox_idx\" ON \"agent_send_approvals\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"agent_send_approvals_draft_idx\" ON \"agent_send_approvals\" USING btree (\"draft_id\");",+ "CREATE INDEX \"ai_usage_created_idx\" ON \"ai_usage\" USING btree (\"created_at\");",+ "CREATE INDEX \"api_keys_user_idx\" ON \"api_keys\" USING btree (\"user_id\");",+ "CREATE INDEX \"audit_logs_actor_idx\" ON \"audit_logs\" USING btree (\"actor_user_id\");",+ "CREATE INDEX \"audit_logs_mailbox_idx\" ON \"audit_logs\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"audit_logs_created_idx\" ON \"audit_logs\" USING btree (\"created_at\");",+ "CREATE INDEX \"audit_logs_message_id_idx\" ON \"audit_logs\" USING btree (\"message_id\");",+ "CREATE INDEX \"audit_logs_target_user_idx\" ON \"audit_logs\" USING btree (\"target_user_id\");",+ "CREATE UNIQUE INDEX \"auto_reply_deliveries_mailbox_recipient_idx\" ON \"auto_reply_deliveries\" USING btree (\"mailbox_id\",\"recipient\");",+ "CREATE INDEX \"auto_reply_deliveries_sent_idx\" ON \"auto_reply_deliveries\" USING btree (\"sent_at\");",+ "CREATE INDEX \"backups_created_idx\" ON \"backups\" USING btree (\"created_at\");",+ "CREATE INDEX \"backups_status_idx\" ON \"backups\" USING btree (\"status\");",+ "CREATE INDEX \"backups_created_by_idx\" ON \"backups\" USING btree (\"created_by_user_id\");",+ "CREATE INDEX \"booking_events_user_idx\" ON \"booking_events\" USING btree (\"user_id\");",+ "CREATE UNIQUE INDEX \"booking_events_user_slug_idx\" ON \"booking_events\" USING btree (\"user_id\",\"slug\");",+ "CREATE INDEX \"calendar_events_user_starts_idx\" ON \"calendar_events\" USING btree (\"user_id\",\"starts_at\");",+ "CREATE INDEX \"calendar_events_mailbox_idx\" ON \"calendar_events\" USING btree (\"mailbox_id\");",+ "CREATE UNIQUE INDEX \"contacts_user_email_idx\" ON \"contacts\" USING btree (\"user_id\",\"email\");",+ "CREATE INDEX \"contacts_user_idx\" ON \"contacts\" USING btree (\"user_id\");",+ "CREATE UNIQUE INDEX \"domain_tracking_hosts_hostname_idx\" ON \"domain_tracking_hosts\" USING btree (\"hostname\");",+ "CREATE UNIQUE INDEX \"domains_hostname_idx\" ON \"domains\" USING btree (\"hostname\");",+ "CREATE INDEX \"domains_user_idx\" ON \"domains\" USING btree (\"user_id\");",+ "CREATE INDEX \"drive_items_owner_parent_idx\" ON \"drive_items\" USING btree (\"owner_id\",\"parent_id\");",+ "CREATE UNIQUE INDEX \"drive_items_link_token_idx\" ON \"drive_items\" USING btree (\"link_token\");",+ "CREATE UNIQUE INDEX \"drive_shares_item_user_idx\" ON \"drive_shares\" USING btree (\"item_id\",\"user_id\");",+ "CREATE INDEX \"drive_shares_user_idx\" ON \"drive_shares\" USING btree (\"user_id\");",+ "CREATE UNIQUE INDEX \"drive_upload_parts_idx\" ON \"drive_upload_parts\" USING btree (\"item_id\",\"part_number\");",+ "CREATE INDEX \"email_templates_user_idx\" ON \"email_templates\" USING btree (\"user_id\");",+ "CREATE UNIQUE INDEX \"folders_mailbox_name_idx\" ON \"folders\" USING btree (\"mailbox_id\",\"name\");",+ "CREATE INDEX \"folders_user_idx\" ON \"folders\" USING btree (\"user_id\");",+ "CREATE INDEX \"folders_mailbox_idx\" ON \"folders\" USING btree (\"mailbox_id\");",+ "CREATE UNIQUE INDEX \"follow_ups_message_idx\" ON \"follow_ups\" USING btree (\"message_id\");",+ "CREATE INDEX \"follow_ups_status_due_idx\" ON \"follow_ups\" USING btree (\"status\",\"due_at\");",+ "CREATE INDEX \"follow_ups_user_status_idx\" ON \"follow_ups\" USING btree (\"user_id\",\"status\");",+ "CREATE INDEX \"import_jobs_user_idx\" ON \"import_jobs\" USING btree (\"user_id\",\"created_at\");",+ "CREATE INDEX \"import_jobs_status_idx\" ON \"import_jobs\" USING btree (\"status\",\"updated_at\");",+ "CREATE INDEX \"jmap_changes_mailbox_seq_idx\" ON \"jmap_changes\" USING btree (\"mailbox_id\",\"seq\");",+ "CREATE INDEX \"login_challenges_user_idx\" ON \"login_challenges\" USING btree (\"user_id\");",+ "CREATE UNIQUE INDEX \"mailbox_access_mailbox_user_idx\" ON \"mailbox_access\" USING btree (\"mailbox_id\",\"user_id\");",+ "CREATE INDEX \"mailbox_access_user_idx\" ON \"mailbox_access\" USING btree (\"user_id\");",+ "CREATE INDEX \"mailbox_access_mailbox_idx\" ON \"mailbox_access\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"mailbox_access_created_by_idx\" ON \"mailbox_access\" USING btree (\"created_by_user_id\");",+ "CREATE INDEX \"mailbox_agent_settings_reviewer_idx\" ON \"mailbox_agent_settings\" USING btree (\"reviewer_user_id\");",+ "CREATE UNIQUE INDEX \"mailbox_aliases_address_idx\" ON \"mailbox_aliases\" USING btree (\"domain_id\",\"local_part\");",+ "CREATE INDEX \"mailbox_aliases_mailbox_idx\" ON \"mailbox_aliases\" USING btree (\"mailbox_id\");",+ "CREATE UNIQUE INDEX \"mailboxes_address_idx\" ON \"mailboxes\" USING btree (\"domain_id\",\"local_part\");",+ "CREATE INDEX \"mailboxes_user_idx\" ON \"mailboxes\" USING btree (\"user_id\");",+ "CREATE UNIQUE INDEX \"mcp_key_mailbox_idx\" ON \"mcp_key_mailboxes\" USING btree (\"key_id\",\"mailbox_id\");",+ "CREATE INDEX \"mcp_key_mailboxes_mailbox_idx\" ON \"mcp_key_mailboxes\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"message_attachments_message_idx\" ON \"message_attachments\" USING btree (\"message_id\");",+ "CREATE INDEX \"message_opens_token_idx\" ON \"message_opens\" USING btree (\"token\",\"opened_at\");",+ "CREATE UNIQUE INDEX \"message_tracking_message_idx\" ON \"message_tracking\" USING btree (\"message_id\");",+ "CREATE INDEX \"messages_user_created_idx\" ON \"messages\" USING btree (\"user_id\",\"created_at\");",+ "CREATE INDEX \"messages_mailbox_idx\" ON \"messages\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"messages_folder_idx\" ON \"messages\" USING btree (\"folder_id\");",+ "CREATE INDEX \"messages_thread_idx\" ON \"messages\" USING btree (\"mailbox_id\",\"thread_id\");",+ "CREATE INDEX \"messages_provider_message_idx\" ON \"messages\" USING btree (\"mailbox_id\",\"provider_message_id\");",+ "CREATE INDEX \"messages_raw_r2_key_idx\" ON \"messages\" USING btree (\"raw_r2_key\");",+ "CREATE INDEX \"messages_trashed_at_idx\" ON \"messages\" USING btree (\"trashed_at\");",+ "CREATE INDEX \"messages_inbox_page_idx\" ON \"messages\" USING btree (\"mailbox_id\",\"status\",\"folder_id\",\"created_at\" desc,\"id\" desc);",+ "CREATE INDEX \"messages_thread_key_idx\" ON \"messages\" USING btree (\"mailbox_id\",\"status\",\"folder_id\",coalesce(\"thread_id\", \"id\"),\"created_at\");",+ "CREATE INDEX \"messages_mailbox_thread_key_idx\" ON \"messages\" USING btree (\"mailbox_id\",coalesce(\"thread_id\", \"id\"));",+ "CREATE INDEX \"messages_nav_cover_idx\" ON \"messages\" USING btree (\"mailbox_id\",\"status\",\"folder_id\",\"created_at\" desc,\"id\" desc,\"direction\",\"read\",\"thread_id\",\"snoozed_until\");",+ "CREATE INDEX \"messages_counts_cover_idx\" ON \"messages\" USING btree (\"mailbox_id\",\"folder_id\",\"direction\",\"status\",\"read\",\"starred\",\"snoozed_until\");",+ "CREATE INDEX \"messages_conv_cover_idx\" ON \"messages\" USING btree (\"mailbox_id\",\"status\",coalesce(\"thread_id\", \"id\"),\"created_at\",\"id\",\"snoozed_until\");",+ "CREATE INDEX \"mfa_recovery_codes_user_idx\" ON \"mfa_recovery_codes\" USING btree (\"user_id\");",+ "CREATE INDEX \"outbound_jobs_user_idx\" ON \"outbound_jobs\" USING btree (\"user_id\");",+ "CREATE INDEX \"outbound_jobs_message_idx\" ON \"outbound_jobs\" USING btree (\"message_id\");",+ "CREATE INDEX \"password_reset_tokens_user_idx\" ON \"password_reset_tokens\" USING btree (\"user_id\");",+ "CREATE UNIQUE INDEX \"push_devices_platform_token_user_idx\" ON \"push_devices\" USING btree (\"platform\",\"token\",\"user_id\");",+ "CREATE INDEX \"push_devices_user_idx\" ON \"push_devices\" USING btree (\"user_id\");",+ "CREATE INDEX \"push_devices_api_key_idx\" ON \"push_devices\" USING btree (\"api_key_id\");",+ "CREATE UNIQUE INDEX \"push_subscriptions_endpoint_idx\" ON \"push_subscriptions\" USING btree (\"endpoint\");",+ "CREATE INDEX \"push_subscriptions_user_idx\" ON \"push_subscriptions\" USING btree (\"user_id\");",+ "CREATE INDEX \"push_subscriptions_session_idx\" ON \"push_subscriptions\" USING btree (\"session_id\");",+ "CREATE INDEX \"routing_rules_domain_scope_idx\" ON \"routing_rules\" USING btree (\"domain_id\",\"scope\",\"enabled\");",+ "CREATE INDEX \"routing_rules_mailbox_idx\" ON \"routing_rules\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"routing_rules_priority_idx\" ON \"routing_rules\" USING btree (\"priority\");",+ "CREATE INDEX \"routing_rules_user_idx\" ON \"routing_rules\" USING btree (\"user_id\");",+ "CREATE INDEX \"routing_rules_folder_idx\" ON \"routing_rules\" USING btree (\"folder_id\");",+ "CREATE INDEX \"sessions_user_idx\" ON \"sessions\" USING btree (\"user_id\");",+ "CREATE INDEX \"spam_feedback_mailbox_idx\" ON \"spam_feedback\" USING btree (\"mailbox_id\");",+ "CREATE INDEX \"spam_feedback_actor_user_idx\" ON \"spam_feedback\" USING btree (\"actor_user_id\");",+ "CREATE UNIQUE INDEX \"spam_reputation_mailbox_type_key_idx\" ON \"spam_reputation\" USING btree (\"mailbox_id\",\"type\",\"key\");",+ "CREATE INDEX \"spam_reputation_mailbox_idx\" ON \"spam_reputation\" USING btree (\"mailbox_id\");",+ "CREATE UNIQUE INDEX \"spam_token_stats_mailbox_token_idx\" ON \"spam_token_stats\" USING btree (\"mailbox_id\",\"token\");",+ "CREATE INDEX \"spam_token_stats_mailbox_idx\" ON \"spam_token_stats\" USING btree (\"mailbox_id\");",+ "CREATE UNIQUE INDEX \"users_booking_username_idx\" ON \"users\" USING btree (\"booking_username\");",+ "CREATE INDEX \"users_created_by_idx\" ON \"users\" USING btree (\"created_by_user_id\");",+ "CREATE INDEX \"webhook_deliveries_webhook_idx\" ON \"webhook_deliveries\" USING btree (\"webhook_id\",\"created_at\");",+ "CREATE INDEX \"webhook_deliveries_status_idx\" ON \"webhook_deliveries\" USING btree (\"status\");",+ "CREATE INDEX \"webhooks_user_idx\" ON \"webhooks\" USING btree (\"user_id\");"+ ]+ },+ {+ "name": "0001_triggers_and_seeds.sql",+ "statements": [+ "INSERT INTO backup_settings (id, enabled, schedule_type, retention_enabled, retention_days, updated_at)\nVALUES ('default', false, 'daily', false, 30, extract(epoch from now())::bigint)\nON CONFLICT DO NOTHING;",+ "INSERT INTO app_settings (id, app_name, updated_at)\nVALUES ('default', 'Mailflare', extract(epoch from now())::bigint)\nON CONFLICT DO NOTHING;",+ "INSERT INTO jmap_change_floor (id, seq) VALUES (1, 0) ON CONFLICT DO NOTHING;",+ "CREATE FUNCTION mailflare_bump_revision(target text) RETURNS void AS $$\nBEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (target, 1)\n\tON CONFLICT (mailbox_id) DO UPDATE SET revision = jmap_mailbox_revisions.revision + 1;\nEND;\n$$ LANGUAGE plpgsql;",+ "CREATE FUNCTION mailflare_messages_trashed_at() RETURNS trigger AS $$\nBEGIN\n\tIF TG_OP = 'INSERT' THEN\n\t\tIF NEW.status IN ('trash', 'spam') THEN\n\t\t\tNEW.trashed_at := extract(epoch from now())::bigint;\n\t\tEND IF;\n\tELSIF (NEW.status IN ('trash', 'spam')) <> (OLD.status IN ('trash', 'spam')) THEN\n\t\tNEW.trashed_at := CASE WHEN NEW.status IN ('trash', 'spam') THEN extract(epoch from now())::bigint ELSE NULL END;\n\tEND IF;\n\tRETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;",+ "CREATE TRIGGER messages_trashed_at_bi BEFORE INSERT OR UPDATE OF status ON messages\nFOR EACH ROW EXECUTE FUNCTION mailflare_messages_trashed_at();",+ "CREATE FUNCTION mailflare_messages_changed() RETURNS trigger AS $$\nBEGIN\n\tIF TG_OP = 'INSERT' THEN\n\t\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\t\tPERFORM mailflare_bump_revision(NEW.mailbox_id);\n\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\t\t\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');\n\t\tEND IF;\n\tELSIF TG_OP = 'UPDATE' THEN\n\t\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\t\tPERFORM mailflare_bump_revision(NEW.mailbox_id);\n\t\tEND IF;\n\t\tIF OLD.mailbox_id IS NOT NULL AND OLD.mailbox_id IS DISTINCT FROM NEW.mailbox_id THEN\n\t\t\tPERFORM mailflare_bump_revision(OLD.mailbox_id);\n\t\tEND IF;\n\t\tIF OLD.mailbox_id IS NOT DISTINCT FROM NEW.mailbox_id THEN\n\t\t\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\t\t\t\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'updated');\n\t\t\tEND IF;\n\t\tELSE\n\t\t\tIF OLD.mailbox_id IS NOT NULL THEN\n\t\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\t\t\t\tVALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');\n\t\t\tEND IF;\n\t\t\tIF NEW.mailbox_id IS NOT NULL THEN\n\t\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\t\t\t\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');\n\t\t\tEND IF;\n\t\tEND IF;\n\tELSE\n\t\tIF OLD.mailbox_id IS NOT NULL THEN\n\t\t\tPERFORM mailflare_bump_revision(OLD.mailbox_id);\n\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\t\t\tVALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');\n\t\tEND IF;\n\tEND IF;\n\tRETURN NULL;\nEND;\n$$ LANGUAGE plpgsql;",+ "CREATE TRIGGER messages_jmap_changed AFTER INSERT OR UPDATE OR DELETE ON messages\nFOR EACH ROW EXECUTE FUNCTION mailflare_messages_changed();",+ "CREATE FUNCTION mailflare_folders_changed() RETURNS trigger AS $$\nBEGIN\n\tIF TG_OP = 'INSERT' THEN\n\t\tPERFORM mailflare_bump_revision(NEW.mailbox_id);\n\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.mailbox_id, 'mailbox', NEW.id, 'created');\n\tELSIF TG_OP = 'UPDATE' THEN\n\t\tPERFORM mailflare_bump_revision(NEW.mailbox_id);\n\t\tIF OLD.mailbox_id IS DISTINCT FROM NEW.mailbox_id THEN\n\t\t\tPERFORM mailflare_bump_revision(OLD.mailbox_id);\n\t\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');\n\t\tEND IF;\n\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change)\n\t\tVALUES (NEW.mailbox_id, 'mailbox', NEW.id, CASE WHEN OLD.mailbox_id IS NOT DISTINCT FROM NEW.mailbox_id THEN 'updated' ELSE 'created' END);\n\tELSE\n\t\tPERFORM mailflare_bump_revision(OLD.mailbox_id);\n\t\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');\n\tEND IF;\n\tRETURN NULL;\nEND;\n$$ LANGUAGE plpgsql;",+ "CREATE TRIGGER folders_jmap_changed AFTER INSERT OR UPDATE OR DELETE ON folders\nFOR EACH ROW EXECUTE FUNCTION mailflare_folders_changed();",+ "CREATE FUNCTION mailflare_mailboxes_changed() RETURNS trigger AS $$\nBEGIN\n\tPERFORM mailflare_bump_revision(NEW.id);\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.id, 'mailbox', NEW.id, 'updated');\n\tRETURN NULL;\nEND;\n$$ LANGUAGE plpgsql;",+ "CREATE TRIGGER mailboxes_jmap_changed AFTER UPDATE ON mailboxes\nFOR EACH ROW EXECUTE FUNCTION mailflare_mailboxes_changed();",+ "CREATE FUNCTION mailflare_aliases_changed() RETURNS trigger AS $$\nBEGIN\n\tIF TG_OP IN ('INSERT', 'UPDATE') THEN\n\t\tPERFORM mailflare_bump_revision(NEW.mailbox_id);\n\tEND IF;\n\tIF TG_OP = 'DELETE' OR (TG_OP = 'UPDATE' AND OLD.mailbox_id IS DISTINCT FROM NEW.mailbox_id) THEN\n\t\tPERFORM mailflare_bump_revision(OLD.mailbox_id);\n\tEND IF;\n\tRETURN NULL;\nEND;\n$$ LANGUAGE plpgsql;",+ "CREATE TRIGGER mailbox_aliases_jmap_changed AFTER INSERT OR UPDATE OR DELETE ON mailbox_aliases\nFOR EACH ROW EXECUTE FUNCTION mailflare_aliases_changed();",+ "DO $$\nBEGIN\n\tCREATE EXTENSION IF NOT EXISTS pg_trgm;\n\tCREATE INDEX messages_subject_trgm_idx ON messages USING gin (lower(subject) gin_trgm_ops);\n\tCREATE INDEX messages_text_body_trgm_idx ON messages USING gin (lower(text_body) gin_trgm_ops);\nEXCEPTION WHEN OTHERS THEN\n\tRAISE NOTICE 'pg_trgm is unavailable; message search will scan with ILIKE instead (%).', SQLERRM;\nEND;\n$$;"+ ]+ }+ ]+}diff --git a/src/lib/migrations/service.ts b/src/lib/migrations/service.tsindex 7588a17..79e0b63 100644--- a/src/lib/migrations/service.ts+++ b/src/lib/migrations/service.ts@@ -1,22 +1,50 @@-import bundle from "./bundle.json";+import { isExternalDatabase } from "@/db/external";+import type { DatabaseDialect } from "@/db/dialect";+import sqliteBundle from "./bundle.json";+import mysqlBundle from "./bundle-mysql.json";+import postgresBundle from "./bundle-postgres.json";import type { BundledMigration, MigrationNameRow, MigrationResult, MigrationStatus } from "./types";-const MIGRATION_TABLE_SQL =- "CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)";+const BUNDLES: Record<DatabaseDialect, BundledMigration[]> = {+ sqlite: sqliteBundle.migrations as BundledMigration[],+ postgres: postgresBundle.migrations as BundledMigration[],+ mysql: mysqlBundle.migrations as BundledMigration[],+};-const migrations = bundle.migrations as BundledMigration[];+/** D1 keeps the table name Wrangler uses, so `wrangler d1 migrations apply` and the in-app runner agree. */+const MIGRATION_TABLES: Record<DatabaseDialect, { table: string; create: string; exists: string }> = {+ sqlite: {+ table: "d1_migrations",+ create: "CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)",+ exists: "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'd1_migrations'",+ },+ postgres: {+ table: "mailflare_migrations",+ create: "CREATE TABLE IF NOT EXISTS mailflare_migrations (id BIGSERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL UNIQUE, applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)",+ exists: "SELECT table_name AS name FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = 'mailflare_migrations'",+ },+ mysql: {+ table: "mailflare_migrations",+ create: "CREATE TABLE IF NOT EXISTS mailflare_migrations (id BIGINT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(191) NOT NULL UNIQUE, applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)",+ exists: "SELECT table_name AS name FROM information_schema.tables WHERE table_schema = database() AND table_name = 'mailflare_migrations'",+ },+};++export function migrationDialect(db: D1Database): DatabaseDialect {+ return isExternalDatabase(db) ? db.config.dialect : "sqlite";+}async function getAppliedMigrationNames(db: D1Database): Promise<string[]> {- const table = await db- .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'd1_migrations'")- .first<MigrationNameRow>();- if (!table) return [];+ const { table, exists } = MIGRATION_TABLES[migrationDialect(db)];+ const found = await db.prepare(exists).first<MigrationNameRow>();+ if (!found) return [];- const result = await db.prepare("SELECT name FROM d1_migrations").all<MigrationNameRow>();+ const result = await db.prepare(`SELECT name FROM ${table}`).all<MigrationNameRow>();return result.results.map((row) => row.name);}export async function getMigrationStatus(db: D1Database): Promise<MigrationStatus> {+ const migrations = BUNDLES[migrationDialect(db)];const applied = new Set(await getAppliedMigrationNames(db));const committed = new Set(migrations.map((migration) => migration.name));const pending = migrations.filter((migration) => !applied.has(migration.name)).map((migration) => migration.name);@@ -26,12 +54,15 @@ export async function getMigrationStatus(db: D1Database): Promise<MigrationStatu}export async function applyPendingMigrations(db: D1Database): Promise<MigrationResult> {+ const dialect = migrationDialect(db);+ const migrations = BUNDLES[dialect];+ const { table, create } = MIGRATION_TABLES[dialect];const initial = await getMigrationStatus(db);if (initial.unknown.length > 0) {throw new Error("The database contains migrations that are not part of this Mailflare release.");}- await db.prepare(MIGRATION_TABLE_SQL).run();+ await db.prepare(create).run();const applied: string[] = [];for (const name of initial.pending) {@@ -39,20 +70,24 @@ export async function applyPendingMigrations(db: D1Database): Promise<MigrationRif (!migration) continue;try {- await db.batch([- db.prepare("INSERT INTO d1_migrations (name) VALUES (?)").bind(name),- ...migration.statements.map((statement) => db.prepare(statement)),- ]);+ if (dialect === "mysql") {+ // MySQL commits DDL implicitly, so a transaction cannot make a migration atomic. Record it last,+ // so a failed migration is retried rather than skipped.+ for (const statement of migration.statements) await db.prepare(statement).run();+ await db.prepare(`INSERT INTO ${table} (name) VALUES (?)`).bind(name).run();+ } else {+ await db.batch([+ db.prepare(`INSERT INTO ${table} (name) VALUES (?)`).bind(name),+ ...migration.statements.map((statement) => db.prepare(statement)),+ ]);+ }applied.push(name);} catch (error) {- const completed = await db- .prepare("SELECT name FROM d1_migrations WHERE name = ?")- .bind(name)- .first<MigrationNameRow>();- if (completed) continue;- throw new Error(- `Migration ${name} failed: ${error instanceof Error ? error.message : "Database error"}`,- );+ if (dialect !== "mysql") {+ const completed = await db.prepare(`SELECT name FROM ${table} WHERE name = ?`).bind(name).first<MigrationNameRow>();+ if (completed) continue;+ }+ throw new Error(`Migration ${name} failed: ${error instanceof Error ? error.message : "Database error"}`);}}diff --git a/src/lib/realtime/revision.ts b/src/lib/realtime/revision.tsindex 1688199..824adc9 100644--- a/src/lib/realtime/revision.ts+++ b/src/lib/realtime/revision.ts@@ -6,13 +6,13 @@ export async function getUserMailRevision(env: CloudflareEnv, userId: string): PSELECT m.id AS mailbox_id, COALESCE(r.revision, 0) AS revision, 'owner' AS permissionFROM mailboxes mLEFT JOIN jmap_mailbox_revisions r ON r.mailbox_id = m.id- WHERE m.user_id = ? AND m.disabled = 0+ WHERE m.user_id = ? AND NOT m.disabledUNIONSELECT m.id AS mailbox_id, COALESCE(r.revision, 0) AS revision, a.permission AS permissionFROM mailbox_access aJOIN mailboxes m ON m.id = a.mailbox_idLEFT JOIN jmap_mailbox_revisions r ON r.mailbox_id = m.id- WHERE a.user_id = ? AND m.type = 'shared' AND m.disabled = 0+ WHERE a.user_id = ? AND m.type = 'shared' AND NOT m.disabledORDER BY mailbox_id, permission`).bind(userId, userId).all<MailboxRevisionRow>();return JSON.stringify(result.results.map((row) => [row.mailbox_id, row.revision, row.permission]));diff --git a/src/lib/search/conditions.ts b/src/lib/search/conditions.tsindex 8d4f55c..7520061 100644--- a/src/lib/search/conditions.ts+++ b/src/lib/search/conditions.ts@@ -1,7 +1,41 @@-import { and, eq, exists, gte, lt, sql } from "drizzle-orm";-import type { SQL } from "drizzle-orm";+import { and, eq, exists, gte, lt, not, or, sql } from "drizzle-orm";+import type { AnyColumn, SQL } from "drizzle-orm";import { messageAttachments, messages } from "@/db/schema";-import { buildFtsMatch, parseSearchQuery } from "./query-utils";+import { schemaDialect } from "@/db/dialect";+import { buildFtsMatch, parseSearchQuery, tokenizeSearchText } from "./query-utils";+import type { ParsedSearchQuery } from "./types";++/** `!` is the escape character because it needs no escaping itself in either SQL string syntax. */+const likePattern = (term: string) => `%${term.toLowerCase().replace(/[!%_]/g, "!$&")}%`;+const contains = (column: SQL | AnyColumn, term: string) => sql`lower(${column}) like ${likePattern(term)} escape '!'`;++/**+ * Text search for databases without FTS5 (PostgreSQL, MySQL): every term must appear as a substring of the+ * subject, an address or the body. It scans the mailbox's messages instead of using an index, which is the+ * documented trade-off of those dialects.+ */+function buildLikeConditions(parsed: ParsedSearchQuery): SQL[] {+ const conditions: SQL[] = [];+ for (const token of tokenizeSearchText(parsed.text)) {+ const match = or(+ contains(messages.subject, token.term),+ contains(messages.fromAddr, token.term),+ contains(messages.toAddr, token.term),+ contains(messages.ccAddr, token.term),+ contains(messages.textBody, token.term),+ and(sql`${messages.textBody} is null`, contains(messages.htmlBody, token.term)),+ )!;+ conditions.push(token.negate ? not(match) : match);+ }+ const column = (columns: Array<SQL | AnyColumn>, value: string | undefined) => {+ if (!value) return;+ for (const token of tokenizeSearchText(value)) conditions.push(or(...columns.map((c) => contains(c, token.term)))!);+ };+ column([messages.subject], parsed.subject);+ column([messages.fromAddr], parsed.from);+ column([messages.toAddr, messages.ccAddr], parsed.to);+ return conditions;+}/*** Translate a search string into WHERE conditions on `messages`. Text goes to@@ -12,9 +46,13 @@ export function buildSearchConditions(raw: string, timeZone = "UTC"): SQL[] {const parsed = parseSearchQuery(raw, timeZone);const conditions: SQL[] = [];- const match = buildFtsMatch(parsed);- if (match) {- conditions.push(sql`${messages}.rowid IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ${match})`);+ if (schemaDialect() === "sqlite") {+ const match = buildFtsMatch(parsed);+ if (match) {+ conditions.push(sql`${messages}.rowid IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ${match})`);+ }+ } else {+ conditions.push(...buildLikeConditions(parsed));}if (parsed.hasAttachment) {conditions.push(diff --git a/src/lib/search/index-admin.ts b/src/lib/search/index-admin.tsindex 3025c59..3fd355e 100644--- a/src/lib/search/index-admin.ts+++ b/src/lib/search/index-admin.ts@@ -1,13 +1,22 @@+import { dialectOf } from "@/db/introspect";+/**- * Maintenance for the FTS5 index. Triggers keep it current, so a rebuild is- * only needed after a restore from a backup that predates the index, or if the- * counts below ever disagree.+ * Maintenance for the full-text index. On SQLite (D1) triggers keep the FTS5 table current, so a rebuild is+ * only needed after a restore from a backup that predates the index, or if the counts below ever disagree.+ * PostgreSQL and MySQL search the message columns directly (see conditions.ts), so there is no index to+ * rebuild and the status always reports every message as searchable.*/export async function rebuildSearchIndex(env: CloudflareEnv): Promise<void> {+ if (dialectOf(env.DB) !== "sqlite") return;await env.DB.prepare("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')").run();}export async function getSearchIndexStatus(env: CloudflareEnv): Promise<{ indexed: number; messages: number }> {+ if (dialectOf(env.DB) !== "sqlite") {+ const total = await env.DB.prepare("SELECT count(*) AS n FROM messages").first<{ n: number }>();+ const messages = Number(total?.n ?? 0);+ return { indexed: messages, messages };+ }const [indexed, total] = await env.DB.batch<{ n: number }>([env.DB.prepare("SELECT count(*) AS n FROM messages_fts"),env.DB.prepare("SELECT count(*) AS n FROM messages"),diff --git a/src/lib/setup/configuration.ts b/src/lib/setup/configuration.tsindex 2f4b695..0ad6fb0 100644--- a/src/lib/setup/configuration.ts+++ b/src/lib/setup/configuration.ts@@ -1,3 +1,4 @@+import { getDatabaseConfig } from "@/db/with-database";import { hasCloudflareCredentials, isNodeRuntime } from "@/lib/runtime";import type { SetupRequirementCheck } from "./types";@@ -5,13 +6,14 @@ export function getSetupRequirementChecks(env: CloudflareEnv): SetupRequirementCconst hasApiToken = !!env.CF_TOKEN?.trim();const hasGlobalKey = !!env.CF_API_KEY?.trim() && !!env.CF_EMAIL?.trim();+ const database = getDatabaseConfig(env);if (isNodeRuntime(env)) {const mailer = env.EMAIL as unknown as { configured?: boolean };return [{key: "Database",configured: !!env.DB,- message: "DATA_DIR must be writable; the SQLite database is created there on start.",+ message: database.driver === "d1" ? "DATA_DIR must be writable; the SQLite database is created there on start." : "DATABASE_URL must be reachable; migrations are applied on start.",},{key: "Outbound mail",@@ -35,9 +37,9 @@ export function getSetupRequirementChecks(env: CloudflareEnv): SetupRequirementCmessage: "Set CF_TOKEN, or set both CF_API_KEY and CF_EMAIL.",},{- key: "D1 database",+ key: database.driver === "d1" ? "D1 database" : "Database",configured: !!env.DB,- message: "Deploy the Worker with the DB binding from wrangler.jsonc.",+ message: database.driver === "d1" ? "Deploy the Worker with the DB binding from wrangler.jsonc." : "Check DATABASE_URL (and DATABASE_DRIVER) for the external database.",},];}diff --git a/src/lib/spam/engine.ts b/src/lib/spam/engine.tsindex 60593ac..c09dc89 100644--- a/src/lib/spam/engine.ts+++ b/src/lib/spam/engine.ts@@ -1,6 +1,7 @@import { and, eq, inArray, sql } from "drizzle-orm";import type { AppDatabase } from "@/db";import { contacts, domains, spamReputation } from "@/db/schema";+import { charIndex } from "@/db/sql";import { getEmailAddress } from "@/lib/email/address";import { analyzeAuthentication } from "./analyzers/authentication";import { analyzeImpersonation } from "./analyzers/impersonation";@@ -18,7 +19,7 @@ const MAX_KNOWN_DOMAINS = 2000;/** Domains a lookalike sender would imitate: ones the user wrote to or saved, and the instance's own. */async function listKnownDomains(db: AppDatabase, userId: string): Promise<string[]> {- const contactDomain = sql<string>`lower(substr(${contacts.email}, instr(${contacts.email}, '@') + 1))`;+ const contactDomain = sql<string>`lower(substr(${contacts.email}, ${charIndex(contacts.email, "@")} + 1))`;const [contactRows, ownRows] = await Promise.all([db.selectDistinct({ domain: contactDomain }).from(contacts).where(and(eq(contacts.userId, userId), inArray(contacts.source, ["outbound", "manual"])))diff --git a/src/lib/spam/feedback.ts b/src/lib/spam/feedback.tsindex 2a79941..bca410e 100644--- a/src/lib/spam/feedback.ts+++ b/src/lib/spam/feedback.ts@@ -1,6 +1,7 @@-import { eq } from "drizzle-orm";+import { eq, sql } from "drizzle-orm";import { getDb } from "@/db";-import { messages, spamFeedback } from "@/db/schema";+import { messages, spamFeedback, spamReputation, spamTokenStats } from "@/db/schema";+import { excluded, greatest } from "@/db/sql";import { getMailboxAccessLevel } from "@/lib/mailboxes/access";import type { SessionUser } from "@/lib/auth/types";import { createAuditLog } from "@/lib/mailboxes/audit";@@ -32,17 +33,46 @@ export async function applySpamFeedback(env: CloudflareEnv, user: SessionUser, mconst prepared = prepareSpamContent(parsed);const tokens = previous ? JSON.parse(previous.trainingTokens) as string[] : tokenizeMessage(parsed, prepared);const keys = previous ? JSON.parse(previous.reputationKeys) as ReputationKey[] : getReputationKeys(parsed, buildFingerprint(parsed, prepared));- const now = Math.floor(Date.now() / 1000);- const statements: D1PreparedStatement[] = [];+ const now = new Date();+ const statements: Array<PromiseLike<unknown>> = [];const addCounts = (target: SpamClassification, amount: 1 | -1) => {- for (const token of tokens) statements.push(env.DB.prepare(`INSERT INTO spam_token_stats (mailbox_id, token, spam_count, ham_count, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(mailbox_id, token) DO UPDATE SET spam_count = MAX(0, spam_count + excluded.spam_count), ham_count = MAX(0, ham_count + excluded.ham_count), updated_at = excluded.updated_at`).bind(message.mailboxId, token, target === "spam" ? amount : 0, target === "ham" ? amount : 0, now));- for (const item of keys) statements.push(env.DB.prepare(`INSERT INTO spam_reputation (mailbox_id, type, key, messages_seen, spam_count, ham_count, first_seen_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(mailbox_id, type, key) DO UPDATE SET messages_seen = MAX(messages_seen, excluded.messages_seen), spam_count = MAX(0, spam_count + excluded.spam_count), ham_count = MAX(0, ham_count + excluded.ham_count), last_seen_at = excluded.last_seen_at`).bind(message.mailboxId, item.type, item.key, amount > 0 ? 1 : 0, target === "spam" ? amount : 0, target === "ham" ? amount : 0, now, now));+ const spamCount = target === "spam" ? amount : 0;+ const hamCount = target === "ham" ? amount : 0;+ for (const token of tokens) {+ statements.push(db.insert(spamTokenStats).values({ mailboxId: message.mailboxId!, token, spamCount, hamCount, updatedAt: now }).onConflictDoUpdate({+ target: [spamTokenStats.mailboxId, spamTokenStats.token],+ set: {+ spamCount: greatest(0, sql`${spamTokenStats.spamCount} + ${excluded(spamTokenStats.spamCount)}`),+ hamCount: greatest(0, sql`${spamTokenStats.hamCount} + ${excluded(spamTokenStats.hamCount)}`),+ updatedAt: now,+ },+ }));+ }+ for (const item of keys) {+ statements.push(db.insert(spamReputation).values({+ mailboxId: message.mailboxId!, type: item.type, key: item.key, messagesSeen: amount > 0 ? 1 : 0, spamCount, hamCount, firstSeenAt: now, lastSeenAt: now,+ }).onConflictDoUpdate({+ target: [spamReputation.mailboxId, spamReputation.type, spamReputation.key],+ set: {+ messagesSeen: greatest(sql`${spamReputation.messagesSeen}`, sql`${excluded(spamReputation.messagesSeen)}`),+ spamCount: greatest(0, sql`${spamReputation.spamCount} + ${excluded(spamReputation.spamCount)}`),+ hamCount: greatest(0, sql`${spamReputation.hamCount} + ${excluded(spamReputation.hamCount)}`),+ lastSeenAt: now,+ },+ }));+ }};if (previous) addCounts(previous.classification, -1);addCounts(classification, 1);- statements.push(env.DB.prepare(`INSERT INTO spam_feedback (message_id, mailbox_id, actor_user_id, classification, training_tokens, reputation_keys, tokenizer_version, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(message_id) DO UPDATE SET actor_user_id = excluded.actor_user_id, classification = excluded.classification, updated_at = excluded.updated_at`).bind(messageId, message.mailboxId, user.id, classification, JSON.stringify(tokens), JSON.stringify(keys), TOKENIZER_VERSION, now, now));- statements.push(env.DB.prepare("UPDATE messages SET status = ?, folder_id = NULL WHERE id = ?").bind(status, messageId));- await env.DB.batch(statements);+ statements.push(db.insert(spamFeedback).values({+ messageId, mailboxId: message.mailboxId, actorUserId: user.id, classification, trainingTokens: JSON.stringify(tokens),+ reputationKeys: JSON.stringify(keys), tokenizerVersion: TOKENIZER_VERSION, createdAt: now, updatedAt: now,+ }).onConflictDoUpdate({+ target: spamFeedback.messageId,+ set: { actorUserId: user.id, classification, updatedAt: now },+ }));+ statements.push(db.update(messages).set({ status, folderId: null }).where(eq(messages.id, messageId)));+ await db.batch(statements as never);await createAuditLog(env, {actorUserId: user.id,mailboxId: message.mailboxId,diff --git a/src/lib/spam/repository.ts b/src/lib/spam/repository.tsindex 06ac0e7..7ede4f9 100644--- a/src/lib/spam/repository.ts+++ b/src/lib/spam/repository.ts@@ -1,8 +1,17 @@+import { sql } from "drizzle-orm";+import { getDb } from "@/db";+import { spamReputation } from "@/db/schema";import type { ReputationKey } from "./types";export async function recordReputationObservation(env: CloudflareEnv, mailboxId: string, keys: ReputationKey[]): Promise<void> {- const now = Math.floor(Date.now() / 1000);- await env.DB.batch(keys.map((item) => env.DB.prepare(- `INSERT INTO spam_reputation (mailbox_id, type, key, messages_seen, spam_count, ham_count, first_seen_at, last_seen_at) VALUES (?, ?, ?, 1, 0, 0, ?, ?) ON CONFLICT(mailbox_id, type, key) DO UPDATE SET messages_seen = messages_seen + 1, last_seen_at = excluded.last_seen_at`,- ).bind(mailboxId, item.type, item.key, now, now)));+ if (keys.length === 0) return;+ const db = getDb(env);+ const now = new Date();+ await db.batch(keys.map((item) => db+ .insert(spamReputation)+ .values({ mailboxId, type: item.type, key: item.key, messagesSeen: 1, spamCount: 0, hamCount: 0, firstSeenAt: now, lastSeenAt: now })+ .onConflictDoUpdate({+ target: [spamReputation.mailboxId, spamReputation.type, spamReputation.key],+ set: { messagesSeen: sql`${spamReputation.messagesSeen} + 1`, lastSeenAt: now },+ })) as never);}diff --git a/tests/database-dialects.test.mjs b/tests/database-dialects.test.mjsnew file mode 100644index 0000000..260f875--- /dev/null+++ b/tests/database-dialects.test.mjs@@ -0,0 +1,186 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { dirname, join } from "node:path";+import test, { after } from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const outDir = mkdtempSync(join(root, "tests", ".tmp-database-dialects-"));+after(() => rmSync(outDir, { recursive: true, force: true }));++await build({+ entryPoints: {+ dialect: join(root, "src/db/dialect.ts"),+ drivers: join(root, "src/db/drivers/types.ts"),+ backups: join(root, "src/lib/backups/export.ts"),+ inspect: join(root, "tests/fixtures/inspect-schema.ts"),+ },+ outdir: outDir,+ outExtension: { ".js": ".mjs" },+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node22",+ alias: { "@": join(root, "src") },+ packages: "external",+ logLevel: "silent",+});++const load = (name) => import(pathToFileURL(join(outDir, `${name}.mjs`)).href);+const { resolveDatabaseConfig, inferDriver, schemaDialect } = await load("dialect");+const { numberPlaceholders, normalizeParam } = await load("drivers");+const { BACKUP_TABLES, INTERNAL_TABLES, INTERNAL_TABLE_PATTERNS } = await load("backups");++test("no DATABASE_URL keeps D1", () => {+ assert.deepEqual(resolveDatabaseConfig({}), { dialect: "sqlite", driver: "d1" });+ assert.deepEqual(resolveDatabaseConfig({ DATABASE_DRIVER: "d1" }), { dialect: "sqlite", driver: "d1" });+ assert.deepEqual(resolveDatabaseConfig({ DATABASE_URL: " " }), { dialect: "sqlite", driver: "d1" });+});++test("drivers are inferred from the connection string", () => {+ const cases = [+ ["postgres://u:[email protected]/app", "node-postgres", "postgres"],+ ["postgresql://u:[email protected]:5432/postgres", "node-postgres", "postgres"],+ ["postgres://u:[email protected]/app?sslmode=require", "neon", "postgres"],+ ["pglite://./data/pg", "pglite", "postgres"],+ ["mysql://u:[email protected]/app", "mysql2", "mysql"],+ ["mysql://u:[email protected]/app", "planetscale", "mysql"],+ ["mariadb://u:[email protected]/app", "mysql2", "mysql"],+ ["libsql://mailflare-me.turso.io", "libsql", "sqlite"],+ ["https://mailflare-me.turso.io", "libsql", "sqlite"],+ ["file:./data/mailflare.db", "better-sqlite3", "sqlite"],+ ];+ for (const [url, driver, dialect] of cases) {+ assert.equal(inferDriver(url), driver, url);+ assert.deepEqual(resolveDatabaseConfig({ DATABASE_URL: url }), { dialect, driver, url, authToken: undefined }, url);+ }+});++test("DATABASE_DRIVER overrides inference and accepts aliases", () => {+ assert.equal(resolveDatabaseConfig({ DATABASE_URL: "postgres://h/db", DATABASE_DRIVER: "postgres-js" }).driver, "postgres-js");+ assert.equal(resolveDatabaseConfig({ DATABASE_URL: "postgres://h/db", DATABASE_DRIVER: "supabase" }).driver, "node-postgres");+ assert.equal(resolveDatabaseConfig({ DATABASE_URL: "postgres://h/db", DATABASE_DRIVER: "vercel" }).driver, "neon");+ assert.equal(resolveDatabaseConfig({ DATABASE_URL: "mysql://h/db", DATABASE_DRIVER: "tidb" }).driver, "mysql2");+ assert.equal(resolveDatabaseConfig({ DATABASE_URL: "libsql://h", DATABASE_AUTH_TOKEN: "t" }).authToken, "t");+ assert.throws(() => resolveDatabaseConfig({ DATABASE_URL: "postgres://h/db", DATABASE_DRIVER: "oracle" }), /Unsupported DATABASE_DRIVER/);+ assert.throws(() => resolveDatabaseConfig({ DATABASE_DRIVER: "pglite" }), /needs DATABASE_URL/);+ assert.throws(() => inferDriver("ftp://nope"), /Cannot infer/);+});++test("a Hyperdrive binding supplies the connection string", () => {+ const config = resolveDatabaseConfig({ DATABASE_DRIVER: "node-postgres" }, "postgres://hyperdrive/db");+ assert.equal(config.url, "postgres://hyperdrive/db");+ assert.equal(config.dialect, "postgres");+});++test("the schema dialect follows the environment", () => {+ const original = { ...process.env };+ try {+ delete process.env.DATABASE_URL;+ delete process.env.DATABASE_DRIVER;+ delete process.env.MAILFLARE_DB_DIALECT;+ assert.equal(schemaDialect(), "sqlite");+ process.env.DATABASE_URL = "postgres://h/db";+ assert.equal(schemaDialect(), "postgres");+ process.env.DATABASE_URL = "mysql://h/db";+ assert.equal(schemaDialect(), "mysql");+ process.env.MAILFLARE_DB_DIALECT = "postgres";+ assert.equal(schemaDialect(), "postgres");+ process.env.MAILFLARE_DB_DIALECT = "oracle";+ assert.throws(() => schemaDialect(), /MAILFLARE_DB_DIALECT/);+ } finally {+ for (const key of Object.keys(process.env)) if (!(key in original)) delete process.env[key];+ Object.assign(process.env, original);+ }+});++test("placeholders are numbered outside literals and comments only", () => {+ assert.equal(numberPlaceholders("SELECT * FROM t WHERE a = ? AND b = ?"), "SELECT * FROM t WHERE a = $1 AND b = $2");+ assert.equal(numberPlaceholders("SELECT '?' , \"a?b\", ? -- why?\n, ?"), "SELECT '?' , \"a?b\", $1 -- why?\n, $2");+ assert.equal(numberPlaceholders("SELECT 'it''s ?' , ?"), "SELECT 'it''s ?' , $1");+});++test("parameters are normalised for every driver", () => {+ assert.equal(normalizeParam(undefined), null);+ assert.equal(normalizeParam(new Date(1_700_000_000_500)), 1_700_000_000);+ assert.equal(normalizeParam("x"), "x");+ assert.ok(normalizeParam(new ArrayBuffer(2)) instanceof Uint8Array);+});++function inspect(dialect) {+ const result = spawnSync(process.execPath, [join(outDir, "inspect.mjs")], { env: { ...process.env, MAILFLARE_DB_DIALECT: dialect }, encoding: "utf8" });+ assert.equal(result.status, 0, result.stderr);+ return JSON.parse(result.stdout);+}++const schemas = { sqlite: inspect("sqlite"), postgres: inspect("postgres"), mysql: inspect("mysql") };++test("every dialect defines the same tables and columns", () => {+ const names = (schema) => Object.keys(schema).sort();+ assert.deepEqual(names(schemas.postgres), names(schemas.sqlite));+ assert.deepEqual(names(schemas.mysql), names(schemas.sqlite));+ for (const table of names(schemas.sqlite)) {+ const columns = (schema) => schema[table].columns.map((column) => column.name);+ assert.deepEqual(columns(schemas.postgres), columns(schemas.sqlite), table);+ assert.deepEqual(columns(schemas.mysql), columns(schemas.sqlite), table);+ }+});++test("MySQL never indexes a TEXT column", () => {+ for (const [table, { columns, indexed }] of Object.entries(schemas.mysql)) {+ for (const name of indexed) {+ const column = columns.find((candidate) => candidate.name === name);+ assert.ok(column, `${table}.${name}`);+ assert.notEqual(column.sqlType, "longtext", `${table}.${name} is indexed but LONGTEXT`);+ }+ }+});++test("MySQL keeps every index under the InnoDB key size limit", () => {+ for (const [table, { indexBytes }] of Object.entries(schemas.mysql)) {+ for (const [name, bytes] of Object.entries(indexBytes)) assert.ok(bytes <= 3072, `${table}.${name} is ${bytes} bytes`);+ }+});++const migrationTables = (directory) =>+ new Set(+ readdirSync(join(root, directory))+ .filter((name) => name.endsWith(".sql"))+ .flatMap((name) => [...readFileSync(join(root, directory, name), "utf8").matchAll(/CREATE TABLE [`"]?(\w+)[`"]?/gi)].map((match) => match[1])),+ );++for (const [dialect, directory] of [["postgres", "drizzle/migrations-pg"], ["mysql", "drizzle/migrations-mysql"], ["sqlite", "drizzle/migrations"]]) {+ // SQLite's history includes tables later dropped; its coverage is checked by backup-table-list.test.mjs.+ const replayable = dialect !== "sqlite";+ test(`${dialect} migrations create the schema tables`, { skip: !replayable }, () => {+ const created = migrationTables(directory);+ for (const table of Object.keys(schemas[dialect])) assert.ok(created.has(table), `${table} is missing from ${directory}`);+ });++ test(`${dialect} backups cover every migrated table`, { skip: !replayable }, () => {+ const created = [...migrationTables(directory)].filter(+ (name) => !INTERNAL_TABLES.includes(name) && !INTERNAL_TABLE_PATTERNS.some((pattern) => name.startsWith(pattern.replace(/%$/, ""))),+ );+ assert.deepEqual(created.filter((name) => !BACKUP_TABLES.includes(name)), []);+ assert.deepEqual(BACKUP_TABLES.filter((name) => !created.includes(name)), []);+ });++ test(`${dialect} migration bundle matches the SQL files`, () => {+ const file = dialect === "sqlite" ? "bundle.json" : `bundle-${dialect}.json`;+ const bundle = JSON.parse(readFileSync(join(root, "src/lib/migrations", file), "utf8"));+ const names = readdirSync(join(root, directory)).filter((name) => name.endsWith(".sql")).sort();+ assert.deepEqual(bundle.migrations.map((migration) => migration.name), names, "run `npm run db:bundle`");+ for (const migration of bundle.migrations) assert.ok(migration.statements.length > 0, migration.name);+ });+}++test("PostgreSQL and MySQL ship the triggers SQLite has", () => {+ for (const directory of ["drizzle/migrations-pg", "drizzle/migrations-mysql"]) {+ const sql = readFileSync(join(root, directory, "0001_triggers_and_seeds.sql"), "utf8");+ for (const needle of ["jmap_changes", "jmap_mailbox_revisions", "trashed_at", "jmap_change_floor", "app_settings", "backup_settings"]) {+ assert.ok(sql.includes(needle), `${directory} lacks ${needle}`);+ }+ }+});diff --git a/tests/fixtures/inspect-schema.ts b/tests/fixtures/inspect-schema.tsnew file mode 100644index 0000000..82264a7--- /dev/null+++ b/tests/fixtures/inspect-schema.ts@@ -0,0 +1,46 @@+// Prints the table/column/index layout of the schema built for the dialect in MAILFLARE_DB_DIALECT.+import { getTableConfig as pgConfig } from "drizzle-orm/pg-core";+import { getTableConfig as mysqlConfig } from "drizzle-orm/mysql-core";+import { getTableConfig as sqliteConfig } from "drizzle-orm/sqlite-core";+import * as schema from "../../src/db/schema/index";++const dialect = process.env.MAILFLARE_DB_DIALECT ?? "sqlite";+const configOf = dialect === "postgres" ? pgConfig : dialect === "mysql" ? mysqlConfig : sqliteConfig;+const out: Record<string, unknown> = {};+type Named = { name?: string };+type TableConfig = {+ name: string;+ columns: Array<{ name: string; primary: boolean; isUnique: boolean; getSQLType(): string }>;+ indexes: Array<{ config: { name: string; columns: Named[] } }>;+ uniqueConstraints?: Array<{ name?: string; columns: Named[] }>;+ foreignKeys: Array<{ reference(): { columns: Named[] } }>;+};++for (const value of Object.values(schema.schema)) {+ const config = (configOf as (table: unknown) => TableConfig)(value);+ const columns = config.columns.map((column) => ({ name: column.name, sqlType: column.getSQLType() }));+ const typeOf = (name: string) => columns.find((column) => column.name === name)?.sqlType as string | undefined;+ const bytesOf = (name: string) => {+ const type = typeOf(name) ?? "";+ const length = /\((\d+)\)/.exec(type);+ return length ? Number(length[1]) * 4 : 8;+ };+ const indexed = new Set<string>();+ const indexBytes: Record<string, number> = {};+ const track = (name: string, indexColumns: Named[]) => {+ let bytes = 0;+ for (const column of indexColumns) {+ if (column?.name) {+ indexed.add(column.name);+ bytes += bytesOf(column.name);+ }+ }+ indexBytes[name] = bytes;+ };+ for (const column of config.columns) if (column.primary || column.isUnique) indexed.add(column.name);+ for (const index of config.indexes) track(index.config.name, index.config.columns);+ for (const unique of config.uniqueConstraints ?? []) track(unique.name ?? "unique", unique.columns);+ for (const fk of config.foreignKeys) for (const column of fk.reference().columns) if (column.name) indexed.add(column.name);+ out[config.name] = { columns, indexed: [...indexed], indexBytes };+}+console.log(JSON.stringify(out));diff --git a/worker.ts b/worker.tsindex d70571d..b7f15ba 100644--- a/worker.ts+++ b/worker.ts@@ -1,3 +1,4 @@+import { withDatabase } from "./src/db/with-database";import { withStorage } from "./src/lib/storage";import vinextHandler from "vinext/server/fetch-handler";import {@@ -30,7 +31,7 @@ export { RealtimeHub } from "./src/lib/realtime/hub";export default {async fetch(request: Request, rawEnv: CloudflareEnv, ctx: ExecutionContext) {- const env = withStorage(rawEnv);+ const env = withDatabase(withStorage(rawEnv));const url = new URL(request.url);if (url.pathname === "/api/realtime") {if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {@@ -55,7 +56,7 @@ export default {},async email(message: ForwardableEmailMessage, rawEnv: CloudflareEnv, ctx: ExecutionContext) {- const env = withStorage(rawEnv);+ const env = withDatabase(withStorage(rawEnv));try {if (message.rawSize > 25 * 1024 * 1024) {message.setReject("Message rejected: raw email exceeds the 25 MiB receiving limit. Send a download link instead.");@@ -104,7 +105,7 @@ export default {},async queue(batch: MessageBatch, rawEnv: CloudflareEnv): Promise<void> {- const env = withStorage(rawEnv);+ const env = withDatabase(withStorage(rawEnv));for (const msg of batch.messages) {try {if (isInboundQueueMessage(msg.body)) {@@ -134,7 +135,7 @@ export default {},async scheduled(controller: ScheduledController, rawEnv: CloudflareEnv, ctx: ExecutionContext) {- const env = withStorage(rawEnv);+ const env = withDatabase(withStorage(rawEnv));if (controller.cron === "0 2 * * *") ctx.waitUntil(runScheduledDatabaseBackup(env, new Date(controller.scheduledTime)));ctx.waitUntil(runAgentMaintenance(env));ctx.waitUntil(runTrashRetention(env, new Date(controller.scheduledTime)));