Class: PgHelper::QueryBuilder

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table_name) ⇒ QueryBuilder

Returns a new instance of QueryBuilder.



9
10
11
12
13
14
15
# File 'lib/pg_helper/query_builder.rb', line 9

def initialize(table_name)
  @table_name = table_name
  @selects = []
  @where = []
  @cte_list = []
  @join_list = []
end

Instance Attribute Details

#table_nameObject (readonly)

Returns the value of attribute table_name.



3
4
5
# File 'lib/pg_helper/query_builder.rb', line 3

def table_name
  @table_name
end

Class Method Details

.from(table_name) ⇒ Object



5
6
7
# File 'lib/pg_helper/query_builder.rb', line 5

def self.from(table_name)
  new(table_name)
end

Instance Method Details

#join(join_sql) ⇒ Object



41
42
43
44
# File 'lib/pg_helper/query_builder.rb', line 41

def join(join_sql)
  @join_list << join_sql
  self
end

#select(value) ⇒ Object



26
27
28
29
# File 'lib/pg_helper/query_builder.rb', line 26

def select(value)
  @selects << value
  self
end

#to_sqlObject



18
19
20
21
22
23
24
# File 'lib/pg_helper/query_builder.rb', line 18

def to_sql
  "#{with_list}"\
  "SELECT #{column_list} "\
  "FROM #{table_name}"\
  "#{join_list}"\
  "#{where_list}"
end

#where(condition) ⇒ Object



31
32
33
34
# File 'lib/pg_helper/query_builder.rb', line 31

def where(condition)
  @where << condition
  self
end

#with(cte_name, cte_query) ⇒ Object



36
37
38
39
# File 'lib/pg_helper/query_builder.rb', line 36

def with(cte_name, cte_query)
  @cte_list << "#{cte_name} AS (#{cte_query})"
  self
end