From 5b53bb1294b04728c82ff5db305deed38d66ec1f Mon Sep 17 00:00:00 2001 From: Oleg Gushul Date: Sat, 31 Aug 2024 09:51:41 +0200 Subject: [PATCH] implement array_shuffle --- diesel/src/pg/expression/functions.rs | 27 ++++++++++++++++++++++++ diesel/src/pg/expression/helper_types.rs | 5 +++++ diesel_derives/tests/auto_type.rs | 1 + 3 files changed, 33 insertions(+) diff --git a/diesel/src/pg/expression/functions.rs b/diesel/src/pg/expression/functions.rs index f7efce2a5c74..008550e5cc13 100644 --- a/diesel/src/pg/expression/functions.rs +++ b/diesel/src/pg/expression/functions.rs @@ -1423,3 +1423,30 @@ define_sql_function! { /// ``` fn array_upper(array: Arr, dimension: Integer) -> Nullable; } + +#[cfg(feature = "postgres_backend")] +define_sql_function! { + /// Randomly shuffles the first dimension of the array. + /// + /// # Example + /// + /// ```rust + /// # include!("../../doctest_setup.rs"); + /// # + /// # fn main() { + /// # run_test().unwrap(); + /// # } + /// # + /// # fn run_test() -> QueryResult<()> { + /// # use diesel::dsl::array_shuffle; + /// # use diesel::sql_types::{Array, Integer}; + /// # let connection = &mut establish_connection(); + /// let shuffled = diesel::select(array_shuffle::, _>(vec![1, 2, 3, 4, 5])) + /// .get_result::>(connection)?; + /// assert_eq!(5, shuffled.len()); + /// assert!(shuffled != vec![1, 2, 3, 4, 5]); // It's very unlikely to get the same order + /// # Ok(()) + /// # } + /// ``` + fn array_shuffle(array: Arr) -> Arr; +} diff --git a/diesel/src/pg/expression/helper_types.rs b/diesel/src/pg/expression/helper_types.rs index 63c5ddac9bd9..41d2161f474b 100644 --- a/diesel/src/pg/expression/helper_types.rs +++ b/diesel/src/pg/expression/helper_types.rs @@ -461,3 +461,8 @@ pub type array_positions = #[allow(non_camel_case_types)] #[cfg(feature = "postgres_backend")] pub type array_ndims = super::functions::array_ndims, A>; + +/// Return type of [`array_shuffle(array)`](super::functions::array_shuffle()) +#[allow(non_camel_case_types)] +#[cfg(feature = "postgres_backend")] +pub type array_shuffle = super::functions::array_shuffle, A>; diff --git a/diesel_derives/tests/auto_type.rs b/diesel_derives/tests/auto_type.rs index e0d853b23c6f..c6dab81b4026 100644 --- a/diesel_derives/tests/auto_type.rs +++ b/diesel_derives/tests/auto_type.rs @@ -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), + array_shuffle(pg_extras::array), ) }