def self.union(*unions) a = *unions u_sql = a[0] p u_sql.to_query a.delete_at 0 a.each do |u| u_sql.lasts << " UNION " << u.to_query u_sql.merge_param(u.params) end u_sql end
def self.union_all(*unions) a = *unions u_sql = a[0] p u_sql.to_query a.delete_at 0 a.each do |u| u_sql.lasts << " UNION ALL " << u.to_query u_sql.merge_param(u.params) end u_sql end
def record @record end
def params @params end
def merge_param(param) c = param.class if c == Hash @params = @params.merge(param) elsif c == Array @params.concat param elsif c == String || c == Fixnum || c == TrueClass || c == Float || c == Time @params << param else param.attributes.collect{ |att| @params = @params.merge({att[0].to_sym,att[1]}) } end end
def columns @columns end
def orders @orders end
def groups @groups end
def conditions @conditions end
def joins @joins end
def havings @havings end
def firsts @firsts end
def lasts @lasts end
def limit @limit end
def limit=(att) @limit = att end
def offset @offset end
def offset=(att) @offset = att end
def table_name @table_name end
def to_columns str = "" @columns.each do |item| str << item + ',' end str = str.chop (str << @table_name << ".*") if columns.size == 0 str end
def to_orders str = "" @orders.each do |item| str << item + ',' end str.chop end
def to_groups str = "" @groups.each do |item| str << item + ',' end str.chop end
def to_conditions str = "" @conditions.each do |item| str << item + ' ' end str.chop end
def to_havings str = "" @havings.each do |item| str << item + ' ' end str.chop end
def to_firsts str = "" @firsts.each do |item| str << item + ' ' end str.chop end
def to_lasts str = "" @lasts.each do |item| str << item + ' ' end str.chop end
def to_joins str = "" @joins.each do |item| str << item + ' ' end str.chop end
def to_query first = to_firsts condition = to_conditions join = to_joins column = to_columns group = to_groups having = to_havings order = to_orders last = to_lasts sql = "SELECT " sql << column if !column.empty? sql << " FROM " sql << @table_name sql << " " << join if !join.empty? sql << " WHERE " << condition if !condition.empty? sql << " GROUP BY " << group if !group.empty? sql << " HAVING " << having if !having.empty? sql << " ORDER BY " << order if !order.empty?
if @offset.nil? sql << " LIMIT " << @limit.to_s if !@limit.nil? else sql << " LIMIT #{@offset.to_s},#{@limit.to_s}" if !@limit.nil? end
(sql << " " << last) if !last.empty?
(sql.insert 0,(first << " ")) if !first.empty? sql end
def to_total total_sql = SQLManager.clone(self) total_sql.limit = nil total_sql.offset = nil if !@groups.empty? total_sql.firsts << "SELECT COUNT(*) AS total FROM (" total_sql.lasts << ") temp_table" else total_sql.columns.clear total_sql.columns << "COUNT(#{total_sql.table_name}.id) AS total" end total_sql end
def query s = [to_query] if(@params.class == Hash) s << @params else s.concat @params end @record.class.find_by_sql s end