GORM Playground Link
https://github.com/go-gorm/playground/pull/477
Description
Within a Hook I would like to do some deletion within a transaction.
type User struct {
gorm.Model
}
type Account struct {
ID uint `gorm:"primarykey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt soft_delete.DeletedAt `gorm:"index"`
UserID sql.NullInt64
}
func (user *User) BeforeDelete(tx *gorm.DB) error {
account := Account{UserID: sql.NullInt64{Int64: int64(user.ID), Valid: true}}
DB.Find(&account)
return tx.Transaction(func(tx2 *gorm.DB) error {
return tx2.Delete(&account).Error
})
}
I would expect this code to work, however it panics.
The cause of the issue seem to be that the transaction create a session with NewDB = false instead of true in finisher_api.go:593
In my example, this cause the code to panic because in the transaction, the statement refer to the table user when deleting the account.
So it uses the StatementModifier of user instead of the one of account.
As account uses soft_delete.DeletedAt and user use gorm.DeletedAt, gorm tries to set a time in account's DeletedAt which is a uint and panic.