Skip to content

Commit

Permalink
Added DB handler
Browse files Browse the repository at this point in the history
  • Loading branch information
okynos committed Dec 16, 2024
1 parent a3b9f4a commit 749cde5
Show file tree
Hide file tree
Showing 3 changed files with 160 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ serde_json = { version = "1.0.79", default-features = false }
time = { version = "0.3.17", default-features = false }
ctrlc = { version = "3.3.1", default-features = false, features = ["termination"] }
log-panics = { version = "2.1.0", features = ["with-backtrace"]}
rusqlite = { version = "0.32.1", features = ["bundled"]}

[dependencies.regex]
version = "1.3"
Expand Down
146 changes: 146 additions & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
use rusqlite::Connection;
use std::path::Path;
use crate::appconfig;
use crate::utils;
use log::*;
use std::fmt;

pub const DBNAME: &str = "fim.db";

pub struct DBFile {
pub id: u64,
pub timestamp: String,
pub hash: String,
pub path: String,
pub size: u32
}

pub struct DB {
path: String
}

impl DB {
pub fn new() -> DB {
let mut config_folder = Path::new(&appconfig::get_config_path(utils::get_os()))
.parent().unwrap().to_path_buf();
config_folder.push(DBNAME);

DB {
path: String::from(config_folder.to_str().unwrap()),
}
}

// ------------------------------------------------------------------------

pub fn open(&self) -> Connection {
match Connection::open(self.path.clone()) {
Ok(database) => {
debug!("Database connection opened ready to read/write");
database
}
Err(e) => {
error!("Database cannot be opened, Err: [{}]", e);
info!("Please, check if {} is locked or in use.", DBNAME);
panic!();
}
}
}

// ------------------------------------------------------------------------

pub fn close(&self, connection: Connection) {
match connection.close(){
Ok(_) => debug!("DB connection closed successfully"),
Err(e) => warn!("DB connection could not be closed, error: {:?}", e)
};
}

// ------------------------------------------------------------------------

pub fn create_table(&self) {
let connection = self.open();
let result = connection.execute(
"CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY,
timestamp TEXT NOT NULL,
hash TEXT NOT NULL,
path TEXT NOT NULL UNIQUE,
size INTEGER)",
(),
);
match result {
Ok(_v) => println!("GOOD"),
Err(e) => println!("ERROR: {:?}", e)
}
self.close(connection);
}

// ------------------------------------------------------------------------

pub fn insert_file(&self, file: DBFile) {
let connection = self.open();
let result = connection.execute(
"INSERT INTO files (timestamp, hash, path, size) VALUES (?1, ?2, ?3, ?4)",
(file.timestamp, file.hash, file.path, file.size)
);
match result {
Ok(_) => debug!("Inserted new file in DB"),
Err(e) => warn!("Could not insert file in DB (Probably duplicated path), error: {:?}", e)
}
self.close(connection);
}

// ------------------------------------------------------------------------

pub fn get_file(&self, path: String) -> DBFile {
let connection = self.open();
let data = connection.query_row(
"SELECT * FROM files WHERE path = ?1 LIMIT 1",
[path],
|row| Ok(DBFile {
id: row.get(0).unwrap(),
timestamp: row.get(1).unwrap(),
hash: row.get(2).unwrap(),
path: row.get(3).unwrap(),
size: row.get(4).unwrap()
})
);

self.close(connection);
data
}

// ------------------------------------------------------------------------

pub fn print(&self) {
let connection = self.open();
let mut query = connection.prepare(
"SELECT * from files").unwrap();
let files = query.query_map([], |row|{
Ok(DBFile {
id: row.get(0).unwrap(),
timestamp: row.get(1).unwrap(),
hash: row.get(2).unwrap(),
path: row.get(3).unwrap(),
size: row.get(4).unwrap(),
})
}).unwrap();

for file in files {
println!("{:?}", file.unwrap());
}
}
}

// ----------------------------------------------------------------------------

impl fmt::Debug for DBFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result{
f.debug_tuple("")
.field(&self.timestamp)
.field(&self.hash)
.field(&self.path)
.field(&self.size)
.finish()
}
}
13 changes: 13 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::sync::mpsc;
use std::thread;
use log::{error, info};
use crate::init::init;
use crate::db::DBFile;

// Utils functions
mod utils;
Expand Down Expand Up @@ -36,6 +37,7 @@ mod launcher;
mod multiwatcher;
mod rotator;
mod init;
mod db;

// ----------------------------------------------------------------------------

Expand Down Expand Up @@ -75,6 +77,17 @@ async fn main() -> windows_service::Result<()> {
Ok(_v) => info!("FIM rotator thread started."),
Err(e) => error!("Could not start FIM rotator thread, error: {}", e)
};
let db = db::DB::new();
db.create_table();
db.insert_file(DBFile {
id: 0, // Not used for insert auto-increment
timestamp: String::from("Test"),
hash: String::from("Test"),
path: String::from("/test3"),
size: 0
});
db.get_file(String::from("/test3"));
db.print();
monitor::monitor(tx, rx, cfg, ruleset).await;
Ok(())
},
Expand Down

0 comments on commit 749cde5

Please sign in to comment.