use std::path::Path;
use serde::Serialize;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::errors::Error;
use crate::{Config, Transaction};
use super::db_inner::DatabaseInner;
use crate::coll::Collection;
use crate::metrics::Metrics;
pub(crate) static SHOULD_LOG: AtomicBool = AtomicBool::new(false);
#[derive(Clone)]
pub struct Database {
inner: Arc<DatabaseInner>,
}
pub type Result<T> = std::result::Result<T, Error>;
impl Database {
pub fn set_log(v: bool) {
SHOULD_LOG.store(v, Ordering::SeqCst);
}
pub fn get_version() -> &'static str {
const VERSION: &str = env!("CARGO_PKG_VERSION");
VERSION
}
#[deprecated]
pub fn open_file<P: AsRef<Path>>(path: P) -> Result<Database> {
Database::open_path(path)
}
#[deprecated]
pub fn open_file_with_config<P: AsRef<Path>>(path: P, config: Config) -> Result<Database> {
Database::open_path_with_config(path, config)
}
pub fn open_path<P: AsRef<Path>>(path: P) -> Result<Database> {
Database::open_path_with_config(path, Config::default())
}
pub fn open_path_with_config<P: AsRef<Path>>(path: P, config: Config) -> Result<Database> {
let inner = DatabaseInner::open_file(path.as_ref(), config)?;
Ok(Database {
inner: Arc::new(inner),
})
}
pub fn metrics(&self) -> Metrics {
self.inner.metrics()
}
pub fn create_collection(&self, name: &str) -> Result<()> {
let _ = self.inner.create_collection(name)?;
Ok(())
}
pub fn collection<T: Serialize>(&self, col_name: &str) -> Collection<T> {
Collection::new(Arc::downgrade(&self.inner), col_name)
}
pub fn start_transaction(&self) -> Result<Transaction> {
let mut inner = self.inner.start_transaction()?;
inner.set_auto_commit(false);
Ok(Transaction::new(Arc::downgrade(&self.inner), inner))
}
pub fn list_collection_names(&self) -> Result<Vec<String>> {
let txn = self.inner.start_transaction()?;
self.inner.list_collection_names_with_session(&txn)
}
}