0Pricing
Go Academy · Lesson

Transactions and Migrations

BEGIN/COMMIT patterns and schema migrations

Transactions in database/sql

Wrap operations in a transaction with db.BeginTx. Commit or rollback at the end; always defer a rollback to handle panics.

tx, err := db.BeginTx(ctx, nil)
if err != nil { return err }
defer tx.Rollback() // no-op after Commit

_, err = tx.ExecContext(ctx, "UPDATE accounts SET balance=balance-100 WHERE id=$1", from)
if err != nil { return err }
_, err = tx.ExecContext(ctx, "UPDATE accounts SET balance=balance+100 WHERE id=$1", to)
if err != nil { return err }
return tx.Commit()

Transaction isolation levels

Pass sql.TxOptions to control isolation level:

tx, err := db.BeginTx(ctx, &sql.TxOptions{
    Isolation: sql.LevelSerializable,
    ReadOnly:  false,
})

All lessons in this course

  1. database/sql and Drivers
  2. sqlx: Struct Scanning and Named Queries
  3. pgx: High-Performance PostgreSQL Driver
  4. Transactions and Migrations
← Back to Go Academy