1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use backend::Backend;
use expression::{
    AppearsOnTable, AsExpressionList, Expression, NonAggregate, SelectableExpression,
};
use query_builder::{AstPass, QueryFragment};
use sql_types;
use std::marker::PhantomData;

/// An ARRAY[...] literal.
#[derive(Debug, Clone, Copy, QueryId)]
pub struct ArrayLiteral<T, ST> {
    elements: T,
    _marker: PhantomData<ST>,
}

/// Creates an `ARRAY[...]` expression.
///
/// The argument should be a tuple of expressions which can be represented by the
/// same SQL type.
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate diesel;
/// # 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 = establish_connection();
/// let ints = diesel::select(array::<Integer, _>((1, 2)))
///     .get_result::<Vec<i32>>(&connection)?;
/// assert_eq!(vec![1, 2], ints);
///
/// let ids = users.select(array((id, id * 2)))
///     .get_results::<Vec<i32>>(&connection)?;
/// let expected = vec![
///     vec![1, 2],
///     vec![2, 4],
/// ];
/// assert_eq!(expected, ids);
/// #     Ok(())
/// # }
/// ```
pub fn array<ST, T>(elements: T) -> ArrayLiteral<T::Expression, ST>
where
    T: AsExpressionList<ST>,
{
    ArrayLiteral {
        elements: elements.as_expression_list(),
        _marker: PhantomData,
    }
}

impl<T, ST> Expression for ArrayLiteral<T, ST>
where
    T: Expression,
{
    type SqlType = sql_types::Array<ST>;
}

impl<T, ST, DB> QueryFragment<DB> for ArrayLiteral<T, ST>
where
    DB: Backend,
    for<'a> (&'a T): QueryFragment<DB>,
{
    fn walk_ast(&self, mut out: AstPass<DB>) -> ::result::QueryResult<()> {
        out.push_sql("ARRAY[");
        QueryFragment::walk_ast(&&self.elements, out.reborrow())?;
        out.push_sql("]");
        Ok(())
    }
}

impl<T, ST, QS> SelectableExpression<QS> for ArrayLiteral<T, ST>
where
    T: SelectableExpression<QS>,
    ArrayLiteral<T, ST>: AppearsOnTable<QS>,
{
}

impl<T, ST, QS> AppearsOnTable<QS> for ArrayLiteral<T, ST>
where
    T: AppearsOnTable<QS>,
    ArrayLiteral<T, ST>: Expression,
{
}

impl<T, ST> NonAggregate for ArrayLiteral<T, ST>
where
    T: NonAggregate,
    ArrayLiteral<T, ST>: Expression,
{
}