Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Relation#union fails on virtual columns #421

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions spec/unit/relation/union_spec.rb
Original file line number Diff line number Diff line change
@@ -72,6 +72,94 @@
end
end

context "when the relations unioned have different names and virtual columns" do
let(:relation1) { relation.where(id: 1).select(:id, :name).select_append { [`NULL`.as(:title)] } }
let(:relation2) { tasks.select(:id).select_append { [`NULL`.as(:name)] }.select_append(:title) }

it "qualifies the table as the concatenated relation names" do
# this produces SQL like
# SELECT
# `users__tasks`.`id`,
# `users__tasks`.`name`,
# NULL AS 'title'
Copy link
Author

Choose a reason for hiding this comment

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

this is the problematic column select. if this got transformed to users__tasks.title, all would be well

# FROM
# (
# SELECT
# *
# FROM
# (
# SELECT
# `users`.`id`,
# `users`.`name`,
# NULL AS 'title'
# FROM
# `users`
# WHERE
# (`id` = 1)
# ORDER BY
# `users`.`id`
# ) AS 't1'
# UNION
# SELECT
# *
# FROM
# (
# SELECT
# `tasks`.`id`,
# NULL AS 'name',
# `tasks`.`title`
# FROM
# `tasks`
# ORDER BY
# `tasks`.`id`
# ) AS 't1'
# ) AS 'users__tasks'
result = relation1.union(relation2)
# But in older versions of ROM and if using Sequel directly it produces:
# SELECT
# *
# FROM
# (
# SELECT
# *
# FROM
# (
# SELECT
# `users`.`id`,
# `users`.`name`,
# NULL AS 'title'
# FROM
# `users`
# WHERE
# (`id` = 1)
# ORDER BY
# `users`.`id`
# ) AS 't1'
# UNION
# SELECT
# *
# FROM
# (
# SELECT
# `tasks`.`id`,
# NULL AS 'name',
# `tasks`.`title`
# FROM
# `tasks`
# ORDER BY
# `tasks`.`id`
# ) AS 't1'
# ) AS 'users__tasks'
expect_to_have_qualified_name(result, :users__tasks)
end

it "has non-nil titles from the tasks relation" do
titles = relation1.union(relation2).to_a.map { |row| row.fetch(:title) }.compact
expect(titles).not_to be_empty
end
end


def expect_to_have_qualified_name(rel, name)
metas = rel.schema.map(&:meta)
expect(metas).to all(include(qualified: name))