leetcode_tui_db/
models.rs1use native_db::*;
2use native_model::{native_model, Model};
3use serde::{Deserialize, Serialize};
4use std::hash::Hash;
5
6use crate::{errors::DBResult, get_db_client, save};
7
8use self::topic::DbTopic;
9pub mod question;
10pub mod topic;
11
12#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
13#[native_model(id = 3, version = 1)]
14#[native_db]
15pub(crate) struct TopicQuestionMap {
16 #[primary_key]
17 id: String,
18 #[secondary_key]
19 topic_id: String,
20 question_id: u32,
21}
22
23impl TopicQuestionMap {
24 fn new(topic_id: &str, question_id: u32) -> Self {
25 Self {
26 id: format!("{topic_id}_{question_id}"),
27 topic_id: topic_id.to_string(),
28 question_id,
29 }
30 }
31
32 pub(crate) fn save_mapping<'a>(question: &question::DbQuestion) -> DBResult<()> {
33 for topic in question.get_topics() {
34 let topic_question_mapping = Self::new(&topic.slug, question.id);
35 topic_question_mapping.save_to_db()?;
36 }
37 Ok(())
38 }
39
40 fn save_to_db<'a>(&self) -> DBResult<()> {
41 save(self)?;
42 Ok(())
43 }
44
45 pub(crate) fn get_all_question_by_topic(topic: &DbTopic) -> DBResult<Vec<u32>> {
46 let trans = get_db_client().r_transaction()?;
47 let mut quests = vec![];
48 for tq_map in trans
49 .scan()
50 .secondary::<Self>(TopicQuestionMapKey::topic_id)?
51 .start_with(topic.slug.to_string())
52 {
53 quests.push(tq_map.question_id);
54 }
55 Ok(quests)
56 }
57}
58
59#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
60#[native_model(id = 4, version = 1)]
61#[native_db]
62pub(crate) struct QuestionTopicMap {
63 #[primary_key]
64 id: String,
65 #[secondary_key]
66 question_id: u32,
67 topic_id: String,
68}
69
70impl QuestionTopicMap {
71 fn new(question_id: u32, topic_id: &str) -> Self {
72 Self {
73 id: format!("{question_id}_{topic_id}"),
74 question_id,
75 topic_id: topic_id.to_string(),
76 }
77 }
78
79 pub(crate) fn save_mapping<'a>(question: &question::DbQuestion) -> DBResult<()> {
80 for topic in question.get_topics() {
81 let question_topic_mapping = Self::new(question.id, &topic.slug);
82 question_topic_mapping.save_to_db()?;
83 }
84 Ok(())
85 }
86
87 fn save_to_db<'a>(&self) -> DBResult<()> {
88 save(self)?;
89 Ok(())
90 }
91}