Created
April 12, 2016 20:02
-
-
Save ericchiang/5f251a1e28bd21375b9c569e5f474624 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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