Propagate errors when loading data from sql

This commit is contained in:
flyingscorpio@clevo 2022-12-10 14:34:52 +01:00
parent f363e84ce9
commit a2c8107656

View file

@ -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<ConnectionError> for CacheError {
fn from(err: ConnectionError) -> Self {
CacheError::PgError(err)
/// To convert between ConnectionError and CacheError::PgConnectionError
impl From<diesel::ConnectionError> for CacheError {
fn from(err: diesel::ConnectionError) -> Self {
CacheError::DieselConnectionError(err)
}
}
/// To convert between DieselResultError and CacheError::PgConnectionError
impl From<diesel::result::Error> for CacheError {
fn from(err: diesel::result::Error) -> Self {
CacheError::DieselResultError(err)
}
}
@ -60,20 +69,28 @@ fn establish_connection() -> Result<PgConnection, CacheError> {
Ok(PgConnection::establish(&database_url)?)
}
fn load_sql() {
let connection = &mut establish_connection().unwrap();
let results = cache
.load::<Cache>(connection)
.expect("Error loading cache");
/// Load data from the cache, and return a vector of Cache.
fn load_sql() -> Result<Vec<Cache>, CacheError> {
let connection = &mut establish_connection()?;
let results = cache.filter(name.eq("Debian")).load::<Cache>(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!("---");
}
}