Skip to content

Commit

Permalink
Merge pull request #4229 from aznszn/add_to_json
Browse files Browse the repository at this point in the history
added `to_json` function
  • Loading branch information
weiznich authored Sep 4, 2024
2 parents 576f3cf + df57cf5 commit f95f06d
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 3 deletions.
19 changes: 16 additions & 3 deletions diesel/src/pg/expression/expression_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
pub(in crate::pg) use self::private::{
ArrayOrNullableArray, InetOrCidr, JsonIndex, JsonOrNullableJsonOrJsonbOrNullableJsonb,
JsonRemoveIndex, JsonbOrNullableJsonb, MultirangeOrNullableMultirange,
JsonRemoveIndex, JsonbOrNullableJsonb, MaybeNullableValue, MultirangeOrNullableMultirange,
MultirangeOrRangeMaybeNullable, RangeHelper, RangeOrNullableRange, TextOrNullableText,
};
use super::date_and_time::{AtTimeZone, DateTimeLike};
Expand Down Expand Up @@ -3417,8 +3417,8 @@ where

pub(in crate::pg) mod private {
use crate::sql_types::{
Array, Binary, Cidr, Inet, Integer, Json, Jsonb, Multirange, Nullable, Range, SingleValue,
SqlType, Text,
Array, Binary, Cidr, Inet, Integer, Json, Jsonb, MaybeNullableType, Multirange, Nullable,
Range, SingleValue, SqlType, Text,
};
use crate::{Expression, IntoSql};

Expand Down Expand Up @@ -3699,4 +3699,17 @@ pub(in crate::pg) mod private {

impl BinaryOrNullableBinary for Binary {}
impl BinaryOrNullableBinary for Nullable<Binary> {}

pub trait MaybeNullableValue<T>: SingleValue {
type Out: SingleValue;
}

impl<T, O> MaybeNullableValue<O> for T
where
T: SingleValue,
T::IsNull: MaybeNullableType<O>,
<T::IsNull as MaybeNullableType<O>>::Out: SingleValue,
{
type Out = <T::IsNull as MaybeNullableType<O>>::Out;
}
}
47 changes: 47 additions & 0 deletions diesel/src/pg/expression/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use super::expression_methods::InetOrCidr;
use crate::expression::functions::define_sql_function;
use crate::pg::expression::expression_methods::ArrayOrNullableArray;
use crate::pg::expression::expression_methods::MaybeNullableValue;
use crate::pg::expression::expression_methods::MultirangeOrNullableMultirange;
use crate::pg::expression::expression_methods::MultirangeOrRangeMaybeNullable;
use crate::pg::expression::expression_methods::RangeOrNullableRange;
Expand Down Expand Up @@ -1423,3 +1424,49 @@ define_sql_function! {
/// ```
fn array_upper<Arr: ArrayOrNullableArray + SingleValue>(array: Arr, dimension: Integer) -> Nullable<Integer>;
}

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

/// Return type of [`to_json(element)`](super::functions::to_json())
#[allow(non_camel_case_types)]
#[cfg(feature = "postgres_backend")]
pub type to_json<E> = super::functions::to_json<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 @@ -432,6 +432,7 @@ fn postgres_functions() -> _ {
array_position_with_subscript(pg_extras::array, pg_extras::id, pg_extras::id),
array_positions(pg_extras::array, pg_extras::id),
array_ndims(pg_extras::array),
to_json(pg_extras::id),
)
}

Expand Down

0 comments on commit f95f06d

Please sign in to comment.