From b233d678f2109fecc7c6a4b9e2d65590819d96d1 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 11 Nov 2018 01:50:03 +0100 Subject: main(): Get a database connection pool instead of a single connection This way we can ask the pool for a connection on each request instead of trying to reuse a single connection. --- license-generator/src/database.rs | 5 ++--- license-generator/src/main.rs | 22 +++++++++++++++++++--- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/license-generator/src/database.rs b/license-generator/src/database.rs index 505a788..a0331c2 100644 --- a/license-generator/src/database.rs +++ b/license-generator/src/database.rs @@ -4,11 +4,10 @@ use mysql; use errors::*; -pub fn get_database_connection() -> Result { +pub fn get_database_pool() -> Result { let connection_url = env::var("DATABASE_URL") .chain_err(|| "DATABASE_URL environment variable not found")?; let pool = mysql::Pool::new_manual(10, 50, connection_url)?; - let cx = pool.get_conn()?; - Ok(cx) + Ok(pool) } diff --git a/license-generator/src/main.rs b/license-generator/src/main.rs index d18b880..fb29824 100644 --- a/license-generator/src/main.rs +++ b/license-generator/src/main.rs @@ -54,10 +54,10 @@ fn main() -> Result<()> { log_config.time_format = Some("%+"); WriteLogger::init(LevelFilter::Info, log_config, log_file)?; - let mut cx = match database::get_database_connection() - .chain_err(|| "failed to create a database connection") + let pool = match database::get_database_pool() + .chain_err(|| "failed to create a database connection pool") { - Ok(cx) => cx, + Ok(pool) => pool, Err(e) => { error!("{}", e); return Err(e); @@ -119,6 +119,22 @@ fn main() -> Result<()> { if name.is_some() && email.is_some() { let purchaser = Purchaser::new(name.unwrap(), email.unwrap()); + + let mut cx = match pool.get_conn() { + Ok(cx) => cx, + Err(e) => { + error!("{}", e); + + response::set_500(&mut req.stdout()).unwrap_or(()); + write!(&mut req.stdout(), "Content-Type: text/plain + +500 Internal Server Error") + .unwrap_or(()); + + return; + }, + }; + match purchaser.insert(&mut cx) { Ok(_) => { // TODO: Print message to be appended to user email -- cgit v1.2.3