-
BackendPostgreSQL Diesel version2.3.0 Diesel FeaturesOperating System VersionMac Third party librariesirrelevant What do you want to do?what works: #[diesel(serialize_as = DbAddress, deserialize_as = DbAddress)]
pub wallet_address: Address,what I'd like to achieve #[diesel(serialize_as = Option<DbAddress>, deserialize_as = Option<DbAddress>)]
pub wallet_address: Option<Address>,or even #[diesel(serialize_as = DbAddress, deserialize_as = DbAddress)]
pub wallet_address: Option<Address>,Compile time errorWhat code do you already have?use alloy::primitives::{Address, private::derive_more};
use derive_more::{Deref, Display, From, Into};
use diesel::{
AsExpression, FromSqlRow,
backend::Backend,
deserialize::FromSql,
pg::Pg,
serialize::{IsNull, Output, ToSql},
sql_types::Bytea,
};
use serde::{Deserialize, Serialize};
use std::{fmt::Debug, io::Write};
/// Address wrapper for diesel.
#[derive(
FromSqlRow,
AsExpression,
Serialize,
Deserialize,
Debug,
Default,
Display,
Deref,
From,
Into,
Copy,
Eq,
PartialEq,
Clone,
Hash,
)]
#[diesel(sql_type = Bytea)]
pub struct DbAddress(pub Address);
impl ToSql<Bytea, Pg> for DbAddress {
fn to_sql<'b>(
&'b self,
out: &mut Output<'b, '_, Pg>,
) -> diesel::serialize::Result {
// Write the Address as a byte slice to the SQL output
out.write_all(self.0.as_slice())?;
Ok(IsNull::No)
}
}
impl FromSql<Bytea, Pg> for DbAddress {
fn from_sql(
bytes: <Pg as Backend>::RawValue<'_>,
) -> diesel::deserialize::Result<Self> {
// Extract the raw bytes from the SQL value
let byte_data: &[u8] = bytes.as_bytes();
// Validate that the data consists of exactly 20 bytes
if byte_data.len() != 20 {
return Err(Box::from(
"Failed to deserialize DbAddress: Expected 20 bytes but got a different length",
));
}
// Convert the byte slice into an Address
Ok(Self(Address::from_slice(byte_data)))
}
}Additional detailsThe code that's already there is irrelevant, it seems that serialize_as/deserialize_as is broken for any kind of Option pair. Checklist
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
|
Your assessment that this attribute is broken for any option type is wrong. You just need to have a existing What does not woraus converting from an option to an option type. That's a language limitation and nothing diesel can fix. If you have opinions about that please contact the rust project instead. |
Beta Was this translation helpful? Give feedback.
Your assessment that this attribute is broken for any option type is wrong. You just need to have a existing
TryFromimpl between both types. That can be done by for example using a custom non-option new type on one side.What does not woraus converting from an option to an option type. That's a language limitation and nothing diesel can fix. If you have opinions about that please contact the rust project instead.