The transaction(fn) method wraps a callback function in a transaction.
- If the function returns successfully, the transaction is committed.
- If the function throws an error, the transaction is rolled back.
If a transaction is already active (e.g., nested calls), the library automatically uses SAVEPOINT and RELEASE instead of BEGIN/COMMIT to support nested transactions.
You can specify the transaction type using the following properties on the returned function:
default: Uses BEGIN.deferred: Uses BEGIN DEFERRED.immediate: Uses BEGIN IMMEDIATE.exclusive: Uses BEGIN EXCLUSIVE.
const stmt = db.prepare("insert into users (id, username) values(?, ?)");
interface User {
id: number;
username: string;
}
const insertUsers = db.transaction((data: User[]) => {
for (const user of data) {
stmt.run(user.id, user.username);
}
});
insertUsers([
{ id: 1, username: "alice" },
{ id: 2, username: "bob" },
]);
// Or use specific modes:
insertUsers.deferred([
{ id: 3, username: "charlie" },
]);