added init

This commit is contained in:
2023-09-15 18:58:52 +00:00
parent 3b2f636e41
commit f4ed0f9af2
3 changed files with 61 additions and 14 deletions

3
.env
View File

@@ -1 +1,2 @@
DATABASE_URL=postgres://dev:dev@db/iot
DATABASE_URL=postgres://dev:dev@db/iot
RUST_LOG=debug

View File

@@ -1,5 +1,5 @@
use log::{info, error};
use sqlx::{pool, postgres::PgPoolOptions, PgPool, Pool, Postgres, query};
use log::{error, info};
use sqlx::{pool, postgres::PgPoolOptions, query, PgPool, Pool, Postgres};
#[derive(Clone)]
pub struct Database {
@@ -24,27 +24,71 @@ impl Database {
}
}
pub fn add_telementry(&self){
info!("Adding telementry")
pub async fn add_telementry_table(&self) {
info!("Adding telementry table");
let query = query!("
CREATE TABLE Telemetry (
timestamp TIMESTAMP NOT NULL,
Software_Version VARCHAR(255),
Voltage FLOAT,
Temperature FLOAT,
uptime FLOAT,
device_id INT,
FOREIGN KEY (device_id) REFERENCES Devices(ID)
);
").execute(&self.conn_pool).await;
if query.is_err(){
error!("Error Creating telemetry table");
std::process::exit(1);
}
info!("Successfully added telemetry table");
}
pub async fn add_devices_table(&self) {
info!("Adding devices table");
let query = query!("
CREATE TABLE Devices (
ID INT PRIMARY KEY,
display_name VARCHAR(255)
);
").execute(&self.conn_pool).await;
if query.is_err(){
error!("Error Creating telemetry table");
std::process::exit(1);
}
info!("Successfully added devices table");
}
// Check if the necessary tables exist. If not, create them. TODO auto-migration
pub async fn init_db(&self){
pub async fn init_db(&self) {
info!("Checking if required tables exist");
let devices_table = self.check_if_table_exists("Devices").await;
let telemetry_table = self.check_if_table_exists("Telementry").await;
let exists = query!(
"SELECT count(*) FROM information_schema.tables WHERE table_name = 'dev';"
).fetch_one(&self.conn_pool).await;
if !devices_table {
self.add_devices_table().await;
}
if !telemetry_table {
self.add_telementry_table().await;
}
}
let exist = match exists {
async fn check_if_table_exists(&self, table_name: &str) -> bool {
info!("Checking if table {} exists", table_name);
let exists_result =
query!("SELECT count(*) FROM information_schema.tables WHERE table_name = $1;", table_name)
.fetch_one(&self.conn_pool)
.await;
let exists = match exists_result {
Ok(res) => res.count > Some(0),
Err(err) => {
error!("Error checking table existence: {:?}", err);
std::process::exit(1);
}
};
info!("Table exists: {:?}", exist);
info!("Table {} exists: {}", table_name, exists);
exists
}
}

View File

@@ -9,8 +9,10 @@ struct AppState {
}
#[post("/telemetry/{device_id}")]
async fn receive_telemetry(device_id: web::Path<String>, data: web::Data<AppState>) -> impl Responder {
data.db.add_telementry();
async fn receive_telemetry(
device_id: web::Path<String>,
data: web::Data<AppState>,
) -> impl Responder {
format!("Hello {}!", &device_id)
}