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 jsonb_set support #4357

Merged
merged 8 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions diesel/src/pg/expression/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2398,3 +2398,86 @@ define_sql_function! {
J: JsonbOrNullableJsonb + CombinedAllNullableValue<Jsonb, B>
>(base: B, from_json: J) -> J::Out;
}

#[cfg(feature = "postgres_backend")]
define_sql_function! {
/// Returns target with the item designated by path replaced by new_value,
/// or with new_value added if create_if_missing is true (which is the default)
/// and the item designated by path does not exist.
///
/// It can't set path in scalar
///
/// All earlier steps in the path must exist, or the target is returned unchanged.
/// As with the path oriented operators, negative integers that appear in the path count from the end of JSON arrays.
/// If the last path step is an array index that is out of range,
/// and create_if_missing is true, the new value is added at the beginning of the array if the index is negative,
/// or at the end of the array if it is positive.
///
/// # Example
///
/// ```rust
/// # include!("../../doctest_setup.rs");
/// #
/// # fn main() {
/// # #[cfg(feature = "serde_json")]
/// # run_test().unwrap();
/// # }
/// #
/// # #[cfg(feature = "serde_json")]
/// # fn run_test() -> QueryResult<()> {
/// # use diesel::dsl::jsonb_set;
/// # use diesel::sql_types::{Jsonb,Array, Json, Nullable, Text};
/// # use serde_json::{json,Value};
/// # let connection = &mut establish_connection();
///
/// let result = diesel::select(jsonb_set::<Jsonb, Array<Text>, _, _, _>(
/// json!([{"f1":1,"f2":null},2,null,3]),
/// vec!["0","f1"],
/// json!([2,3,4])
/// )).get_result::<Value>(connection)?;
/// let expected: Value = json!([{"f1": [2, 3, 4], "f2": null}, 2, null, 3]);
/// assert_eq!(result, expected);
///
/// let result = diesel::select(jsonb_set::<Jsonb, Array<Text>, _, _, _>(
/// json!([{"odd":[2,4,6,8]}]),
/// // not vec!["odd"], cannot set path in scalar
/// vec!["0","odd"],
/// json!([1,3,5,7])
/// )).get_result::<Value>(connection)?;
/// let expected: Value = json!([{"odd":[1,3,5,7]}]);
/// assert_eq!(result, expected);
///
/// let empty:Vec<String> = Vec::new();
/// let result = diesel::select(jsonb_set::<Nullable<Jsonb>, Array<Nullable<Text>>, _, _, _>(
/// None::<Value>,
/// empty,
/// None::<Value>
/// )).get_result::<Option<Value>>(connection)?;
/// assert!(result.is_none());
///
/// let empty:Vec<String> = Vec::new();
/// let result = diesel::select(jsonb_set::<Jsonb, Array<Nullable<Text>>, _, _, _>(
/// // cannot be json!(null)
/// json!([]),
/// empty,
/// json!(null)
/// )).get_result::<Value>(connection)?;
/// let expected = json!([]);
/// assert_eq!(result, expected);
///
Copy link
Member

Choose a reason for hiding this comment

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

I'm sorry to bring that up, but the following example won't infer nullablity correctly:

    /// let result = diesel::select(jsonb_set::<Jsonb, Nullable<Array<Nullable<Text>>>, _, _, _>(
    ///         // cannot be json!(null)
    ///         json!([]),
    ///         None,
    ///         json!({"foo": 42})
    ///     )).get_result::<Value>(connection)?;

This is expected to only accept a Option<Value> as return type as the return value will be NULL in this case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for your kind instuction.
I fixed it by doing this:
before:

fn jsonb_set<
        E: JsonbOrNullableJsonb + SingleValue,
        Arr: TextArrayOrNullableTextArray + SingleValue
    >(base: E, path: Arr, new_value: E) -> E;

after:

fn jsonb_set<
        E: JsonbOrNullableJsonb + SingleValue,
        Arr: TextArrayOrNullableTextArray + CombinedNullableValue<E,Jsonb>
    >(base: E, path: Arr, new_value: E) -> Arr::Out;

Thanks for your instruction again!

/// let result = diesel::select(jsonb_set::<Jsonb, Nullable<Array<Nullable<Text>>>, _, _, _,>(
/// json!(null),
/// None::<Vec<String>>,
/// json!({"foo": 42})
/// )).get_result::<Option<Value>>(connection)?;
/// assert!(result.is_none());
///
///
/// # Ok(())
/// # }
/// ```
fn jsonb_set<
E: JsonbOrNullableJsonb + SingleValue,
Arr: TextArrayOrNullableTextArray + CombinedNullableValue<E,Jsonb>
>(base: E, path: Arr, new_value: E) -> Arr::Out;
}
5 changes: 5 additions & 0 deletions diesel/src/pg/expression/helper_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,3 +592,8 @@ pub type json_populate_record<B, J> =
#[cfg(feature = "postgres_backend")]
pub type jsonb_populate_record<B, J> =
super::functions::jsonb_populate_record<SqlTypeOf<B>, SqlTypeOf<J>, B, J>;

/// Return type of [`jsonb_set(base, path, new_value)`](super::functions::jsonb_set())
#[allow(non_camel_case_types)]
#[cfg(feature = "postgres_backend")]
pub type jsonb_set<B, J, R> = super::functions::jsonb_set<SqlTypeOf<B>, SqlTypeOf<J>, B, J, R>;
1 change: 1 addition & 0 deletions diesel_derives/tests/auto_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,7 @@ fn postgres_functions() -> _ {
row_to_json(pg_extras::record),
json_populate_record(pg_extras::record, pg_extras::json),
jsonb_populate_record(pg_extras::record, pg_extras::jsonb),
jsonb_set(pg_extras::jsonb, pg_extras::text_array, pg_extras::jsonb),
)
}

Expand Down
Loading