diff --git a/app/models/application_record.rb b/app/models/application_record.rb index bfdad82f9..fb38ec9a9 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -3,12 +3,15 @@ class ApplicationRecord < ActiveRecord::Base include Purgeable + # see for details + # on the `pg_class` table QUERY_ESTIMATED_COUNT = <<~SQL.squish.freeze SELECT ( (reltuples / GREATEST(relpages, 1)) * (pg_relation_size(?) / (GREATEST(current_setting('block_size')::integer, 1))) )::bigint AS count - FROM pg_class WHERE relname = ?; + FROM pg_class + WHERE relname = ? AND relkind = 'r'; SQL # Computes an estimated count of the number of rows using stats collected by VACUUM @@ -18,7 +21,7 @@ class ApplicationRecord < ActiveRecord::Base query = sanitize_sql_array([QUERY_ESTIMATED_COUNT, table_name, table_name]) result = connection.execute(query) - count = result.max_by(&:values)["count"] # sometimes is an array of hashes, for ex. [{"count" => 0}, [{"count" => 1000}] + count = result.first["count"] result.clear # PG::Result is manually managed in memory, we need to release its resources count end