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

Function TestRaw

tests/sql_builder_test.go:72–111  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

70}
71
72func TestRaw(t *testing.T) {
73 user1 := User{Name: "ExecRawSqlUser1", Age: 1}
74 user2 := User{Name: "ExecRawSqlUser2", Age: 10}
75 user3 := User{Name: "ExecRawSqlUser3", Age: 20}
76 DB.Save(&user1).Save(&user2).Save(&user3)
77
78 type result struct {
79 Name string
80 Email string
81 }
82
83 var results []result
84 DB.Raw("SELECT name, age FROM users WHERE name = ? or name = ?", user2.Name, user3.Name).Scan(&results)
85 if len(results) != 2 || results[0].Name != user2.Name || results[1].Name != user3.Name {
86 t.Errorf("Raw with scan")
87 }
88
89 rows, _ := DB.Raw("select name, age from users where name = ?", user3.Name).Rows()
90 count := 0
91 for rows.Next() {
92 count++
93 }
94 if count != 1 {
95 t.Errorf("Raw with Rows should find one record with name 3")
96 }
97
98 DB.Exec("update users set name=? where name in (?)", "jinzhu-raw", []string{user1.Name, user2.Name, user3.Name})
99 if DB.Where("name in (?)", []string{user1.Name, user2.Name, user3.Name}).First(&User{}).Error != gorm.ErrRecordNotFound {
100 t.Error("Raw sql to update records")
101 }
102
103 DB.Exec("update users set age=? where name = ?", gorm.Expr("age * ? + ?", 2, 10), "jinzhu-raw")
104
105 var age int
106 DB.Raw("select sum(age) from users where name = ?", "jinzhu-raw").Scan(&age)
107
108 if age != ((1+10+20)*2 + 30) {
109 t.Errorf("Invalid age, got %v", age)
110 }
111}
112
113func TestRowsWithGroup(t *testing.T) {
114 users := []User{

Callers

nothing calls this directly

Calls 10

ExprFunction · 0.92
SaveMethod · 0.80
NextMethod · 0.80
ScanMethod · 0.65
RawMethod · 0.65
RowsMethod · 0.65
ExecMethod · 0.65
FirstMethod · 0.65
WhereMethod · 0.65
ErrorMethod · 0.65

Tested by

no test coverage detected