#![forbid(missing_docs)]
use std::{ffi::CString, os::unix::prelude::OsStrExt, path::Path, ptr};
use crate::{
bindings::{sqlite3_close, sqlite3_open},
ehandle::MinSqliteWrapperError,
prelude::*,
};
unsafe impl Send for Database {}
unsafe impl Sync for Database {}
pub struct Database {
pub(crate) rp: *mut crate::bindings::sqlite3,
}
pub trait Connection<'a> {
fn open<T>(path: T) -> Result<Self, MinSqliteWrapperError<'a>>
where
Self: Sized,
T: AsRef<Path>;
fn close(self) -> SqlitePrimaryResult;
}
impl<'a> Connection<'a> for Database {
fn open<T>(db_path: T) -> Result<Self, MinSqliteWrapperError<'a>>
where
Self: Sized,
T: AsRef<Path>,
{
let mut rp = ptr::null_mut();
let path = CString::new(db_path.as_ref().as_os_str().as_bytes())?;
unsafe {
sqlite3_open(path.as_ptr(), &mut rp);
}
Ok(Database { rp })
}
fn close(self) -> SqlitePrimaryResult {
sqlite_close(self.rp)
}
}
impl Drop for Database {
fn drop(&mut self) {
sqlite_close(self.rp);
}
}
#[inline]
fn sqlite_close(rp: *mut crate::bindings::sqlite3) -> SqlitePrimaryResult {
unsafe { SqlitePrimaryResult::from(sqlite3_close(rp)) }
}