Drizzle transactions in NestJS
Run Drizzle transactions in NestJS across several service calls. Open one with executeSqlTransaction or db.transaction and pass the handle to each call.
To run Drizzle transactions in NestJS, open a transaction and pass its handle to every call as { transaction: tx }. Inside a service, this.executeSqlTransaction(async (tx) => ...) opens it; anywhere else, inject DRIZZLE_DB and call Drizzle's db.transaction. The transaction commits when the callback resolves and rolls back when it throws, so every call that received tx succeeds or fails together.
A call without the handle is outside the transaction
Only calls that receive { transaction: tx } join the transaction. A call that leaves it out runs outside the transaction, commits on its own, and is not rolled back when the callback throws.
How do I run several writes in one transaction?
Call executeSqlTransaction from a method on your service and pass tx to each call:
import { SqlBaseCrudService } from '@avytrix/nestjs-drizzle-crud';
import type { ProfilesService } from '../profiles/profiles.service';
export class UsersService extends SqlBaseCrudService<User, CreateUserDto> {
signUp(dto: CreateUserDto, profiles: ProfilesService) {
return this.executeSqlTransaction(async (tx) => {
const user = await this.create(dto, { transaction: tx });
await profiles.create({ userId: user.id, bio: '' }, { transaction: tx });
return user;
});
}
}executeSqlTransaction is protected, so you call it from inside the service, not from a controller. It returns whatever the callback returns.
operationRequiredasync (tx) => result
existingTransactionOptionalDrizzle transaction
How do I start a transaction outside a service?
Inject DRIZZLE_DB, the Drizzle instance the module built, and call db.transaction yourself. This suits an orchestrating provider that coordinates several CRUD services:
import { Inject, Injectable } from '@nestjs/common';
import { DRIZZLE_DB } from '@avytrix/nestjs-drizzle-crud';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { UsersService } from '../users/users.service';
import { ProfilesService } from '../profiles/profiles.service';
@Injectable()
export class SignupService {
constructor(
@Inject(DRIZZLE_DB) private readonly db: NodePgDatabase,
private readonly users: UsersService,
private readonly profiles: ProfilesService,
) {}
signUp(dto: CreateUserDto) {
return this.db.transaction(async (tx) => {
const user = await this.users.create(dto, { transaction: tx });
await this.profiles.create({ userId: user.id, bio: '' }, { transaction: tx });
return user;
});
}
}DrizzleCrudModule.forRoot registers DRIZZLE_DB globally, so any provider can inject it. Your CRUD services themselves must not inject it: forFeature builds them and hands them the database already (see Defining services).
Which methods accept a transaction?
Every read and write method takes SqlOperationOptions as its last argument, and transaction is one of its fields:
transactionOptionalany (a Drizzle transaction)
Some methods open their own transaction when you do not pass one, and join yours when you do:
| Method | Without transaction | With transaction |
|---|---|---|
massCreate, massUpdate, massUpsert, the other mass writes | Opens its own transaction, with no savepoint on the happy path | Joins yours, with savepoints inside it |
attach, detach, sync | Opens its own transaction | Joins yours |
create with nested relations | Opens its own transaction | Joins yours |
find, findAll, create, update, delete and the other single-row calls | Runs on the pool, no transaction | Joins yours |
So a single update is not wrapped in a transaction of its own. Since 3.8.0 it is usually one statement: on PostgreSQL and SQLite, update, softDelete, restore, delete and forceDelete send the write with the whole check in its WHERE (primary key, tenant scope, expected version, and the soft delete state the call needs) and use RETURNING to tell a miss, which then gets the same 404 or 409 as before. The existence check still runs first, as a second statement, when something you can observe runs between the check and the write: a before* hook, validateUpdate or mapUpdateDtoToEntity your service overrides, or a before event on the event bus. It always runs first on MySQL, which has no RETURNING. Either way the write re-checks everything, so a row deleted or changed in between is not written. Pass a transaction when the hooks and the write must see the same snapshot.
Can I mix package methods with raw Drizzle?
Yes. tx is the standard Drizzle transaction handle, so anything you can do with db you can do with tx, inside the same transaction:
import { posts } from '../db/schema';
createWithWelcomePost(dto: CreateUserDto) {
return this.executeSqlTransaction(async (tx) => {
const user = await this.create(dto, { transaction: tx });
// Raw Drizzle in the same transaction:
await tx.insert(posts).values({ authorId: user.id, title: 'Hello' });
return user;
});
}What happens when I nest transactions?
It depends on what you pass:
| Inside a transaction callback you call | Result |
|---|---|
A package method with { transaction: tx } | Runs in the same transaction. |
this.executeSqlTransaction(cb, tx) | Runs cb in the same transaction. No savepoint. |
this.executeSqlTransaction(cb) without tx | Opens a second, independent transaction. It commits or rolls back on its own. |
tx.transaction(cb) (Drizzle) | Opens a savepoint. A throw inside rolls back only the savepoint, if you catch it. |
For most requests, one top-level transaction with tx passed everywhere is the right shape.
Which SQLite drivers can run a transaction?
executeSqlTransaction needs an interactive transaction that can wait for async work. On SQLite, libSQL (@libsql/client) has one. Cloudflare D1 has no interactive transactions, and synchronous drivers (better-sqlite3, bun:sqlite, sql.js) cannot wait inside theirs, so on those executeSqlTransaction throws a TransactionException before it opens anything. That also covers every bulk write, nested create and attach / detach / sync. See SQLite, libSQL and Cloudflare D1.
What happens when something fails?
The transaction rolls back and the error reaches your caller:
| Failure | Behaviour |
|---|---|
| The callback throws | Rolled back. The error propagates. |
A massCreate inside throws BulkOperationException | Rolled back. The exception propagates as a 400. |
| An after-event subscriber throws | Rolled back, because events fire inside the transaction. |
| The connection drops mid-transaction | The database rolls back. The driver error propagates. |
When should I use a transaction?
Use one when several writes must succeed or fail together:
- Cross-service atomicity. Creating a user and its profile as one unit.
- Read, decide, write. Read a row, decide based on its value, write back. Add a row lock so no one changes the row in between.
- Bulk writes plus related changes. A
massUpdateand the audit rows that go with it.
Skip it for read-only queries, which need no transaction, and for writes that can succeed or fail independently. Keep network calls, queue publishes and other slow awaits out of the callback: a transaction holds its locks until it ends.
Common questions
No. It is a protected method, so call it from a method on your service. Outside a service, inject DRIZZLE_DB and call db.transaction.
No. Every mass write opens its own transaction. Pass { transaction: tx } only when the bulk call must commit together with other writes.
No. Without the second argument it opens a separate transaction, and with it the callback runs in the same transaction. Use Drizzle's tx.transaction for a savepoint.
Yes, when you pass one. Hooks and module-level events run during the call while the transaction is open, and the event payload carries it, so a subscriber can write in the same transaction.
Next steps
Row locks with SELECT FOR UPDATE
Lock rows inside a transaction so no one changes them between your read and your write.
Bulk insert and update with Drizzle
Mass writes that run in their own transaction and name every failed item.
NestJS Drizzle CRUD events and audit logs
Subscribers that run inside the write's transaction.
Drizzle optimistic locking with versions
Drizzle optimistic locking with a version column in NestJS. Set versionColumn, send the version you read, and a stale write is a 409 conflict.
Row locks with SELECT FOR UPDATE
Drizzle SELECT FOR UPDATE in NestJS. Pass lock or forNoKeyUpdate to find, findOne or findAll inside a transaction to lock rows on PostgreSQL or MySQL.