Fix cases where CTE's are not supported

CTE's are not supported for MySQL versions below 8.0, so these tests
were failing locally for me on MySQL 5.7. While 5.7 is quite old, it's
still supported and used by many major Rails applications and we need a
check for support in our tests.

In addition to this PR I'll need to get a buildkite build running for
5.7. This wasn't caught earlier because our buildkite upgraded to 8.0.
This commit is contained in:
eileencodes 2022-07-13 10:46:10 -04:00
parent 05ae3faaf3
commit 3c7e190ee8
No known key found for this signature in database
GPG Key ID: BA5C575120BBE8DF
3 changed files with 67 additions and 54 deletions

View File

@ -326,6 +326,9 @@ module ActiveRecord
# Add a Common Table Expression (CTE) that you can then reference within another SELECT statement.
#
# Note: CTE's are only supported in MySQL for versions 8.0 and above. You will not be able to
# use CTE's with MySQL 5.7.
#
# Post.with(posts_with_tags: Post.where("tags_count > ?", 0))
# # => ActiveRecord::Relation
# # WITH posts_with_tags AS (

View File

@ -394,6 +394,7 @@ class MergingDifferentRelationsTest < ActiveRecord::TestCase
assert_equal dev.ratings, [rating_1]
end
if ActiveRecord::Base.connection.supports_common_table_expressions?
test "merging relation with common table expression" do
posts_with_tags = Post.with(posts_with_tags: Post.where("tags_count > 0")).from("posts_with_tags AS posts")
posts_with_comments = Post.where("legacy_comments_count > 0")
@ -420,4 +421,5 @@ class MergingDifferentRelationsTest < ActiveRecord::TestCase
relation.load
end
end
end
end

View File

@ -15,6 +15,7 @@ module ActiveRecord
POSTS_WITH_TAGS_AND_COMMENTS = (POSTS_WITH_COMMENTS & POSTS_WITH_TAGS).sort.freeze
POSTS_WITH_TAGS_AND_MULTIPLE_COMMENTS = (POSTS_WITH_MULTIPLE_COMMENTS & POSTS_WITH_TAGS).sort.freeze
if ActiveRecord::Base.connection.supports_common_table_expressions?
def test_with_when_hash_is_passed_as_an_argument
relation = Post
.with(posts_with_comments: Post.where("legacy_comments_count > 0"))
@ -60,5 +61,12 @@ module ActiveRecord
assert_raise(ArgumentError) { Post.with(posts_with_tags: nil).load }
assert_raise(ArgumentError) { Post.with(posts_with_tags: [Post.where("tags_count > 0")]).load }
end
else
def test_common_table_expressions_are_unsupported
assert_raises ActiveRecord::StatementInvalid do
Post.with_tags_cte.order(:id).pluck(:id)
end
end
end
end
end