github.com/Accefy/pop@v0.0.0-20230428174248-e9f677eab5b9/migration_info.go (about) 1 package pop 2 3 import "fmt" 4 5 // Migration handles the data for a given database migration 6 type Migration struct { 7 // Path to the migration (./migrations/123_create_widgets.up.sql) 8 Path string 9 // Version of the migration (123) 10 Version string 11 // Name of the migration (create_widgets) 12 Name string 13 // Direction of the migration (up) 14 Direction string 15 // Type of migration (sql) 16 Type string 17 // DB type (all|postgres|mysql...) 18 DBType string 19 // Runner function to run/execute the migration 20 Runner func(Migration, *Connection) error 21 } 22 23 // Run the migration. Returns an error if there is 24 // no mf.Runner defined. 25 func (mf Migration) Run(c *Connection) error { 26 if mf.Runner == nil { 27 return fmt.Errorf("no runner defined for %s", mf.Path) 28 } 29 return mf.Runner(mf, c) 30 } 31 32 // Migrations is a collection of Migration 33 type Migrations []Migration 34 35 func (mfs Migrations) Len() int { 36 return len(mfs) 37 } 38 39 func (mfs Migrations) Swap(i, j int) { 40 mfs[i], mfs[j] = mfs[j], mfs[i] 41 } 42 43 func (mfs *Migrations) Filter(f func(mf Migration) bool) { 44 vsf := make(Migrations, 0) 45 for _, v := range *mfs { 46 if f(v) { 47 vsf = append(vsf, v) 48 } 49 } 50 *mfs = vsf 51 } 52 53 type ( 54 UpMigrations struct { 55 Migrations 56 } 57 DownMigrations struct { 58 Migrations 59 } 60 ) 61 62 func (mfs UpMigrations) Less(i, j int) bool { 63 if mfs.Migrations[i].Version == mfs.Migrations[j].Version { 64 // force "all" to the back 65 return mfs.Migrations[i].DBType != "all" 66 } 67 return mfs.Migrations[i].Version < mfs.Migrations[j].Version 68 } 69 70 func (mfs DownMigrations) Less(i, j int) bool { 71 if mfs.Migrations[i].Version == mfs.Migrations[j].Version { 72 // force "all" to the back 73 return mfs.Migrations[i].DBType != "all" 74 } 75 return mfs.Migrations[i].Version > mfs.Migrations[j].Version 76 }