Transaction
- Go course
- Advanced
- Lesson 29/68
- 4 min
Learn transactions with Begin, Commit and Rollback.
Transactions
Use a transaction when several operations must either all happen or none. db.Begin() gives a *sql.Tx; operations go through tx and end with Commit or Rollback.
tx, err := db.Begin()
if err != nil { return err }
defer tx.Rollback() // no effect after Commit
if _, err := tx.Exec("UPDATE hesap SET bakiye = bakiye - 100 WHERE id = 1"); err != nil { return err }
if _, err := tx.Exec("UPDATE hesap SET bakiye = bakiye + 100 WHERE id = 2"); err != nil { return err }
return tx.Commit()The defer tx.Rollback pattern
defer tx.Rollback() rolls the transaction back on early returns and errors. After a successful Commit, Rollback returns sql.ErrTxDone and does nothing, so the pattern is safe. To work with a context, use db.BeginTx(ctx, nil); if the context is cancelled the transaction is rolled back automatically.
Practice Transaction flow
Model the flow without a real database: write transfer(fail bool) string. Return "rollback" if fail is true, otherwise "commit". Print transfer(false) and transfer(true) on one line.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func transfer(fail bool) string {
if fail {
return "rollback"
}
return "commit"
}
func main() {
fmt.Println(transfer(false), transfer(true))
}Expected output
commit rollback
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Inside a transaction, why run the query with <code>tx.Exec</code> instead of <code>db.Exec</code>?
- There is no difference
- db.Exec takes another pool connection and stays outside the transaction Correct answer
- tx.Exec is faster
- db.Exec closes the transaction
Explanation: A transaction is bound to one connection; operations through db don't use it and aren't rolled back.
2 Commit
if err := step(tx); err != nil {
return err
}
return tx.____()
if err := step(tx); err != nil {
return err
}
return tx.Commit()
Explanation: Commit makes the changes permanent; if an error comes first, the deferred Rollback takes over.
3 Transaction steps
| Term | Meaning |
|---|---|
db.Begin |
Starts it |
tx.Exec |
Runs inside it |
tx.Commit |
Makes it permanent |
tx.Rollback |
Undoes it |