Skip to main content

diesel/expression/functions/
date_and_time.rs

1use crate::backend::Backend;
2use crate::expression::coerce::Coerce;
3use crate::expression::functions::declare_sql_function;
4use crate::expression::{AsExpression, Expression, ValidGrouping};
5use crate::query_builder::*;
6use crate::result::QueryResult;
7use crate::sql_types::*;
8
9/// Represents the SQL `CURRENT_TIMESTAMP` constant. This is equivalent to the
10/// `NOW()` function on backends that support it.
11#[allow(non_camel_case_types)]
12#[derive(Debug, Copy, Clone, QueryId, ValidGrouping)]
13pub struct now;
14
15impl Expression for now {
16    type SqlType = Timestamp;
17}
18
19impl<DB: Backend> QueryFragment<DB> for now {
20    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
21        out.push_sql("CURRENT_TIMESTAMP");
22        Ok(())
23    }
24}
25
26impl_selectable_expression!(now);
27
28operator_allowed!(now, Add, add);
29operator_allowed!(now, Sub, sub);
30
31#[declare_sql_function]
32extern "SQL" {
33    /// Represents the SQL `DATE` function. The argument should be a Timestamp
34    /// expression, and the return value will be an expression of type Date.
35    ///
36    /// # Examples
37    ///
38    /// ```
39    /// # include!("../../doctest_setup.rs");
40    /// # use diesel::dsl::{now, date};
41    /// # use diesel::deserialize::Queryable;
42    /// #
43    /// # fn test<R: Queryable<diesel::sql_types::Date, DB> + 'static>() -> QueryResult<R> {
44    /// #     let connection = &mut establish_connection();
45    /// let today = diesel::select(date(now)).first(connection)?;
46    /// #     Ok(today)
47    /// # }
48    /// # fn main() {
49    /// #
50    /// # }
51    /// ```
52    fn date(expr: Timestamp) -> Date;
53}
54
55/// Implements `AsExpression<$sql_type>` for `$expr`, `&$expr` and `&&$expr`, each
56/// coercing `$expr` to `$sql_type`.
57///
58/// The reference impls mirror the `&T` and `&&T` impls that `#[derive(AsExpression)]`
59/// generates: `#[derive(AsChangeset)]` on a struct also implements `AsChangeset` for a
60/// reference to it, built from references to its fields. Passing a struct by reference
61/// to `.set()`, as batch updates do, therefore needs `&now` for a `now` field and
62/// `&&now` for a `&now` field.
63macro_rules! coerce_as_expression {
64    ($expr:ident => $sql_type:ty) => {
65        impl AsExpression<$sql_type> for $expr {
66            type Expression = Coerce<$expr, $sql_type>;
67
68            fn as_expression(self) -> Self::Expression {
69                Coerce::new(self)
70            }
71        }
72
73        impl AsExpression<$sql_type> for &$expr {
74            type Expression = Coerce<$expr, $sql_type>;
75
76            fn as_expression(self) -> Self::Expression {
77                Coerce::new(*self)
78            }
79        }
80
81        impl AsExpression<$sql_type> for &&$expr {
82            type Expression = Coerce<$expr, $sql_type>;
83
84            fn as_expression(self) -> Self::Expression {
85                Coerce::new(**self)
86            }
87        }
88    };
89}
90
91coerce_as_expression!(now => Nullable<Timestamp>);
92
93#[cfg(feature = "postgres_backend")]
94coerce_as_expression!(now => Timestamptz);
95
96#[cfg(feature = "postgres_backend")]
97coerce_as_expression!(now => Nullable<Timestamptz>);
98
99#[cfg(feature = "__sqlite-shared")]
100coerce_as_expression!(now => TimestamptzSqlite);
101
102#[cfg(feature = "__sqlite-shared")]
103coerce_as_expression!(now => Nullable<TimestamptzSqlite>);
104
105/// Represents the SQL `CURRENT_DATE` constant.
106#[allow(non_camel_case_types)]
107#[derive(Debug, Copy, Clone, QueryId, ValidGrouping)]
108pub struct today;
109
110impl Expression for today {
111    type SqlType = Date;
112}
113
114impl<DB: Backend> QueryFragment<DB> for today {
115    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
116        out.push_sql("CURRENT_DATE");
117        Ok(())
118    }
119}
120
121impl_selectable_expression!(today);
122
123operator_allowed!(today, Add, add);
124operator_allowed!(today, Sub, sub);
125
126coerce_as_expression!(today => Nullable<Date>);