How to enable auto migration in Go?
This article is to enable auto migration in GoLang with integration with GORM in up-down approach.
Instructions
To enable auto migration in Go
with GORM
install golang-migrate
.
At first, create migration CLI
$ go get -u -d github.com/golang-migrate/migrate/cmd/migrate $ cd $GOPATH/src/github.com/golang-migrate/migrate/cmd/migrate $ git checkout $TAG # e.g. v4.8.0 $ go build -tags 'postgres' -ldflags="-X main.Version=$(git describe --tags)
Navigate to your migrate project and find out
migrate.exe
file.Copy
migrate.exe
.Paste it into
$GOPATH/bin
folder.Your migration CLI is ready to use. N.B: [find out the latest version of migrate cmd and replace it]
Read more about CLI.
Run your first migration.
i.e: migrate create -ext sql -dir db/migrations -digits 7 create_users_table
migrate command will create a
db/migrations
folder with tosql
(up/down) file.Edit up file. for example-
CREATE TABLE IF NOT EXISTS users( user_id serial PRIMARY KEY, username VARCHAR (50) UNIQUE NOT NULL, password VARCHAR (50) NOT NULL, email VARCHAR (300) UNIQUE NOT NULL );
Edit down file. for example-
DROP TABLE IF EXISTS users;
Now let install
golang-migrate
.$ go get github.com/golang-migrate/migrate
Configure migration with
GORM
.db, err := gorm.Open("postgres", config.ConnectionString) driver, err := postgres.WithInstance(db.DB(), &postgres.Config{}) m, err := migrate.NewWithDatabaseInstance( "file://db/migrations", "postgres", driver) m.Steps(2)
Use command line to run migration
If you prefer a command-line tool over configured code then it’s for you!
Remove
GORM
configuration. (If any)Run migration script. i.e:
For example:
use down for dropping
Happy Coding…