Class: ForestLiana::SearchQueryBuilder

Inherits:
Object
  • Object
show all
Defined in:
app/services/forest_liana/search_query_builder.rb

Constant Summary collapse

REGEX_UUID =
/\A[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\z/i

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params, includes, collection, user) ⇒ SearchQueryBuilder

Returns a new instance of SearchQueryBuilder.



7
8
9
10
11
12
13
14
# File 'app/services/forest_liana/search_query_builder.rb', line 7

def initialize(params, includes, collection, user)
  @params = params
  @includes = includes
  @collection = collection
  @fields_searched = []
  @search = @params[:search]
  @user = user
end

Instance Attribute Details

#fields_searchedObject (readonly)

Returns the value of attribute fields_searched.



5
6
7
# File 'app/services/forest_liana/search_query_builder.rb', line 5

def fields_searched
  @fields_searched
end

Instance Method Details

#acts_as_taggable?(field) ⇒ Boolean

Returns:

  • (Boolean)


211
212
213
214
# File 'app/services/forest_liana/search_query_builder.rb', line 211

def acts_as_taggable?(field)
  @resource.try(:taggable?) && @resource.respond_to?(:acts_as_taggable) &&
    @resource.acts_as_taggable.include?(field)
end

#acts_as_taggable_query(tagged_records) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'app/services/forest_liana/search_query_builder.rb', line 49

def acts_as_taggable_query(tagged_records)
  ids = tagged_records
    .map {|t| t[@resource.primary_key]}
    .join(',')

  if ids.present?
    return "#{@resource.primary_key} IN (#{ids})"
  end
end

#association_search_condition(table_name, column_name) ⇒ Object



206
207
208
209
# File 'app/services/forest_liana/search_query_builder.rb', line 206

def association_search_condition table_name, column_name
  column_name = format_column_name(table_name, column_name)
  "LOWER(#{column_name}) LIKE :search_value_for_string"
end

#association_table_name(name) ⇒ Object



158
159
160
161
162
163
# File 'app/services/forest_liana/search_query_builder.rb', line 158

def association_table_name(name)
  QueryHelper.get_tables_associated_to_relations_name(@records).detect { |key, values|
    break key if Array(values).include?(name)
  }

end

#detect_reference(param) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'app/services/forest_liana/search_query_builder.rb', line 186

def detect_reference(param)
  ref, field = param.split('.')

  if ref && field
    association = @resource.reflect_on_all_associations
      .find {|a| a.name == ref.to_sym }

    referenced_table = association ? association_table_name(association.name) : ref

    ForestLiana::AdapterHelper
      .format_column_name(referenced_table, field)
  else
    param
  end
end

#detect_sort_order(field) ⇒ Object



202
203
204
# File 'app/services/forest_liana/search_query_builder.rb', line 202

def detect_sort_order(field)
  return (if field[0] == '-' then :desc else :asc end)
end

#format_column_name(table_name, column_name) ⇒ Object



45
46
47
# File 'app/services/forest_liana/search_query_builder.rb', line 45

def format_column_name(table_name, column_name)
  ForestLiana::AdapterHelper.format_column_name(table_name, column_name)
end

#perform(resource) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/services/forest_liana/search_query_builder.rb', line 16

def perform(resource)
  @resource = @records = resource
  @tables_associated_to_relations_name =
    ForestLiana::QueryHelper.get_tables_associated_to_relations_name(@resource)
  @records = search_param

  filters = ForestLiana::ScopeManager.append_scope_for_user(@params[:filters], @user, @collection.name)

  unless filters.blank?
    @records = FiltersParser.new(filters, @records, @params[:timezone]).apply_filters
  end

  if @search
    ForestLiana.schema_for_resource(@resource).fields.each do |field|
      if field.try(:[], :search)
        begin
          @records = field[:search].call(@records, @search)
        rescue => exception
          FOREST_REPORTER.report exception
          FOREST_LOGGER.error "Cannot search properly on Smart Field:\n" \
            "#{exception}"
        end
      end
    end
  end
  @records = sort_query
  @records
