-
Notifications
You must be signed in to change notification settings - Fork 2
/
database_template_test.go
95 lines (81 loc) · 2.04 KB
/
database_template_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package databasetemplate
import (
"database/sql"
"testing"
_ "github.com/go-sql-driver/mysql"
"fmt"
)
type Test struct{
A int
B string
}
func TestExec(t *testing.T){
db, err := sql.Open("mysql", "root:@/lomo_dev?charset=utf8")
defer db.Close()
db.SetMaxIdleConns(10)
if err!=nil{
return
}
dbTemplate:=&DatabaseTemplateImpl{db}
err=dbTemplate.Exec("create table if not exists test(a int not null AUTO_INCREMENT,b varchar(10),primary key(a))")
if err!=nil{
t.Error("can't get from db",err)
}
err=dbTemplate.Exec("truncate table test")
if err!=nil{
t.Error("can't get from db",err)
}
err=dbTemplate.Exec("insert into test(b) values(?)","aaa")
if err!=nil{
t.Error("can't get from db",err)
}
err=dbTemplate.Exec("insert into test(b) values(?)","bbb")
if err!=nil{
t.Error("can't get from db",err)
}
mapRow := func(resultSet *sql.Rows)(object interface{},err error){
t:=Test{}
err = resultSet.Scan(&t.A,&t.B)
if err!= nil{
return nil,err
}
return t,err
}
mapRowPtr := func(resultSet *sql.Rows)(object interface{},err error){
t:=Test{}
err = resultSet.Scan(&t.A,&t.B)
if err!= nil{
return nil,err
}
return &t,err
}
list,err:=dbTemplate.Query("select a,b,c from test",mapRow)
if list!=nil{
t.Error("list should be nil",list)
}
if err.Error()!="Error 1054: Unknown column 'c' in 'field list'"{
t.Errorf("error should be Error 1054: Unknown column 'c' in 'field list'")
}
var tests []Test
err=dbTemplate.QueryIntoArray(&tests,"select * from test",mapRow)
if err!=nil{
t.Error("can't get from db",err)
}
fmt.Println(tests)
var testsPtr []*Test
err=dbTemplate.QueryIntoArray(&testsPtr,"select * from test",mapRowPtr)
if err!=nil{
t.Error("can't get from db",err)
}
fmt.Println(*testsPtr[0])
var testsPtr2 []*Test
err=dbTemplate.QueryIntoArray(&testsPtr2,"select * from test",mapRow)
if err==nil{
t.Error("should be error")
}
var tests2 []Test
err=dbTemplate.QueryIntoArray(&tests2,"select * from test",mapRowPtr)
if err==nil{
t.Error("should be error")
}
}