-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpagorminator.go
More file actions
71 lines (55 loc) · 1.51 KB
/
pagorminator.go
File metadata and controls
71 lines (55 loc) · 1.51 KB
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
package pagorminator
import (
"gorm.io/gorm"
)
const (
countKey = "pagorminator.count"
)
var _ gorm.Plugin = new(PaGorminator)
// PaGorminator Gorm plugin to add total elements and total pages to your pagination query.
type PaGorminator struct {
Debug bool
}
func (p PaGorminator) Name() string {
return "pagorminator"
}
func (p PaGorminator) Initialize(db *gorm.DB) error {
err := db.Callback().Query().Before("gorm:query").Register("pagorminator:count", p.count)
if err != nil {
return err
}
return nil
}
func (p PaGorminator) count(db *gorm.DB) {
if db.Statement.Schema == nil && db.Statement.Table == "" {
return
}
if pageable, ok := p.getPageRequest(db); ok && !pageable.isTotalElementsSet() {
tx := db.Session(&gorm.Session{Context: db.Statement.Context})
if p.Debug {
tx = tx.Debug()
}
delete(tx.Statement.Clauses, "LIMIT")
delete(tx.Statement.Clauses, "OFFSET")
var totalElements int64
tx = tx.Set(countKey, true)
tx.Count(&totalElements)
if tx.Error != nil {
_ = db.AddError(tx.Error)
return
}
pageable.setTotalElements(totalElements)
}
}
func (p PaGorminator) getPageRequest(db *gorm.DB) (*Pagination, bool) {
if value, ok := db.Get(pagorminatorClause); ok { //nolint:nestif // checking many fields in an if way
if paginationClause, okP := value.(*Pagination); okP {
if countValue, okCount := db.Get(countKey); !okCount {
if isCount, hasCount := countValue.(bool); !hasCount || !isCount {
return paginationClause, true
}
}
}
}
return nil, false
}