use sqlx example

This commit is contained in:
Joe Ardent 2023-04-25 22:19:49 -07:00
parent e63248da73
commit 15a5249cda
3 changed files with 1499 additions and 426 deletions

1683
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,17 +1,18 @@
[package] [package]
name = "shwatchit" name = "witch_watch"
version = "0.1.0" version = "0.0.1"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
axum = "0.5" axum = { version = "0.6", features = ["macros", "tracing"] }
askama = "0.11" askama = { version = "0.12", features = ["with-axum"] }
askama_axum = "0.3"
axum-macros = "0.3"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
tracing = "0.1" tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tower = { version = "0.4", features = ["util", "timeout"] } tower = { version = "0.4", features = ["util", "timeout"] }
tower-http = { version = "0.2", features = ["add-extension", "trace"] } tower-http = { version = "0.4", features = ["add-extension", "trace"] }
uuid = { version = "0.8", features = ["serde", "v4"] } uuid = { version = "1.3", features = ["serde", "v4"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
sqlx = { version = "0.5.10", features = ["runtime-tokio-rustls", "any", "sqlite", "chrono", "time", "uuid"] }

View file

@ -1,176 +1,119 @@
//! Provides a RESTful web server managing some Todos. //! Example of application using <https://github.com/launchbadge/sqlx>
//!
//! API will be:
//!
//! - `GET /todos`: return a JSON list of Todos.
//! - `POST /todos`: create a new Todo.
//! - `PUT /todos/:id`: update a specific Todo.
//! - `DELETE /todos/:id`: delete a specific Todo.
//! //!
//! Run with //! Run with
//! //!
//! ```not_rust //! ```not_rust
//! cargo run -p example-todos //! cargo run -p example-sqlx-postgres
//! ```
//!
//! Test with curl:
//!
//! ```not_rust
//! curl 127.0.0.1:3000
//! curl -X POST 127.0.0.1:3000
//! ``` //! ```
use std::{ use std::{net::SocketAddr, time::Duration};
collections::HashMap,
net::SocketAddr,
sync::{Arc, RwLock},
time::Duration,
};
use axum::{ use axum::{
error_handling::HandleErrorLayer, async_trait,
extract::{Extension, Path, Query}, extract::{FromRef, FromRequestParts, State},
http::StatusCode, http::{request::Parts, StatusCode},
response::IntoResponse, routing::get,
routing::{get, patch}, Router,
Json, Router,
}; };
use serde::{Deserialize, Serialize}; use sqlx::{
use tower::{BoxError, ServiceBuilder}; sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions},
use tower_http::trace::TraceLayer; types::uuid::adapter::Hyphenated,
};
use tokio::net::TcpListener;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use uuid::Uuid;
mod form;
mod template;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
tracing_subscriber::registry() tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new( .with(
std::env::var("RUST_LOG") tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_todos=debug,tower_http=debug".into()), .unwrap_or_else(|_| "example_tokio_postgres=debug".into()),
)) )
.with(tracing_subscriber::fmt::layer()) .with(tracing_subscriber::fmt::layer())
.init(); .init();
let db = Db::default(); let db_connection_str = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres:password@localhost".to_string());
// Compose the routes // setup connection pool
let pool = SqlitePoolOptions::new()
.max_connections(5)
.connect_timeout(Duration::from_secs(3))
.connect(&db_connection_str)
.await
.expect("can't connect to database");
// build our application with some routes
let app = Router::new() let app = Router::new()
.route("/todos", get(todos_index).post(todos_create)) .route(
.route("/todos/:id", patch(todos_update).delete(todos_delete)) "/",
.route("/greet/:name", get(template::greet)) get(using_connection_pool_extractor).post(using_connection_extractor),
.route("/", get(form::show_form).post(form::accept_form)) )
// Add middleware to all routes .with_state(pool);
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|error: BoxError| async move {
if error.is::<tower::timeout::error::Elapsed>() {
Ok(StatusCode::REQUEST_TIMEOUT)
} else {
Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
))
}
}))
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http())
.layer(Extension(db))
.into_inner(),
);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); // run it with hyper
tracing::debug!("listening on {}", addr); let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::Server::bind(&addr) tracing::debug!("listening on {}", listener.local_addr().unwrap());
//axum::serve(listener, app).await.unwrap();
axum::Server::bind(&SocketAddr::from(([0, 0, 0, 0], 3000)))
.serve(app.into_make_service()) .serve(app.into_make_service())
.await .await
.unwrap(); .unwrap();
} }
// The query parameters for todos index // we can extract the connection pool with `State`
#[derive(Debug, Deserialize, Default)] async fn using_connection_pool_extractor(
pub struct Pagination { State(pool): State<SqlitePool>,
pub offset: Option<usize>, ) -> Result<String, (StatusCode, String)> {
pub limit: Option<usize>, sqlx::query_scalar("select 'hello world from pg'")
.fetch_one(&pool)
.await
.map_err(internal_error)
} }
async fn todos_index( // we can also write a custom extractor that grabs a connection from the pool
pagination: Option<Query<Pagination>>, // which setup is appropriate depends on your application
Extension(db): Extension<Db>, struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Sqlite>);
) -> impl IntoResponse {
let todos = db.read().unwrap();
let Query(pagination) = pagination.unwrap_or_default(); #[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
where
SqlitePool: FromRef<S>,
S: Send + Sync,
{
type Rejection = (StatusCode, String);
let todos = todos async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
.values() let pool = SqlitePool::from_ref(state);
.skip(pagination.offset.unwrap_or(0))
.take(pagination.limit.unwrap_or(usize::MAX))
.cloned()
.collect::<Vec<_>>();
Json(todos) let conn = pool.acquire().await.map_err(internal_error)?;
}
#[derive(Debug, Deserialize)] Ok(Self(conn))
struct CreateTodo {
text: String,
}
async fn todos_create(
Json(input): Json<CreateTodo>,
Extension(db): Extension<Db>,
) -> impl IntoResponse {
let todo = Todo {
id: Uuid::new_v4(),
text: input.text,
completed: false,
};
db.write().unwrap().insert(todo.id, todo.clone());
(StatusCode::CREATED, Json(todo))
}
#[derive(Debug, Deserialize)]
struct UpdateTodo {
text: Option<String>,
completed: Option<bool>,
}
async fn todos_update(
Path(id): Path<Uuid>,
Json(input): Json<UpdateTodo>,
Extension(db): Extension<Db>,
) -> Result<impl IntoResponse, StatusCode> {
let mut todo = db
.read()
.unwrap()
.get(&id)
.cloned()
.ok_or(StatusCode::NOT_FOUND)?;
if let Some(text) = input.text {
todo.text = text;
}
if let Some(completed) = input.completed {
todo.completed = completed;
}
db.write().unwrap().insert(todo.id, todo.clone());
Ok(Json(todo))
}
async fn todos_delete(Path(id): Path<Uuid>, Extension(db): Extension<Db>) -> impl IntoResponse {
if db.write().unwrap().remove(&id).is_some() {
StatusCode::NO_CONTENT
} else {
StatusCode::NOT_FOUND
} }
} }
type Db = Arc<RwLock<HashMap<Uuid, Todo>>>; async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection,
#[derive(Debug, Serialize, Clone)] ) -> Result<String, (StatusCode, String)> {
struct Todo { let mut conn = conn;
id: Uuid, sqlx::query_scalar("select 'hello world from pg'")
text: String, .fetch_one(&mut conn)
completed: bool, .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())
} }