Now using macaddr datatype and added test for adding devices and displaynames
All checks were successful
Build Project / test (push) Successful in 6m32s

This commit is contained in:
2025-01-04 17:06:13 +00:00
parent 1466075b7b
commit f76f248446
9 changed files with 174 additions and 28 deletions

View File

@@ -1,7 +1,7 @@
use actix_web::{cookie::time::error, web};
use actix_web::web;
use chrono::Utc;
use log::{error, info};
use sqlx::{migrate, pool, postgres::PgPoolOptions, query, query_as, PgPool, Pool, Postgres};
use sqlx::{migrate, postgres::PgPoolOptions, query, query_as, types::mac_address::MacAddress, Pool, Postgres};
use thiserror::Error;
use crate::schemas::{TelemetryMessage, TelemetryMessageFromDevice, ValueMessageFromDevice, ValueMessage, Device};
@@ -35,6 +35,10 @@ impl Database {
}
}
pub async fn init_from_pool(pool: Pool<Postgres>) -> Database {
Database { conn_pool: pool }
}
// Check if the necessary tables exist. If not, create them. TODO auto-migration
pub async fn init_db(&self) {
info!("Checking if required tables exist");
@@ -47,7 +51,7 @@ impl Database {
};
}
pub async fn add_device(&self, device_id: &str) -> Result<(), DatabaseError> {
pub async fn add_device(&self, device_id: &MacAddress) -> Result<(), DatabaseError> {
info!("Adding device with the ID {}", &device_id);
query!("INSERT INTO Devices (ID) VALUES ($1);", device_id)
.execute(&self.conn_pool)
@@ -55,7 +59,15 @@ impl Database {
Ok(())
}
pub async fn create_device_if_not_exists(&self, device_id: &str) -> Result<(), DatabaseError> {
pub async fn add_display_name(&self, device_id: &MacAddress, display_name: &str) -> Result<(), DatabaseError> {
info!("Adding Displayname {display_name} to Device with ID {device_id}");
query!("UPDATE Devices SET display_name = $1 WHERE id = $2;", display_name, device_id)
.execute(&self.conn_pool)
.await?;
Ok(())
}
pub async fn create_device_if_not_exists(&self, device_id: &MacAddress) -> Result<(), DatabaseError> {
info!("Checking if device with the ID {} exists", &device_id);
let exists_result = query!("SELECT count(*) FROM devices WHERE ID = $1;", device_id)
.fetch_one(&self.conn_pool)
@@ -82,7 +94,7 @@ impl Database {
pub async fn add_telemetry(
&self,
msg: &web::Json<TelemetryMessageFromDevice>,
device_id: &str,
device_id: &MacAddress,
) -> Result<(), DatabaseError> {
info!("Adding telemetry message to DB");
let current_timestamp = Utc::now().naive_utc();
@@ -95,7 +107,7 @@ impl Database {
pub async fn get_telemetry_for_id(
&self,
device_id: &str,
device_id: &MacAddress,
) -> Result<Vec<TelemetryMessage>, DatabaseError> {
info!("Getting telemetry messages for {} from DB", &device_id);
let messages = query_as!(
@@ -114,7 +126,7 @@ impl Database {
pub async fn add_value(
&self,
msg: &web::Json<ValueMessageFromDevice>,
device_id: &str,
device_id: &MacAddress,
) -> Result<(), DatabaseError> {
info!("Adding value to DB");
let current_timestamp = Utc::now().naive_utc();
@@ -126,7 +138,7 @@ impl Database {
Ok(())
}
pub async fn get_values_for_id(&self, device_id: &str) -> Result<Vec<ValueMessage>, DatabaseError> {
pub async fn get_values_for_id(&self, device_id: &MacAddress) -> Result<Vec<ValueMessage>, DatabaseError> {
info!("Getting values for {} from DB", &device_id);
let values = query_as!(
ValueMessage,
@@ -154,3 +166,27 @@ impl Database {
Ok(devices)
}
}
#[cfg(test)]
mod tests {
use super::*;
use dotenvy::dotenv;
use sqlx::PgPool;
#[sqlx::test]
async fn add_device(pool: PgPool) {
dotenv().ok();
let db = Database::init_from_pool(pool).await;
let test_device = Device{
display_name: Some("Waterlevel daheim".to_owned()),
id: MacAddress::from([0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F])
};
db.add_device(&MacAddress::from([0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F])).await.unwrap();
db.add_display_name(&MacAddress::from([0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F]), "Waterlevel daheim").await.unwrap();
let devices = db.get_devices().await.unwrap();
assert_eq!(test_device, devices[0]);
}
}