如何使用 golang-migrate 进行迁移

hus*_*sky 3 postgresql go golang-migrate

我有一个简单的应用程序,使用 golang-migrate/migrate 和 postgresql 数据库。但是,我认为当我调用函数时会收到错误,Migration因为我的 sourceURL 或 databaseURLmigrate.New()是无效的内存地址或 nil 指针。

但我不确定为什么我的sourceURL或databaseURL会导致错误-我将sourceURL存储为file:///database/migration存储sql文件的目录,将databaseURL存储为postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable在我的Makefile中定义的目录。

我的Makefile是这样的

migrate:
    migrate -source file://database/migration \
            -database postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable up

rollback:
    migrate -source file://database/migration \
            -database postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable down

drop:
    migrate -source file://database/migration \
            -database postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable drop

migration:
    migrate create -ext sql -dir database/migration go_graphql

run:
    go run main.go

Run Code Online (Sandbox Code Playgroud)

然后,我的main.go就像下面这样。

func main() {
    ctx := context.Background()

    config := config.New()

    db := pg.New(ctx, config)
    println("HEL")

    if err := db.Migration(); err != nil {
        log.Fatal(err)
    }

    fmt.Println("Server started")
}
Run Code Online (Sandbox Code Playgroud)

db.Migration我调用时出错main.go

func (db *DB) Migration() error {

    m, err := migrate.New("file:///database/migration/", "postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable"))
    println(m)
    if err != nil {
        // **I get error here!!**
        return fmt.Errorf("error happened when migration")
    }
    if err := m.Up(); err != nil && err != migrate.ErrNoChange {
        return fmt.Errorf("error when migration up: %v", err)
    }

    log.Println("migration completed!")
    return err
}
Run Code Online (Sandbox Code Playgroud)

这是我的config.goDATABASE_URL与 postgres URL 相同

type database struct {
    URL string
}

type Config struct {
    Database database
}

func New() *Config {
    godotenv.Load()

    return &Config{
        Database: database{
            URL: os.Getenv("DATABASE_URL"),
        },
    }
}
Run Code Online (Sandbox Code Playgroud)

NuL*_*uLo 5

根据您在评论中发布的错误,error happened when migration source driver: unknown driver 'file' (forgotten import?)我可以告诉您,如上所述,您忘记导入file

import (
  ....
  _ "github.com/golang-migrate/migrate/v4/source/file"
)
Run Code Online (Sandbox Code Playgroud)

您可以在https://github.com/golang-migrate/migrate#use-in-your-go-project部分中查看示例Want to use an existing database client?