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:

users.service.ts
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.

operationRequired

async (tx) => result

The work to run. Commit on resolve, roll back on throw.
existingTransactionOptional

Drizzle transaction

Run the callback inside this transaction instead of opening a new one. No savepoint is created.

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:

signup.service.ts
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:

transactionOptional

any (a Drizzle transaction)

Run this call inside the given transaction. Typed as any so the package does not depend on one driver's transaction type.

Some methods open their own transaction when you do not pass one, and join yours when you do:

MethodWithout transactionWith transaction
massCreate, massUpdate, massUpsert, the other mass writesOpens its own transaction, with no savepoint on the happy pathJoins yours, with savepoints inside it
attach, detach, syncOpens its own transactionJoins yours
create with nested relationsOpens its own transactionJoins yours
find, findAll, create, update, delete and the other single-row callsRuns on the pool, no transactionJoins 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:

users.service.ts
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 callResult
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 txOpens 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:

FailureBehaviour
The callback throwsRolled back. The error propagates.
A massCreate inside throws BulkOperationExceptionRolled back. The exception propagates as a 400.
An after-event subscriber throwsRolled back, because events fire inside the transaction.
The connection drops mid-transactionThe 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 massUpdate and 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

Next steps

Last updated View change history

On this page