2021-08-02 23:09:09 +02:00
|
|
|
//! Run with
|
|
|
|
//!
|
|
|
|
//! ```not_rust
|
|
|
|
//! cargo run --example tokio_postgres
|
|
|
|
//! ```
|
|
|
|
|
2021-08-15 20:27:13 +02:00
|
|
|
use axum::{
|
|
|
|
async_trait,
|
|
|
|
extract::{Extension, FromRequest, RequestParts},
|
|
|
|
prelude::*,
|
|
|
|
AddExtensionLayer,
|
|
|
|
};
|
|
|
|
use bb8::{Pool, PooledConnection};
|
2021-06-15 22:25:41 +02:00
|
|
|
use bb8_postgres::PostgresConnectionManager;
|
|
|
|
use http::StatusCode;
|
|
|
|
use std::net::SocketAddr;
|
|
|
|
use tokio_postgres::NoTls;
|
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
2021-08-05 11:25:03 +02:00
|
|
|
// Set the RUST_LOG, if it hasn't been explicitly defined
|
|
|
|
if std::env::var("RUST_LOG").is_err() {
|
|
|
|
std::env::set_var("RUST_LOG", "tokio_postgres=debug")
|
|
|
|
}
|
2021-08-05 19:43:03 +02:00
|
|
|
tracing_subscriber::fmt::init();
|
2021-08-01 22:01:33 +02:00
|
|
|
|
2021-06-15 22:25:41 +02:00
|
|
|
// setup connection pool
|
|
|
|
let manager =
|
|
|
|
PostgresConnectionManager::new_from_stringlike("host=localhost user=postgres", NoTls)
|
|
|
|
.unwrap();
|
|
|
|
let pool = Pool::builder().build(manager).await.unwrap();
|
|
|
|
|
|
|
|
// build our application with some routes
|
2021-08-15 20:27:13 +02:00
|
|
|
let app = route(
|
|
|
|
"/",
|
|
|
|
get(using_connection_pool_extractor).post(using_connection_extractor),
|
|
|
|
)
|
|
|
|
.layer(AddExtensionLayer::new(pool));
|
2021-06-15 22:25:41 +02:00
|
|
|
|
|
|
|
// run it with hyper
|
|
|
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
|
|
|
tracing::debug!("listening on {}", addr);
|
2021-08-04 15:38:51 +02:00
|
|
|
axum::Server::bind(&addr)
|
2021-06-19 12:50:33 +02:00
|
|
|
.serve(app.into_make_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
2021-06-15 22:25:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type ConnectionPool = Pool<PostgresConnectionManager<NoTls>>;
|
|
|
|
|
2021-08-15 20:27:13 +02:00
|
|
|
// we can exact the connection pool with `Extension`
|
|
|
|
async fn using_connection_pool_extractor(
|
2021-06-15 22:25:41 +02:00
|
|
|
Extension(pool): Extension<ConnectionPool>,
|
|
|
|
) -> Result<String, (StatusCode, String)> {
|
|
|
|
let conn = pool.get().await.map_err(internal_error)?;
|
|
|
|
|
|
|
|
let row = conn
|
|
|
|
.query_one("select 1 + 1", &[])
|
|
|
|
.await
|
|
|
|
.map_err(internal_error)?;
|
|
|
|
let two: i32 = row.try_get(0).map_err(internal_error)?;
|
|
|
|
|
|
|
|
Ok(two.to_string())
|
|
|
|
}
|
|
|
|
|
2021-08-15 20:27:13 +02:00
|
|
|
// we can also write a custom extractor that grabs a connection from the pool
|
|
|
|
// which setup is appropriate depends on your application
|
|
|
|
struct DatabaseConnection(PooledConnection<'static, PostgresConnectionManager<NoTls>>);
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
impl<B> FromRequest<B> for DatabaseConnection
|
|
|
|
where
|
|
|
|
B: Send,
|
|
|
|
{
|
|
|
|
type Rejection = (StatusCode, String);
|
|
|
|
|
|
|
|
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
|
|
|
|
let Extension(pool) = Extension::<ConnectionPool>::from_request(req)
|
|
|
|
.await
|
|
|
|
.map_err(internal_error)?;
|
|
|
|
|
|
|
|
let conn = pool.get_owned().await.map_err(internal_error)?;
|
|
|
|
|
|
|
|
Ok(Self(conn))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn using_connection_extractor(
|
|
|
|
DatabaseConnection(conn): DatabaseConnection,
|
|
|
|
) -> Result<String, (StatusCode, String)> {
|
|
|
|
let row = conn
|
|
|
|
.query_one("select 1 + 1", &[])
|
|
|
|
.await
|
|
|
|
.map_err(internal_error)?;
|
|
|
|
let two: i32 = row.try_get(0).map_err(internal_error)?;
|
|
|
|
|
|
|
|
Ok(two.to_string())
|
|
|
|
}
|
|
|
|
|
2021-06-15 22:25:41 +02:00
|
|
|
/// Utility function for mapping any error into a `500 Internal Server Error`
|
|
|
|
/// response.
|
|
|
|
fn internal_error<E>(err: E) -> (StatusCode, String)
|
|
|
|
where
|
|
|
|
E: std::error::Error,
|
|
|
|
{
|
|
|
|
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
|
|
|
|
}
|