Skip to main content

Transactions

db.Tx runs a function in a transaction. It commits if the function returns nil, and rolls back on an error or a panic. tx is your own context type, bound to that transaction.

Run several writes together​

err := db.Tx(ctx, func(tx *AppDB) error {
bob := &User{Name: "Bob", Email: "bob@example.com"}

if err := tx.Users.Insert(ctx, bob); err != nil {
return err
}

return tx.Posts.Insert(ctx, &Post{UserID: bob.ID, Title: "First"})
})

The error is returned unchanged. A panic propagates after the rollback.

Use tx inside the function: anything you do on db runs outside the transaction. Cancelling the context rolls the transaction back.

Lock rows and move money​

ForUpdate locks the rows you read, so two transfers on one account take turns.

func transfer(ctx context.Context, db *BankDB, from, to, amount int64) error {
return db.Tx(ctx, func(tx *BankDB) error {
// A session inside the transaction has a tracker of its own.
tx = ant.Session(tx, ant.WithTracking(true))

source, err := tx.Accounts.Where(ant.Eq(&Accounts.ID, from)).ForUpdate().Single(ctx)
if err != nil {
return err
}

target, err := tx.Accounts.Where(ant.Eq(&Accounts.ID, to)).ForUpdate().Single(ctx)
if err != nil {
return err
}

if source.Balance < amount {
return ErrInsufficientFunds // rolls back, nothing is written
}

source.Balance -= amount
target.Balance += amount

return tx.SaveChanges(ctx)
})
}
SELECT ... FROM "accounts" WHERE "accounts"."id" = $1 LIMIT $2 FOR UPDATE
SELECT ... FROM "accounts" WHERE "accounts"."id" = $1 LIMIT $2 FOR UPDATE
UPDATE "accounts" SET "balance" = $1, "updated_at" = $2, "version" = $3 WHERE "accounts"."id" = $4 AND "accounts"."version" = $5
UPDATE "accounts" SET "balance" = $1, "updated_at" = $2, "version" = $3 WHERE "accounts"."id" = $4 AND "accounts"."version" = $5

The UPDATEs include version because Account has a version column. To run the transfer again after a deadlock, see retries.

SaveChanges in a transaction​

SaveChanges always runs in a transaction. Outside one it opens its own. Inside one it uses a savepoint, so a failed save undoes only itself.

err := db.Tx(ctx, func(tx *AppDB) error {
user, err := tx.Users.Find(ctx, id)
if err != nil {
return err
}

user.Age++

return tx.SaveChanges(ctx)
})
// SAVEPOINT ant_sp_1
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
// RELEASE SAVEPOINT ant_sp_1

If the transaction then rolls back, the tracker takes the save back too: a rolled-back insert has its generated key and timestamps cleared and is inserted by the next SaveChanges, and a rolled-back update is pending again.

user.Age = 50

err := db.Tx(ctx, func(tx *AppDB) error {
if err := tx.SaveChanges(ctx); err != nil {
return err
}

return errors.New("changed my mind")
})

has, _ := db.HasChanges(ctx)
// has is true: the update was rolled back, so it is pending again

ant.WithoutAutoTx() stops SaveChanges and Insert from opening transactions of their own, so a failure partway leaves earlier statements in place. Those rows count as saved, so calling SaveChanges again writes only the rest. Use it only to control transactions yourself.

Nest transactions​

A Tx inside a Tx becomes a savepoint, so only the inner part rolls back. That also recovers from a failed statement, after which PostgreSQL fails every later statement in the transaction until a rollback.

err := db.Tx(ctx, func(tx *AppDB) error {
if err := tx.Users.Insert(ctx, carl); err != nil {
return err
}

inner := tx.Tx(ctx, func(tx2 *AppDB) error {
return tx2.Users.Insert(ctx, dup) // same email as carl
})
if inner != nil {
log.Println("skipped dup:", inner)
}

return nil // carl commits either way
})
// SAVEPOINT ant_sp_1
// INSERT INTO "users" (...) VALUES (...) RETURNING "id" -- carl
// RELEASE SAVEPOINT ant_sp_1
// SAVEPOINT ant_sp_2 -- the inner Tx
// SAVEPOINT ant_sp_3 -- the inner Insert's own
// INSERT INTO "users" (...) VALUES (...) RETURNING "id" -- dup, fails with 23505
// ROLLBACK TO SAVEPOINT ant_sp_3
// ROLLBACK TO SAVEPOINT ant_sp_2

