Skip to content

Commit

Permalink
refactor: Store birth date as UNIX timestamp to ease comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
ducdetronquito committed Dec 24, 2023
1 parent d7089d3 commit d48e2d0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 18 deletions.
45 changes: 28 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::Result;
use chrono::NaiveDate;
use chrono::{NaiveDate, NaiveDateTime};
use rusqlite::Connection;

fn get_db() -> Result<Connection> {
Expand All @@ -8,23 +8,13 @@ fn get_db() -> Result<Connection> {
"CREATE TABLE IF NOT EXISTS birthdays (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
date TEXT NOT NULL
date_timestamp INTEGER 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(())
}

pub struct Birthday {
pub name: String,
pub date: NaiveDate,
Expand All @@ -36,14 +26,35 @@ impl Birthday {
}
}

fn to_timestamp(date: NaiveDate) -> i64 {
date.and_hms_opt(0, 0, 0).unwrap().timestamp()
}

fn from_timestamp(timestamp: i64) -> NaiveDate {
NaiveDateTime::from_timestamp_opt(timestamp, 0)
.unwrap()
.date()
}

pub fn add_birthday(name: String, date: String) -> Result<()> {
let db = get_db()?;
let date = NaiveDate::parse_from_str(&date, "%Y-%m-%d")?;
let timestamp = to_timestamp(date);
db.execute(
"INSERT INTO birthdays(name, date_timestamp) VALUES(?1, ?2)",
(name, timestamp),
)?;
Ok(())
}

pub fn get_all_birthdays() -> Result<Vec<Birthday>> {
let db = get_db()?;
let mut statement = db.prepare("SELECT name, date FROM birthdays")?;
let mut statement = db.prepare("SELECT name, date_timestamp FROM birthdays")?;
let birthday_iter = statement.query_map([], |row| {
Ok(Birthday {
name: row.get(0)?,
date: row.get(1)?,
})
let name = row.get(0)?;
let timestamp = row.get(1)?;
let date = from_timestamp(timestamp);
Ok(Birthday { name, date })
})?;
let birthdays: Result<Vec<Birthday>, rusqlite::Error> = birthday_iter.collect();
Ok(birthdays.unwrap())
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn main() -> Result<()> {
Ok(())
}
Command::Next {} => todo!(),
Command::Search { name, date } => todo!(),
Command::Search { .. } => todo!(),
Command::Today {} => todo!(),
}
}
Expand Down

0 comments on commit d48e2d0

Please sign in to comment.