Skip to content

Fix COUNT(DISTINCT ...) with ORDER BY and LIMIT - #29848

Merged
rafaelfranca merged 3 commits into
rails:masterfrom
kamipo:fix_distinct_count_with_order_and_limit
Jul 24, 2017
Merged

rafaelfranca merged 3 commits into
rails:masterfrom
kamipo:fix_distinct_count_with_order_and_limit

Conversation

@kamipo

@kamipo kamipo commented Jul 19, 2017

Copy link
Copy Markdown
Member

Since #26972, ORDER BY is kept if LIMIT is presented for
performance. But in most SQL servers (e.g. PostgreSQL, SQL Server, etc),
ORDER BY expressions must appear in select list for SELECT DISTINCT.
We should not replace existing select list in that case.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kamipo Do you think we should also add a similar test for offset?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a test for offset below, thanks!

@kamipo
kamipo force-pushed the fix_distinct_count_with_order_and_limit branch 2 times, most recently from 2008468 to c6a3671 Compare July 20, 2017 01:32
@teohm

teohm commented Jul 20, 2017 •

Copy link
Copy Markdown
Contributor

@kamipo I did a quick test on this PR, the count operation fails (tested with Postgres) when the query contains a join e.g.

Model.joins(:associated_resource).order(:updated_at).distinct.limit(10) # this works
# SQL =>  SELECT  DISTINCT "models".* FROM models ... 

Model.joins(:associated_resource).order(:updated_at).distinct.limit(10).count # this fails
# SQL =>  SELECT COUNT(*) FROM (SELECT  DISTINCT * FROM models ...

@kamipo

kamipo commented Jul 20, 2017

Copy link
Copy Markdown
Member Author

@teohm Thanks for your testing. You're right, I updated to keep the table name qualified * for distinct subquery.

@teohm

teohm commented Jul 21, 2017

Copy link
Copy Markdown
Contributor

@kamipo Awesome, I just tested on Postgres, it's working now! 👍 Is it possible to get it merged into the coming patch release?

@basex

basex commented Jul 21, 2017

Copy link
Copy Markdown

Fixed also here 👍. Would be great if it could go online on the next release.

@rafaelfranca

Copy link
Copy Markdown
Member

Could you add a CHANGELOG entry?

kamipo added 2 commits July 22, 2017 08:40
Since rails#26972, `ORDER BY` is kept if `LIMIT` is presented for
performance. But in most SQL servers (e.g. PostgreSQL, SQL Server, etc),
`ORDER BY` expressions must appear in select list for `SELECT DISTINCT`.
We should not replace existing select list in that case.
@kamipo
kamipo force-pushed the fix_distinct_count_with_order_and_limit branch from 0827455 to 45e3965 Compare July 21, 2017 23:41
@kamipo
kamipo force-pushed the fix_distinct_count_with_order_and_limit branch from 45e3965 to 3293ca6 Compare July 21, 2017 23:47
@kamipo

kamipo commented Jul 21, 2017

Copy link
Copy Markdown
Member Author

I added a CHANGELOG entry!

@teohm

teohm commented Jul 24, 2017

Copy link
Copy Markdown
Contributor

@kamipo @rafaelfranca Is it possible to backport this fix to Rails 5.1.x ?

@rafaelfranca
rafaelfranca merged commit 06dff4d into rails:master Jul 24, 2017
rafaelfranca added a commit that referenced this pull request Jul 24, 2017
…nd_limit

Fix `COUNT(DISTINCT ...)` with `ORDER BY` and `LIMIT`
@kamipo
kamipo deleted the fix_distinct_count_with_order_and_limit branch July 24, 2017 19:10
@teohm

teohm commented Jul 26, 2017

Copy link
Copy Markdown
Contributor

@rafaelfranca I saw this is backported to 5-1-stable branch 2 days ago, which is awesome! 😃

but I noticed it's not part of the latest v5.1.3.rc2 released just now? Is it possible to include this fix in the coming v5.1.3 release?

@teohm

teohm commented Jul 27, 2017 •

Copy link
Copy Markdown
Contributor

Also cc @kamipo, is it possible to merge this into 5.1.3 branch? 🙇 🙏

