use libsqlite3_sys::{self as ffi};
use std::ffi::CStr;
use super::{
Database, DatabaseExt, OpenFlag, Statement, StatementExt,
error::{OpenError, PrepareError},
};
use crate::SqliteStr;
#[derive(Debug)]
pub struct SqliteHandle {
sqlite: *mut ffi::sqlite3,
}
impl SqliteHandle {
pub fn open_v2(path: &CStr, flags: OpenFlag) -> Result<Self, OpenError> {
Ok(Self {
sqlite: super::database::open_v2(path, flags)?,
})
}
}
impl Database for SqliteHandle {
fn as_ptr(&self) -> *mut libsqlite3_sys::sqlite3 {
self.sqlite
}
}
impl Drop for SqliteHandle {
fn drop(&mut self) {
if let Err(_err) = self.close() {
#[cfg(feature = "log")]
log::error!("Failed to close db on drop: {_err}")
}
}
}
#[derive(Debug)]
pub struct StatementHandle {
stmt: *mut ffi::sqlite3_stmt,
}
impl StatementHandle {
pub fn prepare_v2<DB: Database, S: SqliteStr>(db: DB, sql: S) -> Result<Self, PrepareError> {
Ok(Self {
stmt: super::statement::prepare_v2(db.as_ptr(), sql)?,
})
}
}
impl Statement for StatementHandle {
fn as_stmt_ptr(&self) -> *mut libsqlite3_sys::sqlite3_stmt {
self.stmt
}
}
impl Drop for StatementHandle {
fn drop(&mut self) {
if let Err(_err) = self.finalize() {
#[cfg(feature = "log")]
log::error!("Failed to finalize prepare statement on drop: {_err}")
}
}
}
#[derive(Debug)]
pub struct SqliteMutexGuard {
lock: *mut ffi::sqlite3_mutex,
}
impl SqliteMutexGuard {
pub(crate) fn new(lock: *mut ffi::sqlite3_mutex) -> Self {
Self { lock }
}
}
impl Drop for SqliteMutexGuard {
fn drop(&mut self) {
unsafe { ffi::sqlite3_mutex_leave(self.lock) }
}
}