Creates a function that always runs inside a transaction. When the function is invoked, it will begin a new transaction. When the function returns, the transaction will be committed. If an exception is thrown, the transaction will be rolled back (and the exception will propagate as usual).
Symbol
Database.transaction
transaction(insideTransaction: (...args: any) => void): CallableFunction & { deferred: (...args: any) => void; exclusive: (...args: any) => void; immediate: (...args: any) => void }
@param insideTransaction
The callback which runs inside a transaction
// setup
import { Database } from "bun:sqlite";
const db = Database.open(":memory:");
db.exec(
"CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)"
);
const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)");
const insertMany = db.transaction((cats) => {
for (const cat of cats) insert.run(cat);
});
insertMany([
{ $name: "Joey", $age: 2 },
{ $name: "Sally", $age: 4 },
{ $name: "Junior", $age: 1 },
]);