-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: Move storage in its own module + rework public API
- Loading branch information
1 parent
b8940cf
commit cb17018
Showing
3 changed files
with
69 additions
and
56 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
use anyhow::Result; | ||
use chrono::{NaiveDate, NaiveDateTime}; | ||
use rusqlite::Connection; | ||
|
||
use crate::Birthday; | ||
|
||
pub fn add(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() -> Result<Vec<Birthday>> { | ||
let db = get_db()?; | ||
let mut statement = db.prepare("SELECT id, name, date_timestamp FROM birthdays")?; | ||
let birthday_iter = statement.query_map([], |row| { | ||
let id = row.get(0)?; | ||
let name = row.get(1)?; | ||
let timestamp = row.get(2)?; | ||
let date = from_timestamp(timestamp); | ||
Ok(Birthday { id, name, date }) | ||
})?; | ||
let birthdays: Result<Vec<Birthday>, rusqlite::Error> = birthday_iter.collect(); | ||
Ok(birthdays.unwrap()) | ||
} | ||
|
||
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_timestamp INTEGER NOT NULL | ||
) STRICT", | ||
(), | ||
)?; | ||
Ok(db) | ||
} | ||
|
||
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() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters