|
8 | 8 | "context"
|
9 | 9 | "database/sql"
|
10 | 10 | "database/sql/driver"
|
| 11 | + "errors" |
11 | 12 | "fmt"
|
12 | 13 | "os"
|
13 | 14 | "path/filepath"
|
@@ -469,6 +470,65 @@ func TestTransaction(t *testing.T) {
|
469 | 470 | }
|
470 | 471 | }
|
471 | 472 |
|
| 473 | +func TestTransactionWithBlock(t *testing.T) { |
| 474 | + // rollback |
| 475 | + err := DB.Transaction(func(tx *gorm.DB) error { |
| 476 | + u := User{Name: "transcation"} |
| 477 | + if err := tx.Save(&u).Error; err != nil { |
| 478 | + t.Errorf("No error should raise") |
| 479 | + } |
| 480 | + |
| 481 | + if err := tx.First(&User{}, "name = ?", "transcation").Error; err != nil { |
| 482 | + t.Errorf("Should find saved record") |
| 483 | + } |
| 484 | + |
| 485 | + return errors.New("the error message") |
| 486 | + }) |
| 487 | + |
| 488 | + if err.Error() != "the error message" { |
| 489 | + t.Errorf("Transaction return error will equal the block returns error") |
| 490 | + } |
| 491 | + |
| 492 | + if err := DB.First(&User{}, "name = ?", "transcation").Error; err == nil { |
| 493 | + t.Errorf("Should not find record after rollback") |
| 494 | + } |
| 495 | + |
| 496 | + // commit |
| 497 | + DB.Transaction(func(tx *gorm.DB) error { |
| 498 | + u2 := User{Name: "transcation-2"} |
| 499 | + if err := tx.Save(&u2).Error; err != nil { |
| 500 | + t.Errorf("No error should raise") |
| 501 | + } |
| 502 | + |
| 503 | + if err := tx.First(&User{}, "name = ?", "transcation-2").Error; err != nil { |
| 504 | + t.Errorf("Should find saved record") |
| 505 | + } |
| 506 | + return nil |
| 507 | + }) |
| 508 | + |
| 509 | + if err := DB.First(&User{}, "name = ?", "transcation-2").Error; err != nil { |
| 510 | + t.Errorf("Should be able to find committed record") |
| 511 | + } |
| 512 | + |
| 513 | + // panic will rollback |
| 514 | + DB.Transaction(func(tx *gorm.DB) error { |
| 515 | + u3 := User{Name: "transcation-3"} |
| 516 | + if err := tx.Save(&u3).Error; err != nil { |
| 517 | + t.Errorf("No error should raise") |
| 518 | + } |
| 519 | + |
| 520 | + if err := tx.First(&User{}, "name = ?", "transcation-3").Error; err != nil { |
| 521 | + t.Errorf("Should find saved record") |
| 522 | + } |
| 523 | + |
| 524 | + panic("force panic") |
| 525 | + }) |
| 526 | + |
| 527 | + if err := DB.First(&User{}, "name = ?", "transcation").Error; err == nil { |
| 528 | + t.Errorf("Should not find record after panic rollback") |
| 529 | + } |
| 530 | +} |
| 531 | + |
472 | 532 | func TestTransaction_NoErrorOnRollbackAfterCommit(t *testing.T) {
|
473 | 533 | tx := DB.Begin()
|
474 | 534 | u := User{Name: "transcation"}
|
|
0 commit comments