Module: IdentityCache::QueryAPI::ClassMethods

Defined in:
lib/identity_cache/query_api.rb

Instance Method Summary collapse

Instance Method Details

#add_cached_associations_to_coder(record, coder) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/identity_cache/query_api.rb', line 149

def add_cached_associations_to_coder(record, coder)
  if record.class.respond_to?(:all_embedded_associations) && record.class.all_embedded_associations.present?
    coder[:associations] = record.class.all_embedded_associations.each_with_object({}) do |(name, options), hash|
      hash[name] = IdentityCache.map_cached_nil_for(get_embedded_association(record, name, options))
    end
  end
  if record.class.respond_to?(:cached_has_manys) && record.class.cached_has_manys.present?
    coder[:normalized_has_many] = record.class.cached_has_manys.each_with_object({}) do |(name, options), hash|
      hash[name] = record.instance_variable_get(:"@#{options[:ids_variable_name]}") unless options[:embed]
    end
  end
end

#all_cached_associations ⇒ Object



192
193
194
# File 'lib/identity_cache/query_api.rb', line 192

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

#all_cached_associations_needing_population ⇒ Object



196
197
198
199
200
# File 'lib/identity_cache/query_api.rb', line 196

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

#all_embedded_associations ⇒ Object



186
187
188
189
190
# File 'lib/identity_cache/query_api.rb', line 186

def all_embedded_associations
  all_cached_associations.select do |cached_association, options|
    options[:embed].present?
  end
end

#cache_fetch_includes(additions = {}) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/identity_cache/query_api.rb', line 202

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

#coder_from_record(record) ⇒ Object

:nodoc:



140
141
142
143
144
145
146
147
# File 'lib/identity_cache/query_api.rb', line 140

def coder_from_record(record) #:nodoc:
  unless record.nil?
    coder = {:class => record.class }
    record.encode_with(coder)
    add_cached_associations_to_coder(record, coder)
    coder
  end
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:

  • (Boolean)

Raises:

  • (NotImplementedError)


23
24
25
26
# File 'lib/identity_cache/query_api.rb', line 23

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.



51
52
53
# File 'lib/identity_cache/query_api.rb', line 51

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

#fetch_by_id(id) ⇒ Object

Default fetcher added to the model on inclusion, it behaves like ActiveRecord::Base.where(id: id).first

Raises:

  • (NotImplementedError)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/identity_cache/query_api.rb', line 30

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

    require_if_necessary do
      object = nil
      coder = IdentityCache.fetch(rails_cache_key(id)){ coder_from_record(object = resolve_cache_miss(id)) }
      object ||= record_from_coder(coder)
      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.where(id: id).first
  end
end

#fetch_multi(*ids) ⇒ Object

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

Raises:

  • (NotImplementedError)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/identity_cache/query_api.rb', line 57

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) ]

      coders_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.map {|record| coder_from_record(record) }
      end

      records = cache_keys.map {|key| record_from_coder(coders_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



226
227
228
229
230
231
232
233
234
235
# File 'lib/identity_cache/query_api.rb', line 226

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])).to_a
  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

#get_embedded_association(record, association, options) ⇒ Object

:nodoc:



129
130
131
132
133
134
135
136
137
138
# File 'lib/identity_cache/query_api.rb', line 129

def get_embedded_association(record, association, options) #:nodoc:
  embedded_variable = record.instance_variable_get(:"@#{options[:records_variable_name]}")
  if IdentityCache.unmap_cached_nil_for(embedded_variable).nil?
    nil
  elsif record.class.reflect_on_association(association).collection?
    embedded_variable.map {|e| coder_from_record(e) }
  else
    coder_from_record(embedded_variable)
  end
end

#hashify_includes_structure(structure) ⇒ Object



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/identity_cache/query_api.rb', line 304

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



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/identity_cache/query_api.rb', line 237

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

#record_from_coder(coder) ⇒ Object

:nodoc:



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
# File 'lib/identity_cache/query_api.rb', line 84

def record_from_coder(coder) #:nodoc:
  if coder.present? && coder.has_key?(:class)
    record = coder[:class].allocate
    unless coder[:class].serialized_attributes.empty?
      coder = coder.dup
      coder['attributes'] = coder['attributes'].dup
    end
    if record.class._initialize_callbacks.empty?
      record.instance_eval do
        @attributes = self.class.initialize_attributes(coder['attributes'])
        @relation = nil

        @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
        @association_cache = {}
        @aggregation_cache = {}
        @_start_transaction_state = {}
        @readonly = @destroyed = @marked_for_destruction = false
        @new_record = false
        @column_types = self.class.column_types if self.class.respond_to?(:column_types)
      end
    else
      record.init_with(coder)
    end

    coder[:associations].each {|name, value| set_embedded_association(record, name, value) } if coder.has_key?(:associations)
    coder[:normalized_has_many].each {|name, ids| record.instance_variable_set(:"@#{record.class.cached_has_manys[name][:ids_variable_name]}", ids) } if coder.has_key?(:normalized_has_many)
    record
  end
end

#require_if_necessary ⇒ Object

:nodoc:



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/identity_cache/query_api.rb', line 162

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



180
181
182
183
184
# File 'lib/identity_cache/query_api.rb', line 180

def resolve_cache_miss(id)
  object = self.includes(cache_fetch_includes).where(id: id).try(:first)
  object.try(:populate_association_caches)
  object
end

#set_embedded_association(record, association_name, coder_or_array) ⇒ Object

:nodoc:



114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/identity_cache/query_api.rb', line 114

def set_embedded_association(record, association_name, coder_or_array) #:nodoc:
  value = if IdentityCache.unmap_cached_nil_for(coder_or_array).nil?
    nil
  elsif (reflection = record.class.reflect_on_association(association_name)).collection?
    association = reflection.association_class.new(record, reflection)
    association.target = coder_or_array.map {|e| record_from_coder(e) }
    association.target.each {|e| association.set_inverse_instance(e) }
    association
  else
    record_from_coder(coder_or_array)
  end
  variable_name = record.class.all_embedded_associations[association_name][:records_variable_name]
  record.instance_variable_set(:"@#{variable_name}", IdentityCache.map_cached_nil_for(value))
end