Add code to get items from sql cache

This commit is contained in:
flyingscorpio@clevo 2022-12-10 11:17:30 +01:00
parent 51375f0086
commit 4349e35060
3 changed files with 33 additions and 8 deletions

View file

@ -10,12 +10,8 @@ use diesel::prelude::*;
use diesel::ConnectionError;
use dotenvy::dotenv;
/// Cache struct, mapped to the SQL cache database.
struct Cache {
name: String,
domain: String,
ip: String,
}
use crate::models::Cache;
use crate::schema::cache::dsl::*;
/// This enum wraps the errors for database connection error and .env access error,
/// as both can happen during the `establish_connection` function.
@ -48,9 +44,26 @@ impl From<env::VarError> for CacheError {
}
}
pub fn establish_connection() -> Result<PgConnection, CacheError> {
/// Uses `.env` file to get credentials to the database and establish a connection.
fn establish_connection() -> Result<PgConnection, CacheError> {
dotenv().ok();
let database_url = env::var("DATABASE_URL")?;
Ok(PgConnection::establish(&database_url)?)
}
fn load_sql() {
let connection = &mut establish_connection().unwrap();
let results = cache
.filter(true)
.limit(5)
.load::<Cache>(connection)
.expect("Error loading cache");
for result in results {
println!("{}", result.name);
println!("{}", result.domain);
println!("{}", result.ip);
println!("---");
};
}

View file

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

10
src/models.rs Normal file
View file

@ -0,0 +1,10 @@
use diesel::prelude::*;
/// 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,
}