A default goose go migration prepares a function providing an *sql.Tx
:
A transaction is provided, rather than the DB instance directly, since goose also needs to record the schema version within the same transaction. Each migration should run as a single transaction to ensure DB integrity, so it's good practice anyway.
I would like to write my migration using gorm migrations, but I’m not sure how to use the given transaction to that purpose. Here’s an example:
func Up_20151230135812(txn *sql.Tx) {
txn.CreateTable(&User{})
}
The build gives me txn.CreateTable undefined (type *sql.Tx has no field or method CreateTable)
as expected. How can I grab the transaction for use with gorm?
goose know nothing about gorm and his functions (CreateTable etc.)
Look at the end of goose / lib / goose / migration_go.go
goose just create transaction
db, err := goose.OpenDBFromDBConf(&conf)
if err != nil {
log.Fatal("failed to open DB:", err)
}
defer db.Close()
txn, err := db.Begin()
if err != nil {
log.Fatal("db.Begin:", err)
}
{{ .Func }}(txn)
err = goose.FinalizeMigration(&conf, txn, {{ .Direction }}, {{ .Version }})
if err != nil {
log.Fatal("Commit() failed:", err)
}
and use sql.Tx from "database/sql" package
but you can implement custom wrapper using gorm ;-)