-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_builder.go
455 lines (384 loc) · 10.6 KB
/
query_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
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
package fluentmodel
import (
"crypto/rand"
"errors"
"fmt"
"github.com/jiveio/fluentsql"
"math/big"
"reflect"
)
// ===========================================================================================================
// Query ONE row
// ===========================================================================================================
type GetOne int
const (
GetFirst GetOne = iota
GetLast
TakeOne
)
// First get the first record ordered by primary key
//
// Example
//
// -------- Query a First --------
//
// var user User
// err = db.First(&user)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user)
//
// -------- Query a First by ID --------
//
// var user3 User
// err = db.First(&user3, 103)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user3)
// var user4 User
// user4 = User{Id: 103}
// err = db.First(&user4)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user4)
//
// -------- Query a First by Model --------
//
// var user5 User
// err = db.Model(User{Id: 102}).First(&user5)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user5)
//
// -------- Query a First by Where --------
//
// var user6 User
// err = db.Where("Id", fluentsql.Eq, 100).First(&user6)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user6)
//
// -------- Query a First by WhereGroup --------
//
// var user7 User
// err = db.Where("Id", fluentsql.Eq, 100).
//
// WhereGroup(func(query fluentsql.WhereBuilder) *fluentsql.WhereBuilder {
// query.Where("age", fluentsql.Eq, 42).
// WhereOr("age", fluentsql.Eq, 39)
//
// return &query
// }).First(&user7)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user7)
func (db *DBModel) First(model any) (err error) {
err = db.Get(model, GetFirst)
return
}
// Last last record, ordered by primary key desc
//
// Example
//
// -------- Query a Last --------
//
// var user1 User
// err = db.Select("name").Last(&user1)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user1)
func (db *DBModel) Last(model any) (err error) {
err = db.Get(model, GetLast)
return
}
// Take get one record, no specified order
//
// Example
//
// -------- Query a Take --------
//
// var user2 User
// err = db.Take(&user2)
//
// if err != nil {
// log.Fatal(err)
// }
//
// log.Printf("User %v\n", user2)
func (db *DBModel) Take(model any, args ...any) (err error) {
if len(args) > 0 {
db.wherePrimaryCondition = fluentsql.Condition{
Field: nil,
Opt: fluentsql.Eq,
Value: args[0],
AndOr: fluentsql.And,
}
}
err = db.Get(model, TakeOne)
return
}
// Get with specific strategy GetLast | GetFirst | TakeOne
func (db *DBModel) Get(model any, getType GetOne) (err error) {
// Query raw SQL
if db.raw.sqlStr != "" {
// Data persistence
if db.tx != nil {
err = db.tx.Get(model, db.raw.sqlStr, db.raw.args...)
} else {
err = dbInstance.Get(model, db.raw.sqlStr, db.raw.args...)
}
if err != nil {
panic(err)
}
// Reset fluent model builder
db.reset()
return
}
typ := reflect.TypeOf(model)
if !(typ.Kind() == reflect.Struct ||
(typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct)) {
err = errors.New("invalid data :: model not Struct type")
return
}
var table *Table
var primaryKey any
// Create a table object from a model
table, err = ModelData(model)
// Get a primary key
if len(table.Primaries) > 0 {
primaryKey = table.Primaries[0].Name
}
// Columns which will be queried
var selectColumns []any
// Only some selected columns or all
if len(db.selectStatement.Columns) > 0 {
selectColumns = db.selectStatement.Columns
} else {
selectColumns = []any{"*"}
}
// Create query builder
queryBuilder := fluentsql.QueryInstance().
Select(selectColumns...).
From(table.Name).
Limit(1, 0)
// Build WHERE condition with specific primary value
if db.wherePrimaryCondition.Value != nil && primaryKey != nil {
db.wherePrimaryCondition.Field = primaryKey
queryBuilder.WhereCondition(db.wherePrimaryCondition)
}
// Build WHERE condition from a condition list
for _, condition := range db.whereStatement.Conditions {
// Sub-conditions
if len(condition.Group) > 0 {
// Append conditions from a group to query builder
queryBuilder.WhereGroup(func(whereBuilder fluentsql.WhereBuilder) *fluentsql.WhereBuilder {
whereBuilder.WhereCondition(condition.Group...)
return &whereBuilder
})
} else if condition.AndOr == fluentsql.And {
// Add Where AND condition
queryBuilder.Where(condition.Field, condition.Opt, condition.Value)
} else if condition.AndOr == fluentsql.Or {
// Add Where OR condition
queryBuilder.WhereOr(condition.Field, condition.Opt, condition.Value)
}
}
// Build WHERE condition from a specific model's data off table.
table.whereFromModel(queryBuilder)
// Build JOIN clause
for _, joinItem := range db.joinStatement.Items {
queryBuilder.Join(joinItem.Join, joinItem.Table, joinItem.Condition)
}
// Build GROUP BY clause
if len(db.groupByStatement.Items) > 0 {
queryBuilder.GroupBy(db.groupByStatement.Items...)
}
// Build HAVING clause
for _, condition := range db.havingStatement.Conditions {
queryBuilder.Having(condition.Field, condition.Opt, condition.Value)
}
// Build LIMIT clause
if db.limitStatement.Limit > 0 {
queryBuilder.Limit(db.limitStatement.Limit, db.limitStatement.Offset)
}
// Build FETCH clause
if db.fetchStatement.Fetch > 0 {
queryBuilder.Fetch(db.fetchStatement.Offset, db.fetchStatement.Fetch)
}
// Build ORDER BY clause
orderByField := ""
if primaryKey != nil {
orderByField = primaryKey.(string)
} else {
orderByField = table.Columns[0].Name
}
var orderByDir fluentsql.OrderByDir
if getType == GetLast && orderByField != "" {
orderByDir = fluentsql.Desc
} else if getType == GetFirst && orderByField != "" {
orderByDir = fluentsql.Asc
} else if getType == TakeOne { // Random order field and order dir
n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(table.Columns)-1)))
orderByField = table.Columns[n.Int64()].Name
n, _ = rand.Int(rand.Reader, big.NewInt(10))
if n.Int64()%2 == 1 {
orderByDir = fluentsql.Asc
} else {
orderByDir = fluentsql.Desc
}
}
queryBuilder.OrderBy(orderByField, orderByDir)
// Data processing
if err = db.get(queryBuilder, model); err != nil {
panic(err)
}
// Reset fluent model builder
db.reset()
return
}
// ===========================================================================================================
// Query MULTI rows
// ===========================================================================================================
// Find search rows
func (db *DBModel) Find(model any, params ...any) (total int, err error) {
// Query raw SQL
if db.raw.sqlStr != "" {
// Data persistence
if db.tx != nil {
err = db.tx.Select(model, db.raw.sqlStr, db.raw.args...)
} else {
err = dbInstance.Select(model, db.raw.sqlStr, db.raw.args...)
}
if err != nil {
panic(err)
}
// Query COUNT
sqlCount := fmt.Sprintf("SELECT COUNT(*) AS total FROM (%s) _result_out_", db.raw.sqlStr)
err = db.getRaw(sqlCount, db.raw.args, &total)
if err != nil {
panic(err)
}
// Reset fluent model builder
db.reset()
return
}
typ := reflect.TypeOf(model)
if !(typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Slice) {
panic(errors.New("invalid data :: model not *Slice type"))
}
var table *Table
var primaryKey any
// Get a type of model and get an element
typeElement := reflect.TypeOf(model).Elem().Elem() // First Elem() for pointer. Second Elem() for item
valueElement := reflect.ValueOf(typeElement).Elem() // Create empty value
table = processModel(typeElement, valueElement, NewTable())
// Get a primary key
if len(table.Primaries) > 0 {
primaryKey = table.Primaries[0].Name
}
// Try to build WHERE for primary column
if len(params) > 0 && primaryKey != nil {
sliceIds := params[0]
typ := reflect.TypeOf(sliceIds)
if !(typ.Kind() == reflect.Slice) {
panic(errors.New("invalid data :: params not *Slice type"))
}
db.wherePrimaryCondition = fluentsql.Condition{
Field: primaryKey,
Opt: fluentsql.In,
Value: sliceIds,
AndOr: fluentsql.And,
}
}
// Columns which will be queried
var selectColumns []any
// Only some selected columns or all
if len(db.selectStatement.Columns) > 0 {
selectColumns = db.selectStatement.Columns
} else {
selectColumns = []any{"*"}
}
// Create query builder
queryBuilder := fluentsql.QueryInstance().
Select(selectColumns...).
From(table.Name)
// Build WHERE condition with specific primary value
if db.wherePrimaryCondition.Value != nil && primaryKey != nil {
db.wherePrimaryCondition.Field = primaryKey
queryBuilder.WhereCondition(db.wherePrimaryCondition)
}
// Build WHERE condition from a condition list
for _, condition := range db.whereStatement.Conditions {
// Sub-conditions
if len(condition.Group) > 0 {
// Append conditions from a group to query builder
queryBuilder.WhereGroup(func(whereBuilder fluentsql.WhereBuilder) *fluentsql.WhereBuilder {
whereBuilder.WhereCondition(condition.Group...)
return &whereBuilder
})
} else if condition.AndOr == fluentsql.And {
// Add Where AND condition
queryBuilder.Where(condition.Field, condition.Opt, condition.Value)
} else if condition.AndOr == fluentsql.Or {
// Add Where OR condition
queryBuilder.WhereOr(condition.Field, condition.Opt, condition.Value)
}
}
// Build WHERE condition from a specific model's data off table.
table.whereFromModel(queryBuilder)
// Build JOIN clause
for _, joinItem := range db.joinStatement.Items {
queryBuilder.Join(joinItem.Join, joinItem.Table, joinItem.Condition)
}
// Build GROUP BY clause
if len(db.groupByStatement.Items) > 0 {
queryBuilder.GroupBy(db.groupByStatement.Items...)
}
// Build HAVING clause
for _, condition := range db.havingStatement.Conditions {
queryBuilder.Having(condition.Field, condition.Opt, condition.Value)
}
// Build LIMIT clause
if db.limitStatement.Limit > 0 {
queryBuilder.Limit(db.limitStatement.Limit, db.limitStatement.Offset)
}
// Build FETCH clause
if db.fetchStatement.Fetch > 0 {
queryBuilder.Fetch(db.fetchStatement.Offset, db.fetchStatement.Fetch)
}
// Build ORDER BY clause
for _, orderItem := range db.orderByStatement.Items {
queryBuilder.OrderBy(orderItem.Field, orderItem.Direction)
}
// Data processing
if err = db.query(queryBuilder, model); err != nil {
panic(err)
}
if err = db.count(queryBuilder, &total); err != nil {
panic(err)
}
// Reset fluent model builder
db.reset()
return
}