First repo code

This commit is contained in:
micialware committed 2026-08-25 15:46:39 +03:00
1 parent 1f3ad22e05
commit 807f398d81
6 files changed
+399 -13

No files matched your search

+1
View File
@@ -1,4 +1,5 @@
pub mod entities;
pub mod repositories;
use rusqlite::ToSql;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
+50
View File
@@ -1,11 +1,14 @@
use crate::app::AppState;
use crate::core::srs::{FADE_PER_DAY, MAX_SCORE, OrderMode, WordOpenMode};
use crate::data::{INVALID_ID, Id};
use crate::notification::MaybeError;
use chrono::{DateTime, Utc};
use log::info;
use rayon::prelude::*;
use rhai::{Engine, Scope};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::time::Instant;
#[derive(Clone, Debug)]
@@ -164,3 +167,50 @@ impl CardStatistics {
(self.score as f32 * multiplier).max(1.0)
}
}
#[derive(Clone)]
pub struct Entity<E, R: Repository<E>> {
pub(crate) repo: R,
pub(crate) _phantom: PhantomData<E>,
pub(crate) inner: EntityInner,
}
#[derive(Clone)]
pub(crate) struct EntityInner {
pub(crate) id: Id,
pub(crate) real: bool,
}
impl<E, R: Repository<E>> Entity<E, R> {
pub fn load(&self) -> EntityAccess<E, R> {
let clone = *self.clone();
let repo = &self.repo;
let value = repo.get(self.inner.id).unwrap();
EntityAccess { value, entity: clone, }
}
}
pub struct EntityAccess<E, R: Repository<E>> {
entity: Entity<E, R>,
value: E,
}
impl<E, R: Repository<E>> Deref for EntityAccess<E, R> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<E, R: Repository<E>> DerefMut for EntityAccess<E, R> {
fn deref_mut(&mut self) -> &mut E {
&mut self.value
}
}
pub trait Repository<T> {
fn get(&self, id: Id) -> Option<T>;
fn create(&mut self, new: T) -> Entity<T, impl Repository<T>>;
fn save(&mut self, entity: EntityInner) -> MaybeError;
}
+46
View File
@@ -0,0 +1,46 @@
use crate::data::Id;
use crate::data::entities::{Entity, EntityInner, Repository, WordData};
use crate::notification::MaybeError;
use parking_lot::{Mutex, RwLock};
use rusqlite::Connection;
use std::marker::PhantomData;
use std::sync::Arc;
#[derive(Clone)]
pub struct WordRepository {
inner: Arc<RwLock<WordRepositoryInner>>,
}
pub struct WordRepositoryInner {
cache: Vec<WordData>,
temporal: Vec<Entity<WordData, WordRepository>>,
next_temporal: u32,
connection: Arc<Mutex<Connection>>,
}
impl Repository<WordData> for WordRepository {
fn get(&self, id: Id) -> Option<WordData> {
let inner = self.inner.read();
Some(inner.cache[inner.cache.binary_search_by(|w| w.id.cmp(&id)).ok()?].clone())
}
fn create(&mut self, new: WordData) -> Entity<WordData, WordRepository> {
let mut inner = self.inner.write();
let next_temporal = inner.next_temporal;
inner.next_temporal += 1;
drop(inner);
let entity = Entity {
inner: EntityInner {
id: next_temporal.into(),
real: false,
},
repo: self.clone(),
_phantom: PhantomData,
};
entity
}
fn save(&mut self, entity: EntityInner) -> MaybeError {
todo!()
}
}