1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/// Implement a named wrapper type around a UUID
#[macro_export]
macro_rules! uuid_val {
    ($name:ident, $ns:ident) => {
        /// Wrapper type around a UUIDv5 for a given namespace.  These types are
        /// parseable from either the UUIDv5 string representation, or from the
        /// name itself, as they are 1-1.
        #[derive(
            Debug,
            Clone,
            Copy,
            Hash,
            PartialEq,
            Eq,
            PartialOrd,
            Ord,
            serde::Serialize,
            serde_with::DeserializeFromStr,
        )]
        #[cfg_attr(feature = "juniper", derive(juniper::GraphQLScalar))]
        #[cfg_attr(feature = "netidx", derive(netidx_derive::Pack))]
        #[cfg_attr(feature = "netidx", derive(derive::FromValue))]
        pub struct $name(pub uuid::Uuid);

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.0)
            }
        }

        impl std::str::FromStr for $name {
            type Err = anyhow::Error;

            fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
                match s.parse::<uuid::Uuid>() {
                    Ok(uuid) => Ok(Self(uuid)),
                    Err(_) => Ok(Self::from(s)),
                }
            }
        }

        /// Implement From<AsRef<str>> for a UUIDv5, using a given namespace
        impl<S: AsRef<str>> From<S> for $name {
            fn from(s: S) -> Self {
                Self(Uuid::new_v5(&$ns, s.as_ref().as_bytes()))
            }
        }

        impl std::ops::Deref for $name {
            type Target = uuid::Uuid;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl std::borrow::Borrow<uuid::Uuid> for $name {
            fn borrow(&self) -> &uuid::Uuid {
                &self.0
            }
        }

        #[cfg(feature = "juniper")]
        impl $name {
            fn to_output<S: juniper::ScalarValue>(&self) -> juniper::Value<S> {
                juniper::Value::scalar(self.0.to_string())
            }

            fn from_input<S>(v: &juniper::InputValue<S>) -> Result<Self, String>
            where
                S: juniper::ScalarValue,
            {
                v.as_string_value()
                    .map(|s| <Self as std::str::FromStr>::from_str(s))
                    .ok_or_else(|| format!("Expected `String`, found: {v}"))?
                    .map(|uuid| Self(*uuid))
                    .map_err(|e| e.to_string())
            }

            fn parse_token<S>(
                value: juniper::ScalarToken<'_>,
            ) -> juniper::ParseScalarResult<S>
            where
                S: juniper::ScalarValue,
            {
                <String as juniper::ParseScalarValue<S>>::from_str(value)
            }
        }

        impl schemars::JsonSchema for $name {
            fn schema_name() -> String {
                format!("{}", stringify!($name)).to_string()
            }

            fn json_schema(
                gen: &mut schemars::gen::SchemaGenerator,
            ) -> schemars::schema::Schema {
                uuid::Uuid::json_schema(gen)
            }
        }

        #[cfg(feature = "rusqlite")]
        impl rusqlite::ToSql for $name {
            fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
                use rusqlite::types::{ToSqlOutput, Value};
                Ok(ToSqlOutput::Owned(Value::Text(self.to_string())))
            }
        }

        impl tokio_postgres::types::ToSql for $name {
            tokio_postgres::types::to_sql_checked!();

            fn to_sql(
                &self,
                ty: &tokio_postgres::types::Type,
                out: &mut bytes::BytesMut,
            ) -> Result<
                tokio_postgres::types::IsNull,
                Box<dyn std::error::Error + Sync + Send>,
            > {
                self.0.to_sql(ty, out)
            }

            fn accepts(ty: &tokio_postgres::types::Type) -> bool {
                Uuid::accepts(ty)
            }
        }

        impl<'a> tokio_postgres::types::FromSql<'a> for $name {
            fn from_sql(
                ty: &tokio_postgres::types::Type,
                raw: &'a [u8],
            ) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
                Uuid::from_sql(ty, raw).map($name)
            }

            fn accepts(ty: &tokio_postgres::types::Type) -> bool {
                Uuid::accepts(ty)
            }
        }
    };
}