Skip to content
Tinbox

tutorials

Postgres to D1 migration: moving an email app to edge SQLite

October 9, 2026

#cloudflare-d1#postgres#sqlite-migration#email-app#drizzle
Message history moves across a paper bridge between two archives.

You built an email app on Postgres, and now you want it co-located with the Worker that serves it on Cloudflare D1. There is no pg_dump | d1 restore, and the first naive import fails on the first timestamptz. Here is the migration that actually lands.

A Postgres to D1 migration sounds like a database swap and is really a dialect port. D1 is SQLite at the edge, and SQLite is a genuinely different engine: four storage classes instead of dozens of types, no timestamptz, no jsonb, no arrays, no ILIKE, no to_tsvector. The schema concepts carry over; the syntax and the type system do not. For an email app this is mostly tractable because mail is append-mostly and read-heavy, but the migration has sharp edges, and the sharpest is data that was fine in Postgres and is illegal in SQLite.

This walks the whole path: porting the schema, rewriting the queries SQLite cannot run, exporting rows out of Postgres, and backfilling them into D1 within its limits. It draws on Tinbox's own pivot from a Postgres MVP to a D1 + R2 + Queues stack, so the gotchas are the ones we actually hit.

Can you migrate a Postgres database directly to D1?

No. A pg_dump file will not import into D1, because the dump is full of Postgres-specific syntax and types that SQLite rejects. The reliable migration is three phases: recreate the schema with SQLite types, rewrite the application's Postgres-only SQL, then stream the data across in batches. Treat it as a port, not a copy.

It helps to be concrete about why the dump fails. A Postgres schema dump for an email app typically contains, in the first hundred lines:

  • CREATE EXTENSION statements (pgcrypto, uuid-ossp) that mean nothing to SQLite.
  • Column types like timestamptz, jsonb, uuid, text[], numeric(12,2) that SQLite does not have.
  • CREATE SEQUENCE plus nextval() defaults, where SQLite uses AUTOINCREMENT or app-generated IDs.
  • GIN indexes over to_tsvector(...) for full-text search, which has no SQLite equivalent.

Each of those is a translation, and the data rows themselves (boolean t/f, ISO timestamp strings, \x blobs) need converting too. So you build the target schema by hand, fix the queries, and move the data deliberately.

How do Postgres types map to D1 (SQLite) types?

SQLite has only four storage classes, so every Postgres type collapses into INTEGER, REAL, TEXT, or BLOB. The mapping below is the one that keeps an email app's queries fast and its data lossless. The two decisions that matter most: store timestamps as INTEGER epoch milliseconds, and store anything structured (JSON, arrays, UUIDs) as TEXT.

PostgresD1 / SQLiteNotes
timestamptz, timestampINTEGEREpoch milliseconds. Sortable, no parsing, no timezone ambiguity.
booleanINTEGER0 or 1. SQLite has no boolean type.
uuidTEXTStore the canonical string; no native UUID.
jsonb, jsonTEXTStore the JSON string, parse in app code; query with json_extract if needed.
text[], int[]TEXTJSON array in a text column. No native arrays.
varchar(n), textTEXTSQLite ignores the length constraint anyway.
numeric(12,2)INTEGER or TEXTStore cents as INTEGER, or the exact decimal as TEXT. Avoid REAL for money.
bytea (small)BLOBBut for email, push bytes to R2 instead (see below).
serial / sequence PKTEXT or INTEGERPrefer app-generated string IDs; AUTOINCREMENT works but couples you to insert order.

Here is a representative Postgres messages table and its D1 translation, so the mapping is not abstract:

