diff --git a/diesel/src/pg/expression/functions.rs b/diesel/src/pg/expression/functions.rs index 9e349534b5f4..5eb92d4046f8 100644 --- a/diesel/src/pg/expression/functions.rs +++ b/diesel/src/pg/expression/functions.rs @@ -1500,3 +1500,49 @@ define_sql_function! { /// ``` fn to_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, Jsonb, Text, Nullable}; + /// # let connection = &mut establish_connection(); + /// let result = diesel::select(to_jsonb::(1)) + /// .get_result::(connection)?; + /// + /// assert_eq!(json!(1), result); + /// + /// let result = diesel::select(to_jsonb::, _>(vec!["abc", "def"])) + /// .get_result::(connection)?; + /// + /// assert_eq!(json!(["abc", "def"]), result); + /// + /// let result = diesel::select(to_jsonb::>, _>(Vec::::new())) + /// .get_result::(connection)?; + /// + /// assert_eq!(json!([]), result); + /// + /// let result = diesel::select(to_jsonb::, _>(None::)) + /// .get_result::>(connection)?; + /// + /// assert!(result.is_none()); + /// + /// # Ok(()) + /// # } + /// ``` + fn to_jsonb>(e: E) -> E::Out; +} diff --git a/diesel/src/pg/expression/helper_types.rs b/diesel/src/pg/expression/helper_types.rs index 9e26a0f9329e..fd199cc4d026 100644 --- a/diesel/src/pg/expression/helper_types.rs +++ b/diesel/src/pg/expression/helper_types.rs @@ -471,3 +471,8 @@ pub type array_shuffle = super::functions::array_shuffle, A>; #[allow(non_camel_case_types)] #[cfg(feature = "postgres_backend")] pub type to_json = super::functions::to_json, E>; + +/// Return type of [`to_jsonb(element)`](super::functions::to_jsonb()) +#[allow(non_camel_case_types)] +#[cfg(feature = "postgres_backend")] +pub type to_jsonb = super::functions::to_jsonb, E>; diff --git a/diesel_derives/tests/auto_type.rs b/diesel_derives/tests/auto_type.rs index c7d0e2a96761..170af4a6265a 100644 --- a/diesel_derives/tests/auto_type.rs +++ b/diesel_derives/tests/auto_type.rs @@ -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), ) }