end

#search_paramObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/services/forest_liana/search_query_builder.rb', line 59

def search_param
  if @search
    conditions = []

    @resource.columns.each_with_index do |column, index|
      @fields_searched << column.name if text_type?(column.type) || column.type == :uuid
      column_name = format_column_name(@resource.table_name, column.name)
      if (@collection.search_fields && !@collection.search_fields.include?(column.name))
        conditions
      elsif column.name == 'id'
        if column.type == :integer
          value = @search.to_i
          conditions << "#{@resource.table_name}.id = #{value}" if value > 0
        elsif REGEX_UUID.match(@search)
          conditions << "#{@resource.table_name}.id = :search_value_for_uuid"
        end
      # NOTICE: Rails 3 do not have a defined_enums method
      elsif REGEX_UUID.match(@search) && column.type == :uuid
        conditions << "#{column_name}  = :search_value_for_uuid"
      elsif @resource.respond_to?(:defined_enums) &&
        @resource.defined_enums.has_key?(column.name) &&
        !@resource.defined_enums[column.name][@search.downcase].nil?
        conditions << "#{column_name} =
          #{@resource.defined_enums[column.name][@search.downcase]}"
      elsif !(column.respond_to?(:array) && column.array) && text_type?(column.type)
        conditions << "LOWER(#{column_name}) LIKE :search_value_for_string"
      end
    end

    # ActsAsTaggable
    if @resource.try(:taggable?) && @resource.respond_to?(:acts_as_taggable)
      @resource.acts_as_taggable.each do |field|
        tagged_records = @records.tagged_with(@search.downcase)
        condition = acts_as_taggable_query(tagged_records)
        conditions << condition if condition
      end
    end

    if (@params['searchExtended'].to_i == 1)
      ForestLiana::QueryHelper.get_one_association_names_symbol(@resource).each do |association|
        if @collection.search_fields
          association_search = @collection.search_fields.map do |field|
            if field.include?('.') && field.split('.')[0] == association.to_s
              field.split('.')[1]
            end
          end
          association_search = association_search.compact
        end

        if @includes.include? association.to_sym
          resource = @resource.reflect_on_association(association.to_sym)
          unless (SchemaUtils.polymorphic?(resource))
            resource.klass.columns.each do |column|
              if !(column.respond_to?(:array) && column.array) && text_type?(column.type)
                if @collection.search_fields.nil? || (association_search &&
                  association_search.include?(column.name))
                  conditions << association_search_condition(resource.table_name,
                    column.name)
                end
              end
            end
          end
        end
      end

      if @collection.search_fields
        SchemaUtils.many_associations(@resource).map(&:name).each do
          |association|
          association_search = @collection.search_fields.map do |field|
            if field.include?('.') && field.split('.')[0] == association.to_s
              field.split('.')[1]
            end
          end
          association_search = association_search.compact
          unless association_search.empty?
            resource = @resource.reflect_on_association(association.to_sym)
            resource.klass.columns.each do |column|
              if !(column.respond_to?(:array) && column.array) && text_type?(column.type)
                if association_search.include?(column.name)
                  conditions << association_search_condition(resource.table_name,
                    column.name)
                end
              end
            end
          end
        end
      end
    end

    @records = @resource.where(
      conditions.join(' OR '),
      search_value_for_string: "%#{@search.downcase}%",
      search_value_for_uuid: @search.to_s
    )
  end

  @records
end

#sort_queryObject



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'app/services/forest_liana/search_query_builder.rb', line 165

def sort_query
  if @params[:sort]
    @params[:sort].split(',').each do |field|
      order_detected = detect_sort_order(field)
      order = order_detected.upcase
      field.slice!(0) if order_detected == :desc

      field = detect_reference(field)
      if field.index('.').nil?
        column = ForestLiana::AdapterHelper.format_column_name(@resource.table_name, field)
      else
        column = field
      end

      @records = @records.order(Arel.sql("#{column} #{order}"))
    end
  end

  @records
end