phonograph/phono-models/src/macros.rs
2025-11-19 02:14:43 +00:00

50 lines
1.4 KiB
Rust

/// Generates code for a `with_id()` method. The `sql` parameter should be a
/// Postgres query which accepts the UUID as its only argument.
///
/// ## Example
///
/// ```ignore
/// use uuid::Uuid;
///
/// struct Test {
/// id: Uuid;
/// }
///
/// with_id_query!(Test, sql = "select id from tests where id = $1");
/// ```
macro_rules! with_id_query {
($target:ty, sql = $sql:expr $(,)?) => {
impl $target {
/// Build a single-field query by ID.
pub fn with_id(id: uuid::Uuid) -> WithIdQuery {
WithIdQuery { id }
}
}
#[derive(Clone, Copy, Debug)]
pub struct WithIdQuery {
id: uuid::Uuid,
}
impl WithIdQuery {
pub async fn fetch_one(
self,
app_db: &mut crate::client::AppDbClient,
) -> sqlx::Result<$target> {
query_as!($target, $sql, self.id)
.fetch_one(app_db.get_conn())
.await
}
pub async fn fetch_optional(
self,
app_db: &mut crate::client::AppDbClient,
) -> sqlx::Result<Option<$target>> {
query_as!($target, $sql, self.id)
.fetch_optional(app_db.get_conn())
.await
}
}
};
}
pub(crate) use with_id_query;