For {insert,read}_sql, use connection as argument, return QueryResult

This commit is contained in:
flyingscorpio@clevo 2022-12-10 15:29:21 +01:00
parent d706119188
commit 0a802befb8

View file

@ -63,32 +63,37 @@ fn establish_connection() -> Result<PgConnection, CacheError> {
}
/// Read data from the cache, and return a vector of Cache.
fn read_sql() -> Result<Vec<Cache>, CacheError> {
let connection = &mut establish_connection()?;
fn read_sql(connection: &mut PgConnection) -> QueryResult<Vec<Cache>> {
let results = cache.filter(name.eq("Debian")).load::<Cache>(connection)?;
Ok(results)
}
/// Insert data into the cache
fn insert_sql(conn: &mut PgConnection, new_name: &str, new_domain: &str, new_ip: &str) -> Cache {
fn insert_sql(
connection: &mut PgConnection,
new_name: &str,
new_domain: &str,
new_ip: &str,
) -> QueryResult<Cache> {
let cache_element = InsertCache {
name: new_name,
domain: new_domain,
ip: new_ip,
};
diesel::insert_into(cache::table)
let results = diesel::insert_into(cache::table)
.values(&cache_element)
.get_result(conn)
.expect("Error saving new cache element")
.get_result(connection)?;
Ok(results)
}
/// SQL cache function to be called by `get_data` (read) and `api_client` (write).
pub fn sql_cache() {
let connection = &mut establish_connection().unwrap();
let data = match read_sql() {
let data = match read_sql(connection) {
Ok(data) => data,
Err(err) => {
eprintln!("Unable to load data: {err}");