-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.go
72 lines (61 loc) · 1.58 KB
/
helpers.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
package clickhouse
import (
"errors"
"fmt"
"net/url"
"strings"
)
type (
// Column name
Column string
// Columns array, order is important
Columns []string
// Row value
Row []interface{}
// Rows array or values
Rows []Row
Array []interface{}
VisitParamsString map[string]interface{}
StringArray []string
)
// NewQuery creates new query from query string and args
func NewQuery(stmt string, args ...interface{}) Query {
return Query{
Stmt: stmt,
args: args,
params: url.Values{},
}
}
// BuildInsert create new query from columns and one row
func BuildInsert(tbl string, cols Columns, row Row) (Query, error) {
return BuildMultiInsert(tbl, cols, Rows{row})
}
// BuildMultiInsert create new bulk query from columns and rows
func BuildMultiInsert(tbl string, cols Columns, rows Rows) (Query, error) {
var (
stmt string
args []interface{}
)
if len(cols) == 0 || len(rows) == 0 {
return Query{}, errors.New("rows and cols cannot be empty")
}
colCount := len(cols)
rowCount := len(rows)
args = make([]interface{}, colCount*rowCount)
argi := 0
for _, row := range rows {
if len(row) != colCount {
return Query{}, errors.New("Amount of row items does not match column count")
}
for _, val := range row {
args[argi] = val
argi++
}
}
binds := strings.Repeat(":value:,", colCount)
binds = "(" + binds[:len(binds)-1] + "),"
batch := strings.Repeat(binds, rowCount)
batch = batch[:len(batch)-1]
stmt = fmt.Sprintf("INSERT INTO %s (%s) VALUES %s", tbl, strings.Join(cols, ","), batch)
return NewQuery(stmt, args...), nil
}