如何使用golang-migrate进行迁移

3
我有一个简单的应用程序,使用golang-migrate/migrate和postgresql数据库。然而,当我调用Migration函数时,我认为我的migrate.New()中的sourceURL或databaseURL是无效的内存地址或空指针,导致错误。
但我不确定我的sourceURL或databaseURL为什么会引起错误-我将sourceURL存储为file:///database/migration,这是存储我的sql文件的目录,将databaseURL定义在我的Makefile中,如下所示:postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable
我的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


然后,我的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")
}

当我在main.go中调用db.Migration时,我遇到了错误。

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
}

这是我的config.go文件。其中DATABASE_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"),
        },
    }
}

它只会打印出0x00。 - husky
你能展示一下错误吗? - NuLo
我的err出现了错误,错误发生在迁移源驱动程序时:未知的驱动程序'file'(是否忘记导入?) - husky
1个回答

4

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

import (
  ....
  _ "github.com/golang-migrate/migrate/v4/source/file"
)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接