Skip to content

Commit 9502253

Browse files
committed
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>, } ```
1 parent 92c3845 commit 9502253

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

sqlx-core/src/types/json.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,20 @@ where
196196
}
197197
}
198198

199+
impl<DB> Type<DB> for Box<JsonRawValue>
200+
where
201+
for<'a> Json<&'a Self>: Type<DB>,
202+
DB: Database,
203+
{
204+
fn type_info() -> DB::TypeInfo {
205+
<Json<&Self> as Type<DB>>::type_info()
206+
}
207+
208+
fn compatible(ty: &DB::TypeInfo) -> bool {
209+
<Json<&Self> as Type<DB>>::compatible(ty)
210+
}
211+
}
212+
199213
// We don't have to implement Encode for JsonRawValue because that's covered by the default
200214
// implementation for Encode
201215
impl<'r, DB> Decode<'r, DB> for &'r JsonRawValue
@@ -207,3 +221,13 @@ where
207221
<Json<Self> as Decode<DB>>::decode(value).map(|item| item.0)
208222
}
209223
}
224+
225+
impl<'r, DB> Decode<'r, DB> for Box<JsonRawValue>
226+
where
227+
Json<Self>: Decode<'r, DB>,
228+
DB: Database,
229+
{
230+
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
231+
<Json<Self> as Decode<DB>>::decode(value).map(|item| item.0)
232+
}
233+
}

tests/postgres/types.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,9 @@ mod json {
465465
.await?;
466466

467467
let value: &JsonRawValue = row.try_get(0)?;
468+
assert_eq!(value.get(), "{\"hello\": \"world\"}");
468469

470+
let value: Box<JsonRawValue> = row.try_get(0)?;
469471
assert_eq!(value.get(), "{\"hello\": \"world\"}");
470472

471473
// prepared, binary API
@@ -474,7 +476,9 @@ mod json {
474476
.await?;
475477

476478
let value: &JsonRawValue = row.try_get(0)?;
479+
assert_eq!(value.get(), "{\"hello\": \"world\"}");
477480

481+
let value: Box<JsonRawValue> = row.try_get(0)?;
478482
assert_eq!(value.get(), "{\"hello\": \"world\"}");
479483

480484
Ok(())

0 commit comments

Comments
 (0)