Go GORM Migrations šŸŽÆ

beginner
19 min

Go GORM Migrations šŸŽÆ

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:

  1. Why use GORM Migrations? šŸ“
  2. Setting up a GORM project
  3. Creating a new migration
  4. Running migrations
  5. Rolling back migrations
  6. Handling errors and conflicts

1. Why use GORM Migrations? šŸ’”

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.

2. Setting up a GORM project

First, let's set up a new GORM project using the Go module system.

bash
mkdir go-gorm-migrations cd go-gorm-migrations go mod init github.com/yourusername/go-gorm-migrations

Next, 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 )

3. Creating a new migration

GORM Migrations allow us to create, update, and rollback database schema changes. To create a new migration, run the following command:

bash
go run github.com/jinzhu/gormigrate/cmd/gormigrate create -dir migrations

This command creates a new migration file in the migrations directory.

4. Running migrations

To apply the migrations, run the following command:

bash
go run github.com/jinzhu/gormigrate/cmd/gormigrate up

5. Rolling back migrations

If something goes wrong, you can roll back to a previous migration using the following command:

bash
go run github.com/jinzhu/gormigrate/cmd/gormigrate down -step N

Replace N with the number of the migration you want to roll back to.

6. Handling errors and conflicts

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:

go
// 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.

Quick Quiz
Question 1 of 1

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! 🌟