aboutsummaryrefslogtreecommitdiff
path: root/src/database.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/database.rs')
-rw-r--r--src/database.rs68
1 files changed, 68 insertions, 0 deletions
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<String>,
+}
+
+impl Database {
+ pub fn new(person: String, amount: i32, note: Option<String>, 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(())
+ }
+}
Feel free to download, copy and edit any repo