[2.1.1] Arel::Visitors::MySQL doesn't parenthesize UNION chains properly #58

Closed
jhtwong opened this Issue Jun 2, 2011 · 0 comments

2 participants

@jhtwong

I have some code that tries to generate UNIONs of 3 or more subqueries, and I ran into a SQL generation problem for MySQL. The problem is that MySQL disallows parentheses around UNION operands. For example, this is bad syntax for MySQL:

((a UNION b) UNION c)

...instead, MySQL wants this:

(a UNION b UNION c)

I have a patch which seems to work for Arel::Visitors::MySQL:

def visit_Arel_Nodes_Union o, suppress_parens = false
  left_result = case o.left
    when Arel::Nodes::Union
      visit_Arel_Nodes_Union o.left, true
    else
      visit o.left
  end

  right_result = case o.right
    when Arel::Nodes::Union
      visit_Arel_Nodes_Union o.right, true
    else
      visit o.right
  end

  if suppress_parens
    "#{left_result} UNION #{right_result}"
  else
    "( #{left_result} UNION #{right_result} )"
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment