Transactions

Ensure data integrity with atomic database transactions.
Stabilize provides a unified API for transactions across PostgreSQL, MySQL, and SQLite.

Basic Transaction

transaction.tstypescript
import { orm } from "./db";
await orm.transaction(async (txClient) => {
const userRepo = orm.getRepository(User);
const profileRepo = orm.getRepository(Profile);
// All operations use the same transaction client
const user = await userRepo.create(
{ name: "Lwazii Dlamini", email: "lwazicd@icloud.com" },
{},
txClient
);
await profileRepo.create(
{ userId: user.id, bio: "Hello Stabilize!" },
{},
txClient
);
// If any operation fails, everything is rolled back
});

Error Handling

transaction-error.tstypescript
try {
await orm.transaction(async (txClient) => {
await userRepo.create(userData, {}, txClient);
await profileRepo.create(profileData, {}, txClient);
});
console.log("Transaction committed successfully");
} catch (error) {
console.error("Transaction rolled back:", error);
}

Nested Transactions

Stabilize automatically handles nested transaction calls by reusing the same transaction client:

nested-transaction.tstypescript
await orm.transaction(async (txClient) => {
// This is the outer transaction
await orm.transaction(async (nestedTxClient) => {
// This will use the same transaction client
await doSomething(nestedTxClient);
}, txClient);
});

Supported Databases

client.tstypescript
await dbClient.transaction(async (txClient) => {
// Works with PostgreSQL, MySQL, and SQLite!
await repo.create(data, {}, txClient);
});

API Reference

client.tstypescript
// DBClient
async transaction<T>(callback: (txClient: DBClient) => Promise<T>): Promise<T>
// Usage example:
await db.transaction(async (tx) => {
// use tx for all DB operations within this transaction
});