Cache the full book counter

This commit is contained in:
Las Zenow 2017-05-19 00:27:14 +00:00
parent 0c3385200e
commit d0670c0b62
2 changed files with 34 additions and 4 deletions

View file

@ -3,6 +3,8 @@ package database
import ( import (
"strings" "strings"
"time" "time"
log "github.com/cihub/seelog"
) )
// Book metadata // Book metadata
@ -84,7 +86,10 @@ func (db *pgDB) getBooks(active bool, query string, length int, start int) (book
OrderExpr(order, rankParams...). OrderExpr(order, rankParams...).
Offset(start). Offset(start).
Limit(length). Limit(length).
SelectAndCountEstimate(100) SelectAndCountEstimate(1000)
if query == "" && active {
num = db.bookCount
}
return books, num, err return books, num, err
} }
@ -158,6 +163,28 @@ func (db *pgDB) IsBookActive(id string) bool {
return active[0] 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 { type columnq struct {
column string column string
value string value string

View file

@ -31,8 +31,9 @@ const (
) )
type pgDB struct { type pgDB struct {
sql *pg.DB sql *pg.DB
tags []string tags []string
bookCount int
} }
// Options for the database // Options for the database
@ -58,8 +59,10 @@ func Init(options Options) (DB, error) {
}) })
// TODO: create db // TODO: create db
db := pgDB{sql, []string{}} var db pgDB
db.sql = sql
go db.tagUpdater() go db.tagUpdater()
go db.countUpdater()
return &db, nil return &db, nil
} }