未验证 提交 d38e5d27 编写于 作者: R Ryuta Kamizono 提交者: Jeremy Daer

Suppress `DISTINCT` clause outside aggregate function

`DISTINCT` clause is applied inside aggregate function by
`operation_over_aggregate_column` if needed. Unneeded outside aggregate
function.

```ruby
  # Before
  author.unique_categorized_posts.count
  # => SELECT DISTINCT COUNT(DISTINCT "posts"."id") FROM "posts" INNER JOIN "categorizations" ON "posts"."id" = "categorizations"."post_id" WHERE "categorizations"."author_id" = ?  [["author_id", 2]]

  # After
  author.unique_categorized_posts.count
  # => SELECT COUNT(DISTINCT "posts"."id") FROM "posts" INNER JOIN "categorizations" ON "posts"."id" = "categorizations"."post_id" WHERE "categorizations"."author_id" = ?  [["author_id", 2]]
```

Closes #27615
上级 558336ee
......@@ -232,7 +232,7 @@ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
query_builder = build_count_subquery(spawn, column_name, distinct)
else
# PostgreSQL doesn't like ORDER BY when there are no GROUP BY
relation = unscope(:order)
relation = unscope(:order).distinct!(false)
column = aggregate_column(column_name)
......@@ -292,7 +292,7 @@ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
end
}
relation = except(:group)
relation = except(:group).distinct!(false)
relation.group_values = group_fields
relation.select_values = select_values
......
......@@ -227,6 +227,17 @@ def test_count_on_invalid_columns_raises
assert_match "credit_limit, firm_name", e.message
end
def test_apply_distinct_in_count
queries = assert_sql do
Account.distinct.count
Account.group(:firm_id).distinct.count
end
queries.each do |query|
assert_match %r{\ASELECT(?! DISTINCT) COUNT\(DISTINCT\b}, query
end
end
def test_should_group_by_summed_field_having_condition
c = Account.group(:firm_id).having("sum(credit_limit) > 50").sum(:credit_limit)
assert_nil c[1]
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册