diff --git a/src/cache.rs b/src/cache.rs index 41f4141..8a5e904 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -4,10 +4,10 @@ use std::env; use std::fmt::Display; +use std::process; use diesel::pg::PgConnection; use diesel::prelude::*; -use diesel::ConnectionError; use dotenvy::dotenv; use crate::schema::cache::dsl::*; @@ -25,23 +25,32 @@ pub struct Cache { /// as both can happen during the `establish_connection` function. #[derive(Debug)] pub enum CacheError { - PgError(ConnectionError), + DieselConnectionError(diesel::ConnectionError), + DieselResultError(diesel::result::Error), EnvError(env::VarError), } impl Display for CacheError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - CacheError::PgError(pg_err) => write!(f, "{}", pg_err), - CacheError::EnvError(env_err) => write!(f, "{}", env_err), + CacheError::DieselConnectionError(err) => write!(f, "{}", err), + CacheError::DieselResultError(err) => write!(f, "{}", err), + CacheError::EnvError(err) => write!(f, "{}", err), } } } -/// To convert between ConnectionError and CacheError::PgError -impl From for CacheError { - fn from(err: ConnectionError) -> Self { - CacheError::PgError(err) +/// To convert between ConnectionError and CacheError::PgConnectionError +impl From for CacheError { + fn from(err: diesel::ConnectionError) -> Self { + CacheError::DieselConnectionError(err) + } +} + +/// To convert between DieselResultError and CacheError::PgConnectionError +impl From for CacheError { + fn from(err: diesel::result::Error) -> Self { + CacheError::DieselResultError(err) } } @@ -60,20 +69,28 @@ fn establish_connection() -> Result { Ok(PgConnection::establish(&database_url)?) } -fn load_sql() { - let connection = &mut establish_connection().unwrap(); - let results = cache - .load::(connection) - .expect("Error loading cache"); +/// Load data from the cache, and return a vector of Cache. +fn load_sql() -> Result, CacheError> { + let connection = &mut establish_connection()?; + let results = cache.filter(name.eq("Debian")).load::(connection)?; - for result in results { - println!("{}", result.name); - println!("{}", result.domain); - println!("{}", result.ip); - println!("---"); - }; + Ok(results) } +/// SQL cache function to be called by `get_data`. pub fn sql_cache() { - load_sql(); + let data = match load_sql() { + Ok(data) => data, + Err(err) => { + eprintln!("Unable to load data: {err}"); + process::exit(1); + } + }; + + for item in data { + println!("{}", item.name); + println!("{}", item.domain); + println!("{}", item.ip); + println!("---"); + } }