1use crate::schema::*;
2use chrono::NaiveDate;
3use diesel::pg::upsert::on_constraint;
4use diesel::prelude::*;
5use diesel::PgConnection;
6use std::collections::HashMap;
7use termion::color;
8
9#[derive(Queryable)]
10pub struct Snapshot {
11 pub id: i32,
12 pub account_id: String,
13 pub date: NaiveDate,
14 pub amount: i32,
15}
16
17#[derive(Insertable)]
18#[table_name = "snapshots"]
19pub struct NewSnapshot {
20 pub account_id: String,
21 pub date: NaiveDate,
22 pub amount: i32,
23}
24
25impl Snapshot {
26 pub fn create_new_snapshot(
27 conn: &PgConnection,
28 account_id: String,
29 ymd_string: String,
30 amount: i32,
31 ) {
32 println!("Creating new snapshot...");
33 let new_snapshot = NewSnapshot {
34 account_id,
35 amount,
36 date: ymd_string
37 .parse::<NaiveDate>()
38 .expect("Error: Failed to parse date string"),
39 };
40 let result = diesel::insert_into(snapshots::table)
41 .values(&new_snapshot)
42 .on_conflict(on_constraint("snapshot_unique"))
43 .do_nothing()
44 .get_result::<Snapshot>(conn);
45
46 match result {
47 Ok(new_snapshot) => println!(
48 "{}Added new snapshot: for {}{}",
49 color::Fg(color::Cyan),
50 new_snapshot.date,
51 color::Fg(color::Reset),
52 ),
53 Err(err) => println!(
54 "Skipping inserting snapshot with id '{}', date '{}'.\nMaybe already there? Error: {}",
55 new_snapshot.account_id,
56 new_snapshot.date,
57 err
58 )
59 }
60 }
61
62 pub fn update_snapshots(
63 conn: &PgConnection,
64 account_id: String,
65 amounts_by_date: HashMap<String, i32>,
66 ) {
67 println!(
68 "Updating snapshots for {} with notion's table data...",
69 &account_id
70 );
71 for (date, amount) in amounts_by_date {
72 Snapshot::create_new_snapshot(conn, account_id.to_owned(), date, amount)
73 }
74 }
75
76 pub fn display_snapshots(conn: &PgConnection) {
77 let all_snapshots = snapshots::table
78 .load::<Snapshot>(conn)
79 .expect("Error getting snapshots");
80 println!("\n *Displaying all snapshots");
81 println!("---");
82 for snapshot in all_snapshots {
83 println!("Id: {}", snapshot.id);
84 println!("Account: {}", snapshot.account_id);
85 println!("Date: {}", snapshot.date);
86 println!("Amount: {}", snapshot.amount);
87 println!("---");
88 }
89 }
90
91 pub fn delete_snapshots(conn: &PgConnection) {
92 use diesel::delete;
93 delete(snapshots::table)
94 .execute(conn)
95 .expect("Error deleting snapshots table");
96 }
97}