提交 c2d33c4a 编写于 作者: R Rafael Sales

Fix generated projection fields in group by query

Closes #21922

Let `Book(id, author_id)`, `Photo(id, book_id, author_id)` and `Author(id)`

Running `Book.group(:author_id).joins(:photos).count` will produce:

* Rails 4.2 - conflicts `author_id` in both projection and group by:
```sql
SELECT COUNT(*) AS count_all, author_id AS author_id
  FROM "books" INNER JOIN "photos" ON "photos"."book_id" = "books"."id"
 GROUP BY author_id
```

* Master (9d02a25d) - conflicts `author_id` only in projection:
```sql
SELECT COUNT(*) AS count_all, author_id AS author_id
  FROM "books" INNER JOIN "photos" ON "photos"."book_id" = "books"."id"
 GROUP BY "books"."author_id"
```

* With this fix:
```sql
SELECT COUNT(*) AS count_all, "books"."author_id" AS books_author_id
  FROM "books" INNER JOIN "photos" ON "photos"."book_id" = "books"."id"
 GROUP BY "books"."author_id"
```
上级 d8b076c9
* Queries such as `Computer.joins(:monitor).group(:status).count` will now be
interpreted as `Computer.joins(:monitor).group('computers.status').count`
so that when `Computer` and `Monitor` have both `status` columns we don't
have conflicts in projection.
*Rafael Sales*
* Add ability to default to `uuid` as primary key when generating database migrations
Set `Rails.application.config.active_record.primary_key = :uuid`
......
......@@ -275,6 +275,7 @@ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
else
group_fields = group_attrs
end
group_fields = arel_columns(group_fields)
group_aliases = group_fields.map { |field|
column_alias_for(field)
......@@ -299,7 +300,7 @@ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
]
select_values += select_values unless having_clause.empty?
select_values.concat arel_columns(group_fields).zip(group_aliases).map { |field,aliaz|
select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
if field.respond_to?(:as)
field.as(aliaz)
else
......
......@@ -455,6 +455,11 @@ def test_should_count_field_in_joined_table_with_group_by
[1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
end
def test_should_count_field_of_root_table_with_conflicting_group_by_column
assert_equal({ 1 => 1 }, Firm.joins(:accounts).group(:firm_id).count)
assert_equal({ 1 => 1 }, Firm.joins(:accounts).group('accounts.firm_id').count)
end
def test_count_with_no_parameters_isnt_deprecated
assert_not_deprecated { Account.count }
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册