Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collection cache_key raises PG::GroupingError with select in query #23038

Closed
plguo opened this issue Jan 13, 2016 · 0 comments
Closed

Collection cache_key raises PG::GroupingError with select in query #23038

plguo opened this issue Jan 13, 2016 · 0 comments

Comments

@plguo
Copy link

plguo commented Jan 13, 2016

ActiveRecord::Relation#cache_key raises PG::GroupingError in PostgreSQL when there is select in the query. I tested the same query in sqlite, and it didn't raise any error.

irb(main):001:0> Post.all.cache_key
   (14.5ms)  SELECT COUNT(*) AS size, MAX("posts"."updated_at") AS timestamp FROM "posts"
=> "posts/query-00644b6a00f2ed4b925407d06501c8fb-5-20160112214758318542"

irb(main):002:0> Post.all.select(:title).cache_key
   (1.7ms)  SELECT "posts"."title", COUNT(*) AS size, MAX("posts"."updated_at") AS timestamp FROM "posts"
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "posts.title" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "posts"."title", COUNT(*) AS size, MAX("posts"."updat...
               ^
: SELECT "posts"."title", COUNT(*) AS size, MAX("posts"."updated_at") AS timestamp FROM "posts"

The problem seems to be fixed by adding unscope(:select)

irb(main):003:0> Post.all.select(:title).unscope(:select).cache_key
   (2.1ms)  SELECT COUNT(*) AS size, MAX("posts"."updated_at") AS timestamp FROM "posts"
=> "posts/query-00644b6a00f2ed4b925407d06501c8fb-5-20160112214758318542"
prathamesh-sonpatki added a commit to prathamesh-sonpatki/rails that referenced this issue Jan 24, 2016
- We don't need the select scope added by user as we only want to max
  timestamp and size of the collection. So we already know which columns
  to select.
- Additionally having user defined columns in select scope blows the cache_key
  method with PostGreSQL because it needs all `selected` columns in the group_by
  clause or aggregate function.
- Fixes rails#23038.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants