Switched over to migrations

This commit is contained in:
2023-09-16 19:08:20 +00:00
parent f4ed0f9af2
commit 3f9dcb3a53
5 changed files with 54 additions and 54 deletions

View File

@@ -9,4 +9,6 @@ edition = "2021"
actix-web = "4.4.0" actix-web = "4.4.0"
env_logger = "0.10.0" env_logger = "0.10.0"
log = "0.4.20" log = "0.4.20"
sqlx = { version = "0.7", features = [ "runtime-tokio", "tls-rustls", "postgres" ] } sqlx = { version = "0.7", features = [ "runtime-tokio", "tls-rustls", "postgres", "migrate"] }
sqlx-cli = "0.7.1"
thiserror = "1.0.48"

5
migrations/1_devices.sql Normal file
View File

@@ -0,0 +1,5 @@
-- Add migration script here
CREATE TABLE Devices (
ID CHAR(32) PRIMARY KEY,
display_name VARCHAR(255)
);

View File

@@ -0,0 +1,10 @@
-- Add migration script here
CREATE TABLE Telemetry (
timestamp TIMESTAMP NOT NULL,
Software_Version VARCHAR(255),
Voltage FLOAT,
Temperature FLOAT,
uptime FLOAT,
device_id CHAR(32),
FOREIGN KEY (device_id) REFERENCES Devices(ID)
);

View File

@@ -1,11 +1,19 @@
use actix_web::cookie::time::error;
use log::{error, info}; use log::{error, info};
use sqlx::{pool, postgres::PgPoolOptions, query, PgPool, Pool, Postgres}; use sqlx::{pool, postgres::PgPoolOptions, query, PgPool, Pool, Postgres, migrate};
use thiserror::Error;
#[derive(Clone)] #[derive(Clone)]
pub struct Database { pub struct Database {
conn_pool: Pool<Postgres>, conn_pool: Pool<Postgres>,
} }
#[derive(Error, Debug)]
pub enum DatabaseError {
#[error("Generic SQLX Error")]
SqlxError(#[from] sqlx::Error)
}
impl Database { impl Database {
pub async fn init(host: &str, user: &str, pass: &str, db_name: &str) -> Database { pub async fn init(host: &str, user: &str, pass: &str, db_name: &str) -> Database {
match PgPoolOptions::new() match PgPoolOptions::new()
@@ -24,62 +32,31 @@ impl Database {
} }
} }
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 // 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"); info!("Checking if required tables exist");
let devices_table = self.check_if_table_exists("Devices").await; match migrate!().run(&self.conn_pool).await{
let telemetry_table = self.check_if_table_exists("Telementry").await; Ok(_) => {},
Err(e) => {
if !devices_table { error!("Error when running migrations {}", e);
self.add_devices_table().await; std::process::exit(1);
} }
if !telemetry_table { };
self.add_telementry_table().await;
}
} }
async fn check_if_table_exists(&self, table_name: &str) -> bool { pub async fn add_device(&self, device_id: &str) -> Result<(), DatabaseError> {
info!("Checking if table {} exists", table_name); info!("Adding device with the ID {}", &device_id);
query!("INSERT INTO Devices (ID) VALUES ($1);", device_id).execute(&self.conn_pool).await?;
Ok(())
}
pub async fn create_device_if_not_exists(&self, device_id: &str) -> Result<(), DatabaseError> {
info!("Checking if device with the ID {} exists", &device_id);
let exists_result = let exists_result =
query!("SELECT count(*) FROM information_schema.tables WHERE table_name = $1;", table_name) query!("SELECT count(*) FROM devices WHERE ID = $1;", device_id)
.fetch_one(&self.conn_pool) .fetch_one(&self.conn_pool)
.await; .await;
let exists = match exists_result { let exists = match exists_result {
Ok(res) => res.count > Some(0), Ok(res) => res.count > Some(0),
Err(err) => { Err(err) => {
@@ -88,7 +65,11 @@ impl Database {
} }
}; };
info!("Table {} exists: {}", table_name, exists); if exists{
exists Ok(())
} else {
self.add_device(device_id).await?;
Ok(())
}
} }
} }

View File

@@ -1,4 +1,4 @@
use actix_web::{post, web, App, HttpServer, Responder}; use actix_web::{post, web, App, HttpServer, Responder, http::StatusCode, HttpResponse};
use database::Database; use database::Database;
use log::info; use log::info;
@@ -13,7 +13,9 @@ async fn receive_telemetry(
device_id: web::Path<String>, device_id: web::Path<String>,
data: web::Data<AppState>, data: web::Data<AppState>,
) -> impl Responder { ) -> impl Responder {
format!("Hello {}!", &device_id) data.db.create_device_if_not_exists(&device_id);
HttpResponse::Ok()
} }
#[actix_web::main] #[actix_web::main]