husky
husky

Reputation: 1351

How to do Migration using golang-migrate

I have a simple application using golang-migrate/migrate with postgresql database. However, I think I receive an error when I call Migration function since my either sourceURL or databaseURL in migrate.New() is invalid memory address or nil pointer.

But I am not sure why my sourceURL or databaseURL is causing error - I store sourceURL as file:///database/migration which is the directory where my sql file is stored, databaseURL as postgres://postgres:[email protected]:5432/go_graphql?sslmode=disable which is defined in my Makefile.

My Makefile is like this

migrate:
    migrate -source file://database/migration \
            -database postgres://postgres:[email protected]:5432/go_graphql?sslmode=disable up

rollback:
    migrate -source file://database/migration \
            -database postgres://postgres:[email protected]:5432/go_graphql?sslmode=disable down

drop:
    migrate -source file://database/migration \
            -database postgres://postgres:[email protected]:5432/go_graphql?sslmode=disable drop

migration:
    migrate create -ext sql -dir database/migration go_graphql

run:
    go run main.go

Then, my main.go is like below.

func main() {
    ctx := context.Background()

    config := config.New()

    db := pg.New(ctx, config)
    println("HEL")

    if err := db.Migration(); err != nil {
        log.Fatal(err)
    }

    fmt.Println("Server started")
}

I got error when I call db.Migration in main.go

func (db *DB) Migration() error {

    m, err := migrate.New("file:///database/migration/", "postgres://postgres:[email protected]:5432/go_graphql?sslmode=disable"))
    println(m)
    if err != nil {
        // **I get error here!!**
        return fmt.Errorf("error happened when migration")
    }
    if err := m.Up(); err != nil && err != migrate.ErrNoChange {
        return fmt.Errorf("error when migration up: %v", err)
    }

    log.Println("migration completed!")
    return err
}

Here is my config.go. DATABASE_URL is the same as postgres URL

type database struct {
    URL string
}

type Config struct {
    Database database
}

func New() *Config {
    godotenv.Load()

    return &Config{
        Database: database{
            URL: os.Getenv("DATABASE_URL"),
        },
    }
}

Upvotes: 3

Views: 9120

Answers (1)

NuLo
NuLo

Reputation: 1528

With the error you posted in the comments error happened when migration source driver: unknown driver 'file' (forgotten import?) I can tell you that, as stated, you forgot to import file:

import (
  ....
  _ "github.com/golang-migrate/migrate/v4/source/file"
)

You can see an example in https://github.com/golang-migrate/migrate#use-in-your-go-project in the section Want to use an existing database client?

Upvotes: 6

Related Questions