Skip to content

feat: derive monotonicity for date_truc with timezone when unit larger than day #20097

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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/expr/impl/src/scalar/date_trunc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const MILLENNIUM: &str = "millennium";

#[function("date_trunc(varchar, timestamp) -> timestamp")]
pub fn date_trunc_timestamp(field: &str, ts: Timestamp) -> Result<Timestamp> {
// NOTE(st1page): please also modify the `MonotonicityAnalyzer::date_unit_larger_than_day` in frontend if this changes
Ok(match field.to_ascii_lowercase().as_str() {
MICROSECONDS => ts.truncate_micros(),
MILLISECONDS => ts.truncate_millis(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@
select * from t where ts + interval '1 hour' > date_trunc('day', now());
expected_outputs:
- stream_plan
- name: date_truc_with_timezone
sql: |
create table t (ts timestamp with time zone, a int);
select * from t where ts + interval '1 hour' > date_trunc('day', now(), 'Asia/Singapore');
expected_outputs:
- stream_plan
- name: Non-trivial now expression 2
sql: |
create table t (ts timestamp with time zone, a int);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,19 @@
└─StreamExchange { dist: Broadcast }
└─StreamProject { exprs: [DateTrunc('day':Varchar, now, 'UTC':Varchar) as $expr2], output_watermarks: [$expr2] }
└─StreamNow { output: [now] }
- name: date_truc_with_timezone
sql: |
create table t (ts timestamp with time zone, a int);
select * from t where ts + interval '1 hour' > date_trunc('day', now(), 'Asia/Singapore');
stream_plan: |-
StreamMaterialize { columns: [ts, a, t._row_id(hidden)], stream_key: [t._row_id], pk_columns: [t._row_id], pk_conflict: NoCheck }
└─StreamProject { exprs: [t.ts, t.a, t._row_id] }
└─StreamDynamicFilter { predicate: ($expr1 > $expr2), output_watermarks: [$expr1], output: [t.ts, t.a, $expr1, t._row_id], cleaned_by_watermark: true }
├─StreamProject { exprs: [t.ts, t.a, AddWithTimeZone(t.ts, '01:00:00':Interval, 'UTC':Varchar) as $expr1, t._row_id] }
│ └─StreamTableScan { table: t, columns: [t.ts, t.a, t._row_id], stream_scan_type: ArrangementBackfill, stream_key: [t._row_id], pk: [_row_id], dist: UpstreamHashShard(t._row_id) }
└─StreamExchange { dist: Broadcast }
└─StreamProject { exprs: [DateTrunc('day':Varchar, now, 'Asia/Singapore':Varchar) as $expr2], output_watermarks: [$expr2] }
└─StreamNow { output: [now] }
- name: Non-trivial now expression 2
sql: |
create table t (ts timestamp with time zone, a int);
Expand Down
25 changes: 24 additions & 1 deletion src/frontend/src/optimizer/property/monotonicity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,23 @@ impl MonotonicityAnalyzer {
tz_is_utc // conservative
}

fn date_unit_larger_than_day(date_unit: Option<&str>) -> bool {
const DAY: &str = "day";
const WEEK: &str = "week";
const MONTH: &str = "month";
const QUARTER: &str = "quarter";
const YEAR: &str = "year";
const DECADE: &str = "decade";
const CENTURY: &str = "century";
const MILLENNIUM: &str = "millennium";
date_unit.map_or(false, |date_unit| {
matches!(
date_unit.to_ascii_lowercase().as_str(),
DAY | WEEK | MONTH | QUARTER | YEAR | DECADE | CENTURY | MILLENNIUM
)
})
Comment on lines +190 to +203
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the point of the const here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case SQL is standardized to use a language other than English in the future?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just maintain it same as the expression's implementation

// TODO(xiangjinwu): parse into an enum
const MICROSECONDS: &str = "microseconds";
const MILLISECONDS: &str = "milliseconds";
const SECOND: &str = "second";
const MINUTE: &str = "minute";
const HOUR: &str = "hour";
const DAY: &str = "day";
const WEEK: &str = "week";
const MONTH: &str = "month";
const QUARTER: &str = "quarter";
const YEAR: &str = "year";
const DECADE: &str = "decade";
const CENTURY: &str = "century";
const MILLENNIUM: &str = "millennium";

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean why not use those existing definition?

It doesn't make sense to

  • Define const repeatedly in multiple places
  • Define const in-place just before its usage site

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This modification is a bit troublesome; we have to expose these const from a very deep level within expr... Since we might never modify it, I would rather make a copy.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could move these const from the deep mod into a upper layer, and import it in the original place. That should be easy to do.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am too lazy....

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your brain will become rusty!

}

match func_call.func_type() {
ExprType::Unspecified => unreachable!(),
ExprType::Add => match self.visit_binary_op(func_call.inputs()) {
Expand Down Expand Up @@ -257,7 +274,13 @@ impl MonotonicityAnalyzer {
.as_literal()
.and_then(|literal| literal.get_data().as_ref())
.map(|tz| tz.as_utf8().as_ref());
if time_zone_is_without_dst(time_zone) {
let date_unit = func_call.inputs()[0]
.as_literal()
.and_then(|literal| literal.get_data().as_ref())
.map(|tz| tz.as_utf8().as_ref());
if time_zone_is_without_dst(time_zone)
|| date_unit_larger_than_day(date_unit)
{
Comment on lines +277 to +283
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please add an example to demonstrate the correctness?

What I can think of is like in a timezone with DST, MM-dd 23:50:00 + interval 12 minutes may be MM-dd 23:02:00, while the date_trunc('day', ...) result be MM-dd 00:12:00 versus MM-dd (00:00:00). Seems this will break the correctness. Am I understanding it wrong?

Copy link
Member

@xxchan xxchan Jan 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it has all fields that are less significant than the selected one set to zero (or one, for day and month).
https://arc.net/l/quote/wfxyyukb

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it has all fields that are less significant than the selected one set to zero (or one, for day and month).

Yes I know that.


I just got it. In my previous comment, I mixed F(X + C) with F(X) + C. I think what we need to ensure here is that, if X2 > X1, F(X2) > F(X1), and vice versa. We don't need to compare F(X + C) with F(X) + C.

Copy link
Contributor

@xiangjinwu xiangjinwu Jan 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

related: #13201
In short:

  • PostgreSQL does treat units >= day and units < day differently (redotz boolean flag)
  • Counter-intuitively, it is possible that date_trunc('day', x) > x and the return value has hour != 0

There may be more tricky cases to think about carefully.

I think what we need to ensure here is that, if X2 > X1, F(X2) > F(X1), and vice versa.

  • We only have X2 > X1 implies F(X2) >= F(X1) with the equal sign
  • Do you mean F(X2) > F(X1) implies X2 > X1 by vice versa?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • We only have X2 > X1 implies F(X2) >= F(X1) with the equal sign
  • Do you mean F(X2) > F(X1) implies X2 > X1 by vice versa?

Yes. Thank for the equal sign though. To be clear, I think it should be:

  • X2 >= X1F(X2) >= F(X1)
  • F(X2) >= F(X1)X2 >= X1
  • X2 <= X1F(X2) <= F(X1)
  • F(X2) <= F(X1)X2 <= X1

Only with the four all satisfied, we can say F maintains the monotonicity.

any
} else {
Inherent(Unknown)
Expand Down
Loading