Xormigrate

Supported databases
It supports any of the databases Xorm supports:
Installing
go get -u src.techknowlogick.com/xormigrate
Usage
package main
import (
"log"
"src.techknowlogick.com/xormigrate"
"xorm.io/xorm"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := xorm.NewEngine("sqlite3", "mydb.sqlite3")
if err != nil {
log.Fatal(err)
}
m := xormigrate.New(db, []*xormigrate.Migration{
{
ID: "201608301400",
Description: "Create the Person table",
Migrate: func(tx *xorm.Engine) error {
type Person struct {
Name string
}
return tx.Sync2(&Person{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(&Person{})
},
},
{
ID: "201608301415",
Migrate: func(tx *xorm.Engine) error {
type Person struct {
Age int
}
return tx.Sync2(&Person{})
},
Rollback: func(tx *xorm.Engine) error {
_, err = tx.Exec("ALTER TABLE person DROP COLUMN age")
if err != nil {
return fmt.Errorf("Drop column failed: %v", err)
}
return nil
},
},
{
ID: "201608301430",
Migrate: func(tx *xorm.Engine) error {
type Pet struct {
Name string
PersonID int
}
return tx.Sync2(&Pet{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(&Pet{})
},
},
})
if err = m.Migrate(); err != nil {
log.Fatalf("Could not migrate: %v", err)
}
log.Printf("Migration did run successfully")
}
Having a separated function for initializing the schema
If you have a lot of migrations, it can be a pain to run all them, as example,
when you are deploying a new instance of the app, in a clean database.
To prevent this, you can set a function that will run if no migration was run
before (in a new clean database). Remember to create everything here, all tables,
foreign keys and what more you need in your app.
type Person struct {
Name string
Age int
}
type Pet struct {
Name string
PersonID int
}
m := xormigrate.New(db, []*xormigrate.Migration{
})
m.InitSchema(func(tx *xorm.Engine) error {
err := tx.sync2(
&Person{},
&Pet{},
)
if err != nil {
return err
}
return nil
})
Adding migration descriptions to your logging
Xormigrate's logger defaults to stdout, but it can be changed to suit your needs.
m := xormigrate.New(db, []*xormigrate.Migration{
})
m.NilLogger()
m.DefaultLogger()
m.NewLogger(os.Stdout)
Credits