Skip to content

Update dependencies of the examples #3931

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions examples/postgres/axum-social-with-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ edition = "2021"

[dependencies]
# Primary crates
axum = { version = "0.5.13", features = ["macros"] }
axum = { version = "0.8.4", features = ["macros"] }
sqlx = { path = "../../../", features = [ "runtime-tokio", "tls-rustls-ring", "postgres", "time", "uuid" ] }
tokio = { version = "1.20.1", features = ["rt-multi-thread", "macros"] }

# Important secondary crates
argon2 = "0.4.1"
rand = "0.8.5"
argon2 = "0.5.3"
rand = "0.9.1"
regex = "1.6.0"
serde = "1.0.140"
serde_with = { version = "2.0.0", features = ["time_0_3"] }
serde_with = { version = "3.14.0", features = ["time_0_3"] }
time = "0.3.11"
uuid = { version = "1.1.2", features = ["serde"] }
validator = { version = "0.16.0", features = ["derive"] }
validator = { version = "0.20.0", features = ["derive"] }

# Auxilliary crates
anyhow = "1.0.58"
Expand All @@ -29,4 +29,5 @@ tracing = "0.1.35"

[dev-dependencies]
serde_json = "1.0.82"
tower = "0.4.13"
tower = "0.5.2"
http-body-util = "0.1.3"
9 changes: 5 additions & 4 deletions examples/postgres/axum-social-with-tests/src/http/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use anyhow::Context;
use axum::{Extension, Router};
use axum::Router;
use sqlx::PgPool;
use tokio::net::TcpListener;

mod error;

Expand All @@ -15,12 +16,12 @@ pub fn app(db: PgPool) -> Router {
Router::new()
.merge(user::router())
.merge(post::router())
.layer(Extension(db))
.with_state(db)
}

pub async fn serve(db: PgPool) -> anyhow::Result<()> {
axum::Server::bind(&"0.0.0.0:8080".parse().unwrap())
.serve(app(db).into_make_service())
let listener = TcpListener::bind("0.0.0.0:8080").await?;
axum::serve(listener, app(db))
.await
.context("failed to serve API")
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use axum::extract::Path;
use axum::{Extension, Json, Router};
use axum::extract::{Path, State};
use axum::{Json, Router};

use axum::routing::get;

Expand All @@ -15,9 +15,9 @@ use crate::http::Result;
use time::format_description::well_known::Rfc3339;
use uuid::Uuid;

pub fn router() -> Router {
pub fn router() -> Router<PgPool> {
Router::new().route(
"/v1/post/:postId/comment",
"/v1/post/{postId}/comment",
get(get_post_comments).post(create_post_comment),
)
}
Expand All @@ -44,7 +44,7 @@ struct Comment {

// #[axum::debug_handler] // very useful!
async fn create_post_comment(
db: Extension<PgPool>,
db: State<PgPool>,
Path(post_id): Path<Uuid>,
Json(req): Json<CreateCommentRequest>,
) -> Result<Json<Comment>> {
Expand Down Expand Up @@ -76,7 +76,7 @@ async fn create_post_comment(

/// Returns comments in ascending chronological order.
async fn get_post_comments(
db: Extension<PgPool>,
db: State<PgPool>,
Path(post_id): Path<Uuid>,
) -> Result<Json<Vec<Comment>>> {
// Note: normally you'd want to put a `LIMIT` on this as well,
Expand Down
12 changes: 5 additions & 7 deletions examples/postgres/axum-social-with-tests/src/http/post/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use axum::{Extension, Json, Router};
use axum::extract::State;
use axum::{Json, Router};

use axum::routing::get;

Expand All @@ -16,7 +17,7 @@ use uuid::Uuid;

mod comment;

pub fn router() -> Router {
pub fn router() -> Router<PgPool> {
Router::new()
.route("/v1/post", get(get_posts).post(create_post))
.merge(comment::router())
Expand All @@ -43,10 +44,7 @@ struct Post {
}

// #[axum::debug_handler] // very useful!
async fn create_post(
db: Extension<PgPool>,
Json(req): Json<CreatePostRequest>,
) -> Result<Json<Post>> {
async fn create_post(db: State<PgPool>, Json(req): Json<CreatePostRequest>) -> Result<Json<Post>> {
req.validate()?;
let user_id = req.auth.verify(&*db).await?;

Expand All @@ -73,7 +71,7 @@ async fn create_post(
}

/// Returns posts in descending chronological order.
async fn get_posts(db: Extension<PgPool>) -> Result<Json<Vec<Post>>> {
async fn get_posts(db: State<PgPool>) -> Result<Json<Vec<Post>>> {
// Note: normally you'd want to put a `LIMIT` on this as well,
// though that would also necessitate implementing pagination.
let posts = sqlx::query_as!(
Expand Down
11 changes: 6 additions & 5 deletions examples/postgres/axum-social-with-tests/src/http/user.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use axum::extract::State;
use axum::http::StatusCode;
use axum::{routing::post, Extension, Json, Router};
use axum::{routing::post, Json, Router};
use rand::Rng;
use regex::Regex;
use std::{sync::LazyLock, time::Duration};
Expand All @@ -13,7 +14,7 @@ use crate::http::{Error, Result};

pub type UserId = Uuid;

pub fn router() -> Router {
pub fn router() -> Router<PgPool> {
Router::new().route("/v1/user", post(create_user))
}

Expand All @@ -24,15 +25,15 @@ static USERNAME_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[0-9A-Za
#[derive(Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct UserAuth {
#[validate(length(min = 3, max = 16), regex = "USERNAME_REGEX")]
#[validate(length(min = 3, max = 16), regex(path = USERNAME_REGEX))]
username: String,
#[validate(length(min = 8, max = 32))]
password: String,
}

// WARNING: this API has none of the checks that a normal user signup flow implements,
// such as email or phone verification.
async fn create_user(db: Extension<PgPool>, Json(req): Json<UserAuth>) -> Result<StatusCode> {
async fn create_user(db: State<PgPool>, Json(req): Json<UserAuth>) -> Result<StatusCode> {
req.validate()?;

let UserAuth { username, password } = req;
Expand Down Expand Up @@ -84,7 +85,7 @@ impl UserAuth {

// Sleep a random amount of time to avoid leaking existence of a user in timing.
let sleep_duration =
rand::thread_rng().gen_range(Duration::from_millis(100)..=Duration::from_millis(500));
rand::rng().random_range(Duration::from_millis(100)..=Duration::from_millis(500));
tokio::time::sleep(sleep_duration).await;

Err(Error::UnprocessableEntity(
Expand Down
3 changes: 2 additions & 1 deletion examples/postgres/axum-social-with-tests/src/password.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use anyhow::{anyhow, Context};
use argon2::password_hash::rand_core::OsRng;
use tokio::task;

use argon2::password_hash::SaltString;
use argon2::{password_hash, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};

pub async fn hash(password: String) -> anyhow::Result<String> {
task::spawn_blocking(move || {
let salt = SaltString::generate(rand::thread_rng());
let salt = SaltString::generate(&mut OsRng);
Ok(Argon2::default()
.hash_password(password.as_bytes(), &salt)
.map_err(|e| anyhow!(e).context("failed to hash password"))?
Expand Down
19 changes: 8 additions & 11 deletions examples/postgres/axum-social-with-tests/tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// This is imported by different tests that use different functions.
#![allow(dead_code)]

use axum::body::{Body, BoxBody, HttpBody};
use axum::body::Body;
use axum::http::header::CONTENT_TYPE;
use axum::http::{request, Request};
use axum::response::Response;
use http_body_util::BodyExt;
use time::format_description::well_known::Rfc3339;
use time::OffsetDateTime;
use uuid::Uuid;
Expand All @@ -27,23 +28,19 @@ impl RequestBuilderExt for request::Builder {
}
}

pub async fn response_json(resp: &mut Response<BoxBody>) -> serde_json::Value {
pub async fn response_json(resp: &mut Response) -> serde_json::Value {
assert_eq!(
resp.headers()
.get(CONTENT_TYPE)
.expect("expected Content-Type"),
"application/json"
);

let body = resp.body_mut();

let mut bytes = Vec::new();

while let Some(res) = body.data().await {
let chunk = res.expect("error reading response body");

bytes.extend_from_slice(&chunk[..]);
}
let bytes = resp
.collect()
.await
.expect("error reading response body")
.to_bytes();

serde_json::from_slice(&bytes).expect("failed to read response body as json")
}
Expand Down
6 changes: 3 additions & 3 deletions examples/postgres/chat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ workspace = "../../../"
[dependencies]
sqlx = { path = "../../../", features = [ "postgres", "runtime-tokio", "tls-native-tls" ] }
tokio = { version = "1.20.0", features = [ "rt-multi-thread", "macros" ] }
ratatui = "0.27.0"
crossterm = "0.27.0"
unicode-width = "0.1"
ratatui = "0.29.0"
crossterm = "0.29.0"
unicode-width = "0.2.0"
2 changes: 1 addition & 1 deletion examples/postgres/chat/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ This example demonstrates how to use PostgreSQL channels to create a very simple
Run the project

```
cargo run -p sqlx-examples-postgres-chat
cargo run -p sqlx-example-postgres-chat
```
6 changes: 3 additions & 3 deletions examples/postgres/chat/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl ChatApp {
]
.as_ref(),
)
.split(frame.size());
.split(frame.area());

let text = Text::from(Line::from(vec![
Span::raw("Press "),
Expand All @@ -114,12 +114,12 @@ impl ChatApp {
.style(Style::default().fg(Color::Yellow))
.block(Block::default().borders(Borders::ALL).title("Input"));
frame.render_widget(input, chunks[1]);
frame.set_cursor(
frame.set_cursor_position((
// Put cursor past the end of the input text
chunks[1].x + self.input.width() as u16 + 1,
// Move one line down, from the border to the input line
chunks[1].y + 1,
);
));

let messages =
List::new(messages).block(Block::default().borders(Borders::ALL).title("Messages"));
Expand Down
2 changes: 1 addition & 1 deletion examples/postgres/mockable-todos/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ clap = { version = "4", features = ["derive"] }
tokio = { version = "1.20.0", features = ["rt", "macros"]}
dotenvy = "0.15.0"
async-trait = "0.1.41"
mockall = "0.11"
mockall = "0.13"
2 changes: 1 addition & 1 deletion examples/postgres/mockable-todos/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ mod tests {
use super::*;
use mockall::predicate::*;

#[async_std::test]
#[tokio::test]
async fn test_mocked_add() {
let description = String::from("My todo");
let args = Args {
Expand Down
2 changes: 1 addition & 1 deletion examples/postgres/multi-database/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ tracing-subscriber = "0.3.19"

rust_decimal = "1.36.0"

rand = "0.8.5"
rand = "0.9.1"

[dependencies.sqlx]
# version = "0.9.0"
Expand Down
6 changes: 3 additions & 3 deletions examples/postgres/multi-database/accounts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ edition = "2021"
sqlx = { workspace = true, features = ["postgres", "time", "uuid", "macros", "sqlx-toml"] }
tokio = { version = "1", features = ["rt", "sync"] }

argon2 = { version = "0.5.3", features = ["password-hash"] }
argon2 = "0.5.3"
password-hash = { version = "0.5", features = ["std"] }

uuid = { version = "1", features = ["serde"] }
thiserror = "1"
rand = "0.8"
thiserror = "2"
rand = "0.9.1"

time = { version = "0.3.37", features = ["serde"] }

Expand Down
8 changes: 4 additions & 4 deletions examples/postgres/multi-database/accounts/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use argon2::{password_hash, Argon2, PasswordHasher, PasswordVerifier};
use password_hash::PasswordHashString;
use rand::distributions::{Alphanumeric, DistString};
use password_hash::{rand_core::OsRng, PasswordHashString};
use rand::distr::{Alphanumeric, SampleString};
use sqlx::PgPool;
use std::sync::Arc;
use uuid::Uuid;
Expand Down Expand Up @@ -141,7 +141,7 @@ impl AccountsManager {
// We transfer ownership to the blocking task and back to ensure Tokio doesn't spawn
// excess threads.
let (_guard, res) = tokio::task::spawn_blocking(move || {
let salt = password_hash::SaltString::generate(rand::thread_rng());
let salt = password_hash::SaltString::generate(&mut OsRng);
(
guard,
Argon2::default()
Expand Down Expand Up @@ -288,6 +288,6 @@ impl SessionToken {
const LEN: usize = 32;

fn generate() -> Self {
SessionToken(Alphanumeric.sample_string(&mut rand::thread_rng(), Self::LEN))
SessionToken(Alphanumeric.sample_string(&mut rand::rng(), Self::LEN))
}
}
4 changes: 2 additions & 2 deletions examples/postgres/multi-database/payments/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use accounts::{AccountId, AccountsManager};
use accounts::AccountId;
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use sqlx::{Acquire, PgConnection, PgPool, Postgres};
use sqlx::PgPool;
use time::OffsetDateTime;
use uuid::Uuid;

Expand Down
6 changes: 3 additions & 3 deletions examples/postgres/multi-database/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use accounts::AccountsManager;
use color_eyre::eyre;
use color_eyre::eyre::{Context, OptionExt};
use payments::PaymentsManager;
use rand::distributions::{Alphanumeric, DistString};
use rand::distr::{Alphanumeric, SampleString};
use sqlx::Connection;

#[tokio::main]
Expand Down Expand Up @@ -42,11 +42,11 @@ async fn main() -> eyre::Result<()> {

// POST /account
let user_email = format!("user{}@example.com", rand::random::<u32>());
let user_password = Alphanumeric.sample_string(&mut rand::thread_rng(), 16);
let user_password = Alphanumeric.sample_string(&mut rand::rng(), 16);

// Requires an externally managed transaction in case any application-specific records
// should be created after the actual account record.
let mut txn = conn.begin().await?;
let txn = conn.begin().await?;

let account_id = accounts
// Takes ownership of the password string because it's sent to another thread for hashing.
Expand Down
2 changes: 1 addition & 1 deletion examples/postgres/multi-tenant/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ tracing-subscriber = "0.3.19"

rust_decimal = "1.36.0"

rand = "0.8.5"
rand = "0.9.1"

[dependencies.sqlx]
# version = "0.9.0"
Expand Down
4 changes: 2 additions & 2 deletions examples/postgres/multi-tenant/accounts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ argon2 = { version = "0.5.3", features = ["password-hash"] }
password-hash = { version = "0.5", features = ["std"] }

uuid = { version = "1", features = ["serde"] }
thiserror = "1"
rand = "0.8"
thiserror = "2"
rand = "0.9.1"

time = { version = "0.3.37", features = ["serde"] }

Expand Down
Loading
Loading