/
string_util.go
223 lines (216 loc) · 6.21 KB
/
string_util.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package sq
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"math/rand"
"reflect"
"strconv"
"strings"
"time"
)
// expandValues will expand each value one by one into successive question mark
// ? placeholders in the format string, writing the results into the buffer and
// args slice. It propagates the excludedTableQualifiers down to its child elements.
func expandValues(buf *strings.Builder, args *[]interface{}, excludedTableQualifiers []string, format string, values []interface{}) {
for i := strings.Index(format, "?"); i >= 0 && len(values) > 0; i = strings.Index(format, "?") {
buf.WriteString(format[:i])
// TODO: I don't know if ?? should be unescaped to ?
// if len(format[i:]) > 1 && format[i:i+2] == "??" {
// buf.WriteString("?")
// format = format[i+2:]
// continue
// }
appendSQLValue(buf, args, excludedTableQualifiers, values[0])
format = format[i+1:]
values = values[1:]
}
buf.WriteString(format)
}
// appendSQLValue will write the SQL representation of the interface{} value
// into the buffer and args slice. It propagates excludedTableQualifiers where
// relevant.
func appendSQLValue(buf *strings.Builder, args *[]interface{}, excludedTableQualifiers []string, value interface{}) {
switch v := value.(type) {
case nil:
buf.WriteString("NULL")
return
case interface {
AppendSQLExclude(*strings.Builder, *[]interface{}, map[string]int, []string)
}:
v.AppendSQLExclude(buf, args, nil, excludedTableQualifiers)
return
case interface {
AppendSQL(*strings.Builder, *[]interface{}, map[string]int)
}:
v.AppendSQL(buf, args, nil)
return
}
switch reflect.TypeOf(value).Kind() {
case reflect.Slice, reflect.Array:
s := reflect.ValueOf(value)
if l := s.Len(); l == 0 {
buf.WriteString("NULL")
} else {
buf.WriteString("?")
buf.WriteString(strings.Repeat(", ?", l-1))
for i := 0; i < l; i++ {
*args = append(*args, s.Index(i).Interface())
}
}
return
}
buf.WriteString("?")
*args = append(*args, value)
}
// randomString is the RandStringBytesMaskImprSrcSB function taken from
// https://stackoverflow.com/a/31832326. It generates a random alphabetical
// string of length n.
func randomString(n int) string {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var src = rand.NewSource(time.Now().UnixNano())
sb := strings.Builder{}
sb.Grow(n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
sb.WriteByte(letterBytes[idx])
i--
}
cache >>= letterIdxBits
remain--
}
return sb.String()
}
// interpolateSQLValue interpolates an interface value as its SQL
// representation into a buffer. This makes it vulnerable to SQL injection and
// should be used for display purposes ONLY, not for actually running against a
// database.
func interpolateSQLValue(buf *strings.Builder, value interface{}) {
switch v := value.(type) {
case nil:
buf.WriteString("NULL")
case bool:
if v {
buf.WriteString("TRUE")
} else {
buf.WriteString("FALSE")
}
case string:
buf.WriteString("'")
buf.WriteString(v)
buf.WriteString("'")
case int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64:
buf.WriteString(fmt.Sprint(value))
case time.Time:
buf.WriteString("'")
buf.WriteString(v.Format(time.RFC3339Nano))
buf.WriteString("'")
case driver.Valuer:
Interface, err := v.Value()
if err != nil {
buf.WriteString(":")
buf.WriteString(err.Error())
buf.WriteString(":")
} else {
switch Concrete := Interface.(type) {
case string:
buf.WriteString("'")
buf.WriteString(Concrete)
buf.WriteString("'")
case nil:
buf.WriteString("NULL")
default:
buf.WriteString(":")
buf.WriteString(fmt.Sprintf("%#v", value)) // give up, don't know what it is, resort to fmt.Sprintf
buf.WriteString(":")
}
}
default:
b, err := json.Marshal(value)
if err != nil {
buf.WriteString(":")
buf.WriteString(fmt.Sprintf("%#v", value)) // give up, don't know what it is, resort to fmt.Sprintf
buf.WriteString(":")
} else {
buf.WriteString("'")
buf.Write(b)
buf.WriteString("'")
}
}
}
// appendSQLDisplay marshals an interface value into a buffer.
func appendSQLDisplay(buf *strings.Builder, value interface{}) {
switch v := value.(type) {
case nil:
buf.WriteString("𝗡𝗨𝗟𝗟")
case *sql.NullBool:
if v.Valid {
if v.Bool {
buf.WriteString("true")
} else {
buf.WriteString("false")
}
} else {
buf.WriteString("𝗡𝗨𝗟𝗟")
}
case *sql.NullFloat64:
if v.Valid {
buf.WriteString(fmt.Sprintf("%f", v.Float64))
} else {
buf.WriteString("𝗡𝗨𝗟𝗟")
}
case *sql.NullInt64:
if v.Valid {
buf.WriteString(strconv.FormatInt(v.Int64, 10))
} else {
buf.WriteString("𝗡𝗨𝗟𝗟")
}
case *sql.NullString:
if v.Valid {
buf.WriteString(v.String)
} else {
buf.WriteString("𝗡𝗨𝗟𝗟")
}
case *sql.NullTime:
if v.Valid {
buf.WriteString(v.Time.String())
} else {
buf.WriteString("𝗡𝗨𝗟𝗟")
}
default:
buf.WriteString(fmt.Sprintf("%#v", value))
}
}
// questionInterpolate interpolates the question mark ? placeholders in a query
// string with the args in the args slice. It is vulnerable to SQL injection
// and should be used for display purposes only, not for actually running
// against a database.
func questionInterpolate(query string, args ...interface{}) string {
buf := &strings.Builder{}
// i is the position of the ? in the query
for i := strings.Index(query, "?"); i >= 0 && len(args) > 0; i = strings.Index(query, "?") {
buf.WriteString(query[:i])
if len(query[i:]) > 1 && query[i:i+2] == "??" {
buf.WriteString("?")
query = query[i+2:]
continue
}
interpolateSQLValue(buf, args[0])
query = query[i+1:]
args = args[1:]
}
buf.WriteString(query)
return buf.String()
}