-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueryBuilder.go
109 lines (100 loc) · 2.57 KB
/
queryBuilder.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
package metrics
import (
"errors"
"fmt"
"strings"
)
var (
errQueryIsNotDefined = errors.New("query is not defined")
errLabelIsNotDefined = errors.New("label is not defined")
)
// queryBuilder provides making of the query to ClickHouse
type queryBuilder struct {
aq query
c *Config
q string
}
// make retruns query for ClickHouse
func (q *queryBuilder) make() (string, error) {
if err := q.validateQuery(); err != nil {
return "", err
}
queryReq := "SELECT "
switch q.aq.Type() {
case AggregationQueryType:
action, err := q.checkAction()
if err != nil {
return "", err
}
queryReq += fmt.Sprintf("%s(values[indexOf(names, '%s')]) ", action, q.aq.GetLabel())
case ListQueryType:
queryReq += fmt.Sprintf("values[indexOf(names, '%s')] ", q.aq.GetLabel())
}
queryReq += fmt.Sprintf("AS result FROM %s ", q.c.DBName)
if len(q.aq.GetEntities()) > 0 {
queryReq += q.makeEntitiesQuery()
}
if q.aq.GetRange() != "" {
queryReq += q.makeRangeQuery()
}
return queryReq, nil
}
// validateQuery provides validation of the query
func (q *queryBuilder) validateQuery() error {
if q.aq == nil {
return errQueryIsNotDefined
}
if q.aq.GetLabel() == "" {
return errLabelIsNotDefined
}
return nil
}
func (q *queryBuilder) makeEntitiesQuery() string {
entities := q.aq.GetEntities()
if len(entities) == 1 {
return fmt.Sprintf(" WHERE entity = '%s'", entities[0])
}
res := " WHERE ( "
for i := 0; i < len(entities); i++ {
res += fmt.Sprintf("entity = '%s' ", entities[i])
if i+1 != len(entities) {
res += "OR "
}
}
q.q = res + ")"
return q.q
}
// makeRangeQuery retruns query if range is defined
func (q *queryBuilder) makeRangeQuery() string {
var res string
defer func(value string) {
q.q += res
}(res)
if strings.Contains(q.q, "WHERE") {
res = fmt.Sprintf(" AND (datetime > (%s))", constructDateRange(q.aq.GetRange()))
return res
}
res = fmt.Sprintf("WHERE datetime > (%s)", constructDateRange(q.aq.GetRange()))
return res
}
// checkAction return error if action function is not defined
func (q *queryBuilder) checkAction() (string, error) {
res, ok := actions[q.aq.GetAction()]
if !ok {
return "", errActionIsNotFound
}
return res, nil
}
// constructDateRange provides constructing of the range
// to ClickHouse format. In the case of invalid input
// its return default range within hour
func constructDateRange(r string) string {
resp := "now()"
for k, v := range dateRanges {
if strings.HasSuffix(r, k) {
value := r[:len(r)-1]
return resp + fmt.Sprintf(" - %s(%s)", v, value)
}
}
return fmt.Sprintf("%s - toIntervalHour(1)", resp)
}