leetcode_tui_db/models/
topic.rs1use crate::{errors::DBResult, get_db_client};
2
3use super::{question::DbQuestion, *};
4
5#[native_model(id = 2, version = 1)]
6#[native_db]
7#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
8pub struct DbTopic {
9 #[primary_key]
10 pub slug: String,
11}
12
13impl Hash for DbTopic {
14 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
15 self.slug.hash(state);
16 }
17}
18
19impl DbTopic {
20 pub fn new(slug: &str) -> Self {
21 Self { slug: slug.into() }
22 }
23
24 pub fn fetch_all<'a>() -> DBResult<Vec<DbTopic>> {
25 let r = get_db_client().r_transaction()?;
26 let x = r.scan().primary::<Self>()?.all().into_iter().collect();
27 Ok(x)
28 }
29
30 pub fn fetch_questions<'a>(&self) -> DBResult<Vec<DbQuestion>> {
31 let q_ids = if self.slug.eq("all") {
32 (1..=5000).map(|x| x as u32).collect()
33 } else {
34 TopicQuestionMap::get_all_question_by_topic(self)?
35 };
36 let mut v = vec![];
37 for q_id in q_ids {
38 if let Some(available_ques) = DbQuestion::get_question_by_id(q_id)? {
39 v.push(available_ques);
40 };
41 }
42 Ok(v)
43 }
44
45 pub fn get_topic_by_slug<'a>(slug: &str) -> DBResult<Self> {
46 let r = get_db_client().r_transaction()?;
47
48 Ok(r.get()
49 .primary(slug.to_string())?
50 .ok_or(crate::errors::DbErr::TopicsNotFoundInDb(slug.to_string()))?)
51 }
52}