Description
When I used gorm to start a transaction to update the database, Panic occurred. The specific reasons are analyzed as follows: The following code section is located at lines 446 to 457 of gorm v1.20.5/finisher_api.go.
tx := db.Begin(opts...)
defer func() {
// Make sure to rollback when panic, Block error or Commit error
if panicked || err != nil {
tx.Rollback()
}
}()
err = fc(tx)
if err == nil {
err = tx.Commit().Error
}
In the function db.Begin(opts...), the tx.Statement.ConnPool is actually nil due to the BeginTx method execution failure. So that during the subsequent processing of fc(tx), the function database/sql.(*Tx).QueryContext will trigger the panic.
The version of gorm and golang I uese as follow: gorm.io/driver/mysql v1.0.3 gorm.io/gorm v1.20.5 go version go1.18.3 linux/amd64
Stack Information
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0xb21e32]
goroutine 733380 [running]:
database/sql.(*Tx).grabConn(0x0, {0x128ca48, 0xc000040088})
/opt/go-1.18.3/src/database/sql/sql.go:2231 +0x52
database/sql.(*Tx).QueryContext(0x0, {0x128ca48, 0xc000040088}, {0xc0020341a0, 0x6e}, {0xc003ad51f0, 0x1, 0x1})
/opt/go-1.18.3/src/database/sql/sql.go:2505 +0x57
gorm.io/gorm/callbacks.Query(0xc00387b800)
/home/tt/go/pkg/mod/gorm.io/gorm@v1.20.5/callbacks/query.go:27 +0x113
gorm.io/gorm.(*processor).Execute(0xc00022fa00, 0xc00387b800)
/home/tt/go/pkg/mod/gorm.io/gorm@v1.20.5/callbacks.go:105 +0x31e
gorm.io/gorm.(*DB).First(0xc0043d0b10?, {0xeb51e0?, 0xc0027d96c0}, {0xc00327f700, 0x2, 0x2})
/home/tt/go/pkg/mod/gorm.io/gorm@v1.20.5/finisher_api.go:75 +0x1d9
sample-server/pkg/repo/task.(*TaskRepository).Update(0x100d160?, {0x128cab8, 0xc00267bd40}, 0x127d6a0?, {0xc0043d0b10, 0x26}, 0xc0001f4a80, {0xc0003aa540, 0x6})
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 30 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 ✨