/
db.go
128 lines (111 loc) · 2.41 KB
/
db.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package db
import (
"bytes"
"database/sql"
"unicode"
"unicode/utf8"
"github.com/jmoiron/sqlx"
)
//
type Executor interface {
NamedExec(query string, arg interface{}) (sql.Result, error)
NamedQuery(query string, arg interface{}) (*sqlx.Rows, error)
}
func init() {
sqlx.NameMapper = toSnakeCase
}
//
func toSnakeCase(x string) string {
if len(x) == 0 {
return ""
}
output := make([]byte, 0)
first := true
for len(x) > 0 {
v, size := utf8.DecodeRuneInString(x)
// If underscore, append and keep going.
if v == '_' {
output = append(output, byte('_'))
} else if unicode.IsLetter(v) {
if unicode.IsLower(v) {
// Keep it the same if it is lower.
buf := make([]byte, size)
utf8.EncodeRune(buf, v)
output = bytes.Join([][]byte{output, buf}, nil)
} else if unicode.IsUpper(v) {
// Lowercase it otherwise.
buf := make([]byte, size)
utf8.EncodeRune(buf, unicode.ToLower(v))
if first {
output = buf
first = false
} else {
output = bytes.Join([][]byte{output, buf}, []byte("_"))
}
}
}
x = x[size:]
}
return string(output)
}
//
func toCamelCase(x string) string {
if len(x) == 0 {
return ""
}
output := make([]byte, 0)
uppercase := true
for len(x) > 0 {
v, size := utf8.DecodeRuneInString(x)
// If underscore, append and keep going.
if v == '_' {
uppercase = true
} else if unicode.IsLetter(v) {
if uppercase {
uppercase = false
buf := make([]byte, size)
utf8.EncodeRune(buf, unicode.ToUpper(v))
output = bytes.Join([][]byte{output, buf}, nil)
} else if unicode.IsUpper(v) {
buf := make([]byte, size)
utf8.EncodeRune(buf, v)
output = bytes.Join([][]byte{output, buf}, []byte("_"))
}
}
x = x[size:]
}
return string(output)
}
//
func mapUnion(x map[string]interface{}, y map[string]interface{}) map[string]interface{} {
z := make(map[string]interface{})
if x != nil {
for key, value := range x {
z[key] = value
}
}
if y != nil {
for key, value := range y {
_, ok := z[key]
if ok {
panic("mapUnion will overwrite.")
}
z[key] = value
}
}
return z
}
//
func JoinClausesOn(c []Clause, on string) (string, map[string]interface{}) {
outStmt := ""
outObj := make(map[string]interface{})
for i, v := range c {
if i != 0 {
outStmt += on
}
tempStmt, tempObjects := v.Compile()
outStmt += tempStmt
outObj = mapUnion(outObj, tempObjects)
}
return outStmt, outObj
}