pkaramol
pkaramol

Reputation: 19322

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?

Upvotes: 6

Views: 6729

Answers (2)

demirpolatb
demirpolatb

Reputation: 151

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/

Upvotes: 1

pkaramol
pkaramol

Reputation: 19322

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"

Upvotes: 7

Related Questions