Search code examples
postgresqlgogolang-migrate

golang-migrate unable to find postgres driver


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?


Solution

  • 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"