From b2e771df2cb4130889a5e45cfff97a76772639ce Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sun, 1 Apr 2018 08:20:15 -0700 Subject: [PATCH] use r2d2 for diesel example --- examples/diesel/Cargo.toml | 4 +++- examples/diesel/src/db.rs | 10 +++++++--- examples/diesel/src/main.rs | 12 +++++++++--- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/examples/diesel/Cargo.toml b/examples/diesel/Cargo.toml index 20c9b75c9..ac9122c6f 100644 --- a/examples/diesel/Cargo.toml +++ b/examples/diesel/Cargo.toml @@ -15,5 +15,7 @@ serde = "1.0" serde_json = "1.0" serde_derive = "1.0" -diesel = { version = "1.0.0-beta1", features = ["sqlite"] } +diesel = { version = "1.0", features = ["sqlite"] } +r2d2 = "0.8" +r2d2-diesel = "1.0" dotenv = "0.10" diff --git a/examples/diesel/src/db.rs b/examples/diesel/src/db.rs index afbf43dea..b835d34f4 100644 --- a/examples/diesel/src/db.rs +++ b/examples/diesel/src/db.rs @@ -4,12 +4,14 @@ use diesel; use actix_web::*; use actix::prelude::*; use diesel::prelude::*; +use r2d2::Pool; +use r2d2_diesel::ConnectionManager; use models; use schema; /// This is db executor actor. We are going to run 3 of them in parallel. -pub struct DbExecutor(pub SqliteConnection); +pub struct DbExecutor(pub Pool>); /// This is only message that this actor can handle, but it is easy to extend number of /// messages. @@ -37,14 +39,16 @@ impl Handler for DbExecutor { name: &msg.name, }; + let conn: &SqliteConnection = &self.0.get().unwrap(); + diesel::insert_into(users) .values(&new_user) - .execute(&self.0) + .execute(conn) .expect("Error inserting person"); let mut items = users .filter(id.eq(&uuid)) - .load::(&self.0) + .load::(conn) .expect("Error loading person"); Ok(items.pop().unwrap()) diff --git a/examples/diesel/src/main.rs b/examples/diesel/src/main.rs index cf5b183d1..d71880fca 100644 --- a/examples/diesel/src/main.rs +++ b/examples/diesel/src/main.rs @@ -10,6 +10,8 @@ extern crate serde_json; extern crate serde_derive; #[macro_use] extern crate diesel; +extern crate r2d2; +extern crate r2d2_diesel; extern crate uuid; extern crate futures; extern crate actix; @@ -21,6 +23,7 @@ use actix_web::{http, middleware, App, HttpServer, HttpRequest, HttpResponse, Error, AsyncResponder}; use diesel::prelude::*; +use r2d2_diesel::ConnectionManager; use futures::future::Future; mod db; @@ -53,12 +56,15 @@ fn index(req: HttpRequest) -> Box> fn main() { ::std::env::set_var("RUST_LOG", "actix_web=info"); - let _ = env_logger::init(); + env_logger::init(); let sys = actix::System::new("diesel-example"); // Start 3 db executor actors - let addr = SyncArbiter::start(3, || { - DbExecutor(SqliteConnection::establish("test.db").unwrap()) + let manager = ConnectionManager::::new("test.db"); + let pool = r2d2::Pool::builder().build(manager).expect("Failed to create pool."); + + let addr = SyncArbiter::start(3, move || { + DbExecutor(pool.clone()) }); // Start http server