-- BEFORE: Postgres
CREATE TABLE messages (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  thread_id   uuid NOT NULL REFERENCES threads(id),
  message_id  text UNIQUE,
  is_read     boolean NOT NULL DEFAULT false,
  recipients  jsonb NOT NULL DEFAULT '[]'::jsonb,
  labels      text[] NOT NULL DEFAULT '{}',
  body_html   text,
  date        timestamptz NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now()
);
-- AFTER: D1 (SQLite)
CREATE TABLE messages (
  id          TEXT PRIMARY KEY,                 -- app-generated id string
  thread_id   TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
  message_id  TEXT UNIQUE,
  is_read     INTEGER NOT NULL DEFAULT 0,       -- boolean -> 0/1
  recipients  TEXT NOT NULL DEFAULT '[]',       -- jsonb -> JSON in TEXT
  labels      TEXT NOT NULL DEFAULT '[]',       -- text[] -> JSON in TEXT
  body_html   TEXT,
  date        INTEGER NOT NULL,                 -- timestamptz -> epoch millis
  created_at  INTEGER NOT NULL                  -- timestamptz -> epoch millis
);

A subtle one worth flagging: gen_random_uuid() as a column default has no SQLite equivalent you want to rely on, so IDs move to the application layer. If your Postgres app already generated IDs in code (a KSUID, a nanoid), you are done. If it leaned on the database default, this is the moment to move ID generation into the app, which is healthier anyway because it lets you know an ID before the row exists.

If you are designing the target tables from scratch rather than translating one-for-one, the full reference shape (threads, messages, attachments, indexes) is laid out in designing a D1 email database schema. This article assumes you have a Postgres schema and want the closest faithful port.

What Postgres SQL does not work on D1?

Several Postgres idioms your email app almost certainly uses have no direct D1 equivalent and will throw at runtime, not at migration time, so find them before you cut over. The big four for an email app are full-text search, ILIKE, array operators, and the details of RETURNING and ON CONFLICT.

Go through your query layer and translate each pattern:

ILIKE for case-insensitive search. SQLite has no ILIKE. Plain LIKE is already case-insensitive for ASCII in SQLite, so a substring search ports directly:

-- Postgres
SELECT * FROM messages WHERE subject ILIKE '%invoice%';
-- D1: LIKE is case-insensitive for ASCII
SELECT * FROM messages WHERE subject LIKE '%invoice%';

But LIKE '%term%' is a full table scan in both engines. If your Postgres app used to_tsvector / to_tsquery for real search, that is the harder rewrite.

Full-text search (to_tsvector). There is no port; you switch engines. SQLite ships FTS5, a virtual table you populate alongside messages:

-- D1: an FTS5 search index over the fields you search
CREATE VIRTUAL TABLE messages_fts USING fts5(
  subject, body_text, sender,
  content='messages', content_rowid='rowid'
);

-- Query it with MATCH instead of @@/to_tsquery
SELECT m.* FROM messages_fts f
JOIN messages m ON m.rowid = f.rowid
WHERE messages_fts MATCH 'invoice OR receipt'
ORDER BY rank
LIMIT 50;

You keep messages_fts in sync with triggers (or in app code) on insert and update. That is more setup than a GIN index, but it is the supported path on D1.

Arrays and their operators. Postgres labels @> ARRAY['urgent'] or 'urgent' = ANY(labels) has no SQLite equivalent because there is no array type. With labels stored as JSON text, you either filter in app code after parsing, or use json_each:

-- D1: does this message carry the 'urgent' label?
SELECT m.* FROM messages m, json_each(m.labels) j
WHERE j.value = 'urgent';

RETURNING and ON CONFLICT. Recent D1 supports RETURNING, but lean on it lightly and test it; the safest cross-engine pattern is to generate the ID in app code and not depend on the database handing it back. ON CONFLICT works but you must name the conflict target explicitly, which matters for idempotent email ingestion keyed on message_id:

