Skip to content

Commit

Permalink
fix(clickhouse): fix truncating to date from a timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
cpcloud committed Sep 25, 2024
1 parent 78c938d commit 9edc984
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
14 changes: 8 additions & 6 deletions ibis/backends/clickhouse/tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,14 +495,16 @@ def my_eq(a: int, b: int) -> bool: ...


def test_timestamp_to_start_of_week(con):
expr = ibis.timestamp("2024-02-03 00:00:00")
expr1 = expr.truncate("W")
result = con.to_pyarrow(expr1)
assert result is not None
pytest.importorskip("pyarrow")

expr = ibis.timestamp("2024-02-03 00:00:00").truncate("W")
result = con.to_pyarrow(expr).as_py()
assert result == datetime(2024, 1, 29, 0, 0, 0)


def test_date_to_start_of_day(con):
pytest.importorskip("pyarrow")

expr = ibis.date("2024-02-03")
expr1 = expr.truncate("D")
result = con.to_pyarrow(expr1)
assert result is not None
assert con.to_pyarrow(expr1) == con.to_pyarrow(expr)
10 changes: 8 additions & 2 deletions ibis/backends/sql/compilers/clickhouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,15 +383,21 @@ def visit_TimestampTruncate(self, op, *, arg, unit):

if short in ("s", "ms", "us", "ns"):
arg = self.f.toDateTime64(arg, op.arg.dtype.scale or 0)
return self.f[func](arg)
return self.cast(self.f[func](arg), op.dtype)

visit_TimeTruncate = visit_TimestampTruncate

def visit_DateTruncate(self, op, *, arg, unit):
if unit.short == "W":
if unit.short == "D":
# no op because truncating a date to a date has no effect
return arg
elif unit.short == "W":
func = "toMonday"
else:
func = f"toStartOf{unit.singular.capitalize()}"

# no cast needed here because all of the allow units here return `Date`
# values
return self.f[func](arg)

def visit_TimestampBucket(self, op, *, arg, interval, offset):
Expand Down

0 comments on commit 9edc984

Please sign in to comment.