-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathfactory.go
448 lines (371 loc) · 9.73 KB
/
factory.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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package buildsqlx
import (
"fmt"
"github.com/lib/pq"
"log"
"strconv"
"strings"
)
const (
plusSign = "+"
minusSign = "-"
// Errors
errTableCallBeforeOp = "sql: there was no Table() call with table name set"
)
// Get builds all sql statements chained before and executes query collecting data to the slice
func (r *DB) Get() ([]map[string]interface{}, error) {
builder := r.Builder
if builder.table == "" {
return nil, fmt.Errorf(errTableCallBeforeOp)
}
query := ""
if len(builder.union) > 0 { // got union - need different logic to glue
for _, uBuilder := range builder.union {
query += uBuilder + " UNION "
if builder.isUnionAll == true {
query += "ALL "
}
}
query += builder.buildSelect()
} else { // std builder
query = builder.buildSelect()
}
rows, err := r.Sql().Query(query, prepareValues(r.Builder.whereBindings, true)...)
if err != nil {
return nil, err
}
columns, _ := rows.Columns()
count := len(columns)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
// collecting data from struct with fields
var res []map[string]interface{}
for rows.Next() {
collect := make(map[string]interface{}, count)
for i := range columns {
valuePtrs[i] = &values[i]
}
err := rows.Scan(valuePtrs...)
if err != nil {
return nil, err
}
for i, col := range columns {
val := values[i]
b, ok := val.([]byte)
if ok {
collect[col] = string(b)
} else {
collect[col] = val
}
}
res = append(res, collect)
}
return res, nil
}
func prepareValues(values []map[string]interface{}, where bool) []interface{} {
var vls []interface{}
for _, v := range values {
_, vals, _ := prepareBindings(v, where)
vls = append(vls, vals...)
}
return vls
}
// buildSelect constructs a query for select statement
func (r *builder) buildSelect() string {
query := "SELECT " + strings.Join(r.columns, ", ") + " FROM " + r.table
return query + r.buildClauses()
}
// builds query string clauses
func (r *builder) buildClauses() string {
clauses := ""
for _, j := range r.join {
clauses += j
}
// build where clause
if len(r.whereBindings) > 0 {
clauses += composeWhere(r.whereBindings, r.startBindingsAt)
} else { // std without bindings todo: change all to bindings
clauses += r.where
}
if r.groupBy != "" {
clauses += " GROUP BY " + r.groupBy
}
if r.having != "" {
clauses += " HAVING " + r.having
}
clauses += composeOrderBy(r.orderBy, r.orderByRaw)
if r.limit > 0 {
clauses += " LIMIT " + strconv.FormatInt(r.limit, 10)
}
if r.offset > 0 {
clauses += " OFFSET " + strconv.FormatInt(r.offset, 10)
}
if r.lockForUpdate != nil {
clauses += *r.lockForUpdate
}
return clauses
}
// composes WHERE clause string for particular query stmt
func composeWhere(whereBindings []map[string]interface{}, startedAt int) string {
where := " WHERE "
i := startedAt
for _, m := range whereBindings {
for k := range m {
// operand >= $i
where += k + " $" + strconv.Itoa(i)
i++
}
}
return where
}
// composers ORDER BY clause string for particular query stmt
func composeOrderBy(orderBy []map[string]string, orderByRaw *string) string {
if len(orderBy) > 0 {
orderStr := ""
for _, m := range orderBy {
for field, direct := range m {
if orderStr == "" {
orderStr = " ORDER BY " + field + " " + direct
} else {
orderStr += ", " + field + " " + direct
}
}
}
return orderStr
} else if orderByRaw != nil {
return " ORDER BY " + *orderByRaw
}
return ""
}
// Insert inserts one row with param bindings
func (r *DB) Insert(data map[string]interface{}) error {
builder := r.Builder
if builder.table == "" {
return fmt.Errorf(errTableCallBeforeOp)
}
columns, values, bindings := prepareBindings(data, false)
query := "INSERT INTO " + builder.table + " (" + strings.Join(columns, ", ") + ") VALUES(" + strings.Join(bindings, ", ") + ")"
_, err := r.Sql().Exec(query, values...)
if err != nil {
return err
}
return nil
}
// InsertGetId inserts one row with param bindings and returning id
func (r *DB) InsertGetId(data map[string]interface{}) (uint64, error) {
builder := r.Builder
if builder.table == "" {
return 0, fmt.Errorf(errTableCallBeforeOp)
}
columns, values, bindings := prepareBindings(data, false)
query := "INSERT INTO " + builder.table + " (" + strings.Join(columns, ", ") + ") VALUES(" + strings.Join(bindings, ", ") + ") RETURNING id"
var id uint64
err := r.Sql().QueryRow(query, values...).Scan(&id)
if err != nil {
return 0, err
}
return id, nil
}
// prepareBindings prepares slices to split in favor of INSERT sql statement
func prepareBindings(data map[string]interface{}, where bool) (columns []string, values []interface{}, bindings []string) {
i := 1
for column, value := range data {
columns = append(columns, column)
switch v := value.(type) {
case string:
if where {
values = append(values, "'"+v+"'")
} else {
values = append(values, v)
}
break
case int:
values = append(values, strconv.FormatInt(int64(v), 10))
break
case float64:
values = append(values, fmt.Sprintf("%g", v))
break
case int64:
values = append(values, strconv.FormatInt(v, 10))
break
case uint64:
values = append(values, strconv.FormatUint(v, 10))
break
}
bindings = append(bindings, "$"+strconv.FormatInt(int64(i), 10))
i++
}
return
}
// InsertBatch inserts multiple rows based on transaction
func (r *DB) InsertBatch(data []map[string]interface{}) error {
builder := r.Builder
if builder.table == "" {
return fmt.Errorf(errTableCallBeforeOp)
}
txn, err := r.Sql().Begin()
if err != nil {
log.Fatal(err)
}
columns, values := prepareInsertBatch(data)
stmt, err := txn.Prepare(pq.CopyIn(builder.table, columns...))
if err != nil {
return err
}
for _, value := range values {
_, err = stmt.Exec(value...)
if err != nil {
return err
}
}
_, err = stmt.Exec()
if err != nil {
return err
}
err = stmt.Close()
if err != nil {
return err
}
err = txn.Commit()
if err != nil {
return err
}
return nil
}
// prepareInsertBatch prepares slices to split in favor of INSERT sql statement
func prepareInsertBatch(data []map[string]interface{}) (columns []string, values [][]interface{}) {
values = make([][]interface{}, len(data))
colToIdx := make(map[string]int)
i := 0
for k, v := range data {
values[k] = make([]interface{}, len(v))
for column, value := range v {
if k == 0 {
columns = append(columns, column)
// todo: don't know yet how to match them explicitly (it is bad idea, but it works well now)
colToIdx[column] = i
i++
}
switch casted := value.(type) {
case string:
values[k][colToIdx[column]] = casted
break
case int:
values[k][colToIdx[column]] = strconv.FormatInt(int64(casted), 10)
break
case float64:
values[k][colToIdx[column]] = fmt.Sprintf("%g", casted)
break
case int64:
values[k][colToIdx[column]] = strconv.FormatInt(casted, 10)
break
case uint64:
values[k][colToIdx[column]] = strconv.FormatUint(casted, 10)
break
}
}
}
return
}
// Update builds an UPDATE sql stmt with corresponding where/from clauses if stated
// returning affected rows
func (r *DB) Update(data map[string]interface{}) (int64, error) {
builder := r.Builder
if builder.table == "" {
return 0, fmt.Errorf(errTableCallBeforeOp)
}
columns, values, bindings := prepareBindings(data, false)
setVal := ""
l := len(columns)
for k, col := range columns {
setVal += col + " = " + bindings[k]
if k < l-1 {
setVal += ", "
}
}
query := "UPDATE " + r.Builder.table + " SET " + setVal
if r.Builder.from != "" {
query += " FROM " + r.Builder.from
}
r.Builder.startBindingsAt = l + 1
query += r.Builder.buildClauses()
values = append(values, prepareValues(r.Builder.whereBindings, false)...)
res, err := r.Sql().Exec(query, values...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Delete builds a DELETE stmt with corresponding where clause if stated
// returning affected rows
func (r *DB) Delete() (int64, error) {
builder := r.Builder
if builder.table == "" {
return 0, fmt.Errorf(errTableCallBeforeOp)
}
query := "DELETE FROM " + r.Builder.table
query += r.Builder.buildClauses()
res, err := r.Sql().Exec(query, prepareValues(r.Builder.whereBindings, false)...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Replace inserts data if conflicting row hasn't been found, else it will update an existing one
func (r *DB) Replace(data map[string]interface{}, conflict string) (int64, error) {
builder := r.Builder
if builder.table == "" {
return 0, fmt.Errorf(errTableCallBeforeOp)
}
columns, values, bindings := prepareBindings(data, false)
query := "INSERT INTO " + builder.table + " (" + strings.Join(columns, ", ") + ") VALUES(" + strings.Join(bindings, ", ") + ") ON CONFLICT(" + conflict + ") DO UPDATE SET "
for i, v := range columns {
columns[i] = v + " = excluded." + v
}
query += strings.Join(columns, ", ")
res, err := r.Sql().Exec(query, values...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// InTransaction executes fn passed as an argument in transaction mode
// if there are no results returned - txn will be rolled back, otherwise committed and returned
func (r *DB) InTransaction(fn func() (interface{}, error)) error {
txn, err := r.Sql().Begin()
res, err := fn()
if err != nil {
return err
}
isOk := false
switch v := res.(type) {
case int64:
if v > 0 {
isOk = true
}
break
case uint64:
if v > 0 {
isOk = true
}
break
case []map[string]interface{}:
if len(v) > 0 {
isOk = true
}
break
case map[string]interface{}:
if len(v) > 0 {
isOk = true
}
break
}
if !isOk {
return txn.Rollback()
}
err = txn.Commit()
if err != nil {
return err
}
return nil
}