You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.7 KiB

use diesel::{
4 years ago
pg::PgConnection,
prelude::*
};
use dotenv::dotenv;
use std::{
env,
sync::{Arc, Mutex}
};
use crate::{
errors::USrvResult
};
use u_lib::models::*;
pub type Storage = Arc<Mutex<UDB>>;
pub struct UDB {
4 years ago
conn: PgConnection
}
impl UDB {
4 years ago
pub fn new() -> USrvResult<Storage> {
dotenv()?;
4 years ago
let db_path = env::var("DATABASE_URL").unwrap();
let conn = PgConnection::establish(&db_path)?;
let instance = UDB {
conn
};
Ok(Arc::new(Mutex::new(instance)))
}
pub fn new_agent(&self, agent: IAgent) -> USrvResult<()> {
use schema::agents;
diesel::insert_into(agents::table)
.values(agent)
.execute(&self.conn)?;
Ok(())
}
4 years ago
pub fn get_agents(&self) -> USrvResult<Vec<Agent>> {
4 years ago
use schema::agents;
let result = agents::table
.load::<Agent>(&self.conn)?;
4 years ago
Ok(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn setup_db() -> Storage {
4 years ago
return UDB::new().unwrap();
}
#[tokio::test]
async fn test_add_agent() {
let db = setup_db();
let agent = IAgent {
alias: None,
4 years ago
id: "000-000".to_string(),
hostname: "test".to_string(),
is_root: false,
is_root_allowed: false,
platform: "linux".to_string(),
status: None,
token: None,
username: "test".to_string()
};
db.lock().unwrap().new_agent(agent).unwrap();
let result = db.lock().unwrap().get_agents().unwrap();
assert_eq!(
result[0].username,
"test".to_string()
)
}
}