forked from go-gorm/gen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
condition.go
66 lines (56 loc) · 1.52 KB
/
condition.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
package gen
import (
"fmt"
"gorm.io/datatypes"
"gorm.io/gen/field"
"gorm.io/gorm/clause"
)
// Cond convert expression array to condition array
func Cond(exprs ...clause.Expression) []Condition {
return exprToCondition(exprs...)
}
var _ Condition = &condContainer{}
type condContainer struct {
value interface{}
err error
}
func (c *condContainer) BeCond() interface{} { return c.value }
func (c *condContainer) CondError() error { return c.err }
func exprToCondition(exprs ...clause.Expression) []Condition {
conds := make([]Condition, 0, len(exprs))
for _, e := range exprs {
switch e := e.(type) {
case *datatypes.JSONQueryExpression, *datatypes.JSONOverlapsExpression, *datatypes.JSONArrayExpression:
conds = append(conds, &condContainer{value: e})
default:
conds = append(conds, &condContainer{err: fmt.Errorf("unsupported Expression %T to converted to Condition", e)})
}
}
return conds
}
func condToExpression(conds []Condition) ([]clause.Expression, error) {
if len(conds) == 0 {
return nil, nil
}
exprs := make([]clause.Expression, 0, len(conds))
for _, cond := range conds {
if cond == nil {
continue
}
if err := cond.CondError(); err != nil {
return nil, err
}
switch cond.(type) {
case *condContainer, field.Expr, SubQuery:
default:
return nil, fmt.Errorf("unsupported condition: %+v", cond)
}
switch e := cond.BeCond().(type) {
case []clause.Expression:
exprs = append(exprs, e...)
case clause.Expression:
exprs = append(exprs, e)
}
}
return exprs, nil
}