Class: Superstore::Adapters::JsonbAdapter::QueryBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/superstore/adapters/jsonb_adapter.rb

Instance Method Summary collapse

Constructor Details

#initialize(adapter, scope) ⇒ QueryBuilder

Returns a new instance of QueryBuilder.



8
9
10
11
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 8

def initialize(adapter, scope)
  @adapter  = adapter
  @scope    = scope
end

Instance Method Details

#from_stringObject



23
24
25
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 23

def from_string
  "FROM #{@scope.klass.table_name}"
end

#limit_stringObject



60
61
62
63
64
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 60

def limit_string
  if @scope.limit_value
    "LIMIT #{@scope.limit_value}"
  end
end

#order_stringObject



50
51
52
53
54
55
56
57
58
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 50

def order_string
  if @scope.order_values.any?
    orders = @scope.order_values.join(', ')
    "ORDER BY #{orders}"
  elsif @scope.id_values.many?
    id_orders = @scope.id_values.map { |id| "ID=#{@adapter.quote(id)} DESC" }.join(',')
    "ORDER BY #{id_orders}"
  end
end

#select_stringObject



27
28
29
30
31
32
33
34
35
36
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 27

def select_string
  if @scope.select_values.empty?
    '*'
  elsif @scope.select_values == [@adapter.primary_key_column]
    @adapter.primary_key_column
  else
    selects = @scope.select_values.map { |key| "#{@adapter.quote(key)},document->>#{@adapter.quote(key)}" }
    "#{@adapter.primary_key_column}, json_build_object(#{selects * ','}) as document"
  end
end

#to_queryObject



13
14
15
16
17
18
19
20
21
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 13

def to_query
  [
    "SELECT #{select_string}",
    from_string,
    where_string,
    order_string,
    limit_string
  ].delete_if(&:blank?) * ' '
end

#where_stringObject



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 38

def where_string
  wheres = where_values_as_strings

  if @scope.id_values.any?
    wheres << @adapter.create_ids_where_clause(@scope.id_values)
  end

  if wheres.any?
    "WHERE #{wheres * ' AND '}"
  end
end

#where_values_as_stringsObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/superstore/adapters/jsonb_adapter.rb', line 66

def where_values_as_strings
  @scope.where_values.map do |where_value|
    if where_value.is_a?(Hash)
      key = where_value.keys.first
      value = where_value.values.first

      if value.nil?
        "(document->>'#{key}') IS NULL"
      elsif value.is_a?(Array)
        typecasted_values = value.map { |v| "'#{v}'" }.join(',')
        "document->>'#{key}' IN (#{typecasted_values})"
      else
        "document->>'#{key}' = '#{value}'"
      end
    else
      where_value
    end
  end
end