0Pricing
Go Academy · Lesson

Models and AutoMigrate

Define and migrate schema.

Models and AutoMigrate is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is GORM

GORM is the most popular ORM for Go. It maps Go structs to database tables so you work with objects instead of raw SQL. It supports PostgreSQL, MySQL, SQLite, and more.

  • Struct-to-table mapping
  • Automatic migrations
  • Associations and hooks

Defining a Model

A model is a Go struct. Each exported field becomes a column. Embedding gorm.Model adds ID, CreatedAt, UpdatedAt, and DeletedAt fields.

type User struct {
    gorm.Model
    Name  string
    Email string
    Age   int
}

Field Tags

Struct tags customize columns. You can set size, uniqueness, indexes, and defaults with the gorm tag. A tag is written in backticks after the field type, for example gorm:"uniqueIndex;size:255".

type User struct {
    // ID    uint    tag: gorm:"primaryKey"
    // Email string  tag: gorm:"uniqueIndex;size:255"
    // Name  string  tag: gorm:"not null"
    ID    uint
    Email string
    Name  string
}

Naming Conventions

GORM pluralizes and snake_cases by default: a User struct maps to a users table, and field CreatedAt maps to created_at. You can override these.

Opening with GORM

gorm.Open takes a dialector for your database and returns a *gorm.DB. This handle wraps the connection pool.

db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
    log.Fatal(err)
}

AutoMigrate

AutoMigrate creates tables, missing columns, and indexes to match your structs. It is additive: it will not drop columns or alter types destructively.

db.AutoMigrate(&User{}, &Product{})

What AutoMigrate Does Not Do

AutoMigrate never deletes unused columns or shrinks types, to avoid data loss. For renames, drops, or type changes you need explicit migration tooling.

A Runnable Model Mapping Simulation

GORM needs a real database driver, so this runnable example simulates the snake_case table and column mapping that AutoMigrate performs.

package main

import (
    "fmt"
    "strings"
)

func toSnake(s string) string {
    var b strings.Builder
    for i, r := range s {
        if i > 0 && r >= 65 && r <= 90 {
            b.WriteByte(95)
        }
        if r >= 65 && r <= 90 {
            r = r + 32
        }
        b.WriteRune(r)
    }
    return b.String()
}

func main() {
    model := "User"
    fields := []string{"ID", "Name", "CreatedAt"}
    fmt.Println("table:", toSnake(model)+"s")
    for _, f := range fields {
        fmt.Println("column:", toSnake(f))
    }
}

The DeletedAt Field

If your model embeds gorm.Model or has a gorm.DeletedAt field, GORM enables soft deletes. Deleted rows get a timestamp and are hidden from queries instead of being removed.

Custom Table Names

Implement a TableName method on the model to override the default. This is useful when your schema uses names that do not match GORM conventions.

func (User) TableName() string {
    return "app_users"
}

External Package Note

GORM and its dialectors live outside the standard library, requiring go get gorm.io/gorm and a driver like gorm.io/driver/postgres. The GORM snippets here are illustrative.

Quick Check

Test your model knowledge.

Recap

You learned models and AutoMigrate:

  • Structs map to tables; gorm.Model adds ID and timestamps
  • Tags set primary keys, indexes, constraints
  • Default naming is pluralized snake_case
  • AutoMigrate is additive and never destructive
  • DeletedAt enables soft deletes

Frequently asked questions

Is the “Models and AutoMigrate” lesson free?

Yes — the full text of “Models and AutoMigrate” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Models and AutoMigrate”?

Define and migrate schema. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Models and AutoMigrate” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Models and AutoMigrate
  2. CRUD Operations
  3. Associations
  4. Hooks and Scopes
← Back to Go Academy