Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fast count #115

Merged
merged 1 commit into from Apr 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 8 additions & 8 deletions app/views/admin/dashboard/index.html.erb
Expand Up @@ -10,7 +10,7 @@
Total Bookmarks
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= Bookmark.count %>
<%= FastCount.new(Bookmark.all).call %>
</dd>
</dl>
</div>
Expand All @@ -22,7 +22,7 @@
Total Users
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= User.count %>
<%= FastCount.new(User.all).call %>
</dd>
</dl>
</div>
Expand All @@ -35,7 +35,7 @@
Total Tags
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= Tag.count %>
<%= FastCount.new(Tag.all).call %>
</dd>
</dl>
</div>
Expand All @@ -48,7 +48,7 @@
Total Likes
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= Like.count %>
<%= FastCount.new(Like.all).call %>
</dd>
</dl>
</div>
Expand All @@ -61,7 +61,7 @@
Total Clicks
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= Click.count %>
<%= FastCount.new(Click.all).call %>
</dd>
</dl>
</div>
Expand All @@ -74,7 +74,7 @@
Total Comments
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= Comment.count %>
<%= FastCount.new(Comment.all).call %>
</dd>
</dl>
</div>
Expand All @@ -87,7 +87,7 @@
Total Follows
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= Follow.count %>
<%= FastCount.new(Follow.all).call %>
</dd>
</dl>
</div>
Expand All @@ -100,7 +100,7 @@
Total Subscriptions
</dt>
<dd class="mt-1 text-3xl leading-9 font-semibold text-gray-900">
<%= TagSubscription.count %>
<%= FastCount.new(TagSubscription.all).call %>
</dd>
</dl>
</div>
Expand Down
23 changes: 23 additions & 0 deletions config/initializers/fast_count.rb
@@ -0,0 +1,23 @@
# frozen_string_literal: true

# usage
# FastCount.new(User.all).call
# => 826
# FastCount.new(User.where("id > 200")).call
# => 665

class FastCount
attr_reader :scope, :sql

def initialize(scope)
@scope = scope
@sql = scope.to_sql
end

def call
explain_sql = "explain (format json) #{sql}"
result = ApplicationRecord.connection.execute(explain_sql)[0]["QUERY PLAN"]
json = JSON.parse(result)
json[0]["Plan"]["Plan Rows"].to_i
end
end