Rockwell Rice
Rockwell Rice

Reputation: 3002

Heroku DB Query running thousands of times for 4 records

Not really sure what is going on. I have an application that worked fine until about a week ago. Now when I try to load a specific page that displays data it runs this query thousands of times and eventually times out. There are only 4 records that meet these criteria, and the query itself was working fine with as many as 4k + records (with some downtime but it is a personal app).

This is the output, over and over

...
2019-08-01T21:14:28.443577+00:00 app[web.1]: [9d861f61-b6eb-42a8-b3d2-a9132d974644]   CACHE (0.0ms)  SELECT COUNT(*) FROM "steps" WHERE (user_id = 1 AND status = 1)
...

The number in brackets changes but everything else just keeps running until it times out. I'm not sure if I have to dump a cache or something, never had this issue and I cannot figure out why it just keeps running this even though at the moment, if I run query on the db it returns 4 records.

This is the method generating the query, it hasn't changed

  # Returns the user's grade to the profile view
  def get_grade(user)
    completed_steps = Step.where("user_id = ? AND status = ?", user, 1)
    failed_steps    = Step.where("user_id = ? AND status = ?", user, 2)
    ongoing_steps   = Step.where("user_id = ? AND status = ?", user, 0)
    all_steps = completed_steps.count.to_f + failed_steps.count.to_f

    if all_steps.to_f > 0
      grade = completed_steps.count.to_f / all_steps * 100
      return grade.to_i
    else
      grade = 0
      return grade.to_i
    end
  end

Upvotes: 0

Views: 43

Answers (1)

jvillian
jvillian

Reputation: 20263

I realize this isn't your question, but I'm just wondering...

If you have a status enum in your Step model, couldn't you do:

# Returns the user's grade to the profile view
def get_grade(user)
  completed_steps = user.steps.completed?.count
  failed_steps    = user.steps.failed?.count
  all_steps       = completed_steps + failed_steps

  return ((completed_steps.to_f / all_steps) * 100).to_i if all_steps > 0
  0
end

Apologies, it was just a random observation.

Upvotes: 1

Related Questions