Skip to content

Commit c0f5f7b

Browse files
authored
Rails 6.1: Fix "ActiveRecord::StatementInvalid: A column has been specified more than once in the order by list" (#894)
* add spec showing adapters behaviour * coerce test avoiding duplicate columns in order list
1 parent b5e38a1 commit c0f5f7b

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

test/cases/coerced_tests.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1667,3 +1667,29 @@ def marshal_fixture_path(file_name)
16671667
)
16681668
end
16691669
end
1670+
1671+
class NestedThroughAssociationsTest < ActiveRecord::TestCase
1672+
# Same as original but replace order with "order(:id)" to ensure that assert_includes_and_joins_equal doesn't raise
1673+
# "A column has been specified more than once in the order by list"
1674+
# Example: original test generate queries like "ORDER BY authors.id, [authors].[id]". We don't support duplicate columns in the order list
1675+
coerce_tests! :test_has_many_through_has_many_with_has_many_through_habtm_source_reflection_preload_via_joins, :test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection_preload_via_joins
1676+
def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection_preload_via_joins_coerced
1677+
# preload table schemas
1678+
Author.joins(:category_post_comments).first
1679+
1680+
assert_includes_and_joins_equal(
1681+
Author.where("comments.id" => comments(:does_it_hurt).id).order(:id),
1682+
[authors(:david), authors(:mary)], :category_post_comments
1683+
)
1684+
end
1685+
1686+
def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection_preload_via_joins_coerced
1687+
# preload table schemas
1688+
Category.joins(:post_comments).first
1689+
1690+
assert_includes_and_joins_equal(
1691+
Category.where("comments.id" => comments(:more_greetings).id).order(:id),
1692+
[categories(:general), categories(:technology)], :post_comments
1693+
)
1694+
end
1695+
end

test/cases/order_test_sqlserver.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,4 +143,11 @@ class OrderTestSQLServer < ActiveRecord::TestCase
143143
assert_equal post1, Post.order(Arel.sql(order)).first
144144
assert_equal post2, Post.order(Arel.sql(order)).second
145145
end
146+
147+
# Executing this kind of queries will raise "A column has been specified more than once in the order by list"
148+
# This test shows that we don't do anything to prevent this
149+
it "doesn't deduplicate semantically equal orders" do
150+
sql = Post.order(:id).order("posts.id ASC").to_sql
151+
assert_equal "SELECT [posts].* FROM [posts] ORDER BY [posts].[id] ASC, posts.id ASC", sql
152+
end
146153
end

0 commit comments

Comments
 (0)