Debian Codegraph @

query_test.go

raw symbols SCIP
1 // Copyright 2016 Qiang Xue. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package dbx
6
7 import (
8 ss "database/sql"
9 "encoding/json"
10 "errors"
11 "testing"
12 "time"
13
14 "github.com/stretchr/testify/assert"
15 )
16
17 type City struct {
18 ID int
19 Name string
20 }
21
22 func TestNewQuery(t *testing.T) {
23 db := getDB()
24 sql := "SELECT * FROM users WHERE id={:id}"
25 q := NewQuery(db, db.sqlDB, sql)
26 assert.Equal(t, q.SQL(), sql, "q.SQL()")
27 assert.Equal(t, q.rawSQL, "SELECT * FROM users WHERE id=?", "q.RawSQL()")
28
29 assert.Equal(t, len(q.Params()), 0, "len(q.Params())@1")
30 q.Bind(Params{"id": 1})
31 assert.Equal(t, len(q.Params()), 1, "len(q.Params())@2")
32 }
33
34 func TestQuery_Execute(t *testing.T) {
35 db := getPreparedDB()
36 defer db.Close()
37
38 result, err := db.NewQuery("INSERT INTO item (name) VALUES ('test')").Execute()
39 if assert.Nil(t, err) {
40 rows, _ := result.RowsAffected()
41 assert.Equal(t, rows, int64(1), "Result.RowsAffected()")
42 lastID, _ := result.LastInsertId()
43 assert.Equal(t, lastID, int64(6), "Result.LastInsertId()")
44 }
45 }
46
47 type Customer struct {
48 scanned bool
49
50 ID int
51 Email string
52 Status int
53 Name string
54 Address ss.NullString
55 }
56
57 func (m Customer) TableName() string {
58 return "customer"
59 }
60
61 func (m *Customer) PostScan() error {
62 m.scanned = true
63 return nil
64 }
65
66 type CustomerPtr struct {
67 ID *int `db:"pk"`
68 Email *string
69 Status *int
70 Name string
71 Address *string
72 }
73
74 func (m CustomerPtr) TableName() string {
75 return "customer"
76 }
77
78 type CustomerNull struct {
79 ID ss.NullInt64 `db:"pk,id"`
80 Email ss.NullString
81 Status *ss.NullInt64
82 Name string
83 Address ss.NullString
84 }
85
86 func (m CustomerNull) TableName() string {
87 return "customer"
88 }
89
90 type CustomerEmbedded struct {
91 Id int
92 Email *string
93 InnerCustomer
94 }
95
96 func (m CustomerEmbedded) TableName() string {
97 return "customer"
98 }
99
100 type CustomerEmbedded2 struct {
101 ID int
102 Email *string
103 Inner InnerCustomer
104 }
105
106 type InnerCustomer struct {
107 Status ss.NullInt64
108 Name *string
109 Address ss.NullString
110 }
111
112 func TestQuery_Rows(t *testing.T) {
113 db := getPreparedDB()
114 defer db.Close()
115
116 var (
117 sql string
118 err error
119 )
120
121 // Query.All()
122 var customers []Customer
123 sql = `SELECT * FROM customer ORDER BY id`
124 err = db.NewQuery(sql).All(&customers)
125 if assert.Nil(t, err) {
126 assert.Equal(t, len(customers), 3, "len(customers)")
127 assert.Equal(t, customers[2].ID, 3, "customers[2].ID")
128 assert.Equal(t, customers[2].Email, `[email protected]`, "customers[2].Email")
129 assert.Equal(t, customers[2].Status, 2, "customers[2].Status")
130 assert.Equal(t, customers[0].scanned, true, "customers[0].scanned")
131 assert.Equal(t, customers[1].scanned, true, "customers[1].scanned")
132 assert.Equal(t, customers[2].scanned, true, "customers[2].scanned")
133 }
134
135 // Query.All() with slice of pointers
136 var customersPtrSlice []*Customer
137 sql = `SELECT * FROM customer ORDER BY id`
138 err = db.NewQuery(sql).All(&customersPtrSlice)
139 if assert.Nil(t, err) {
140 assert.Equal(t, len(customersPtrSlice), 3, "len(customersPtrSlice)")
141 assert.Equal(t, customersPtrSlice[2].ID, 3, "customersPtrSlice[2].ID")
142 assert.Equal(t, customersPtrSlice[2].Email, `[email protected]`, "customersPtrSlice[2].Email")
143 assert.Equal(t, customersPtrSlice[2].Status, 2, "customersPtrSlice[2].Status")
144 assert.Equal(t, customersPtrSlice[0].scanned, true, "customersPtrSlice[0].scanned")
145 assert.Equal(t, customersPtrSlice[1].scanned, true, "customersPtrSlice[1].scanned")
146 assert.Equal(t, customersPtrSlice[2].scanned, true, "customersPtrSlice[2].scanned")
147 }
148
149 var customers2 []NullStringMap
150 err = db.NewQuery(sql).All(&customers2)
151 if assert.Nil(t, err) {
152 assert.Equal(t, len(customers2), 3, "len(customers2)")
153 assert.Equal(t, customers2[1]["id"].String, "2", "customers2[1][id]")
154 assert.Equal(t, customers2[1]["email"].String, `[email protected]`, "customers2[1][email]")
155 assert.Equal(t, customers2[1]["status"].String, "1", "customers2[1][status]")
156 }
157 err = db.NewQuery(sql).All(customers)
158 assert.NotNil(t, err)
159
160 var customers3 []string
161 err = db.NewQuery(sql).All(&customers3)
162 assert.NotNil(t, err)
163
164 var customers4 string
165 err = db.NewQuery(sql).All(&customers4)
166 assert.NotNil(t, err)
167
168 var customers5 []Customer
169 err = db.NewQuery(`SELECT * FROM customer WHERE id=999`).All(&customers5)
170 if assert.Nil(t, err) {
171 assert.NotNil(t, customers5)
172 assert.Zero(t, len(customers5))
173 }
174
175 // One
176 var customer Customer
177 sql = `SELECT * FROM customer WHERE id={:id}`
178 err = db.NewQuery(sql).Bind(Params{"id": 2}).One(&customer)
179 if assert.Nil(t, err) {
180 assert.Equal(t, customer.ID, 2, "customer.ID")
181 assert.Equal(t, customer.Email, `[email protected]`, "customer.Email")
182 assert.Equal(t, customer.Status, 1, "customer.Status")
183 }
184
185 var customerPtr2 CustomerPtr
186 sql = `SELECT id, email, address FROM customer WHERE id=2`
187 rows2, err := db.sqlDB.Query(sql)
188 defer rows2.Close()
189 assert.Nil(t, err)
190 rows2.Next()
191 err = rows2.Scan(&customerPtr2.ID, &customerPtr2.Email, &customerPtr2.Address)
192 if assert.Nil(t, err) {
193 assert.Equal(t, *customerPtr2.ID, 2, "customer.ID")
194 assert.Equal(t, *customerPtr2.Email, `[email protected]`)
195 assert.Nil(t, customerPtr2.Address)
196 }
197
198 // struct fields are pointers
199 var customerPtr CustomerPtr
200 sql = `SELECT * FROM customer WHERE id={:id}`
201 err = db.NewQuery(sql).Bind(Params{"id": 2}).One(&customerPtr)
202 if assert.Nil(t, err) {
203 assert.Equal(t, *customerPtr.ID, 2, "customer.ID")
204 assert.Equal(t, *customerPtr.Email, `[email protected]`, "customer.Email")
205 assert.Equal(t, *customerPtr.Status, 1, "customer.Status")
206 }
207
208 // struct fields are null types
209 var customerNull CustomerNull
210 sql = `SELECT * FROM customer WHERE id={:id}`
211 err = db.NewQuery(sql).Bind(Params{"id": 2}).One(&customerNull)
212 if assert.Nil(t, err) {
213 assert.Equal(t, customerNull.ID.Int64, int64(2), "customer.ID")
214 assert.Equal(t, customerNull.Email.String, `[email protected]`, "customer.Email")
215 assert.Equal(t, customerNull.Status.Int64, int64(1), "customer.Status")
216 }
217
218 // embedded with anonymous struct
219 var customerEmbedded CustomerEmbedded
220 sql = `SELECT * FROM customer WHERE id={:id}`
221 err = db.NewQuery(sql).Bind(Params{"id": 2}).One(&customerEmbedded)
222 if assert.Nil(t, err) {
223 assert.Equal(t, customerEmbedded.Id, 2, "customer.ID")
224 assert.Equal(t, *customerEmbedded.Email, `[email protected]`, "customer.Email")
225 assert.Equal(t, customerEmbedded.Status.Int64, int64(1), "customer.Status")
226 }
227
228 // embedded with named struct
229 var customerEmbedded2 CustomerEmbedded2
230 sql = `SELECT id, email, status as "inner.status" FROM customer WHERE id={:id}`
231 err = db.NewQuery(sql).Bind(Params{"id": 2}).One(&customerEmbedded2)
232 if assert.Nil(t, err) {
233 assert.Equal(t, customerEmbedded2.ID, 2, "customer.ID")
234 assert.Equal(t, *customerEmbedded2.Email, `[email protected]`, "customer.Email")
235 assert.Equal(t, customerEmbedded2.Inner.Status.Int64, int64(1), "customer.Status")
236 }
237
238 customer2 := NullStringMap{}
239 sql = `SELECT * FROM customer WHERE id={:id}`
240 err = db.NewQuery(sql).Bind(Params{"id": 1}).One(customer2)
241 if assert.Nil(t, err) {
242 assert.Equal(t, customer2["id"].String, "1", "customer2[id]")
243 assert.Equal(t, customer2["email"].String, `[email protected]`, "customer2[email]")
244 assert.Equal(t, customer2["status"].String, "1", "customer2[status]")
245 }
246
247 err = db.NewQuery(sql).Bind(Params{"id": 2}).One(customer)
248 assert.NotNil(t, err)
249
250 var customer3 NullStringMap
251 err = db.NewQuery(sql).Bind(Params{"id": 2}).One(customer3)
252 assert.NotNil(t, err)
253
254 err = db.NewQuery(sql).Bind(Params{"id": 1}).One(&customer3)
255 if assert.Nil(t, err) {
256 assert.Equal(t, customer3["id"].String, "1", "customer3[id]")
257 }
258
259 // Rows
260 sql = `SELECT * FROM customer ORDER BY id DESC`
261 rows, err := db.NewQuery(sql).Rows()
262 if assert.Nil(t, err) {
263 s := ""
264 for rows.Next() {
265 rows.ScanStruct(&customer)
266 s += customer.Email + ","
267 }
268 assert.Equal(t, s, "[email protected],[email protected],[email protected],", "Rows().Next()")
269 }
270
271 // FieldMapper
272 var a struct {
273 MyID string `db:"id"`
274 name string
275 }
276 sql = `SELECT * FROM customer WHERE id=2`
277 err = db.NewQuery(sql).One(&a)
278 if assert.Nil(t, err) {
279 assert.Equal(t, a.MyID, "2", "a.MyID")
280 // unexported field is not populated
281 assert.Equal(t, a.name, "", "a.name")
282 }
283
284 // prepared statement
285 sql = `SELECT * FROM customer WHERE id={:id}`
286 q := db.NewQuery(sql).Prepare()
287 q.Bind(Params{"id": 1}).One(&customer)
288 assert.Equal(t, customer.ID, 1, "prepared@1")
289 err = q.Bind(Params{"id": 20}).One(&customer)
290 assert.Equal(t, err, ss.ErrNoRows, "prepared@2")
291 q.Bind(Params{"id": 3}).One(&customer)
292 assert.Equal(t, customer.ID, 3, "prepared@3")
293
294 sql = `SELECT name FROM customer WHERE id={:id}`
295 var name string
296 q = db.NewQuery(sql).Prepare()
297 q.Bind(Params{"id": 1}).Row(&name)
298 assert.Equal(t, name, "user1", "prepared2@1")
299 err = q.Bind(Params{"id": 20}).Row(&name)
300 assert.Equal(t, err, ss.ErrNoRows, "prepared2@2")
301 q.Bind(Params{"id": 3}).Row(&name)
302 assert.Equal(t, name, "user3", "prepared2@3")
303
304 // Query.LastError
305 sql = `SELECT * FROM a`
306 q = db.NewQuery(sql).Prepare()
307 customer.ID = 100
308 err = q.Bind(Params{"id": 1}).One(&customer)
309 assert.NotEqual(t, err, nil, "LastError@0")
310 assert.Equal(t, customer.ID, 100, "LastError@1")
311 assert.Equal(t, q.LastError, nil, "LastError@2")
312
313 // Query.Column
314 sql = `SELECT name, id FROM customer ORDER BY id`
315 var names []string
316 err = db.NewQuery(sql).Column(&names)
317 if assert.Nil(t, err) && assert.Equal(t, 3, len(names)) {
318 assert.Equal(t, "user1", names[0])
319 assert.Equal(t, "user2", names[1])
320 assert.Equal(t, "user3", names[2])
321 }
322 err = db.NewQuery(sql).Column(names)
323 assert.NotNil(t, err)
324 }
325
326 func TestQuery_logSQL(t *testing.T) {
327 db := getDB()
328 q := db.NewQuery("SELECT * FROM users WHERE type={:type} AND id={:id} AND bytes={:bytes}").Bind(Params{
329 "id": 1,
330 "type": "a",
331 "bytes": []byte("test"),
332 })
333 expected := "SELECT * FROM users WHERE type='a' AND id=1 AND bytes=0x74657374"
334 assert.Equal(t, q.logSQL(), expected, "logSQL()")
335 }
336
337 func TestReplacePlaceholders(t *testing.T) {
338 tests := []struct {
339 ID string
340 Placeholders []string
341 Params Params
342 ExpectedParams string
343 HasError bool
344 }{
345 {"t1", nil, nil, "null", false},
346 {"t2", []string{"id", "name"}, Params{"id": 1, "name": "xyz"}, `[1,"xyz"]`, false},
347 {"t3", []string{"id", "name"}, Params{"id": 1}, `null`, true},
348 {"t4", []string{"id", "name"}, Params{"id": 1, "name": "xyz", "age": 30}, `[1,"xyz"]`, false},
349 }
350 for _, test := range tests {
351 params, err := replacePlaceholders(test.Placeholders, test.Params)
352 result, _ := json.Marshal(params)
353 assert.Equal(t, string(result), test.ExpectedParams, "params@"+test.ID)
354 assert.Equal(t, err != nil, test.HasError, "error@"+test.ID)
355 }
356 }
357
358 func TestIssue6(t *testing.T) {
359 db := getPreparedDB()
360 q := db.Select("*").From("customer").Where(HashExp{"id": 1})
361 var customer Customer
362 assert.Equal(t, q.One(&customer), nil)
363 assert.Equal(t, 1, customer.ID)
364 }
365
366 type User struct {
367 ID int64
368 Email string
369 Created time.Time
370 Updated *time.Time
371 }
372
373 func TestIssue13(t *testing.T) {
374 db := getPreparedDB()
375 var user User
376 err := db.Select().From("user").Where(HashExp{"id": 1}).One(&user)
377 if assert.Nil(t, err) {
378 assert.NotZero(t, user.Created)
379 assert.Nil(t, user.Updated)
380 }
381
382 now := time.Now()
383
384 user2 := User{
385 Email: "[email protected]",
386 Created: now,
387 }
388 err = db.Model(&user2).Insert()
389 if assert.Nil(t, err) {
390 assert.NotZero(t, user2.ID)
391 }
392
393 user3 := User{
394 Email: "[email protected]",
395 Created: now,
396 Updated: &now,
397 }
398 err = db.Model(&user3).Insert()
399 if assert.Nil(t, err) {
400 assert.NotZero(t, user2.ID)
401 }
402 }
403
404 func TestQueryWithExecHook(t *testing.T) {
405 db := getPreparedDB()
406 defer db.Close()
407
408 // error return
409 {
410 err := db.NewQuery("select * from user").
411 WithExecHook(func(q *Query, op func() error) error {
412 return errors.New("test")
413 }).
414 Row()
415
416 assert.Error(t, err)
417 }
418
419 // Row()
420 {
421 calls := 0
422 err := db.NewQuery("select * from user").
423 WithExecHook(func(q *Query, op func() error) error {
424 calls++
425 return nil
426 }).
427 Row()
428 assert.Nil(t, err)
429 assert.Equal(t, 1, calls, "Row()")
430 }
431
432 // One()
433 {
434 calls := 0
435 err := db.NewQuery("select * from user").
436 WithExecHook(func(q *Query, op func() error) error {
437 calls++
438 return nil
439 }).
440 One(nil)
441 assert.Nil(t, err)
442 assert.Equal(t, 1, calls, "One()")
443 }
444
445 // All()
446 {
447 calls := 0
448 err := db.NewQuery("select * from user").
449 WithExecHook(func(q *Query, op func() error) error {
450 calls++
451 return nil
452 }).
453 All(nil)
454 assert.Nil(t, err)
455 assert.Equal(t, 1, calls, "All()")
456 }
457
458 // Column()
459 {
460 calls := 0
461 err := db.NewQuery("select * from user").
462 WithExecHook(func(q *Query, op func() error) error {
463 calls++
464 return nil
465 }).
466 Column(nil)
467 assert.Nil(t, err)
468 assert.Equal(t, 1, calls, "Column()")
469 }
470
471 // Execute()
472 {
473 calls := 0
474 _, err := db.NewQuery("select * from user").
475 WithExecHook(func(q *Query, op func() error) error {
476 calls++
477 return nil
478 }).
479 Execute()
480 assert.Nil(t, err)
481 assert.Equal(t, 1, calls, "Execute()")
482 }
483
484 // op call
485 {
486 calls := 0
487 var id int
488 err := db.NewQuery("select id from user where id = 2").
489 WithExecHook(func(q *Query, op func() error) error {
490 calls++
491 return op()
492 }).
493 Row(&id)
494 assert.Nil(t, err)
495 assert.Equal(t, 1, calls, "op hook calls")
496 assert.Equal(t, 2, id, "id mismatch")
497 }
498 }
499
500 func TestQueryWithOneHook(t *testing.T) {
501 db := getPreparedDB()
502 defer db.Close()
503
504 // error return
505 {
506 err := db.NewQuery("select * from user").
507 WithOneHook(func(q *Query, a interface{}, op func(b interface{}) error) error {
508 return errors.New("test")
509 }).
510 One(nil)
511
512 assert.Error(t, err)
513 }
514
515 // hooks call order
516 {
517 hookCalls := []string{}
518 err := db.NewQuery("select * from user").
519 WithExecHook(func(q *Query, op func() error) error {
520 hookCalls = append(hookCalls, "exec")
521 return op()
522 }).
523 WithOneHook(func(q *Query, a interface{}, op func(b interface{}) error) error {
524 hookCalls = append(hookCalls, "one")
525 return nil
526 }).
527 One(nil)
528
529 assert.Nil(t, err)
530 assert.Equal(t, hookCalls, []string{"exec", "one"})
531 }
532
533 // op call
534 {
535 calls := 0
536 other := User{}
537 err := db.NewQuery("select id from user where id = 2").
538 WithOneHook(func(q *Query, a interface{}, op func(b interface{}) error) error {
539 calls++
540 return op(&other)
541 }).
542 One(nil)
543
544 assert.Nil(t, err)
545 assert.Equal(t, 1, calls, "hook calls")
546 assert.Equal(t, int64(2), other.ID, "replaced scan struct")
547 }
548 }
549
550 func TestQueryWithAllHook(t *testing.T) {
551 db := getPreparedDB()
552 defer db.Close()
553
554 // error return
555 {
556 err := db.NewQuery("select * from user").
557 WithAllHook(func(q *Query, a interface{}, op func(b interface{}) error) error {
558 return errors.New("test")
559 }).
560 All(nil)
561
562 assert.Error(t, err)
563 }
564
565 // hooks call order
566 {
567 hookCalls := []string{}
568 err := db.NewQuery("select * from user").
569 WithExecHook(func(q *Query, op func() error) error {
570 hookCalls = append(hookCalls, "exec")
571 return op()
572 }).
573 WithAllHook(func(q *Query, a interface{}, op func(b interface{}) error) error {
574 hookCalls = append(hookCalls, "all")
575 return nil
576 }).
577 All(nil)
578
579 assert.Nil(t, err)
580 assert.Equal(t, hookCalls, []string{"exec", "all"})
581 }
582
583 // op call
584 {
585 calls := 0
586 other := []User{}
587 err := db.NewQuery("select id from user order by id asc").
588 WithAllHook(func(q *Query, a interface{}, op func(b interface{}) error) error {
589 calls++
590 return op(&other)
591 }).
592 All(nil)
593
594 assert.Nil(t, err)
595 assert.Equal(t, 1, calls, "hook calls")
596 assert.Equal(t, 2, len(other), "users length")
597 assert.Equal(t, int64(1), other[0].ID, "user 1 id check")
598 assert.Equal(t, int64(2), other[1].ID, "user 2 id check")
599 }
600 }