2022-01-30 20:09:18 +01:00
|
|
|
//! Example of application using <https://github.com/launchbadge/sqlx>
|
2022-01-25 16:20:00 +01:00
|
|
|
//!
|
|
|
|
|
//! Run with
|
|
|
|
|
//!
|
|
|
|
|
//! ```not_rust
|
2023-03-10 12:02:11 +01:00
|
|
|
//! cargo run -p example-sqlx-postgres
|
2022-01-25 16:20:00 +01:00
|
|
|
//! ```
|
|
|
|
|
//!
|
|
|
|
|
//! Test with curl:
|
|
|
|
|
//!
|
|
|
|
|
//! ```not_rust
|
|
|
|
|
//! curl 127.0.0.1:3000
|
|
|
|
|
//! curl -X POST 127.0.0.1:3000
|
|
|
|
|
//! ```
|
|
|
|
|
|
|
|
|
|
use axum::{
|
|
|
|
|
async_trait,
|
2022-08-22 12:23:20 +02:00
|
|
|
extract::{FromRef, FromRequestParts, State},
|
|
|
|
|
http::{request::Parts, StatusCode},
|
2022-01-25 16:20:00 +01:00
|
|
|
routing::get,
|
2022-03-01 00:39:22 +01:00
|
|
|
Router,
|
2022-01-25 16:20:00 +01:00
|
|
|
};
|
|
|
|
|
use sqlx::postgres::{PgPool, PgPoolOptions};
|
2023-03-22 23:42:14 +01:00
|
|
|
use tokio::net::TcpListener;
|
2022-03-06 12:37:00 +01:00
|
|
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
2022-01-25 16:20:00 +01:00
|
|
|
|
2023-03-22 23:42:14 +01:00
|
|
|
use std::time::Duration;
|
2022-01-25 16:20:00 +01: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()
|
|
|
|
|
.unwrap_or_else(|_| "example_tokio_postgres=debug".into()),
|
|
|
|
|
)
|
2022-03-06 12:37:00 +01:00
|
|
|
.with(tracing_subscriber::fmt::layer())
|
|
|
|
|
.init();
|
2022-01-25 16:20:00 +01:00
|
|
|
|
|
|
|
|
let db_connection_str = std::env::var("DATABASE_URL")
|
|
|
|
|
.unwrap_or_else(|_| "postgres://postgres:password@localhost".to_string());
|
|
|
|
|
|
|
|
|
|
// setup connection pool
|
|
|
|
|
let pool = PgPoolOptions::new()
|
|
|
|
|
.max_connections(5)
|
2023-05-18 11:40:19 -07:00
|
|
|
.acquire_timeout(Duration::from_secs(3))
|
2022-01-25 16:20:00 +01:00
|
|
|
.connect(&db_connection_str)
|
|
|
|
|
.await
|
2022-12-16 11:16:09 +01:00
|
|
|
.expect("can't connect to database");
|
2022-01-25 16:20:00 +01:00
|
|
|
|
|
|
|
|
// 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);
|
2022-01-25 16:20:00 +01:00
|
|
|
|
|
|
|
|
// run it with hyper
|
2023-03-22 23:42:14 +01:00
|
|
|
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
|
|
|
|
|
tracing::debug!("listening on {}", listener.local_addr().unwrap());
|
|
|
|
|
axum::serve(listener, app).await.unwrap();
|
2022-01-25 16:20:00 +01:00
|
|
|
}
|
|
|
|
|
|
2022-08-17 17:13:31 +02:00
|
|
|
// we can extract the connection pool with `State`
|
2022-01-25 16:20:00 +01:00
|
|
|
async fn using_connection_pool_extractor(
|
2022-08-17 17:13:31 +02:00
|
|
|
State(pool): State<PgPool>,
|
2022-01-25 16:20:00 +01:00
|
|
|
) -> Result<String, (StatusCode, String)> {
|
|
|
|
|
sqlx::query_scalar("select 'hello world from pg'")
|
|
|
|
|
.fetch_one(&pool)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(internal_error)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// we can also write a custom extractor that grabs a connection from the pool
|
|
|
|
|
// which setup is appropriate depends on your application
|
|
|
|
|
struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Postgres>);
|
|
|
|
|
|
|
|
|
|
#[async_trait]
|
2022-08-22 12:23:20 +02:00
|
|
|
impl<S> FromRequestParts<S> for DatabaseConnection
|
2022-01-25 16:20:00 +01:00
|
|
|
where
|
2022-08-22 12:23:20 +02:00
|
|
|
PgPool: FromRef<S>,
|
|
|
|
|
S: Send + Sync,
|
2022-01-25 16:20:00 +01: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 = PgPool::from_ref(state);
|
2022-01-25 16:20:00 +01:00
|
|
|
|
|
|
|
|
let conn = pool.acquire().await.map_err(internal_error)?;
|
|
|
|
|
|
|
|
|
|
Ok(Self(conn))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn using_connection_extractor(
|
2023-07-16 13:49:53 +02:00
|
|
|
DatabaseConnection(mut conn): DatabaseConnection,
|
2022-01-25 16:20:00 +01:00
|
|
|
) -> Result<String, (StatusCode, String)> {
|
|
|
|
|
sqlx::query_scalar("select 'hello world from pg'")
|
2023-07-16 13:49:53 +02:00
|
|
|
.fetch_one(&mut *conn)
|
2022-01-25 16:20:00 +01:00
|
|
|
.await
|
|
|
|
|
.map_err(internal_error)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 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())
|
|
|
|
|
}
|