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(#[automatically_derived]
#[allow(non_camel_case_types)]
impl ::core::fmt::Debug for now {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "now")
    }
}Debug, #[automatically_derived]
#[allow(non_camel_case_types)]
impl ::core::marker::Copy for now { }Copy, #[automatically_derived]
#[allow(non_camel_case_types)]
impl ::core::clone::Clone for now {
    #[inline]
    fn clone(&self) -> now { *self }
}Clone, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl diesel::query_builder::QueryId for now {
            type QueryId = now<>;
            const HAS_STATIC_QUERY_ID: bool = true;
            const IS_WINDOW_FUNCTION: bool = false;
        }
    };QueryId, const _: () =
    {
        use diesel;
        impl<__GroupByClause>
            diesel::expression::ValidGrouping<__GroupByClause> for now {
            type IsAggregate = diesel::expression::is_aggregate::Never;
        }
    };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<QS> crate::expression::SelectableExpression<QS> for now where
    now: crate::expression::AppearsOnTable<QS> {}
impl<QS> crate::expression::AppearsOnTable<QS> for now where
    now: crate::expression::Expression {}impl_selectable_expression!(now);
27
28impl<Rhs> ::std::ops::Add<Rhs> for now where
    Rhs: crate::expression::AsExpression<<<now as crate::Expression>::SqlType
    as crate::sql_types::ops::Add>::Rhs> {
    type Output =
        crate::internal::table_macro::ops::Add<Self, Rhs::Expression>;
    fn add(self, __diesel_internal_rhs: Rhs) -> Self::Output {
        crate::internal::table_macro::ops::Add::new(self,
            __diesel_internal_rhs.as_expression())
    }
}operator_allowed!(now, Add, add);
29impl<Rhs> ::std::ops::Sub<Rhs> for now where
    Rhs: crate::expression::AsExpression<<<now as crate::Expression>::SqlType
    as crate::sql_types::ops::Sub>::Rhs> {
    type Output =
        crate::internal::table_macro::ops::Sub<Self, Rhs::Expression>;
    fn sub(self, __diesel_internal_rhs: Rhs) -> Self::Output {
        crate::internal::table_macro::ops::Sub::new(self,
            __diesel_internal_rhs.as_expression())
    }
}operator_allowed!(now, Sub, sub);
30
31#[doc(hidden)]
#[allow(non_camel_case_types, non_snake_case, unused_imports)]
pub(crate) mod date_utils {
    use diesel::{self, QueryResult};
    use diesel::expression::{
        AsExpression, Expression, SelectableExpression, AppearsOnTable,
        ValidGrouping,
    };
    use diesel::query_builder::{QueryFragment, AstPass};
    use diesel::sql_types::*;
    use diesel::internal::sql_functions::*;
    use super::*;
    pub struct date<expr> {
        pub(in super) expr: expr,
    }
    const _: () =
        {
            use diesel;
            use diesel::internal::derives::numeric_ops as ops;
            use diesel::expression::{Expression, AsExpression};
            use diesel::sql_types::ops::{Add, Sub, Mul, Div};
            use diesel::sql_types::{SqlType, SingleValue};
            impl<expr, __Rhs> ::std::ops::Add<__Rhs> for date<expr> where
                Self: Expression, Self: Expression,
                <Self as Expression>::SqlType: Add,
                <<Self as Expression>::SqlType as Add>::Rhs: SqlType +
                SingleValue,
                __Rhs: AsExpression<<<Self as Expression>::SqlType as
                Add>::Rhs> {
                type Output = ops::Add<Self, __Rhs::Expression>;
                fn add(self, rhs: __Rhs) -> Self::Output {
                    ops::Add::new(self, rhs.as_expression())
                }
            }
            impl<expr, __Rhs> ::std::ops::Sub<__Rhs> for date<expr> where
                Self: Expression, Self: Expression,
                <Self as Expression>::SqlType: Sub,
                <<Self as Expression>::SqlType as Sub>::Rhs: SqlType +
                SingleValue,
                __Rhs: AsExpression<<<Self as Expression>::SqlType as
                Sub>::Rhs> {
                type Output = ops::Sub<Self, __Rhs::Expression>;
                fn sub(self, rhs: __Rhs) -> Self::Output {
                    ops::Sub::new(self, rhs.as_expression())
                }
            }
            impl<expr, __Rhs> ::std::ops::Mul<__Rhs> for date<expr> where
                Self: Expression, Self: Expression,
                <Self as Expression>::SqlType: Mul,
                <<Self as Expression>::SqlType as Mul>::Rhs: SqlType +
                SingleValue,
                __Rhs: AsExpression<<<Self as Expression>::SqlType as
                Mul>::Rhs> {
                type Output = ops::Mul<Self, __Rhs::Expression>;
                fn mul(self, rhs: __Rhs) -> Self::Output {
                    ops::Mul::new(self, rhs.as_expression())
                }
            }
            impl<expr, __Rhs> ::std::ops::Div<__Rhs> for date<expr> where
                Self: Expression, Self: Expression,
                <Self as Expression>::SqlType: Div,
                <<Self as Expression>::SqlType as Div>::Rhs: SqlType +
                SingleValue,
                __Rhs: AsExpression<<<Self as Expression>::SqlType as
                Div>::Rhs> {
                type Output = ops::Div<Self, __Rhs::Expression>;
                fn div(self, rhs: __Rhs) -> Self::Output {
                    ops::Div::new(self, rhs.as_expression())
                }
            }
        };
    #[automatically_derived]
    impl<expr: ::core::fmt::Debug> ::core::fmt::Debug for date<expr> {
        #[inline]
        fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
            ::core::fmt::Formatter::debug_struct_field1_finish(f, "date",
                "expr", &&self.expr)
        }
    }
    #[automatically_derived]
    impl<expr: ::core::clone::Clone> ::core::clone::Clone for date<expr> {
        #[inline]
        fn clone(&self) -> date<expr> {
            date { expr: ::core::clone::Clone::clone(&self.expr) }
        }
    }
    #[automatically_derived]
    impl<expr: ::core::marker::Copy> ::core::marker::Copy for date<expr> { }
    const _: () =
        {
            use diesel;
            #[allow(non_camel_case_types)]
            impl<expr: diesel::query_builder::QueryId>
                diesel::query_builder::QueryId for date<expr> {
                type QueryId =
                    date<<expr as diesel::query_builder::QueryId>::QueryId>;
                const HAS_STATIC_QUERY_ID: bool =
                    <expr as
                            diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID &&
                        true;
                const IS_WINDOW_FUNCTION: bool =
                    <expr as diesel::query_builder::QueryId>::IS_WINDOW_FUNCTION
                        || false;
            }
        };
    #[doc = "The return type of [`date()`](super::fn_name)"]
    pub type HelperType<expr> =
        date<<expr as AsExpression<Timestamp>>::Expression>;
    impl<expr> Expression for date<expr> where (expr): Expression {
        type SqlType = Date;
    }
    impl<expr, __DieselInternal> SelectableExpression<__DieselInternal> for
        date<expr> where expr: SelectableExpression<__DieselInternal>,
        Self: AppearsOnTable<__DieselInternal> {}
    impl<expr, __DieselInternal> AppearsOnTable<__DieselInternal> for
        date<expr> where expr: AppearsOnTable<__DieselInternal>,
        Self: Expression {}
    impl<expr, __DieselInternal> FunctionFragment<__DieselInternal> for
        date<expr> where __DieselInternal: diesel::backend::Backend,
        expr: QueryFragment<__DieselInternal> {
        const FUNCTION_NAME: &'static str = "date";
        #[allow(unused_assignments)]
        fn walk_arguments<'__b>(&'__b self,
            mut out: AstPass<'_, '__b, __DieselInternal>) -> QueryResult<()> {
            let mut needs_comma = false;
            if !self.expr.is_noop(out.backend())? {
                if needs_comma { out.push_sql(", "); }
                self.expr.walk_ast(out.reborrow())?;
                needs_comma = true;
            }
            Ok(())
        }
    }
    impl<expr, __DieselInternal> QueryFragment<__DieselInternal> for
        date<expr> where __DieselInternal: diesel::backend::Backend,
        expr: QueryFragment<__DieselInternal> {
        fn walk_ast<'__b>(&'__b self,
            mut out: AstPass<'_, '__b, __DieselInternal>) -> QueryResult<()> {
            out.push_sql(<Self as
                    FunctionFragment<__DieselInternal>>::FUNCTION_NAME);
            out.push_sql("(");
            self.walk_arguments(out.reborrow())?;
            out.push_sql(")");
            Ok(())
        }
    }
    pub struct __Derived<expr>(expr);
    const _: () =
        {
            use diesel;
            impl<expr, __GroupByClause>
                diesel::expression::ValidGrouping<__GroupByClause> for
                __Derived<expr> where
                expr: diesel::expression::ValidGrouping<__GroupByClause> {
                type IsAggregate =
                    <expr as
                    diesel::expression::ValidGrouping<__GroupByClause>>::IsAggregate;
            }
        };
    impl<expr, __DieselInternal> ValidGrouping<__DieselInternal> for
        date<expr> where __Derived<expr>: ValidGrouping<__DieselInternal> {
        type IsAggregate =
            <__Derived<expr> as ValidGrouping<__DieselInternal>>::IsAggregate;
    }
    use diesel::sqlite::{Sqlite, SqliteConnection};
    use diesel::serialize::ToSql;
    use diesel::deserialize::{FromSqlRow, StaticallySizedRow};
    #[allow(dead_code)]
    #[doc =
    r" Registers an implementation for this function on the given connection"]
    #[doc = r""]
    #[doc =
    r" This function must be called for every `SqliteConnection` before"]
    #[doc =
    r" this SQL function can be used on SQLite. The implementation must be"]
    #[doc =
    r" deterministic (returns the same result given the same arguments). If"]
    #[doc = r" the function is nondeterministic, call"]
    #[doc = r" `register_nondeterministic_impl` instead."]
    pub fn register_impl<F, Ret, expr>(conn: &mut SqliteConnection, f: F)
        -> QueryResult<()> where F: Fn(expr) -> Ret + std::panic::UnwindSafe +
        Send + 'static, (expr,): FromSqlRow<(Timestamp,), Sqlite> +
        StaticallySizedRow<(Timestamp,), Sqlite>, Ret: ToSql<Date, Sqlite> {
        conn.register_sql_function::<(Timestamp,), Date, _, _,
            _>("date", true, move |(expr,)| f(expr))
    }
    #[allow(dead_code)]
    #[doc =
    r" Registers an implementation for this function on the given connection"]
    #[doc = r""]
    #[doc =
    r" This function must be called for every `SqliteConnection` before"]
    #[doc = r" this SQL function can be used on SQLite."]
    #[doc = r" `register_nondeterministic_impl` should only be used if your"]
    #[doc =
    r" function can return different results with the same arguments (e.g."]
    #[doc = r" `random`). If your function is deterministic, you should call"]
    #[doc = r" `register_impl` instead."]
    pub fn register_nondeterministic_impl<F, Ret,
        expr>(conn: &mut SqliteConnection, mut f: F) -> QueryResult<()> where
        F: FnMut(expr) -> Ret + std::panic::UnwindSafe + Send + 'static,
        (expr,): FromSqlRow<(Timestamp,), Sqlite> +
        StaticallySizedRow<(Timestamp,), Sqlite>, Ret: ToSql<Date, Sqlite> {
        conn.register_sql_function::<(Timestamp,), Date, _, _,
            _>("date", false, move |(expr,)| f(expr))
    }
}#[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
55impl AsExpression<Nullable<Timestamp>> for now {
56    type Expression = Coerce<now, Nullable<Timestamp>>;
57
58    fn as_expression(self) -> Self::Expression {
59        Coerce::new(self)
60    }
61}
62
63#[cfg(feature = "postgres_backend")]
64impl AsExpression<Timestamptz> for now {
65    type Expression = Coerce<now, Timestamptz>;
66
67    fn as_expression(self) -> Self::Expression {
68        Coerce::new(self)
69    }
70}
71
72#[cfg(feature = "postgres_backend")]
73impl AsExpression<Nullable<Timestamptz>> for now {
74    type Expression = Coerce<now, Nullable<Timestamptz>>;
75
76    fn as_expression(self) -> Self::Expression {
77        Coerce::new(self)
78    }
79}
80
81#[cfg(feature = "sqlite")]
82impl AsExpression<TimestamptzSqlite> for now {
83    type Expression = Coerce<now, TimestamptzSqlite>;
84
85    fn as_expression(self) -> Self::Expression {
86        Coerce::new(self)
87    }
88}
89
90#[cfg(feature = "sqlite")]
91impl AsExpression<Nullable<TimestamptzSqlite>> for now {
92    type Expression = Coerce<now, Nullable<TimestamptzSqlite>>;
93
94    fn as_expression(self) -> Self::Expression {
95        Coerce::new(self)
96    }
97}
98
99/// Represents the SQL `CURRENT_DATE` constant.
100#[allow(non_camel_case_types)]
101#[derive(#[automatically_derived]
#[allow(non_camel_case_types)]
impl ::core::fmt::Debug for today {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "today")
    }
}Debug, #[automatically_derived]
#[allow(non_camel_case_types)]
impl ::core::marker::Copy for today { }Copy, #[automatically_derived]
#[allow(non_camel_case_types)]
impl ::core::clone::Clone for today {
    #[inline]
    fn clone(&self) -> today { *self }
}Clone, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl diesel::query_builder::QueryId for today {
            type QueryId = today<>;
            const HAS_STATIC_QUERY_ID: bool = true;
            const IS_WINDOW_FUNCTION: bool = false;
        }
    };QueryId, const _: () =
    {
        use diesel;
        impl<__GroupByClause>
            diesel::expression::ValidGrouping<__GroupByClause> for today {
            type IsAggregate = diesel::expression::is_aggregate::Never;
        }
    };ValidGrouping)]
