Add more JsonRawValue encode/decode impls. (#3859)

* Add support for `Box<JsonRawValue>` types.

This allows keeping structs that implement FromRow lifetime-free,
previously you had to use `&'a JsonRawValue`.

```rust
struct Foo {
    bar: Box<JsonRawValue>,
}
```

* Add Encode impls for `JsonRawValue`.
This commit is contained in:
Dario Nieuwenhuis 2025-08-26 01:40:26 +02:00 committed by GitHub
parent 99ec41913c
commit 648250dc6d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 67 additions and 2 deletions

View File

@ -196,8 +196,59 @@ where
}
}
// We don't have to implement Encode for JsonRawValue because that's covered by the default
// implementation for Encode
impl<DB> Type<DB> for Box<JsonRawValue>
where
for<'a> Json<&'a Self>: Type<DB>,
DB: Database,
{
fn type_info() -> DB::TypeInfo {
<Json<&Self> as Type<DB>>::type_info()
}
fn compatible(ty: &DB::TypeInfo) -> bool {
<Json<&Self> as Type<DB>>::compatible(ty)
}
}
impl<'q, DB> Encode<'q, DB> for JsonRawValue
where
for<'a> Json<&'a Self>: Encode<'q, DB>,
DB: Database,
{
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, BoxDynError> {
<Json<&Self> as Encode<'q, DB>>::encode(Json(self), buf)
}
}
impl<'q, DB> Encode<'q, DB> for &'q JsonRawValue
where
for<'a> Json<&'a Self>: Encode<'q, DB>,
DB: Database,
{
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, BoxDynError> {
<Json<&Self> as Encode<'q, DB>>::encode(Json(self), buf)
}
}
impl<'q, DB> Encode<'q, DB> for Box<JsonRawValue>
where
for<'a> Json<&'a Self>: Encode<'q, DB>,
DB: Database,
{
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, BoxDynError> {
<Json<&Self> as Encode<'q, DB>>::encode(Json(self), buf)
}
}
impl<'r, DB> Decode<'r, DB> for &'r JsonRawValue
where
Json<Self>: Decode<'r, DB>,
@ -207,3 +258,13 @@ where
<Json<Self> as Decode<DB>>::decode(value).map(|item| item.0)
}
}
impl<'r, DB> Decode<'r, DB> for Box<JsonRawValue>
where
Json<Self>: Decode<'r, DB>,
DB: Database,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
<Json<Self> as Decode<DB>>::decode(value).map(|item| item.0)
}
}

View File

@ -468,7 +468,9 @@ mod json {
.await?;
let value: &JsonRawValue = row.try_get(0)?;
assert_eq!(value.get(), "{\"hello\": \"world\"}");
let value: Box<JsonRawValue> = row.try_get(0)?;
assert_eq!(value.get(), "{\"hello\": \"world\"}");
// prepared, binary API
@ -477,7 +479,9 @@ mod json {
.await?;
let value: &JsonRawValue = row.try_get(0)?;
assert_eq!(value.get(), "{\"hello\": \"world\"}");
let value: Box<JsonRawValue> = row.try_get(0)?;
assert_eq!(value.get(), "{\"hello\": \"world\"}");
Ok(())