subquery_alias = Arel.sql("subquery_for_count")
relation.select_values = [
if column_name == :all
distinct ? table[Arel.star] : Arel.sql("1")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi! I am the maintainer of the SQL Server adapter. I'm just catching up to this change and I found out it breaks all the adapter counts during this code path because this is not a valid syntax:

SELECT * FROM ( SELECT 1 ) count

It would be if AS one was used which is provided by FinderMethods::ONE_AS_ONE.

kamipo added a commit that referenced this pull request Oct 14, 2017
This is the fix for the regression of #29848.

In #29848, I've kept existing select list in the subquery for the count
if ORDER BY is given. But it had accidentally affect to GROUP BY
queries also. It should keep the previous behavior in that case.

Fixes #30886.
kamipo added a commit that referenced this pull request Oct 14, 2017
This is the fix for the regression of #29848.

In #29848, I've kept existing select list in the subquery for the count
if ORDER BY is given. But it had accidentally affect to GROUP BY
queries also. It should keep the previous behavior in that case.

Fixes #30886.
fastjames added a commit to geminimvp/solidus_asset_variant_options that referenced this pull request Nov 14, 2017
In Rails 5.1 using DISTINCT where a lot of ORDER BY clauses are present
seems to cause some confusion in Arel. See

rails/rails#29848

and its references for more context. I don't think there is currently a
case where we would get the same image more than once, as our image
asset management is strictly tied to Product Variants right now.
fastjames added a commit to geminimvp/solidus_asset_variant_options that referenced this pull request Nov 14, 2017
In Rails 5.1, SQL queries with DISTINCT, COUNT(), and ORDER_BY are not
parsed correctly leading to an error from Postgres. A similar problem
was reported and fixed on

rails/rails#29848

but I don't think it is the same problem as this one.

I prefer to avoid putting ORDER BY clauses into has_many associtainos,
default scopes, & etc. because they inevitably get in the way. By
removing them here, we will probably have to add  them back in a
presenter later. For now it's enough to get them out of the way.
bogdanvlviv added a commit to bogdanvlviv/rails that referenced this pull request Mar 18, 2018
- Remove
  ```
  *   Namespace error pages' CSS selectors to stop the styles from bleeding
      into other pages when using Turbolinks.
      ([Pull Request](rails#28814))
  ```
  since it was backported to
  `5-1-stable` by 50d5baf
  and
  `5-0-stable` by d1c4a39.

- Remove
  ```
  *   Allow irb options to be passed from `rails console` command.
      ([Pull Request](rails#29010))
  ```
  since it was backported to
  `5-1-stable` by e91b483.

- Remove
  ```
  *   Load environment file in `dbconsole` command.
      ([Pull Request](rails#29725))
  ```
  since it was backported to
  `5-1-stable` by 7f93428.

- Remove
  ```
  *   Gemfile for new apps: upgrade redis-rb from ~> 3.0 to 4.0.
      ([Pull Request](rails#30748))
  ```
  since it was backported to
  `5-1-stable` by 3789531.

- Remove
  ```
  *   Fix minitest rails plugin.
      The custom reporters are added only if needed.
      This will fix conflicts with others plugins.
      ([Commit](rails@ac99916))
  ```
  since it was backported to
  `5-1-stable` by caa7695.

- Remove
  ```
  *   Add support for compatibility with redis-rb gem for 4.0 version.
      ([Pull Request](rails#30748))
  ```
  since it was backported to
  `5-1-stable` by 3789531.

- Remove
  ```
  *   Add `action_controller_api` and `action_controller_base` load hooks to be
      called in `ActiveSupport.on_load`.
      ([Pull Request](rails#28402))
  ```
  since it was backported to
  `5-1-stable` by b9a5fd7.

- Remove
  ```
  *   `driven_by` now registers poltergeist and capybara-webkit.
      ([Pull Request](rails#29315))
  ```
  since it was backported to
  `5-1-stable` by c5dd451.

- Remove
  ```
  *   Fallback `ActionController::Parameters#to_s` to `Hash#to_s`.
      ([Pull Request](rails#29630))
  ```
  since it was backported to
  `5-1-stable` by c1014e4
  and
  `5-0-stable` by 0e71fc3.

- Remove
  ```
  *   Make `take_failed_screenshot` work within engine.
      ([Pull Request](rails#30421))
  ```
  since it was backported to
  `5-1-stable` by 595a231.

- Remove
  ```
  *   Fix optimized url helpers when using relative url root.
      ([Pull Request](rails#31261))
  ```
  since it was backported to
  `5-1-stable` by e9b7795.

- Remove
  ```
  *   Update `distance_of_time_in_words` helper to display better error messages
      for bad input.
      ([Pull Request](rails#20701))
  ```
  since it was backported to
  `5-1-stable` by 2c97fbf.

- Remove
  ```
  *   Generate field ids in `collection_check_boxes` and
      `collection_radio_buttons`.
      ([Pull Request](rails#29412))
  ```
  since it was backported to
  `5-1-stable` by 2d8c10a.

- Remove
  ```
  *   Fix issues with scopes and engine on `current_page?` method.
      ([Pull Request](rails#29503))
  ```
  since it was backported to
  `5-1-stable` by 2135daf.

- Remove
  ```
  *   Bring back proc with arity of 1 in `ActionMailer::Base.default` proc
      since it was supported in Rails 5.0 but not deprecated.
      ([Pull Request](rails#30391))
  ```
  since it was backported to
  `5-1-stable` by b2bedb1.

- Remove
  ```
  *   Add type caster to `RuntimeReflection#alias_name`.
      ([Pull Request](rails#28961))
  ```
  since it was backported to
  `5-1-stable` by f644e7a.

- Remove
  ```
  *   Loading model schema from database is now thread-safe.
      ([Pull Request](rails#29216))
  ```
  since it was backported to
  `5-1-stable` by 02926cf.
  and
  `5-0-stable` by 84bcfe5

- Remove
  ```
  *   Fix destroying existing object does not work well when optimistic locking
      enabled and `locking_column` is null in the database.
      ([Pull Request](rails#28926))
  ```
  since it was backported to
  `5-1-stable` by e498052.

- Remove
  ```
  *   `ActiveRecord::Persistence#touch` does not work well
      when optimistic locking enabled and `locking_column`,
      without default value, is null in the database.
      ([Pull Request](rails#28914))
  ```
  since it was backported to
  `5-1-stable` by 1e2f63d.

- Remove
  ```
  *   Previously, when building records using a `has_many :through` association,
      if the child records were deleted before the parent was saved,
      they would still be persisted. Now, if child records are deleted
      before the parent is saved on a `has_many :through` association,
      the child records will not be persisted.
      ([Pull Request](rails#29593))
  ```
  since it was backported to
  `5-1-stable` by a22c39e.

- Remove
  ```
  *   Query cache was unavailable when entering the `ActiveRecord::Base.cache`
      block without being connected.
      ([Pull Request](rails#29609))
  ```
  since it was backported to
  `5-1-stable` by fd6c8cd
  and
  `5-0-stable` by 9f2532b.

- Remove
  ```
  *   `Relation#joins` is no longer affected by the target model's
      `current_scope`, with the exception of `unscoped`.
      ([Commit](rails@5c71000))
  ```
  since it was backported to
  `5-1-stable` by 3630d63.

- Remove
  ```
  *   Fix `unscoped(where: [columns])` removing the wrong bind values.
      ([Pull Request](rails#29780))
  ```
  since it was backported to
  `5-1-stable` by d378fcb.

- Remove
  ```
  *   When a `has_one` association is destroyed by `dependent: destroy`,
      `destroyed_by_association` will now be set to the reflection, matching the
      behaviour of `has_many` associations.
      ([Pull Request](rails#29855))
  ```
  since it was backported to
  `5-1-stable` by 8254a8b.

- Remove
  ```
  *   Fix `COUNT(DISTINCT ...)` with `ORDER BY` and `LIMIT`
      to keep the existing select list.
      ([Pull Request](rails#29848))
  ```
  since it was backported to
  `5-1-stable` by 0e8d4ed.

- Remove
  ```
  *   Ensure `sum` honors `distinct` on `has_many :through` associations.
      ([Commit](rails@566f1fd))
  ```
  since it was backported to
  `5-1-stable` by c0a1dc2.

- Remove
  ```
  *   Fix `COUNT(DISTINCT ...)` for `GROUP BY` with `ORDER BY` and `LIMIT`.
      ([Commit](rails@5668dc6))
  ```
  since it was backported to
  `5-1-stable` by 87ca68e.

- Remove
  ```
  *   MySQL: Don't lose `auto_increment: true` in the `db/schema.rb`.
      ([Commit](rails@9493d45))
  ```
  since it was backported to
  `5-1-stable` by 8b6e694.

- Remove
  ```
  *   Fix longer sequence name detection for serial columns.
      ([Pull Request](rails#28339))
  ```
  since it was backported to
  `5-1-stable` by af9c170
  and
  `5-0-stable` by 7025b1d.

- Remove
  ```
  *   Fix `bin/rails db:setup` and `bin/rails db:test:prepare` create wrong
      ar_internal_metadata's data for a test database.
      ([Pull Request](rails#30579))
  ```
  since it was backported to
  `5-1-stable` by bb67b5f
  and
  `5-0-stable` by 60437e6.

- Remove
  ```
  *   Fix conflicts `counter_cache` with `touch: true` by optimistic locking.
      ([Pull Request](rails#31405))
  ```
  since it was backported to
  `5-1-stable` by 5236dda.

- Remove
  ```
  *   Fix `count(:all)` to correctly work `distinct` with custom SELECT list.
      ([Commit](rails@c6cd9a5))
  ```
  since it was backported to
  `5-1-stable` by 6beb4de.

- Remove
  ```
  *   Fix to invoke callbacks when using `update_attribute`.
      ([Commit](rails@732aa34))
  ```
  since it was backported to
  `5-1-stable` by 6346683.

- Remove
  ```
  *   Use `count(:all)` in `HasManyAssociation#count_records` to prevent invalid
      SQL queries for association counting.
      ([Pull Request](rails#27561))
  ```
  since it was backported to
  `5-1-stable` by eef3c89.

- Remove
  ```
  *   Fix `count(:all)` with eager loading and having an order other than
      the driving table.
      ([Commit](rails@ebc09ed))
  ```
  since it was backported to
  `5-1-stable` by 6df9b69.

- Remove
  ```
  *   PostgreSQL: Allow pg-1.0 gem to be used with Active Record.
      ([Pull Request](rails#31671))
  ```
  since it was backported to
  `5-1-stable` by a9c06f6.

- Remove
  ```
  *   Fix that after commit callbacks on update does not triggered
      when optimistic locking is enabled.
      ([Commit](rails@7f9bd03))
  ```
  since it was backported to
  `5-1-stable` by aaee10e.

- Remove
  ```
  *   Fix regression in numericality validator when comparing Decimal and Float
      input values with more scale than the schema.
      ([Pull Request](rails#28584))
  ```
  since it was backported to
  `5-1-stable` by 5b1c3e5.
  Note that there was incorrect link to PR,
  original PR is rails#29249.

- Remove
  ```
  *   Fix to working before/after validation callbacks on multiple contexts.
      ([Pull Request](rails#31483))
  ```
  since it was backported to
  `5-1-stable` by 0f7046a.

- Remove
  ```
  *   Fix implicit coercion calculations with scalars and durations.
      ([Pull Request](rails#29163),
      [Pull Request](rails#29971))
  ```
  since it was backported to
  `5-1-stable` by 51ea27c,
                  4d82e2a.

- Remove
  ```
  *   Fix modulo operations involving durations.
      ([Commit](rails@a54e13b))
  ```
  since it was backported to
  `5-1-stable` by 233fa7e.

- Remove
  ```
  *   Return all mappings for a timezone identifier in `country_zones`.
      ([Commit](rails@cdce6a7))
  ```
  since it was backported to
  `5-1-stable` by 0222ebb.

- Remove
  ```
  *   Add support for compatibility with redis-rb gem for 4.0 version.
      ([Pull Request](rails#30748))
  ```
  since it was backported to
  `5-1-stable` by 3789531.
  Related to rails#32252.

Related to rails#32222, rails#32222 (comment).
Follow up a489cc8.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants