-
Notifications
You must be signed in to change notification settings - Fork 0
/
condition.go
96 lines (84 loc) · 2.34 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
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
package gosql
import "strings"
const (
ConditionOperatorAnd = "AND"
ConditionOperatorOr = "OR"
ConditionOperatorXor = "XOR"
)
// Merge with Condition
type merge struct {
operator string
condition []*Condition
}
// Condition type
type Condition struct {
operator string
expression []string
argument []interface{}
merge *merge
}
// NewSqlCondition init condition
func NewSqlCondition(operator string) *Condition {
return &Condition{operator: operator, expression: make([]string, 0, 8), argument: make([]interface{}, 0, 8)}
}
// Get string of conditions
func (c *Condition) String() string {
if c.merge != nil {
var slaves []string
for i := range (*c.merge).condition {
slaves = append(slaves, (*c.merge).condition[i].String())
}
if c.expression != nil {
slaves = append(slaves, "("+strings.Join(c.expression, " "+c.operator+" ")+")")
}
return "(" + strings.Join(slaves, " "+c.merge.operator+" ") + ")"
} else {
if c.expression != nil {
return "(" + strings.Join(c.expression, " "+c.operator+" ") + ")"
}
return ""
}
}
// IsEmpty check if condition is empty
func (c *Condition) IsEmpty() bool {
return c == nil || (len(c.expression) == 0 && c.merge == nil)
}
// GetArguments get arguments
func (c *Condition) GetArguments() []interface{} {
var arguments = make([]interface{}, 0, 4)
if c.merge != nil {
for i := range (*c.merge).condition {
arguments = append(arguments, (*c.merge).condition[i].GetArguments()...)
}
}
return append(arguments, c.argument...)
}
// AddExpression add expression
func (c *Condition) AddExpression(expression string, values ...interface{}) *Condition {
c.expression = append(c.expression, expression)
c.argument = append(c.argument, values...)
return c
}
// AddArgument add argument
func (c *Condition) AddArgument(values ...interface{}) *Condition {
c.argument = append(c.argument, values...)
return c
}
// Replace current condition
func (c *Condition) Replace(cond *Condition) *Condition {
*c = *cond
return c
}
// Merge with conditions
func (c *Condition) Merge(operator string, conditions ...*Condition) *Condition {
for i := range conditions {
if conditions[i].IsEmpty() {
continue
}
if c.merge == nil {
c.merge = &merge{operator: operator, condition: make([]*Condition, 0, len(conditions))}
}
c.merge.condition = append(c.merge.condition, conditions[i])
}
return c
}