use sync.Once to lazy load cache
This commit is contained in:
parent
30200d5ff4
commit
709f8f1302
|
@ -11,21 +11,13 @@ import (
|
|||
)
|
||||
|
||||
type interestCache struct {
|
||||
sync.Mutex
|
||||
loaded bool
|
||||
sync.Once
|
||||
postings map[time.Time][]posting.Posting
|
||||
}
|
||||
|
||||
var icache interestCache
|
||||
|
||||
func loadInterestCache(db *gorm.DB) {
|
||||
icache.Lock()
|
||||
defer icache.Unlock()
|
||||
|
||||
if icache.loaded {
|
||||
return
|
||||
}
|
||||
|
||||
var postings []posting.Posting
|
||||
result := db.Where("account like ?", "Income:Interest:%").Find(&postings)
|
||||
if result.Error != nil {
|
||||
|
@ -33,16 +25,15 @@ func loadInterestCache(db *gorm.DB) {
|
|||
}
|
||||
|
||||
icache.postings = lo.GroupBy(postings, func(p posting.Posting) time.Time { return p.Date })
|
||||
icache.loaded = true
|
||||
}
|
||||
|
||||
func IsInterest(db *gorm.DB, p posting.Posting) bool {
|
||||
icache.Do(func() { loadInterestCache(db) })
|
||||
|
||||
if p.Commodity != "INR" {
|
||||
return false
|
||||
}
|
||||
|
||||
loadInterestCache(db)
|
||||
|
||||
for _, ip := range icache.postings[p.Date] {
|
||||
if ip.Date.Equal(p.Date) &&
|
||||
-ip.Amount == p.Amount &&
|
||||
|
|
|
@ -14,21 +14,13 @@ import (
|
|||
)
|
||||
|
||||
type priceCache struct {
|
||||
sync.Mutex
|
||||
loaded bool
|
||||
sync.Once
|
||||
pricesTree map[string]*btree.BTree
|
||||
}
|
||||
|
||||
var pcache priceCache
|
||||
|
||||
func loadPriceCache(db *gorm.DB) {
|
||||
pcache.Lock()
|
||||
defer pcache.Unlock()
|
||||
|
||||
if pcache.loaded {
|
||||
return
|
||||
}
|
||||
|
||||
var prices []price.Price
|
||||
result := db.Find(&prices)
|
||||
if result.Error != nil {
|
||||
|
@ -58,12 +50,11 @@ func loadPriceCache(db *gorm.DB) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
pcache.loaded = true
|
||||
}
|
||||
|
||||
func GetMarketPrice(db *gorm.DB, p posting.Posting, date time.Time) float64 {
|
||||
loadPriceCache(db)
|
||||
pcache.Do(func() { loadPriceCache(db) })
|
||||
|
||||
if p.Commodity == "INR" {
|
||||
return p.Amount
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue