-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathgorm4.go
86 lines (74 loc) · 2.39 KB
/
gorm4.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
package gorm4
import (
"time"
"github.com/jinzhu/gorm"
)
func getGormDB() *gorm.DB {
db, _ := gorm.Open("mysql",
"user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
return db
}
//go:generate goqueryset -in gorm4.go
// User struct represents user model.
// gen:qs
type User struct {
gorm.Model
Rating int
RatingMarks int
}
func getTodayBegin() time.Time {
year, month, day := time.Now().Date()
return time.Date(year, month, day, 0, 0, 0, 0, time.Now().Location())
}
// WithMaxRating is our defined on UserQuerySet method, that selects
// users with max rating.
// UserQuerySet is an autogenerated struct with a lot of typesafe methods.
// We can define any methods on it because it's in the same package
func (qs UserQuerySet) WithMaxRating(minMarks int) UserQuerySet {
return qs.RatingMarksGte(minMarks).OrderDescByRating()
}
// RegisteredToday returns only users registered today
func (qs UserQuerySet) RegisteredToday() UserQuerySet {
// autogenerated typesafe method CreatedAtGte(time.Time)
return qs.CreatedAtGte(getTodayBegin())
}
// now we can parametrize it
const minRatingMarks = 10
// GetUsersWithMaxRating returns limit users with max rating
func GetUsersWithMaxRating(limit int) ([]User, error) {
var users []User
err := NewUserQuerySet(getGormDB()).
WithMaxRating(minRatingMarks). // reuse our method
Limit(limit). // autogenerated typesafe method Limit(int)
All(&users) // autogenerated typesafe method All(*[]User)
if err != nil {
return nil, err
}
return users, nil
}
// GetUsersRegisteredToday returns limit users registered today
func GetUsersRegisteredToday(limit int) ([]User, error) {
var users []User
err := NewUserQuerySet(getGormDB()).
RegisteredToday(). // reuse our method
Limit(limit). // autogenerated typesafe method Limit(int)
All(&users) // autogenerated typesafe method All(*[]User)
if err != nil {
return nil, err
}
return users, nil
}
// GetUsersRegisteredTodayWithMaxRating returns limit users
// registered today and with max rating
func GetUsersRegisteredTodayWithMaxRating(limit int) ([]User, error) {
var users []User
err := NewUserQuerySet(getGormDB()).
RegisteredToday(). // reuse our method
WithMaxRating(minRatingMarks). // reuse our method
Limit(limit).
All(&users) // autogenerated typesafe method All(*[]User)
if err != nil {
return nil, err
}
return users, nil
}