-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsqlbuilder_where.go
106 lines (86 loc) · 2.55 KB
/
sqlbuilder_where.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
package sqle
import "strings"
// WhereBuilder is a struct that represents a SQL WHERE clause builder.
type WhereBuilder struct {
*Builder
written bool
shouldSkip bool
}
// NewWhere creates a new instance of WhereBuilder.
func NewWhere() *WhereBuilder {
return &WhereBuilder{
Builder: New(),
}
}
// Where adds a WHERE clause to the SQL statement.
// It takes one or more criteria strings as arguments.
// Each criteria string represents a condition in the WHERE clause.
// If a criteria string is empty, it will be ignored.
// Returns a *WhereBuilder that can be used to further build the SQL statement.
func (b *Builder) Where(criteria ...string) *WhereBuilder {
wb := &WhereBuilder{Builder: b}
for _, it := range criteria {
if it != "" {
if !wb.written {
b.stmt.WriteString(" WHERE")
}
wb.written = true
b.stmt.WriteString(" ")
b.stmt.WriteString(it)
}
}
return wb
}
// WithWhere adds the input and parameter values from the given WhereBuilder to the current Builder
// and sets the WHERE clause of the SQL statement to the string representation of the WhereBuilder's statement.
// It returns the modified WhereBuilder.
func (b *Builder) WithWhere(wb *WhereBuilder) *WhereBuilder {
if wb == nil {
return nil
}
for k, v := range wb.inputs {
b.Input(k, v)
}
for k, v := range wb.params {
b.Param(k, v)
}
return b.Where(strings.TrimPrefix(wb.stmt.String(), " WHERE "))
}
// If sets a condition to skip the subsequent SQL statements.
// If the predicate is false, the subsequent SQL statements will be skipped.
func (wb *WhereBuilder) If(predicate bool) *WhereBuilder {
wb.shouldSkip = !predicate
return wb
}
// And adds an AND condition to the WHERE clause.
func (wb *WhereBuilder) And(criteria string) *WhereBuilder {
return wb.SQL("AND", criteria)
}
// Or adds an OR condition to the WHERE clause.
func (wb *WhereBuilder) Or(criteria string) *WhereBuilder {
return wb.SQL("OR", criteria)
}
// SQL adds a condition to the WHERE clause with the specified operator.
func (wb *WhereBuilder) SQL(op string, criteria string) *WhereBuilder {
if wb.shouldSkip {
wb.shouldSkip = false
return wb
}
if criteria != "" {
// first condition, op expression should not be written
if wb.written {
wb.Builder.stmt.WriteString(" ")
wb.Builder.stmt.WriteString(op)
} else {
wb.Builder.stmt.WriteString(" WHERE")
}
wb.written = true
wb.Builder.stmt.WriteString(" ")
wb.Builder.stmt.WriteString(criteria)
}
return wb
}
// End returns the underlying Builder instance.
func (wb *WhereBuilder) End() *Builder {
return wb.Builder
}