Debian Codegraph @

tests/prepared_stmt_test.go

raw
1 package tests_test
2
3 import (
4 "context"
5 "errors"
6 "sync"
7 "testing"
8 "time"
9
10 "gorm.io/gorm"
11 . "gorm.io/gorm/utils/tests"
12 )
13
14 func TestPreparedStmt(t *testing.T) {
15 tx := DB.Session(&gorm.Session{PrepareStmt: true})
16
17 if _, ok := tx.ConnPool.(*gorm.PreparedStmtDB); !ok {
18 t.Fatalf("should assign PreparedStatement Manager back to database when using PrepareStmt mode")
19 }
20
21 ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
22 defer cancel()
23 txCtx := tx.WithContext(ctx)
24
25 user := *GetUser("prepared_stmt", Config{})
26
27 txCtx.Create(&user)
28
29 var result1 User
30 if err := txCtx.Find(&result1, user.ID).Error; err != nil {
31 t.Fatalf("no error should happen but got %v", err)
32 }
33
34 time.Sleep(time.Second)
35
36 var result2 User
37 if err := tx.Find(&result2, user.ID).Error; err != nil {
38 t.Fatalf("no error should happen but got %v", err)
39 }
40
41 user2 := *GetUser("prepared_stmt2", Config{})
42 if err := txCtx.Create(&user2).Error; err == nil {
43 t.Fatalf("should failed to create with timeout context")
44 }
45
46 if err := tx.Create(&user2).Error; err != nil {
47 t.Fatalf("failed to create, got error %v", err)
48 }
49
50 var result3 User
51 if err := tx.Find(&result3, user2.ID).Error; err != nil {
52 t.Fatalf("no error should happen but got %v", err)
53 }
54 }
55
56 func TestPreparedStmtFromTransaction(t *testing.T) {
57 db := DB.Session(&gorm.Session{PrepareStmt: true, SkipDefaultTransaction: true})
58
59 tx := db.Begin()
60 defer func() {
61 if r := recover(); r != nil {
62 tx.Rollback()
63 }
64 }()
65 if err := tx.Error; err != nil {
66 t.Errorf("Failed to start transaction, got error %v\n", err)
67 }
68
69 if err := tx.Where("name=?", "zzjin").Delete(&User{}).Error; err != nil {
70 tx.Rollback()
71 t.Errorf("Failed to run one transaction, got error %v\n", err)
72 }
73
74 if err := tx.Create(&User{Name: "zzjin"}).Error; err != nil {
75 tx.Rollback()
76 t.Errorf("Failed to run one transaction, got error %v\n", err)
77 }
78
79 if err := tx.Commit().Error; err != nil {
80 t.Errorf("Failed to commit transaction, got error %v\n", err)
81 }
82
83 if result := db.Where("name=?", "zzjin").Delete(&User{}); result.Error != nil || result.RowsAffected != 1 {
84 t.Fatalf("Failed, got error: %v, rows affected: %v", result.Error, result.RowsAffected)
85 }
86
87 tx2 := db.Begin()
88 if result := tx2.Where("name=?", "zzjin").Delete(&User{}); result.Error != nil || result.RowsAffected != 0 {
89 t.Fatalf("Failed, got error: %v, rows affected: %v", result.Error, result.RowsAffected)
90 }
91 tx2.Commit()
92 }
93
94 func TestPreparedStmtLruFromTransaction(t *testing.T) {
95 db, _ := OpenTestConnection(&gorm.Config{PrepareStmt: true, PrepareStmtMaxSize: 10, PrepareStmtTTL: 20 * time.Second})
96
97 tx := db.Begin()
98 defer func() {
99 if r := recover(); r != nil {
100 tx.Rollback()
101 }
102 }()
103 if err := tx.Error; err != nil {
104 t.Errorf("Failed to start transaction, got error %v\n", err)
105 }
106
107 if err := tx.Where("name=?", "zzjin").Delete(&User{}).Error; err != nil {
108 tx.Rollback()
109 t.Errorf("Failed to run one transaction, got error %v\n", err)
110 }
111
112 if err := tx.Create(&User{Name: "zzjin"}).Error; err != nil {
113 tx.Rollback()
114 t.Errorf("Failed to run one transaction, got error %v\n", err)
115 }
116
117 if err := tx.Commit().Error; err != nil {
118 t.Errorf("Failed to commit transaction, got error %v\n", err)
119 }
120
121 if result := db.Where("name=?", "zzjin").Delete(&User{}); result.Error != nil || result.RowsAffected != 1 {
122 t.Fatalf("Failed, got error: %v, rows affected: %v", result.Error, result.RowsAffected)
123 }
124
125 tx2 := db.Begin()
126 if result := tx2.Where("name=?", "zzjin").Delete(&User{}); result.Error != nil || result.RowsAffected != 0 {
127 t.Fatalf("Failed, got error: %v, rows affected: %v", result.Error, result.RowsAffected)
128 }
129
130 tx2.Commit()
131 // Attempt to convert the connection pool of tx to the *gorm.PreparedStmtDB type.
132 // If the conversion is successful, ok will be true and conn will be the converted object;
133 // otherwise, ok will be false and conn will be nil.
134 conn, ok := tx.ConnPool.(*gorm.PreparedStmtDB)
135 // Get the number of statement keys stored in the PreparedStmtDB.
136 lens := len(conn.Stmts.Keys())
137 // Check if the number of stored statement keys is 0.
138 if lens == 0 {
139 // If the number is 0, it means there are no statements stored in the LRU cache.
140 // The test fails and an error message is output.
141 t.Fatalf("lru should not be empty")
142 }
143 // Wait for 40 seconds to give the statements in the cache enough time to expire.
144 time.Sleep(time.Second * 40)
145 // Assert whether the connection pool of tx is successfully converted to the *gorm.PreparedStmtDB type.
146 AssertEqual(t, ok, true)
147 // Assert whether the number of statement keys stored in the PreparedStmtDB is 0 after 40 seconds.
148 // If it is not 0, it means the statements in the cache have not expired as expected.
149 AssertEqual(t, len(conn.Stmts.Keys()), 0)
150
151 }
152
153 func TestPreparedStmtDeadlock(t *testing.T) {
154 tx, err := OpenTestConnection(&gorm.Config{})
155 AssertEqual(t, err, nil)
156
157 sqlDB, _ := tx.DB()
158 sqlDB.SetMaxOpenConns(1)
159
160 tx = tx.Session(&gorm.Session{PrepareStmt: true})
161
162 wg := sync.WaitGroup{}
163 for i := 0; i < 100; i++ {
164 wg.Add(1)
165 go func() {
166 user := User{Name: "jinzhu"}
167 tx.Create(&user)
168
169 var result User
170 tx.First(&result)
171 wg.Done()
172 }()
173 }
174 wg.Wait()
175
176 conn, ok := tx.ConnPool.(*gorm.PreparedStmtDB)
177 AssertEqual(t, ok, true)
178 AssertEqual(t, len(conn.Stmts.Keys()), 2)
179 for _, stmt := range conn.Stmts.Keys() {
180 if stmt == "" {
181 t.Fatalf("stmt cannot bee nil")
182 }
183 }
184
185 AssertEqual(t, sqlDB.Stats().InUse, 0)
186 }
187
188 func TestPreparedStmtInTransaction(t *testing.T) {
189 user := User{Name: "jinzhu"}
190
191 if err := DB.Transaction(func(tx *gorm.DB) error {
192 tx.Session(&gorm.Session{PrepareStmt: true}).Create(&user)
193 return errors.New("test")
194 }); err == nil {
195 t.Error(err)
196 }
197
198 var result User
199 if err := DB.First(&result, user.ID).Error; err == nil {
200 t.Errorf("Failed, got error: %v", err)
201 }
202 }
203
204 func TestPreparedStmtClose(t *testing.T) {
205 tx := DB.Session(&gorm.Session{PrepareStmt: true})
206
207 user := *GetUser("prepared_stmt_close", Config{})
208 tx = tx.Create(&user)
209
210 pdb, ok := tx.ConnPool.(*gorm.PreparedStmtDB)
211 if !ok {
212 t.Fatalf("should assign PreparedStatement Manager back to database when using PrepareStmt mode")
213 }
214
215 pdb.Mux.Lock()
216 if len(pdb.Stmts.Keys()) == 0 {
217 pdb.Mux.Unlock()
218 t.Fatalf("prepared stmt can not be empty")
219 }
220 pdb.Mux.Unlock()
221
222 pdb.Close()
223 pdb.Mux.Lock()
224 defer pdb.Mux.Unlock()
225 if len(pdb.Stmts.Keys()) != 0 {
226 t.Fatalf("prepared stmt should be empty")
227 }
228 }
229
230 func isUsingClosedConnError(err error) bool {
231 // https://github.com/golang/go/blob/e705a2d16e4ece77e08e80c168382cdb02890f5b/src/database/sql/sql.go#L2717
232 return err.Error() == "sql: statement is closed"
233 }
234
235 // TestPreparedStmtConcurrentClose test calling close and executing SQL concurrently
236 // this test making sure that the gorm would not get a Segmentation Fault, and the only error cause by this is using a closed Stmt
237 func TestPreparedStmtConcurrentClose(t *testing.T) {
238 name := "prepared_stmt_concurrent_close"
239 user := *GetUser(name, Config{})
240 createTx := DB.Session(&gorm.Session{}).Create(&user)
241 if createTx.Error != nil {
242 t.Fatalf("failed to prepare record due to %s, test cannot be continue", createTx.Error)
243 }
244
245 // create a new connection to keep away from other tests
246 tx, err := OpenTestConnection(&gorm.Config{PrepareStmt: true})
247 if err != nil {
248 t.Fatalf("failed to open test connection due to %s", err)
249 }
250 pdb, ok := tx.ConnPool.(*gorm.PreparedStmtDB)
251 if !ok {
252 t.Fatalf("should assign PreparedStatement Manager back to database when using PrepareStmt mode")
253 }
254
255 loopCount := 100
256 var wg sync.WaitGroup
257 var unexpectedError bool
258 writerFinish := make(chan struct{})
259
260 wg.Add(1)
261 go func(id uint) {
262 defer wg.Done()
263 defer close(writerFinish)
264
265 for j := 0; j < loopCount; j++ {
266 var tmp User
267 err := tx.Session(&gorm.Session{}).First(&tmp, id).Error
268 if err == nil || isUsingClosedConnError(err) {
269 continue
270 }
271 t.Errorf("failed to read user of id %d due to %s, there should not be error", id, err)
272 unexpectedError = true
273 break
274 }
275 }(user.ID)
276
277 wg.Add(1)
278 go func() {
279 defer wg.Done()
280 <-writerFinish
281 pdb.Close()
282 }()
283
284 wg.Wait()
285
286 if unexpectedError {
287 t.Fatalf("should is a unexpected error")
288 }
289 }