-
Notifications
You must be signed in to change notification settings - Fork 3
/
sqlbuf.go
80 lines (65 loc) · 1.31 KB
/
sqlbuf.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
package mysql
import (
"bytes"
"strings"
)
type SqlBuffer struct {
*bytes.Buffer
args []interface{}
}
func NewSqlBuffer() *SqlBuffer {
return &SqlBuffer{
Buffer: bytes.NewBuffer(make([]byte, 0, 1024)),
}
}
func (b *SqlBuffer) Reset() {
b.Buffer.Reset()
b.args = b.args[:0]
}
func (b *SqlBuffer) GetSQL() string {
return b.Buffer.String()
}
func (b *SqlBuffer) GetArgs() []interface{} {
return b.args
}
func (b *SqlBuffer) String() string {
buf := &bytes.Buffer{}
argPos := 0
query := b.GetSQL()
args := b.GetArgs()
for i := 0; i < len(query); i++ {
q := strings.IndexByte(query[i:], '?')
if q == -1 {
buf.WriteString(query[i:])
break
}
buf.WriteString(query[i : i+q])
i += q
buf.WriteString(Quote(args[argPos]))
argPos++
}
return buf.String()
}
func (b *SqlBuffer) WriteIdentifier(identifier string) {
b.WriteString(QuoteIdentifier(identifier))
}
func (b *SqlBuffer) WriteValue(value interface{}) {
b.WriteByte('?')
b.args = append(b.args, value)
}
func (b *SqlBuffer) WriteIdentifiersList(identifiers []string) {
for i, identifier := range identifiers {
if i > 0 {
b.WriteByte(',')
}
b.WriteIdentifier(identifier)
}
}
func (b *SqlBuffer) WriteValuesList(values []interface{}) {
for i, value := range values {
if i > 0 {
b.WriteByte(',')
}
b.WriteValue(value)
}
}