stringqb/src/drivers/postgres.rs

65 lines
1.5 KiB
Rust
Raw Normal View History

2019-04-09 18:55:53 -04:00
//! Database Driver for Postgres
//!
2019-04-22 08:59:40 -04:00
//! 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
2019-04-02 16:35:52 -04:00
use super::*;
2019-04-22 08:59:40 -04:00
use pg::{Client, Error, NoTls, Row};
use std::any::Any;
use std::cell::RefCell;
2019-04-09 18:55:53 -04:00
/// The struct implementing the `DatabaseDriver` trait
2019-04-22 08:59:40 -04:00
pub struct PostgresDriver {
connection: RefCell<Option<Client>>,
}
2019-04-02 16:35:52 -04:00
2019-04-12 17:09:59 -04:00
impl PostgresDriver {
/// Create a PostgresDriver driver
2019-04-22 08:59:40 -04:00
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));
}
2019-04-04 16:39:05 -04:00
}
2019-04-09 14:13:37 -04:00
2019-04-12 17:09:59 -04:00
impl DatabaseDriver for PostgresDriver {
fn explain(&self, sql: &str) -> String {
2019-04-17 09:09:31 -04:00
format!("EXPLAIN VERBOSE {}", sql)
2019-04-12 17:09:59 -04:00
}
fn random(&self) -> String {
String::from(" RANDOM()")
}
2019-07-19 12:45:18 -04:00
fn query(&self, sql: &str) -> Result<Box<dyn Any>, Box<dyn Any>> {
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)),
}
}
2019-04-25 13:09:18 -04:00
}