-
Notifications
You must be signed in to change notification settings - Fork 19
/
utils.go
223 lines (183 loc) · 6.3 KB
/
utils.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
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.DATANODE file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package sqlstore
import (
"fmt"
"reflect"
"strconv"
"strings"
"code.vegaprotocol.io/vega/datanode/entities"
"github.com/georgysavva/scany/dbscan"
)
// A handy little helper function for building queries. Appends 'value'
// to the 'args' slice and returns a string '$N' referring to the index
// of the value in args. For example:
//
// var args []interface{}
// query = "select * from foo where id=" + nextBindVar(&args, 100)
// db.Query(query, args...)
func nextBindVar(args *[]interface{}, value interface{}) string {
*args = append(*args, value)
return "$" + strconv.Itoa(len(*args))
}
// orderAndPaginateQuery is a helper function to simplify adding ordering and pagination statements to the end of a query
// with the appropriate binding variables amd returns the query string and list of arguments to pass to the query execution handler.
func orderAndPaginateQuery(query string, orderColumns []string, pagination entities.OffsetPagination, args ...interface{}) (string, []interface{}) {
ordering := "ASC"
if pagination.Descending {
ordering = "DESC"
}
sbOrderBy := strings.Builder{}
if len(orderColumns) > 0 {
sbOrderBy.WriteString("ORDER BY")
sep := ""
for _, column := range orderColumns {
sbOrderBy.WriteString(fmt.Sprintf("%s %s %s", sep, column, ordering))
sep = ","
}
}
var paging string
if pagination.Skip != 0 {
paging = fmt.Sprintf("%sOFFSET %s ", paging, nextBindVar(&args, pagination.Skip))
}
if pagination.Limit != 0 {
paging = fmt.Sprintf("%sLIMIT %s ", paging, nextBindVar(&args, pagination.Limit))
}
query = fmt.Sprintf("%s %s %s", query, sbOrderBy.String(), paging)
return query, args
}
func orderAndPaginateWithCursor(query string, pagination entities.CursorPagination, cursors CursorQueryParameters,
args ...interface{}) (string, []interface{},
) {
var order string
whereOrAnd := "WHERE"
if strings.Contains(strings.ToUpper(query), "WHERE") {
whereOrAnd = "AND"
}
var cursor string
cursor, args = cursors.Where(args...)
if cursor != "" {
query = fmt.Sprintf("%s %s %s", query, whereOrAnd, cursor)
}
limit := calculateLimit(pagination)
if limit == 0 {
// return everything ordered by the cursor column ordered ascending
order = cursors.OrderBy()
query = fmt.Sprintf("%s ORDER BY %s", query, order)
return query, args
}
order = cursors.OrderBy()
query = fmt.Sprintf("%s ORDER BY %s", query, order)
query = fmt.Sprintf("%s LIMIT %d", query, limit)
return query, args
}
func calculateLimit(pagination entities.CursorPagination) int {
var limit int32
if pagination.HasForward() && pagination.Forward.Limit != nil {
limit = *pagination.Forward.Limit + 1
if pagination.Forward.HasCursor() {
limit = *pagination.Forward.Limit + 2 // +2 to make sure we get the previous and next cursor
}
} else if pagination.HasBackward() && pagination.Backward.Limit != nil {
limit = *pagination.Backward.Limit + 1
if pagination.Backward.HasCursor() {
limit = *pagination.Backward.Limit + 2 // +2 to make sure we get the previous and next cursor
}
}
return int(limit)
}
func extractPaginationInfo(pagination entities.CursorPagination) (Sorting, Compare, string) {
var cmp Compare
var value string
sort := ASC
if pagination.NewestFirst {
sort = DESC
}
if pagination.HasForward() {
if pagination.Forward.HasCursor() {
cmp = GE
if pagination.NewestFirst {
cmp = LE
}
value = pagination.Forward.Cursor.Value()
}
} else if pagination.HasBackward() {
sort = DESC
if pagination.NewestFirst {
sort = ASC
}
if pagination.Backward.HasCursor() {
cmp = LE
if pagination.NewestFirst {
cmp = GE
}
value = pagination.Backward.Cursor.Value()
}
}
return sort, cmp, value
}
func extractCursorFromPagination(pagination entities.CursorPagination) (cursor string) {
if pagination.HasForward() && pagination.Forward.HasCursor() {
cursor = pagination.Forward.Cursor.Value()
} else if pagination.HasBackward() && pagination.Backward.HasCursor() {
cursor = pagination.Backward.Cursor.Value()
}
return
}
// StructValueForColumn replicates some of the unexported functionality from Scanny. You pass a
// struct (or pointer to a struct), and a column name. It converts the struct field names into
// database column names in a similar way to scanny and if one matches colName, that field value
// is returned. For example
//
// type Foo struct {
// Thingy int `db:"wotsit"`
// SomethingElse int
// }
//
// val, err := StructValueForColumn(foo, "wotsit") -> 1
// val, err := StructValueForColumn(&foo, "something_else") -> 2
//
// NB - not all functionality of scanny is supported (but could be added if needed)
// - we don't support embedded structs
// - assumes the 'dbTag' is the default 'db'
func StructValueForColumn(obj any, colName string) (interface{}, error) {
structType := reflect.TypeOf(obj)
structValue := reflect.ValueOf(obj)
if structType.Kind() == reflect.Pointer {
structType = structType.Elem()
structValue = structValue.Elem()
}
if structType.Kind() != reflect.Struct {
return nil, fmt.Errorf("obj must be struct")
}
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
thisColName := field.Tag.Get("db")
if thisColName == "" {
thisColName = dbscan.SnakeCaseMapper(field.Name)
}
if thisColName == colName {
fieldValue := structValue.Field(i)
return fieldValue.Interface(), nil
}
}
return nil, fmt.Errorf("no field matching column name %s", colName)
}
func filterDateRange(query, dateColumn string, dateRange entities.DateRange, args ...interface{}) (string, []interface{}) {
if dateRange.Start != nil {
query = fmt.Sprintf("%s AND %s >= %s", query, dateColumn, nextBindVar(&args, *dateRange.Start))
}
if dateRange.End != nil {
query = fmt.Sprintf("%s AND %s < %s", query, dateColumn, nextBindVar(&args, *dateRange.End))
}
return query, args
}