From a5dfd2627853bd67e9d17ef870fc84be312b1397 Mon Sep 17 00:00:00 2001 From: jvech Date: Tue, 23 Apr 2024 07:52:28 -0500 Subject: add: first commit done --- src/database.rs | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/database.rs (limited to 'src/database.rs') diff --git a/src/database.rs b/src/database.rs new file mode 100644 index 0000000..6a7bde0 --- /dev/null +++ b/src/database.rs @@ -0,0 +1,68 @@ +use rusqlite::Connection; +use rusqlite::Result; +use chrono::Utc; +use std::path::PathBuf; + +pub struct Database { + date: i64, + person: String, + amount: i32, + note: Option, +} + +impl Database { + pub fn new(person: String, amount: i32, note: Option, is_debt: bool) -> Database { + Database { + date: Utc::now().timestamp(), + amount: if !is_debt {amount} else {-amount}, + person, + note, + } + } + + pub fn add_register(&self, filepath: &PathBuf) -> Result<()> { + let conn = Connection::open(filepath)?; + conn.execute("PRAGMA foreign_key=1", ())?; + conn.execute(" + INSERT INTO Registers (agent_id, register_date, amount, note) + VALUES ( + (SELECT id FROM Agents WHERE name=?1), + ?2, ?3, ?4)", + (&self.person, + &self.date, + self.amount, + &self.note))?; + println!("Register added successfully"); + Ok(()) + } + + pub fn add_agent(&self, filepath: &PathBuf) -> Result<()> { + let conn = Connection::open(filepath)?; + conn.execute(" + INSERT INTO Agents (name) + VALUES (?1)", (&self.person,))?; + println!("agent '{}' successfully", &self.person); + Ok(()) + } + + pub fn init_database(filepath: &PathBuf) -> Result<()> { + let conn = Connection::open(filepath).expect("Database file creation Error"); + conn.execute(" + CREATE TABLE Agents ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE)", ()) + .expect("SQL initialization error"); + + conn.execute(" + CREATE TABLE Registers ( + id INTEGER PRIMARY KEY, + agent_id INTEGER, + register_date INTEGER NOT NULL, + amount INTEGER NOT NULL, + note TEXT, + FOREIGN KEY(agent_id) REFERENCES Agents(id))", ()) + .expect("SQL initialization error"); + println!("'{}' database created", &filepath.display()); + Ok(()) + } +} -- cgit v1.2.3-70-g09d2