Class: Hyperion::Sql::QueryBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperion/sql/query_builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(qb_strategy) ⇒ QueryBuilder

Returns a new instance of QueryBuilder.



9
10
11
# File 'lib/hyperion/sql/query_builder.rb', line 9

def initialize(qb_strategy)
  @qb_strategy = qb_strategy
end

Instance Method Details

#build_count(query) ⇒ Object



49
50
51
52
53
# File 'lib/hyperion/sql/query_builder.rb', line 49

def build_count(query)
  sql_query = SqlQuery.new("SELECT COUNT(*) FROM \"#{query.kind}\"")
  apply_filters(sql_query, query.filters)
  sql_query
end

#build_delete(query) ⇒ Object



43
44
45
46
47
# File 'lib/hyperion/sql/query_builder.rb', line 43

def build_delete(query)
  sql_query = SqlQuery.new("DELETE FROM \"#{query.kind}\"")
  apply_filters(sql_query, query.filters)
  sql_query
end

#build_insert(record) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/hyperion/sql/query_builder.rb', line 13

def build_insert(record)
  record = record.dup
  table = format_table(record.delete(:kind))
  unless record.empty?
    columns = format_array(record.keys.map {|c| format_column(c) })
    values = format_array(record.values.map {|v| '?'})
    query = "INSERT INTO #{table} #{columns} VALUES #{values}"
  else
    query = qb_strategy.empty_insert_query(table)
  end
  SqlQuery.new(qb_strategy.normalize_insert(query), record.values)
end

#build_select(query) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/hyperion/sql/query_builder.rb', line 35

def build_select(query)
  sql_query = SqlQuery.new("SELECT * FROM \"#{query.kind}\"")
  apply_filters(sql_query, query.filters)
  apply_sorts(sql_query, query.sorts)
  qb_strategy.apply_limit_and_offset(sql_query, query.limit, query.offset)
  sql_query
end

#build_update(record) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/hyperion/sql/query_builder.rb', line 26

def build_update(record)
  record = record.dup
  table, id = Key.decompose_key(record.delete(:key))
  table = format_table(record.delete(:kind))
  column_values = record.keys.map {|field| "#{format_column(field)} = ?"}
  query = qb_strategy.normalize_update("UPDATE #{table} SET #{column_values.join(', ')} WHERE #{quote('id')} = #{id}")
  SqlQuery.new(query, record.values)
end