-
Notifications
You must be signed in to change notification settings - Fork 2
/
conditions.go
438 lines (384 loc) · 13.2 KB
/
conditions.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright 2016 NDP Systèmes. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package models
import (
"fmt"
"reflect"
"strings"
"github.com/labneco/doxa/doxa/models/operator"
)
// ExprSep define the expression separation
const (
ExprSep = "."
sqlSep = "__"
)
type predicate struct {
exprs []string
operator operator.Operator
arg interface{}
cond *Condition
isOr bool
isNot bool
isCond bool
}
// A Condition represents a WHERE clause of an SQL query.
type Condition struct {
predicates []predicate
}
// newCondition returns a new condition struct
func newCondition() *Condition {
c := &Condition{}
return c
}
// And completes the current condition with a simple AND clause : c.And().nextCond => c AND nextCond.
//
// No brackets are added so AND precedence over OR applies.
func (c Condition) And() *ConditionStart {
res := ConditionStart{cond: c}
return &res
}
// AndCond completes the current condition with the given cond as an AND clause
// between brackets : c.And(cond) => (c) AND (cond)
func (c Condition) AndCond(cond *Condition) *Condition {
if !cond.IsEmpty() {
c.predicates = append(c.predicates, predicate{cond: cond, isCond: true})
}
return &c
}
// AndNot completes the current condition with a simple AND NOT clause :
// c.AndNot().nextCond => c AND NOT nextCond
//
// No brackets are added so AND precedence over OR applies.
func (c Condition) AndNot() *ConditionStart {
res := ConditionStart{cond: c}
res.nextIsNot = true
return &res
}
// AndNotCond completes the current condition with an AND NOT clause between
// brackets : c.AndNot(cond) => (c) AND NOT (cond)
func (c Condition) AndNotCond(cond *Condition) *Condition {
c.predicates = append(c.predicates, predicate{cond: cond, isCond: true, isNot: true})
return &c
}
// Or completes the current condition both with a simple OR clause : c.Or().nextCond => c OR nextCond
//
// No brackets are added so AND precedence over OR applies.
func (c Condition) Or() *ConditionStart {
res := ConditionStart{cond: c}
res.nextIsOr = true
return &res
}
// OrCond completes the current condition both with an OR clause between
// brackets : c.Or(cond) => (c) OR (cond)
func (c Condition) OrCond(cond *Condition) *Condition {
if !cond.IsEmpty() {
c.predicates = append(c.predicates, predicate{cond: cond, isCond: true, isOr: true})
}
return &c
}
// OrNot completes the current condition both with a simple OR NOT clause : c.OrNot().nextCond => c OR NOT nextCond
//
// No brackets are added so AND precedence over OR applies.
func (c Condition) OrNot() *ConditionStart {
res := ConditionStart{cond: c}
res.nextIsNot = true
res.nextIsOr = true
return &res
}
// OrNotCond completes the current condition both with an OR NOT clause between
// brackets : c.OrNot(cond) => (c) OR NOT (cond)
func (c Condition) OrNotCond(cond *Condition) *Condition {
c.predicates = append(c.predicates, predicate{cond: cond, isCond: true, isOr: true, isNot: true})
return &c
}
// Serialize returns the condition as a list which mimics Odoo domains.
func (c Condition) Serialize() []interface{} {
return serializePredicates(c.predicates)
}
// HasField returns true if the given field is in at least one of the
// the predicates of this condition or of one of its nested conditions.
//
func (c Condition) HasField(f *Field) bool {
for _, pred := range c.predicates {
if len(pred.exprs) > 0 {
if strings.Join(jsonizeExpr(f.model, pred.exprs), ExprSep) == f.json {
return true
}
}
if pred.cond != nil && pred.cond.HasField(f) {
return true
}
}
return false
}
// String method for the Condition. Recursively print all predicates.
func (c Condition) String() string {
var res string
for _, p := range c.predicates {
if p.isOr {
res += "OR "
} else {
res += "AND "
}
if p.isNot {
res += "NOT "
}
if p.isCond {
res += fmt.Sprintf("(\n%s\n)\n", p.cond.String())
continue
}
res += fmt.Sprintf("%s %s %v\n", strings.Join(p.exprs, ExprSep), p.operator, p.arg)
}
return res
}
// Underlying returns the underlying Condition (i.e. itself)
func (c Condition) Underlying() *Condition {
return &c
}
var _ Conditioner = Condition{}
// A ConditionStart is an object representing a Condition when
// we just added a logical operator (AND, OR, ...) and we are
// about to add a predicate.
type ConditionStart struct {
cond Condition
nextIsOr bool
nextIsNot bool
}
// Field adds a field path (dot separated) to this condition
func (cs ConditionStart) Field(name string) *ConditionField {
newExprs := strings.Split(name, ExprSep)
cp := ConditionField{cs: cs}
cp.exprs = append(cp.exprs, newExprs...)
return &cp
}
// FilteredOn adds a condition with a table join on the given field and
// filters the result with the given condition
func (cs ConditionStart) FilteredOn(field string, condition *Condition) *Condition {
res := cs.cond
for i, p := range condition.predicates {
condition.predicates[i].exprs = append([]string{field}, p.exprs...)
}
condition.predicates[0].isOr = cs.nextIsOr
condition.predicates[0].isNot = cs.nextIsNot
res.predicates = append(res.predicates, condition.predicates...)
return &res
}
// A ConditionField is a partial Condition when we have set
// a field name in a predicate and are about to add an operator.
type ConditionField struct {
cs ConditionStart
exprs []string
}
// FieldName returns the field name of this ConditionField
func (c ConditionField) FieldName() FieldName {
return FieldName(strings.Join(c.exprs, ExprSep))
}
// String method for ConditionField
func (c ConditionField) String() string {
return FieldName(strings.Join(c.exprs, ExprSep)).String()
}
var _ FieldNamer = ConditionField{}
// AddOperator adds a condition value to the condition with the given operator and data
// If multi is true, a recordset will be converted into a slice of int64
// otherwise, it will return an int64 and panic if the recordset is not
// a singleton.
//
// This method is low level and should be avoided. Use operator methods such as Equals()
// instead.
func (c ConditionField) AddOperator(op operator.Operator, data interface{}) *Condition {
cond := c.cs.cond
data = sanitizeArgs(data, op.IsMulti())
if data != nil && op.IsMulti() && reflect.ValueOf(data).Kind() == reflect.Slice && reflect.ValueOf(data).Len() == 0 {
return &cond
}
cond.predicates = append(cond.predicates, predicate{
exprs: c.exprs,
operator: op,
arg: data,
isNot: c.cs.nextIsNot,
isOr: c.cs.nextIsOr,
})
return &cond
}
// sanitizeArgs returns the given args suitable for SQL query
// In particular, retrieves the ids of a recordset if args is one.
// If multi is true, a recordset will be converted into a slice of int64
// otherwise, it will return an int64 and panic if the recordset is not
// a singleton
func sanitizeArgs(args interface{}, multi bool) interface{} {
if rs, ok := args.(RecordSet); ok {
if multi {
return rs.Ids()
}
if len(rs.Ids()) > 1 {
log.Panic("Trying to extract a single ID from a non singleton", "args", args)
}
if len(rs.Ids()) == 0 {
return nil
}
return rs.Ids()[0]
}
return args
}
// Equals appends the '=' operator to the current Condition
func (c ConditionField) Equals(data interface{}) *Condition {
return c.AddOperator(operator.Equals, data)
}
// NotEquals appends the '!=' operator to the current Condition
func (c ConditionField) NotEquals(data interface{}) *Condition {
return c.AddOperator(operator.NotEquals, data)
}
// Greater appends the '>' operator to the current Condition
func (c ConditionField) Greater(data interface{}) *Condition {
return c.AddOperator(operator.Greater, data)
}
// GreaterOrEqual appends the '>=' operator to the current Condition
func (c ConditionField) GreaterOrEqual(data interface{}) *Condition {
return c.AddOperator(operator.GreaterOrEqual, data)
}
// Lower appends the '<' operator to the current Condition
func (c ConditionField) Lower(data interface{}) *Condition {
return c.AddOperator(operator.Lower, data)
}
// LowerOrEqual appends the '<=' operator to the current Condition
func (c ConditionField) LowerOrEqual(data interface{}) *Condition {
return c.AddOperator(operator.LowerOrEqual, data)
}
// Like appends the 'LIKE' operator to the current Condition
func (c ConditionField) Like(data interface{}) *Condition {
return c.AddOperator(operator.Like, data)
}
// ILike appends the 'ILIKE' operator to the current Condition
func (c ConditionField) ILike(data interface{}) *Condition {
return c.AddOperator(operator.ILike, data)
}
// Contains appends the 'LIKE %%' operator to the current Condition
func (c ConditionField) Contains(data interface{}) *Condition {
return c.AddOperator(operator.Contains, data)
}
// NotContains appends the 'NOT LIKE %%' operator to the current Condition
func (c ConditionField) NotContains(data interface{}) *Condition {
return c.AddOperator(operator.NotContains, data)
}
// IContains appends the 'ILIKE %%' operator to the current Condition
func (c ConditionField) IContains(data interface{}) *Condition {
return c.AddOperator(operator.IContains, data)
}
// NotIContains appends the 'NOT ILIKE %%' operator to the current Condition
func (c ConditionField) NotIContains(data interface{}) *Condition {
return c.AddOperator(operator.NotIContains, data)
}
// In appends the 'IN' operator to the current Condition
func (c ConditionField) In(data interface{}) *Condition {
return c.AddOperator(operator.In, data)
}
// NotIn appends the 'NOT IN' operator to the current Condition
func (c ConditionField) NotIn(data interface{}) *Condition {
return c.AddOperator(operator.NotIn, data)
}
// ChildOf appends the 'child of' operator to the current Condition
func (c ConditionField) ChildOf(data interface{}) *Condition {
return c.AddOperator(operator.ChildOf, data)
}
// IsNull checks if the current condition field is null
func (c ConditionField) IsNull() *Condition {
return c.AddOperator(operator.Equals, nil)
}
// IsNotNull checks if the current condition field is not null
func (c ConditionField) IsNotNull() *Condition {
return c.AddOperator(operator.NotEquals, nil)
}
// IsEmpty check the condition arguments are empty or not.
func (c *Condition) IsEmpty() bool {
switch {
case c == nil:
return false
case len(c.predicates) == 0:
return true
case len(c.predicates) == 1 && c.predicates[0].cond.IsEmpty():
return true
}
return false
}
// getAllExpressions returns a list of all exprs used in this condition,
// and recursively in all subconditions.
// Expressions are given in field json format
func (c Condition) getAllExpressions(mi *Model) [][]string {
var res [][]string
for _, p := range c.predicates {
res = append(res, jsonizeExpr(mi, p.exprs))
if p.cond != nil {
res = append(res, p.cond.getAllExpressions(mi)...)
}
}
return res
}
// substituteExprs recursively replaces condition exprs that match substs keys
// with the corresponding substs values.
func (c *Condition) substituteExprs(mi *Model, substs map[string][]string) {
for i, p := range c.predicates {
for k, v := range substs {
if len(p.exprs) > 0 && strings.Join(jsonizeExpr(mi, p.exprs), ExprSep) == k {
c.predicates[i].exprs = v
}
}
if p.cond != nil {
p.cond.substituteExprs(mi, substs)
}
}
}
// substituteChildOfOperator recursively replaces in the condition the
// predicates with ChildOf operator by the predicates to actually execute.
func (c *Condition) substituteChildOfOperator(rc *RecordCollection) {
for i, p := range c.predicates {
if p.cond != nil {
p.cond.substituteChildOfOperator(rc)
}
if p.operator != operator.ChildOf {
continue
}
recModel := rc.model.getRelatedModelInfo(strings.Join(p.exprs, ExprSep))
if !recModel.hasParentField() {
// If we have no parent field, then we fetch only the "parent" record
c.predicates[i].operator = operator.Equals
continue
}
var parentIds []int64
rc.Env().Cr().Select(&parentIds, adapters[db.DriverName()].childrenIdsQuery(recModel.tableName), p.arg)
c.predicates[i].operator = operator.In
c.predicates[i].arg = parentIds
}
}
// evaluateArgFunctions recursively evaluates all args in the queries that are
// functions and substitute it with the result.
func (c *Condition) evaluateArgFunctions(rc *RecordCollection) {
for i, p := range c.predicates {
if p.cond != nil {
p.cond.evaluateArgFunctions(rc)
}
fnctVal := reflect.ValueOf(p.arg)
if fnctVal.Kind() != reflect.Func {
continue
}
firstArgType := fnctVal.Type().In(0)
if !firstArgType.Implements(reflect.TypeOf((*RecordSet)(nil)).Elem()) {
continue
}
argValue := reflect.ValueOf(rc.Collection())
res := fnctVal.Call([]reflect.Value{argValue})
c.predicates[i].arg = sanitizeArgs(res[0].Interface(), p.operator.IsMulti())
}
}
// A ClientEvaluatedString is a string that contains code that will be evaluated by the client
type ClientEvaluatedString string