zed/crates/db/src/db.rs

82 lines
2.3 KiB
Rust
Raw Normal View History

pub mod items;
pub mod kvp;
2022-10-14 01:24:00 +00:00
mod migrations;
pub mod pane;
pub mod workspace;
2022-10-13 23:31:26 +00:00
use std::fs;
2022-11-01 20:15:58 +00:00
use std::ops::Deref;
use std::path::Path;
2022-10-18 18:43:18 +00:00
use anyhow::Result;
2022-11-01 20:15:58 +00:00
use indoc::indoc;
use kvp::KVP_MIGRATION;
use pane::PANE_MIGRATIONS;
2022-11-01 20:15:58 +00:00
use sqlez::connection::Connection;
use sqlez::thread_safe_connection::ThreadSafeConnection;
2022-10-20 23:24:33 +00:00
pub use workspace::*;
#[derive(Clone)]
2022-11-01 20:15:58 +00:00
struct Db(ThreadSafeConnection);
impl Deref for Db {
type Target = sqlez::connection::Connection;
2022-11-01 20:15:58 +00:00
fn deref(&self) -> &Self::Target {
&self.0.deref()
}
}
2022-10-13 22:43:42 +00:00
impl Db {
/// Open or create a database at the given directory path.
2022-10-28 18:50:26 +00:00
pub fn open(db_dir: &Path, channel: &'static str) -> Self {
// Use 0 for now. Will implement incrementing and clearing of old db files soon TM
2022-10-28 18:50:26 +00:00
let current_db_dir = db_dir.join(Path::new(&format!("0-{}", channel)));
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"));
2022-11-01 20:15:58 +00:00
Db(
ThreadSafeConnection::new(db_path.to_string_lossy().as_ref(), true)
.with_initialize_query(indoc! {"
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA foreign_keys=TRUE;
PRAGMA case_sensitive_like=TRUE;
"})
.with_migrations(&[KVP_MIGRATION, WORKSPACES_MIGRATION, PANE_MIGRATIONS]),
2022-11-01 20:15:58 +00:00
)
}
pub fn persisting(&self) -> bool {
2022-11-01 20:15:58 +00:00
self.persistent()
}
2022-10-13 23:31:26 +00:00
/// Open a in memory database for testing and as a fallback.
pub fn open_in_memory() -> Self {
2022-11-01 20:15:58 +00:00
Db(
ThreadSafeConnection::new("Zed DB", false).with_initialize_query(indoc! {"
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA foreign_keys=TRUE;
PRAGMA case_sensitive_like=TRUE;
"}),
)
2022-10-13 22:43:42 +00:00
}
pub fn write_to<P: AsRef<Path>>(&self, dest: P) -> Result<()> {
2022-11-01 20:15:58 +00:00
let destination = Connection::open_file(dest.as_ref().to_string_lossy().as_ref());
self.backup_main(&destination)
2022-10-18 18:43:18 +00:00
}
}
impl Drop for Db {
fn drop(&mut self) {
2022-11-01 20:15:58 +00:00
self.exec(indoc! {"
PRAGMA analysis_limit=500;
PRAGMA optimize"})
.ok();
}
}