From 370790ab51a542cf9b56d21548451c84e741701e Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Sun, 1 Oct 2017 22:04:47 +0200 Subject: Move database setup to lib.rs. --- src/lib.rs | 27 +++++++++++++++++++++++++++ src/main.rs | 30 ++---------------------------- 2 files changed, 29 insertions(+), 28 deletions(-) create mode 100644 src/lib.rs diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..5152ae5 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,27 @@ +#[macro_use] +extern crate diesel; +#[macro_use] +extern crate diesel_codegen; +extern crate dotenv; +extern crate r2d2_diesel; +extern crate r2d2; + +use diesel::pg::PgConnection; +use r2d2_diesel::ConnectionManager; +use dotenv::dotenv; +use std::env; + +// An alias to the type for a pool of Diesel PostgreSql connections. +type Pool = r2d2::Pool>; + +/// Initializes a database pool. +pub fn init_db_pool() -> Pool { + dotenv().ok(); + + let config = r2d2::Config::default(); + let dburl = env::var("DATABASE_URL") + .expect("DATABASE_URL environment variable must be set"); + + let manager = ConnectionManager::::new(dburl); + r2d2::Pool::new(config, manager).expect("db pool") +} diff --git a/src/main.rs b/src/main.rs index 9e29a52..d9747c9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,33 +2,7 @@ #![plugin(rocket_codegen)] extern crate rocket; -#[macro_use] -extern crate diesel; -#[macro_use] -extern crate diesel_codegen; -extern crate dotenv; -extern crate r2d2_diesel; -extern crate r2d2; - -use diesel::pg::PgConnection; -use r2d2_diesel::ConnectionManager; -use dotenv::dotenv; -use std::env; - -// An alias to the type for a pool of Diesel PostgreSql connections. -type Pool = r2d2::Pool>; - -/// Initializes a database pool. -fn init_pool() -> Pool { - dotenv().ok(); - - let config = r2d2::Config::default(); - let dburl = env::var("DATABASE_URL") - .expect("DATABASE_URL environment variable must be set"); - - let manager = ConnectionManager::::new(dburl); - r2d2::Pool::new(config, manager).expect("db pool") -} +extern crate rocket_blog; #[get("/")] fn index() -> &'static str { @@ -37,7 +11,7 @@ fn index() -> &'static str { fn main() { rocket::ignite() - .manage(init_pool()) + .manage(rocket_blog::init_db_pool()) .mount("/", routes![index]) .launch(); } -- cgit v1.2.3