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