英文:
Writing a goose go migration with gorm
问题
默认的goose迁移会准备一个函数,提供一个*sql.Tx
:
> 之所以提供一个事务,而不是直接提供DB实例,是因为goose还需要在同一个事务中记录模式版本。为了确保数据库的完整性,每个迁移都应该作为一个单独的事务运行,这是一个好的实践。
我想使用gorm迁移来编写我的迁移,但我不确定如何使用给定的事务来实现这个目的。这里有一个例子:
func Up_20151230135812(txn *sql.Tx) {
txn.CreateTable(&User{})
}
构建时给出了txn.CreateTable undefined (type *sql.Tx has no field or method CreateTable)
的错误,这是预期的。我该如何获取事务以便与gorm一起使用?
英文:
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?
答案1
得分: 1
鹅对gorm及其函数(CreateTable等)一无所知。
请查看goose / lib / goose / migration_go.go的末尾。
goose只是创建了一个事务。
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)
}
并且使用了来自“database/sql”包的sql.Tx。
但是你可以使用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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论