zed/crates/db/src/db.rs

47 lines
1.5 KiB
Rust
Raw Normal View History

pub mod kvp;
2022-10-13 23:31:26 +00:00
use std::fs;
2022-11-01 20:15:58 +00:00
use std::path::Path;
2022-10-18 18:43:18 +00:00
#[cfg(any(test, feature = "test-support"))]
use anyhow::Result;
2022-11-01 20:15:58 +00:00
use indoc::indoc;
#[cfg(any(test, feature = "test-support"))]
2022-11-01 20:15:58 +00:00
use sqlez::connection::Connection;
use sqlez::domain::Domain;
2022-11-01 20:15:58 +00:00
use sqlez::thread_safe_connection::ThreadSafeConnection;
const INITIALIZE_QUERY: &'static str = indoc! {"
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA foreign_keys=TRUE;
PRAGMA case_sensitive_like=TRUE;
"};
/// Open or create a database at the given directory path.
pub fn open_file_db<D: Domain>() -> ThreadSafeConnection<D> {
// Use 0 for now. Will implement incrementing and clearing of old db files soon TM
let current_db_dir = (*util::paths::DB_DIR).join(Path::new(&format!(
"0-{}",
*util::channel::RELEASE_CHANNEL_NAME
)));
fs::create_dir_all(&current_db_dir).expect("Should be able to create the database directory");
let db_path = current_db_dir.join(Path::new("db.sqlite"));
ThreadSafeConnection::new(db_path.to_string_lossy().as_ref(), true)
.with_initialize_query(INITIALIZE_QUERY)
}
2022-10-13 22:43:42 +00:00
pub fn open_memory_db<D: Domain>(db_name: &str) -> ThreadSafeConnection<D> {
ThreadSafeConnection::new(db_name, false).with_initialize_query(INITIALIZE_QUERY)
}
#[cfg(any(test, feature = "test-support"))]
pub fn write_db_to<D: Domain, P: AsRef<Path>>(
conn: &ThreadSafeConnection<D>,
dest: P,
) -> Result<()> {
let destination = Connection::open_file(dest.as_ref().to_string_lossy().as_ref());
conn.backup_main(&destination)
}