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 d3496fd commit ea195cf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
16 changes: 16 additions & 0 deletions ibis/backends/clickhouse/tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,3 +492,19 @@ def my_eq(a: int, b: int) -> bool: ...
expr = alltypes.int_col.collect().filter(lambda x: my_eq(x, 1))
result = expr.execute()
assert set(result) == {1}


def test_timestamp_to_start_of_week(con):
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")
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 allowed units return `Date`
# values
return self.f[func](arg)

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

0 comments on commit ea195cf

Please sign in to comment.