Module: IdentityCache::QueryAPI::ClassMethods

Defined in:
lib/identity_cache/query_api.rb

Instance Method Summary collapse

Instance Method Details

#all_cached_associationsObject



100
101
102
# File 'lib/identity_cache/query_api.rb', line 100

def all_cached_associations
  (cached_has_manys || {}).merge(cached_has_ones || {}).merge(cached_belongs_tos || {})
end

#all_cached_associations_needing_populationObject



104
105
106
107
108
# File 'lib/identity_cache/query_api.rb', line 104

def all_cached_associations_needing_population
  all_cached_associations.select do |cached_association, options|
    options[:population_method_name].present? # non-embedded belongs_to associations don't need population
  end
end

#cache_fetch_includes(additions = {}) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/identity_cache/query_api.rb', line 110

def cache_fetch_includes(additions = {})
  additions = hashify_includes_structure(additions)
  embedded_associations = all_cached_associations.select { |name, options| options[:embed] }

  associations_for_identity_cache = embedded_associations.map do |child_association, options|
    child_class = reflect_on_association(child_association).try(:klass)

    child_includes = additions.delete(child_association)

    if child_class.respond_to?(:cache_fetch_includes)
      child_includes = child_class.cache_fetch_includes(child_includes)
    end

    if child_includes.blank?
      child_association
    else
      { child_association => child_includes }
    end
  end

  associations_for_identity_cache.push(additions) if additions.keys.size > 0
  associations_for_identity_cache.compact
end

#exists_with_identity_cache?(id) ⇒ Boolean

Similar to ActiveRecord::Base#exists? will return true if the id can be found in the cache or in the DB.

Returns:

Raises:



18
19
20
21
# File 'lib/identity_cache/query_api.rb', line 18

def exists_with_identity_cache?(id)
  raise NotImplementedError, "exists_with_identity_cache? needs the primary index enabled" unless primary_cache_index_enabled
  !!fetch_by_id(id)
end

#fetch(id) ⇒ Object

Default fetcher added to the model on inclusion, it behaves like ActiveRecord::Base.find, will raise ActiveRecord::RecordNotFound exception if id is not in the cache or the db.



43
44
45
# File 'lib/identity_cache/query_api.rb', line 43

def fetch(id)
  fetch_by_id(id) or raise(ActiveRecord::RecordNotFound, "Couldn't find #{self.class.name} with ID=#{id}")
end

#fetch_by_id(id) ⇒ Object

Default fetcher added to the model on inclusion, it behaves like ActiveRecord::Base.find_by_id

Raises:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/identity_cache/query_api.rb', line 25

def fetch_by_id(id)
  raise NotImplementedError, "fetching needs the primary index enabled" unless primary_cache_index_enabled
  if IdentityCache.should_cache?

    require_if_necessary do
      object = IdentityCache.fetch(rails_cache_key(id)){ resolve_cache_miss(id) }
      IdentityCache.logger.error "[IDC id mismatch] fetch_by_id_requested=#{id} fetch_by_id_got=#{object.id} for #{object.inspect[(0..100)]} " if object && object.id != id.to_i
      object
    end

  else
    self.find_by_id(id)
  end
end

#fetch_multi(*ids) ⇒ Object

Default fetcher added to the model on inclusion, if behaves like ActiveRecord::Base.find_all_by_id

Raises:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/identity_cache/query_api.rb', line 49

def fetch_multi(*ids)
  raise NotImplementedError, "fetching needs the primary index enabled" unless primary_cache_index_enabled
  options = ids.extract_options!
  if IdentityCache.should_cache?

    require_if_necessary do
      cache_keys = ids.map {|id| rails_cache_key(id) }
      key_to_id_map = Hash[ cache_keys.zip(ids) ]

      objects_by_key = IdentityCache.fetch_multi(*cache_keys) do |unresolved_keys|
        ids = unresolved_keys.map {|key| key_to_id_map[key] }
        records = find_batch(ids, options)
        records.compact.each(&:populate_association_caches)
        records
      end

      records = cache_keys.map {|key| objects_by_key[key] }.compact
      prefetch_associations(options[:includes], records) if options[:includes]

      records
    end

  else
    find_batch(ids, options)
  end
end

#find_batch(ids, options = {}) ⇒ Object



