From d5c7356822a710bbde733af78dd149c9f9cc4eb4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Phil=20H=C3=B6fer?= <phil.hoefer@suma-ev.de>
Date: Thu, 11 Jul 2024 15:23:43 +0200
Subject: [PATCH] Improve Error Handling

---
 src/main.rs | 45 ++++++++++++++++++++++++---------------------
 1 file changed, 24 insertions(+), 21 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index adf2a43..7e8c5cd 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -122,36 +122,39 @@ fn main() -> Result<(), io::Error> {
 
 fn read_from_db(config: HashMap<String, String>, mut predictor: SetPredictor) -> SetPredictor {
     let default_password = &String::from("");
-    let db_password = config.get("db_password").unwrap_or(default_password);
-    let mut client = Client::connect(format!("host=database-postgresql.metager-2 user=metager password={} dbname=postgres",db_password).as_str(), NoTls);
-
-
-
-    match client {
-        Ok(mut c) => {
-            let mut count = 0;
-            match c.query("SELECT query FROM public.logs_partitioned ORDER BY time DESC LIMIT 5000", &[]) {
-                Ok(rows) => {
-                    for row in rows {
-                        let query: &str = row.get(0);
-                        predictor.update(query);
-                        count += 1;
+    match config.get("db_password") {
+        Some(db_password) => {
+            let mut client = Client::connect(format!("host=database-postgresql.metager-2 user=metager password={} dbname=postgres",db_password).as_str(), NoTls);
+            match client {
+                Ok(mut c) => {
+                    let mut count = 0;
+                    match c.query("SELECT query FROM public.logs_partitioned ORDER BY time DESC LIMIT 5000", &[]) {
+                        Ok(rows) => {
+                            for row in rows {
+                                let query: &str = row.get(0);
+                                predictor.update(query);
+                                count += 1;
+                            }
+                            println!("{} queries read from DB", count);
+                            predictor
+                        },
+                        Err(e) => {
+                            println!("Error while reading from DB: {}", e);
+                            predictor
+                        }
                     }
-                    println!("{} queries read from DB", count);
-                    predictor
                 },
                 Err(e) => {
-                    println!("Error while reading from DB: {}", e);
+                    println!("Error while connecting to DB: {}", e);
                     predictor
                 }
             }
         },
-        Err(e) => {
-            println!("Error while connecting to DB: {}", e);
+        None => {
+            println!("No DB password found. Skipping...");
             predictor
         }
-        
-    }
+    }  
 
 } 
 
-- 
GitLab