diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6ee358d --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,45 @@ +use anyhow::Result; +use chrono::NaiveDate; +use rusqlite::Connection; + +fn get_db() -> Result { + let db = Connection::open("test.db")?; + db.execute( + "CREATE TABLE IF NOT EXISTS birthdays ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + date TEXT NOT NULL + ) STRICT", + (), + )?; + Ok(db) +} + +pub fn add_birthday(name: String, date: String) -> Result<()> { + let db = get_db()?; + let naive_date = NaiveDate::parse_from_str(&date, "%Y-%m-%d")?; + db.execute( + "INSERT INTO birthdays(name, date) VALUES(?1, ?2)", + (name, naive_date), + )?; + Ok(()) +} + +#[derive(Debug)] +pub struct Birthday { + name: String, + date: NaiveDate, +} + +pub fn get_all_birthdays() -> Result> { + let db = get_db()?; + let mut statement = db.prepare("SELECT name, date FROM birthdays")?; + let birthday_iter = statement.query_map([], |row| { + Ok(Birthday { + name: row.get(0)?, + date: row.get(1)?, + }) + })?; + let birthdays: Result, rusqlite::Error> = birthday_iter.collect(); + Ok(birthdays.unwrap()) +} diff --git a/src/main.rs b/src/main.rs index e507af7..c034bf9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +use anyhow::Result; +use birthday::{add_birthday, Birthday}; use clap::{Parser, Subcommand}; #[derive(Parser, Debug)] @@ -29,7 +31,24 @@ enum Command { Today {}, } -fn main() { - let args = Cli::parse(); - println!("You ran cli with: {:?}", args); +fn print_birthdays(birthdays: Vec) { + for birthday in birthdays { + println!("{:?}", birthday); + } +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + println!("You ran cli with: {:?}", cli); + match cli.command { + Command::Add { name, date } => birthday::add_birthday(name, date), + Command::All {} => { + let birthdays = birthday::get_all_birthdays()?; + print_birthdays(birthdays); + Ok(()) + } + Command::Next {} => todo!(), + Command::Search { name, date } => todo!(), + Command::Today {} => todo!(), + } }