# HG changeset patch # User Peter Sanchez # Date 1681760774 21600 # Mon Apr 17 13:46:14 2023 -0600 # Node ID d0253f8abd8592d43b1556665753bc8dec3338bd # Parent cabd7b9560d21a6d92a267e5307a49088ee66860 Adding FSFileMigration function to support fs.FS types diff --git a/migrate.go b/migrate.go --- a/migrate.go +++ b/migrate.go @@ -4,7 +4,8 @@ "context" "database/sql" "fmt" - "io/ioutil" + "io" + "io/fs" "os" ) @@ -315,7 +316,7 @@ // think it makes more sense to panic here. panic(err) } - fileBytes, err := ioutil.ReadAll(f) + fileBytes, err := io.ReadAll(f) if err != nil { panic(err) } @@ -333,3 +334,35 @@ } return m } + +// FSFileMigration is the same as FileMigration except that it uses the provided +// `fs.FS` instance to read the file from. Useful for embedding migrations, etc. +func FSFileMigration(id, upFile, downFile string, timeout int, sfs fs.FS) Migration { + fileFn := func(filename string) func(ctx context.Context, tx *sql.Tx) error { + if filename == "" { + return nil + } + f, err := sfs.Open(filename) + if err != nil { + // We could return a migration that errors when the migration is run, but I + // think it makes more sense to panic here. + panic(err) + } + fileBytes, err := io.ReadAll(f) + if err != nil { + panic(err) + } + return func(ctx context.Context, tx *sql.Tx) error { + _, err := tx.ExecContext(ctx, string(fileBytes)) + return err + } + } + + m := Migration{ + ID: id, + Timeout: timeout, + Migrate: fileFn(upFile), + Rollback: fileFn(downFile), + } + return m +}