package stmtcache
import (
"container/list"
"github.com/jackc/pgx/v5/pgconn"
)
type LRUCache struct {
cap int
m map [string ]*list .Element
l *list .List
invalidStmts []*pgconn .StatementDescription
}
func NewLRUCache (cap int ) *LRUCache {
return &LRUCache {
cap : cap ,
m : make (map [string ]*list .Element ),
l : list .New (),
}
}
func (c *LRUCache ) Get (key string ) *pgconn .StatementDescription {
if el , ok := c .m [key ]; ok {
c .l .MoveToFront (el )
return el .Value .(*pgconn .StatementDescription )
}
return nil
}
func (c *LRUCache ) Put (sd *pgconn .StatementDescription ) {
if sd .SQL == "" {
panic ("cannot store statement description with empty SQL" )
}
if _ , present := c .m [sd .SQL ]; present {
return
}
if c .l .Len () == c .cap {
c .invalidateOldest ()
}
el := c .l .PushFront (sd )
c .m [sd .SQL ] = el
}
func (c *LRUCache ) Invalidate (sql string ) {
if el , ok := c .m [sql ]; ok {
delete (c .m , sql )
c .invalidStmts = append (c .invalidStmts , el .Value .(*pgconn .StatementDescription ))
c .l .Remove (el )
}
}
func (c *LRUCache ) InvalidateAll () {
el := c .l .Front ()
for el != nil {
c .invalidStmts = append (c .invalidStmts , el .Value .(*pgconn .StatementDescription ))
el = el .Next ()
}
c .m = make (map [string ]*list .Element )
c .l = list .New ()
}
func (c *LRUCache ) HandleInvalidated () []*pgconn .StatementDescription {
invalidStmts := c .invalidStmts
c .invalidStmts = nil
return invalidStmts
}
func (c *LRUCache ) Len () int {
return c .l .Len ()
}
func (c *LRUCache ) Cap () int {
return c .cap
}
func (c *LRUCache ) invalidateOldest () {
oldest := c .l .Back ()
sd := oldest .Value .(*pgconn .StatementDescription )
c .invalidStmts = append (c .invalidStmts , sd )
delete (c .m , sd .SQL )
c .l .Remove (oldest )
}
The pages are generated with Golds v0.6.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .