Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Databases and GORM

Transactions, Hooks and Migrations in GORM

Keep data consistent with GORM transactions, use hooks like BeforeCreate, handle errors and rollback in Gin handlers, and manage schema changes with versioned migrations.

Some operations must succeed or fail together. Moving money means subtracting from one account and adding to another; placing an order means creating the order, its lines and reducing stock. If the server crashes between steps, you cannot be left with half the work done. Databases solve this with transactions. This lesson shows how to use them in GORM inside Gin handlers, how hooks run code around saves, and how to evolve the schema safely with migrations.

GORM is not runnable in the page, so its code is read-only. The runnable examples model the same behaviours with the standard library: a store with commit and rollback, hook-like interfaces, and a version-based migration runner.

Why transactions: ACID in one paragraph

A transaction is a group of statements that is atomic (all or nothing), consistent (rules hold before and after), isolated (concurrent transactions do not see each other's half-finished work) and durable (committed data survives a crash). The SQL tutorial explains isolation levels in detail; here we focus on using them from Go.

The Transaction helper

Go
func (s *Server) transfer(c *gin.Context) {
	var in struct {
		From, To uint
		Amount   int `binding:"gt=0"`
	}
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := s.db.WithContext(c.Request.Context()).Transaction(func(tx *gorm.DB) error {
		var from Account
		// lock the row so two transfers cannot both spend the same balance
		if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&from, in.From).Error; err != nil {
			return err
		}
		if from.Balance < in.Amount {
			return ErrInsufficientFunds // returning an error rolls everything back
		}
		if err := tx.Model(&Account{}).Where("id = ?", in.From).
			Update("balance", gorm.Expr("balance - ?", in.Amount)).Error; err != nil {
			return err
		}
		return tx.Model(&Account{}).Where("id = ?", in.To).
			Update("balance", gorm.Expr("balance + ?", in.Amount)).Error
	})

	switch {
	case errors.Is(err, ErrInsufficientFunds):
		c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "insufficient funds"})
	case errors.Is(err, gorm.ErrRecordNotFound):
		c.JSON(http.StatusNotFound, gin.H{"error": "account not found"})
	case err != nil:
		c.JSON(http.StatusInternalServerError, gin.H{"error": "transfer failed"})
	default:
		c.Status(http.StatusNoContent)
	}
}

The rules of Transaction(func(tx *gorm.DB) error):

  • Return nil to commit; return an error to roll back. A panic also rolls back.
  • Inside the function use only tx, never the outer db, or those queries run outside the transaction.
  • Keep transactions short: no HTTP calls, no sleeping and no user interaction while a transaction (and its locks) is open.

Manual control exists too: tx := db.Begin(), then tx.Commit() or tx.Rollback(). It is easy to forget a rollback on an early return, so prefer the helper. Nested calls create savepoints, so an inner failure can roll back only its part.

Atomicity you can run

The stand-in below models a tiny bank. Transaction works on a copy of the data and swaps it in only if the callback returns nil, which is what rollback means from the outside. First run a successful transfer, then one that fails halfway.

Go Commit and rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In the failed transfer the credit was applied to the copy but never committed, so the balances stay as they were.

Hooks

GORM calls methods on your model at set moments: BeforeSave, BeforeCreate, AfterCreate, BeforeUpdate, AfterUpdate, BeforeDelete, AfterFind and more. They run inside the same transaction as the operation, and an error from a Before hook cancels it:

Go
func (u *User) BeforeCreate(tx *gorm.DB) error {
	u.Email = strings.ToLower(strings.TrimSpace(u.Email))
	if u.ID == 0 { // e.g. generate a UUID primary key
		u.UID = uuid.NewString()
	}
	return nil
}

func (o *Order) AfterCreate(tx *gorm.DB) error {
	return tx.Model(&Product{}).Where("id = ?", o.ProductID).
		Update("stock", gorm.Expr("stock - ?", o.Quantity)).Error
}

Hooks are good for small invariants (normalizing data, setting defaults). Avoid hiding business rules, network calls or emails inside them: they surprise readers and run on every save path, including bulk imports. Put workflows in an explicit service function instead. Note too that batch methods like Updates with a map or Exec may skip hooks, so do not rely on them for security rules.

The hook mechanism is just an interface check, which you can build in a few lines:

Go Hooks as optional interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Migrations: changing the schema over time

AutoMigrate is additive and convenient, but it cannot rename a column, drop one, change a type or backfill data. In production use versioned migrations: numbered SQL files applied in order, each exactly once, with a record of which have run. Popular tools are golang-migrate, goose, atlas and pressly's libraries. A typical layout:

TEXT
migrations/
  0001_create_products.up.sql
  0001_create_products.down.sql
  0002_add_sku.up.sql
  0002_add_sku.down.sql
SQL
-- 0002_add_sku.up.sql
ALTER TABLE products ADD COLUMN sku VARCHAR(40);
UPDATE products SET sku = 'LEGACY-' || id;
ALTER TABLE products ALTER COLUMN sku SET NOT NULL;
CREATE UNIQUE INDEX products_sku_key ON products (sku);

Safe-change habits: add a new column as nullable, backfill, then add the constraint; deploy code that works with both schemas before removing anything (expand and contract); never edit a migration that has already run anywhere.

The runner is simple enough to read in one screen. It keeps a version number (a table row in real life) and applies each pending step in order:

Go A version-based migration runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Run migrations as a separate step in your deploy (a one-off command or an init container), not at the start of every app instance, so two replicas never race.

Common mistakes

  • Using db instead of tx inside the transaction callback.
  • Holding a transaction open while calling a payment API or sending email.
  • Reading a balance, checking it in Go and writing it back without a lock or an atomic expression.
  • Relying on AutoMigrate in production for renames and drops.
  • Editing a migration that has already been applied.
  • Putting business workflows in hooks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you roll back inside db.Transaction(func(tx *gorm.DB) error {...})?

    A nil return commits and any error (or panic) rolls back.
  2. 2. Which handle must queries inside the transaction use?

    Only tx is bound to the transaction. Using db runs outside it and breaks atomicity.
  3. 3. What is a good use of a BeforeCreate hook?

    Hooks suit small data invariants. Slow or external side effects belong in explicit service code.
  4. 4. Why prefer versioned migrations over AutoMigrate in production?

    AutoMigrate only adds. Versioned files describe every change and run exactly once.

Summary

  • Wrap multi-step writes in db.Transaction; return an error to roll back; use only tx inside.
  • Keep transactions short and use locks or atomic gorm.Expr updates against races.
  • Hooks such as BeforeCreate enforce small invariants inside the same transaction.
  • Use versioned migrations in production, with expand-and-contract for risky changes.

Next: Passwords and Sessions