Files
jap_learn/src/data/repositories.rs
T

272 lines
8.2 KiB
Rust
Raw Normal View History

2026-08-25 15:46:39 +03:00
use crate::data::Id;
2026-08-26 17:53:09 +03:00
use crate::data::entities::{EntityData, EntityHandle, WordData};
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 17:53:09 +03:00
use std::ops::{Deref, DerefMut};
2026-08-25 15:46:39 +03:00
use std::sync::Arc;
2026-08-26 17:53:09 +03:00
use iced::application::IntoBoot;
use rusqlite::fallible_iterator::Iterator;
pub trait Repository<T, D> where D : DbLayer<T> {
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;
}
pub trait BatchedRepository<T, D> where D : BatchedDbLayer<T>, T: EntityData
{
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;
fn load_all(&self, storage: &mut Vec<T>, connection: &Connection) -> MaybeError;
}
pub trait BatchedDbLayer<T> where T : EntityData{
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> {
EntityHandle{
_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();
self.data_layer.write_entity(data, &self.connection.lock())?;
} else {
let index = fast_position_of(self.temporal.as_slice(), entity).unwrap();
let mut value = self.temporal.remove(index);
self.data_layer.add_entity(&mut value, &self.connection.lock())?;
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 {
self.data_layer.delete_entity(handle.id, &self.connection.lock())?;
&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 {
self.data_layer.load_all(&mut self.cache, &self.connection.lock())?;
Ok(())
}
fn reload(&mut self) -> MaybeError {
self.cache.clear();
self.temporal.clear();
self.init()?;
Ok(())
}
}
impl<T: EntityData + Clone, D: BatchedDbLayer<T>> BatchedRepository<T, D> for DataRepositoryInner<T, D> {
fn save_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError {
2026-08-25 15:46:39 +03:00
todo!()
}
2026-08-26 17:53:09 +03:00
fn delete_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);
let mut cell = 0;
handles.sort_by(|a, b| {a.id.cmp(&b.id)});
handles.iter().for_each(|handle| if handle.real { cached.push(handle.id)} else {
temp.push(handle.id)
});
let len = temp.len();
self.temporal.retain(|x| {
if cell == len { return true; }
let find = temp[cell];
let remove = x.id() == find;
if remove { cell += 1; }
!remove
});
self.data_layer.delete_many(cached.as_slice(), &self.connection.lock())?;
let len = cached.len();
cell = 0;
self.cache.retain(|x| {
if cell == len { return true; }
let find = cached[cell];
let remove = x.id() == find;
if remove { cell += 1; }
!remove
});
Ok(())
}
}
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
}