-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery_where.go
125 lines (110 loc) · 2.55 KB
/
query_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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package QueryHelper
import (
"fmt"
"strings"
)
type WhereStmt struct {
LeftValue Column
Conditional string
RightValue interface{}
Level int
JoinOperator string
Index int
Flip bool
}
func NewWhere(column Column, value interface{}) *WhereStmt {
return &WhereStmt{
LeftValue: column,
Conditional: "=",
RightValue: value,
Level: 0,
JoinOperator: "AND",
}
}
func (w *WhereStmt) GetArg() (string, interface{}) {
if w.RightValue == nil {
return "", nil
}
var suffix string
if w.Index > 0 {
suffix = fmt.Sprintf("_%d", w.Index)
}
return fmt.Sprintf("%s%s", w.LeftValue.Name, suffix), w.RightValue
}
func (w *WhereStmt) ToString() string {
column := w.LeftValue
if column.Name == "" {
return ""
}
tmp := column.Where
if w.Conditional != "" {
tmp = w.Conditional
} else if tmp == "" {
tmp = "="
}
var suffix string
if w.Index > 0 {
suffix = fmt.Sprintf("_%d", w.Index)
}
var formatted string
switch strings.TrimSpace(strings.ToLower(tmp)) {
case "is not":
if w.RightValue == nil {
formatted = fmt.Sprintf("%s %s null", column.FullName(false, false), tmp)
}
case "is":
if w.RightValue == nil {
formatted = fmt.Sprintf("%s %s null", column.FullName(false, false), tmp)
}
case "not in":
fallthrough
case "in":
formatted = fmt.Sprintf("%s %s (:%s%s)", column.FullName(false, false), tmp, column.Name, suffix)
default:
if w.Flip {
formatted = fmt.Sprintf(":%s%s %s %s", column.Name, suffix, tmp, column.FullName(false, false))
} else {
formatted = fmt.Sprintf("%s %s :%s%s", column.FullName(false, false), tmp, column.Name, suffix)
}
}
if strings.Contains(formatted, ":") {
return formatted
}
return ""
}
func generateWhere(whereStatements []*WhereStmt) string {
var builder strings.Builder
builder.WriteString("WHERE ")
previousLevel := 0
for i, w := range whereStatements {
if where := w.ToString(); where != "" {
// Handle level changes
if w.Level < previousLevel {
for j := 0; j < previousLevel-w.Level; j++ {
builder.WriteString(")")
}
}
if i > 0 {
if w.JoinOperator == "" {
w.JoinOperator = "AND"
}
builder.WriteString(" ")
builder.WriteString(strings.ToUpper(w.JoinOperator))
}
if w.Level > previousLevel {
for j := 0; j < w.Level-previousLevel; j++ {
builder.WriteString("(")
}
}
builder.WriteString(" ")
builder.WriteString(where)
previousLevel = w.Level
}
}
if previousLevel > 0 {
for j := 0; j < previousLevel; j++ {
builder.WriteString(")")
}
}
return builder.String()
}