Move Cache to models.rs, add InsertCache and insert function

This commit is contained in:
flyingscorpio@clevo 2022-12-10 15:15:57 +01:00
parent d995bf904c
commit b07c64fec0
3 changed files with 42 additions and 9 deletions

View file

@ -10,17 +10,9 @@ use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenvy::dotenv;
use crate::models::{Cache, InsertCache};
use crate::schema::cache::dsl::*;
/// Cache struct, mapped to the SQL cache database.
#[derive(Queryable)]
pub struct Cache {
pub id: i32,
pub name: String,
pub domain: String,
pub ip: String,
}
/// This enum wraps the errors for database connection error and .env access error,
/// as both can happen during the `establish_connection` function.
#[derive(Debug)]
@ -77,8 +69,25 @@ fn load_sql() -> Result<Vec<Cache>, CacheError> {
Ok(results)
}
/// Insert data into the cache
fn insert_sql(conn: &mut PgConnection, new_name: &str, new_domain: &str, new_ip: &str) -> Cache {
use crate::schema::cache;
let cache_element = InsertCache {
name: new_name,
domain: new_domain,
ip: new_ip,
};
diesel::insert_into(cache::table)
.values(&cache_element)
.get_result(conn)
.expect("Error saving new cache element")
}
/// 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 load_sql() {
Ok(data) => data,
Err(err) => {
@ -93,4 +102,6 @@ pub fn sql_cache() {
println!("{}", item.ip);
println!("---");
}
let new_cache_element = insert_sql(connection, "Arch", "archlinux.org", "95.217.163.246");
}

View file

@ -8,6 +8,7 @@ mod api_client;
mod ear;
mod mouth;
mod cache;
mod models;
mod schema;
use api_client::ApiClient;

21
src/models.rs Normal file
View file

@ -0,0 +1,21 @@
use diesel::prelude::*;
use crate::schema::cache;
/// Cache struct, mapped to the SQL cache database.
#[derive(Queryable)]
pub struct Cache {
pub id: i32,
pub name: String,
pub domain: String,
pub ip: String,
}
/// InsertCache struct, needed for inserting into the cache table.
#[derive(Insertable)]
#[diesel(table_name = cache)]
pub struct InsertCache<'a> {
pub name: &'a str,
pub domain: &'a str,
pub ip: &'a str,
}