class SQB::Select

Public Instance Methods

to_sql() click to toggle source
# File lib/sqb/select.rb, line 25
def to_sql
  [].tap do |query|
    query << "SELECT"
    query << "DISTINCT" if @distinct
    if @columns.nil? || @columns.empty?
      query << escape_and_join(@table_name, SQB::STAR)
    else
      query << @columns.join(', ')
    end

    query << "FROM"
    query << escape_and_join(@options[:database_name], @table_name)

    if @index_hints && !@index_hints.empty?
      query << 'USE INDEX (' + @index_hints.join(', ') + ')'
    end

    if @joins && !@joins.empty?
      query << @joins.join(' ')
    end

    if @where && !@where.empty?
      query << "WHERE"
      query << @where.join(' AND ')
    end

    if @groups && !@groups.empty?
      query << "GROUP BY"
      query << @groups.join(', ')
    end

    if @orders && !@orders.empty?
      query << "ORDER BY"
      query << @orders.join(', ')
    end

    if @limit
      query << "LIMIT #{@limit.to_i}"
    end

    if @offset
      query << "OFFSET #{@offset.to_i}"
    end
  end.join(' ')
end