summaryrefslogtreecommitdiffstats
path: root/src/plugins/factoids/database.rs
blob: 386d3f79a2fb72aec9a93e25a93bdf7db8611b8f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#[cfg(feature = "mysql")]
extern crate dotenv;

use std::collections::HashMap;

#[cfg(feature = "mysql")]
use diesel::prelude::*;
#[cfg(feature = "mysql")]
use diesel::mysql::MysqlConnection;
#[cfg(feature = "mysql")]
use r2d2::Pool;
#[cfg(feature = "mysql")]
use r2d2_diesel::ConnectionManager;

use chrono::NaiveDateTime;

pub enum DbResponse {
    Success,
    Failed(&'static str),
}

#[cfg_attr(feature = "mysql", derive(Queryable))]
#[derive(Clone, Debug)]
pub struct Factoid {
    pub name: String,
    pub idx: i32,
    pub content: String,
    pub author: String,
    pub created: NaiveDateTime,
}

#[cfg(feature = "mysql")]
use self::mysql::factoids;
#[cfg_attr(feature = "mysql", derive(Insertable))]
#[cfg_attr(feature = "mysql", table_name = "factoids")]
pub struct NewFactoid<'a> {
    pub name: &'a str,
    pub idx: i32,
    pub content: &'a str,
    pub author: &'a str,
    pub created: NaiveDateTime,
}

pub trait Database: Send {
    fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse;
    fn get_factoid(&self, name: &str, idx: i32) -> Option<Factoid>;
    fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse;
    fn count_factoids(&self, name: &str) -> Result<i32, &'static str>;
}

// HashMap
impl Database for HashMap<(String, i32), Factoid> {
    fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse {
        let factoid = Factoid {
            name: String::from(factoid.name),
            idx: factoid.idx,
            content: factoid.content.to_string(),
            author: factoid.author.to_string(),
            created: factoid.created,
        };

        let name = factoid.name.clone();
        match self.insert((name, factoid.idx), factoid) {
            None => DbResponse::Success,
            Some(_) => DbResponse::Failed("Factoid was overwritten"),
        }
    }

    fn get_factoid(&self, name: &str, idx: i32) -> Option<Factoid> {
        self.get(&(String::from(name), idx)).cloned()
    }

    fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse {
        match self.remove(&(String::from(name), idx)) {
            Some(_) => DbResponse::Success,
            None => DbResponse::Failed("Factoid not found"),
        }
    }

    fn count_factoids(&self, name: &str) -> Result<i32, &'static str> {
        Ok(self.iter().filter(|&(&(ref n, _), _)| n == name).count() as i32)
    }
}

// Diesel automatically define the factoids module as public.
// For now this is how we keep it private.
#[cfg(feature = "mysql")]
mod mysql {
    table! {
        factoids (name, idx) {
            name -> Varchar,
            idx -> Integer,
            content -> Text,
            author -> Varchar,
            created -> Timestamp,
        }
    }
}

#[cfg(feature = "mysql")]
impl Database for Pool<ConnectionManager<MysqlConnection>> {
    fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse {
        use diesel;

        let conn = &*self.get().expect("Failed to get connection");
        match diesel::insert_into(factoids::table)
            .values(factoid)
            .execute(conn)
        {
            Ok(_) => DbResponse::Success,
            Err(e) => {
                error!("DB Insertion Error: {}", e);
                DbResponse::Failed("Failed to add factoid")
            }
        }
    }

    fn get_factoid(&self, name: &str, idx: i32) -> Option<Factoid> {
        let conn = &*self.get().expect("Failed to get connection");
        match factoids::table.find((name, idx)).first(conn) {
            Ok(f) => Some(f),
            Err(e) => {
                error!("DB Count Error: {}", e);
                None
            }
        }
    }

    fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse {
        use diesel;
        use self::factoids::columns;

        let conn = &*self.get().expect("Failed to get connection");
        match diesel::delete(
            factoids::table
                .filter(columns::name.eq(name))
                .filter(columns::idx.eq(idx)),
        ).execute(conn)
        {
            Ok(v) => {
                if v > 0 {
                    DbResponse::Success
                } else {
                    DbResponse::Failed("Could not find any factoid with that name")
                }
            }
            Err(e) => {
                error!("DB Deletion Error: {}", e);
                DbResponse::Failed("Failed to delete factoid")
            }
        }
    }

    fn count_factoids(&self, name: &str) -> Result<i32, &'static str> {
        use diesel;

        let conn = &*self.get().expect("Failed to get connection");
        let count: Result<i64, _> = factoids::table
            .filter(factoids::columns::name.eq(name))
            .count()
            .get_result(conn);

        match count {
            Ok(c) => Ok(c as i32),
            Err(diesel::NotFound) => Ok(0),
            Err(e) => {
                error!("DB Count Error: {}", e);
                Err("Database Error")
            }
        }
    }
}