Skip to content
Esc

    Search bindings, commands, errors and guides.

    Storage / D1

    Storage

    D1

    Run D1 databases on OpenOrange, where each database is one Rivet Actor with its own SQLite database.

    Drop-in

    Runs on Internal Rivet Actor per database, on the Durable Object SQL bridge

    Works
    prepare(), batch(), exec(), sessions, and orange d1 migrations, with JSON, FTS5, and window functions
    Differs
    meta.rows_read and meta.rows_written are approximate, and the PRAGMAs that D1 refuses run
    Missing
    DELETE ... LIMIT, UPDATE ... LIMIT, SQLite math functions such as cos(), query(), dump(), and read replicas
    Migration
    Migration with downtime orange migrate d1 refuses writes during the move, and every query fails while Cloudflare exports the database. A 1 GB database froze writes for about 3 minutes. Migration guide
    Configure
    d1_databases
    Scales by
    Database
    Checks
    1 pass

    A D1 database on OpenOrange is one Rivet Actor with its own SQLite database. Your D1 code, migrations, and Wrangler configuration run unchanged.

    Quickstart

    1. Bind the database

      Add a d1_databases entry to wrangler.jsonc. Keep your Cloudflare database_id: Orange uses it as the database’s name.

      {
        "name": "d1-migrations",
        "main": "src/index.ts",
        "compatibility_date": "2026-09-03",
        "d1_databases": [
          {
            "binding": "DB",
            "database_name": "comments",
            "database_id": "d1-migrations-comments"
          }
        ]
      }
    2. Write a migration

      Put numbered SQL files in migrations/, as for Wrangler. This one creates the table and adds three rows.

      -- migrations/0001_create_comments_table.sql
      CREATE TABLE IF NOT EXISTS comments (
      	id INTEGER PRIMARY KEY NOT NULL,
      	author TEXT NOT NULL,
      	content TEXT NOT NULL
      );
      
      INSERT INTO comments (author, content)
      VALUES
      	('Kristian', 'Congrats!'),
      	('Serena', 'Great job!'),
      	('Max', 'Keep up the good work!');
    3. Query it from your Worker

      interface Env {
        DB: D1Database;
      }
      
      export default {
        async fetch(request, env): Promise<Response> {
          if (request.method === "POST") {
            const { author, content } = await request.json<{ author: string; content: string }>();
            const comment = await env.DB.prepare(
              "INSERT INTO comments (author, content) VALUES (?, ?) RETURNING *",
            )
              .bind(author, content)
              .first();
            return Response.json(comment, { status: 201 });
          }
          const { results } = await env.DB.prepare("SELECT * FROM comments ORDER BY id").all();
          return Response.json({ comments: results });
        },
      } satisfies ExportedHandler<Env>;
    4. Apply the migration

      orange d1 migrations apply DB

      It lists each new migration and marks it ✅ when it applies.

    5. Run it

      orange dev shows the database as a Rivet Actor.

      orange dev
        Binding   Resource      Runs on
        env.DB    D1 Database   Rivet Actor

      A GET returns the three rows from the migration. A POST adds one:

      curl localhost:8787/comments -d '{"author":"Ada","content":"Nice work"}'
      {"id":4,"author":"Ada","content":"Nice work"}

    How it works

    • Each database is one Rivet Actor with its own SQLite database. Result shapes, meta, and error text match wrangler dev.
    • Under orange dev, it lives in your project’s .open-orange directory, so rows survive a restart. After orange deploy, it runs on your Rivet cluster.
    • One actor serves each database. For more throughput, split the data into more databases, such as one per tenant.
    AI context Compatibility, limits and details

    Written for LLMs and coding agents: every edge case, measurement, and known deviation. You do not need it to use the feature.

    Compatibility

    FeatureStatusNotes
    prepare(), bind(), first(), all(), run(), and raw()SupportedSame result shapes and meta fields.
    batch()SupportedOne transaction. If one statement fails, none of them apply.
    exec()SupportedEach line runs as one statement.
    withSession() and bookmarksSupportedThe bookmark advances after each query.
    meta.rows_read and meta.rows_writtenPartialrows_read counts returned rows, not scanned rows. rows_written counts changed rows, without index and trigger writes.
    DELETE ... LIMIT and UPDATE ... LIMITNot supportedFail with near "LIMIT": syntax error.
    SQLite math functions, such as cos(), sqrt(), and floor()Not supportedFail with no such function. abs() and round() work.
    query()Not supportedNeeds the d1_binding_jsrpc compatibility flag, which Orange does not apply.
    dump()Not supportedFails with D1_DUMP_ERROR, as in wrangler dev.
    Read replicationNot supportedEvery query reaches the one database.
    orange d1 execute, orange d1 migrations apply, and orange d1 migrations listSupportedLocal by default, or --remote.
    Other wrangler d1 commands, such as exportNot supportedThey print that the command is not implemented.

    Your D1 code runs unchanged, except for the SQL above. Three differences reach most projects:

    • DELETE ... LIMIT and UPDATE ... LIMIT fail. Select the rows in a subquery instead, which runs on Cloudflare too: DELETE FROM t WHERE rowid IN (SELECT rowid FROM t WHERE ... LIMIT 1).
    • chanfana before 3.1.0 fails every D1DeleteEndpoint with a 500, because it deletes with DELETE ... RETURNING * LIMIT 1. Upgrade chanfana to 3.1.0 or later. orange doctor flags an older chanfana in a project with a D1 database.
    • Everything in the SQLite section of the compatibility page applies to D1. It runs on the same SQLite as Durable Objects.

    Limits

    WhatLimitWhat happens over it
    Queries on one databaseWhat one Rivet Actor servesSplit the data into more databases, for example one per tenant.
    One query or batch()128 MiB of changed SQLite pages, Rivet’s limit for one commitThe call fails.
    A long queryRuns on the one Node.js runtime threadThe other Workers and objects in that process wait until it ends.

    What Orange reads

    On Orange, database_id only names the database, so a Cloudflare database ID works as it is.

    In wrangler.jsoncOn Orange
    database_idNames the database. Under orange dev, a preview_database_id wins, as in wrangler dev. With neither, the binding name names it. orange serve, --remote, and a deployed Worker skip preview_database_id, as wrangler deploy does.
    The same database_id on two bindingsOne database, also for every Worker of one orange dev session. See Multiple Workers.
    migrations_dir, migrations_pattern, migrations_tableRead by orange d1 migrations, as Wrangler reads them. The defaults are migrations and d1_migrations.

    Commands

    These run on the same local database that orange dev uses. Name the database by its binding or its database_name.

    orange d1 migrations list DB
    orange d1 migrations apply DB
    orange d1 execute DB --command "SELECT * FROM comments"
    orange d1 execute DB --file ./seed.sql --json

    With --remote, they run on the database of the deployed Worker, through the Rivet Engine of the linked cluster. Run them in the project, with the Worker name and --env of the deployment. The deployment must be up.

    orange d1 migrations apply DB --remote

    API details

    • The client is a port of workerd’s D1 binding, and the backend follows the local D1 backend of wrangler dev, so result shapes, meta, and error text match.
    • Each request to the database runs as one transaction on its actor.
    • Errors use D1’s prefixes, with SQLite’s message and result code: D1_ERROR: no such table: users: SQLITE_ERROR, and D1_ERROR: UNIQUE constraint failed: notes.body: SQLITE_CONSTRAINT (extended: SQLITE_CONSTRAINT_UNIQUE).
    • bind() takes numbers, strings, null, booleans as 1 and 0, byte arrays, ArrayBuffer, and typed arrays as BLOBs. A DataView binds as an empty BLOB, as in workerd. Any other value fails with D1_TYPE_ERROR: Type '<type>' not supported for value '<value>'.
    • A BLOB column reads back as an array of byte values. An integer outside the safe range is a lossy number, as in workerd.
    • first(column) with an unknown column fails with D1_COLUMN_NOTFOUND: Column not found (<column>).
    • exec() splits its input by line. A failing line fails with D1_EXEC_ERROR: Error in line <n>: <line>: <message>, and an empty input with No SQL statements detected.
    • meta has changed_db, changes, duration, last_row_id, rows_read, rows_written, size_after, served_by, served_by_primary: true, and timings.sql_duration_ms.
    • A session bookmark is a timestamp and a counter, and only has to increase, because every query reaches the one database.
    • query() always fails with D1_ERROR: D1Database.query() requires the d1_binding_jsrpc compatibility flag.

    SQLite

    D1 runs on RivetKit’s SQLite 3.46.0, a different build from workerd’s. It is built from its amalgamation without SQLITE_ENABLE_UPDATE_DELETE_LIMIT, so its parser has no LIMIT on DELETE and UPDATE, with or without RETURNING and ORDER BY. The full error is D1_ERROR: near "LIMIT": syntax error at offset <n>: SQLITE_ERROR.

    • JSON, FTS5, RETURNING, upsert, window functions, CTEs, STRICT tables, and generated columns run. Foreign keys are enforced by default.
    • SQL that reads a _cf_ or _rivet_ table fails with access to <table>.<column> is prohibited. Other SQL that names one fails with not authorized.
    • Orange leaves its _rivet_ tables out of sqlite_master, sqlite_schema, and PRAGMA table_list, so a tool that dumps every listed table works. A query that renames the name and tbl_name columns, or only counts rows, still sees them.
    • PRAGMAs and internal functions that D1 refuses run, against the database itself. ATTACH, DETACH, and PRAGMA writable_schema fail with not authorized, as on Cloudflare.
    • A prepared statement with several statements runs them all and returns the last statement’s rows. wrangler dev rejects it. Bindings on it fail with OpenOrange does not yet support bindings on multi-statement SQL.
    • BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, and RELEASE fail, as on Cloudflare. Use batch().

    Command details

    • Each orange d1 command starts the Orange runtime for a moment and writes the same database that orange dev uses.
    • Migrations come from migrations_dir, filtered by migrations_pattern, and run in the order of their leading number. The migrations_table records each applied migration.
    • Each migration runs as one batch with its record, so a failed migration rolls back, and the later ones do not run.
    • orange d1 migrations apply does not ask for confirmation, and it does not capture a backup.
    • orange d1 execute takes --command or --file, not both. With --json, or when the output is not a terminal, it prints the results as JSON.
    • --remote reaches a Rivet Engine, not a Cloudflare account. It uses RIVET_ENDPOINT when it is set. Otherwise it gets the Engine and its token from Rivet Cloud for the cluster that orange deploy uses: RIVET_CLUSTER, then the link, with orange login or RIVET_CLOUD_TOKEN. --cloud-api <url> sets the Cloud API. Default: https://cloud-api.rivet.dev. With no cluster or no sign-in, the command fails with --remote needs a Rivet cluster. Run `orange login` and `orange link --cluster <name>`, or set RIVET_ENDPOINT, .... The Engine runs the database on the deployed runner.
    • --local is accepted, and is the default. --preview and --persist-to fail. Orange keeps local data under .open-orange.

    Debug a database

    SymptomCauseFix
    D1_ERROR: no such table: <name>The migrations have not run on this databaseRun orange d1 migrations apply DB, or add --remote for the deployed database.
    D1_ERROR: near "LIMIT": syntax errorDELETE ... LIMIT or UPDATE ... LIMITUse the subquery under Compatibility.
    D1_ERROR: no such function: cosSQLite math functions are not in this buildCompute in JavaScript, or store the value in a column.
    D1_ERROR: The D1 database could not answer (status <n>): <group>.<code>: ...The database’s actor could not be reachedCheck the Rivet Engine and the runner.
    This D1 database has an unfinished copy from Cloudflare, so Orange won't serve its partial data.An orange migrate d1 stopped before it endedFinish it with orange migrate d1, or replace the copy with orange migrate d1 --replace. See Migrate from Cloudflare.

    Deviations

    These add to the differences under Compatibility.

    • meta.rows_read and meta.rows_written come from the returned rows and SQLite’s change count, so a query that scans 5 rows and returns 1 reports 1. Do not build cost limits on them.

    Conformance

    • tests/cli/d1.test.ts applies migrations with orange d1, including a failed migration that rolls back, and reads the result through orange dev.
    • tests/bindings/bindings.test.ts drives D1 through a real orange dev: result shapes, meta, BLOB and boolean bindings, batch rollback, error text, sessions, overlapping inserts, and persistence across restarts. The same Worker returns identical results under wrangler dev.
    • tests/cli/orange-serve.test.ts runs orange d1 migrations apply --remote against orange serve through a linked cluster, refuses it with no link, and checks that orange serve skips preview_database_id.
    • tests/rpc-and-websockets/session-shared-storage.test.ts checks that the Workers of one session share a database by ID, and that another ID stays separate.
    • The sqlite-surface probe runs batch() order, cos(), and DELETE ... LIMIT through the D1 binding, next to its Durable Object SQL checks.
    • workerd’s upstream D1 tests are not part of the conformance corpus.
    Recorded results

    Recorded results from the conformance run of 2026-11-10 (Orange ea40348), 1,670 of 1,851 tests passing across every area. Each check is works when every result passed and partial when some did. The full feature matrix is on the compatibility page.

    D1
    Check Status Results
    D1 Works
    • Pass: example: d1-migrations
    • Pass: sqlite-surface: D1: batch() runs statements in order