sql.go
1.9 KB
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
96
97
98
99
100
101
102
package mybeego
import (
"bytes"
"fmt"
"github.com/astaxie/beego/orm"
"strings"
)
type SqlExcutor struct {
table string
wherestr []string
orderstr []string
islimit bool
offset int
pagenum int
}
func NewSqlExutor()*SqlExcutor{
return &SqlExcutor{}
}
func(s *SqlExcutor)Table(str string)*SqlExcutor{
s.table = str
return s
}
func(s *SqlExcutor)Where(condition ...string)*SqlExcutor{
if len(condition)<=0{
return s
}
s.wherestr = append(s.wherestr,condition...)
return s
}
func(s *SqlExcutor)Order(condition ...string)*SqlExcutor{
if len(condition)<=0{
return s
}
s.orderstr = append(s.orderstr,condition...)
return s
}
func(s *SqlExcutor)Limit(page,pagenum int)*SqlExcutor{
offset :=0
if page>0{
offset = (page-1)*pagenum
}
s.islimit =true
s.offset = offset
s.pagenum = pagenum
return s
}
func(s *SqlExcutor)Strings()( string, string, error){
sqlRow :=bytes.NewBufferString(" select * ")
sqlCount :=bytes.NewBufferString("select count(0) ")
sql :=bytes.NewBufferString("")
if len(s.table)<0{
err := fmt.Errorf("table name is empty")
return "","",err
}
sql.WriteString(fmt.Sprintf(" from %v",s.table))
if len(s.wherestr)>0{
sql.WriteString(" where ")
for i:=range s.wherestr{
if i!=0{
sql.WriteString( " AND ")
}
sql.WriteString(s.wherestr[i])
}
}
if len(s.orderstr)>0{
sql.WriteString("\n order by ")
sql.WriteString(strings.Join(s.orderstr,","))
}
sqlCount.WriteString(sql.String())
if s.islimit{
sql.WriteString(fmt.Sprintf("\n limit %v,%v",s.offset,s.pagenum))
}
sqlRow.WriteString(sql.String())
return sqlRow.String(),sqlCount.String(),nil
}
func(s *SqlExcutor)Querys(v interface{})(total int,err error){
o :=orm.NewOrm()
var sqlRow,sqlCount string
if sr,sc,e :=s.Strings();e!=nil{
err =e
return
}else{
sqlRow = sr
sqlCount = sc
}
if err=o.Raw(sqlCount).QueryRow(&total);err!=nil{
return
}
if _,err=o.Raw(sqlRow).QueryRows(v);err!=nil{
return
}
return
}