//! Database Driver for Postgres //! //! Use of this driver requires enabling the `postgres` feature. The `postgres` //! feature is enabled by default. //! //! Uses the [Postgres](https://crates.io/crates/postgres) crate for //! interfacing with the database use super::*; use pg::{Client, Error, NoTls, Row}; use std::any::Any; use std::cell::RefCell; /// The struct implementing the `DatabaseDriver` trait pub struct PostgresDriver { connection: RefCell>, } impl PostgresDriver { /// Create a PostgresDriver driver pub fn new(dsn: &str) -> Self { let mut driver = PostgresDriver { connection: RefCell::new(None), }; driver.connect(dsn); driver } fn connect(&mut self, dsn: &str) { let connection = Client::connect(dsn, NoTls).unwrap(); self.connection = RefCell::new(Some(connection)); } } impl DatabaseDriver for PostgresDriver { fn explain(&self, sql: &str) -> String { format!("EXPLAIN VERBOSE {}", sql) } fn random(&self) -> String { String::from(" RANDOM()") } fn query(&self, sql: &str) -> Result, Box> { if self.connection.borrow().is_none() { panic!("No database connection."); } let result = self .connection .borrow_mut() .as_mut() .unwrap() .query(sql, &[]); match result { Ok(res) => Ok(Box::new(res)), Err(e) => Err(Box::new(e)), } } }