Welcome to our in-depth tutorial on Go GORM Migrations! In this lesson, we'll learn about database schema management with GORM, a popular ORM for Go. We'll cover:
In software development, database schema changes are inevitable. GORM Migrations help automate the process of updating the database schema to match changes in the application. This makes it easier to develop, test, and deploy applications with less manual effort.
First, let's set up a new GORM project using the Go module system.
mkdir go-gorm-migrations
cd go-gorm-migrations
go mod init github.com/yourusername/go-gorm-migrationsNext, add the GORM and GORM Migrations dependencies to the go.mod file:
require (
github.com/jinzhu/gorm v1.20.0
github.com/jinzhu/gormigrate v1.6.0
)
GORM Migrations allow us to create, update, and rollback database schema changes. To create a new migration, run the following command:
go run github.com/jinzhu/gormigrate/cmd/gormigrate create -dir migrationsThis command creates a new migration file in the migrations directory.
To apply the migrations, run the following command:
go run github.com/jinzhu/gormigrate/cmd/gormigrate upIf something goes wrong, you can roll back to a previous migration using the following command:
go run github.com/jinzhu/gormigrate/cmd/gormigrate down -step NReplace N with the number of the migration you want to roll back to.
During the migration process, you might encounter errors or conflicts. To handle these, you can use the OnConflict and OnError clauses in your migration files.
Here's an example:
// Up migration
func (dn *Schema) Up100001(tx *gomigrate.DB) error {
if err := tx.AutoMigrate(&User{}); err != nil {
return err
}
return tx.Model(&User{}).AddIndex("user_index", "username", func(index *index.Index) {
index.Unique = true
index.OnConflict = index.OnConflictError
}).Error
}
// Down migration
func (dn *Schema) Down100001(tx *gomigrate.DB) error {
if err := tx.Model(&User{}).DropIndex("user_index").Error; err != nil {
return err
}
return nil
}š Note: In the OnConflict example, the migration will fail if a unique index conflict occurs.
What is the purpose of GORM Migrations?
We'll continue exploring GORM Migrations in the next lessons, including more advanced topics like creating custom migrations and handling complex schema changes. Stay tuned! š