stringqb/src/drivers/postgres.rs

59 lines
1.4 KiB
Rust

//! 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<Option<Client>>,
}
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));
}
pub fn query(&self, sql: &str) -> Result<Vec<Row>, Error> {
if self.connection.borrow().is_none() {
panic!("No database connection.");
}
self.connection
.borrow_mut()
.as_mut()
.unwrap()
.query(sql, &[])
}
}
impl DatabaseDriver for PostgresDriver {
fn explain(&self, sql: &str) -> String {
format!("EXPLAIN VERBOSE {}", sql)
}
fn random(&self) -> String {
String::from(" RANDOM()")
}
}