-
Notifications
You must be signed in to change notification settings - Fork 0
/
gormx.go
211 lines (184 loc) · 4.8 KB
/
gormx.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
package gormx
import (
"bytes"
"fmt"
"reflect"
"strings"
"time"
"github.com/go-dawn/dawn/config"
"github.com/jinzhu/copier"
jsoniter "github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"gorm.io/gorm"
)
type Dao struct {
ID uint32 `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *gorm.DeletedAt `gorm:"index"`
}
// Pagination contains page, page size, total count
// and list data
type Pagination struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
Total int `json:"total"`
Data interface{} `json:"data"`
}
// Paginate gets pagination based on index query and transfer
// dao to domain object
func Paginate(scope *gorm.DB, args *fasthttp.Args, daos, data interface{}) (*Pagination, error) {
q := indexQuery{args}
page, pageSize := q.pageInfo()
scope = scope.Scopes(
scopeSearch(q.search()),
scopeSort(q.sort()),
scopePaginate(page, pageSize),
)
var (
total int64
errChan = make(chan error)
)
go func() {
errChan <- scope.Find(daos).Error
}()
// get total count
err1, err2 := <-errChan, scope.Model(daos).Count(&total).Error
if err1 != nil && err1 != gorm.ErrRecordNotFound {
return nil, err1
}
if err2 != nil {
return nil, err2
}
if err := copier.Copy(data, daos); err != nil {
return nil, err
}
return &Pagination{
Page: page,
PageSize: pageSize,
Total: int(total),
// transfer pointer to slice
Data: reflect.ValueOf(data).Elem().Interface(),
}, nil
}
// indexQuery wraps helper functions of query string
type indexQuery struct {
*fasthttp.Args
}
// search gets search data in json format
func (q indexQuery) search() []byte {
return q.Peek("search")
}
// sort gets sort params
func (q indexQuery) sort() []byte {
return q.Peek("sort")
}
// page gets index page
func (q indexQuery) page() int {
n := q.GetUintOrZero("page")
if n <= 0 {
return 1
}
return n
}
// pageSize gets page size of index
func (q indexQuery) pageSize() int {
n := q.GetUintOrZero("pageSize")
if n <= 0 {
return config.GetInt("http.pageSize", 15)
}
return n
}
// pageInfo gets page and page size
func (q indexQuery) pageInfo() (int, int) {
return q.page(), q.pageSize()
}
func scopePaginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
return func(scope *gorm.DB) *gorm.DB {
offset := (page - 1) * pageSize
return scope.Offset(offset).Limit(pageSize)
}
}
func scopeSearch(search []byte) func(db *gorm.DB) *gorm.DB {
return func(scope *gorm.DB) *gorm.DB {
params := map[string]interface{}{}
if err := jsoniter.Unmarshal(search, ¶ms); err == nil {
//"name":"jone" => name like ?, %jone%
//"name":["jone","kj"] => name in (?), ["jone","kj"]
//"free": true | false => free = ?, true
//"name$<>": "jone" name <> ? , "jone"
//"date$<>":["2020-12-12",""] date not in (?), "", ""
//"date$><":["2020-12-12",""] date between ? and ?, "", ""
//"date$<":"" => date < ?
//"date$<=":"" => date <= ?
//"date$>=":"" => date >= ?
//"date$>":"" => date > ?
for key, val := range params {
// 使用$分割列名和操作符
strs := strings.Split(key, "$")
// 不带操作符
if len(strs) == 1 {
column := strs[0]
// 根据值的类型附加过滤条件
switch reflect.TypeOf(val).Kind() {
case reflect.String:
// 字符串全部用like过滤
scope = scope.Where(column+" LIKE ?", fmt.Sprintf("%%%v%%", val))
case reflect.Bool, reflect.Float64:
scope = scope.Where(column+" = ?", val)
case reflect.Slice, reflect.Array:
// 数组使用 IN
if arr, ok := val.([]interface{}); ok {
scope = scope.Where(column+" IN (?)", arr)
}
}
}
// 带操作符
if len(strs) == 2 {
column, opt := strs[0], strs[1]
switch opt {
// 比较操作符
case ">", ">=", "<", "<=":
switch val.(type) {
// 只支持字符串和数字类型
case string, float64:
scope = scope.Where(fmt.Sprintf("%s %s ?", column, opt), val)
}
case "><": // between 操作符
switch reflect.TypeOf(val).Kind() {
case reflect.Slice, reflect.Array:
// 只支持长度为2的数组
if arr, ok := val.([]interface{}); ok && len(arr) == 2 {
scope = scope.Where(strs[0]+" BETWEEN ? AND ?", arr[0], arr[1])
}
}
}
}
// 忽略其他情况
}
}
return scope
}
}
var sortSep = []byte(",")
func scopeSort(sort []byte) func(db *gorm.DB) *gorm.DB {
return func(scope *gorm.DB) *gorm.DB {
if len(sort) == 0 {
return scope
}
buf := new(bytes.Buffer)
for _, key := range bytes.Split(sort, sortSep) {
if key[0] == '-' {
buf.Write(key[1:])
buf.WriteString(" desc,")
} else {
buf.Write(key)
buf.WriteByte(',')
}
}
if buf.Len() != 0 {
scope = scope.Order(buf.String()[:buf.Len()-1])
}
return scope
}
}