diff --git a/src/cache.rs b/src/cache.rs index 47e6688..c3ad91f 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -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, 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"); } diff --git a/src/lib.rs b/src/lib.rs index a771213..550a87d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ mod api_client; mod ear; mod mouth; mod cache; +mod models; mod schema; use api_client::ApiClient; diff --git a/src/models.rs b/src/models.rs new file mode 100644 index 0000000..46cdf58 --- /dev/null +++ b/src/models.rs @@ -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, +}