forked from sabrinalua/simple-sql-helper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
condition-builder.go
69 lines (56 loc) · 1.77 KB
/
condition-builder.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
package helper
import (
"fmt"
"strings"
)
// ConditionBuilder /...
type ConditionBuilder struct {
unnamedConditions []string
namedConditions []string
AliasMap map[string]interface{}
Values []interface{}
conditions []*Condition
}
// NewConditionBuilder ...
func NewConditionBuilder(c *Condition) *ConditionBuilder {
me := &ConditionBuilder{
AliasMap: map[string]interface{}{},
}
return me.build(c, "WHERE")
}
// And ...
func (me *ConditionBuilder) And(c *Condition) *ConditionBuilder {
return me.build(c, "AND")
}
// Or ...
func (me *ConditionBuilder) Or(c *Condition) *ConditionBuilder {
return me.build(c, "OR")
}
// ConditionBuilder .. where verb = WHERE, AND, OR
func (me *ConditionBuilder) build(c *Condition, verb string) *ConditionBuilder {
// check current size of condition store
i := len(me.conditions)
//add c to the collection of conditions
me.conditions = append(me.conditions, c)
alias := fmt.Sprintf("%v", i)
// build unnamed condition name=?
unnamedCondition := c.string()
unnamedCondition = fmt.Sprintf("%v %v ", verb, unnamedCondition)
me.unnamedConditions = append(me.unnamedConditions, unnamedCondition)
//set named conditions
namedCondition := c.string(i)
namedCondition = fmt.Sprintf("%v %v ", verb, namedCondition)
me.namedConditions = append(me.namedConditions, namedCondition)
//set alias
me.AliasMap[alias] = c.Value
me.Values = append(me.Values, c.Value)
return me
}
// NamedConditionString ...
func (me *ConditionBuilder) NamedConditionString() string {
return strings.Join(me.namedConditions, "")
}
// UnnamedConditionString ...
func (me *ConditionBuilder) UnnamedConditionString() string {
return strings.Join(me.unnamedConditions, "")
}