1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-02-07 22:04:24 +01:00
actix-web/guide/src/qs_14.md

128 lines
3.7 KiB
Markdown
Raw Normal View History

# Database integration
## Diesel
At the moment of 1.0 release Diesel does not support asynchronous operations.
2018-03-28 22:16:01 +02:00
But it possible to use the `actix` synchronous actor system as a db interface api.
2017-12-18 20:03:42 -08:00
Technically sync actors are worker style actors, multiple of them
2018-03-28 22:16:01 +02:00
can be run in parallel and process messages from same queue (sync actors work in mpsc mode).
2018-03-28 22:16:01 +02:00
Let's create a simple db api that can insert a new user row into an SQLite table.
We have to define sync actor and connection that this actor will use. The same approach
can be used for other databases.
```rust,ignore
use actix::prelude::*;
struct DbExecutor(SqliteConnection);
impl Actor for DbExecutor {
type Context = SyncContext<Self>;
}
```
2018-03-28 22:16:01 +02:00
This is the definition of our actor. Now we need to define the *create user* message and response.
```rust,ignore
struct CreateUser {
name: String,
}
2018-03-06 00:44:45 -08:00
impl Message for CreateUser {
type Result = Result<User, Error>;
}
```
2018-03-28 22:16:01 +02:00
We can send a `CreateUser` message to the `DbExecutor` actor, and as a result we get a
`User` model instance. Now we need to define the actual handler implementation for this message.
```rust,ignore
impl Handler<CreateUser> for DbExecutor {
2018-03-06 01:46:16 +01:00
type Result = Result<User, Error>;
2017-12-18 20:00:57 -08:00
2018-01-13 11:17:48 -08:00
fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result
{
use self::schema::users::dsl::*;
// Create insertion model
let uuid = format!("{}", uuid::Uuid::new_v4());
let new_user = models::NewUser {
id: &uuid,
name: &msg.name,
};
2018-03-24 09:35:52 +03:00
// normal diesel operations
diesel::insert_into(users)
.values(&new_user)
.execute(&self.0)
.expect("Error inserting person");
let mut items = users
.filter(id.eq(&uuid))
.load::<models::User>(&self.0)
.expect("Error loading person");
2018-01-13 11:17:48 -08:00
Ok(items.pop().unwrap())
}
}
```
2018-03-28 22:16:01 +02:00
That's it. Now we can use the *DbExecutor* actor from any http handler or middleware.
All we need is to start *DbExecutor* actors and store the address in a state where http handler
can access it.
```rust,ignore
2017-12-26 21:07:51 -08:00
/// This is state where we will store *DbExecutor* address.
struct State {
2018-02-17 13:33:38 -08:00
db: Addr<Syn, DbExecutor>,
}
fn main() {
let sys = actix::System::new("diesel-example");
2018-01-13 11:17:48 -08:00
// Start 3 parallel db executors
let addr = SyncArbiter::start(3, || {
DbExecutor(SqliteConnection::establish("test.db").unwrap())
});
// Start http server
HttpServer::new(move || {
2018-03-31 00:16:55 -07:00
App::with_state(State{db: addr.clone()})
.resource("/{name}", |r| r.method(Method::GET).a(index))})
.bind("127.0.0.1:8080").unwrap()
.start().unwrap();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}
```
2018-03-28 22:16:01 +02:00
And finally we can use the address in a request handler. We get a message response
asynchronously, so the handler needs to return a future object, also `Route::a()` needs to be
used for async handler registration.
```rust,ignore
/// Async handler
fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>> {
let name = &req.match_info()["name"];
2017-12-20 21:06:04 -08:00
// Send message to `DbExecutor` actor
2018-02-17 13:33:38 -08:00
req.state().db.send(CreateUser{name: name.to_owned()})
2017-12-20 21:06:04 -08:00
.from_err()
.and_then(|res| {
match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into())
2017-12-20 21:06:04 -08:00
}
})
.responder()
}
```
2018-03-28 22:16:01 +02:00
Full example is available in the
2017-12-19 10:10:03 -08:00
[examples directory](https://github.com/actix/actix-web/tree/master/examples/diesel/).
2018-03-28 22:16:01 +02:00
More information on sync actors can be found in the
[actix documentation](https://docs.rs/actix/0.5.0/actix/sync/index.html).