Skip to content

Instantly share code, notes, and snippets.

@pollend
Created October 21, 2025 04:16
Show Gist options
  • Select an option

  • Save pollend/3550ef01dcb9274a04c53047941f57f2 to your computer and use it in GitHub Desktop.

Select an option

Save pollend/3550ef01dcb9274a04c53047941f57f2 to your computer and use it in GitHub Desktop.
macro_rules! db_id {
($type: ty,$name:ident) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type, Hash)]
#[sqlx(transparent)]
pub struct $name(pub $type);
impl $name {
pub fn new(id: $type) -> Self {
Self(id)
}
}
impl From<$type> for $name {
fn from(value: $type) -> Self {
$name(value)
}
}
impl From<$name> for $type {
fn from(value: $name) -> Self {
value.0
}
}
impl ser::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
<$type>::serialize(&self.0, serializer)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let id = <$type>::deserialize(deserializer)?;
Ok(Self(id))
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment