Open and close sqlite db properly

This commit is contained in:
Joscha 2022-06-15 21:52:05 +02:00
parent e65bf49a6e
commit 9d1810eceb
4 changed files with 165 additions and 0 deletions

View file

@ -3,14 +3,22 @@
mod chat;
mod store;
mod ui;
mod vault;
use directories::ProjectDirs;
use toss::terminal::Terminal;
use ui::Ui;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let dirs = ProjectDirs::from("de", "plugh", "cove").expect("unable to determine directories");
println!("Data dir: {}", dirs.data_dir().to_string_lossy());
let vault = vault::launch(&dirs.data_dir().join("vault.db"))?;
let mut terminal = Terminal::new()?;
// terminal.set_measuring(true);
Ui::run(&mut terminal).await?;
vault.close().await;
Ok(())
}

44
cove-tui/src/vault.rs Normal file
View file

@ -0,0 +1,44 @@
use std::path::Path;
use std::{fs, thread};
use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
enum Request {
Close(oneshot::Sender<()>),
Nop,
}
pub struct Vault {
tx: mpsc::Sender<Request>,
}
impl Vault {
pub async fn close(&self) {
let (tx, rx) = oneshot::channel();
let _ = self.tx.send(Request::Close(tx)).await;
let _ = rx.await;
}
}
fn run(conn: Connection, mut rx: mpsc::Receiver<Request>) -> anyhow::Result<()> {
while let Some(request) = rx.blocking_recv() {
match request {
// Drops the Sender resulting in `Vault::close` exiting
Request::Close(_) => break,
Request::Nop => {}
}
}
Ok(())
}
pub fn launch(path: &Path) -> rusqlite::Result<Vault> {
// If this fails, rusqlite will complain about not being able to open the db
// file, which saves me from adding a separate vault error type.
let _ = fs::create_dir_all(path.parent().expect("path to file"));
let conn = Connection::open(path)?;
let (tx, rx) = mpsc::channel(8);
thread::spawn(move || run(conn, rx));
Ok(Vault { tx })
}