Transactions
Transactions
Section titled “Transactions”New in v3.7.0.
A transaction makes several writes succeed or fail together. The awkward part is usually plumbing: opening one gives you a different object (tx), so every query has to be rewritten to use it and every helper has to accept it as a parameter — and a query that keeps using this.db silently runs outside the transaction.
Veloce-TS removes the plumbing. The database you inject follows the transaction of the current call chain.
How it works
Section titled “How it works”registerDrizzle(app, db) registers a transaction-aware handle to your database. It behaves exactly like db, with one difference:
- outside a transaction, queries go to the database;
- inside
runInTransaction()or a@Transactional()method, queries made through the handle go to that transaction — in the method itself and in anything it awaits.
The active transaction is tracked with AsyncLocalStorage, so it belongs to one asynchronous call chain. Concurrent requests never see each other’s transaction, and a class that stored this.db in its constructor — a singleton controller, a service — needs no change.
import { registerDrizzle, InjectDB } from 'veloce-ts';
registerDrizzle(app, db);
class Inventory { constructor(@InjectDB() private db: DB) {}
async reserve(items: Item[]) { for (const item of items) { await this.db .update(stock) .set({ reserved: sql`${stock.reserved} + ${item.qty}` }) .where(eq(stock.sku, item.sku)); } }}Inventory.reserve knows nothing about transactions. Whether its updates are transactional depends on who calls it.
@Transactional()
Section titled “@Transactional()”import { Transactional, BadRequestException } from 'veloce-ts';
class Orders { constructor( @InjectDB() private db: DB, @Inject(Inventory) private inventory: Inventory, ) {}
@Transactional() async place(order: NewOrder) { await this.db.insert(orders).values(order); await this.inventory.reserve(order.items); // same transaction
if (order.total > order.creditLimit) { throw new BadRequestException('Credit limit exceeded'); // rolls back both } }}The method commits when it resolves and rolls back when it throws; the error is rethrown. It works on service methods and directly on route handlers.
The decorator finds the handle on the instance. If a class holds more than one database, name the property:
@Transactional({ db: 'analytics' })runInTransaction()
Section titled “runInTransaction()”The same thing for a block instead of a whole method:
import { runInTransaction } from 'veloce-ts';
async cancel(id: string) { await runInTransaction(this.db, async () => { await this.db.update(orders).set({ status: 'cancelled' }).where(eq(orders.id, id)); await this.inventory.release(id); });}The callback also receives the transaction object, for code that prefers it explicit: runInTransaction(this.db, async (tx) => { … }).
this.db.transaction(cb) — Drizzle’s own API — is ambient too when called on the injected handle: queries made on this.db inside cb are part of it.
Nesting
Section titled “Nesting”| Call | When a transaction is already active |
|---|---|
@Transactional() / runInTransaction(db, fn) | Joins it. One transaction, one commit |
@Transactional({ nested: true }) / runInTransaction(db, fn, { nested: true }) | Opens a savepoint. A failure inside can be caught without aborting the outer transaction |
this.db.transaction(cb) | Savepoint |
await runInTransaction(this.db, async () => { await this.db.insert(orders).values(order);
// Best effort: a failure here must not lose the order await runInTransaction(this.db, () => this.loyalty.award(order), { nested: true }) .catch((error) => logger.warn({ error }, 'Loyalty points not awarded'));});One transaction per request
Section titled “One transaction per request”registerDrizzle(app, db, { transactionPerRequest: (c) => c.req.method !== 'GET',});transactionPerRequest takes true or a predicate. The request is then wrapped in one transaction:
| Outcome of the request | Transaction |
|---|---|
| The handler returns | Committed |
| The handler throws — any HTTP exception or unexpected error | Rolled back; the client still gets the normal error response |
The response is a 5xx | Rolled back |
The handler returns a 4xx response without throwing | Committed — you chose to return it |
It is off by default, for a reason: the transaction holds a connection from the pool for the whole request, including time the handler spends waiting on other services. Under load that exhausts the pool long before the database is busy. Prefer @Transactional() on the operations that need it, and reserve request-wide transactions for applications where every write request is short.
text/event-stream requests are never wrapped: a streaming response outlives the handler.
onBegin
Section titled “onBegin”registerDrizzle(app, db, { onBegin: async (tx, c) => { const tenant = c?.get('tenant'); if (tenant) { await tx.execute(sql`select set_config('app.tenant_id', ${tenant.id}, true)`); } },});onBegin(tx, c) runs at the start of every outermost transaction on that database — per-request, @Transactional() or runInTransaction() — inside the transaction and before any of your queries. c is the current request when there is one, undefined for transactions started outside a request (a job, a script). Savepoints do not trigger it; they inherit what the outer transaction set up.
It is the place for per-transaction session state. The example writes the tenant that PostgreSQL row-level security policies read — see Multi-tenancy.
Things to know
Section titled “Things to know”Only awaited work is covered. A promise you start and do not await may run after the commit. It then uses the plain database — never the finished transaction:
@Transactional()async place(order: NewOrder) { await this.db.insert(orders).values(order); void this.mailer.sendConfirmation(order); // not awaited: outside the transaction}That is usually what you want for an email. It is not what you want for a write that must be atomic with the rest: await it.
The driver must run the transaction callback asynchronously. This is verified against Drizzle’s PostgreSQL dialect; other async drivers follow the same contract but are not covered by the framework’s tests. Synchronous SQLite drivers are not supported — bun:sqlite and better-sqlite3 commit before an await inside the callback resolves, so the statements after it run outside the transaction.
injected === db is false. The handle is a proxy. It behaves like your database; it is not the same object. registerDrizzle() returns the handle if you need a reference to it.
Other ORMs. Ambient transactions are implemented for databases registered with registerDrizzle(). With Prisma or TypeORM, use their own transaction APIs. @Transactional() on a class that holds no such handle falls back to the global transaction manager used by the repository layer, as before.
registerDrizzle(app, db, options?) | Registers the handle and returns it. options: token, transactionPerRequest, onBegin |
@Transactional(options?) | options: nested, db |
runInTransaction(db, fn, options?) | options: nested, config (passed to the driver: isolation level, access mode) |
isInTransaction(db) | Whether a transaction is active for db in this call chain |
getActiveTransaction(db) | The active transaction object, or undefined |
createTransactionalDb(db, { onBegin? }) | Build a handle without the DI container — in a script or a test |