github.com/mpontillo/pop@v4.13.1+incompatible/migration_box.go (about) 1 package pop 2 3 import ( 4 "github.com/gobuffalo/packd" 5 "github.com/pkg/errors" 6 ) 7 8 // MigrationBox is a wrapper around packr.Box and Migrator. 9 // This will allow you to run migrations from a packed box 10 // inside of a compiled binary. 11 type MigrationBox struct { 12 Migrator 13 Box packd.Walkable 14 } 15 16 // NewMigrationBox from a packr.Box and a Connection. 17 func NewMigrationBox(box packd.Walkable, c *Connection) (MigrationBox, error) { 18 fm := MigrationBox{ 19 Migrator: NewMigrator(c), 20 Box: box, 21 } 22 23 runner := func(f packd.File) func(mf Migration, tx *Connection) error { 24 return func(mf Migration, tx *Connection) error { 25 content, err := MigrationContent(mf, tx, f, true) 26 if err != nil { 27 return errors.Wrapf(err, "error processing %s", mf.Path) 28 } 29 if content == "" { 30 return nil 31 } 32 err = tx.RawQuery(content).Exec() 33 if err != nil { 34 return errors.Wrapf(err, "error executing %s, sql: %s", mf.Path, content) 35 } 36 return nil 37 } 38 } 39 40 err := fm.findMigrations(runner) 41 if err != nil { 42 return fm, err 43 } 44 45 return fm, nil 46 } 47 48 func (fm *MigrationBox) findMigrations(runner func(f packd.File) func(mf Migration, tx *Connection) error) error { 49 return fm.Box.Walk(func(p string, f packd.File) error { 50 info, err := f.FileInfo() 51 if err != nil { 52 return err 53 } 54 match, err := ParseMigrationFilename(info.Name()) 55 if err != nil { 56 return err 57 } 58 if match == nil { 59 return nil 60 } 61 mf := Migration{ 62 Path: p, 63 Version: match.Version, 64 Name: match.Name, 65 DBType: match.DBType, 66 Direction: match.Direction, 67 Type: match.Type, 68 Runner: runner(f), 69 } 70 fm.Migrations[mf.Direction] = append(fm.Migrations[mf.Direction], mf) 71 return nil 72 }) 73 }