diesel/expression/
count.rs

1use super::Expression;
2use backend::Backend;
3use query_builder::*;
4use result::QueryResult;
5use sql_types::BigInt;
6
7sql_function! {
8    /// Creates a SQL `COUNT` expression
9    ///
10    /// As with most bare functions, this is not exported by default. You can import
11    /// it specifically as `diesel::dsl::count`, or glob import
12    /// `diesel::dsl::*`
13    ///
14    /// # Examples
15    ///
16    /// ```rust
17    /// # #[macro_use] extern crate diesel;
18    /// # include!("../doctest_setup.rs");
19    /// # use diesel::dsl::*;
20    /// #
21    /// # fn main() {
22    /// #     use schema::animals::dsl::*;
23    /// #     let connection = establish_connection();
24    /// assert_eq!(Ok(1), animals.select(count(name)).first(&connection));
25    /// # }
26    /// ```
27    #[aggregate]
28    fn count<T>(expr: T) -> BigInt;
29}
30
31/// Creates a SQL `COUNT(*)` expression
32///
33/// For selecting the count of a query, and nothing else, you can just call
34/// [`count`](../query_dsl/trait.QueryDsl.html#method.count)
35/// on the query instead.
36///
37/// As with most bare functions, this is not exported by default. You can import
38/// it specifically as `diesel::dsl::count_star`, or glob import
39/// `diesel::dsl::*`
40///
41/// # Examples
42///
43/// ```rust
44/// # #[macro_use] extern crate diesel;
45/// # include!("../doctest_setup.rs");
46/// # use diesel::dsl::*;
47/// #
48/// # fn main() {
49/// #     use schema::users::dsl::*;
50/// #     let connection = establish_connection();
51/// assert_eq!(Ok(2), users.select(count_star()).first(&connection));
52/// # }
53/// ```
54pub fn count_star() -> CountStar {
55    CountStar
56}
57
58#[derive(Debug, Clone, Copy, QueryId, DieselNumericOps)]
59#[doc(hidden)]
60pub struct CountStar;
61
62impl Expression for CountStar {
63    type SqlType = BigInt;
64}
65
66impl<DB: Backend> QueryFragment<DB> for CountStar {
67    fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
68        out.push_sql("COUNT(*)");
69        Ok(())
70    }
71}
72
73impl_selectable_expression!(CountStar);