Permalink
Browse files

Merge pull request #10616 from Empact/backport-distinct-distinct

Backport a super-simplified version of #6792, fixing that #exists? can produce invalid SQL: "SELECT DISTINCT DISTINCT"
  • Loading branch information...
2 parents 010ea71 + 23c656c commit 5b020fa1101b878e5f3b8b8a5e7d47e39b505b1e @rafaelfranca rafaelfranca committed May 14, 2013
@@ -1,5 +1,12 @@
## unreleased ##
+* Fix that under some conditions, Active Record could produce invalid SQL of the sort:
+ "SELECT DISTINCT DISTINCT".
+
+ Backport of #6792.
+
+ *Ben Woosley*
+
* Require `ActiveRecord::Base` in railtie hooks for rake_tasks, console and runner to
avoid circular constant loading issues.
@@ -254,6 +254,7 @@ def construct_limited_ids_condition(relation)
values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
relation = relation.dup.select(values)
+ relation.uniq_value = nil
id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
ids_array = id_rows.map {|row| row[primary_key]}
@@ -93,6 +93,18 @@ def test_exists_with_includes_limit_and_empty_result
assert !Topic.includes(:replies).limit(1).where('0 = 1').exists?
end
+ def test_exists_with_distinct_association_includes_and_limit
+ author = Author.first
+ assert !author.unique_categorized_posts.includes(:special_comments).limit(0).exists?
+ assert author.unique_categorized_posts.includes(:special_comments).limit(1).exists?
+ end
+
+ def test_exists_with_distinct_association_includes_limit_and_order
+ author = Author.first
+ assert !author.unique_categorized_posts.includes(:special_comments).order('comments.taggings_count DESC').limit(0).exists?
+ assert author.unique_categorized_posts.includes(:special_comments).order('comments.taggings_count DESC').limit(1).exists?
+ end
+
def test_exists_with_empty_table_and_no_args_given
Topic.delete_all
assert !Topic.exists?

0 comments on commit 5b020fa

Please sign in to comment.