forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
finders.go
379 lines (327 loc) · 9.38 KB
/
finders.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
package pop
import (
"database/sql"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/gobuffalo/pop/associations"
"github.com/gobuffalo/pop/logging"
"github.com/gobuffalo/uuid"
"github.com/pkg/errors"
)
var rLimitOffset = regexp.MustCompile("(?i)(limit [0-9]+ offset [0-9]+)$")
var rLimit = regexp.MustCompile("(?i)(limit [0-9]+)$")
// Find the first record of the model in the database with a particular id.
//
// c.Find(&User{}, 1)
func (c *Connection) Find(model interface{}, id interface{}) error {
q := Q(c)
return q.Find(model, id)
}
// Find the first record of the model in the database with a particular id.
//
// q.Find(&User{}, 1)
func (q *Query) Find(model interface{}, id interface{}) error {
m := &Model{Value: model}
tn := m.TableName()
for _, c := range q.fromClauses {
if c.From == tn {
tn = c.As
break
}
}
idq := m.whereID()
switch t := id.(type) {
case uuid.UUID:
return q.Where(idq, t.String()).First(model)
case string:
l := len(t)
if l > 0 {
// Handle leading '0':
// if the string have a leading '0' and is not "0", prevent parsing to int
if t[0] != '0' || l == 1 {
var err error
id, err = strconv.Atoi(t)
if err != nil {
return q.Where(idq, t).First(model)
}
}
}
}
return q.Where(idq, id).First(model)
}
// First record of the model in the database that matches the query.
//
// c.First(&User{})
func (c *Connection) First(model interface{}) error {
q := Q(c)
return q.First(model)
}
// First record of the model in the database that matches the query.
//
// q.Where("name = ?", "mark").First(&User{})
func (q *Query) First(model interface{}) error {
err := q.Connection.timeFunc("First", func() error {
q.Limit(1)
m := &Model{Value: model}
if err := q.Connection.Dialect.SelectOne(q.Connection.Store, m, *q); err != nil {
return err
}
return m.afterFind(q.Connection)
})
if err != nil {
return err
}
if q.eager {
err = q.eagerAssociations(model)
q.disableEager()
return err
}
return nil
}
// Last record of the model in the database that matches the query.
//
// c.Last(&User{})
func (c *Connection) Last(model interface{}) error {
q := Q(c)
return q.Last(model)
}
// Last record of the model in the database that matches the query.
//
// q.Where("name = ?", "mark").Last(&User{})
func (q *Query) Last(model interface{}) error {
err := q.Connection.timeFunc("Last", func() error {
q.Limit(1)
q.Order("created_at DESC, id DESC")
m := &Model{Value: model}
if err := q.Connection.Dialect.SelectOne(q.Connection.Store, m, *q); err != nil {
return err
}
return m.afterFind(q.Connection)
})
if err != nil {
return err
}
if q.eager {
err = q.eagerAssociations(model)
q.disableEager()
return err
}
return nil
}
// All retrieves all of the records in the database that match the query.
//
// c.All(&[]User{})
func (c *Connection) All(models interface{}) error {
q := Q(c)
return q.All(models)
}
// All retrieves all of the records in the database that match the query.
//
// q.Where("name = ?", "mark").All(&[]User{})
func (q *Query) All(models interface{}) error {
err := q.Connection.timeFunc("All", func() error {
m := &Model{Value: models}
err := q.Connection.Dialect.SelectMany(q.Connection.Store, m, *q)
if err != nil {
return err
}
err = q.paginateModel(models)
if err != nil {
return err
}
return m.afterFind(q.Connection)
})
if err != nil {
return err
}
if q.eager {
err = q.eagerAssociations(models)
q.disableEager()
return err
}
return nil
}
func (q *Query) paginateModel(models interface{}) error {
if q.Paginator == nil {
return nil
}
ct, err := q.Count(models)
if err != nil {
return err
}
q.Paginator.TotalEntriesSize = ct
st := reflect.ValueOf(models).Elem()
q.Paginator.CurrentEntriesSize = st.Len()
q.Paginator.TotalPages = q.Paginator.TotalEntriesSize / q.Paginator.PerPage
if q.Paginator.TotalEntriesSize%q.Paginator.PerPage > 0 {
q.Paginator.TotalPages = q.Paginator.TotalPages + 1
}
return nil
}
// Load loads all association or the fields specified in params for
// an already loaded model.
//
// tx.First(&u)
// tx.Load(&u)
func (c *Connection) Load(model interface{}, fields ...string) error {
q := Q(c)
q.eagerFields = fields
err := q.eagerAssociations(model)
q.disableEager()
return err
}
func (q *Query) eagerAssociations(model interface{}) error {
var err error
// eagerAssociations for a slice or array model passed as a param.
v := reflect.ValueOf(model)
if reflect.Indirect(v).Kind() == reflect.Slice ||
reflect.Indirect(v).Kind() == reflect.Array {
v = v.Elem()
for i := 0; i < v.Len(); i++ {
err = q.eagerAssociations(v.Index(i).Addr().Interface())
if err != nil {
return err
}
}
return err
}
assos, err := associations.ForStruct(model, q.eagerFields...)
if err != nil {
return err
}
// disable eager mode for current connection.
q.eager = false
q.Connection.eager = false
for _, association := range assos {
if association.Skipped() {
continue
}
query := Q(q.Connection)
whereCondition, args := association.Constraint()
query = query.Where(whereCondition, args...)
// validates if association is Sortable
sortable := (*associations.AssociationSortable)(nil)
t := reflect.TypeOf(association)
if t.Implements(reflect.TypeOf(sortable).Elem()) {
m := reflect.ValueOf(association).MethodByName("OrderBy")
out := m.Call([]reflect.Value{})
orderClause := out[0].String()
if orderClause != "" {
query = query.Order(orderClause)
}
}
sqlSentence, args := query.ToSQL(&Model{Value: association.Interface()})
query = query.RawQuery(sqlSentence, args...)
if association.Kind() == reflect.Slice || association.Kind() == reflect.Array {
err = query.All(association.Interface())
}
if association.Kind() == reflect.Struct {
err = query.First(association.Interface())
}
if err != nil && errors.Cause(err) != sql.ErrNoRows {
return err
}
// load all inner associations.
innerAssociations := association.InnerAssociations()
for _, inner := range innerAssociations {
v = reflect.Indirect(reflect.ValueOf(model)).FieldByName(inner.Name)
innerQuery := Q(query.Connection)
innerQuery.eagerFields = []string{inner.Fields}
err = innerQuery.eagerAssociations(v.Addr().Interface())
if err != nil {
return err
}
}
}
return nil
}
// Exists returns true/false if a record exists in the database that matches
// the query.
//
// q.Where("name = ?", "mark").Exists(&User{})
func (q *Query) Exists(model interface{}) (bool, error) {
tmpQuery := Q(q.Connection)
q.Clone(tmpQuery) //avoid meddling with original query
var res bool
err := tmpQuery.Connection.timeFunc("Exists", func() error {
tmpQuery.Paginator = nil
tmpQuery.orderClauses = clauses{}
tmpQuery.limitResults = 0
query, args := tmpQuery.ToSQL(&Model{Value: model})
// when query contains custom selected fields / executed using RawQuery,
// sql may already contains limit and offset
if rLimitOffset.MatchString(query) {
foundLimit := rLimitOffset.FindString(query)
query = query[0 : len(query)-len(foundLimit)]
} else if rLimit.MatchString(query) {
foundLimit := rLimit.FindString(query)
query = query[0 : len(query)-len(foundLimit)]
}
existsQuery := fmt.Sprintf("SELECT EXISTS (%s)", query)
log(logging.SQL, existsQuery, args...)
return q.Connection.Store.Get(&res, existsQuery, args...)
})
return res, err
}
// Count the number of records in the database.
//
// c.Count(&User{})
func (c *Connection) Count(model interface{}) (int, error) {
return Q(c).Count(model)
}
// Count the number of records in the database.
//
// q.Where("name = ?", "mark").Count(&User{})
func (q Query) Count(model interface{}) (int, error) {
return q.CountByField(model, "*")
}
// CountByField counts the number of records in the database, for a given field.
//
// q.Where("sex = ?", "f").Count(&User{}, "name")
func (q Query) CountByField(model interface{}, field string) (int, error) {
tmpQuery := Q(q.Connection)
q.Clone(tmpQuery) //avoid meddling with original query
res := &rowCount{}
err := tmpQuery.Connection.timeFunc("CountByField", func() error {
tmpQuery.Paginator = nil
tmpQuery.orderClauses = clauses{}
tmpQuery.limitResults = 0
query, args := tmpQuery.ToSQL(&Model{Value: model})
//when query contains custom selected fields / executed using RawQuery,
// sql may already contains limit and offset
if rLimitOffset.MatchString(query) {
foundLimit := rLimitOffset.FindString(query)
query = query[0 : len(query)-len(foundLimit)]
} else if rLimit.MatchString(query) {
foundLimit := rLimit.FindString(query)
query = query[0 : len(query)-len(foundLimit)]
}
countQuery := fmt.Sprintf("SELECT COUNT(%s) AS row_count FROM (%s) a", field, query)
log(logging.SQL, countQuery, args...)
return q.Connection.Store.Get(res, countQuery, args...)
})
return res.Count, err
}
type rowCount struct {
Count int `db:"row_count"`
}
// Select allows to query only fields passed as parameter.
// c.Select("field1", "field2").All(&model)
// => SELECT field1, field2 FROM models
func (c *Connection) Select(fields ...string) *Query {
return c.Q().Select(fields...)
}
// Select allows to query only fields passed as parameter.
// c.Select("field1", "field2").All(&model)
// => SELECT field1, field2 FROM models
func (q *Query) Select(fields ...string) *Query {
for _, f := range fields {
if strings.TrimSpace(f) != "" {
q.addColumns = append(q.addColumns, f)
}
}
return q
}