Class: SQB::Select

Inherits:
Base
  • Object
show all
Includes:
Columns, Distinct, Filtering, Grouping, IndexHint, Joins, Limiting, Offsetting, Ordering
Defined in:
lib/sqb/select.rb

Direct Known Subclasses

Query

Constant Summary

Constants included from Ordering

Ordering::VALID_ORDERS

Instance Attribute Summary

Attributes inherited from Base

#options, #prepared_arguments

Instance Method Summary collapse

Methods included from IndexHint

#index_hint, #no_index_hint!

Methods included from Offsetting

#offset

Methods included from Limiting

#limit

Methods included from Grouping

#group_by

Methods included from Ordering

#no_order!, #order, #order!

Methods included from Joins

#join

Methods included from Filtering

#or, #where

Methods included from Columns

#column, #column!

Methods included from Distinct

#distinct

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from SQB::Base

Instance Method Details

#to_sqlObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 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