Find or create inside a transaction​

FirstOrCreate returns the matching row or inserts yours. If another writer inserts the same row in between, the unique constraint stops the insert and FirstOrCreate returns that writer's row. Inside a transaction the re-read locks the row FOR UPDATE, because the snapshot, at MySQL's default REPEATABLE READ, predates that row and wouldn't show it, and because the caller usually updates it next: two callers holding a shared lock would deadlock there.

err := db.Tx(ctx, func(tx *AppDB) error {
eve := &User{Name: "Eve", Email: "eve@example.com"}

found, created, err := tx.Users.FirstOrCreate(ctx, eve, ant.Eq(&Users.Email, eve.Email))
if err != nil {
return err
}

log.Println(found.ID, created)

return nil
})
// SELECT ... FROM "users" WHERE "users"."email" = $1 LIMIT $2
// INSERT INTO "users" (...) VALUES (...) RETURNING "id" -- loses the race, 23505
// SELECT ... FROM "users" WHERE "users"."email" = $1 LIMIT $2 FOR UPDATE

The failed insert runs in a savepoint, so the transaction stays usable.

Begin and Commit yourself​

ant.Begin returns a transaction you must finish. Prefer Tx, which can't leave one open.

tx, err := ant.Begin(ctx, db)
if err != nil {
return err
}

defer tx.Rollback()

if err := tx.Users.Insert(ctx, alice); err != nil {
return err
}

return tx.Commit()

After Commit, the deferred Rollback returns ant.ErrTxDone and does nothing. db.Commit() outside a transaction returns ant.ErrNotInTx.

Savepoints by hand​

err := tx.Savepoint(ctx, "before")
err = tx.RollbackTo(ctx, "before")
err = tx.Release(ctx, "before")
// SAVEPOINT "before"
// ROLLBACK TO SAVEPOINT "before"
// RELEASE SAVEPOINT "before"

RollbackTo does not rewind the tracker. Reload entities whose changes it undid, or use a nested Tx, which does.

Isolation and read-only​

Options go after the function, on Tx and Begin.

err := db.Tx(
ctx,
func(tx *AppDB) error {
return nil
},
ant.Isolation(sql.LevelSerializable),
)

err = db.Tx(
ctx,
func(tx *AppDB) error {
return nil
},
ant.ReadOnly(),
)

The options hold on a nested Tx too. There it is a savepoint, so on PostgreSQL ant.ReadOnly() lasts until the savepoint ends. The other databases can't make a transaction read-only once it has begun, so they return ant.ErrUnsupported, and ant.Isolation on a nested Tx is ant.ErrNestedIsolation everywhere.

Preview what a transaction writes​

ant.DryRun runs a function in a transaction that always rolls back, and returns the statements it ran.

statements, err := ant.DryRun(ctx, bank, func(tx *BankDB) error {
return transfer(ctx, tx, 1, 2, 30)
})

for _, s := range statements {
fmt.Println(s.SQL, s.Args)
}

Sequences still move on, and anything the function does outside the database still happens.

One goroutine at a time​

A transaction is one connection, so use tx from one goroutine at a time, as with a *sql.Tx. Goroutines may pass it on, but two running together fail in the driver, and two sets of savepoints on one connection would undo each other's work. A context from UseConn is one connection too.

For parallel work, give each goroutine its own transaction:

var wg sync.WaitGroup

for _, batch := range batches {
wg.Go(func() {
_ = db.Tx(ctx, func(tx *AppDB) error {
return tx.Posts.Insert(ctx, batch...)
})
})
}

wg.Wait()

On SQL Server, ant rolls the transaction back itself when ctx ends, because go-mssqldb v1.11.2 leaves a goroutine reading the connection after a rollback with an ended context.