mirror of
https://github.com/gofiber/storage.git
synced 2025-10-05 08:37:10 +08:00
Fix GC deleting values without expiry (#54)
* Test MYSQL Fix * Test * Add postgres * Fix mysql * Fix sqlite
This commit is contained in:
@@ -82,11 +82,11 @@ func New(config ...Config) *Storage {
|
||||
sqlInsert: fmt.Sprintf("INSERT INTO %s (k, v, e) VALUES (?,?,?) ON DUPLICATE KEY UPDATE v = ?, e = ?", cfg.Table),
|
||||
sqlDelete: fmt.Sprintf("DELETE FROM %s WHERE k=?", cfg.Table),
|
||||
sqlReset: fmt.Sprintf("DELETE FROM %s;", cfg.Table),
|
||||
sqlGC: fmt.Sprintf("DELETE FROM %s WHERE e <= ?", cfg.Table),
|
||||
sqlGC: fmt.Sprintf("DELETE FROM %s WHERE e <= ? AND e != 0", cfg.Table),
|
||||
}
|
||||
|
||||
// Start garbage collector
|
||||
go store.gc()
|
||||
go store.gcTicker()
|
||||
|
||||
return store
|
||||
}
|
||||
@@ -160,8 +160,8 @@ func (s *Storage) Close() error {
|
||||
return s.db.Close()
|
||||
}
|
||||
|
||||
// Garbage collector to delete expired keys
|
||||
func (s *Storage) gc() {
|
||||
// gcTicker starts the gc ticker
|
||||
func (s *Storage) gcTicker() {
|
||||
ticker := time.NewTicker(s.gcInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
@@ -169,7 +169,12 @@ func (s *Storage) gc() {
|
||||
case <-s.done:
|
||||
return
|
||||
case t := <-ticker.C:
|
||||
_, _ = s.db.Exec(s.sqlGC, t.Unix())
|
||||
s.gc(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gc deletes all expired entries
|
||||
func (s *Storage) gc(t time.Time) {
|
||||
_, _ = s.db.Exec(s.sqlGC, t.Unix())
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -122,6 +123,31 @@ func Test_MYSQL_Reset(t *testing.T) {
|
||||
utils.AssertEqual(t, true, len(result) == 0)
|
||||
}
|
||||
|
||||
func Test_MYSQL_GC(t *testing.T) {
|
||||
var (
|
||||
testVal = []byte("doe")
|
||||
)
|
||||
|
||||
// This key should expire
|
||||
err := testStore.Set("john", testVal, time.Nanosecond)
|
||||
utils.AssertEqual(t, nil, err)
|
||||
|
||||
testStore.gc(time.Now())
|
||||
row := testStore.db.QueryRow(testStore.sqlSelect, "john")
|
||||
err = row.Scan(nil, nil)
|
||||
utils.AssertEqual(t, sql.ErrNoRows, err)
|
||||
|
||||
// This key should not expire
|
||||
err = testStore.Set("john", testVal, 0)
|
||||
utils.AssertEqual(t, nil, err)
|
||||
|
||||
testStore.gc(time.Now())
|
||||
val, err := testStore.Get("john")
|
||||
utils.AssertEqual(t, nil, err)
|
||||
utils.AssertEqual(t, testVal, val)
|
||||
|
||||
}
|
||||
|
||||
func Test_MYSQL_Close(t *testing.T) {
|
||||
utils.AssertEqual(t, nil, testStore.Close())
|
||||
}
|
||||
|
Reference in New Issue
Block a user