Skip to main content

Module identity_map

Module identity_map 

Source
Expand description

Identity Map pattern for tracking unique object instances per primary key.

The Identity Map ensures that each database row corresponds to exactly one object instance within a session. This provides:

  • Uniqueness: Same PK always returns the same object reference
  • Cache: Avoids redundant queries for the same object
  • Consistency: Changes to an object are visible everywhere it’s used

§Design

Unlike the simple clone-based approach, this implementation uses Arc<RwLock<T>> to provide true shared references. When you get an object twice with the same PK, you get references to the same underlying object.

§Example

let mut map = IdentityMap::new();

// Insert a new object
let user_ref = map.insert(user);

// Get the same object by PK
let user_ref2 = map.get::<User>(&pk_values);

// Both references point to the same object
assert!(Arc::ptr_eq(&user_ref.unwrap(), &user_ref2.unwrap()));

// Modifications are visible through both references
user_ref.write().unwrap().name = "Changed".to_string();
assert_eq!(user_ref2.read().unwrap().name, "Changed");

Structs§

IdentityMap
Identity Map for tracking unique object instances.
WeakIdentityMap
A weak-reference based identity map that allows objects to be garbage collected.

Type Aliases§

ModelReadGuard
A guard for reading an object from the identity map.
ModelRef
A reference to an object in the identity map.
ModelWriteGuard
A guard for writing to an object in the identity map.