Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This article is to enable auto migration in GoLang with integration with GORM in up-down approach.

...

  1. At first, create migration CLI

    Code Block
    languagego
    $ 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)
  2. Navigate to your migrate project and find out migrate.exe file. 

  3. Copy migrate.exe.

  4. Paste it into $GOPATH/bin folder.

  5. Your migration CLI is ready to use. N.B: [find out the latest version of migrate cmd and replace it]

  6. Read more about CLI.

...

  1. migrate command will create a db/migrations folder with to sql (up/down) file.

  2. Edit up file. for example-

    • Code Block
      languagesql
      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
      );
  3. Edit down file. for example-

    • DROP TABLE IF EXISTS users;

  4. Now let install golang-migrate.

    1. $ go get github.com/golang-migrate/migrate

  5. Configure migration with GORM.

    • Code Block
      languagego
      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)
  6. 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)

      Code Block
      languagego
      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)
    • Run migration script. i.e:

      Code Block
      languagego
      migrate -source file://{migration file path} -database postgres://{user name}:{password}@{db location}/{db name}?sslmode=disable up
    • For example:

      Code Block
      migrate -source file://db/migrations -database postgres://postgres:648782@localhost:5432/zachai_auction?sslmode=disable up
    • use down for dropping

  7. Happy Coding…(smile)

 

Info

...