GORM AutoMigrate: Tables Not Created
In this tutorial, you'll learn about GORM AutoMigrate: Tables Not Created. We cover key concepts, practical examples, and best practices.
GORM AutoMigrate -- Use GORM's AutoMigrate correctly by ensuring all model structs are passed and fields are exported.
The Problem
AutoMigrate only creates tables for models passed to it. Unexported fields (lowercase) are ignored. Structs without a primary key field may fail silently.
Wrong
type user struct { Name string }
db.AutoMigrate(&user{})
Output:
// No table created! user is not exported
Right
type User struct {
ID uint `gorm:'primaryKey'`
Name string `gorm:"not null"`
}
db.AutoMigrate(&User{}, &Product{})
Output:
// Tables created with columns and constraints
Prevention
- Pass all model structs to AutoMigrate
- Ensure struct names are capitalized
- Always include a primary key
- AutoMigrate does not delete columns
- Use db.Migrator() for fine-grained control
Common Mistakes with gorm auto migrate
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro