Skip to content
Myr

main.rs

This file

Path

examples/diesel-postgres/src/main.rs

129 lines · 3.6 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//! ```not_rust4//! cargo run -p example-diesel-postgres5//! ```6//!7//! Checkout the [diesel webpage](https://diesel.rs) for8//! longer guides about diesel9//!10//! Checkout the [crates.io source code](https://github.com/rust-lang/crates.io/)11//! for a real world application using axum and diesel1213use axum::{14    extract::State,15    http::StatusCode,16    response::Json,17    routing::{get, post},18    Router,19};20use diesel::prelude::*;21use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};22use std::net::SocketAddr;23use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};2425// this embeds the migrations into the application binary26// the migration path is relative to the `CARGO_MANIFEST_DIR`27pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations/");2829// normally part of your generated schema.rs file30table! {31    users (id) {32        id -> Integer,33        name -> Text,34        hair_color -> Nullable<Text>,35    }36}3738#[derive(serde::Serialize, HasQuery)]39struct User {40    id: i32,41    name: String,42    hair_color: Option<String>,43}4445#[derive(serde::Deserialize, Insertable)]46#[diesel(table_name = users)]47struct NewUser {48    name: String,49    hair_color: Option<String>,50}5152#[tokio::main]53async fn main() {54    tracing_subscriber::registry()55        .with(56            tracing_subscriber::EnvFilter::try_from_default_env()57                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),58        )59        .with(tracing_subscriber::fmt::layer())60        .init();6162    let db_url = std::env::var("DATABASE_URL").unwrap();6364    // set up connection pool65    let manager = deadpool_diesel::postgres::Manager::new(db_url, deadpool_diesel::Runtime::Tokio1);66    let pool = deadpool_diesel::postgres::Pool::builder(manager)67        .build()68        .unwrap();6970    // run the migrations on server startup71    {72        let conn = pool.get().await.unwrap();73        conn.interact(|conn| conn.run_pending_migrations(MIGRATIONS).map(|_| ()))74            .await75            .unwrap()76            .unwrap();77    }7879    // build our application with some routes80    let app = Router::new()81        .route("/user/list", get(list_users))82        .route("/user/create", post(create_user))83        .with_state(pool);8485    // run it with hyper86    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));87    tracing::debug!("listening on {addr}");88    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();89    axum::serve(listener, app).await;90}9192async fn create_user(93    State(pool): State<deadpool_diesel::postgres::Pool>,94    Json(new_user): Json<NewUser>,95) -> Result<Json<User>, (StatusCode, String)> {96    let conn = pool.get().await.map_err(internal_error)?;97    let res = conn98        .interact(|conn| {99            diesel::insert_into(users::table)100                .values(new_user)101                .returning(User::as_returning())102                .get_result(conn)103        })104        .await105        .map_err(internal_error)?106        .map_err(internal_error)?;107    Ok(Json(res))108}109110async fn list_users(111    State(pool): State<deadpool_diesel::postgres::Pool>,112) -> Result<Json<Vec<User>>, (StatusCode, String)> {113    let conn = pool.get().await.map_err(internal_error)?;114    let res = conn115        .interact(|conn| User::query().load(conn))116        .await117        .map_err(internal_error)?118        .map_err(internal_error)?;119    Ok(Json(res))120}121122/// Utility function for mapping any error into a `500 Internal Server Error`123/// response.124fn internal_error<E>(err: E) -> (StatusCode, String)125where126    E: std::error::Error,127{128    (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())129}