1
0
mirror of https://github.com/actix/actix-website synced 2024-11-27 10:02:57 +01:00
actix-website/content/docs/databases.md

47 lines
1.9 KiB
Markdown
Raw Normal View History

2018-05-22 23:15:08 +02:00
---
title: Databases
menu: docs_patterns
weight: 1010
---
# Diesel
At the moment, Diesel 1.0 does not support asynchronous operations,
2018-05-30 22:07:50 +02:00
but it's possible to use the `actix` synchronous actor system as a database interface api.
2018-05-22 23:15:08 +02:00
Technically, sync actors are worker style actors. Multiple sync actors
can be run in parallel and process messages from same queue. Sync actors work in mpsc mode.
Let's create a simple database api that can insert a new user row into a SQLite table.
We must define a sync actor and a connection that this actor will use. The same approach
can be used for other databases.
2019-06-18 08:25:55 +02:00
{{< include-example example="og_databases" file="main.rs" section="actor" >}}
2018-05-22 23:15:08 +02:00
This is the definition of our actor. Now, we must define the *create user* message and response.
2019-06-18 08:21:24 +02:00
{{< include-example example="og_databases" file="main.rs" section="message" >}}
2018-05-22 23:15:08 +02:00
We can send a `CreateUser` message to the `DbExecutor` actor, and as a result, we will receive a
`User` model instance. Next, we must define the handler implementation for this message.
2019-06-18 08:21:24 +02:00
{{< include-example example="og_databases" file="main.rs" section="handler" >}}
2018-05-22 23:15:08 +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.
2019-06-18 08:21:24 +02:00
{{< include-example example="og_databases" file="main.rs" section="main" >}}
2018-05-22 23:15:08 +02:00
We will use the address in a request handler. The handle returns a future object;
thus, we receive the message response asynchronously.
`Route::a()` must be used for async handler registration.
2019-06-18 08:21:24 +02:00
{{< include-example example="og_databases" file="main.rs" section="index" >}}
2018-05-22 23:15:08 +02:00
> A full example is available in the
> [examples directory](https://github.com/actix/examples/tree/master/diesel/).
> More information on sync actors can be found in the
2018-07-21 14:40:42 +02:00
> [actix documentation](https://docs.rs/actix/0.7.0/actix/sync/index.html).