Class: PostJson::DynamicIndex

Inherits:
ActiveRecord::Base
  • Object
show all
Extended by:
ArgumentMethods
Defined in:
lib/post_json/dynamic_index.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ArgumentMethods

assert_valid_indifferent_keys, flatten_arguments, join_arguments

Class Method Details

.destroy_index(model_settings_id, selector) ⇒ Object


24
25
26
# File 'lib/post_json/dynamic_index.rb', line 24

def destroy_index(model_settings_id, selector)
  where(model_settings_id: model_settings_id, selector: selector).destroy_all.present?
end

.ensure_index(model_settings_id, *selectors) ⇒ Object


6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/post_json/dynamic_index.rb', line 6

def ensure_index(model_settings_id, *selectors)
  selectors = flatten_arguments(selectors)
  if selectors.length == 0
    []
  else
    existing_selectors = where(model_settings_id: model_settings_id).pluck(:selector)
    new_selectors = selectors - existing_selectors
    new_selectors.map do |selector|
      create(model_settings_id: model_settings_id, selector: selector)
    end
  end
end

.indexed_selectors(model_settings_id) ⇒ Object


19
20
21
22
# File 'lib/post_json/dynamic_index.rb', line 19

def indexed_selectors(model_settings_id)
  # distinct is needed since race condition can cause 1+ records to own the same index
  where(model_settings_id: model_settings_id).distinct.pluck(:selector)
end

Instance Method Details

#index_nameObject


37
38
39
40
41
42
43
44
45
46
47
# File 'lib/post_json/dynamic_index.rb', line 37

def index_name
  @index_name ||= unless @index_name
                    prefix = "dyn_#{model_settings_id.gsub('-', '')}_"
                    if 63 < prefix.length + selector.length
                      digest = Digest::MD5.hexdigest(selector) 
                      "#{prefix}#{digest}"[0..62]
                    else
                      "#{prefix}#{selector.gsub('.', '_')}"
                    end
                  end
end

#inline_create_index_procedureObject


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/post_json/dynamic_index.rb', line 63

def inline_create_index_procedure
  schemas = ActiveRecord::Base.connection.schema_search_path.gsub(/\s+/, '').split(',')
  current_schema =  if schemas[0] == "\"$user\"" && 1 < schemas.length
                      schemas[1]
                    else
                      schemas[0]
                    end
"DO $$
BEGIN

IF NOT EXISTS (
SELECT 1
FROM   pg_class c
JOIN   pg_namespace n ON n.oid = c.relnamespace
WHERE  c.relname = '#{index_name}'
AND    n.nspname = '#{current_schema}' -- 'public' by default
) THEN

CREATE INDEX #{index_name} ON #{current_schema}.#{Base.table_name} (json_selector('#{selector}', __doc__body));
END IF;

END$$;"
end