2

在我的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")
    }

此函数从 my 调用cmd/my-api/main.go如下:


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)
    }

虽然我在两个文件中都导入了postgres驱动程序,_ "github.com/lib/pq"

运行程序失败如下:

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

这是为什么?

4

2 回答 2

4

好像golang-migrate需要自己版本的对应驱动(?)

以下导入为我解决了

_ "github.com/golang-migrate/migrate/v4/database/postgres"
于 2020-03-28T19:20:46.643 回答
1

当您导入以下内容时,会触发 postgres 驱动程序初始化函数,并且该函数会注册 postgres 驱动程序。

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

你可以检查这个。 https://www.calhoun.io/why-we-import-sql-drivers-with-the-blank-identifier/

于 2020-04-01T00:20:45.487 回答