你可以使用 golang-migrate 和 go 的嵌入功能吗?

Can you use golang-migrate with go's embed function?

我正在尝试使用 golang-migrate 将 sql 文件迁移到我的 postgresql 数据库中。我可能做错了,但是当我 运行 迁移命令时它说没有找到方案:

 $ go run ./cmd/  migrate
2022/04/05 16:20:29 no scheme
exit status 1

代码如下:

  // package dbschema contains the database schema, migrations, and seeding data.

    package dbschema
    
    import (
        "context"
        _ "embed" // Calls init function.
        "fmt"
        "log"
    
        "github.com/golang-migrate/migrate/v4"
        "github.com/golang-migrate/migrate/v4/database/postgres"
        "github.com/jmoiron/sqlx"
        "github.com/jonleopard/bootstrap/pkg/sys/database"
        _ "github.com/lib/pq"
    )
    
    var (
        //go:embed sql/000001_schema.up.sql
        schemaDoc string
    
        //go:embed sql/seed.sql
        seedDoc string
    )
    
    // Migrate attempts to bring the schema for db up to date with the migrations
    // defined in this package.
    func Migrate(ctx context.Context, db *sqlx.DB) error {
        if err := database.StatusCheck(ctx, db); err != nil {
            return fmt.Errorf("status check database: %w", err)
        }
    
        driver, err := postgres.WithInstance(db.DB, &postgres.Config{})
        if err != nil {
            return fmt.Errorf("Construct Migrate driver: %w", err)
        }
    
        m, err := migrate.NewWithDatabaseInstance(schemaDoc, "postgres", driver)
        if err != nil {
            log.Fatal(err)
        }
    
        return m.Up()
    }

NewWithDatabaseInstance的定义是:

func NewWithDatabaseInstance(sourceURL string, databaseName string, databaseInstance database.Driver) (*Migrate, error)

所以第一个参数是 URL 并且您正在传递脚本本身。 NewWithDatabaseInstance calls SchemeFromURL which is what generates the error you are seeing (because the url you are passing does not contain a :). A URL 包含一个“方案”,然后是 :,然后是其他信息。

要将 golang-migrate 与 embed 一起使用,请参阅 example in the docs:

//go:embed testdata/migrations/*.sql
var fs embed.FS

func main() {
    d, err := iofs.New(fs, "testdata/migrations")
    if err != nil {
        log.Fatal(err)
    }
    m, err := migrate.NewWithSourceInstance("iofs", d, "postgres://postgres@localhost/postgres?sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    err = m.Up()
    if err != nil {
        // ...
    }
    // ...
}

您会注意到,这会传递一个文件夹(作为 embed.FS)而不是单个文件。这是因为 golang-migrate 旨在应用多个迁移,而不仅仅是 运行 针对数据库的单个脚本。你应该能够使用类似的东西:

//go:embed sql/*.sql
var schemaFs embed.FS
...
d, err := iofs.New(fs, "sql") // Get migrations from sql folder
if err != nil {
    log.Fatal(err)
}
m, err := migrate.NewWithSourceInstance("iofs", d, "postgres", driver)