custom_arrays/model/protocol_type/
mod.rs

1use diesel::deserialize::{FromSql, FromSqlRow};
2use diesel::expression::AsExpression;
3use diesel::pg::{Pg, PgValue};
4use diesel::serialize::{IsNull, Output, ToSql};
5use diesel::sql_types::SqlType;
6use diesel::{deserialize, serialize};
7use std::io::Write;
8
9//  Diesel type mapping requires a struct to derive a SqlType for custom ToSql and FromSql implementations
10#[derive(SqlType)]
11#[diesel(sql_type = protocol_type)]
12#[diesel(postgres_type(name = "protocol_type", schema = "smdb"))]
13pub struct PgProtocolType;
14
15#[derive(Debug, Clone, FromSqlRow, AsExpression, PartialEq, Eq)]
16#[diesel(sql_type = PgProtocolType)]
17#[allow(clippy::upper_case_acronyms)]
18pub enum ProtocolType {
19    UnknownProtocol,
20    GRPC,
21    HTTP,
22    UDP,
23}
24
25impl ToSql<PgProtocolType, Pg> for ProtocolType {
26    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
27        match *self {
28            ProtocolType::UnknownProtocol => out.write_all(b"UnknownProtocol")?,
29            ProtocolType::GRPC => out.write_all(b"GRPC")?,
30            ProtocolType::HTTP => out.write_all(b"HTTP")?,
31            ProtocolType::UDP => out.write_all(b"UDP")?,
32        }
33        Ok(IsNull::No)
34    }
35}
36
37impl FromSql<PgProtocolType, Pg> for ProtocolType {
38    fn from_sql(bytes: PgValue<'_>) -> deserialize::Result<Self> {
39        match bytes.as_bytes() {
40            b"UnknownProtocol" => Ok(ProtocolType::UnknownProtocol),
41            b"GRPC" => Ok(ProtocolType::GRPC),
42            b"HTTP" => Ok(ProtocolType::HTTP),
43            b"UDP" => Ok(ProtocolType::UDP),
44            _ => Err(format!(
45                "Unrecognized enum variant: {:?}",
46                String::from_utf8_lossy(bytes.as_bytes())
47            )
48            .into()),
49        }
50    }
51}