134
135
136
137
138
139
140
141
142
143
# File 'lib/identity_cache/query_api.rb', line 134

def find_batch(ids, options = {})
  @id_column ||= columns.detect {|c| c.name == "id"}
  ids = ids.map{ |id| @id_column.type_cast(id) }
  records = where('id IN (?)', ids).includes(cache_fetch_includes(options[:includes])).all
  records_by_id = records.index_by(&:id)
  records = ids.map{ |id| records_by_id[id] }
  mismatching_ids = records.compact.map(&:id) - ids
  IdentityCache.logger.error "[IDC id mismatch] fetch_batch_requested=#{ids.inspect} fetch_batch_got=#{mismatchig_ids.inspect} mismatching ids "  unless mismatching_ids.empty?
  records
end

#hashify_includes_structure(structure) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/identity_cache/query_api.rb', line 212

def hashify_includes_structure(structure)
  case structure
  when nil
    {}
  when Symbol
    {structure => []}
  when Hash
    structure.clone
  when Array
    structure.each_with_object({}) do |member, hash|
      case member
      when Hash
        hash.merge!(member)
      when Symbol
        hash[member] = []
      end
    end
  end
end

#prefetch_associations(associations, records) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/identity_cache/query_api.rb', line 145

def prefetch_associations(associations, records)
  associations = hashify_includes_structure(associations)

  associations.each do |association, sub_associations|
    case
    when details = cached_has_manys[association]

      if details[:embed]
        child_records = records.map(&details[:cached_accessor_name].to_sym).flatten
      else
        ids_to_parent_record = records.each_with_object({}) do |record, hash|
          child_ids = record.send(details[:cached_ids_name])
          child_ids.each do |child_id|
            hash[child_id] = record
          end
        end

        parent_record_to_child_records = Hash.new { |h, k| h[k] = [] }
        child_records = details[:association_class].fetch_multi(*ids_to_parent_record.keys)
        child_records.each do |child_record|
          parent_record = ids_to_parent_record[child_record.id]
          parent_record_to_child_records[parent_record] << child_record
        end

        parent_record_to_child_records.each do |parent_record, child_records|
          parent_record.send(details[:prepopulate_method_name], child_records)
        end
      end

      next_level_records = child_records

    when details = cached_belongs_tos[association]
      if details[:embed]
        raise ArgumentError.new("Embedded belongs_to associations do not support prefetching yet.")
      else
        ids_to_child_record = records.each_with_object({}) do |child_record, hash|
          parent_id = child_record.send(details[:foreign_key])
          hash[parent_id] = child_record if parent_id.present?
        end
        parent_records = details[:association_class].fetch_multi(*ids_to_child_record.keys)
        parent_records.each do |parent_record|
          child_record = ids_to_child_record[parent_record.id]
          child_record.send(details[:prepopulate_method_name], parent_record)
        end
      end

      next_level_records = parent_records

    when details = cached_has_ones[association]
      if details[:embed]
        parent_records = records.map(&details[:cached_accessor_name].to_sym)
      else
        raise ArgumentError.new("Non-embedded has_one associations do not support prefetching yet.")
      end

      next_level_records = parent_records

    else
      raise ArgumentError.new("Unknown cached association #{association} listed for prefetching")
    end

    if details && details[:association_class].respond_to?(:prefetch_associations)
      details[:association_class].prefetch_associations(sub_associations, next_level_records)
    end
  end
end

#require_if_necessaryObject

:nodoc:



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/identity_cache/query_api.rb', line 76

def require_if_necessary #:nodoc:
  # mem_cache_store returns raw value if unmarshal fails
  rval = yield
  case rval
  when String
    rval = Marshal.load(rval)
  when Array
    rval.map!{ |v| v.kind_of?(String) ? Marshal.load(v) : v }
  end
  rval
rescue ArgumentError => e
  if e.message =~ /undefined [\w\/]+ (\w+)/
    ok = Kernel.const_get($1) rescue nil
    retry if ok
  end
  raise
end

#resolve_cache_miss(id) ⇒ Object



94
95
96
97
98
# File 'lib/identity_cache/query_api.rb', line 94

def resolve_cache_miss(id)
  self.find_by_id(id, :include => cache_fetch_includes).tap do |object|
    object.try(:populate_association_caches)
  end
end