[BUG]: Cloudflare D1 transaction not supported
What version of drizzle-orm are you using?
0.31.1
What version of drizzle-kit are you using?
0.22.2
Describe the Bug
When trying to execute a transacction with cloudflare d1 adapter it throws the following error:
To execute a transaction, please use the state.storage.transaction() API instead of the SQL BEGIN TRANSACTION or SAVEPOINT statements. The JavaScript API is safer because it will automatically roll back on exceptions, and because it interacts correctly with Durable Objects' automatic atomic write coalescing.
To reproduce create a project using c3
import { drizzle } from 'drizzle-orm/d1';
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const db = drizzle(env.DB);
await db.transaction(async (tx) => {
// Throws error
});
return new Response('OK');
}
};
Expected behavior
No response
Environment & setup
No response
Use the Batch API to achieve 'transactions' in Cloudflare D1
const batchResponse: BatchResponse = await db.batch([
db.insert(usersTable).values({ id: 1, name: 'John' }).returning({ id: usersTable.id }),
db.update(usersTable).set({ name: 'Dan' }).where(eq(usersTable.id, 1)),
db.query.usersTable.findMany({}),
db.select().from(usersTable).where(eq(usersTable.id, 1)),
db.select({ id: usersTable.id, invitedBy: usersTable.invitedBy }).from(usersTable),
]);
facing same error how could i fix these?
@emmanuelchucks unfortunately, this workaround will not work in some scenarios like the following:
const [createdUser] = await global.db
.insert(users)
.values({
name: account.name
})
.returning({
id: users.id
});
// It may fail if the account already exists,
// in this case I want to rollback the transaction, removing the previously inserted user
const [createdAccount] = await global.db
.insert(accounts)
.values({
userId: createdUser.id, // I need to know the id returned from the previous query
provider: account.provider,
providerAccountId: account.providerAccountId,
})
.returning();
@emmanuelchucks unfortunately, this workaround will not work in some scenarios like the following:
const [createdUser] = await global.db .insert(users) .values({ name: account.name }) .returning({ id: users.id }); // It may fail if the account already exists, // in this case I want to rollback the transaction, removing the previously inserted user const [createdAccount] = await global.db .insert(accounts) .values({ userId: createdUser.id, // I need to know the id returned from the previous query provider: account.provider, providerAccountId: account.providerAccountId, }) .returning();
@duducpp It's the drawback of Cloudflare D1 rather than drizzle. Even if you switch to prisma, this transaction feature is still unsupported. They (cloudflare team) have a workaround may help you: https://blog.cloudflare.com/whats-new-with-d1
@emmanuelchucks
This is a curious situation where batch is not a true workaround, as one action against the database in a batch "tx" may have return data needed for the following action in the batch call.
@emmanuelchucks unfortunately, this workaround will not work in some scenarios like the following:
const [createdUser] = await global.db .insert(users) .values({ name: account.name }) .returning({ id: users.id }); // It may fail if the account already exists, // in this case I want to rollback the transaction, removing the previously inserted user const [createdAccount] = await global.db .insert(accounts) .values({ userId: createdUser.id, // I need to know the id returned from the previous query provider: account.provider, providerAccountId: account.providerAccountId, }) .returning();@duducpp It's the drawback of Cloudflare D1 rather than drizzle. Even if you switch to prisma, this transaction feature is still unsupported. They (cloudflare team) have a workaround may help you: https://blog.cloudflare.com/whats-new-with-d1
This is the only workaround, thanks for the tip.
@duducpp I did see this last night as well: https://blog.cloudflare.com/whats-new-with-d1
Are you aware if we can instead of workers-qb, use drizzle in this pattern? I reached out to the authors as well.
Cloudflare never shipped the stored procedure feature mentioned in that blog post. It was just something they were looking into at the time. See here: https://community.cloudflare.com/t/d1-stored-procedures-can-not-use/649207
To execute a transaction, please use the state.storage.transaction() API instead of the SQL BEGIN TRANSACTION or SAVEPOINT statements. The JavaScript API is safer because it will automatically roll back on exceptions, and because it interacts correctly with Durable Objects' automatic atomic write coalescing.
I am having this error
I found a feature request to add transaction support to D1 in Cloudflare's workers SDK repo. That seems likely to have the latest status on this. Unfortunately, no updates on the issue for nearly a year.
https://github.com/cloudflare/workers-sdk/issues/2733
I found a feature request to add transaction support to D1 in Cloudflare's workers SDK repo. That seems likely to have the latest status on this. Unfortunately, no updates on the issue for nearly a year.
https://github.com/cloudflare/workers-sdk/issues/2733
Unfortunately D1 product manager said there's no ETA to add support to javascript transaction API (https://github.com/cloudflare/workers-sdk/issues/2733#issuecomment-2712365336) as the technology behind D1 has changed since the "procedures proposal implementation". Instead they recommend bound D1 to a DO for lock/unlock management.
The batch workaround is handy with its limitations.
Batch purpose is to write multiple operations at once (atomic, all or nothing) while transactions lock the DB to allow safe reads and writes (enforcing data integrity, ACID, no race conditions)
And because SQLite supports only one open transaction at a time, using them through workers would easily leave D1 pretty much useless -> imagine each user able to lock the entire database...
That's why another or real workaround is doing transactions through Durable Objects, because each of them has their own SQLite instance, so no global lock.
To execute a transaction, please use the state.storage.transaction() API instead of the SQL BEGIN TRANSACTION or SAVEPOINT statements. The JavaScript API is safer because it will automatically roll back on exceptions, and because it interacts correctly with Durable Objects' automatic atomic write coalescing.
I am having this error
I believe it comes from the durable object and not d1 as d1 databases lack transactions. transaction
To execute a transaction, please use the state.storage.transaction() API instead of the SQL BEGIN TRANSACTION or SAVEPOINT statements. The JavaScript API is safer because it will automatically roll back on exceptions, and because it interacts correctly with Durable Objects' automatic atomic write coalescing. I am having this error
I believe it comes from the durable object and not d1 as d1 databases lack transactions. transaction
It comes from an experimental architecture that does not exists anymore, the JS API was replaced by Durable Objects.
Here D1 project manager said
The past blog described a proposal when D1 had a different underlying architecture, which was replaced for performance and reliability issues
Hey everyone!
I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.
I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!
We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.
First branch is drizzle-kit rewrite
All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439
As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.
What's left here:
- We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the
sridissue here as well). - We are finishing commutative migrations for all dialects.
- We are finishing up the command, so the migration flow will be as simple as
drizzle-kit upfor you.
Where it brings us:
- We are getting drizzle-kit into a new good shape where we can call it
[email protected]!
Timeline:
- We need ~2 weeks to finish all of the above and send this branch to beta for testing.
Second big branch is a complex one with several HUGE updates
- Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)
TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k
You can read more about it here.
What's left here:
- We have 1 issue with TS that is already in progress of being fixed. The issue and Post about fixing.
Where it brings us:
- We are getting drizzle-orm into a new good shape where we can call it
[email protected]!
Breaking changes:
- We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.
Third branch is adding support for CockroachDB and MSSQL dialects
Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.
Summary
All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.
We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).
We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.
Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!
Timelines
We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!
Sooo.... no transactions then?
An ugly workaround here.
import { DrizzleD1Database } from 'drizzle-orm/d1';
type RevertFn = () => Promise<any>;
export const transaction = async (
db: DrizzleD1Database,
runner: (tx: DrizzleD1Database, revertWhenError: (fn: RevertFn) => any) => Promise<any>
) => {
const revertQueue: RevertFn[] = [];
try {
const revertWhenError = (fn: RevertFn) => {
revertQueue.push(fn);
};
return await runner(db, revertWhenError);
} catch (error) {
// delete records (reverse order) added previously in the transaction
for (const revert of revertQueue.reverse()) {
await revert();
}
return Promise.reject(error); // re-throw the error to the caller
}
};
hey any updates on this? been marked as priority for a while now but still no fix 👀
hey any updates on this? been marked as priority for a while now but still no fix 👀
D1 project manager comment: https://github.com/cloudflare/workers-sdk/issues/2733#issuecomment-2712365336