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

feat: Raise on invalid temporal arithmetic #16934

Merged
merged 3 commits into from
Jun 13, 2024
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
80 changes: 68 additions & 12 deletions crates/polars-plan/src/logical_plan/aexpr/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,30 +312,78 @@ fn get_arithmetic_field(
let mut left_field = left_ae.to_field_impl(schema, arena, nested)?;

let super_type = match op {
Operator::Minus if left_field.dtype.is_temporal() => {
Operator::Minus => {
let right_type = right_ae.to_field_impl(schema, arena, nested)?.dtype;
match (&left_field.dtype, right_type) {
match (&left_field.dtype, &right_type) {
#[cfg(feature = "dtype-struct")]
(Struct(_), Struct(_)) => {
return Ok(left_field);
},
(Duration(_), Datetime(_, _))
| (Datetime(_, _), Duration(_))
| (Duration(_), Date)
| (Date, Duration(_))
| (Duration(_), Time)
| (Time, Duration(_)) => try_get_supertype(left_field.data_type(), &right_type)?,
// T - T != T if T is a datetime / date
(Datetime(tul, _), Datetime(tur, _)) => Duration(get_time_units(tul, &tur)),
(Datetime(tul, _), Datetime(tur, _)) => Duration(get_time_units(tul, tur)),
(_, Datetime(_, _)) | (Datetime(_, _), _) => {
polars_bail!(InvalidOperation: "{} not allowed on {} and {}", op, left_field.dtype, right_type)
},
(Date, Date) => Duration(TimeUnit::Milliseconds),
(left, right) => try_get_supertype(left, &right)?,
(_, Date) | (Date, _) => {
polars_bail!(InvalidOperation: "{} not allowed on {} and {}", op, left_field.dtype, right_type)
},
(Duration(tul), Duration(tur)) => Duration(get_time_units(tul, tur)),
(_, Duration(_)) | (Duration(_), _) => {
polars_bail!(InvalidOperation: "{} not allowed on {} and {}", op, left_field.dtype, right_type)
},
(_, Time) | (Time, _) => {
polars_bail!(InvalidOperation: "{} not allowed on {} and {}", op, left_field.dtype, right_type)
},
(left, right) => try_get_supertype(left, right)?,
}
},
Operator::Plus
if left_field.dtype == Boolean
&& right_ae.get_type(schema, Context::Default, arena)? == Boolean =>
{
IDX_DTYPE
Operator::Plus => {
let right_type = right_ae.to_field_impl(schema, arena, nested)?.dtype;
match (&left_field.dtype, &right_type) {
(Duration(_), Datetime(_, _))
| (Datetime(_, _), Duration(_))
| (Duration(_), Date)
| (Date, Duration(_))
| (Duration(_), Time)
| (Time, Duration(_)) => try_get_supertype(left_field.data_type(), &right_type)?,
(_, Datetime(_, _))
| (Datetime(_, _), _)
| (_, Date)
| (Date, _)
| (Time, _)
| (_, Time) => {
polars_bail!(InvalidOperation: "{} not allowed on {} and {}", op, left_field.dtype, right_type)
},
(Duration(tul), Duration(tur)) => Duration(get_time_units(tul, tur)),
(_, Duration(_)) | (Duration(_), _) => {
polars_bail!(InvalidOperation: "{} not allowed on {} and {}", op, left_field.dtype, right_type)
},
(Boolean, Boolean) => IDX_DTYPE,
(left, right) => try_get_supertype(left, right)?,
}
},
_ => {
let right_type = right_ae.to_field_impl(schema, arena, nested)?.dtype;

match (&left_field.dtype, &right_type) {
#[cfg(feature = "dtype-struct")]
(Struct(_), Struct(_)) => {
if op.is_arithmetic() {
return Ok(left_field);
}
return Ok(left_field);
},
(Datetime(_, _), _)
| (_, Datetime(_, _))
| (Time, _)
| (_, Time)
| (Date, _)
| (_, Date) => {
polars_bail!(InvalidOperation: "{} not allowed on {} and {}", op, left_field.dtype, right_type)
},
_ => {
// Avoid needlessly type casting numeric columns during arithmetic
Expand Down Expand Up @@ -381,6 +429,14 @@ fn get_truediv_field(
dt if dt.is_numeric() => Float64,
#[cfg(feature = "dtype-duration")]
Duration(_) => Float64,
#[cfg(feature = "dtype-datetime")]
Datetime(_, _) => {
polars_bail!(InvalidOperation: "division of 'Datetime' datatype is not allowed")
},
#[cfg(feature = "dtype-time")]
Time => polars_bail!(InvalidOperation: "division of 'Time' datatype is not allowed"),
#[cfg(feature = "dtype-date")]
Date => polars_bail!(InvalidOperation: "division of 'Date' datatype is not allowed"),
// we don't know what to do here, best return the dtype
dt => dt.clone(),
};
Expand Down
26 changes: 26 additions & 0 deletions py-polars/tests/unit/operations/arithmetic/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,29 @@ def test_duration_division_schema() -> None:

assert q.schema == {"a": pl.Float64}
assert q.collect().to_dict(as_series=False) == {"a": [1.0]}


@pytest.mark.parametrize(
("a", "b", "op"),
[
(pl.Duration, pl.Int32, "+"),
(pl.Int32, pl.Duration, "+"),
(pl.Time, pl.Int32, "+"),
(pl.Int32, pl.Time, "+"),
(pl.Date, pl.Int32, "+"),
(pl.Int32, pl.Date, "+"),
(pl.Datetime, pl.Duration, "*"),
(pl.Duration, pl.Datetime, "*"),
(pl.Date, pl.Duration, "*"),
(pl.Duration, pl.Date, "*"),
(pl.Time, pl.Duration, "*"),
(pl.Duration, pl.Time, "*"),
],
)
def test_raise_invalid_temporal(a: pl.DataType, b: pl.DataType, op: str) -> None:
a = pl.Series("a", [], dtype=a) # type: ignore[assignment]
b = pl.Series("b", [], dtype=b) # type: ignore[assignment]
_df = pl.DataFrame([a, b])

with pytest.raises(pl.InvalidOperationError):
eval(f"_df.select(pl.col('a') {op} pl.col('b'))")