目录

golang jinzhu/gorm no valid transactions

gorm no valid transactions

现象

poc:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main

import (
	"fmt"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)

var db *gorm.DB

// A is just a demo table.
type A struct{ Val string }

func init() {
	var err error
	db, err = gorm.Open("postgres", "postgres://postgres:postgres@localhost?sslmode=disable")
	if err != nil {
		panic(err)
	}
	db.LogMode(true)
}

func main() {
	panicOnDBErr(db.DropTableIfExists(&A{}))
	panicOnDBErr(db.AutoMigrate(&A{}))

	panicOnDBErr(db.Begin())

	panicOnDBErr(db.Create(&A{"test"}))

	panicOnDBErr(db.Rollback()) // panic here

	var list []A
	panicOnDBErr(db.Find(&list))

	fmt.Println(&list)
}

func panicOnDBErr(db *gorm.DB) {
	panicOnErr(db.Error)
}

func panicOnErr(err error) {
	if err != nil {
		panic(err)
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(main.go:26) 
[2017-12-02 14:30:56]  [49.42ms]  DROP TABLE "as"  
[0 rows affected or returned ] 

(main.go:27) 
[2017-12-02 14:30:56]  [40.77ms]  CREATE TABLE "as" ("val" text )   
[0 rows affected or returned ] 

(main.go:31) 
[2017-12-02 14:30:56]  [0.51ms]  INSERT INTO "as" ("val") VALUES ('test') RETURNING "as".*  
[1 rows affected or returned ] 

(main.go:33) 
[2017-12-02 14:30:56]  no valid transaction 
panic: no valid transaction

goroutine 1 [running]:
main.panicOnErr(0x850c20, 0xc4201324e0)
	main.go:47 +0x4a
main.panicOnDBErr(0xc420180000)
	main.go:42 +0x38
main.main()
	main.go:33 +0x1a8
exit status 2

问题出现原因及解决方法

问题原因:db.Begin() 会将 db 对象锁定在一个数据库连接中,当 rollback 后,当前数据库连接已经不可用了。

解决方法:db.Begin() 之前,clone 一个 db 示例,用 clone 出的 newDB 实例执行 newDB.Begin(), 保证 db 变量中的状态始终是状态健康的.

references