Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Databases and GORM

GORM Setup and Models for Gin

Connect a Gin app to a database with GORM, define models with struct tags, run AutoMigrate, share the connection through dependency injection, and learn what GORM does underneath.

Most Gin applications store data in a relational database. Go gives you the low-level database/sql package (see database/sql), and on top of it sits GORM, the most widely used object-relational mapper (ORM). GORM turns structs into tables and method calls into SQL, so a lot of repetitive code disappears. The price is some magic that you should understand, which is what this lesson is for.

Neither Gin nor GORM can run in the in-page runner. The GORM code below is read-only, and the runnable examples build the same ideas (models as structs, struct tags, a repository, dependency injection) with the standard library, so you can see exactly what GORM automates. For the ORM versus SQL trade-off in general, read ORM, GORM and SQL Builders.

Install and connect

Terminal
go get gorm.io/gorm
go get gorm.io/driver/postgres   # or mysql, sqlite, sqlserver
Go
import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func Connect(dsn string) (*gorm.DB, error) {
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	sqlDB, _ := db.DB() // the underlying *sql.DB connection pool
	sqlDB.SetMaxOpenConns(25)
	sqlDB.SetMaxIdleConns(5)
	sqlDB.SetConnMaxLifetime(30 * time.Minute)
	return db, nil
}

gorm.Open does not mean "one connection". It builds a connection pool, so you create the *gorm.DB once at start-up and share it. Never open a new one per request. A typical DSN for PostgreSQL is host=localhost user=app password=... dbname=shop port=5432 sslmode=disable; read it from an environment variable, never hard-code it.

Models are structs

A model is an ordinary struct. GORM maps the struct name to a plural snake-case table (Product becomes products) and each field to a column:

Go
type Product struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	Name      string         `gorm:"size:120;not null;index" json:"name"`
	SKU       string         `gorm:"uniqueIndex;size:40" json:"sku"`
	PriceCents int           `gorm:"not null;default:0" json:"price_cents"`
	InStock   bool           `gorm:"default:true" json:"in_stock"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"-"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

Conventions that do real work:

  • A field named ID is the primary key.
  • CreatedAt and UpdatedAt are filled in automatically.
  • A gorm.DeletedAt field turns Delete into a soft delete: the row stays, with a timestamp, and normal queries hide it.
  • You can embed gorm.Model (it contains ID, CreatedAt, UpdatedAt, DeletedAt) instead of writing them.
  • gorm:"..." tags describe column details; json:"..." tags (from Struct Tags) describe the API output, and the same struct can serve both. For larger apps use separate request and response types so the database shape does not leak into your API.

Create the tables

Go
db.AutoMigrate(&Product{}, &Category{})

AutoMigrate creates missing tables, columns and indexes. It never drops or changes the type of existing columns, so it is safe for development and small projects. For production, most teams switch to versioned SQL migration files, as covered in Transactions, Hooks and Migrations.

What the struct tags mean, in running code

GORM reads your struct with reflection and tags. Here is the idea in a few lines, using the standard library. This stand-in inspects a struct and prints the table definition GORM would derive, so you see how a tag becomes a column.

Go From struct tags to a CREATE TABLE statement

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.

GORM's real implementation is more careful (dialects, defaults, naming strategies), but the principle is this: your struct is the schema.

Sharing the connection with handlers

Handlers need the database. Avoid a global variable; it makes tests painful. Put the dependency in a struct and give the handlers as methods:

Go
type Server struct {
	db *gorm.DB
}

func (s *Server) listProducts(c *gin.Context) {
	var products []Product
	if err := s.db.WithContext(c.Request.Context()).Find(&products).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
		return
	}
	c.JSON(http.StatusOK, products)
}

func main() {
	db, err := Connect(os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	db.AutoMigrate(&Product{})

	s := &Server{db: db}
	r := gin.Default()
	r.GET("/products", s.listProducts)
	r.Run()
}

WithContext(c.Request.Context()) ties the query to the request: if the client disconnects, the query is cancelled. A better design hides GORM behind an interface, so handlers depend on behaviour, not on the library, and tests can use a fake. You can run exactly that pattern:

Go Handlers depend on an interface, not on the database

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.

Swap memStore for a type that wraps *gorm.DB and the handler does not change. This is the same separation that Clean Architecture in Go recommends.

Choosing a driver and configuring GORM

Drivers are separate modules (gorm.io/driver/postgres, mysql, sqlite, sqlserver). SQLite is convenient for tests and prototypes (a CGO-free variant exists). Useful gorm.Config options:

  • Logger: logger.Default.LogMode(logger.Info) prints every SQL statement, great while learning.
  • NamingStrategy: schema.NamingStrategy{SingularTable: true} uses product instead of products.
  • PrepareStmt: true caches prepared statements.
  • SkipDefaultTransaction: true skips the implicit transaction around single writes, a speed-up when you manage transactions yourself.
  • DryRun: true builds SQL without running it.

Common mistakes

  • Opening a new connection inside each handler (exhausts the database).
  • Forgetting that AutoMigrate will not remove or retype columns.
  • Exposing the model directly as JSON and leaking fields such as PasswordHash; use json:"-" or a response type.
  • Ignoring .Error. GORM methods return a *gorm.DB; the failure lives in its Error field.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many *gorm.DB values should a typical service create?

    gorm.Open creates a connection pool, so it is created once and shared. Per-request connections would exhaust the database.
  2. 2. What does adding a gorm.DeletedAt field to a model do?

    With DeletedAt, Delete sets the timestamp and normal queries hide the row. Unscoped() sees it again.
  3. 3. What does AutoMigrate NOT do?

    AutoMigrate is additive on purpose. Destructive changes need explicit migrations.
  4. 4. Why put handlers on a Server struct holding the database?

    Dependency injection keeps handlers testable. Gin accepts any func(*gin.Context), including method values.

Summary

  • GORM maps structs to tables through naming conventions and gorm:"..." tags; AutoMigrate creates what is missing.
  • Create one *gorm.DB at start-up, configure the pool, and inject it (ideally behind an interface).
  • Use WithContext so queries stop when the request ends, and always check .Error.
  • Keep database models and API response types separate as the app grows.

Next: CRUD with GORM and Gin