From 2a10109d7f60e263fe44a6d59cbda24fc40f27ac Mon Sep 17 00:00:00 2001 From: Astro Date: Thu, 26 Aug 2021 16:45:06 +0200 Subject: [PATCH] trees: don't crash on botanic_pfaf IS NULL --- server/src/trees.rs | 64 +++++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/server/src/trees.rs b/server/src/trees.rs index d2e34fe..b113aaa 100644 --- a/server/src/trees.rs +++ b/server/src/trees.rs @@ -70,39 +70,41 @@ pub fn get_tree(state: State) -> (State, Response) { let app_state = AppState::borrow_from(&state); let result = { let mut db = app_state.db.lock().unwrap(); - let row = db.query("SELECT id, coord, botanic, botanic_pfaf, german, planted FROM trees WHERE id=$1 LIMIT 1", &[&ie.id]).unwrap() + match db.query("SELECT id, coord, botanic, botanic_pfaf, german, planted FROM trees WHERE id=$1 LIMIT 1", &[&ie.id]).unwrap() .into_iter() - .next(); - if let Some(row) = row { - let botanic_pfaf: &str = row.get(3); - let mut query = format!("SELECT "); - for (i, col) in PFAF_COLS.iter().enumerate() { - query = format!("{}{}\"{}\"::text", query, if i == 0 { "" } else { ", " }, col); + .next() { + None => None, + Some(row) => { + let botanic_pfaf: Option = row.get(3); + botanic_pfaf.and_then(|botanic_pfaf| { + let mut query = format!("SELECT "); + for (i, col) in PFAF_COLS.iter().enumerate() { + query = format!("{}{}\"{}\"::text", query, if i == 0 { "" } else { ", " }, col); + } + query = format!("{} FROM \"PlantsForAFuture\" WHERE \"Latin name\"=$1 LIMIT 1", query); + db.query(query.as_str(), &[&botanic_pfaf]).unwrap() + .into_iter() + .next() + }).map(|pfaf_row| { + let mut details: HashMap = HashMap::with_capacity(PFAF_COLS.len()); + for (i, col) in PFAF_COLS.iter().enumerate() { + if let Some(value) = pfaf_row.get(i) { + details.insert(col.to_string(), value); + } + } + + let point: Point = row.get(1); + Tree { + id: row.get(0), + coords: [point.x(), point.y()], + botanic: row.get(2), + german: row.get(4), + details: Some(details), + planted: row.get(5), + } + }) + } } - query = format!("{} FROM \"PlantsForAFuture\" WHERE \"Latin name\"=$1 LIMIT 1", query); - let pfaf_row = db.query(query.as_str(), &[&botanic_pfaf]).unwrap() - .into_iter() - .next(); - pfaf_row.map(|pfaf_row| { - let point: Point = row.get(1); - let mut details: HashMap = HashMap::with_capacity(PFAF_COLS.len()); - for (i, col) in PFAF_COLS.iter().enumerate() { - if let Some(value) = pfaf_row.get(i) { - details.insert(col.to_string(), value); - } - } - Tree { - id: row.get(0), - coords: [point.x(), point.y()], - botanic: row.get(2), - german: row.get(4), - details: Some(details), - planted: row.get(5), - } - }) - } else { - None - } }; let res = match result {