Skip to content

Instantly share code, notes, and snippets.

@ericchiang
Created April 12, 2016 20:02
Show Gist options
  • Select an option

  • Save ericchiang/5f251a1e28bd21375b9c569e5f474624 to your computer and use it in GitHub Desktop.

Select an option

Save ericchiang/5f251a1e28bd21375b9c569e5f474624 to your computer and use it in GitHub Desktop.
package migrate
type Migration struct {
// Pre and Post are commands to execute before and after a migration.
//
// If nil, these fields are ignored.
Pre func(tx *sql.Tx) error
Post func(tx *sql.Tx) error
// Migration is a list of SQL commands to run.
Migration []string
}
func Migrate(db *sql.DB, migrations ...Migration) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// ... Determine what migration needs to be maded based on some table in the DB.
for _, migration := range migrations {
if migration.Pre != nil {
if err := migration.Pre(tx); err != nil {
return err
}
}
// do migration
if migration.Post != nil {
if err := migration.Post(tx); err != nil {
return err
}
}
}
return tx.Commit()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment