Skip to content

Commit

Permalink
fix(rust): Do not panic when casting from an empty Series to pl.Decimal
Browse files Browse the repository at this point in the history
  • Loading branch information
petrosbar committed Feb 7, 2024
1 parent 6fc0395 commit 97abb20
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
5 changes: 2 additions & 3 deletions crates/polars-core/src/chunked_array/logical/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ impl LogicalType for DecimalChunked {
fn cast(&self, dtype: &DataType) -> PolarsResult<Series> {
let (precision_src, scale_src) = (self.precision(), self.scale());
if let &DataType::Decimal(precision_dst, scale_dst) = dtype {
let scale_dst = scale_dst.ok_or_else(
|| polars_err!(ComputeError: "cannot cast to Decimal with unknown scale"),
)?;
let scale_dst = scale_dst.unwrap_or(scale_src);
// for now, let's just allow same-scale conversions
// where precision is either the same or bigger or gets converted to `None`
// (these are the easy cases requiring no checks and arithmetics which we can add later)
Expand All @@ -95,6 +93,7 @@ impl LogicalType for DecimalChunked {
_ => false,
};
if scale_src == scale_dst && is_widen {
let dtype = &DataType::Decimal(precision_dst, Some(scale_dst));
return self.0.cast(dtype); // no conversion or checks needed
}
}
Expand Down
5 changes: 1 addition & 4 deletions crates/polars-core/src/series/ops/null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ impl Series {
.into_series(),
#[cfg(feature = "dtype-decimal")]
DataType::Decimal(precision, scale) => Int128Chunked::full_null(name, size)
.into_decimal_unchecked(
*precision,
scale.unwrap_or_else(|| unreachable!("scale should be set")),
)
.into_decimal_unchecked(*precision, scale.unwrap_or(0))
.into_series(),
#[cfg(feature = "dtype-struct")]
DataType::Struct(fields) => {
Expand Down
8 changes: 8 additions & 0 deletions py-polars/tests/unit/datatypes/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,14 @@ def test_decimal_cast() -> None:
assert result.to_dict(as_series=False) == expected


def test_decimal_cast_no_scale() -> None:
s = pl.Series().cast(pl.Decimal)
assert s.dtype == pl.Decimal(precision=None, scale=0)

s = pl.Series([D("10.0")]).cast(pl.Decimal)
assert s.dtype == pl.Decimal(precision=None, scale=1)


def test_decimal_scale_precision_roundtrip(monkeypatch: Any) -> None:
monkeypatch.setenv("POLARS_ACTIVATE_DECIMAL", "1")
assert pl.from_arrow(pl.Series("dec", [D("10.0")]).to_arrow()).item() == D("10.0")
Expand Down

0 comments on commit 97abb20

Please sign in to comment.