Skip to content

Commit 59835b9

Browse files
committed
add statistics store
1 parent 501c462 commit 59835b9

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

store/statistic.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package store
2+
3+
import (
4+
"context"
5+
)
6+
7+
type IStatisticsStore[M any] interface {
8+
IBaseStore[M]
9+
SumByGroup(ctx context.Context, group string, selectSQL string, conditions string, args ...interface{}) ([]*M, error)
10+
SumByGroupPage(ctx context.Context, group string, order interface{}, offset, limit int, selectSQL string, conditions string, args ...interface{}) ([]*M, int64, error)
11+
}
12+
13+
type StatisticsStore[M any] struct {
14+
Store[M]
15+
db IDB `autowired:""`
16+
name string
17+
}
18+
19+
func (s *StatisticsStore[M]) OnComplete() {
20+
s.Store.OnComplete()
21+
}
22+
23+
func (s *StatisticsStore[M]) SumByGroup(ctx context.Context, group string, selectSQL string, conditions string, args ...interface{}) ([]*M, error) {
24+
db := s.db.DB(ctx)
25+
results := make([]*M, 0)
26+
err := db.Model(s.Model).Select(selectSQL).Where(conditions, args...).Group(group).Scan(&results).Error
27+
if err != nil {
28+
return nil, err
29+
}
30+
return results, nil
31+
}
32+
33+
func (s *StatisticsStore[M]) SumByGroupPage(ctx context.Context, group string, order interface{}, offset, limit int, selectSQL string, conditions string, args ...interface{}) ([]*M, int64, error) {
34+
db := s.db.DB(ctx)
35+
results := make([]*M, 0)
36+
var count int64
37+
err := db.Model(s.Model).Select(selectSQL).Where(conditions, args...).Group(group).Count(&count).Error
38+
if err != nil {
39+
return nil, 0, err
40+
}
41+
err = db.Model(s.Model).Select(selectSQL).Where(conditions, args...).Group(group).Order(order).Limit(limit).Offset(offset).Scan(&results).Error
42+
if err != nil {
43+
return nil, 0, err
44+
}
45+
return results, count, nil
46+
}

0 commit comments

Comments
 (0)