102pub struct today;
103
104impl Expression for today {
105    type SqlType = Date;
106}
107
108impl<DB: Backend> QueryFragment<DB> for today {
109    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
110        out.push_sql("CURRENT_DATE");
111        Ok(())
112    }
113}
114
115impl<QS> crate::expression::SelectableExpression<QS> for today where
    today: crate::expression::AppearsOnTable<QS> {}
impl<QS> crate::expression::AppearsOnTable<QS> for today where
    today: crate::expression::Expression {}impl_selectable_expression!(today);
116
117impl<Rhs> ::std::ops::Add<Rhs> for today where
    Rhs: crate::expression::AsExpression<<<today as
    crate::Expression>::SqlType as crate::sql_types::ops::Add>::Rhs> {
    type Output =
        crate::internal::table_macro::ops::Add<Self, Rhs::Expression>;
    fn add(self, __diesel_internal_rhs: Rhs) -> Self::Output {
        crate::internal::table_macro::ops::Add::new(self,
            __diesel_internal_rhs.as_expression())
    }
}operator_allowed!(today, Add, add);
118impl<Rhs> ::std::ops::Sub<Rhs> for today where
    Rhs: crate::expression::AsExpression<<<today as
    crate::Expression>::SqlType as crate::sql_types::ops::Sub>::Rhs> {
    type Output =
        crate::internal::table_macro::ops::Sub<Self, Rhs::Expression>;
    fn sub(self, __diesel_internal_rhs: Rhs) -> Self::Output {
        crate::internal::table_macro::ops::Sub::new(self,
            __diesel_internal_rhs.as_expression())
    }
}operator_allowed!(today, Sub, sub);
119
120impl AsExpression<Nullable<Date>> for today {
121    type Expression = Coerce<today, Nullable<Date>>;
122
123    fn as_expression(self) -> Self::Expression {
124        Coerce::new(self)
125    }
126}