diff --git a/lib/database/books.go b/lib/database/books.go index 6f8720e..c69938d 100644 --- a/lib/database/books.go +++ b/lib/database/books.go @@ -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 diff --git a/lib/database/database.go b/lib/database/database.go index 77f5d81..91edf3e 100644 --- a/lib/database/database.go +++ b/lib/database/database.go @@ -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 }