MCPcopy
hub / github.com/go-gorm/gorm / TestScan

Function TestScan

tests/scan_test.go:19–120  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

17}
18
19func TestScan(t *testing.T) {
20 user1 := User{Name: "ScanUser1", Age: 1}
21 user2 := User{Name: "ScanUser2", Age: 10}
22 user3 := User{Name: "ScanUser3", Age: 20}
23 DB.Save(&user1).Save(&user2).Save(&user3)
24
25 type result struct {
26 ID uint
27 Name string
28 Age int
29 }
30
31 var res result
32 DB.Table("users").Select("id, name, age").Where("id = ?", user3.ID).Scan(&res)
33 if res.ID != user3.ID || res.Name != user3.Name || res.Age != int(user3.Age) {
34 t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user3)
35 }
36
37 var resPointer *result
38 if err := DB.Table("users").Select("id, name, age").Where("id = ?", user3.ID).Scan(&resPointer).Error; err != nil {
39 t.Fatalf("Failed to query with pointer of value, got error %v", err)
40 } else if resPointer.ID != user3.ID || resPointer.Name != user3.Name || resPointer.Age != int(user3.Age) {
41 t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user3)
42 }
43
44 DB.Table("users").Select("id, name, age").Where("id = ?", user2.ID).Scan(&res)
45 if res.ID != user2.ID || res.Name != user2.Name || res.Age != int(user2.Age) {
46 t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user2)
47 }
48
49 DB.Model(&User{Model: gorm.Model{ID: user3.ID}}).Select("id, name, age").Scan(&res)
50 if res.ID != user3.ID || res.Name != user3.Name || res.Age != int(user3.Age) {
51 t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user3)
52 }
53
54 doubleAgeRes := &result{}
55 if err := DB.Table("users").Select("age + age as age").Where("id = ?", user3.ID).Scan(&doubleAgeRes).Error; err != nil {
56 t.Errorf("Scan to pointer of pointer")
57 }
58
59 if doubleAgeRes.Age != int(res.Age)*2 {
60 t.Errorf("Scan double age as age, expect: %v, got %v", res.Age*2, doubleAgeRes.Age)
61 }
62
63 var results []result
64 DB.Table("users").Select("name, age").Where("id in ?", []uint{user2.ID, user3.ID}).Scan(&results)
65
66 sort.Slice(results, func(i, j int) bool {
67 return strings.Compare(results[i].Name, results[j].Name) <= -1
68 })
69
70 if len(results) != 2 || results[0].Name != user2.Name || results[1].Name != user3.Name {
71 t.Errorf("Scan into struct map, got %#v", results)
72 }
73
74 type ID uint64
75 var id ID
76 DB.Raw("select id from users where id = ?", user2.ID).Scan(&id)

Callers

nothing calls this directly

Calls 8

SaveMethod · 0.80
ModelMethod · 0.80
ScanMethod · 0.65
WhereMethod · 0.65
SelectMethod · 0.65
TableMethod · 0.65
RawMethod · 0.65
FindMethod · 0.65

Tested by

no test coverage detected