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
pub extern crate mongodb; pub extern crate r2d2; use r2d2::ManageConnection; use mongodb::{ThreadedClient, Client, Error}; use mongodb::db::{ThreadedDatabase, Database}; #[derive(Clone)] pub struct ConnectionOptions { host: String, port: u16, db: String, username: Option<String>, password: Option<String>, } impl Default for ConnectionOptions { fn default() -> ConnectionOptions { ConnectionOptions { host: "localhost".to_string(), port: 27017, db: "admin".to_string(), username: None, password: None, } } } pub struct MongodbConnectionManagerBuilder { options: ConnectionOptions, } impl MongodbConnectionManagerBuilder { pub fn new() -> MongodbConnectionManagerBuilder { MongodbConnectionManagerBuilder{ options: ConnectionOptions::default() } } pub fn with_host<'a>(&'a mut self, host: &str) -> &'a mut MongodbConnectionManagerBuilder { self.options.host = host.to_string(); self } pub fn with_port<'a>(&'a mut self, port: u16) -> &'a mut MongodbConnectionManagerBuilder { self.options.port = port; self } pub fn with_db<'a>(&'a mut self, db: &str) -> &'a mut MongodbConnectionManagerBuilder { self.options.db = db.to_string(); self } pub fn with_username<'a>(&'a mut self, username: &str) -> &'a mut MongodbConnectionManagerBuilder { self.options.username = Some(username.to_string()); self } pub fn with_password<'a>(&'a mut self, password: &str) -> &'a mut MongodbConnectionManagerBuilder { self.options.password = Some(password.to_string()); self } pub fn build(&mut self) -> MongodbConnectionManager { MongodbConnectionManager{ options: self.options.clone() } } } pub struct MongodbConnectionManager { options: ConnectionOptions, } impl ManageConnection for MongodbConnectionManager { type Connection = Database; type Error = Error; fn connect(&self) -> Result<Database, Error> { let client = Client::connect(&self.options.host, self.options.port)?; let db = client.db(&self.options.db); if let (&Some(ref username), &Some(ref password)) = (&self.options.username, &self.options.password) { db.auth(&username, &password)?; } Ok(db) } fn is_valid(&self, db: &mut Database) -> Result<(), Error> { db.version().map(|_| ()) } fn has_broken(&self, _db: &mut Database) -> bool { false } }