Skip to content

Commit

Permalink
feat: Can add a birthday and show all birthdays
Browse files Browse the repository at this point in the history
  • Loading branch information
ducdetronquito committed Dec 23, 2023
1 parent b134ff5 commit 7dc3959
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 3 deletions.
45 changes: 45 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use anyhow::Result;
use chrono::NaiveDate;
use rusqlite::Connection;

fn get_db() -> Result<Connection> {
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<Vec<Birthday>> {
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<Vec<Birthday>, rusqlite::Error> = birthday_iter.collect();
Ok(birthdays.unwrap())
}
25 changes: 22 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use anyhow::Result;
use birthday::{add_birthday, Birthday};
use clap::{Parser, Subcommand};

#[derive(Parser, Debug)]
Expand Down Expand Up @@ -29,7 +31,24 @@ enum Command {
Today {},
}

fn main() {
let args = Cli::parse();
println!("You ran cli with: {:?}", args);
fn print_birthdays(birthdays: Vec<Birthday>) {
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!(),
}
}

0 comments on commit 7dc3959

Please sign in to comment.