I want to use SQL SELECT statements with UNION in my Ruby on Rails application. For example (1):
SELECT *
FROM (SELECT row FROM users) UNION (SELECT row FROM customers)
Or as part of a JOIN statement (2):
SELECT *
FROM authors
INNER JOIN (SELECT row FROM users) UNION (SELECT row FROM customers)
The subqueries can be constructed with ActiveRecord but, as far as I know, the statement itself can’t. So thought of the following workarounds.
Workaround for (1):
ActiveRecord::Base.connection.select_rows(%{
SELECT *
FROM (#{User.select(:row).to_sql}) UNION (#{Customer.select(:row).to_sql)
})
Workaround for (2):
Author.joins(%{
INNER JOIN (#{User.select(:row).to_sql}) UNION (#{Customer.select(:row).to_sql)
})
My question is: Does this possibly introduce an SQL injection vulnerability? Given, of course, that the subqueries themselves are secure and not, for example, something like Users.where("id = #{params[:id]}").select(:row)
.
It feels like I’m doing something wrong but I can’t think of a better way. I thought about using Arel but apparently it is considered a private API and should not be used by developers.