Class: PatternQueryHelper::Sql

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

Class Method Summary collapse

Class Method Details

.single_record_query(config) ⇒ Object



55
56
57
58
# File 'lib/pattern_query_helper/sql.rb', line 55

def self.single_record_query(config)
  results = sql_query(config)
  results.first
end

.sql_query(config) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/pattern_query_helper/sql.rb', line 3

def self.sql_query(config)
  model = config[:model]
  query = config[:query]
  query_params = config[:query_params] || {}
  page = config[:page]
  per_page = config[:per_page]
  filter_string = config[:filter_string]
  filter_params = config[:filter_params] || {}
  sort_string = config[:sort_string]

  if page && per_page
    query_params[:limit] = per_page
    query_params[:offset] = (page - 1) * per_page
    limit = "limit :limit offset :offset"
  end

  query_params = query_params.merge(filter_params).symbolize_keys
  sort_string = "order by #{sort_string}" if !sort_string.blank?
  filter_string = "where #{filter_string}" if !filter_string.blank?

  sql = %(
      with query as (#{query})
      select *
      from query
      #{filter_string}
      #{sort_string}
      #{limit}
    )

  model.find_by_sql([sql, query_params])
end

.sql_query_count(config) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/pattern_query_helper/sql.rb', line 35

def self.sql_query_count(config)
  model = config[:model]
  query = config[:query]
  query_params = config[:query_params] || {}
  filter_string = config[:filter_string]
  filter_params = config[:filter_params] || {}

  query_params = query_params.merge(filter_params).symbolize_keys
  filter_string = "where #{filter_string}" if !filter_string.blank?

  count_sql = %(
      with query as (#{query})
      select count(*) as count
      from query
      #{filter_string}
    )

  model.find_by_sql([count_sql, query_params]).first["count"]
end