lib/veritas/sql/generator/relation/set.rb in veritas-sql-generator-0.0.3 vs lib/veritas/sql/generator/relation/set.rb in veritas-sql-generator-0.0.4
- old
+ new
@@ -10,10 +10,31 @@
DIFFERENCE = 'EXCEPT'.freeze
INTERSECTION = 'INTERSECT'.freeze
UNION = 'UNION'.freeze
+ # Normalize the headers of the operands
+ #
+ # This is necessary to make sure the columns are in the correct
+ # order when generating SQL.
+ #
+ # @param [Relation::Operation::Set] relation
+ #
+ # @return [Relation::Operation::Set]
+ #
+ # @api private
+ def self.normalize_operand_headers(relation)
+ left = relation.left
+ right = relation.right
+ left_header = left.header
+ if left_header.to_a != right.header.to_a
+ relation.class.new(left, right.project(left_header))
+ else
+ relation
+ end
+ end
+
# Visit a Union
#
# @param [Algebra::Union] union
#
# @return [self]
@@ -52,42 +73,29 @@
set_operands(difference)
set_name
self
end
- # Return the SQL for the set relation
- #
- # @example
- # sql = set_relation.to_s
- #
- # @return [#to_s]
- #
- # @api public
- def to_s
- generate_sql(:to_s)
- end
+ private
- # Return the SQL suitable for an subquery
+ # Generate the SQL using the supplied method
#
# @return [#to_s]
#
# @api private
- def to_subquery
- generate_sql(:to_subquery)
+ def generate_sql(*)
+ "(#{@left}) #{@operation} (#{@right})"
end
- private
-
- # Generate the SQL using the supplied method
+ # Set the operands from the relation
#
- # @param [Symbol] method
+ # @param [Relation::Operation::Set] relation
#
- # @return [#to_s]
+ # @return [undefined]
#
# @api private
- def generate_sql(method)
- return EMPTY_STRING unless visited?
- "(#{@left.send(method)}) #{@operation} (#{@right.send(method)})"
+ def set_operands(relation)
+ super self.class.normalize_operand_headers(relation)
end
# Generates an SQL statement for base relation set operands
class Base < Relation::Base; end