diesel::pg::expression::dsl

Function jsonb_set

Source
pub fn jsonb_set<E: JsonbOrNullableJsonb + SingleValue, Arr: TextArrayOrNullableTextArray + CombinedNullableValue<E, Jsonb>, base, path, new_value>(
    base: base,
    path: path,
    new_value: new_value,
) -> jsonb_set<E, Arr, base, path, new_value>
where base: AsExpression<E>, path: AsExpression<Arr>, new_value: AsExpression<E>,
Available on crate feature postgres_backend only.
Expand description

Returns target with the item designated by path replaced by new_value, or with new_value added 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, 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


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);

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());