From e46c146cb12ac618c9d7aef655a01c48c0834308 Mon Sep 17 00:00:00 2001 From: Marco Cameriero Date: Mon, 17 Jul 2023 12:16:46 +0200 Subject: [PATCH] Add docs and fix formatting --- sqlx-core/src/from_row.rs | 45 +++++++++++++++++++++++++++-- sqlx-macros-core/src/derives/row.rs | 2 +- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/sqlx-core/src/from_row.rs b/sqlx-core/src/from_row.rs index 82ebd9c98e..509e289525 100644 --- a/sqlx-core/src/from_row.rs +++ b/sqlx-core/src/from_row.rs @@ -1,5 +1,4 @@ -use crate::error::Error; -use crate::row::Row; +use crate::{error::Error, row::Row}; /// A record that can be built from a row returned by the database. /// @@ -210,6 +209,48 @@ use crate::row::Row; /// /// In MySql, `BigInt` type matches `i64`, but you can convert it to `u64` by `try_from`. /// +/// #### `json` +/// +/// If your database supports a JSON type, you can leverage `#[sqlx(json)]` +/// to automatically integrate JSON deserialization in your [`FromRow`] implementation using [`serde`](https://docs.rs/serde/latest/serde/). +/// +/// ```rust,ignore +/// #[derive(serde::Deserialize)] +/// struct Data { +/// field1: String, +/// field2: u64 +/// } +/// +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// #[sqlx(json)] +/// metadata: Data +/// } +/// ``` +/// +/// Given a query like the following: +/// +/// ```sql +/// SELECT +/// 1 AS id, +/// 'Name' AS name, +/// JSON_OBJECT('field1', 'value1', 'field2', 42) AS metadata +/// ``` +/// +/// The `metadata` field will be deserialized used its `serde::Deserialize` implementation: +/// +/// ```rust,ignore +/// User { +/// id: 1, +/// name: "Name", +/// metadata: Data { +/// field1: "value1", +/// field2: 42 +/// } +/// } +/// ``` pub trait FromRow<'r, R: Row>: Sized { fn from_row(row: &'r R) -> Result; } diff --git a/sqlx-macros-core/src/derives/row.rs b/sqlx-macros-core/src/derives/row.rs index 69563156a6..7b92f56c9d 100644 --- a/sqlx-macros-core/src/derives/row.rs +++ b/sqlx-macros-core/src/derives/row.rs @@ -123,7 +123,7 @@ fn expand_derive_from_row_struct( predicates .push(parse_quote!(::sqlx::types::Json<#try_from>: ::sqlx::decode::Decode<#lifetime, R::Database>)); predicates.push(parse_quote!(::sqlx::types::Json<#try_from>: ::sqlx::types::Type)); - + parse_quote!( row.try_get::<::sqlx::types::Json<_>, _>(#id_s).and_then(|v| <#ty as ::std::convert::TryFrom::<#try_from>>::try_from(v.0)