Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Postgre function: DATE_TRUNC #825

Merged
merged 7 commits into from
Feb 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/backend/postgres/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ impl QueryBuilder for PostgresQueryBuilder {
PgFunction::GenRandomUUID => "GEN_RANDOM_UUID",
PgFunction::JsonBuildObject => "JSON_BUILD_OBJECT",
PgFunction::JsonAgg => "JSON_AGG",
PgFunction::DateTrunc => "DATE_TRUNC",
#[cfg(feature = "postgres-array")]
PgFunction::Any => "ANY",
#[cfg(feature = "postgres-array")]
Expand Down
42 changes: 41 additions & 1 deletion src/extension/postgres/func.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! For calling built-in Postgres SQL functions.

use crate::{expr::*, func::*};
use crate::{expr::*, func::*, PgDateTruncUnit};

/// Functions
#[derive(Debug, Clone, PartialEq)]
Expand All @@ -16,6 +16,7 @@ pub enum PgFunction {
GenRandomUUID,
JsonBuildObject,
JsonAgg,
DateTrunc,
#[cfg(feature = "postgres-array")]
Any,
#[cfg(feature = "postgres-array")]
Expand Down Expand Up @@ -384,6 +385,45 @@ impl PgFunc {
FunctionCall::new(Function::PgFunction(PgFunction::JsonBuildObject)).args(args)
}

/// Call the `DATE_TRUNC` function. Postgres only.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::select()
/// .expr(PgFunc::date_trunc(
/// PgDateTruncUnit::Day,
/// Expr::val("2020-01-01"),
/// ))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"SELECT DATE_TRUNC('day', '2020-01-01')"#
/// );
///
/// let query = Query::select()
/// .expr(PgFunc::date_trunc(
/// PgDateTruncUnit::Microseconds,
/// Expr::val("2020-01-01"),
/// ))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"SELECT DATE_TRUNC('microseconds', '2020-01-01')"#
/// );
/// ```
pub fn date_trunc<T>(unit: PgDateTruncUnit, expr: T) -> FunctionCall
where
T: Into<SimpleExpr>,
{
FunctionCall::new(Function::PgFunction(PgFunction::DateTrunc))
.args([Expr::val(unit.to_string()).into(), expr.into()])
}

/// Call the `JSON_AGG` function. Postgres only.
///
/// # Examples
Expand Down
41 changes: 41 additions & 0 deletions src/table/column.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt;

use crate::{expr::*, types::*};

/// Specification of a table column
Expand Down Expand Up @@ -200,6 +202,45 @@ pub enum PgInterval {
MinuteToSecond,
}

// All possible inputs to DATE_TRUNC (https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC)
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum PgDateTruncUnit {
Microseconds,
Milliseconds,
Second,
Minute,
Hour,
Day,
Week,
Month,
Quarter,
Year,
Decade,
Century,
Millennium,
}

impl fmt::Display for PgDateTruncUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = match self {
PgDateTruncUnit::Microseconds => "microseconds",
PgDateTruncUnit::Milliseconds => "milliseconds",
PgDateTruncUnit::Second => "second",
PgDateTruncUnit::Minute => "minute",
PgDateTruncUnit::Hour => "hour",
PgDateTruncUnit::Day => "day",
PgDateTruncUnit::Week => "week",
PgDateTruncUnit::Month => "month",
PgDateTruncUnit::Quarter => "quarter",
PgDateTruncUnit::Year => "year",
PgDateTruncUnit::Decade => "decade",
PgDateTruncUnit::Century => "century",
PgDateTruncUnit::Millennium => "millennium",
};
write!(f, "{}", text)
}
}

impl ColumnDef {
/// Construct a table column
pub fn new<T>(name: T) -> Self
Expand Down