Using database migration in Golang ensures that the database is synchronized with the code. Migration can be performed using libraries such as Ent or Gormigrate: Using Ent: Install Ent. Generate migration files. Run the migration. Using Gormigrate: Install Gormigrate. Create migration files (including up and down migration functions). Run the migration.
#How to use database migration in Golang?
Database migration is a technique for managing database schema changes to ensure that the database is always in sync with the code. In Golang, database migrations can be performed using libraries such as [ent](https://entgo.io/docs/migrate/) or [gormigrate](https://github.com/go-gormigrate/gormigrate).
Use Ent for database migration
Ent is a Golang ORM that provides a built-in migration system. To use Ent for database migration, follow these steps:
Install Ent:
go get github.com/ent/ent/cmd/ent
Generate migration file:
ent generate migration AddUser
Run migration:
ent migrate
Use Gormigrate for database migration
Gormigrate is a third-party library that can be used Perform database migration in Golang. To use Gormigrate, follow these steps:
Install Gormigrate:
go get github.com/go-gormigrate/gormigrate/v2
Create migration files:
touch migrations/001_add_user.go
Write code in the migration file:
import ( "github.com/go-gormigrate/gormigrate/v2/gormigrate" "gorm.io/gorm" ) func Up(db *gorm.DB) error { type User struct { ID uint `gormigrate:"primary_key"` Name string } return db.AutoMigrate(&User{}) } func Down(db *gorm.DB) error { return db.Migrator().DropTable("users") }
Run the migration:
gormigrate -up
Practical case
Suppose we have a user table and its schema has changed. Using Gormigrate, we can create a migration file like the following:
import ( "github.com/go-gormigrate/gormigrate/v2/gormigrate" "gorm.io/gorm" ) func Up(db *gorm.DB) error { type User struct { ID uint `gormigrate:"primary_key"` Name string Password string } return db.AutoMigrate(&User{}) } func Down(db *gorm.DB) error { return db.Migrator().DropColumn("users", "password") }
Running this migration will add a new "password" column to the "users" table.
The above is the detailed content of How to use database migration in Golang?. For more information, please follow other related articles on the PHP Chinese website!