stringqb/src/drivers/sqlite.rs

72 lines
1.7 KiB
Rust

//! Database Driver for SQLite
//!
//! Use of this driver requires enabling the `sqlite` feature.
//!
//! Uses the [rusqlite](https://crates.io/crates/rusqlite) crate for
//! interfacing with the database
use super::*;
use slite::NO_PARAMS;
use slite::{params, Connection, Result as SResult};
use std::cell::RefCell;
/// The struct implementing the `DatabaseDriver` trait
#[derive(Debug)]
pub struct SQLiteDriver {
connection: RefCell<Option<Connection>>,
}
impl SQLiteDriver {
/// Create an SQLiteDriver driver
pub fn new(dsn: &str) -> Self {
let mut driver = SQLiteDriver {
connection: RefCell::new(None),
};
driver.connect(dsn);
driver
}
fn connect(&mut self, dsn: &str) {
let connection = if dsn == ":memory:" {
Connection::open_in_memory().unwrap()
} else {
Connection::open(dsn).unwrap()
};
self.connection = RefCell::new(Some(connection));
}
}
impl DatabaseDriver for SQLiteDriver {
fn query(&self, sql: &str) -> Result<Box<dyn Any>, Box<dyn Any>> {
if self.connection.borrow().is_none() {
panic!("No database connection.");
}
self.connection
.borrow_mut()
.as_mut()
.unwrap()
.execute(sql, NO_PARAMS);
// TODO: map native result to generic result
unimplemented!();
}
/// Return the sql to empty a table
fn truncate(&self, table: &str) -> String {
String::from("DELETE FROM ")
+ &self.quote_identifier(table)
}
fn explain(&self, sql: &str) -> String {
format!("EXPLAIN QUERY PLAN {}", sql)
}
fn random(&self) -> String {
String::from(" RANDOM()")
}
}