use crate::database::Store;
use crate::entities::Table;
use crate::error::RepositoryError;
use crate::types::EntityId;
use std::collections::HashMap as StdHashMap;
use super::table_repository::TableRelationshipField;
use super::table_repository::TableTable;
use super::table_repository::TableTableRO;
fn read_field(table: &Table, field: &TableRelationshipField) -> Vec<EntityId> {
match field {
TableRelationshipField::Cells => table.cells.clone(),
}
}
fn write_field(table: &mut Table, field: &TableRelationshipField, ids: Vec<EntityId>) {
match field {
TableRelationshipField::Cells => table.cells = ids,
}
}
pub struct TableHashMapTable<'a> {
store: &'a Store,
}
impl<'a> TableHashMapTable<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> TableTable for TableHashMapTable<'a> {
fn create(&mut self, entity: &Table) -> Result<Table, RepositoryError> {
self.create_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn create_multi(&mut self, entities: &[Table]) -> Result<Vec<Table>, RepositoryError> {
let mut created = Vec::with_capacity(entities.len());
let mut table_map = self.store.tables.write();
for entity in entities {
let new_entity = if entity.id == EntityId::default() {
let id = self.store.next_id("table");
Table {
id,
..entity.clone()
}
} else {
if table_map.contains_key(&entity.id) {
return Err(RepositoryError::DuplicateId {
entity: "Table",
id: entity.id,
});
}
entity.clone()
};
table_map.insert(new_entity.id, new_entity.clone());
created.push(new_entity);
}
Ok(created)
}
fn get(&self, id: &EntityId) -> Result<Option<Table>, RepositoryError> {
Ok(self.store.tables.read().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Table>>, RepositoryError> {
let map = self.store.tables.read();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Table>, RepositoryError> {
Ok(self.store.tables.read().values().cloned().collect())
}
fn update(&mut self, entity: &Table) -> Result<Table, RepositoryError> {
self.update_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn update_multi(&mut self, entities: &[Table]) -> Result<Vec<Table>, RepositoryError> {
let mut table_map = self.store.tables.write();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
let mut to_write = entity.clone();
if let Some(existing) = table_map.get(&entity.id) {
to_write.cells = existing.cells.clone();
}
table_map.insert(entity.id, to_write.clone());
result.push(to_write);
}
Ok(result)
}
fn update_with_relationships(&mut self, entity: &Table) -> Result<Table, RepositoryError> {
self.update_with_relationships_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn update_with_relationships_multi(
&mut self,
entities: &[Table],
) -> Result<Vec<Table>, RepositoryError> {
let mut table_map = self.store.tables.write();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
table_map.insert(entity.id, entity.clone());
result.push(entity.clone());
}
Ok(result)
}
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 removed: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
{
let mut table_map = self.store.tables.write();
for id in ids {
table_map.remove(id);
}
}
{
let mut doc_map = self.store.documents.write();
let updates: Vec<(EntityId, crate::entities::Document)> = doc_map
.iter()
.filter_map(|(did, d)| {
if d.tables.iter().any(|tid| removed.contains(tid)) {
let mut updated = d.clone();
updated.tables.retain(|tid| !removed.contains(tid));
Some((*did, updated))
} else {
None
}
})
.collect();
for (did, d) in updates {
doc_map.insert(did, d);
}
}
{
let mut frame_map = self.store.frames.write();
let updates: Vec<(EntityId, crate::entities::Frame)> = frame_map
.iter()
.filter_map(|(fid, f)| {
f.table.filter(|t| removed.contains(t)).map(|_| {
let mut updated = f.clone();
updated.table = None;
(*fid, updated)
})
})
.collect();
for (fid, f) in updates {
frame_map.insert(fid, f);
}
}
Ok(())
}
fn get_relationship(
&self,
id: &EntityId,
field: &TableRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.tables
.read()
.get(id)
.map(|t| read_field(t, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &TableRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.tables.read();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|t| read_field(t, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &TableRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.tables
.read()
.get(id)
.map(|t| read_field(t, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &TableRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.tables
.read()
.get(id)
.map(|t| {
read_field(t, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &TableRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
Ok(tables_naming_any(self.store, field, right_ids))
}
fn set_relationship_multi(
&mut self,
field: &TableRelationshipField,
relationships: Vec<(EntityId, Vec<EntityId>)>,
) -> Result<(), RepositoryError> {
let mut map = self.store.tables.write();
for (id, ids) in relationships {
if let Some(table) = map.get_mut(&id) {
write_field(table, field, ids);
}
}
Ok(())
}
fn set_relationship(
&mut self,
id: &EntityId,
field: &TableRelationshipField,
right_ids: &[EntityId],
) -> Result<(), RepositoryError> {
let mut map = self.store.tables.write();
if let Some(table) = map.get_mut(id) {
write_field(table, field, right_ids.to_vec());
}
Ok(())
}
fn move_relationship_ids(
&mut self,
id: &EntityId,
field: &TableRelationshipField,
ids_to_move: &[EntityId],
new_index: i32,
) -> Result<Vec<EntityId>, RepositoryError> {
let mut map = self.store.tables.write();
let Some(table) = map.get_mut(id) else {
return Ok(Vec::new());
};
let current = read_field(table, field);
let moved = reorder(current, ids_to_move, new_index);
write_field(table, field, moved.clone());
Ok(moved)
}
}
pub struct TableHashMapTableRO<'a> {
store: &'a Store,
}
impl<'a> TableHashMapTableRO<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> TableTableRO for TableHashMapTableRO<'a> {
fn get(&self, id: &EntityId) -> Result<Option<Table>, RepositoryError> {
Ok(self.store.tables.read().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Table>>, RepositoryError> {
let map = self.store.tables.read();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Table>, RepositoryError> {
Ok(self.store.tables.read().values().cloned().collect())
}
fn get_relationship(
&self,
id: &EntityId,
field: &TableRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.tables
.read()
.get(id)
.map(|t| read_field(t, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &TableRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.tables.read();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|t| read_field(t, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &TableRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.tables
.read()
.get(id)
.map(|t| read_field(t, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &TableRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.tables
.read()
.get(id)
.map(|t| {
read_field(t, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &TableRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
Ok(tables_naming_any(self.store, field, right_ids))
}
}
fn tables_naming_any(
store: &Store,
field: &TableRelationshipField,
right_ids: &[EntityId],
) -> Vec<(EntityId, Vec<EntityId>)> {
let wanted: std::collections::HashSet<EntityId> = right_ids.iter().copied().collect();
let map = store.tables.read();
let mut out = Vec::new();
for (id, table) in map.iter() {
let list = read_field(table, field);
if list.iter().any(|named| is_wanted(&wanted, named)) {
out.push((*id, list));
}
}
out
}
fn is_wanted(wanted: &std::collections::HashSet<EntityId>, id: &EntityId) -> bool {
#[cfg(test)]
tests::PROBES.with(|probes| probes.set(probes.get() + 1));
wanted.contains(id)
}
fn reorder(current: Vec<EntityId>, ids_to_move: &[EntityId], new_index: i32) -> Vec<EntityId> {
if ids_to_move.is_empty() {
return current;
}
let move_set: std::collections::HashSet<EntityId> = ids_to_move.iter().copied().collect();
let mut remaining: Vec<EntityId> = current
.into_iter()
.filter(|eid| !move_set.contains(eid))
.collect();
let insert_pos = if new_index < 0 || (new_index as usize) > remaining.len() {
remaining.len()
} else {
new_index as usize
};
for (i, &eid) in ids_to_move.iter().enumerate() {
remaining.insert(insert_pos + i, eid);
}
remaining
}
#[cfg(test)]
mod tests {
use super::*;
use crate::entities::TableCell;
use std::cell::Cell;
thread_local! {
pub(super) static PROBES: Cell<usize> = const { Cell::new(0) };
}
const CELLS_PER_TABLE: u64 = 4;
fn small_tables(tables: u64) -> (Store, Vec<EntityId>) {
let store = Store::new();
let mut cell_ids = Vec::new();
{
let mut table_map = store.tables.write();
let mut cell_map = store.table_cells.write();
for table_id in 1..=tables {
let cells: Vec<EntityId> = (0..CELLS_PER_TABLE)
.map(|k| table_id * CELLS_PER_TABLE + k)
.collect();
for &id in &cells {
cell_map.insert(
id,
TableCell {
id,
..TableCell::default()
},
);
}
cell_ids.push(cells[cells.len() - 1]);
table_map.insert(
table_id,
Table {
id: table_id,
cells,
..Table::default()
},
);
}
}
(store, cell_ids)
}
#[test]
fn finding_owners_probes_each_listed_id_once() -> Result<(), RepositoryError> {
const TABLES: u64 = 1_000;
let listed = (TABLES * CELLS_PER_TABLE) as usize;
let (store, cell_ids) = small_tables(TABLES);
PROBES.with(|probes| probes.set(0));
let owners = TableHashMapTable::new(&store)
.get_relationships_from_right_ids(&TableRelationshipField::Cells, &cell_ids)?;
assert_eq!(owners.len(), TABLES as usize, "every table owns cells");
assert_eq!(
PROBES.with(Cell::get),
listed,
"the write lookup probed each of the {listed} listed ids once"
);
PROBES.with(|probes| probes.set(0));
let owners = TableHashMapTableRO::new(&store)
.get_relationships_from_right_ids(&TableRelationshipField::Cells, &cell_ids)?;
assert_eq!(owners.len(), TABLES as usize, "every table owns cells");
assert_eq!(
PROBES.with(Cell::get),
listed,
"the read lookup probed each of the {listed} listed ids once"
);
let asked = TABLES / 2 * CELLS_PER_TABLE + 1;
PROBES.with(|probes| probes.set(0));
let owners = TableHashMapTable::new(&store)
.get_relationships_from_right_ids(&TableRelationshipField::Cells, &[asked])?;
let owner = TABLES / 2;
assert_eq!(
owners,
vec![(
owner,
(0..CELLS_PER_TABLE)
.map(|k| owner * CELLS_PER_TABLE + k)
.collect()
)]
);
assert_eq!(
PROBES.with(Cell::get),
listed - (CELLS_PER_TABLE as usize - 2)
);
Ok(())
}
}