Skip to content

Conversation

@dprkh
Copy link

@dprkh dprkh commented Dec 15, 2025

Does your PR solve an issue?

#2833

Is this a breaking change?

This is a new feature without breaking changes.


This PR adds ability to experience the pleasure of writing code like as follows.

use anyhow::*;

use derive_more::Display;

use serde::{Deserialize, Serialize};

use sqlx::Type;

#[derive(Clone, PartialEq, Display, Deserialize, Serialize, Type)]
#[serde(try_from = "String")]
#[sqlx(try_from = "String")]
pub struct Id(String);

impl TryFrom<String> for Id {
    type Error = Error;

    fn try_from(value: String) -> Result<Self> {
        if value.len() != 36 {
            bail!("user id length must be 36");
        }

        let id = Self(value);

        Ok(id)
    }
}
#[get("/api/users", database: Extension<Database>)]
async fn get_users() -> Result<Vec<(user::Id, user::Name)>, anyhow::Error> {
    sqlx::query(include_str!("./queries/get_users.sql"))
        .fetch_all(database.pool())
        .await
        .context("failed to execute query `get_users`")?
        .into_iter()
        .map(|row| {
            Ok::<_, anyhow::Error>((
                row.try_get::<user::Id, _>(0)
                    .context("failed to decode user id")?,
                row.try_get::<user::Name, _>(1)
                    .context("failed to decode user name")?,
            ))
        })
        .try_collect()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant