| 11 | ) |
| 12 | |
| 13 | func 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 { |