Sobes.tech
Senior

Milliseid tehingu tüüpe tead? Milleks nad on vajalikud?

sobes.tech AI

Vastus AI-lt

In Go, transactions are usually associated with databases and are used to ensure the ACID properties (atomicity, consistency, isolation, durability).

Types of transactions:

  • Automatic transactions — each operation is performed as a separate transaction.
  • Explicit transactions — the developer explicitly starts, commits, or rolls back a transaction using the Begin(), Commit(), Rollback() methods.
  • Long-lived transactions — used in distributed systems, where a transaction can last a long time and requires coordination.

Why transactions are needed:

  • They ensure that a group of operations is either fully completed or not at all.
  • Prevent race conditions and ensure data integrity.
  • Allow rollback of changes in case of errors.

Example of using a transaction in Go with a database:

tx, err := db.Begin()
if err != nil {
    log.Fatal(err)
}
_, err = tx.Exec("INSERT INTO users(name) VALUES(?)", "Alice")
if err != nil {
    tx.Rollback()
    log.Fatal(err)
}
err = tx.Commit()
if err != nil {
    log.Fatal(err)
}