-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhere.go
More file actions
351 lines (307 loc) · 9.77 KB
/
where.go
File metadata and controls
351 lines (307 loc) · 9.77 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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package gormx
import (
"fmt"
"strings"
)
// RangeMode defines the type of range query
type RangeMode string
const (
// RangeModeClosed represents [A, B] - both inclusive (default)
RangeModeClosed RangeMode = "closed"
// RangeModeOpen represents (A, B) - both exclusive
RangeModeOpen RangeMode = "open"
// RangeModeLeftClosed represents [A, B) - left inclusive, right exclusive
RangeModeLeftClosed RangeMode = "left_closed"
// RangeModeRightClosed represents (A, B] - left exclusive, right inclusive
RangeModeRightClosed RangeMode = "right_closed"
)
// WhereCondition is a type constraint for where conditions.
// It can be either map[any]any or *Where.
type WhereCondition interface {
map[any]any | *Where
}
// ToWhere converts a where condition to *Where.
// If the input is already *Where, return it directly.
// If the input is map[any]any, convert it to *Where.
func ToWhere[T WhereCondition](condition T) *Where {
var result any = condition
// If it's already *Where, return directly
if w, ok := result.(*Where); ok {
return w
}
// If it's map[any]any, convert to *Where
if m, ok := result.(map[any]any); ok {
where := NewWhere()
for k, v := range m {
if key, ok := k.(string); ok {
where.Set(key, v)
}
}
return where
}
// Should not reach here due to type constraint
return nil
}
// WhereOne is the where one.
type WhereOne struct {
Key string
Value interface{}
// IsEqual => =
IsEqual bool
// IsNotEqual => !=
IsNotEqual bool
// IsFuzzy => ILike
IsFuzzy bool
// IsIn => in (?)
IsIn bool
// IsNotIn => not in (?)
IsNotIn bool
// IsPlain => plain
IsPlain bool
// IsRange => BETWEEN ? AND ? (or other range modes)
IsRange bool
rangeStart interface{}
rangeEnd interface{}
rangeMode RangeMode // Range mode: closed, open, left_closed, right_closed
// IsGreaterThan => >
IsGreaterThan bool
// IsLessThan => <
IsLessThan bool
// IsGreaterOrEqualThan => >=
IsGreaterOrEqualThan bool
// IsLessOrEqualThan => <=
IsLessOrEqualThan bool
// IsFullTextSearch => ILike (field1) OR ILike (field2) OR ...
IsFullTextSearch bool
FullTextSearchFields []string
}
// Where is the where.
type Where struct {
Items []WhereOne
//
FullTextSearchFields []string
}
// SetWhereOptions is the options for SetWhere.
type SetWhereOptions struct {
IsEqual bool
IsNotEqual bool
IsFuzzy bool
IsIn bool
IsNotIn bool
IsPlain bool
IsRange bool
RangeMode RangeMode // Range mode: closed (default), open, left_closed, right_closed
IsGreaterThan bool
IsLessThan bool
IsGreaterOrEqualThan bool
IsLessOrEqualThan bool
IsFullTextSearch bool
FullTextSearchFields []string
}
// NewWhere returns a new where.
func NewWhere() *Where {
return &Where{}
}
// Set sets a where, if exists, update.
func (w *Where) Set(key string, value interface{}, opts ...*SetWhereOptions) {
// @TODO cannot real update
_, ok := w.Get(key)
if ok {
w.Del(key)
}
w.Add(key, value, opts...)
}
// Add adds a where, if exists, append.
func (w *Where) Add(key string, value interface{}, opts ...*SetWhereOptions) {
item := WhereOne{
Key: key,
Value: value,
}
for _, opt := range opts {
if opt == nil {
continue
}
item.IsFuzzy = opt.IsFuzzy
item.IsEqual = opt.IsEqual
item.IsNotEqual = opt.IsNotEqual
item.IsIn = opt.IsIn
item.IsNotIn = opt.IsNotIn
item.IsPlain = opt.IsPlain
item.IsRange = opt.IsRange
item.IsGreaterThan = opt.IsGreaterThan
item.IsLessThan = opt.IsLessThan
item.IsGreaterOrEqualThan = opt.IsGreaterOrEqualThan
item.IsLessOrEqualThan = opt.IsLessOrEqualThan
item.IsFullTextSearch = opt.IsFullTextSearch
item.FullTextSearchFields = opt.FullTextSearchFields
// Handle range values
if opt.IsRange {
// Set range mode (default to closed if not specified)
if opt.RangeMode == "" {
item.rangeMode = RangeModeClosed
} else {
item.rangeMode = opt.RangeMode
}
// Value should be an array [start, end]
if arr, ok := value.([]interface{}); ok && len(arr) >= 2 {
item.rangeStart = arr[0]
item.rangeEnd = arr[1]
} else if arr, ok := value.([]string); ok && len(arr) >= 2 {
item.rangeStart = arr[0]
item.rangeEnd = arr[1]
} else if arr, ok := value.([]int); ok && len(arr) >= 2 {
item.rangeStart = arr[0]
item.rangeEnd = arr[1]
} else if arr, ok := value.([]int64); ok && len(arr) >= 2 {
item.rangeStart = arr[0]
item.rangeEnd = arr[1]
} else if arr, ok := value.([]float64); ok && len(arr) >= 2 {
item.rangeStart = arr[0]
item.rangeEnd = arr[1]
}
}
}
w.Items = append(w.Items, item)
}
// Get gets a where.
func (w *Where) Get(key string) (interface{}, bool) {
for _, v := range w.Items {
if v.Key == key {
return v.Value, true
}
}
return "", false
}
// Del deletes a where.
func (w *Where) Del(key string) {
for i, v := range w.Items {
if v.Key == key {
w.Items = append(w.Items[:i], w.Items[i+1:]...)
return
}
}
}
// Length returns the length of the wheres.
func (w *Where) Length() int {
return len(w.Items)
}
// Build builds the wheres.
func (w *Where) Build() (query string, args []interface{}, err error) {
whereClauses := []string{}
whereValues := []interface{}{}
for _, item := range w.Items {
// @TODO built-in keywords
if item.Key == "q" {
item.IsFullTextSearch = true
item.FullTextSearchFields = w.FullTextSearchFields
}
// @TODO full text search search keyword
if item.IsFullTextSearch {
// ignore if no fields
if len(item.FullTextSearchFields) == 0 {
// return "", nil, fmt.Errorf("FullTextSearchFields is required when IsFullTextSearch is true (key: %s)", item.Key)
// continue
if len(w.FullTextSearchFields) == 0 {
// return "", nil, fmt.Errorf("FullTextSearchFields is required when IsFullTextSearch is true (key: %s)", item.Key)
continue
}
item.FullTextSearchFields = w.FullTextSearchFields
}
keyword, v := item.Value.(string)
if !v {
return "", nil, fmt.Errorf("value must be string when IsFullTextSearch is true (key: %s)", item.Key)
}
// @TODO
keywordExtract := strings.Replace(keyword, ":*", "", 1)
//
keywordFuzzy := fmt.Sprintf("%%%s%%", keywordExtract)
qs := []string{}
args := []interface{}{}
fields := item.FullTextSearchFields
for _, field := range fields {
qs = append(qs, fmt.Sprintf("%s ILike ?", field))
args = append(args, keywordFuzzy)
}
query := strings.Join(qs, " OR ")
whereClauses = append(whereClauses, fmt.Sprintf("(%s)", query))
whereValues = append(whereValues, args...)
} else {
if item.IsFuzzy {
whereClauses = append(whereClauses, fmt.Sprintf("%s ILike ?", item.Key))
whereValues = append(whereValues, fmt.Sprintf("%%%s%%", item.Value))
} else if item.IsEqual {
whereClauses = append(whereClauses, fmt.Sprintf("%s = ?", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsNotEqual {
whereClauses = append(whereClauses, fmt.Sprintf("%s != ?", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsIn {
whereClauses = append(whereClauses, fmt.Sprintf("%s in (?)", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsNotIn {
whereClauses = append(whereClauses, fmt.Sprintf("%s not in (?)", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsRange {
// Generate SQL based on range mode
switch item.rangeMode {
case RangeModeOpen:
// (A, B): field > A AND field < B
whereClauses = append(whereClauses, fmt.Sprintf("(%s > ? AND %s < ?)", item.Key, item.Key))
whereValues = append(whereValues, item.rangeStart, item.rangeEnd)
case RangeModeLeftClosed:
// [A, B): field >= A AND field < B
whereClauses = append(whereClauses, fmt.Sprintf("(%s >= ? AND %s < ?)", item.Key, item.Key))
whereValues = append(whereValues, item.rangeStart, item.rangeEnd)
case RangeModeRightClosed:
// (A, B]: field > A AND field <= B
whereClauses = append(whereClauses, fmt.Sprintf("(%s > ? AND %s <= ?)", item.Key, item.Key))
whereValues = append(whereValues, item.rangeStart, item.rangeEnd)
default:
// RangeModeClosed (default): [A, B]: field BETWEEN A AND B
whereClauses = append(whereClauses, fmt.Sprintf("%s BETWEEN ? AND ?", item.Key))
whereValues = append(whereValues, item.rangeStart, item.rangeEnd)
}
} else if item.IsGreaterThan {
whereClauses = append(whereClauses, fmt.Sprintf("%s > ?", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsLessThan {
whereClauses = append(whereClauses, fmt.Sprintf("%s < ?", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsGreaterOrEqualThan {
whereClauses = append(whereClauses, fmt.Sprintf("%s >= ?", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsLessOrEqualThan {
whereClauses = append(whereClauses, fmt.Sprintf("%s <= ?", item.Key))
whereValues = append(whereValues, item.Value)
} else if item.IsPlain {
whereClauses = append(whereClauses, fmt.Sprintf("(%s)", item.Key))
if v, ok := item.Value.([]any); ok {
whereValues = append(whereValues, v...)
} else {
whereValues = append(whereValues, item.Value)
}
} else {
whereClauses = append(whereClauses, fmt.Sprintf("%s = ?", item.Key))
whereValues = append(whereValues, item.Value)
}
}
}
whereClause := strings.Join(whereClauses, " AND ")
return whereClause, whereValues, nil
}
// Debug prints the wheres.
func (w *Where) Debug() {
for _, item := range w.Items {
var fuzzy string
if item.IsFuzzy {
fuzzy = "Fuzzy"
} else {
fuzzy = "Extract"
}
fmt.Printf("[where] %s %s %s\n", item.Key, item.Value, fuzzy)
}
}
// Reset resets the wheres.
func (w *Where) Reset() {
w.Items = []WhereOne{}
}