/
db-query.go
125 lines (104 loc) · 2.2 KB
/
db-query.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
package mongosvc
import (
"reflect"
underscore "github.com/ahl5esoft/golang-underscore"
"github.com/ahl5esoft/lite-go/contract"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
type dbQuery struct {
sorts bson.D
filter bson.M
pool *dbPool
model *modelMetadata
findOption *options.FindOptions
}
func (m dbQuery) Count() (int64, error) {
defer m.Reset()
c, err := m.pool.GetCollection(m.model)
if err != nil {
return 0, err
}
return c.CountDocuments(m.pool.Ctx, m.filter)
}
func (m *dbQuery) Order(fields ...string) contract.IDbQuery {
m.sort(1, fields)
return m
}
func (m *dbQuery) OrderByDesc(fields ...string) contract.IDbQuery {
m.sort(-1, fields)
return m
}
func (m *dbQuery) Reset() {
m.filter = make(bson.M)
m.findOption = options.Find()
m.sorts = bson.D{}
}
func (m *dbQuery) Skip(v int) contract.IDbQuery {
m.findOption = m.findOption.SetSkip(
int64(v),
)
return m
}
func (m *dbQuery) Take(v int) contract.IDbQuery {
m.findOption = m.findOption.SetLimit(
int64(v),
)
return m
}
func (m *dbQuery) ToArray(dst interface{}) error {
defer m.Reset()
c, err := m.pool.GetCollection(m.model)
if err != nil {
return err
}
if len(m.sorts) > 0 {
m.findOption = m.findOption.SetSort(m.sorts)
}
cur, err := c.Find(m.pool.Ctx, m.filter, m.findOption)
if err != nil {
return err
}
sliceType := reflect.SliceOf(
m.model.GetType(),
)
sliceValue := reflect.MakeSlice(sliceType, 0, 0)
for cur.Next(m.pool.Ctx) {
value := reflect.New(
m.model.GetType(),
)
temp := value.Interface()
cur.Decode(temp)
sliceValue = reflect.Append(
sliceValue,
value.Elem(),
)
}
reflect.ValueOf(dst).Elem().Set(sliceValue)
return nil
}
func (m *dbQuery) Where(args ...interface{}) contract.IDbQuery {
if len(args) == 0 {
return m
}
if f, ok := args[0].(bson.M); ok {
m.filter = f
}
return m
}
func (m *dbQuery) sort(flag int, fields []string) {
underscore.Chain(fields).Each(func(r string, _ int) {
m.sorts = append(m.sorts, bson.E{
Key: r,
Value: flag,
})
})
}
func newDbQuery(pool *dbPool, model *modelMetadata) contract.IDbQuery {
q := &dbQuery{
model: model,
pool: pool,
}
q.Reset()
return q
}