Skip to content

Commit

Permalink
Fix bug when database is locked
Browse files Browse the repository at this point in the history
  • Loading branch information
mchavez committed Aug 28, 2024
1 parent 40c5957 commit 9d42e97
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions pkg/uhttp/dbcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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() {
Expand All @@ -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
}

0 comments on commit 9d42e97

Please sign in to comment.