-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplequery.go
More file actions
88 lines (81 loc) · 1.8 KB
/
Copy pathsimplequery.go
File metadata and controls
88 lines (81 loc) · 1.8 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
package click
import (
"errors"
"time"
)
type SimpleQuery struct {
IsTimeSeriesQuery bool
TimeColumn Column
GranularityFunction string
StartTime time.Time
EndTime time.Time
Select []Expression
From string // From is table name
Where Expression
GroupBy []Expression
OrderBy []Expression
Having Expression
Limit int // Limit is valid only with positive values
Offset int
}
func (q SimpleQuery) Build() (SelectQuery, error) {
b := SelectBuilder{}
if len(q.Select) == 0 {
return nil, errors.New("no selects")
}
b.Select(q.Select...)
if q.From == "" {
return nil, errors.New("no from")
}
b.From(Table(q.From))
if q.Where != nil {
b.Where(q.Where)
}
if len(q.GroupBy) > 0 {
b.GroupBy(q.GroupBy...)
}
if q.Having != nil {
b.Having(q.Having)
}
if len(q.OrderBy) > 0 {
b.OrderBy(q.OrderBy...)
}
if q.Limit > 0 {
b.Limit(q.Limit)
}
if q.Offset > 0 {
b.Offset(q.Offset)
}
if q.IsTimeSeriesQuery {
// time series query:
// - select & group-by & order-by: add time granularity
// - where: add time range filter
// add time granularity
timeOffset := Fn(q.GranularityFunction, q.TimeColumn)
b.Select(timeOffset)
b.GroupBy(timeOffset)
b.OrderBy(timeOffset)
// add time range filter
var wheres []Expression
if q.Where != nil {
wheres = append(wheres, q.Where)
}
if !q.StartTime.IsZero() {
wheres = append(wheres, GreaterOrEqualThan(q.TimeColumn, LiteralExpression(q.StartTime)))
}
if !q.EndTime.IsZero() {
wheres = append(wheres, LessThan(q.TimeColumn, LiteralExpression(q.EndTime)))
}
if len(wheres) > 0 {
b.Where(And(wheres...))
}
}
return sealedSelect(b), nil
}
func (q SimpleQuery) BuildString() (string, error) {
query, err := q.Build()
if err != nil {
return "", err
}
return query.String(), nil
}