-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlbuilder.go
47 lines (37 loc) · 839 Bytes
/
sqlbuilder.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
package main
import (
"bytes"
"strconv"
"strings"
)
type SqlBuilder struct {
query bytes.Buffer
values []interface{}
}
func NewSqlBuilder() SqlBuilder {
return SqlBuilder{
values: make([]interface{}, 0, 4),
}
}
func (b *SqlBuilder) Sql() string {
return b.query.String()
}
func (b *SqlBuilder) Values() []interface{} {
return b.values
}
func (b *SqlBuilder) WriteSql(sql string) {
b.query.WriteString(sql)
}
func (b *SqlBuilder) WriteId(id string) {
b.query.WriteString(quoteIdentifier(id))
}
func (b *SqlBuilder) WriteValue(value interface{}) {
b.values = append(b.values, value)
b.query.WriteString("$" + strconv.Itoa(len(b.values)))
}
func quoteIdentifier(name string) string {
if end := strings.IndexRune(name, 0); end > -1 {
name = name[:end]
}
return `"` + strings.Replace(name, `"`, `""`, -1) + `"`
}