stringqb/src/drivers/sqlite.rs

63 lines
1.4 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};
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));
}
pub fn query(&self, sql: &str) -> Result<usize> {
if self.connection.borrow().is_none() {
panic!("No database connection.");
}
self.connection
.borrow_mut()
.as_mut()
.unwrap()
.execute(sql, NO_PARAMS)
}
}
impl DatabaseDriver for SQLiteDriver {
fn explain(&self, sql: &str) -> String {
format!("EXPLAIN QUERY PLAN {}", sql)
}
fn random(&self) -> String {
String::from(" RANDOM()")
}
}