generated from mrz1836/go-template
/
where_builder.go
244 lines (215 loc) · 7.29 KB
/
where_builder.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package datastore
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/bitcoin-sv/spv-wallet/engine/datastore/customtypes"
"gorm.io/gorm"
)
// whereBuilder holds a state during custom where preparation
type whereBuilder struct {
client ClientInterface
tx *gorm.DB
varNum int
}
// processConditions will process all conditions
func (builder *whereBuilder) processConditions(tx customWhereInterface, conditions map[string]interface{}, parentKey *string) {
for key, condition := range conditions {
switch {
case key == conditionAnd:
builder.processWhereAnd(tx, condition)
case key == conditionOr:
builder.processWhereOr(tx, condition)
case key == conditionGreaterThan:
builder.applyCondition(tx, *parentKey, ">", condition)
case key == conditionLessThan:
builder.applyCondition(tx, *parentKey, "<", condition)
case key == conditionGreaterThanOrEqual:
builder.applyCondition(tx, *parentKey, ">=", condition)
case key == conditionLessThanOrEqual:
builder.applyCondition(tx, *parentKey, "<=", condition)
case key == conditionExists:
builder.applyExistsCondition(tx, *parentKey, condition.(bool))
case StringInSlice(key, builder.client.GetArrayFields()):
builder.applyJSONArrayContains(tx, key, condition.(string))
case StringInSlice(key, builder.client.GetObjectFields()):
builder.applyJSONCondition(tx, key, condition)
case condition == nil:
builder.applyCondition(tx, key, "IS NULL", nil)
default:
v := reflect.ValueOf(condition)
if v.Kind() == reflect.Map {
dict := convertToDict(condition)
builder.processConditions(tx, dict, &key)
} else {
builder.applyCondition(tx, key, "=", condition)
}
}
}
}
func (builder *whereBuilder) applyCondition(tx customWhereInterface, key string, operator string, condition interface{}) {
columnName := builder.getColumnNameOrPanic(key)
if condition == nil {
tx.Where(columnName + " " + operator)
return
}
varName := builder.nextVarName()
query := fmt.Sprintf("%s %s @%s", columnName, operator, varName)
tx.Where(query, map[string]interface{}{varName: builder.formatCondition(condition)})
}
func (builder *whereBuilder) applyExistsCondition(tx customWhereInterface, key string, condition bool) {
operator := "IS NULL"
if condition {
operator = "IS NOT NULL"
}
builder.applyCondition(tx, key, operator, nil)
}
// applyJSONArrayContains will apply array condition on JSON Array field - client.GetArrayFields()
func (builder *whereBuilder) applyJSONArrayContains(tx customWhereInterface, key string, condition string) {
columnName := builder.getColumnNameOrPanic(key)
engine := builder.client.Engine()
switch engine {
case PostgreSQL:
builder.applyPostgresJSONB(tx, columnName, fmt.Sprintf(`["%s"]`, condition))
case MySQL:
varName := builder.nextVarName()
tx.Where(
fmt.Sprintf("JSON_CONTAINS(%s, CAST(@%s AS JSON))", columnName, varName),
map[string]interface{}{varName: fmt.Sprintf(`["%s"]`, condition)},
)
case SQLite:
varName := builder.nextVarName()
tx.Where(
fmt.Sprintf("EXISTS (SELECT 1 FROM json_each(%s) WHERE value = @%s)", columnName, varName),
map[string]interface{}{varName: condition},
)
case MongoDB, Empty:
panic("Database engine not supported")
default:
panic("Unknown database engine")
}
}
// applyJSONCondition will apply condition on JSON Object field - client.GetObjectFields()
func (builder *whereBuilder) applyJSONCondition(tx customWhereInterface, key string, condition interface{}) {
if isEmptyCondition(condition) {
return
}
columnName := builder.getColumnNameOrPanic(key)
engine := builder.client.Engine()
if engine == PostgreSQL {
builder.applyPostgresJSONB(tx, columnName, condition)
} else if engine == MySQL || engine == SQLite {
builder.applyJSONExtract(tx, columnName, condition)
} else {
panic("Database engine not supported")
}
}
func (builder *whereBuilder) applyPostgresJSONB(tx customWhereInterface, columnName string, condition interface{}) {
varName := builder.nextVarName()
query := fmt.Sprintf("%s::jsonb @> @%s", columnName, varName)
tx.Where(query, map[string]interface{}{varName: condition})
}
func (builder *whereBuilder) applyJSONExtract(tx customWhereInterface, columnName string, condition interface{}) {
dict := convertToDict(condition)
for key, value := range dict {
keyVarName := builder.nextVarName()
valueVarName := builder.nextVarName()
query := fmt.Sprintf("JSON_EXTRACT(%s, @%s) = @%s", columnName, keyVarName, valueVarName)
tx.Where(query, map[string]interface{}{
keyVarName: fmt.Sprintf("$.%s", key),
valueVarName: value,
})
}
}
func (builder *whereBuilder) processWhereAnd(tx customWhereInterface, condition interface{}) {
accumulator := &txAccumulator{
WhereClauses: make([]string, 0),
Vars: make(map[string]interface{}),
}
for _, c := range condition.([]map[string]interface{}) {
builder.processConditions(accumulator, c, nil)
}
query := " ( " + strings.Join(accumulator.WhereClauses, " AND ") + " ) "
if len(accumulator.Vars) > 0 {
tx.Where(query, accumulator.Vars)
} else {
tx.Where(query)
}
}
func (builder *whereBuilder) processWhereOr(tx customWhereInterface, condition interface{}) {
or := make([]string, 0)
orVars := make(map[string]interface{})
for _, cond := range condition.([]map[string]interface{}) {
statement := make([]string, 0)
accumulator := &txAccumulator{
WhereClauses: make([]string, 0),
Vars: make(map[string]interface{}),
}
builder.processConditions(accumulator, cond, nil)
statement = append(statement, accumulator.WhereClauses...)
for varName, varValue := range accumulator.Vars {
orVars[varName] = varValue
}
or = append(or, strings.Join(statement[:], " AND "))
}
query := " ( (" + strings.Join(or, ") OR (") + ") ) "
if len(orVars) > 0 {
tx.Where(query, orVars)
} else {
tx.Where(query)
}
}
func (builder *whereBuilder) nextVarName() string {
varName := fmt.Sprintf("var%d", builder.varNum)
builder.varNum++
return varName
}
func (builder *whereBuilder) getColumnNameOrPanic(key string) string {
columnName, ok := GetColumnName(key, builder.tx.Statement.Model, builder.tx)
if !ok {
panic(fmt.Errorf("column %s does not exist in the model", key))
}
return columnName
}
func (builder *whereBuilder) formatCondition(condition interface{}) interface{} {
if nullType, ok := condition.(customtypes.NullTime); ok {
return builder.formatNullTime(nullType)
}
return condition
}
func (builder *whereBuilder) formatNullTime(condition customtypes.NullTime) interface{} {
if !condition.Valid {
return nil
}
engine := builder.client.Engine()
if engine == MySQL {
return condition.Time.Format("2006-01-02 15:04:05")
}
if engine == PostgreSQL {
return condition.Time.Format("2006-01-02T15:04:05Z07:00")
}
return condition.Time.Format("2006-01-02T15:04:05.000Z")
}
func convertToDict(object interface{}) map[string]interface{} {
if converted, ok := object.(map[string]interface{}); ok {
return converted
}
vJSON, _ := json.Marshal(object)
var converted map[string]interface{}
_ = json.Unmarshal(vJSON, &converted)
return converted
}
func isEmptyCondition(condition interface{}) bool {
val := reflect.ValueOf(condition)
for ; val.Kind() == reflect.Ptr; val = val.Elem() {
if val.IsNil() {
return true
}
}
kind := val.Kind()
if kind == reflect.Map || kind == reflect.Slice {
return val.Len() == 0
}
return false
}