use crate::database::hashmap_store::{
HashMapJunction, HashMapStore, delete_from_backward_junction, junction_get, junction_remove,
junction_set, read_or_recover, write_or_recover,
};
use crate::entities::Relationship;
use crate::error::RepositoryError;
use crate::types::EntityId;
use crate::{impl_relationship_methods, impl_write_relationship_methods};
use std::sync::RwLock;
use super::relationship_repository::RelationshipRelationshipField;
use super::relationship_repository::RelationshipTable;
use super::relationship_repository::RelationshipTableRO;
pub struct RelationshipHashMapTable<'a> {
store: &'a HashMapStore,
}
impl<'a> RelationshipHashMapTable<'a> {
pub fn new(store: &'a HashMapStore) -> Self {
Self { store }
}
fn resolve_junction(&self, field: &RelationshipRelationshipField) -> &RwLock<HashMapJunction> {
match field {
RelationshipRelationshipField::LeftEntity => {
&self.store.jn_entity_from_relationship_left_entity
}
RelationshipRelationshipField::RightEntity => {
&self.store.jn_entity_from_relationship_right_entity
}
}
}
fn relationship_source_exists(&self, id: &EntityId) -> bool {
read_or_recover(&self.store.relationships).contains_key(id)
}
fn relationship_is_ordered(&self, field: &RelationshipRelationshipField) -> bool {
match field {
RelationshipRelationshipField::LeftEntity => false,
RelationshipRelationshipField::RightEntity => false,
}
}
fn validate_relationship_updates(
&self,
field: &RelationshipRelationshipField,
rows: &[(EntityId, Vec<EntityId>)],
_creating_ids: &[EntityId],
) -> Result<(), RepositoryError> {
let scalar = match field {
RelationshipRelationshipField::LeftEntity => {
let targets = read_or_recover(&self.store.entities);
let missing: Vec<_> = rows
.iter()
.flat_map(|(_, ids)| ids)
.copied()
.filter(|id| !targets.contains_key(id))
.collect();
if !missing.is_empty() {
return Err(RepositoryError::MissingRelationshipTarget {
operation: "relationship update",
ids: missing,
});
}
true
}
RelationshipRelationshipField::RightEntity => {
let targets = read_or_recover(&self.store.entities);
let missing: Vec<_> = rows
.iter()
.flat_map(|(_, ids)| ids)
.copied()
.filter(|id| !targets.contains_key(id))
.collect();
if !missing.is_empty() {
return Err(RepositoryError::MissingRelationshipTarget {
operation: "relationship update",
ids: missing,
});
}
true
}
};
crate::database::hashmap_store::validate_junction_updates(
self.resolve_junction(field),
rows,
scalar,
)
}
fn hydrate(&self, entity: &mut Relationship) {
entity.left_entity = junction_get(
&self.store.jn_entity_from_relationship_left_entity,
&entity.id,
)
.into_iter()
.next();
entity.right_entity = junction_get(
&self.store.jn_entity_from_relationship_right_entity,
&entity.id,
)
.into_iter()
.next();
}
}
impl<'a> RelationshipTable for RelationshipHashMapTable<'a> {
fn create(&mut self, entity: &Relationship) -> Result<Relationship, RepositoryError> {
self.create_multi(std::slice::from_ref(entity))
.and_then(|v| {
v.into_iter().next().ok_or_else(|| {
RepositoryError::Other(anyhow::anyhow!(
"create: the store returned no row for the entity it was given"
))
})
})
}
fn create_multi(
&mut self,
entities: &[Relationship],
) -> Result<Vec<Relationship>, RepositoryError> {
let entities: Vec<_> = entities
.iter()
.map(|entity| {
let mut entity = entity.clone();
if entity.id == EntityId::default() {
entity.id = self.store.next_id("relationship");
}
entity
})
.collect();
let mut created = Vec::with_capacity(entities.len());
let mut relationship_map = write_or_recover(&self.store.relationships);
for entity in &entities {
let new_entity = if entity.id == EntityId::default() {
let id = self.store.next_id("relationship");
Relationship {
id,
..entity.clone()
}
} else {
if relationship_map.contains_key(&entity.id) {
return Err(RepositoryError::DuplicateId {
entity: "Relationship",
id: entity.id,
});
}
entity.clone()
};
relationship_map.insert(new_entity.id, new_entity.clone());
junction_set(
&self.store.jn_entity_from_relationship_left_entity,
new_entity.id,
new_entity
.left_entity
.into_iter()
.collect::<Vec<EntityId>>(),
);
junction_set(
&self.store.jn_entity_from_relationship_right_entity,
new_entity.id,
new_entity
.right_entity
.into_iter()
.collect::<Vec<EntityId>>(),
);
created.push(new_entity);
}
Ok(created)
}
fn get(&self, id: &EntityId) -> Result<Option<Relationship>, RepositoryError> {
let relationship_map = read_or_recover(&self.store.relationships);
match relationship_map.get(id) {
Some(entity) => {
let mut e = entity.clone();
drop(relationship_map);
self.hydrate(&mut e);
Ok(Some(e))
}
None => Ok(None),
}
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Relationship>>, RepositoryError> {
let mut result = Vec::with_capacity(ids.len());
for id in ids {
result.push(self.get(id)?);
}
Ok(result)
}
fn get_all(&self) -> Result<Vec<Relationship>, RepositoryError> {
let relationship_map = read_or_recover(&self.store.relationships);
let entries: Vec<Relationship> = relationship_map.values().cloned().collect();
drop(relationship_map);
let mut result = Vec::with_capacity(entries.len());
for mut entity in entries {
self.hydrate(&mut entity);
result.push(entity);
}
Ok(result)
}
fn update(&mut self, entity: &Relationship) -> Result<Relationship, RepositoryError> {
self.update_multi(std::slice::from_ref(entity))
.and_then(|v| {
v.into_iter().next().ok_or_else(|| {
RepositoryError::Other(anyhow::anyhow!(
"update: the store returned no row for the entity it was given"
))
})
})
}
fn update_multi(
&mut self,
entities: &[Relationship],
) -> Result<Vec<Relationship>, RepositoryError> {
let mut relationship_map = write_or_recover(&self.store.relationships);
for entity in entities {
relationship_map.insert(entity.id, entity.clone());
}
drop(relationship_map);
let ids: Vec<EntityId> = entities.iter().map(|e| e.id).collect();
let result = self.get_multi(&ids)?;
Ok(result.into_iter().flatten().collect())
}
fn update_with_relationships(
&mut self,
entity: &Relationship,
) -> Result<Relationship, RepositoryError> {
self.update_with_relationships_multi(std::slice::from_ref(entity))
.and_then(|v| {
v.into_iter().next().ok_or_else(|| {
RepositoryError::Other(anyhow::anyhow!(
"update_with_relationships: the store returned no row for the entity it was given"
))
})
})
}
fn update_with_relationships_multi(
&mut self,
entities: &[Relationship],
) -> Result<Vec<Relationship>, RepositoryError> {
let mut relationship_map = write_or_recover(&self.store.relationships);
for entity in entities {
relationship_map.insert(entity.id, entity.clone());
junction_set(
&self.store.jn_entity_from_relationship_left_entity,
entity.id,
entity.left_entity.into_iter().collect::<Vec<EntityId>>(),
);
junction_set(
&self.store.jn_entity_from_relationship_right_entity,
entity.id,
entity.right_entity.into_iter().collect::<Vec<EntityId>>(),
);
}
drop(relationship_map);
let ids: Vec<EntityId> = entities.iter().map(|e| e.id).collect();
let result = self.get_multi(&ids)?;
Ok(result.into_iter().flatten().collect())
}
fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError> {
self.remove_multi(std::slice::from_ref(id))
}
fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError> {
let mut relationship_map = write_or_recover(&self.store.relationships);
for id in ids {
relationship_map.remove(id);
junction_remove(&self.store.jn_entity_from_relationship_left_entity, id);
junction_remove(&self.store.jn_entity_from_relationship_right_entity, id);
delete_from_backward_junction(
&self.store.jn_relationship_from_entity_relationships,
id,
);
}
Ok(())
}
impl_write_relationship_methods!(RelationshipHashMapTable<'a>, RelationshipRelationshipField);
}
pub struct RelationshipHashMapTableRO<'a> {
store: &'a HashMapStore,
}
impl<'a> RelationshipHashMapTableRO<'a> {
pub fn new(store: &'a HashMapStore) -> Self {
Self { store }
}
fn resolve_junction(&self, field: &RelationshipRelationshipField) -> &RwLock<HashMapJunction> {
match field {
RelationshipRelationshipField::LeftEntity => {
&self.store.jn_entity_from_relationship_left_entity
}
RelationshipRelationshipField::RightEntity => {
&self.store.jn_entity_from_relationship_right_entity
}
}
}
fn hydrate(&self, entity: &mut Relationship) {
entity.left_entity = junction_get(
&self.store.jn_entity_from_relationship_left_entity,
&entity.id,
)
.into_iter()
.next();
entity.right_entity = junction_get(
&self.store.jn_entity_from_relationship_right_entity,
&entity.id,
)
.into_iter()
.next();
}
}
impl<'a> RelationshipTableRO for RelationshipHashMapTableRO<'a> {
fn get(&self, id: &EntityId) -> Result<Option<Relationship>, RepositoryError> {
let relationship_map = read_or_recover(&self.store.relationships);
match relationship_map.get(id) {
Some(entity) => {
let mut e = entity.clone();
drop(relationship_map);
self.hydrate(&mut e);
Ok(Some(e))
}
None => Ok(None),
}
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Relationship>>, RepositoryError> {
let mut result = Vec::with_capacity(ids.len());
for id in ids {
result.push(self.get(id)?);
}
Ok(result)
}
fn get_all(&self) -> Result<Vec<Relationship>, RepositoryError> {
let relationship_map = read_or_recover(&self.store.relationships);
let entries: Vec<Relationship> = relationship_map.values().cloned().collect();
drop(relationship_map);
let mut result = Vec::with_capacity(entries.len());
for mut entity in entries {
self.hydrate(&mut entity);
result.push(entity);
}
Ok(result)
}
impl_relationship_methods!(
RelationshipHashMapTableRO<'a>,
RelationshipRelationshipField
);
}