Merge pull request #45586 from eileencodes/check-for-cte-support

Fix cases where CTE's are not supported
This commit is contained in:
Eileen M. Uchitelle 2022-07-13 12:12:42 -04:00 committed by GitHub
commit e7633661b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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")
@ -421,3 +422,4 @@ class MergingDifferentRelationsTest < ActiveRecord::TestCase
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