use super::tables::{Tables, TABLES_COUNT};
use heed::{Env, EnvOpenOptions};
use std::fs;
use std::path::Path;
use std::sync::Arc;
use super::migrations;
pub const DEFAULT_MAP_SIZE: usize = 10995116277760;
#[derive(Debug, Clone)]
pub struct LmDB {
pub(crate) env: Env,
pub(crate) tables: Tables,
pub(crate) max_chunk_size: usize,
#[allow(dead_code)]
test_dir: Option<Arc<tempfile::TempDir>>,
}
impl LmDB {
pub unsafe fn open(main_dir: &Path) -> anyhow::Result<Self> {
fs::create_dir_all(main_dir)?;
let env = unsafe {
EnvOpenOptions::new()
.max_dbs(TABLES_COUNT)
.map_size(DEFAULT_MAP_SIZE)
.open(main_dir)
}?;
migrations::run(&env)?;
let mut wtxn = env.write_txn()?;
let tables = Tables::new(&env, &mut wtxn)?;
wtxn.commit()?;
let db = LmDB {
env,
tables,
max_chunk_size: Self::max_chunk_size(),
test_dir: None,
};
Ok(db)
}
#[cfg(test)]
pub fn test() -> LmDB {
let temp_dir = tempfile::tempdir().unwrap();
let mut lmdb = unsafe { LmDB::open(temp_dir.path()).unwrap() };
lmdb.test_dir = Some(Arc::new(temp_dir));
lmdb
}
fn max_chunk_size() -> usize {
let page_size = page_size::get();
((page_size - 16) / 2) - (8 + 2) - 12
}
}