diesel::pg::expression::dsl

Function array_sample

source
pub fn array_sample<Arr: ArrayOrNullableArray + SingleValue, array, n>(
    array: array,
    n: n,
) -> array_sample<Arr, array, n>
where array: AsExpression<Arr>, n: AsExpression<Integer>,
Available on crate feature postgres_backend only.
Expand description

Returns an array of n items randomly selected from array. n may not exceed the length of the array.

ยงExample


let vec = vec![1,2,3,4,5];
let sampled = diesel::select(array_sample::<Array<Integer>, _, _>(vec.clone(),3))
    .get_result::<Vec<i32>>(connection)?;
assert_eq!(3, sampled.len());
assert!(sampled.iter().all(|x| vec.contains(x)));

let vec: Vec<i32> = Vec::new();
let sampled = diesel::select(array_sample::<Array<Integer>, _, _>(vec,0))
    .get_result::<Vec<i32>>(connection)?;
assert_eq!(0, sampled.len());

let sampled = diesel::select(array_sample::<Nullable<Array<Integer>>, _, _>(None::<Vec<i32>>,1))
    .get_result::<Option<Vec<i32>>>(connection)?;
assert!(sampled.is_none());