method
sqlite.Database.transaction
Creates a function that always runs inside a transaction. When the function is invoked, it begins a new transaction. When the function returns, the transaction is committed. If an exception is thrown, the transaction is rolled back (and the exception propagates as usual).
The function must be synchronous, because the transaction is committed when it returns. An async function returns at its first await: everything after that await runs outside the transaction, and an error thrown there does not roll anything back. Do the awaited work first and pass the results in.
If the function returns a promise that is already rejected, as an async function does when it throws before its first await, the transaction is rolled back and the promise is returned.
The synchronous callback which runs inside a transaction
// setup
import { Database } from "bun:sqlite";
const db = Database.open(":memory:");
db.run(
"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 },
]);