Add JSON support to FromRow derive (#2121)

* Add `json` attribute to `FromRow` derive

* Add docs and fix formatting
This commit is contained in:
Marco Cameriero
2023-07-31 21:52:42 +02:00
committed by GitHub
parent 84f21e99ef
commit 9463b7592f
4 changed files with 166 additions and 30 deletions

View File

@@ -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<Self, Error>;
}