Enforces wrapping multiple related write operations (INSERT/UPDATE/DELETE) in a database transaction to ensure atomicity. Use when writing code that performs two or more writes that must succeed or fail together. Do not use for single-statement writes or read-only queries where transactions add unnecessary overhead.
When an operation requires multiple writes (INSERT, UPDATE, DELETE) to the database, wrap them in a Transaction. If any part fails, the entire transaction should be Rolled Back.
ROLLBACK immediately.COMMIT.Rollback is deferred in case of panics or early returns.db.DecreaseBalance(userA, 100)
// If this fails or crashes, money is lost but not transferred
db.IncreaseBalance(userB, 100)
tx := db.Begin()
if err := tx.DecreaseBalance(userA, 100); err != nil {
tx.Rollback()
return err
}
if err := tx.IncreaseBalance(userB, 100); err != nil {
tx.Rollback()
return err
}
tx.Commit()