github.com/Goboolean/common@v0.0.0-20231130153141-cb54596b217d/pkg/rdbms/transaction_test.go (about) 1 package rdbms_test 2 3 import ( 4 "context" 5 "testing" 6 "database/sql" 7 8 ) 9 10 11 12 13 func Test_Commit(t *testing.T) { 14 15 count, err := queries.CountTestTableEntity(context.Background()) 16 if err != nil { 17 t.Errorf("CountTestTableEntity() failed: %v", err) 18 return 19 } 20 21 tx, err := db.NewTx(context.Background()) 22 if err != nil { 23 t.Errorf("NewTx() failed: %v", err) 24 return 25 } 26 27 q := queries.WithTx(tx.Transaction().(*sql.Tx)) 28 29 if err := q.InsertTestTableEntity(context.Background()); err != nil { 30 t.Errorf("InsertTestTableEntity() failed: %v", err) 31 return 32 } 33 34 if err := tx.Commit(); err != nil { 35 t.Errorf("Commit() failed: %v", err) 36 return 37 } 38 39 updatedCount, err := queries.CountTestTableEntity(context.Background()) 40 if err != nil { 41 t.Errorf("CountTestTableEntity() failed: %v", err) 42 return 43 } 44 45 if updatedCount != count + 1 { 46 t.Errorf("count = %d, updatedCount = %d, Commit() does not works", count, updatedCount) 47 return 48 } 49 } 50 51 52 53 func Test_Rollback(t *testing.T) { 54 55 count, err := queries.CountTestTableEntity(context.Background()) 56 if err != nil { 57 t.Errorf("CountTestTableEntity() failed: %v", err) 58 return 59 } 60 61 tx, err := db.NewTx(context.Background()) 62 if err != nil { 63 t.Errorf("NewTx() failed: %v", err) 64 return 65 } 66 67 q := queries.WithTx(tx.Transaction().(*sql.Tx)) 68 69 if err := q.InsertTestTableEntity(context.Background()); err != nil { 70 t.Errorf("InsertTestTableEntity() failed: %v", err) 71 return 72 } 73 74 if err := tx.Rollback(); err != nil { 75 t.Errorf("Rollback() failed: %v", err) 76 return 77 } 78 79 updatedCount, err := queries.CountTestTableEntity(context.Background()) 80 if err != nil { 81 t.Errorf("CountTestTableEntity() failed: %v", err) 82 return 83 } 84 85 if updatedCount != count { 86 t.Errorf("count = %d, updatedCount = %d, Rollback() does not works", count, updatedCount) 87 return 88 } 89 }