/
options.go
78 lines (66 loc) · 1.53 KB
/
options.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
package repository
import (
"fmt"
"github.com/jinzhu/gorm"
"strings"
)
type Option interface {
Sql(db *gorm.DB) *gorm.DB
}
type limitOption struct {
offset int
limit int
}
// create a limitOption
func Limit(offset, limit int) *limitOption {
return &limitOption{offset, limit}
}
// create a limitOption
func Limit32(offset, limit int32) *limitOption {
return &limitOption{int(offset), int(limit)}
}
func (lo *limitOption) Sql(db *gorm.DB) *gorm.DB {
return db.Offset(lo.offset).Limit(lo.limit)
}
type orderOption struct {
field FieldInterface
order ORDER
}
// ParseOrderOption parse string to orderOption, case insensitive
//
// CREATE_TIME -> create_time asc
//
// CREATE_TIME_DESC -> create_time desc
//
// CREATE_TIME DESC -> create_time desc
//
// CREATE_TIME_ASC -> create_time asc
//
// CREATE_TIME ASC -> create_time asc
func ParseOrderOption(str string) Option {
str = strings.ToLower(str)
if strings.HasSuffix(str, "desc") {
return SimpleField(str[:len(str)-5]).Desc()
} else if strings.HasSuffix(str, "asc") {
return SimpleField(str[:len(str)-4]).Asc()
}
return SimpleField(str).Asc()
}
func (oo *orderOption) Sql(db *gorm.DB) *gorm.DB {
return db.Order(fmt.Sprintf("%s %s", oo.field, oo.order.String()))
}
type selectOption struct {
columns []FieldInterface
}
func (so *selectOption) Sql(db *gorm.DB) *gorm.DB {
var cols []string
for _, c := range so.columns {
cols = append(cols, c.Column())
}
return db.Select(cols)
}
func Select(cols ...FieldInterface) *selectOption {
return &selectOption{
columns: cols,
}
}