-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_builder.go
More file actions
executable file
·380 lines (369 loc) · 10.3 KB
/
query_builder.go
File metadata and controls
executable file
·380 lines (369 loc) · 10.3 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package f
import (
"fmt"
"github.com/andreyvit/diff"
gjson "github.com/og/go-json"
ge "github.com/og/x/error"
glist "github.com/og/x/list"
gmap "github.com/og/x/map"
gtime "github.com/og/x/time"
"github.com/pkg/errors"
"log"
"os"
"reflect"
"regexp"
"strings"
"time"
)
type Order struct {
Type string
Field string
}
type Group struct {
Field string
}
type QB struct {
Table string
Select []string
Where []AND
Offset int
Limit int
Order Map
Group []string
SoftDelete string
Insert Map
Update Map
Count bool
Debug bool
Check string
}
// QueryBuilder Where
type AND map[string]OP
// FindOr(Find(...), Find(...))
func Or (find ...[]AND) (andList []AND) {
andList = []AND{}
for _, v := range find {
andList = append(andList, v[0])
}
return
}
func And(v ...interface{}) []AND {
and := AND{}
for i:=0;i<len(v);i++ {
itemAny := v[i]
var item Filter
var isKey bool
if i%2 == 0 { isKey = true }
if !isKey {
keyAny := v[i-1]
key := keyAny.(string)
_, has := and[key]
_=has
if reflect.TypeOf(itemAny).Name() != "Filter" {
item = Eql(itemAny)
} else {
item = itemAny.(Filter)
}
if has {
and[key] = append(and[key], item)
} else {
and[key] = OP{item}
}
}
}
return []AND{and}
}
func wrapField(field string) string {
return "`" + field + "`"
}
// filter list interface maybe Filter
func (qb QB) GetSelect() (sql string, sqlValues []interface{}) {
return qb.SQL(SQLProps{
Statement: "SELECT",
})
}
func (qb QB) GetUpdate() (sql string, sqlValues []interface{}) {
return qb.SQL(SQLProps{
Statement: "UPDATE",
})
}
func (qb QB) GetInsert() (sql string, sqlValues []interface{}) {
return qb.SQL(SQLProps{
Statement: "INSERT",
})
}
type SQLProps struct {
Statement string `eg:"[]string{\"SELECT\", \"UPDATE\", \"DELETE\", \"INSERT\"}"`
}
func (qb QB) SQL(props SQLProps) (sql string, sqlValues []interface{}){
var sqlList glist.StringList
tableName := "`" + qb.Table + "`"
{// Statement
switch props.Statement {
case "SELECT":
sqlList.Push("SELECT")
if qb.Count {
sqlList.Push("count(*)")
} else {
if len(qb.Select) == 0 {
sqlList.Push("*")
} else {
sqlList.Push("`" + strings.Join(qb.Select, "`, `") + "`")
}
}
sqlList.Push("FROM")
sqlList.Push(tableName)
case "UPDATE":
sqlList.Push("UPDATE")
sqlList.Push(tableName)
sqlList.Push("SET")
keys := gmap.Keys(qb.Update).String()
if len(keys) == 0 {
panic(errors.New("gofree: update can not be a empty map"))
}
updateValueList := glist.StringList{}
for _, key := range keys {
value := qb.Update[key]
updateValueList.Push(wrapField(key) +" = ?")
sqlValues = append(sqlValues, value)
}
sqlList.Push(updateValueList.Join(", "))
case "DELETE":
sqlList.Push("DELETE")
case "INSERT":
sqlList.Push("INSERT INTO")
sqlList.Push(tableName)
keys := gmap.Keys(qb.Insert).String()
if len(keys) == 0 {
panic(errors.New("gofree: Insert can not be a empty map"))
}
insertKeyList := glist.StringList{}
insertValueList := glist.StringList{}
for _, key := range keys {
value := qb.Insert[key]
insertKeyList.Push(wrapField(key))
insertValueList.Push("?")
sqlValues = append(sqlValues, value)
}
sqlList.Push("(" + insertKeyList.Join(", ") + ")")
sqlList.Push("VALUES")
sqlList.Push("(" + insertValueList.Join(", ") + ")")
}
}
{
// Where field operator value
shouldWhere := len(qb.Where) != 0 || qb.SoftDelete != ""
if props.Statement == "INSERT" {
shouldWhere = false
}
if shouldWhere {
sqlList.Push("WHERE")
var WhereList glist.StringList
parseWhere(qb.Where, &WhereList, &sqlValues)
switch props.Statement {
case "SELECT", "UPDATE":
if qb.SoftDelete != "" {
WhereList.Push(wrapField(qb.SoftDelete) + " IS NULL")
}
}
sqlList.Push(WhereList.Join(" AND "))
}
}
{
// group by
if len(qb.Group) != 0 {
sqlList.Push("GROUP BY")
sqlList.Push("`" + strings.Join(qb.Group,"`, `") + "`")
}
}
{
// order by
if len(qb.Order) != 0 {
sqlList.Push("ORDER BY")
orderASCList := glist.StringList{}
orderDESCList := glist.StringList{}
firstType := ""
for _, field := range gmap.Keys(qb.Order).String() {
orderType := qb.Order[field]
switch orderType {
case ASC:
if firstType == "" {
firstType = "ASC"
}
orderASCList.Push(wrapField(field))
case DESC:
if firstType == "" {
firstType = "DESC"
}
orderDESCList.Push(wrapField(field))
}
orderASCList.Join(",")
}
orderList := glist.StringList{}
switch firstType {
case ASC:
if len(orderASCList.Value) != 0 { orderList.Push(orderASCList.Join(", ") + " " + "ASC") }
if len(orderDESCList.Value) != 0 { orderList.Push(orderDESCList.Join(", ") + " " + "DESC") }
case DESC:
if len(orderDESCList.Value) != 0 { orderList.Push(orderDESCList.Join(", ") + " " + "DESC") }
if len(orderASCList.Value) != 0 { orderList.Push(orderASCList.Join(", ") + " " + "ASC") }
}
sqlList.Push(orderList.Join(", "))
}
}
{
// limit
if qb.Limit != 0 && !qb.Count {
sqlList.Push("LIMIT ?")
sqlValues = append(sqlValues, qb.Limit)
}
}
{
// offset
if qb.Offset != 0 && !qb.Count {
sqlList.Push("OFFSET ?")
sqlValues = append(sqlValues, qb.Offset)
}
}
sql = sqlList.Join(" ")
logDebug(qb.Debug, Map{
"sql": sql,
"values": gjson.String(sqlValues),
})
if qb.Check != "" && qb.Check != sql {
panic("sql check fail:# diff:\r\n" + diff.CharacterDiff(sql, qb.Check) + "\r\n# actual\r\n" + sql + "\r\n# expect:\r\n" + qb.Check)
}
return
}
func parseAnd (field string, op OP, whereList *glist.StringList, sqlValues *[]interface{}) {
for _, filter := range op {
if reflect.ValueOf(filter.Value).IsValid() && reflect.TypeOf(filter.Value).String() == "time.Time" {
panic("gofree: can not use time.Time be sql value, mayby you should time.Format(layout), \r\n` "+ field + ":"+ filter.Value.(time.Time).Format(gtime.Second) + "`")
}
var fieldSymbolCondition glist.StringList
switch filter.Symbol {
case "year":
fieldSymbolCondition.Push(filter.FieldWrap+"("+field+",'"+filter.FieldWarpArg+"')", "=")
fieldSymbolCondition.Push("?")
*sqlValues = append(*sqlValues, filter.Value)
case "month":
fieldSymbolCondition.Push(filter.FieldWrap+"("+field+",'"+filter.FieldWarpArg+"')", "=")
fieldSymbolCondition.Push("?")
*sqlValues = append(*sqlValues, filter.Value)
case "day":
fieldSymbolCondition.Push(field + " >= ?")
*sqlValues = append(*sqlValues, filter.TimeValue.Format(gtime.Day) + " 00:00:00")
fieldSymbolCondition.Push("AND")
fieldSymbolCondition.Push(field + " <= ?")
*sqlValues = append(*sqlValues, filter.TimeValue.Format(gtime.Day) + " 23:59:59")
case "NOT":
fieldSymbolCondition.Push(wrapField(field), "!=")
fieldSymbolCondition.Push("?")
*sqlValues = append(*sqlValues, filter.Value)
case "IS NOT NULL":
fieldSymbolCondition.Push(wrapField(field), filter.Symbol)
case "IS NULL":
fieldSymbolCondition.Push(wrapField(field), filter.Symbol)
case "custom":
var valueList []interface{}
anyValue := reflect.ValueOf(filter.Value)
for i := 0; i < anyValue.Len(); i++ {
valueList = append(valueList, anyValue.Index(i).Interface())
}
*sqlValues = append(*sqlValues, valueList...)
fieldSymbolCondition.Push(wrapField(field), filter.Custom)
case "CustomSQL":
var valueList []interface{}
anyValue := reflect.ValueOf(filter.Value)
for i := 0; i < anyValue.Len(); i++ {
valueList = append(valueList, anyValue.Index(i).Interface())
}
*sqlValues = append(*sqlValues, valueList...)
fieldSymbolCondition.Push("(" + filter.CustomSQL + ")")
case "IN", "NOT IN":
fieldSymbolCondition.Push(wrapField(field), filter.Symbol)
var valueList []interface{}
var placeholderList glist.StringList
anyValue := reflect.ValueOf(filter.Value)
if anyValue.Len() == 0 {
fieldSymbolCondition.Push("(NULL)")
} else {
for i := 0; i < anyValue.Len(); i++ {
valueList = append(valueList, anyValue.Index(i).Interface())
placeholderList.Push("?")
}
*sqlValues = append(*sqlValues, valueList...)
fieldSymbolCondition.Push("(" + placeholderList.Join(", ") + ")")
}
case "LIKE":
var likeValue string
filterValueString := fmt.Sprintf("%s", filter.Value)
switch filter.Like {
case "start":
likeValue = filterValueString+"%"
case "end":
likeValue = "%" + filterValueString
case "have":
likeValue = "%" + filterValueString + "%"
}
fieldSymbolCondition.Push(wrapField(field), filter.Symbol)
fieldSymbolCondition.Push("?")
*sqlValues = append(*sqlValues, likeValue)
default:
fieldSymbolCondition.Push(wrapField(field), filter.Symbol)
fieldSymbolCondition.Push("?")
*sqlValues = append(*sqlValues, filter.Value)
}
whereList.Push(fieldSymbolCondition.Join(" "))
}
}
func parseWhere (Where []AND, WhereList *glist.StringList, sqlValues *[]interface{}) {
var orSqlList glist.StringList
for _, and := range Where {
var andList glist.StringList
for _, field := range gmap.Keys(and).String() {
op := and[field]
parseAnd(field, op, &andList, sqlValues)
}
andString := andList.Join(" AND ")
orSqlList.Push(andString)
}
orSqlString := orSqlList.Join(" ) OR ( ")
if len(orSqlList.Value) > 1 {
orSqlString = "( " + orSqlString + " )"
}
if orSqlString != "" {
WhereList.Push(orSqlString)
}
}
type Model interface {
TableName () string
}
func logSQL(isDebug bool, sql string, values []interface{}) {
replaceRegexp, err := regexp.Compile(`"`);ge.Check(err)
removeStartEndRegExp, err := regexp.Compile(`(^\[|\]$)`) ; ge.Check(err)
removeValuesRegexp, err := regexp.Compile(`VALUES.*$`) ; ge.Check(err)
logDebug(true, Map{
"sql": sql,
"values": values,
"debug sql": removeValuesRegexp.ReplaceAllString(sql, "") + ` VALUES (` + removeStartEndRegExp.ReplaceAllString(replaceRegexp.ReplaceAllString(gjson.String(values), "`"), "") + ")",
})
}
func logDebug(isDebug bool, data Map) {
if !isDebug {
return
}
onlyValueLogger := log.New(os.Stdout,"",log.LUTC)
log.Print("gofree debug: ")
for key, value := range data {
onlyValueLogger.Print(key + ":")
onlyValueLogger.Printf("\t%#+v",value)
}
}
func (qb *QB) BindModel(model Model) {
tableName := model.TableName()
qb.Table = tableName
if reflect.ValueOf(model).Elem().FieldByName("DeletedAt").IsValid() {
qb.SoftDelete = "deleted_at"
}
}