-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcondition.go
91 lines (85 loc) · 1.85 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
package sq
const sqlPlaceholder = "?"
type Condition struct {
Column Column
OP OP
}
func ConditionRaw(query string, values []interface{}) Condition {
return Condition{
OP: OP{
Query: query,
Values: values,
},
}
}
func And(column Column, operator OP) conditions {
return conditions{}.And(column, operator)
}
func AndRaw(query string, values ...interface{}) conditions {
return And("", OP{
Query: query,
Values: values,
})
}
func OrGroup(conditions ...Condition) conditions {
op := OP{OrGroup: conditions}
item := Condition{OP: op}
return []Condition{item}
}
func ToConditions(c []Condition) conditions {
return conditions(c)
}
type conditions []Condition
func (w conditions) And(column Column, operator OP) conditions {
w = append(w, Condition{
Column: column,
OP: operator,
})
return w
}
func (w conditions) AndRaw(query string, values ...interface{}) conditions {
w = append(w, Condition{
Column: "",
OP: OP{
Query: query,
Values: values,
},
})
return w
}
// func (w conditions) OrGroup(conditions []Condition) conditions {
// op := OP{OrGroup: conditions}
// item := Condition{OP:op}
// w = append(w, item)
// return w
// }
func ConditionsSQL(w [][]Condition) (raw Raw) {
var orList stringQueue
for _, whereAndList := range w {
andsQV := ToConditions(whereAndList).coreSQL("AND")
if len(andsQV.Query) != 0 {
orList.Push(andsQV.Query)
raw.Values = append(raw.Values, andsQV.Values...)
}
}
raw.Query = orList.Join(") OR (")
if len(orList.Value) > 1 {
raw.Query = "(" + raw.Query + ")"
}
return
}
func (w conditions) coreSQL(split string) Raw {
var andList stringQueue
var values []interface{}
for _, c := range w {
if c.OP.Ignore {
continue
}
sql := c.OP.sql(c.Column, &values)
if len(sql) != 0 {
andList.Push(sql)
}
}
query := andList.Join(" " + split + " ")
return Raw{query, values}
}