Skip to content

Commit

Permalink
feat: Store DB in OS data directory
Browse files Browse the repository at this point in the history
  • Loading branch information
ducdetronquito committed Jan 14, 2024
1 parent 995f208 commit 7acfe29
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 4 deletions.
117 changes: 114 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ name = "birthday"
anyhow = "1.0.76"
chrono = "0.4"
clap = { version = "4.4", features = ["derive"] }
directories = "5.0.1"
rusqlite = { version = "0.30", features = ["bundled", "chrono"] }
tabled = "0.15"
16 changes: 15 additions & 1 deletion src/birthday_store.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use std::path::{Path, PathBuf};

use anyhow::Result;
use chrono::{NaiveDate, NaiveDateTime};
use directories::ProjectDirs;
use rusqlite::Connection;

use crate::Birthday;
Expand All @@ -15,6 +18,16 @@ pub fn add(name: String, date: String) -> Result<()> {
Ok(())
}

fn get_db_path() -> Result<PathBuf> {
let mut data_dir = match ProjectDirs::from("", "", "birthday") {
Some(project_dirs) => project_dirs.data_dir().to_owned(),
None => Path::new("./").to_owned(),
};
std::fs::create_dir_all(&data_dir)?;
data_dir.push("test.db");
Ok(data_dir)
}

pub fn get_all() -> Result<Vec<Birthday>> {
let db = get_db()?;
let mut statement = db.prepare("SELECT id, name, date_timestamp FROM birthdays")?;
Expand Down Expand Up @@ -49,7 +62,8 @@ pub fn remove(id: i32) -> Result<Option<Birthday>> {
}

fn get_db() -> Result<Connection> {
let db = Connection::open("test.db")?;
let db_path = get_db_path()?;
let db = Connection::open(db_path)?;
db.execute(
"CREATE TABLE IF NOT EXISTS birthdays (
id INTEGER PRIMARY KEY,
Expand Down

0 comments on commit 7acfe29

Please sign in to comment.