TechBuzzPro

Testing D1 Batch Rollback on Statement Errors

· 6 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

When you run a batch of SQL statements against Cloudflare D1, you want to know exactly what happens if one statement fails mid-batch. By default, D1 batches are atomic: if any statement throws an error, the entire batch is rolled back, leaving your database unchanged. This guide walks you through testing that rollback behavior step by step, so you can verify your application handles failures gracefully and your data stays consistent.

What You'll Need

  • A Cloudflare account with D1 enabled.
  • A D1 database created (e.g., my-db).
  • Wrangler CLI installed and authenticated (npx wrangler login).
  • Node.js (v18 or later) for running scripts.
  • A basic understanding of SQL and JavaScript promises.

Step-by-Step

  1. Create a test table
    In your D1 database, create a simple table to work with. Run this SQL via Wrangler or the Cloudflare dashboard:
    CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
    This gives you a clean slate to observe rollback behavior.
  2. Insert a known row
    Insert a row that you can later check for existence. For example:
    INSERT INTO users (id, name) VALUES (1, 'Alice');
    This row will serve as your baseline.
  3. Write a test script
    Create a JavaScript file (e.g., test-rollback.mjs) that uses the D1 client API. If you're using Wrangler's --local mode, you can test against a local D1 instance; for production, use wrangler d1 execute with a script or use the Cloudflare Workers runtime. Here's a minimal script using the Workers binding:
    // test-rollback.mjs
    import { D1Database } from '@cloudflare/workers-types'; // not needed if using wrangler
    
    export default {
      async fetch(request, env) {
        const db = env.DB; // your D1 binding
        try {
          await db.batch([
            db.prepare("INSERT INTO users (id, name) VALUES (2, 'Bob')"),
            db.prepare("INSERT INTO users (id, name) VALUES (1, 'Duplicate')"), // this will fail (PK conflict)
            db.prepare("INSERT INTO users (id, name) VALUES (3, 'Carol')")
          ]);
          return new Response('Batch succeeded');
        } catch (e) {
          return new Response('Batch failed: ' + e.message);
        }
      }
    };
    The second statement intentionally violates the primary key constraint to trigger an error.
  4. Run the script
    If using Wrangler dev, run npx wrangler dev and send a request to your worker. Alternatively, use npx wrangler d1 execute my-db --file=script.sql for a simpler SQL-only test, but the batch API requires a Worker. For a quick test without a full Worker, you can use the D1 REST API with a script that simulates the batch, but the official behavior is best observed via the Worker binding.
  5. Check the database state
    After the batch fails, query the table to see what rows exist:
    SELECT * FROM users;
    You should see only the original row (id=1, 'Alice'). If the rollback worked, the inserts for Bob and Carol are not present, and the duplicate insert attempt did not corrupt the existing row.
  6. Verify atomicity with a successful batch
    For comparison, run a batch where all statements succeed, e.g., insert ids 4 and 5. Confirm both appear. This proves that the rollback only happens on error, not on success.
  7. Test with a conditional rollback
    To simulate a more realistic scenario, use a statement that fails based on a condition, such as a CHECK constraint or a foreign key. Create a table with a CHECK constraint, then attempt to insert a value that violates it. The entire batch should roll back.

Common Mistakes

  • Not using the batch API: If you execute statements sequentially with await db.prepare().run() individually, there is no rollback—each statement is committed separately. Use db.batch() to get atomicity.
  • Ignoring the error object: The batch error may contain a cause or error property with details. Always log the full error to understand which statement failed.
  • Assuming partial commits: Some databases allow partial commits; D1 does not. If you see partial rows, you're likely not using batch() correctly.
  • Testing with auto-commit: In the dashboard or with wrangler d1 execute, each statement is auto-committed. To test rollback, you must use the Worker binding or the REST API batch endpoint.

Tips

  • Use a unique constraint for reliable failure: A primary key conflict is the simplest way to force an error. Make sure the conflicting value exists before running the batch.
  • Wrap the batch in a try/catch: Always catch errors to handle the rollback gracefully in your application logic—for example, by returning a 500 or a custom error message.
  • Test in a local environment first: Use wrangler dev --local to test against a local D1 instance. This is faster and avoids consuming production resources.
  • Log the batch results: The batch() method returns an array of results. Even if it throws, you can inspect the results array to see which statements succeeded before the error (though they are rolled back).
  • Consider transactions for complex logic: If you need conditional logic within a batch, use db.exec() with a transaction or use the D1 transactions API (if available). For simple atomic batches, batch() is sufficient.

Troubleshooting

Batch didn't roll back: If you see partial data after an error, ensure you are using db.batch() and not sequential run() calls. Also check that the error is actually thrown—some statements like INSERT OR IGNORE suppress errors.

Error not caught: If the batch fails but your catch block doesn't execute, verify that your Worker is properly configured with the D1 binding and that you're awaiting the batch() promise. Unhandled promise rejections can crash the worker silently.

Local vs. production differences: Local D1 may behave slightly differently from the production service. Always test against a remote database if you suspect a discrepancy, but note that production tests will affect real data—use a test table.

Permission errors: If you get a 500 or permission error, check that your Worker has the correct D1 binding and that your account has access to the database. Use wrangler d1 list to verify.

SQL syntax errors: A syntax error in any statement will cause the batch to fail. Double-check your SQL for typos, especially quotes and commas.

Frequently Asked Questions

Q: Does D1 batch rollback apply to all statements or just the failed one?
A: It applies to the entire batch. If any statement fails, all changes made by the batch are rolled back, leaving the database as it was before the batch started.

Q: Can I partially commit a batch by handling errors inside the batch?
A: No. The batch() API is atomic by design. If you need conditional logic, you must split the batch or use a transaction with explicit control.

Q: What happens to auto-increment counters after a rollback?
A: In D1, auto-increment counters are not rolled back. If you insert a row with an auto-increment ID and the batch fails, the next insert will use the next ID, leaving gaps. This is normal for SQLite-based systems.

Q: How do I test rollback without creating a Worker?
A: You can use the D1 REST API with a script that sends a batch request. The API endpoint /batch accepts an array of SQL statements and returns an error if any fail. This is a good way to test without deploying a Worker.

Q: Are there limits on batch size?
A: Yes, D1 batches have a maximum number of statements and a total size limit. Check the current Cloudflare documentation for exact numbers, but typically it's around 100 statements or 1MB of data. Exceeding these limits will cause the batch to fail, and rollback applies.

Q: Can I use transactions instead of batch for rollback?
A: D1 supports transactions via db.exec() with BEGIN/COMMIT. Transactions offer more control (e.g., you can rollback manually), but for simple atomic operations, batch() is simpler and recommended.