Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add json(nullable) macro attribute #3677

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

seanaye
Copy link

@seanaye seanaye commented Jan 10, 2025

Does your PR solve an issue?

fixes #2849

This MR introduces a #[sqlx(json(nullable))] attribute which allows for the correct behaviour on

#[derive(Serialize, Deserialize)]
enum Foo {
  Bar,
  Baz
}

struct Test {
  #[sqlx(json(nullable))]
  hello: Option<Foo>
}

by allowing the underlying row value to be null

@seanaye seanaye changed the title Add json(optional) macro attribute Add json(nullable) macro attribute Jan 10, 2025
@seanaye seanaye marked this pull request as ready for review January 10, 2025 03:50
@seanaye seanaye force-pushed the seanaye/feat/json-optional branch from 0a74698 to 9c7cbab Compare January 24, 2025 03:51
@frederikhors

This comment was marked as spam.

Copy link
Collaborator

@abonander abonander left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An explanation of this feature should be added to the docs here:

/// #### `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
/// }
/// }
/// ```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

#[sqlx(json)] does not support nullable values
3 participants