Senior
What types of transactions do you know? What are they used for?
sobes.tech AI
Answer from AI
In Go, transactions are usually associated with databases and are used to ensure atomicity, consistency, isolation, and durability (ACID).
Types of transactions:
- Automatic transactions — when each operation is executed as a separate transaction.
- Explicit transactions — when the developer explicitly begins, commits, or rolls back a transaction using methods like
Begin(),Commit(),Rollback(). - Long-lived transactions — used in distributed systems where a transaction can last a long time and requires coordination.
Why transactions are needed:
- Guarantee that a group of operations either completes entirely or not at all.
- Prevent race conditions and ensure data integrity.
- Allow rolling back changes in case of errors.
Example of using a transaction in Go with a database:
trx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
_, err = trx.Exec("INSERT INTO users(name) VALUES(?)", "Alice")
if err != nil {
trx.Rollback()
log.Fatal(err)
}
err = trx.Commit()
if err != nil {
log.Fatal(err)
}