Adding FSFileMigration function to support fs.FS types
1 files changed, 35 insertions(+), 2 deletions(-)

M migrate.go
M migrate.go +35 -2
@@ 4,7 4,8 @@ import (
 	"context"
 	"database/sql"
 	"fmt"
-	"io/ioutil"
+	"io"
+	"io/fs"
 	"os"
 )
 

          
@@ 315,7 316,7 @@ func FileMigration(id, upFile, downFile 
 			// 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 @@ func FileMigration(id, upFile, downFile 
 	}
 	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
+}