Skip to content
Myr

main.rs

This file

Path

examples/diesel-async-postgres/src/main.rs

141 lines · 4.0 KiB · Rust

Last changed by

Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7

History of this file

Take it

1//! Run with2//!3//! ```sh4//! export DATABASE_URL=postgres://localhost/your_db5//! cargo run -p example-diesel-async-postgres6//! ```7//!8//! Checkout the [diesel webpage](https://diesel.rs) for9//! longer guides about diesel10//!11//! Checkout the [crates.io source code](https://github.com/rust-lang/crates.io/)12//! for a real world application using axum and diesel1314use axum::{15    extract::{FromRef, FromRequestParts, State},16    http::{request::Parts, StatusCode},17    response::Json,18    routing::{get, post},19    Router,20};21use diesel::prelude::*;22use diesel_async::{23    pooled_connection::{bb8, AsyncDieselConnectionManager},24    AsyncMigrationHarness, AsyncPgConnection, RunQueryDsl,25};26use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};27use std::net::SocketAddr;28use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};2930pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();3132// normally part of your generated schema.rs file33table! {34    users (id) {35        id -> Integer,36        name -> Text,37        hair_color -> Nullable<Text>,38    }39}4041#[derive(serde::Serialize, HasQuery)]42struct User {43    id: i32,44    name: String,45    hair_color: Option<String>,46}4748#[derive(serde::Deserialize, Insertable)]49#[diesel(table_name = users)]50struct NewUser {51    name: String,52    hair_color: Option<String>,53}5455type Pool = bb8::Pool<AsyncPgConnection>;5657#[tokio::main]58async fn main() {59    tracing_subscriber::registry()60        .with(61            tracing_subscriber::EnvFilter::try_from_default_env()62                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),63        )64        .with(tracing_subscriber::fmt::layer())65        .init();6667    let db_url = std::env::var("DATABASE_URL").unwrap();6869    // set up connection pool70    let config = AsyncDieselConnectionManager::<diesel_async::AsyncPgConnection>::new(db_url);71    let pool = bb8::Pool::builder().build(config).await.unwrap();7273    let mut harness = AsyncMigrationHarness::new(pool.get_owned().await.unwrap());74    harness.run_pending_migrations(MIGRATIONS).unwrap();7576    // build our application with some routes77    let app = Router::new()78        .route("/user/list", get(list_users))79        .route("/user/create", post(create_user))80        .with_state(pool);8182    // run it with hyper83    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));84    tracing::debug!("listening on {addr}");85    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();86    axum::serve(listener, app).await;87}8889async fn create_user(90    State(pool): State<Pool>,91    Json(new_user): Json<NewUser>,92) -> Result<Json<User>, (StatusCode, String)> {93    let mut conn = pool.get().await.map_err(internal_error)?;9495    let res = diesel::insert_into(users::table)96        .values(new_user)97        .returning(User::as_returning())98        .get_result(&mut conn)99        .await100        .map_err(internal_error)?;101    Ok(Json(res))102}103104// we can also write a custom extractor that grabs a connection from the pool105// which setup is appropriate depends on your application106struct DatabaseConnection(bb8::PooledConnection<'static, AsyncPgConnection>);107108impl<S> FromRequestParts<S> for DatabaseConnection109where110    S: Send + Sync,111    Pool: FromRef<S>,112{113    type Rejection = (StatusCode, String);114115    async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {116        let pool = Pool::from_ref(state);117118        let conn = pool.get_owned().await.map_err(internal_error)?;119120        Ok(Self(conn))121    }122}123124async fn list_users(125    DatabaseConnection(mut conn): DatabaseConnection,126) -> Result<Json<Vec<User>>, (StatusCode, String)> {127    let res = User::query()128        .load(&mut conn)129        .await130        .map_err(internal_error)?;131    Ok(Json(res))132}133134/// Utility function for mapping any error into a `500 Internal Server Error`135/// response.136fn internal_error<E>(err: E) -> (StatusCode, String)137where138    E: std::error::Error,139{140    (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())141}