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.
25 lines
424 B
Ruby
25 lines
424 B
Ruby
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}")
|
|
json = JSON.parse(result["QUERY PLAN"])
|
|
json.first["Plan"]
|
|
end
|
|
|
|
def row_count
|
|
query_plan["Plan Rows"]
|
|
end
|
|
|
|
def sql
|
|
relation.reorder(nil).to_sql
|
|
end
|
|
|
|
memoize :query_plan
|
|
end
|