How to maintain migration and schema in xorm?
type Version struct {
ID int64
Name string
}
engine.Sync(new(Version))
This will only sync the xorm model with database. But I need data migrations in some cases. Is there any option like rails schema.rb and migrations?
I know it's been a while since the question asked but I've recently had to research over scarce information regarding the issue so I've decided to elaborate on @Alex Yu comment and post my findings.
Indeed in order to perform a migration, we need xorm/migrate package.
Consider initial migration which adds 2 tables.
var migrations = []*migrate.Migration{
{
ID: "201608301400",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync2(&Person{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(&Person{})
},
},
{
ID: "201608301430",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync2(&Pet{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(&Person{})
},
},
}
We can consume it as follows
m := migrate.New(engine, &migrate.Options{
TableName: "migrations",
IDColumnName: "id",
}, migrations)
err = m.Migrate()
Now let's imagine the scenario when we add a field to a table Person. Contrary to approach that one might find as default when we explicitly tell engine to add column, here we just sync our db once again.
Also upon my research I have not found a way to explicitly drop column on rollback so I suggest using raw SQL.
Now migration will look as below. Note that your SQL may vary.
var migrations = []*migrate.Migration{
{
ID: "201608301400",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync2(&Person{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(&Person{})
},
},
{
ID: "201608301430",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync2(&Pet{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(&Person{})
},
},
{
ID: "201608301460",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync2(&Person{})
},
Rollback: func(tx *xorm.Engine) error {
_, e := tx.QueryString("ALTER TABLE dbo.person DROP COLUMN IF EXISTS your_new_column")
return e
},
},
}
Xorm keeps track of migrations that are alsready executed, so only the last one will be run.