Models and AutoMigrate
Define and migrate schema.
Models and AutoMigrate is a free Go Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.
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
Learn Go with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Models and AutoMigrate” lesson free?
Yes — any 3 lessons of the Go Academy learning path, including “Models and AutoMigrate”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
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
- Models and AutoMigrate
- CRUD Operations
- Associations
- Hooks and Scopes