Module: Sequel::Plugins::IdentityMap

Defined in:
lib/sequel/plugins/identity_map.rb

Overview

The identity_map plugin allows the user to create temporary identity maps via the with_identity_map method, which takes a block. Inside the block, objects have a 1-1 correspondence with rows in the database.

For example, the following is true, and wouldn’t be true if you weren’t using the identity map:

Sequel::Model.with_identity_map do
  Album.filter{(id > 0) & (id < 2)}.first.object_id == Album.first(:id=>1).object_id
end

In addition to providing a 1-1 correspondence, the identity_map plugin also provides a cached looked up of records in two cases:

  • Model.[] (e.g. Album)

  • Model.many_to_one accessor methods (e.g. album.artist)

If the object you are looking up, using one of those two methods, is already in the identity map, the record is returned without a database query being issued.

Identity maps are thread-local and only persist for the duration of the block, so they should only be considered as a possible performance enhancer.

The identity_map plugin is not compatible with the standard eager loading of many_to_many and many_through_many associations. If you want to use the identity_map plugin, you should use eager_graph instead of eager for those associations. It is also not compatible with the eager loading in the rcte_tree plugin.

Usage:

# Use an identity map that will affect all model classes (called before loading subclasses)
Sequel::Model.plugin :identity_map

# Use an identity map just for the Album class
Album.plugin :identity_map
# would need to do Album.with_identity_map{} to use the identity map

Defined Under Namespace

Modules: ClassMethods, InstanceMethods