-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.go
More file actions
305 lines (281 loc) · 6.58 KB
/
db.go
File metadata and controls
305 lines (281 loc) · 6.58 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
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package db
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/kisielk/sqlstruct"
"github.com/shopspring/decimal"
)
const DateTimeTzFormat = "2006-01-02 15:04:05.999999999-07"
type Params map[string]interface{}
type CommaListParam []interface{}
type Error struct {
cause error
Query string
Params Params
}
func (e *Error) Error() string {
return e.cause.Error()
}
func (e *Error) Cause() error {
return e.cause
}
func (e *Error) Unwrap() error {
return e.cause
}
func wrapError(err error, sql string, params Params) error {
if err == nil {
return nil
}
return &Error{
cause: err,
Query: sql,
Params: params,
}
}
func qprintf(sql string, params Params) (string, error) {
isNotWordChar := func(r rune) bool {
return !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || r == '_' || (r >= '0' && r <= '9'))
}
var result strings.Builder
s := sql
for {
idx := strings.IndexRune(s, ':')
// ':' not found or its at the end of the string
if idx == -1 || idx == len(s)-1 {
result.WriteString(s)
break
}
// followed by a non-word char?
if isNotWordChar(rune(s[idx+1])) {
result.WriteString(s[:idx+2])
s = s[idx+2:]
continue
}
result.WriteString(s[:idx])
s = s[idx+1:] // skip ':' char
// find next \W character
idxEnd := strings.IndexFunc(s, isNotWordChar)
var param string
if idxEnd == -1 {
param = s
} else {
param = s[:idxEnd]
}
v, ok := params[param]
if !ok {
return "", fmt.Errorf("parameter %s is missing", param)
}
castedValue, err := toDbValue(v)
if err != nil {
return "", err
}
result.WriteString(castedValue)
if idxEnd == -1 {
break
}
s = s[idxEnd:]
}
return result.String(), nil
}
func Exec(ctx context.Context, db Queryable, sql string, params Params) (sql.Result, error) {
query, err := qprintf(sql, params)
if err != nil {
return nil, wrapError(err, sql, params)
}
res, err := db.ExecContext(ctx, query)
if err != nil {
return nil, wrapError(err, sql, params)
}
return res, nil
}
func Query(ctx context.Context, db Queryable, sql string, params Params) (*sql.Rows, error) {
query, err := qprintf(sql, params)
if err != nil {
return nil, wrapError(err, sql, params)
}
rows, err := db.QueryContext(ctx, query)
if err != nil {
return nil, wrapError(err, sql, params)
}
return rows, nil
}
func QueryRow(ctx context.Context, db Queryable, sql string, params Params) (*sql.Row, error) {
query, err := qprintf(sql, params)
if err != nil {
return nil, wrapError(err, sql, params)
}
return db.QueryRowContext(ctx, query), nil
}
func QueryRowAndScan(ctx context.Context, db Queryable, q string, params Params, dest ...interface{}) error {
row, err := QueryRow(ctx, db, q, params)
if err != nil {
return err
}
if err := row.Scan(dest...); err != nil {
if err == sql.ErrNoRows {
return err
}
return wrapError(err, q, params)
}
return nil
}
func QueryJSONRowIntoStruct(ctx context.Context, db Queryable, q string, params Params, target interface{}) error {
row, err := QueryRow(ctx, db, q, params)
if err != nil {
return err
}
var data []byte
if err = row.Scan(&data); err != nil {
if err == sql.ErrNoRows {
return err
}
return wrapError(err, q, params)
}
if err = json.Unmarshal(data, target); err != nil {
return wrapError(err, q, params)
}
return nil
}
func QueryRowIntoStruct(ctx context.Context, db Queryable, q string, params Params, target interface{}) error {
rows, err := Query(ctx, db, q, params)
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return sql.ErrNoRows
}
if err = sqlstruct.Scan(target, rows); err != nil {
return wrapError(err, q, params)
}
return nil
}
func QueryRowsIntoSlice(ctx context.Context, db Queryable, q string, params Params, target interface{}) (interface{}, error) {
rows, err := Query(ctx, db, q, params)
if err != nil {
return nil, err
}
defer rows.Close()
elemType := reflect.TypeOf(target)
v := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 0)
for rows.Next() {
elemPtr := reflect.New(elemType)
if err := sqlstruct.Scan(elemPtr.Interface(), rows); err != nil {
return nil, wrapError(err, q, params)
}
elem := reflect.Indirect(elemPtr)
v = reflect.Append(v, elem)
}
return v.Interface(), nil
}
func ScanJSONRowsIntoStruct(rows *sql.Rows, target interface{}) error {
var data []byte
if err := rows.Scan(&data); err != nil {
return err
}
return json.Unmarshal(data, target)
}
// toDbValue prepares value to be passed in SQL query
// with respect to its type and converts it to string
func toDbValue(value interface{}) (string, error) {
if value == nil {
return "NULL", nil
}
switch value := value.(type) {
case *string:
if value == nil {
return "NULL", nil
}
return toDbValue(*value)
case string:
return quoteLiteral(value), nil
case *int:
if value == nil {
return "NULL", nil
}
return toDbValue(*value)
case int:
return strconv.Itoa(value), nil
case *float64:
if value == nil {
return "NULL", nil
}
return toDbValue(*value)
case float64:
return strconv.FormatFloat(value, 'g', -1, 64), nil
case *bool:
if value == nil {
return "NULL", nil
}
return toDbValue(*value)
case bool:
return strconv.FormatBool(value), nil
case *decimal.Decimal:
if value == nil {
return "NULL", nil
}
return toDbValue(*value)
case decimal.Decimal:
return value.String(), nil
case *time.Time:
if value == nil {
return "NULL", nil
}
return toDbValue(*value)
case time.Time:
return quoteLiteral(value.Format(DateTimeTzFormat)), nil
case CommaListParam:
e := make([]string, len(value))
for i := range value {
var err error
e[i], err = toDbValue(value[i])
if err != nil {
return "", err
}
}
return strings.Join(e, ", "), nil
}
// the value is either slice or map, so insert it as JSON string
// fixme: marshaller doesn't know how to encode map[interface{}]interface{}
encoded, err := json.Marshal(value)
if err != nil {
return "", err
}
asString := string(encoded)
if encoded == nil || asString == "null" {
return "NULL", nil
}
return quoteLiteral(asString), nil
}
// quoteLiteral properly escapes string to be safely
// passed as a value in SQL query
func quoteLiteral(s string) string {
var b strings.Builder
b.Grow(len(s)*2 + 3)
b.WriteRune('E')
b.WriteRune('\'')
hasSlash := false
for _, c := range s {
if c == '\\' {
b.WriteString(`\\`)
hasSlash = true
} else if c == '\'' {
b.WriteString(`''`)
} else {
b.WriteRune(c)
}
}
b.WriteRune('\'')
s = b.String()
if !hasSlash {
// remove unnecessary E at the beginning
return s[1:]
}
return s
}