aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/factoids/database.rs
blob: dbf136c02988dce813af40ffffd094f5c828a8c5 (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
#[cfg(feature = "mysql")]
extern crate dotenv;

use std::collections::HashMap;

#[cfg(feature = "mysql")]
use diesel::prelude::*;

#[cfg(feature = "mysql")]
use diesel::mysql::MysqlConnection;

pub trait Database: Send {
    fn insert(&mut self, name: &str, content: &str) -> Option<()>;
    fn get(&self, name: &str) -> Option<String>;
}

impl Database for HashMap<String, String> {
    fn insert(&mut self, name: &str, content: &str) -> Option<()> {
        self.insert(String::from(name), String::from(content)).map(|_| ())
    }

    fn get(&self, name: &str) -> Option<String> {
        self.get(name).cloned()
    }
}

#[cfg(feature = "mysql")]
#[derive(Queryable)]
struct Factoid {
    pub name: String,
    pub content: String,
}

#[cfg(feature = "mysql")]
table! {
    factoids (name) {
        name -> Varchar,
        content -> Varchar,
    }
}

#[cfg(feature = "mysql")]
#[derive(Insertable)]
#[table_name="factoids"]
struct NewFactoid<'a> {
    pub name: &'a str,
    pub content: &'a str,
}


#[cfg(feature = "mysql")]
impl Database for MysqlConnection {
    fn insert(&mut self, name: &str, content: &str) -> Option<()> {
        let factoid = NewFactoid {
            name: name,
            content: content,
        };

        ::diesel::insert(&factoid)
            .into(factoids::table)
            .execute(self)
            .ok()
            .map(|_| ())
    }

    fn get(&self, name: &str) -> Option<String> {
        factoids::table
            .filter(factoids::columns::name.eq(name))
            .limit(1)
            .load::<Factoid>(self)
            .ok()
            .and_then(|v| v.first().map(|f| f.content.clone()))
    }
}