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

48 lines
2.0 KiB
Markdown
Raw Normal View History

2018-05-22 23:15:08 +02:00
---
title: Databases
menu: docs_patterns
weight: 1010
---
2020-09-12 17:21:54 +02:00
# Async Options
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
We have several example projects showing use of async database adapters:
2018-05-22 23:15:08 +02:00
- Postgres: https://github.com/actix/examples/tree/master/databases/postgres
- SQLite: https://github.com/actix/examples/tree/master/databases/sqlite
- MongoDB: https://github.com/actix/examples/tree/master/databases/mongodb
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
# Diesel
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
The current version of Diesel (v1) does not support asynchronous operations, so it is important to
use the [`web::block`][web-block] function to offload your database operations to the Actix runtime
thread-pool.
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
You can create action functions that correspond to all the operations your app will perform on the
database.
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
{{< include-example example="databases" file="main.rs" section="handler" >}}
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
Now you should set up the database pool using a crate such as `r2d2`, which makes many DB
connections available to your app. This means that multiple handlers can manipulate the DB at the
same time, and still accept new connections. Simply, the pool in your app state. (In this case, it's
beneficial not to use a state wrapper struct because the pool handles shared access for you.)
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
{{< include-example example="databases" file="main.rs" section="main" >}}
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
Now, in a request handler, use the `Data<T>` extractor to get the pool from app state and get a
connection from it. This provides an owned database connection that can be passed into a
[`web::block`][web-block] closure. Then just call the action function with the necessary arguments
and `.await` the result.
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
This example also maps the error to an `HttpResponse` before using the `?` operator but this is not
necessary if your return error type implements [`ResponseError`][response-error].
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
{{< include-example example="databases" file="main.rs" section="index" >}}
2018-05-22 23:15:08 +02:00
2021-02-26 19:48:27 +01:00
That's it! See the full example here:
2022-02-18 11:13:22 +01:00
https://github.com/actix/examples/tree/master/databases/diesel
2020-09-12 17:21:54 +02:00
[web-block]: https://docs.rs/actix-web/3/actix_web/web/fn.block.html
[response-error]: https://docs.rs/actix-web/3/actix_web/trait.ResponseError.html