Class: HasHelpers::Search::SqlSearch

Inherits:
Object
  • Object
show all
Includes:
Provider, SearchExtensions::ProviderExtensions
Defined in:
app/lib/has_helpers/search/sql_search.rb

Constant Summary

Constants included from Provider

Provider::PAGINATION_ATTRS

Instance Attribute Summary

Attributes included from Provider

#controller

Instance Method Summary collapse

Methods included from Provider

#initialize, owner_relation_from_scope, #results, #search_prefix, #search_screen

Instance Method Details

#exec_query(resource:, query:, options:, filter:) ⇒ Object



11
12
13
14
15
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
44
45
46
47
48
49
50
51
52
# File 'app/lib/has_helpers/search/sql_search.rb', line 11

def exec_query(resource:, query:, options:, filter:)
  resource_klasses = Array(resource).map { |r| normalize_resource_to_class(r) }.compact.uniq

  base_limit = Integer(options.dig(:with, :limit)) rescue Rails.application.config.x.search_default_limit
  limit = base_limit * resource_klasses.size

  intermediate_results = resource_klasses.map do |klass|
    # Is the class have a custom search
    if klass.respond_to?(:search)
      sql_results = klass.search(query, sql_search_options(options))

      # NOTE: Previously pagination was required.
      if defined?(ActiveRecord::Relation) && sql_results.is_a?(ActiveRecord::Relation)
        scoped = apply_org_scope_relation(sql_results, options)
        scoped = apply_filters_relation(scoped, filter)
        scoped.limit(limit)
      else
        # If the search already return the response (e.g. an Array, Hash).
        sql_results
      end
    else
      resource_relation_name, owner_relation_name, owner_relation = owner_relation_from_scope(klass)

      # If an owner relation exists then search on its name and sub_item columns.
      # Otherwise fallback to searching the name column for the base relation.
      if owner_relation
        scope = owner_relation
        search_vector = "CONCAT_WS(' ', #{ owner_relation_name }.name, #{ owner_relation_name }.sub_item)"
      else
        scope = klass
        search_vector = "#{ resource_relation_name }.name"
      end

      table_name = owner_relation ? owner_relation_name : resource_relation_name
      scoped = apply_org_scope_table(scope, table_name, options)
      scoped = apply_filters_relation(scoped, filter)
      scoped.where(::HasHelpers::Query::Sql.sql(search_vector, query)).limit(limit)
    end
  end

  { results: intermediate_results.flatten }
end

#search_options(prefix, screen = prefix, query) ⇒ Object



7
8
9
# File 'app/lib/has_helpers/search/sql_search.rb', line 7

def search_options(prefix, screen = prefix, query)
  super.merge(organization_id: current_user.organization_id)
end