diff options
| author | Jokler <jokler.contact@gmail.com> | 2017-11-04 22:46:39 +0100 |
|---|---|---|
| committer | Jokler <jokler.contact@gmail.com> | 2017-12-24 00:40:06 +0100 |
| commit | 5928afc3bf83661cd3b11130a31a2d97ef135a9e (patch) | |
| tree | 4d1ad028c3a7130eb98c18ef5b97bea9f52f2e2f /src/plugins/factoids/database.rs | |
| parent | f3d679da59a64711ef96042668b26dffd1e662d5 (diff) | |
| download | frippy-5928afc3bf83661cd3b11130a31a2d97ef135a9e.tar.gz frippy-5928afc3bf83661cd3b11130a31a2d97ef135a9e.zip | |
Add MySql as a possible database for the Factoids plugin
Diffstat (limited to 'src/plugins/factoids/database.rs')
| -rw-r--r-- | src/plugins/factoids/database.rs | 72 |
1 files changed, 64 insertions, 8 deletions
diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index 7a6f568..dbf136c 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -1,18 +1,74 @@ -use std::fmt; +#[cfg(feature = "mysql")] +extern crate dotenv; use std::collections::HashMap; -pub trait Database: Send + Sync + fmt::Debug { - fn insert(&mut self, name: String, content: String) -> Option<String>; - fn get(&self, name: &str) -> Option<&str>; +#[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: String, content: String) -> Option<String> { - self.insert(name, content) + 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<&str> { - self.get(name).map(String::as_str) + 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())) } } |