-- Idempotent insert: ignore a duplicate inbound email
INSERT INTO messages (id, message_id, thread_id, date, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(message_id) DO NOTHING;

CTEs and window functions are supported, so reporting queries usually port unchanged. The failures cluster in search, arrays, and the ILIKE/RETURNING ergonomics.

One D1-specific trap to know before you trust any rewritten query: D1 has had subtle behavior differences from server SQLite, and correlated subqueries in particular have returned wrong results in some cases (a subquery referencing the outer row silently resolving to the wrong value). If you port a Postgres correlated subquery, such as an inline per-thread unread count, verify the output against known data before shipping it. The robust pattern for an email app is to maintain rollup columns (message_count, has_unread) at write time rather than compute them inline on read.

How do you backfill the data from Postgres into D1?

Export each Postgres table to JSON in primary-key order, converting types as you read, then batch-insert into D1 in chunks small enough to fit its per-batch limits. You cannot COPY or restore a dump; you stream rows out of one engine and bind them into the other, a few hundred at a time.

D1's relevant limits during a backfill: a single batched call is capped (on the order of 100 bound statements per batch(), and a few megabytes per request), so you cannot insert a million rows in one statement. You loop.

Step 1: export from Postgres, converting types as you go. Stream in PK order so the job is resumable. Convert timestamps to epoch millis and booleans to 0/1 here, where you have a real Postgres driver, rather than guessing later:

// export.ts: run with a Node Postgres client, write NDJSON
import { Client } from "pg";
import { createWriteStream } from "node:fs";

const pg = new Client({ connectionString: process.env.PG_URL });
await pg.connect();
const out = createWriteStream("messages.ndjson");

const { rows } = await pg.query(
  `SELECT id, thread_id, message_id, is_read, recipients, labels,
          body_html, date, created_at
   FROM messages ORDER BY id`,
);

for (const r of rows) {
  out.write(
    JSON.stringify({
      id: r.id,
      thread_id: r.thread_id,
      message_id: r.message_id,
      is_read: r.is_read ? 1 : 0,                 // boolean -> 0/1
      recipients: JSON.stringify(r.recipients),    // jsonb -> string
      labels: JSON.stringify(r.labels),            // text[] -> JSON string
      body_html: r.body_html,
      date: r.date.getTime(),                      // timestamptz -> millis
      created_at: r.created_at.getTime(),
    }) + "\n",
  );
}
out.end();
await pg.end();

For tables with millions of rows, swap the single query for a cursor (pg-cursor) so you do not buffer the whole table in memory.

Step 2: move inline bytes to R2 first. If your Postgres messages stored raw .eml or attachment bytes in a bytea column, do not carry them into D1. Upload each blob to R2 keyed by its content hash, and replace the column with the R2 object key. Large blobs will blow past D1's row and batch limits and slow every list query.

Step 3: batch-insert into D1. Read the NDJSON in chunks and bind each chunk into a single batch() under the statement cap:

// import.ts: runs inside a Worker (or wrangler dev) with the D1 binding
const CHUNK = 200; // stay well under the per-batch statement cap

export async function importMessages(db: D1Database, rows: any[]) {
  const stmt = db.prepare(
    `INSERT INTO messages
       (id, thread_id, message_id, is_read, recipients, labels,
        body_html, date, created_at)
     VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)
     ON CONFLICT(message_id) DO NOTHING`,
  );

  for (let i = 0; i < rows.length; i += CHUNK) {
    const slice = rows.slice(i, i + CHUNK);
    const batch = slice.map((r) =>
      stmt.bind(
        r.id, r.thread_id, r.message_id, r.is_read,
        r.recipients, r.labels, r.body_html, r.date, r.created_at,
      ),
    );

    // Retry the whole chunk on transient failure.
    for (let attempt = 0; ; attempt++) {
      try {
        await db.batch(batch);
        break;
      } catch (err) {
        if (attempt >= 4) throw err;
        await new Promise((r) => setTimeout(r, 250 * 2 ** attempt));
      }
    }
  }
}

The ON CONFLICT(message_id) DO NOTHING makes the whole import idempotent: if a chunk half-applies and you re-run, duplicates are skipped instead of erroring. Migrate tables in dependency order (inboxes, then threads, then messages, then attachments) so foreign keys resolve. If you have foreign keys enabled and ordering is awkward, you can PRAGMA foreign_keys=OFF for the load and re-enable after.

A real failure you will hit if you ignore the cap:

✘ [ERROR] D1_ERROR: too many SQL variables / batch too large

That is the per-batch limit rejecting an oversized chunk. Lower CHUNK, or split wide rows. It is a hard stop, not a slowdown, so size for it up front.

How do you verify the migration landed correctly?

Compare row counts per table between the two databases, then spot-check the email-specific invariants that a count alone will not catch: threading, ordering, and attachment links. A successful COUNT(*) match is necessary but not sufficient, because the failure modes here are silent.

Start with counts:

# Postgres
psql "$PG_URL" -c "SELECT count(*) FROM messages;"

# D1
npx wrangler d1 execute my-inbox-db --remote \
  --command="SELECT count(*) FROM messages;"

Then check the things types and ordering can quietly corrupt:

  • Timestamp sanity. SELECT date FROM messages ORDER BY date DESC LIMIT 1; in D1 should be a recent epoch-millis value. If you see 1970-era numbers, you stored seconds instead of milliseconds somewhere; if everything is NULL, a .getTime() ran on a null date.
  • JSON round-trips. SELECT recipients FROM messages WHERE message_id = ? should parse cleanly with JSON.parse. Double-encoding (a JSON string of a JSON string) is the classic bug from stringifying an already-stringified jsonb.
  • Threading resolves. Open a known multi-message thread in the app. Messages should appear in order and grouped correctly, which exercises both the foreign keys and the date column.
  • Attachments link. Open a message with an attachment and confirm it downloads, proving the R2 keys survived the move.

If counts match and those four checks pass, the migration is sound. If the app rendered against Postgres and renders identically against D1, you are done with the data and can cut traffic over.

Skip the port: deploy a stack that is already on D1

Everything above is the hard way, and it is worth doing if you have an existing Postgres email app you must carry forward. But if what you actually want is an email stack that already lives on D1 + R2 + Queues, correctly typed and indexed, you do not have to derive it from a Postgres port. Tinbox is the result of having done exactly this pivot, from a Postgres MVP to an edge-native stack, so the schema, the FTS5 search table, the R2 blob split, and the idempotent ingestion are already in place.

One command provisions the D1 database, the R2 bucket, and the Worker with the migrations applied:

npx tinbox init yourdomain.com

You can still bring your old data in: the same batched-insert pattern from this article is how the importers backfill, and the schema you would be migrating to is the one this scaffolds. Use it as the canonical D1 email schema the next time you face this port.

Related reading from here:

Deploy this yourself: npx tinbox init yourdomain.com. The schema, migrations, and importer patterns are part of what the bootstrapper scaffolds, and the docs walk the data backfill in detail.

Frequently asked questions

Can you migrate a Postgres database directly to Cloudflare D1?

Not with a straight dump-and-restore. D1 is SQLite, so a pg_dump file will not import as-is: Postgres-specific types (timestamptz, jsonb, uuid, arrays), sequences, and SQL like RETURNING or ILIKE all need translating. The reliable path is to recreate the schema with SQLite types, then stream rows out of Postgres and batch-insert them into D1.

How do Postgres types map to D1 (SQLite) types?

SQLite has four storage classes (INTEGER, REAL, TEXT, BLOB), so everything collapses into those. Use INTEGER epoch milliseconds for timestamptz, INTEGER 0/1 for boolean, TEXT for uuid and for jsonb (store the JSON string and parse in app code), TEXT for varchar/text, and REAL for numeric where you can tolerate float. There is no native array type, so Postgres arrays become JSON in a TEXT column.

What Postgres SQL does not work on Cloudflare D1?

RETURNING is supported in recent D1 but behaves more narrowly, ILIKE does not exist (use LIKE, which is case-insensitive for ASCII in SQLite), Postgres array operators and to_tsvector full-text search have no equivalent (use an FTS5 virtual table instead), and ON CONFLICT works but you must name the conflict target. Window functions and CTEs are supported.

What are the size limits when backfilling data into D1?

A single D1 batch is capped (on the order of 100 bound statements per batch and a few megabytes per request), and the whole database has a storage ceiling per Cloudflare's current limits. Backfill in chunks of a few hundred rows per batch, push large blobs (raw .eml, attachments) to R2 instead of D1, and run the import in a loop with backoff rather than one giant statement.

Should email bodies and attachments go in D1 during migration?

No. Keep small text/HTML bodies and a preview in D1, but move the full raw .eml and all attachment bytes to R2 and store only the object key. Large blobs blow past D1 row and batch limits and slow every list query. The migration is a good moment to do this split if your Postgres schema stored bytes inline.