Files
jap_learn/src/data/repositories.rs
T

346 lines
9.9 KiB
Rust
Raw Normal View History

2026-08-25 15:46:39 +03:00
use crate::data::Id;
2026-08-26 19:48:22 +03:00
use crate::data::entities::{EntityData, EntityHandle};
2026-08-25 15:46:39 +03:00
use crate::notification::MaybeError;
use parking_lot::{Mutex, RwLock};
use rusqlite::Connection;
use std::marker::PhantomData;
2026-08-26 19:48:22 +03:00
use std::ops::Deref;
2026-08-25 15:46:39 +03:00
use std::sync::Arc;
2026-08-26 17:53:09 +03:00
2026-08-26 19:48:22 +03:00
pub trait Repository<T, D>
where
D: DbLayer<T>,
{
2026-08-26 17:53:09 +03:00
fn get(&self, handle: &mut EntityHandle<T>) -> Option<T>;
fn get_ref(&self, handle: &mut EntityHandle<T>) -> Option<&T>;
fn get_mut(&mut self, handle: &mut EntityHandle<T>) -> Option<&mut T>;
fn handle_by_id(&self, id: Id) -> EntityHandle<T>;
fn create(&mut self, new: T) -> EntityHandle<T>;
fn save(&mut self, entity: &mut EntityHandle<T>) -> MaybeError;
fn delete(&mut self, handle: EntityHandle<T>) -> MaybeError;
fn init(&mut self) -> MaybeError;
fn reload(&mut self) -> MaybeError;
}
2026-08-26 19:48:22 +03:00
pub trait BatchedRepository<T, D>
where
D: BatchedDbLayer<T>,
T: EntityData,
2026-08-26 17:53:09 +03:00
{
fn save_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError;
fn delete_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError;
}
pub trait DbLayer<T> {
fn write_entity(&self, entity: &T, connection: &Connection) -> MaybeError;
fn add_entity(&mut self, entity: &mut T, connection: &Connection) -> MaybeError;
fn delete_entity(&mut self, id: Id, connection: &Connection) -> MaybeError;
2026-08-26 19:48:22 +03:00
fn load_all(&self, storage: &mut Vec<T>, connection: &Connection) -> MaybeError;
2026-08-26 17:53:09 +03:00
}
2026-08-26 19:48:22 +03:00
pub trait BatchedDbLayer<T>
where
T: EntityData,
{
2026-08-26 17:53:09 +03:00
fn delete_many(&mut self, ids: &[Id], connection: &Connection) -> MaybeError;
fn add_many_entity(&mut self, entity: &mut [T], connection: &Connection) -> MaybeError;
}
2026-08-25 15:46:39 +03:00
#[derive(Clone)]
2026-08-26 17:53:09 +03:00
pub struct DataRepository<T, D> {
inner: Arc<RwLock<DataRepositoryInner<T, D>>>,
2026-08-25 15:46:39 +03:00
}
2026-08-26 17:53:09 +03:00
pub struct DataRepositoryInner<T, D> {
cache: Vec<T>,
temporal: Vec<T>,
2026-08-25 15:46:39 +03:00
next_temporal: u32,
connection: Arc<Mutex<Connection>>,
2026-08-26 17:53:09 +03:00
data_layer: D,
}
impl<T, D> Deref for DataRepository<T, D> {
type Target = Arc<RwLock<DataRepositoryInner<T, D>>>;
fn deref(&self) -> &Self::Target {
&self.inner
}
2026-08-25 15:46:39 +03:00
}
2026-08-26 17:53:09 +03:00
impl<T: EntityData + Clone, D: DbLayer<T>> Repository<T, D> for DataRepositoryInner<T, D> {
fn get(&self, handle: &mut EntityHandle<T>) -> Option<T> {
let slice = if handle.real {
self.cache.as_slice()
} else {
self.temporal.as_slice()
};
let index = fast_position_of(slice, handle)?;
Some(slice[index].clone())
}
fn get_ref(&self, handle: &mut EntityHandle<T>) -> Option<&T> {
let slice = if handle.real {
self.cache.as_slice()
} else {
self.temporal.as_slice()
};
let index = fast_position_of(slice, handle)?;
Some(&slice[index])
}
fn get_mut(&mut self, handle: &mut EntityHandle<T>) -> Option<&mut T> {
let slice = if handle.real {
self.cache.as_mut_slice()
} else {
self.temporal.as_mut_slice()
};
let index = fast_position_of(slice, handle)?;
Some(&mut slice[index])
2026-08-25 15:46:39 +03:00
}
2026-08-26 17:53:09 +03:00
fn handle_by_id(&self, id: Id) -> EntityHandle<T> {
2026-08-26 19:48:22 +03:00
EntityHandle {
2026-08-26 17:53:09 +03:00
_phantom: Default::default(),
id,
real: true,
index: id.0,
}
}
// fn get_static(&self, mut handle: EntityHandle<T>) -> Option<T> {
// let slice = if handle.real {
// self.cache.as_slice()
// } else {
// self.temporal.as_slice()
// };
// let index = fast_position_of(slice, &mut handle)?;
// Some(slice[index].clone())
// }
//
// fn get_ref_static(&self, mut handle: EntityHandle<T>) -> Option<&T> {
// let slice = if handle.real {
// self.cache.as_slice()
// } else {
// self.temporal.as_slice()
// };
// let index = fast_position_of(slice, &mut handle)?;
// Some(&slice[index])
// }
//
// fn get_mut_static(&mut self, mut handle: EntityHandle<T>) -> Option<&mut T> {
// let slice = if handle.real {
// self.cache.as_mut_slice()
// } else {
// self.temporal.as_mut_slice()
// };
// let index = fast_position_of(slice, &mut handle)?;
// Some(&mut slice[index])
// }
fn create(&mut self, mut new: T) -> EntityHandle<T> {
let next_temporal = self.next_temporal;
self.next_temporal += 1;
let entity = EntityHandle {
id: next_temporal.into(),
real: false,
index: self.temporal.len() as u32,
2026-08-25 15:46:39 +03:00
_phantom: PhantomData,
};
2026-08-26 17:53:09 +03:00
new.set_id(entity.id);
self.temporal.push(new);
2026-08-25 15:46:39 +03:00
entity
}
2026-08-26 17:53:09 +03:00
fn save(&mut self, entity: &mut EntityHandle<T>) -> MaybeError {
if entity.real {
let data = self.get_ref(entity).unwrap();
2026-08-26 19:48:22 +03:00
self.data_layer
.write_entity(data, &self.connection.lock())?;
2026-08-26 17:53:09 +03:00
} else {
let index = fast_position_of(self.temporal.as_slice(), entity).unwrap();
let mut value = self.temporal.remove(index);
2026-08-26 19:48:22 +03:00
self.data_layer
.add_entity(&mut value, &self.connection.lock())?;
2026-08-26 17:53:09 +03:00
entity.real = true;
entity.id = value.id();
entity.index = self.cache.len() as u32;
self.cache.push(value);
}
Ok(())
}
fn delete(&mut self, mut handle: EntityHandle<T>) -> MaybeError {
let vec = if handle.real {
2026-08-26 19:48:22 +03:00
self.data_layer
.delete_entity(handle.id, &self.connection.lock())?;
2026-08-26 17:53:09 +03:00
&mut self.cache
} else {
&mut self.temporal
};
let index = fast_position_of(vec.as_slice(), &mut handle).unwrap();
vec.remove(index);
Ok(())
}
fn init(&mut self) -> MaybeError {
2026-08-26 19:48:22 +03:00
self.data_layer
.load_all(&mut self.cache, &self.connection.lock())?;
2026-08-26 17:53:09 +03:00
Ok(())
}
fn reload(&mut self) -> MaybeError {
self.cache.clear();
self.temporal.clear();
self.init()?;
Ok(())
}
}
2026-08-26 19:48:22 +03:00
impl<T: EntityData + Clone, D: BatchedDbLayer<T> + DbLayer<T>> BatchedRepository<T, D>
for DataRepositoryInner<T, D>
{
2026-08-26 17:53:09 +03:00
fn save_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError {
let mut temp = Vec::with_capacity(handles.len() / 2);
let mut cached = Vec::with_capacity(handles.len() / 2);
2026-08-26 19:48:22 +03:00
handles.sort_by_key(|a| a.id);
handles.iter_mut().for_each(|handle| {
if handle.real {
cached.push(handle)
} else {
temp.push(handle)
}
});
let mut values = Vec::with_capacity(temp.len());
2026-08-26 17:53:09 +03:00
let mut cell = 0;
2026-08-26 19:48:22 +03:00
let len = temp.len();
self.temporal.retain(|x| {
if cell == len {
return true;
}
let find = temp[cell].id;
let remove = x.id() == find;
if remove || find > x.id() {
cell += 1;
values.push(x.clone());
}
!remove
2026-08-26 17:53:09 +03:00
});
2026-08-26 19:48:22 +03:00
self.data_layer
.add_many_entity(&mut values, &self.connection.lock())?;
let mut index = self.cache.len();
values
.iter()
.zip(temp)
.for_each(|(x, y)| {
y.id = x.id();
y.index = index as u32;
index += 1;
});
for in_cache in cached {
let value = self.get_ref(in_cache).unwrap();
self.data_layer.write_entity(value, &self.connection.lock())?;
}
todo!()
}
fn delete_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError {
let (cached, temp) = split_temp_real(handles, |e| e.id);
let mut cell = 0;
2026-08-26 17:53:09 +03:00
let len = temp.len();
self.temporal.retain(|x| {
2026-08-26 19:48:22 +03:00
if cell == len {
return true;
}
2026-08-26 17:53:09 +03:00
let find = temp[cell];
let remove = x.id() == find;
2026-08-26 19:48:22 +03:00
if remove || find > x.id() {
cell += 1;
}
2026-08-26 17:53:09 +03:00
!remove
});
2026-08-26 19:48:22 +03:00
self.data_layer
.delete_many(cached.as_slice(), &self.connection.lock())?;
2026-08-26 17:53:09 +03:00
let len = cached.len();
cell = 0;
self.cache.retain(|x| {
2026-08-26 19:48:22 +03:00
if cell == len {
return true;
}
2026-08-26 17:53:09 +03:00
let find = cached[cell];
let remove = x.id() == find;
2026-08-26 19:48:22 +03:00
if remove || find > x.id() {
cell += 1;
}
2026-08-26 17:53:09 +03:00
!remove
});
2026-08-26 19:48:22 +03:00
Ok(())
2026-08-26 17:53:09 +03:00
}
}
2026-08-26 19:48:22 +03:00
fn split_temp_real<T, F, V>(handles: &mut [EntityHandle<T>], getter: F) -> (Vec<V>, Vec<V>)
where
F: Fn(&EntityHandle<T>) -> V,
{
let mut temp = Vec::with_capacity(handles.len() / 2);
let mut cached = Vec::with_capacity(handles.len() / 2);
handles.sort_by(|a, b| a.id.cmp(&b.id));
handles.iter().for_each(|handle| {
if handle.real {
cached.push(getter(handle))
} else {
temp.push(getter(handle))
}
});
(cached, temp)
}
2026-08-26 17:53:09 +03:00
pub fn fast_position_of<E: EntityData>(
storage: &[E],
handle: &mut EntityHandle<E>,
) -> Option<usize> {
if storage.is_empty() {
return None;
}
let max_idx = storage.len() - 1;
let upper = (handle.index as usize).min(max_idx);
let peek = storage[upper].id();
if peek == handle.id {
handle.index = upper as u32;
return Some(upper);
}
if peek.0 < handle.id.0 {
return None;
}
let target_id_val = handle.id.0 as i64;
let peek_val = peek.0 as i64;
let delta = peek_val - target_id_val;
let new_index = (upper as i64 - delta).max(0) as usize;
if storage[new_index].id() == handle.id {
handle.index = new_index as u32;
return Some(new_index);
}
if new_index == upper {
return None;
}
let index = storage[new_index..upper]
.binary_search_by(|e| e.id().cmp(&handle.id))
.ok()?
+ new_index;
handle.index = index as u32;
Some(index)
2026-08-25 15:46:39 +03:00
}