From a3bdb4e328f279ff4f5a69564cba0264f1f4410c Mon Sep 17 00:00:00 2001 From: Troy Benson Date: Mon, 15 Jan 2024 16:46:48 +0000 Subject: [PATCH] feat(types): add support for prost messages Adds a wrapper type for prost messages to help deserialize bytea values directly into the protobuf structure. --- postgres-types/Cargo.toml | 2 ++ postgres-types/src/lib.rs | 6 ++++++ postgres-types/src/prost_012.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 postgres-types/src/prost_012.rs diff --git a/postgres-types/Cargo.toml b/postgres-types/Cargo.toml index cfd083637..d305b8566 100644 --- a/postgres-types/Cargo.toml +++ b/postgres-types/Cargo.toml @@ -26,6 +26,7 @@ with-uuid-0_8 = ["uuid-08"] with-uuid-1 = ["uuid-1"] with-time-0_2 = ["time-02"] with-time-0_3 = ["time-03"] +with-prost-0_12 = ["prost-012"] [dependencies] bytes = "1.0" @@ -52,3 +53,4 @@ uuid-1 = { version = "1.0", package = "uuid", optional = true } time-02 = { version = "0.2", package = "time", optional = true } time-03 = { version = "0.3", package = "time", default-features = false, optional = true } smol_str-01 = { version = "0.1.23", package = "smol_str", default-features = false, optional = true } +prost-012 = { version = "0.12", package = "prost", optional = true } diff --git a/postgres-types/src/lib.rs b/postgres-types/src/lib.rs index 2f02f6e5f..65d31620d 100644 --- a/postgres-types/src/lib.rs +++ b/postgres-types/src/lib.rs @@ -199,6 +199,10 @@ pub use postgres_derive::{FromSql, ToSql}; #[cfg(feature = "with-serde_json-1")] pub use crate::serde_json_1::Json; + +#[cfg(feature = "with-prost-0_12")] +pub use crate::prost_012::Protobuf; + use crate::type_gen::{Inner, Other}; #[doc(inline)] @@ -276,6 +280,8 @@ mod eui48_1; mod geo_types_06; #[cfg(feature = "with-geo-types-0_7")] mod geo_types_07; +#[cfg(feature = "with-prost-0_12")] +mod prost_012; #[cfg(feature = "with-serde_json-1")] mod serde_json_1; #[cfg(feature = "with-smol_str-01")] diff --git a/postgres-types/src/prost_012.rs b/postgres-types/src/prost_012.rs new file mode 100644 index 000000000..f2bf23547 --- /dev/null +++ b/postgres-types/src/prost_012.rs @@ -0,0 +1,28 @@ +use crate::{accepts, to_sql_checked, types, FromSql, IsNull, ToSql, Type}; +use bytes::BytesMut; +use prost_012::Message; +use std::error::Error; + +/// A wrapper type to allow for `prost::Message` types to convert to & from Postgres BYTEA values. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Protobuf(pub T); + +impl FromSql<'_> for Protobuf { + fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { + Ok(Self(T::decode(types::bytea_from_sql(raw))?)) + } + + accepts!(BYTEA); +} + +impl ToSql for Protobuf { + fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { + <&[u8] as ToSql>::to_sql(&&*self.0.encode_to_vec(), ty, w) + } + + fn accepts(ty: &Type) -> bool { + <&[u8] as ToSql>::accepts(ty) + } + + to_sql_checked!(); +}