1
0
mirror of https://github.com/actix/examples synced 2025-03-28 22:08:38 +01:00
examples/r2d2/src/db.rs
2018-05-20 21:03:29 -07:00

45 lines
1.2 KiB
Rust

//! Db executor actor
use actix::prelude::*;
use actix_web::*;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use std::io;
use uuid;
/// This is db executor actor. We are going to run 3 of them in parallel.
pub struct DbExecutor(pub Pool<SqliteConnectionManager>);
/// This is only message that this actor can handle, but it is easy to extend
/// number of messages.
pub struct CreateUser {
pub name: String,
}
impl Message for CreateUser {
type Result = Result<String, io::Error>;
}
impl Actor for DbExecutor {
type Context = SyncContext<Self>;
}
impl Handler<CreateUser> for DbExecutor {
type Result = Result<String, io::Error>;
fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result {
let conn = self.0.get().unwrap();
let uuid = format!("{}", uuid::Uuid::new_v4());
conn.execute(
"INSERT INTO users (id, name) VALUES ($1, $2)",
&[&uuid, &msg.name],
).unwrap();
Ok(conn
.query_row("SELECT name FROM users WHERE id=$1", &[&uuid], |row| {
row.get(0)
})
.map_err(|_| io::Error::new(io::ErrorKind::Other, "db error"))?)
}
}