Skip to content

Commit

Permalink
feat: implement to_jsonb function
Browse files Browse the repository at this point in the history
  • Loading branch information
wowinter13 committed Sep 7, 2024
1 parent 158f113 commit 5ba6172
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
46 changes: 46 additions & 0 deletions diesel/src/pg/expression/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1500,3 +1500,49 @@ define_sql_function! {
/// ```
fn to_json<E: MaybeNullableValue<Json>>(e: E) -> E::Out;
}

#[cfg(feature = "postgres_backend")]
define_sql_function! {
/// Converts any SQL value to jsonb
///
/// # 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::to_jsonb;
/// # use serde_json::{json, Value};
/// # use diesel::sql_types::{Integer, Array, Json, Jsonb, Text, Nullable};
/// # let connection = &mut establish_connection();
/// let result = diesel::select(to_jsonb::<Integer, _>(1))
/// .get_result::<Value>(connection)?;
///
/// assert_eq!(json!(1), result);
///
/// let result = diesel::select(to_jsonb::<Array<Text>, _>(vec!["abc", "xyz"]))
/// .get_result::<Value>(connection)?;
///
/// assert_eq!(json!(["abc", "xyz"]), result);
///
/// let result = diesel::select(to_jsonb::<Array<Nullable<Text>>, _>(Vec::<String>::new()))
/// .get_result::<Value>(connection)?;
///
/// assert_eq!(json!([]), result);
///
/// let result = diesel::select(to_jsonb::<Nullable<Text>, _>(None::<String>))
/// .get_result::<Option<Value>>(connection)?;
///
/// assert!(result.is_none());
///
/// # Ok(())
/// # }
/// ```
fn to_jsonb<E: MaybeNullableValue<Jsonb>>(e: E) -> E::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 @@ -471,3 +471,8 @@ pub type array_shuffle<A> = super::functions::array_shuffle<SqlTypeOf<A>, A>;
#[allow(non_camel_case_types)]
#[cfg(feature = "postgres_backend")]
pub type to_json<E> = super::functions::to_json<SqlTypeOf<E>, E>;

/// Return type of [`to_jsonb(element)`](super::functions::to_jsonb())
#[allow(non_camel_case_types)]
#[cfg(feature = "postgres_backend")]
pub type to_jsonb<E> = super::functions::to_jsonb<SqlTypeOf<E>, E>;
1 change: 1 addition & 0 deletions diesel_derives/tests/auto_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ fn postgres_functions() -> _ {
array_ndims(pg_extras::array),
array_shuffle(pg_extras::array),
to_json(pg_extras::id),
to_jsonb(pg_extras::id),
)
}

Expand Down

0 comments on commit 5ba6172

Please sign in to comment.