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 100 101 102 103 104 105 106 107 108 109 110 111
use backend::Backend; use query_builder::*; use result::QueryResult; use super::Expression; use types::BigInt; /// Creates a SQL `COUNT` expression /// /// As with most bare functions, this is not exported by default. You can import /// it specifically as `diesel::expression::count`, or glob import /// `diesel::expression::dsl::*` /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate diesel; /// # include!("src/doctest_setup.rs"); /// # use diesel::expression::dsl::*; /// # /// # table! { /// # users { /// # id -> Integer, /// # name -> VarChar, /// # } /// # } /// # /// # fn main() { /// # use self::animals::dsl::*; /// # let connection = establish_connection(); /// assert_eq!(Ok(1), animals.select(count(name)).first(&connection)); /// # } /// ``` pub fn count<T: Expression>(t: T) -> Count<T> { Count { target: t, } } /// Creates a SQL `COUNT(*)` expression /// /// For selecting the count of a query, and nothing else, you can just call /// [`count`](http://docs.diesel.rs/diesel/prelude/trait.CountDsl.html#method.count) /// on the query instead. /// /// As with most bare functions, this is not exported by default. You can import /// it specifically as `diesel::expression::count_star`, or glob import /// `diesel::expression::dsl::*` /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate diesel; /// # include!("src/doctest_setup.rs"); /// # use diesel::expression::dsl::*; /// # /// # table! { /// # users { /// # id -> Integer, /// # name -> VarChar, /// # } /// # } /// # /// # fn main() { /// # use self::users::dsl::*; /// # let connection = establish_connection(); /// assert_eq!(Ok(2), users.select(count_star()).first(&connection)); /// # } /// ``` pub fn count_star() -> CountStar { CountStar } #[derive(Debug, Clone, Copy)] #[doc(hidden)] pub struct Count<T> { target: T, } impl<T: Expression> Expression for Count<T> { type SqlType = BigInt; } impl<T: QueryFragment<DB>, DB: Backend> QueryFragment<DB> for Count<T> { fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> { out.push_sql("COUNT("); self.target.walk_ast(out.reborrow())?; out.push_sql(")"); Ok(()) } } impl_query_id!(Count<T>); impl_selectable_expression!(Count<T>); #[derive(Debug, Clone, Copy)] #[doc(hidden)] pub struct CountStar; impl Expression for CountStar { type SqlType = BigInt; } impl<DB: Backend> QueryFragment<DB> for CountStar { fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> { out.push_sql("COUNT(*)"); Ok(()) } } impl_query_id!(CountStar); impl_selectable_expression!(CountStar);