MCPcopy
hub / github.com/go-gorm/gorm / TestTransaction

Function TestTransaction

tests/transaction_test.go:13–74  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

11)
12
13func TestTransaction(t *testing.T) {
14 tx := DB.Begin()
15 user := *GetUser("transaction", Config{})
16
17 if err := tx.Save(&user).Error; err != nil {
18 t.Fatalf("No error should raise, but got %v", err)
19 }
20
21 if err := tx.First(&User{}, "name = ?", "transaction").Error; err != nil {
22 t.Fatalf("Should find saved record, but got %v", err)
23 }
24
25 user1 := *GetUser("transaction1-1", Config{})
26
27 if err := tx.Save(&user1).Error; err != nil {
28 t.Fatalf("No error should raise, but got %v", err)
29 }
30
31 if err := tx.First(&User{}, "name = ?", user1.Name).Error; err != nil {
32 t.Fatalf("Should find saved record, but got %v", err)
33 }
34
35 if sqlTx, ok := tx.Statement.ConnPool.(gorm.TxCommitter); !ok || sqlTx == nil {
36 t.Fatalf("Should return the underlying sql.Tx")
37 }
38
39 tx.Rollback()
40
41 if err := DB.First(&User{}, "name = ?", "transaction").Error; err == nil {
42 t.Fatalf("Should not find record after rollback, but got %v", err)
43 }
44
45 txDB := DB.Where("fake_name = ?", "fake_name")
46 tx2 := txDB.Session(&gorm.Session{NewDB: true}).Begin()
47 user2 := *GetUser("transaction-2", Config{})
48 if err := tx2.Save(&user2).Error; err != nil {
49 t.Fatalf("No error should raise, but got %v", err)
50 }
51
52 if err := tx2.First(&User{}, "name = ?", "transaction-2").Error; err != nil {
53 t.Fatalf("Should find saved record, but got %v", err)
54 }
55
56 tx2.Commit()
57
58 if err := DB.First(&User{}, "name = ?", "transaction-2").Error; err != nil {
59 t.Fatalf("Should be able to find committed record, but got %v", err)
60 }
61
62 t.Run("this is test nested transaction and prepareStmt coexist case", func(t *testing.T) {
63 // enable prepare statement
64 tx3 := DB.Session(&gorm.Session{PrepareStmt: true})
65 if err := tx3.Transaction(func(tx4 *gorm.DB) error {
66 // nested transaction
67 return tx4.Transaction(func(tx5 *gorm.DB) error {
68 return tx5.First(&User{}, "name = ?", "transaction-2").Error
69 })
70 }); err != nil {

Callers

nothing calls this directly

Calls 9

GetUserFunction · 0.85
BeginMethod · 0.80
SaveMethod · 0.80
SessionMethod · 0.80
TransactionMethod · 0.80
FirstMethod · 0.65
RollbackMethod · 0.65
WhereMethod · 0.65
CommitMethod · 0.65

Tested by

no test coverage detected