🧹 introduce reset and close

This commit is contained in:
Fenny
2020-11-06 01:41:46 +01:00
parent 1634e44e61
commit f9a30234b9
28 changed files with 125 additions and 87 deletions

View File

@@ -19,7 +19,7 @@ type Storage struct {
sqlSelect string
sqlInsert string
sqlDelete string
sqlClear string
sqlReset string
sqlGC string
}
@@ -77,7 +77,7 @@ func New(config ...Config) *Storage {
}
// Drop table if set to true
if cfg.Clear {
if cfg.Reset {
if _, err = db.Exec(fmt.Sprintf(dropQuery, cfg.Table)); err != nil {
_ = db.Close()
panic(err)
@@ -100,7 +100,7 @@ func New(config ...Config) *Storage {
sqlSelect: fmt.Sprintf(`SELECT v, e FROM %s WHERE k=$1;`, cfg.Table),
sqlInsert: fmt.Sprintf("INSERT INTO %s (k, v, e) VALUES ($1, $2, $3) ON CONFLICT (k) DO UPDATE SET v = $4, e = $5", cfg.Table),
sqlDelete: fmt.Sprintf("DELETE FROM %s WHERE k=$1", cfg.Table),
sqlClear: fmt.Sprintf("DELETE FROM %s;", cfg.Table),
sqlReset: fmt.Sprintf("DELETE FROM %s;", cfg.Table),
sqlGC: fmt.Sprintf("DELETE FROM %s WHERE e <= $1", cfg.Table),
}
@@ -156,12 +156,17 @@ func (s *Storage) Delete(key string) error {
return err
}
// Clear all entries, including unexpired
func (s *Storage) Clear() error {
_, err := s.db.Exec(s.sqlClear)
// Reset all entries, including unexpired
func (s *Storage) Reset() error {
_, err := s.db.Exec(s.sqlReset)
return err
}
// Close the database
func (s *Storage) Close() error {
return s.db.Close()
}
// GC deletes all expired entries
func (s *Storage) gc() {
tick := time.NewTicker(s.gcInterval)