2021-08-02 23:09:09 +02:00
|
|
|
//! Run with
|
|
|
|
|
//!
|
|
|
|
|
//! ```not_rust
|
2023-03-10 12:02:11 +01:00
|
|
|
//! cargo run -p example-tokio-postgres
|
2021-08-02 23:09:09 +02:00
|
|
|
//! ```
|
|
|
|
|
|
2021-08-15 20:27:13 +02:00
|
|
|
use axum::{
|
2022-08-22 12:23:20 +02:00
|
|
|
extract::{FromRef, FromRequestParts, State},
|
|
|
|
|
http::{request::Parts, StatusCode},
|
2021-10-24 22:05:16 +02:00
|
|
|
routing::get,
|
2022-03-01 00:39:22 +01:00
|
|
|
Router,
|
2021-08-15 20:27:13 +02:00
|
|
|
};
|
|
|
|
|
use bb8::{Pool, PooledConnection};
|
2021-06-15 22:25:41 +02:00
|
|
|
use bb8_postgres::PostgresConnectionManager;
|
|
|
|
|
use tokio_postgres::NoTls;
|
2022-03-06 12:37:00 +01:00
|
|
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
2021-06-15 22:25:41 +02:00
|
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
|
async fn main() {
|
2022-03-06 12:37:00 +01:00
|
|
|
tracing_subscriber::registry()
|
2022-11-30 18:46:19 +09:00
|
|
|
.with(
|
|
|
|
|
tracing_subscriber::EnvFilter::try_from_default_env()
|
2024-08-24 14:36:08 +08:00
|
|
|
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
|
2022-11-30 18:46:19 +09:00
|
|
|
)
|
2022-03-06 12:37:00 +01:00
|
|
|
.with(tracing_subscriber::fmt::layer())
|
|
|
|
|
.init();
|
2021-08-01 22:01:33 +02:00
|
|
|
|
2022-07-18 14:46:38 -02:30
|
|
|
// set up connection pool
|
2021-06-15 22:25:41 +02:00
|
|
|
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
|
2022-11-18 12:02:58 +01:00
|
|
|
let app = Router::new()
|
|
|
|
|
.route(
|
|
|
|
|
"/",
|
|
|
|
|
get(using_connection_pool_extractor).post(using_connection_extractor),
|
|
|
|
|
)
|
|
|
|
|
.with_state(pool);
|
2021-06-15 22:25:41 +02:00
|
|
|
|
2023-03-22 23:42:14 +01:00
|
|
|
// run it
|
|
|
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
|
2021-06-19 12:50:33 +02:00
|
|
|
.await
|
|
|
|
|
.unwrap();
|
2023-03-22 23:42:14 +01:00
|
|
|
tracing::debug!("listening on {}", listener.local_addr().unwrap());
|
2025-04-26 22:09:00 +02:00
|
|
|
axum::serve(listener, app).await;
|
2021-06-15 22:25:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type ConnectionPool = Pool<PostgresConnectionManager<NoTls>>;
|
|
|
|
|
|
2021-08-15 20:27:13 +02:00
|
|
|
async fn using_connection_pool_extractor(
|
2022-08-17 17:13:31 +02:00
|
|
|
State(pool): State<ConnectionPool>,
|
2021-06-15 22:25:41 +02:00
|
|
|
) -> 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>>);
|
|
|
|
|
|
2022-08-22 12:23:20 +02:00
|
|
|
impl<S> FromRequestParts<S> for DatabaseConnection
|
2021-08-15 20:27:13 +02:00
|
|
|
where
|
2022-08-22 12:23:20 +02:00
|
|
|
ConnectionPool: FromRef<S>,
|
|
|
|
|
S: Send + Sync,
|
2021-08-15 20:27:13 +02:00
|
|
|
{
|
|
|
|
|
type Rejection = (StatusCode, String);
|
|
|
|
|
|
2022-08-22 12:23:20 +02:00
|
|
|
async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
|
|
|
|
let pool = ConnectionPool::from_ref(state);
|
2021-08-15 20:27:13 +02:00
|
|
|
|
|
|
|
|
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())
|
|
|
|
|
}
|