mirror of
https://github.com/launchbadge/sqlx.git
synced 2026-04-15 08:50:23 +00:00
Add JSON support to FromRow derive (#2121)
* Add `json` attribute to `FromRow` derive * Add docs and fix formatting
This commit is contained in:
@@ -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>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user