Go - Transactions & Migrations

Beginner 10/10 Teacher 10/10 Architect 10/10

Transactions & Migrations

Group database operations atomically using transactions and evolve schema safely with migrations.

Try it: Wrap an insert+update in a transaction and roll back on error.

Transactions

tx, err := db.Begin()
if err != nil { /* handle */ }
_, err = tx.ExecContext(ctx, "INSERT INTO accounts(id,balance) VALUES(?,?)", 1, 100)
if err != nil { tx.Rollback(); /* handle */ }
_, err = tx.ExecContext(ctx, "UPDATE accounts SET balance=balance-? WHERE id=?", 10, 1)
if err != nil { tx.Rollback(); /* handle */ }
if err := tx.Commit(); err != nil { /* handle */ }

Migrations (CLI)

Use a migration tool (e.g., golang-migrate) to version schema changes.

// CLI example (bash)
// migrate create -ext sql -dir db/migrations add_users
// migrate -path db/migrations -database $DSN up

Common errors

  • Forgetting to set proper isolation level when needed.
  • Not using context.Context with deadlines for long operations.

Practice

  • Create an idempotent migration to add an index and verify down scripts.

Quick quiz

  1. What happens if you forget to Commit or Rollback?
Show answer The transaction remains open, holding locks/resources—always finish explicitly.