db.CommonDB() no longer works in gorm v2.
if tx, ok := DB.CommonDB().(*sql.Tx) ; ok { ... }
can't work.
Any alternative way to get the underlying sql.Tx instance?
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 2 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨
Comment From: li-jin-gou
@liush5 hello, you can look this doc https://gorm.io/zh_CN/docs/generic_interface.html
Comment From: liush5-zz
@liush5 hello, you can look this doc https://gorm.io/zh_CN/docs/generic_interface.html
@li-jin-gou thanks,but i still have question
for example:
type Payment struct {
UserId int64
Amount int64
}
func SendPayment(gdb *gorm.DB, user_id, amount int64) error {
tx := gdb.Begin()
defer tx.Rollback()
// question: gorm.Db how to get sql.Tx ?
b, err := GetBalance(??, user_id)
if err != nil {
return err
}
if b < amount {
return errors.New("insufficient funds")
}
p := Payment{user_id, amount}
gdb.Save(p)
return gdb.Commit().Error
}
func GetBalance(tx *sql.Tx, userId int64) int64 {
return 20
}
question: gorm.DB how to get sql.Tx Instance ?
Comment From: li-jin-gou
@liush5 hello, you can look this doc https://gorm.io/zh_CN/docs/generic_interface.html
@li-jin-gou thanks,but i still have question
for example:
```go type Payment struct { UserId int64 Amount int64 }
func SendPayment(gdb *gorm.DB, user_id, amount int64) error { tx := gdb.Begin() defer tx.Rollback()
// question: gorm.Db how to get sql.Tx ? b, err := GetBalance(??, user_id) if err != nil { return err } if b < amount { return errors.New("insufficient funds") }
p := Payment{user_id, amount} gdb.Save(p)
return gdb.Commit().Error }
func GetBalance(tx *sql.Tx, userId int64) int64 { return 20 } ```
question: gorm.DB how to get sql.Tx Instance ?
txDB := DB.Begin()
tx,ok := txDB.Statement.ConnPool.(*sql.Tx)
if !ok{
// deal type assert error
}