search: fix underestimation of page count for blank searches.

Bug: In Postgres 13, getting the count of a blank search underestimated
the page count by a large margin (~700,000 posts).

The query we were executing was this:

    EXPLAIN (FORMAT JSON) SELECT * FROM posts ORDER BY id DESC

The `ORDER BY id DESC` clause triggered a parallel seq scan query plan
in Postgres 13, which for some reason causes Postgres to underestimate
the row count by large amount in each parallel branch.

Getting rid of the ORDER BY clause makes it do a regular seq scan, which
gives an accurate estimate.
This commit is contained in:
evazion
2021-02-18 04:06:11 -06:00
parent af84314c38
commit 93f6e935a8
2 changed files with 11 additions and 2 deletions

View File

@@ -1,5 +1,10 @@
class ExplainParser < Struct.new(:sql)
class ExplainParser
extend Memoist
attr_reader :relation
def initialize(relation)
@relation = relation
end
def query_plan
result = ApplicationRecord.connection.select_one("EXPLAIN (FORMAT JSON) #{sql}")
@@ -11,5 +16,9 @@ class ExplainParser < Struct.new(:sql)
query_plan["Plan Rows"]
end
def sql
relation.reorder(nil).to_sql
end
memoize :query_plan
end

View File

@@ -851,7 +851,7 @@ class PostQueryBuilder
end
def estimated_row_count
ExplainParser.new(build.to_sql).row_count
ExplainParser.new(build).row_count
end
def cached_count