6

In my internal/platform/database/database.go


import (
    "github.com/golang-migrate/migrate"
    "github.com/jmoiron/sqlx"
    _ "github.com/lib/pq"
)

func RunMigrations() error {
    m, err := migrate.New(
        "file://schema",
        "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable")
    if err != nil {
        return errors.Wrap(err, "error creating migrations object")
    }

This function is invoked from my cmd/my-api/main.go as follows:


import (
    _ "github.com/golang-migrate/migrate/v4/database/postgres"
    _ "github.com/golang-migrate/migrate/v4/source/file"
    "github.com/jmoiron/sqlx"
    _ "github.com/lib/pq"
    "github.com/myrepo/myproject/internal/platform/database"
)

    // =========================================================================
    // Executing migrations
    if err := database.RunMigrations(); err != nil {
        log.Fatal(err)
    }

Although I am importing postgres driver in both files, _ "github.com/lib/pq"

running the program fails as follows:

error creating migrations object: source driver: unknown driver file (forgotten import?)
exit status 1

Why is that?

2 Answers 2

7

It seems that golang-migrate needs its own version of the corresponding driver (?)

The following import solved it for me

_ "github.com/golang-migrate/migrate/v4/database/postgres"
Sign up to request clarification or add additional context in comments.

Comments

1

When you import the following, postgres driver init function triggered and this function register the postgres driver.

_ "github.com/golang-migrate/migrate/v4/database/postgres"

You can inspect this. https://www.calhoun.io/why-we-import-sql-drivers-with-the-blank-identifier/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.