-
Notifications
You must be signed in to change notification settings - Fork 532
/
parsers.go
185 lines (147 loc) · 4.12 KB
/
parsers.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
package postgres
import (
"fmt"
"strings"
"github.com/ignite/cli/v28/ignite/pkg/cosmostxcollector/query"
"github.com/ignite/cli/v28/ignite/pkg/errors"
)
const (
eventAttrPrefix = "attribute."
sqlSelectAll = "SELECT *"
sqlWhereTrue = "WHERE true"
tplSelectEventsSQL = `
SELECT event.id, event.index, event.tx_hash, event.type, event.created_at
FROM event INNER JOIN tx ON event.tx_hash = tx.hash
%s
ORDER BY tx.height, tx.index, event.index
`
tplSelectEventsWithAttrSQL = `
SELECT DISTINCT events.*
FROM (
SELECT event.id, event.index, event.tx_hash, event.type, event.created_at
FROM event
INNER JOIN tx ON event.tx_hash = tx.hash
INNER JOIN attribute ON event.id = attribute.event_id
%s
ORDER BY tx.height, tx.index, event.index
) AS events
`
)
var (
ErrUnknownEntity = errors.New("unknown query entity")
ErrInvalidSortOrder = errors.New("invalid query sort order")
)
// TODO: Use an SQL builder/parser to build the queries?
func parseQuery(q query.Query) (string, error) {
sections := []string{
// Add SELECT
parseFields(q.Fields()),
// Add FROM
parseFrom(q),
}
// Add WHERE
sections = append(sections, parseFilters(q.Filters()))
// Add ORDER BY
sortBy, err := parseSortBy(q.SortBy())
if err != nil {
return "", err
}
if sortBy != "" {
sections = append(sections, sortBy)
}
// Add LIMIT/OFFSET
if s, ok := parsePaging(q); ok {
sections = append(sections, s)
}
return strings.Join(sections, " "), nil
}
func parseEventQuery(q query.EventQuery) string {
sql := tplSelectEventsSQL
filters := q.Filters()
// Check if any of the filters references an event attribute
// and if so add the required INNER JOIN to the raw SQL query.
// The JOIN is not present by default to improve events queries.
for _, f := range filters {
if strings.HasPrefix(f.Field(), eventAttrPrefix) {
sql = tplSelectEventsWithAttrSQL
break
}
}
// Add SELECT
sections := []string{
fmt.Sprintf(sql, parseFilters(q.Filters())),
}
// Add LIMIT/OFFSET
if s, ok := parsePaging(q); ok {
sections = append(sections, s)
}
return strings.Join(sections, " ")
}
func parseFields(fields []string) string {
if len(fields) == 0 {
// By default select all fields
return sqlSelectAll
}
return fmt.Sprintf("SELECT DISTINCT %s", strings.Join(fields, ", "))
}
func parseFrom(q query.Query) string {
// Init the function call placeholders for the arguments
args := q.Args()
placeholders := make([]string, len(args))
for i := range args {
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
// When there are arguments it means it is a postgres function
// call otherwise the call is treated as a table or view.
s := fmt.Sprintf("FROM %s", q.Name())
if len(placeholders) > 0 {
s = fmt.Sprintf("%s(%s)", s, strings.Join(placeholders, ", "))
}
return s
}
func parseFilters(filters []query.Filter) string {
if len(filters) == 0 {
return sqlWhereTrue
}
pos := 0
items := make([]string, len(filters))
for i, f := range filters {
// Render the filter, so it can be applied to the query
expr := f.String()
// When the filter has a value replace the "?" by a positional
// postgres placeholder like "$1", "$2", and so on
if v := f.Value(); v != nil {
index := strings.LastIndex(expr, filterPlaceholder)
expr = expr[:index] + fmt.Sprintf("$%d", pos+1) + expr[index+1:]
pos++
}
items[i] = expr
}
return fmt.Sprintf("WHERE %s", strings.Join(items, " AND "))
}
func parseSortBy(sortInfo []query.SortBy) (string, error) {
if len(sortInfo) == 0 {
return "", nil
}
var items []string
for _, s := range sortInfo {
if s.Order != query.SortOrderAsc && s.Order != query.SortOrderDesc {
return "", ErrInvalidSortOrder
}
items = append(items, fmt.Sprintf("%s %s", s.Field, s.Order))
}
return fmt.Sprintf("ORDER BY %s", strings.Join(items, ", ")), nil
}
func parsePaging(q query.Pager) (string, bool) {
if !q.IsPagingEnabled() {
return "", false
}
// Get the current page and make sure that the page number is valid
page := q.AtPage()
if page == 0 {
page = 1
}
limit := q.PageSize()
offset := limit * (page - 1)
return fmt.Sprintf("LIMIT %d OFFSET %d", limit, offset), true
}