use crate::dsl; use crate::expression::array_comparison::{AsInExpression, InExpression}; use crate::expression::subselect::Subselect; use crate::expression::{ AppearsOnTable, AsExpression, Expression, SelectableExpression, TypedExpressionType, ValidGrouping, }; use crate::pg::Pg; use crate::query_builder::combination_clause::CombinationClause; use crate::query_builder::{ AstPass, BoxedSelectStatement, QueryFragment, QueryId, SelectQuery, SelectStatement, }; use crate::sql_types::{self, SqlType}; use std::marker::PhantomData; /// Creates an `ARRAY[e1, e2, ...]` or `ARRAY(subselect)` expression. /// /// The argument should be a tuple of expressions which can be represented by the /// same SQL type, or a subquery. /// /// # Examples /// /// ```rust /// # include!("../../doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # use diesel::dsl::array; /// # use diesel::sql_types::Integer; /// # let connection = &mut establish_connection(); /// let ints = diesel::select(array::((1, 2))).get_result::>(connection)?; /// assert_eq!(vec![1, 2], ints); /// /// let ids = users /// .select(array((id, id * 2))) /// .get_results::>(connection)?; /// let expected = vec![vec![1, 2], vec![2, 4]]; /// assert_eq!(expected, ids); /// /// let ids = diesel::select(array(users.select(id))).first::>(connection)?; /// assert_eq!(vec![1, 2], ids); /// # Ok(()) /// # } /// ``` pub fn array(elements: T) -> dsl::array where T: IntoArrayExpression, ST: SqlType + TypedExpressionType, { elements.into_array_expression() } /// Return type of [`array(tuple_or_subselect)`](super::dsl::array()) #[allow(non_camel_case_types)] #[cfg(feature = "postgres_backend")] pub type array = >::ArrayExpression; /// Trait for types which can be converted into an expression of type `Array` /// /// This includes tuples of expressions with the same SQL type, and subselects with a single column. #[diagnostic::on_unimplemented( message = "cannot convert `{Self}` into an expression of type `Array<{ST}>`", note = "`the trait bound `{Self}: IntoArrayExpression<{ST}>` is not satisfied. \ (`AsExpressionList` is a deprecated trait alias for `IntoArrayExpression`)" )] pub trait IntoArrayExpression { /// Type of the expression returned by [IntoArrayExpression::into_array_expression] type ArrayExpression: Expression>; /// Construct the diesel query dsl representation of /// the `ARRAY (values)` clause for the given type fn into_array_expression(self) -> Self::ArrayExpression; } /// Implement as a no-op for expressions that were already arrays (that is, don't wrap in ARRAY[]). impl IntoArrayExpression for T where T: AsExpression>, ST: SqlType + TypedExpressionType + 'static, { type ArrayExpression = >>::Expression; fn into_array_expression(self) -> Self::ArrayExpression { >>::as_expression(self) } } // This has to be implemented for each tuple directly because an intermediate trait would cause // conflicting impls. (Compiler says people could implement AsExpression for // SelectStatement) // This is not implemented with other tuple impls because this is feature-flagged by // `postgres-backend` macro_rules! tuple_impls { ($( $Tuple:tt { $(($idx:tt) -> $T:ident, $ST:ident, $TT:ident,)+ } )+) => { $( impl<$($T,)+ ST> IntoArrayExpression for ($($T,)+) where $($T: AsExpression,)+ ST: SqlType + TypedExpressionType, { type ArrayExpression = ArrayLiteral<($($T::Expression,)+), ST>; fn into_array_expression(self) -> Self::ArrayExpression { ArrayLiteral { elements: ($(self.$idx.as_expression(),)+), _marker: PhantomData, } } } )+ } } diesel_derives::__diesel_for_each_tuple!(tuple_impls); /// An ARRAY[...] literal. #[derive(Debug, Clone, Copy, QueryId)] pub struct ArrayLiteral { elements: T, _marker: PhantomData, } impl Expression for ArrayLiteral where ST: 'static, T: Expression, { type SqlType = sql_types::Array; } impl QueryFragment for ArrayLiteral where T: QueryFragment, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Pg>) -> crate::result::QueryResult<()> { out.push_sql("ARRAY["); QueryFragment::walk_ast(&self.elements, out.reborrow())?; out.push_sql("]"); Ok(()) } } impl SelectableExpression for ArrayLiteral where T: SelectableExpression, ArrayLiteral: AppearsOnTable, { } impl AppearsOnTable for ArrayLiteral where T: AppearsOnTable, ArrayLiteral: Expression, { } impl ValidGrouping for ArrayLiteral where T: ValidGrouping, { type IsAggregate = T::IsAggregate; } impl InExpression for ArrayLiteral where Self: Expression>, ST: SqlType, { type SqlType = ST; fn is_empty(&self) -> bool { false } fn is_array(&self) -> bool { // we want to use the `= ANY(_)` syntax false } } impl AsInExpression for ArrayLiteral where Self: Expression>, ST: SqlType, { type InExpression = Self; fn as_in_expression(self) -> Self::InExpression { self } } impl IntoArrayExpression for SelectStatement where ST: SqlType + TypedExpressionType, ArraySubselect: Expression>, Self: SelectQuery, { type ArrayExpression = ArraySubselect; fn into_array_expression(self) -> Self::ArrayExpression { ArraySubselect::new(self) } } impl<'a, ST, QS, DB, GB> IntoArrayExpression for BoxedSelectStatement<'a, ST, QS, DB, GB> where ST: SqlType + TypedExpressionType, ArraySubselect, ST>: Expression>, { type ArrayExpression = ArraySubselect; fn into_array_expression(self) -> Self::ArrayExpression { ArraySubselect::new(self) } } impl IntoArrayExpression for CombinationClause where ST: SqlType + TypedExpressionType, Self: SelectQuery, ArraySubselect: Expression>, { type ArrayExpression = ArraySubselect; fn into_array_expression(self) -> Self::ArrayExpression { ArraySubselect::new(self) } } /// An ARRAY(...) subselect. #[derive(Debug, Clone, Copy, QueryId)] pub struct ArraySubselect { subquery: Subselect, } impl ArraySubselect { pub(crate) fn new(elements: T) -> Self { Self { subquery: Subselect::new(elements), } } } impl Expression for ArraySubselect where ST: 'static, Subselect: Expression, { type SqlType = sql_types::Array; } impl QueryFragment for ArraySubselect where Subselect: QueryFragment, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Pg>) -> crate::result::QueryResult<()> { out.push_sql("ARRAY("); QueryFragment::walk_ast(&self.subquery, out.reborrow())?; out.push_sql(")"); Ok(()) } } impl SelectableExpression for ArraySubselect where Subselect: SelectableExpression, ArraySubselect: AppearsOnTable, { } impl AppearsOnTable for ArraySubselect where Subselect: AppearsOnTable, ArraySubselect: Expression, { } impl ValidGrouping for ArraySubselect where Subselect: ValidGrouping, { type IsAggregate = as ValidGrouping>::IsAggregate; } impl InExpression for ArraySubselect where Self: Expression>, ST: SqlType, { type SqlType = ST; fn is_empty(&self) -> bool { false } fn is_array(&self) -> bool { // we want to use the `= ANY(_)` syntax false } } impl AsInExpression for ArraySubselect where Self: Expression>, ST: SqlType, { type InExpression = Self; fn as_in_expression(self) -> Self::InExpression { self } }