main.rs
This file
Path
examples/sqlx-postgres/src/main.rs
109 lines · 3.0 KiB · Rust
Last changed by
Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7
History of this fileTake it
1//! Example of application using <https://github.com/launchbadge/sqlx>2//!3//! Run with4//!5//! ```not_rust6//! cargo run -p example-sqlx-postgres7//! ```8//!9//! Test with curl:10//!11//! ```not_rust12//! curl 127.0.0.1:300013//! curl -X POST 127.0.0.1:300014//! ```1516use axum::{17 extract::{FromRef, FromRequestParts, State},18 http::{request::Parts, StatusCode},19 routing::get,20 Router,21};22use sqlx::postgres::{PgPool, PgPoolOptions};23use tokio::net::TcpListener;24use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};2526use std::time::Duration;2728#[tokio::main]29async fn main() {30 tracing_subscriber::registry()31 .with(32 tracing_subscriber::EnvFilter::try_from_default_env()33 .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),34 )35 .with(tracing_subscriber::fmt::layer())36 .init();3738 let db_connection_str = std::env::var("DATABASE_URL")39 .unwrap_or_else(|_| "postgres://postgres:password@localhost".to_string());4041 // set up connection pool42 let pool = PgPoolOptions::new()43 .max_connections(5)44 .acquire_timeout(Duration::from_secs(3))45 .connect(&db_connection_str)46 .await47 .expect("can't connect to database");4849 // build our application with some routes50 let app = Router::new()51 .route(52 "/",53 get(using_connection_pool_extractor).post(using_connection_extractor),54 )55 .with_state(pool);5657 // run it with hyper58 let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();59 tracing::debug!("listening on {}", listener.local_addr().unwrap());60 axum::serve(listener, app).await;61}6263// we can extract the connection pool with `State`64async fn using_connection_pool_extractor(65 State(pool): State<PgPool>,66) -> Result<String, (StatusCode, String)> {67 sqlx::query_scalar("select 'hello world from pg'")68 .fetch_one(&pool)69 .await70 .map_err(internal_error)71}7273// we can also write a custom extractor that grabs a connection from the pool74// which setup is appropriate depends on your application75struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Postgres>);7677impl<S> FromRequestParts<S> for DatabaseConnection78where79 PgPool: FromRef<S>,80 S: Send + Sync,81{82 type Rejection = (StatusCode, String);8384 async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {85 let pool = PgPool::from_ref(state);8687 let conn = pool.acquire().await.map_err(internal_error)?;8889 Ok(Self(conn))90 }91}9293async fn using_connection_extractor(94 DatabaseConnection(mut conn): DatabaseConnection,95) -> Result<String, (StatusCode, String)> {96 sqlx::query_scalar("select 'hello world from pg'")97 .fetch_one(&mut *conn)98 .await99 .map_err(internal_error)100}101102/// Utility function for mapping any error into a `500 Internal Server Error`103/// response.104fn internal_error<E>(err: E) -> (StatusCode, String)105where106 E: std::error::Error,107{108 (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())109}