Cache the full book counter
This commit is contained in:
parent
0c3385200e
commit
d0670c0b62
2 changed files with 34 additions and 4 deletions
|
@ -3,6 +3,8 @@ package database
|
|||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/cihub/seelog"
|
||||
)
|
||||
|
||||
// Book metadata
|
||||
|
@ -84,7 +86,10 @@ func (db *pgDB) getBooks(active bool, query string, length int, start int) (book
|
|||
OrderExpr(order, rankParams...).
|
||||
Offset(start).
|
||||
Limit(length).
|
||||
SelectAndCountEstimate(100)
|
||||
SelectAndCountEstimate(1000)
|
||||
if query == "" && active {
|
||||
num = db.bookCount
|
||||
}
|
||||
return books, num, err
|
||||
}
|
||||
|
||||
|
@ -158,6 +163,28 @@ func (db *pgDB) IsBookActive(id string) bool {
|
|||
return active[0]
|
||||
}
|
||||
|
||||
func (db *pgDB) updateCounter() {
|
||||
var count int
|
||||
err := db.sql.Model(&Book{}).
|
||||
ColumnExpr("count(*)").
|
||||
Where("active = true").
|
||||
Select(&count)
|
||||
if err != nil {
|
||||
log.Error("Error updating count: ", err)
|
||||
} else {
|
||||
db.bookCount = count
|
||||
}
|
||||
}
|
||||
|
||||
func (db *pgDB) countUpdater() {
|
||||
periodicity := 61 * time.Minute
|
||||
|
||||
for true {
|
||||
db.updateCounter()
|
||||
time.Sleep(periodicity)
|
||||
}
|
||||
}
|
||||
|
||||
type columnq struct {
|
||||
column string
|
||||
value string
|
||||
|
|
|
@ -31,8 +31,9 @@ const (
|
|||
)
|
||||
|
||||
type pgDB struct {
|
||||
sql *pg.DB
|
||||
tags []string
|
||||
sql *pg.DB
|
||||
tags []string
|
||||
bookCount int
|
||||
}
|
||||
|
||||
// Options for the database
|
||||
|
@ -58,8 +59,10 @@ func Init(options Options) (DB, error) {
|
|||
})
|
||||
// TODO: create db
|
||||
|
||||
db := pgDB{sql, []string{}}
|
||||
var db pgDB
|
||||
db.sql = sql
|
||||
go db.tagUpdater()
|
||||
go db.countUpdater()
|
||||
|
||||
return &db, nil
|
||||
}
|
||||
|
|
Reference in a new issue