Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

D1

Run your Models on Cloudflare D1.

Installing

The D1 adapter comes with @forestfuture/active-record, as its /d1 entry:

npm install @forestfuture/active-record

Binding a database

Bind your D1 database in your Wrangler config:

{
  "d1_databases": [{ "binding": "DB", "database_name": "my-app-db", "database_id": "…" }],
}

Then run npx active-record init, which names it in your active-record.jsonc as a D1 database. active-record schema reads its migrations through your Wrangler config, and your generated schema names it with adapter: d1({ binding: "DB" }). Your Models then query it with nothing to set up. connect(env.DB) opens it yourself, for a request’s database or an explicit one. active-record migrate applies your migrations through Wrangler.

If your Wrangler config is in another folder, name it in the database’s entry with wranglerConfig.

Reading your own writes

With read replication, wrap each request in withSession, from @forestfuture/active-record/d1. It opens a D1 Session, so the request reads its own writes, and carries its bookmark to the user’s next request.

Sending queries in one round trip

D1 sends a batch of queries in one round trip. A preload sends its whole tree on one database that way, with the records’ own query, so includes({ articles: "comments" }) is three queries in one round trip. A page sends its COUNT and its records together, with their preloads.

A batch runs as one transaction, so every query in it reads the same data. A preload’s nested query that would bind more than 100 values waits for the records above it, and takes one more round trip.

D1 also differs in these ways.

No interactive transactions

D1 can’t hold a transaction open while your Worker awaits, so there’s no transaction(async (tx) => …). You can’t read, decide, then write atomically.

What you can make atomic is a set of writes prepared in advance: batch sends bulk writes and records together, and D1 writes all of them or none. Active Record uses the same batches itself:

  • A destroy’s dependent strategies on the owner’s database are written in one batch with its DELETE.
  • A record autosaved with its owner joins the owner’s batch when it’s on the owner’s database and the owner’s key is known in advance.

Generating keys in code

Rows in a batch can only point at each other through keys that exist before it’s sent. Generated TEXT keys are made in code by generateId, so records have their key from build(). Then:

  • A graph of new records built through associations on one database saves in one atomic batch.
  • A batch can insert rows that point at each other.

When D1 generates the key (INTEGER PRIMARY KEY), it doesn’t exist until the row is written. An owner is written first, then the records built through it in the next batch, a level at a time, and the batches aren’t atomic together. See Autosaving.

Uniqueness is checked twice

The uniqueness validation asks D1 before saving, which gives a friendly error, but two requests can both pass it at once. Only a UNIQUE index guarantees uniqueness. Declare both, and handle RecordNotUnique where a race matters. To create such a row only once, use createOrFindBy with the index alone.

caseSensitive: false compares with SQLite’s lower(), which only lowercases ASCII letters, so "Ä" and "ä" are still different.

Bound parameters

D1 allows 100 bound values in one statement. The adapter binds lists as one JSON value (json_each), so where({ id: [...] }), find([...]), preloads, and insertAll work with any number of values.

D1 takes at most 2 MB in one value. When a bulk write’s rows add up to more, the adapter sends them as several statements in one batch, which writes all of them or none. D1 counts the batch as one query.

Foreign keys are enforced

D1 enforces the foreign keys a table declares with REFERENCES. Destroying a record whose rows still point at it throws InvalidForeignKey, unless the association has a dependent strategy that removes or updates those rows first. A foreign key that isn’t declared in the table isn’t checked at all.

Nothing rolls back after a write

Once D1 has accepted a write, it’s done. An error thrown by an after-callback reaches the caller, but the record stays saved.

Decimals keep about 15 digits

SQLite stores a decimal as a number, so D1 keeps about 15 significant digits of it and rounds the rest: "1.2345678901234567891" reads back as "1.234567890123457". Postgres keeps every digit.

Last updated on