rom-rb / rom

Data mapping and persistence toolkit for Ruby
https://rom-rb.org
MIT License
2.08k stars 161 forks source link

Too many nested queries when using union #348

Closed blelump closed 8 years ago

blelump commented 8 years ago

Hi!

I am not sure this is related either to ROM or Sequel, but consider such query:

        users
        .inner_join(:students, id: :verifable_id)
        .where(verifable_type: "student")
        .select(:users__id,:email,:name,:surname)
        .union(
          users.inner_join(:employees, id: :verifable_id)
          .where(verifable_type: "employee")
          .select(:users__id,:email,:name,:surname)
        )

The corresponding SQL is given as:

SELECT * FROM 
    (SELECT * FROM (
        SELECT users.id, "email", "name", "surname" FROM "users" 
        INNER JOIN "students"  ON ("students"."id" = "users"."verifable_id") 
        WHERE ( ("verifable_type" = 'ForeignStudent')) ORDER BY "users"."id"
    ) AS "t1" 
    UNION 
    (SELECT * FROM (
        SELECT "users"."id", "email", "name", "surname" FROM "users" 
        INNER JOIN "employees" ON ("employees"."id" = "users"."verifable_id") 
        WHERE (("users"."id" IN ('1', '2')) AND ("verifable_type" = 'Employee')) ORDER BY "users"."id") 
    AS "t1")
) AS "t1";

which looks quite complex. Are we missing something?

I'd expect smth like:

SELECT users.id, "email", "name", "surname" FROM "users" 
INNER JOIN "students"  ON ("students"."id" = "users"."verifable_id") 
WHERE ( ("verifable_type" = 'ForeignStudent'))

UNION 

SELECT "users"."id", "email", "name", "surname" FROM "users" 
INNER JOIN "employees" ON ("employees"."id" = "users"."verifable_id") 
WHERE (("users"."id" IN ('1', '2')) AND ("verifable_type" = 'Employee'))
solnic commented 8 years ago

This issue was moved to rom-rb/rom-sql#72