-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsearch.go
463 lines (419 loc) · 11.4 KB
/
search.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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package crud
import (
"fmt"
"strconv"
"strings"
)
// JoinCon join条件
type JoinCon struct {
TableName string
Condition string
}
// JoinCons join条件slice
type JoinCons []JoinCon
// HaveTable join条件中是否已经添加了这张表的join
func (jc JoinCons) HaveTable(tableName string) bool {
for _, v := range jc {
if v.TableName == tableName {
return true
}
}
return false
}
// WhereCon where条件
type WhereCon struct {
Query string
Args []interface{}
}
// Search 搜索结构体
type Search struct {
table *Table
fields []string
tableName string
joinConditions JoinCons
whereConditions []WhereCon
orderbyConditions []string
groupConditions []string
havingConditions []WhereCon
with string
having string
limit interface{}
offset interface{}
query string
args []interface{}
raw bool
}
// Clone 克隆一个当前结构体
func (s *Search) Clone() *Search {
clone := *s
return &clone
}
// Fields 需要查询的字段
func (s *Search) Fields(args ...string) *Search {
if len(args) == 0 {
return s
}
for i := 0; i < len(args); i++ {
switch args[i] {
case "$C", "$c":
args[i] = "COUNT(1) AS total"
}
}
s.fields = append(s.fields, args...)
return s
}
// Where where语法
func (s *Search) Where(query string, values ...interface{}) *Search {
s.whereConditions = append(s.whereConditions, WhereCon{Query: query, Args: values})
return s
}
// WhereID id = ?
func (s *Search) WhereID(id interface{}) *Search {
s.whereConditions = append(s.whereConditions, WhereCon{Query: s.tableName + ".id = ?", Args: []interface{}{id}})
return s
}
// In in语法
func (s *Search) In(field string, args ...interface{}) *Search {
//in没有参数的话SQL就会报错
if len(args) == 0 {
return s
}
s.whereConditions = append(s.whereConditions, WhereCon{Query: fmt.Sprintf("%s IN (%s)", field, placeholder(len(args))), Args: args})
return s
}
// NotIn not in 语法
func (s *Search) NotIn(field string, args ...interface{}) *Search {
//not in没有参数的话SQL就会报错
if len(args) == 0 {
return s
}
s.whereConditions = append(s.whereConditions, WhereCon{Query: fmt.Sprintf("%s NOT IN (%s)", field, placeholder(len(args))), Args: args})
return s
}
// Joins join语法,自动连表。
func (s *Search) Joins(tablename string, condition ...string) *Search {
if len(condition) == 1 {
s.joinConditions = append(s.joinConditions, JoinCon{TableName: tablename, Condition: condition[0]})
} else {
if s.table.tableColumns[tablename].HaveColumn(s.tableName + "id") {
s.joinConditions = append(s.joinConditions, JoinCon{TableName: tablename, Condition: fmt.Sprintf("%s.%s = %s.id", tablename, s.tableName+"id", s.tableName)})
} else if s.table.tableColumns[tablename].HaveColumn(s.tableName + "_id") {
s.joinConditions = append(s.joinConditions, JoinCon{TableName: tablename, Condition: fmt.Sprintf("%s.%s = %s.id", tablename, s.tableName+"_id", s.tableName)})
} else if s.table.tableColumns[s.tableName].HaveColumn(tablename + "id") {
s.joinConditions = append(s.joinConditions, JoinCon{TableName: tablename, Condition: fmt.Sprintf("%s.%s = %s.id", s.tableName, tablename+"id", tablename)})
} else if s.table.tableColumns[s.tableName].HaveColumn(tablename + "_id") {
s.joinConditions = append(s.joinConditions, JoinCon{TableName: tablename, Condition: fmt.Sprintf("%s.%s = %s.id", s.tableName, tablename+"_id", tablename)})
}
}
return s
}
// OrderBy OrderBy 默认升序
func (s *Search) OrderBy(field string, isDESC ...bool) *Search {
if len(isDESC) > 0 && isDESC[0] {
s.orderbyConditions = append(s.orderbyConditions, field+" DESC")
} else {
s.orderbyConditions = append(s.orderbyConditions, field+" ASC")
}
return s
}
// TableName tableName
func (s *Search) TableName(name string) *Search {
s.tableName = name
return s
}
// Limit LIMIT ?
func (s *Search) Limit(limit interface{}) *Search {
s.limit = limit
return s
}
// Offset OFFSET ?
func (s *Search) Offset(offset interface{}) *Search {
s.offset = offset
return s
}
// Group GROUP BY
func (s *Search) Group(field ...string) *Search {
s.groupConditions = append(s.groupConditions, field...)
return s
}
// Having having
func (s *Search) Having(query string, args ...interface{}) *Search {
s.havingConditions = append(s.havingConditions, WhereCon{Query: query, Args: args})
return s
}
// Parse Parse
func (s *Search) Parse() (string, []interface{}) {
if s.raw == true {
return s.query, s.args
}
var (
fields string
joins string
paddingwhere string
wheres []string
groupby string
having string
orderby string
limit string
offset string
)
if s.table.tableColumns[s.tableName].HaveColumn(IsDeleted) {
s.Where("is_deleted = ?", 0)
}
s.query = ""
s.args = []interface{}{}
if len(s.fields) == 0 {
fields = "*"
} else {
for i := 0; i < len(s.fields); i++ {
var tableName string
s.fields[i], tableName, _ = s.warpField(s.fields[i])
if tableName != s.tableName {
if !s.joinConditions.HaveTable(tableName) {
s.Joins(tableName)
}
}
}
fields = strings.Join(s.fields, ",")
}
for _, joincon := range s.joinConditions {
joins += fmt.Sprintf(" LEFT JOIN %s ON %s", joincon.TableName, joincon.Condition)
}
for _, wherecon := range s.whereConditions {
paddingwhere = " WHERE "
wheres = append(wheres, wherecon.Query)
s.args = append(s.args, wherecon.Args...)
}
if len(s.groupConditions) > 0 {
groupby = " GROUP BY " + strings.Join(s.groupConditions, ",")
}
if len(s.havingConditions) > 0 {
hcs := []string{}
for _, c := range s.havingConditions {
hcs = append(hcs, c.Query)
s.args = append(s.args, c.Args...)
}
having = " HAVING " + strings.Join(hcs, " AND ")
}
if len(s.orderbyConditions) > 0 {
orderby = " ORDER BY " + strings.Join(s.orderbyConditions, ",")
}
if s.limit != nil {
limit = " LIMIT ?"
s.args = append(s.args, s.limit)
}
if s.offset != nil {
offset = " OFFSET ?"
s.args = append(s.args, s.offset)
}
s.query = fmt.Sprintf("SELECT %s FROM `%s`%s%s%s%s%s%s%s%s",
fields,
s.tableName,
joins,
paddingwhere,
strings.Join(wheres, " AND "),
groupby,
having,
orderby,
limit,
offset,
)
// 如果table进行搜索了(table.RowsMap()),那么table下面所有的条件都会一直使用之前的搜索语句。
// s.raw = true
return s.query, s.args
}
// DISTINCT XX
// DISTICT XXX.XXX AS aaa
// XXX.XXX AS aaa
// COUNT(*) AS total
// tablename.*
// DATE_FORMAT(repair.createdtime,'%Y-%m-%d') AS dt
func (s *Search) warpField(field string) (warpStr string, tablename string, fieldname string) {
if strings.Contains(field, " ") {
if strings.Contains(field, "AS") {
// XXX AS XXX
sp := strings.Split(field, " ")
for i := 0; i < len(sp); i++ {
if sp[i] == "AS" {
sp[i-1], tablename, fieldname = s.warpFieldSingel(sp[i-1])
warpStr = strings.Join(sp, " ")
break
}
}
} else {
sp := strings.Split(field, " ")
sp[len(sp)-1], tablename, fieldname = s.warpFieldSingel(sp[len(sp)-1])
warpStr = strings.Join(sp, " ")
}
} else {
return s.warpFieldSingel(field)
}
return
}
// warpFieldSingel field without space
// warp xxx OR xxx.xxx OR * OR COUNT(*) OR tablename.*
// 这里的都没有空格的
// 单个属性 id
// 表名.属性
// 表名.*
// COUNT(1)之类的函数
// DATE_FORMAT(repair.createdtime,'%Y-%m-%d')
func (s *Search) warpFieldSingel(field string) (warpStr string, tablename string, fieldname string) {
if strings.Contains(field, ".") {
sp := strings.Split(field, ".")
tablename = sp[0]
fieldname = sp[1]
if tablename == "" {
tablename = s.tableName
}
if fieldname == "" {
fieldname = "*"
}
tablenameCombine := tablename
fieldnameCombine := fieldname
if !strings.Contains(tablename, "`") {
tablenameCombine = "`" + tablename + "`"
} else {
tablename = strings.Replace(tablename, "`", "", -1)
}
if !strings.Contains(fieldname, "`") && fieldname != "*" {
fieldnameCombine = "`" + fieldname + "`"
} else {
fieldname = strings.Replace(fieldname, "`", "", -1)
}
if s.table.DataBase.HaveTable(tablename) && s.table.DataBase.Table(tablename).HaveColumn(fieldname) {
warpStr = tablenameCombine + "." + fieldnameCombine
} else {
warpStr = field
}
} else {
// 如果没有.
tablename = s.tableName
fieldname = field
warpStr = field
cols := s.table.DataBase.getColumns(tablename)
for _, col := range cols {
if col.Name == field {
warpStr = "`" + tablename + "`.`" + field + "`"
break
}
}
}
return
}
//结果展示
// RawMap RawMap
func (s *Search) RawMap() RowMap {
return s.RowMap()
}
// RawsMap RawsMap
func (s *Search) RawsMap() RowsMap {
return s.RowsMap()
}
// RawsMapInterface RawsMapInterface
func (s *Search) RawsMapInterface() RowsMapInterface {
return s.RowsMapInterface()
}
// RowMap RowMap
func (s *Search) RowMap() RowMap {
nb := (*s).Clone().Limit(1)
query, args := nb.Parse()
return s.table.Query(query, args...).RowMap()
}
// Explain explian sql
func (s *Search) Explain(debug bool) Explain {
query, args := s.Parse()
r := s.table.Query("EXPLAIN "+query, args...).RowMap()
if debug {
fmt.Println(query)
fmt.Println(args)
fmt.Println(getFullSQL(query, args...))
}
e := Explain{
ID: r.Int("id"),
SelectType: r["select_type"],
Table: r["table"],
Partitions: r["partitions"],
Type: r["type"],
PossibleKeys: r["possible_keys"],
Key: r["key"],
KeyLen: r.Int("key_len"),
Ref: r["ref"],
Rows: r.Int("rows"),
Filtered: r.Int("filtered"),
Extra: r["extra"],
}
return e
}
// func (s *Search) String() string {
// return s.table.Query(s.Parse()).String()
// }
// SQLRows SQLRows
func (s *Search) SQLRows() *SQLRows {
query, args := s.Parse()
return s.table.Query(query, args...)
}
// RowsMap RowsMap
func (s *Search) RowsMap() RowsMap {
query, args := s.Parse()
return s.table.Query(query, args...).RowsMap()
}
// RowMapInterface RowMapInterface
func (s *Search) RowMapInterface() RowMapInterface {
query, args := s.Parse()
return s.table.Query(query, args...).RowMapInterface()
}
// RowsMapInterface RowsMapInterface
func (s *Search) RowsMapInterface() RowsMapInterface {
query, args := s.Parse()
return s.table.Query(query, args...).RowsMapInterface()
}
// DoubleSlice DoubleSlice
func (s *Search) DoubleSlice() (map[string]int, [][]string) {
query, args := s.Parse()
return s.table.Query(query, args...).DoubleSlice()
}
// Int 如果指定字段,则返回指定字段的int值,否则返回第一个字段作为int值返回。
func (s *Search) Int(args ...string) int {
row := s.RowMap()
if len(args) == 0 {
for _, v := range row {
i, _ := strconv.Atoi(v)
return i
}
} else {
i, _ := strconv.Atoi(row[args[0]])
return i
}
return 0
}
// String like int
func (s *Search) String(args ...string) string {
row := s.RowMap()
if len(args) == 0 {
for _, v := range row {
return v
}
} else {
return row[args[0]]
}
return ""
}
// Bool Bool
func (s *Search) Bool(args ...string) bool {
row := s.RowMap()
return row.Bool(args...)
}
// Finds 将查询的结构放入到结构体当中
func (s *Search) Finds(v interface{}) error {
query, args := s.Parse()
return s.table.FindAll(v, append([]interface{}{query}, args...)...)
}
// //Count 计算这次查询结果的个数
// func (s *Search) Count() int {
// var count int
// s.fields = []string{"COUNT(*)"}
// query, args := s.Parse()
// s.table.Query(query, args...).Find(&count)
// return count
// }