Skip to content

Commit

Permalink
fix: return 0 if there is no job with the given state
Browse files Browse the repository at this point in the history
  • Loading branch information
JorgeLNJunior committed Sep 1, 2024
1 parent 69e16bf commit ac0c720
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
15 changes: 9 additions & 6 deletions queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,12 +303,12 @@ func (q *SQLiteQueue) Count(ctx context.Context) (*JobCount, error) {
row := q.readDB.QueryRowContext(
ctx,
`SELECT COUNT(rowid) AS total,
SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as pending,
SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as running,
SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as retry,
SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as failed,
SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as completed
from queuelite_job`,
COALESCE(SUM(CASE WHEN state = ? THEN 1 ELSE 0 END), 0) as pending,
COALESCE(SUM(CASE WHEN state = ? THEN 1 ELSE 0 END), 0) as running,
COALESCE(SUM(CASE WHEN state = ? THEN 1 ELSE 0 END), 0) as retry,
COALESCE(SUM(CASE WHEN state = ? THEN 1 ELSE 0 END), 0) as failed,
COALESCE(SUM(CASE WHEN state = ? THEN 1 ELSE 0 END), 0) as completed
from queuelite_job`,
JobStatePending,
JobStateRunning,
JobStateRetry,
Expand All @@ -325,6 +325,9 @@ func (q *SQLiteQueue) Count(ctx context.Context) (*JobCount, error) {
&count.Failed,
&count.Completed,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return &JobCount{}, nil
}
return nil, err
}

Expand Down
21 changes: 21 additions & 0 deletions queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ func TestIsEmpty(t *testing.T) {
})

t.Run("should return false if the queue is not empty", func(tt *testing.T) {
os.Remove(dbDir)

queue, err := queuelite.NewSQLiteQueue(dbDir)
if err != nil {
t.Error(err)
Expand Down Expand Up @@ -242,6 +244,25 @@ func TestCount(t *testing.T) {
tt.Errorf("expected retry to be 1 but got %d", count.Retry)
}
})

t.Run("should return an empty struct if there is no jobs in the queue", func(tt *testing.T) {
os.Remove(dbDir)

queue, err := queuelite.NewSQLiteQueue(dbDir)
if err != nil {
t.Error(err)
}
defer queue.Close()

count, err := queue.Count(context.Background())
if err != nil {
tt.Error(err)
}

if count.Total != 0 {
tt.Errorf("expected total to be 0 but got %d", count.Total)
}
})
}

func TestComplete(t *testing.T) {
Expand Down

0 comments on commit ac0c720

Please sign in to comment.