Module: Sqlbuilder::Statements::Builders::SelectBuilder

Included in:
DeleteBuilder, Select
Defined in:
lib/sqlbuilder/statements/builders/select_builder.rb

Instance Method Summary collapse

Instance Method Details

#build_columnsObject



5
6
7
8
9
10
11
# File 'lib/sqlbuilder/statements/builders/select_builder.rb', line 5

def build_columns
  if @columns.empty?
    "#{prefix}*"
  else
    @columns.map {|col| build_column(col) }.join(", ")
  end
end

#build_fromObject



13
14
15
16
17
18
19
20
# File 'lib/sqlbuilder/statements/builders/select_builder.rb', line 13

def build_from
  from = "FROM #{@table}"
  if @aliaz
    from << " #{@aliaz}"
  end

  from
end

#build_joinsObject



22
23
24
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
# File 'lib/sqlbuilder/statements/builders/select_builder.rb', line 22

def build_joins
  join_lines = @joins.map do |join|
    from = join[:from]
    type = join[:type]
    aliaz = join[:aliaz]

    table1_alias = if @aliaz then "#{@aliaz}" else "#{@table}" end
    table2_alias = if aliaz then "#{aliaz}" else "#{from}" end

    on = join[:on]
      .map do |col1, col2|
        [@utils.format_column(col1), @utils.format_column(col2)]
      end
      .map do |table1_col, table2_col|
        "#{table1_alias}.#{table1_col} = #{table2_alias}.#{table2_col}"
      end

    join_statement = "#{type} JOIN #{from}"

    if aliaz
      join_statement << " #{aliaz}"
    end

    unless on.empty?
      join_statement << " ON #{on.join(' AND ')}"
    end

    join_statement
  end

  join_lines.join(" ")
end

#build_limitObject



80
81
82
# File 'lib/sqlbuilder/statements/builders/select_builder.rb', line 80

def build_limit
  "LIMIT #{@limit}"
end

#build_offsetObject



84
85
86
# File 'lib/sqlbuilder/statements/builders/select_builder.rb', line 84

def build_offset
  "OFFSET #{@offset}"
end

#build_orderObject



72
73
74
75
76
77
78
# File 'lib/sqlbuilder/statements/builders/select_builder.rb', line 72

def build_order
  order_by_clause = @order.map do |key, order|
    "#{prefix}#{@utils.format_column(key)} #{order}"
  end

  "ORDER BY #{order_by_clause.join(", ")}"
end

#build_whereObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/sqlbuilder/statements/builders/select_builder.rb', line 55

def build_where
  where_clause = @where.map do |key, value|
    if value.is_a?(String) &&
       [">", "<", "!=", ">=", "<="].any? {|comp| value.include? comp }

      # TODO: raise custom exception if has more values after split
      symbol, extracted_value = value.split(" ")
      "#{prefix}#{@utils.format_column(key)} #{symbol} "\
      "#{format_value(extracted_value)}"
    else
      "#{prefix}#{@utils.format_column(key)} = #{format_value(value)}"
    end
  end

  "WHERE #{where_clause.join(" AND ")}"
end