module MR::Query::CountRelation

Public Class Methods

new(relation) click to toggle source
# File lib/mr/query.rb, line 51
def self.new(relation)
  relation = relation.except(:select, :order)
  if relation.group_values.empty?
    relation
  else
    # use `SELECT 1` to count grouped results, this avoids trying to use
    # a column which may not work because it's not part of the group by
    # (Postgres errors if a column is selected that isn't part of the
    # sql GROUP BY)
    subquery = relation.select('1').to_sql
    relation.klass.scoped.from("(#{subquery}) AS grouped_records")
  end
end