From 9d42e975ef677794e5ff3e4829bc5bdcdcd11003 Mon Sep 17 00:00:00 2001 From: mchavez Date: Tue, 27 Aug 2024 22:53:40 -0600 Subject: [PATCH] Fix bug when database is locked --- pkg/uhttp/dbcache.go | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/pkg/uhttp/dbcache.go b/pkg/uhttp/dbcache.go index 6158d196..64e43f6b 100644 --- a/pkg/uhttp/dbcache.go +++ b/pkg/uhttp/dbcache.go @@ -85,6 +85,7 @@ func NewDBCache(ctx context.Context, cfg CacheConfig) (*DBCache, error) { if err != nil { l.Debug("Failed to delete expired cache entries", zap.Error(err)) } + return } } }() @@ -280,7 +281,7 @@ func (d *DBCache) Select(ctx context.Context, key string) ([]byte, error) { } l := ctxzap.Extract(ctx) - rows, err := d.db.Query("SELECT data FROM http_cache where key = ?", key) + rows, err := d.db.Query("SELECT data FROM http_cache where key = '?'", key) if err != nil { l.Debug(errQueryingTable, zap.Error(err)) return nil, err @@ -311,7 +312,7 @@ func (d *DBCache) Remove(ctx context.Context, key string) error { return err } - _, err = d.db.Exec("DELETE FROM http_cache WHERE key = ?", key) + _, err = d.db.Exec("DELETE FROM http_cache WHERE key = '?'", key) if err != nil { if errtx := tx.Rollback(); errtx != nil { l.Debug(failRollback, zap.Error(errtx)) @@ -357,8 +358,9 @@ func (d *DBCache) Expired(expiration int64) bool { // Delete all expired items from the cache. func (d *DBCache) DeleteExpired(ctx context.Context) error { var ( - expiration int64 - key string + expiration int64 + key string + mapExpiredKeys = make(map[string]bool) ) if d.IsNilConnection() { @@ -376,18 +378,30 @@ func (d *DBCache) DeleteExpired(ctx context.Context) error { for rows.Next() { err = rows.Scan(&key, &expiration) if err != nil { - l.Debug("error scanning rows", zap.Error(err)) + l.Debug("error scanning rows", + zap.Error(err), + zap.String("key", key), + ) return err } - if d.Expired(expiration) { - err := d.Remove(ctx, key) - if err != nil { - l.Debug("error removing rows", zap.Error(err)) - return err + mapExpiredKeys[key] = d.Expired(expiration) + } + + go func() { + for key, isExpired := range mapExpiredKeys { + if isExpired { + err := d.Remove(ctx, key) + if err != nil { + l.Debug("error removing rows", + zap.Error(err), + zap.String("key", key), + ) + return + } } } - } + }() return nil }