【问题标题】:golang-migrate unable to find postgres drivergolang-migrate 找不到 postgres 驱动程序
【发布时间】:2020-04-01 08:20:45
【问题描述】:

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

这个函数是从我的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

为什么会这样?

【问题讨论】:

    标签: postgresql go golang-migrate


    【解决方案1】:

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

    以下导入为我解决了它

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2017-08-02
        • 2023-03-27
        • 2016-01-13
        • 2013-08-31
        • 2016-08-09
        • 1970-01-01
        • 2019-01-17
        • 2016-05-26
        • 2019-10-17
        相关资源
        最近更新 更多