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]
name = "shwatchit"
version = "0.1.0"
name = "witch_watch"
version = "0.0.1"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
axum = "0.5"
askama = "0.11"
axum = { version = "0.6", features = ["macros", "tracing"] }
askama = { version = "0.12", features = ["with-axum"] }
askama_axum = "0.3"
axum-macros = "0.3"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tower = { version = "0.4", features = ["util", "timeout"] }
tower-http = { version = "0.2", features = ["add-extension", "trace"] }
uuid = { version = "0.8", features = ["serde", "v4"] }
tower-http = { version = "0.4", features = ["add-extension", "trace"] }
uuid = { version = "1.3", features = ["serde", "v4"] }
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.
//!
//! 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.
//! Example of application using <https://github.com/launchbadge/sqlx>
//!
//! Run with
//!
//! ```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::{
collections::HashMap,
net::SocketAddr,
sync::{Arc, RwLock},
time::Duration,
};
use std::{net::SocketAddr, time::Duration};
use axum::{
error_handling::HandleErrorLayer,
extract::{Extension, Path, Query},
http::StatusCode,
response::IntoResponse,
routing::{get, patch},
Json, Router,
async_trait,
extract::{FromRef, FromRequestParts, State},
http::{request::Parts, StatusCode},
routing::get,
Router,
};
use serde::{Deserialize, Serialize};
use tower::{BoxError, ServiceBuilder};
use tower_http::trace::TraceLayer;
use sqlx::{
sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions},
types::uuid::adapter::Hyphenated,
};
use tokio::net::TcpListener;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use uuid::Uuid;
mod form;
mod template;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG")
.unwrap_or_else(|_| "example_todos=debug,tower_http=debug".into()),
))
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_tokio_postgres=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.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()
.route("/todos", get(todos_index).post(todos_create))
.route("/todos/:id", patch(todos_update).delete(todos_delete))
.route("/greet/:name", get(template::greet))
.route("/", get(form::show_form).post(form::accept_form))
// Add middleware to all routes
.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(),
);
.route(
"/",
get(using_connection_pool_extractor).post(using_connection_extractor),
)
.with_state(pool);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
// run it with hyper
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();
axum::Server::bind(&SocketAddr::from(([0, 0, 0, 0], 3000)))
.serve(app.into_make_service())
.await
.unwrap();
}
// The query parameters for todos index
#[derive(Debug, Deserialize, Default)]
pub struct Pagination {
pub offset: Option<usize>,
pub limit: Option<usize>,
// we can extract the connection pool with `State`
async fn using_connection_pool_extractor(
State(pool): State<SqlitePool>,
) -> Result<String, (StatusCode, String)> {
sqlx::query_scalar("select 'hello world from pg'")
.fetch_one(&pool)
.await
.map_err(internal_error)
}
async fn todos_index(
pagination: Option<Query<Pagination>>,
Extension(db): Extension<Db>,
) -> impl IntoResponse {
let todos = db.read().unwrap();
// 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::Sqlite>);
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
.values()
.skip(pagination.offset.unwrap_or(0))
.take(pagination.limit.unwrap_or(usize::MAX))
.cloned()
.collect::<Vec<_>>();
async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let pool = SqlitePool::from_ref(state);
Json(todos)
}
let conn = pool.acquire().await.map_err(internal_error)?;
#[derive(Debug, Deserialize)]
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
Ok(Self(conn))
}
}
type Db = Arc<RwLock<HashMap<Uuid, Todo>>>;
#[derive(Debug, Serialize, Clone)]
struct Todo {
id: Uuid,
text: String,
completed: bool,
async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
let mut conn = conn;
sqlx::query_scalar("select 'hello world from pg'")
.fetch_one(&mut conn)
.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())
}