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

fix: Ensure number of names passed to struct.rename_fields is valid #15624

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
14 changes: 8 additions & 6 deletions crates/polars-plan/src/dsl/function_expr/struct_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,25 @@ impl StructFunction {
polars_bail!(StructFieldNotFound: "{}", name.as_ref());
}
}),
RenameFields(names) => mapper.map_dtype(|dt| match dt {
RenameFields(names) => mapper.try_map_dtype(|dt| match dt {
DataType::Struct(fields) => {
polars_ensure!(fields.len() == names.len(), ComputeError: "expected {} names, got {}", fields.len(), names.len());
let fields = fields
.iter()
.zip(names.as_ref())
.map(|(fld, name)| Field::new(name, fld.data_type().clone()))
.collect();
DataType::Struct(fields)
Ok(DataType::Struct(fields))
},
// The types will be incorrect, but its better than nothing
// we can get an incorrect type with python lambdas, because we only know return type when running
// the query
dt => DataType::Struct(
dt => Ok(DataType::Struct(
names
.iter()
.map(|name| Field::new(name, dt.clone()))
.collect(),
),
)),
}),
PrefixFields(prefix) => mapper.try_map_dtype(|dt| match dt {
DataType::Struct(fields) => {
Expand Down Expand Up @@ -131,8 +132,9 @@ pub(super) fn get_by_name(s: &Series, name: Arc<str>) -> PolarsResult<Series> {

pub(super) fn rename_fields(s: &Series, names: Arc<Vec<String>>) -> PolarsResult<Series> {
let ca = s.struct_()?;
let fields = ca
.fields()
let fields = ca.fields();
polars_ensure!(fields.len() == names.len(), ComputeError: "expected {} names, got {}", fields.len(), names.len());
let fields = fields
.iter()
.zip(names.as_ref())
.map(|(s, name)| {
Expand Down
15 changes: 15 additions & 0 deletions py-polars/tests/unit/datatypes/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -868,3 +868,18 @@ def test_struct_null_count_10130() -> None:

s = pl.Series([{"a": None}])
assert s.null_count() == 1


def test_struct_rename_mismatch_9052() -> None:
df = pl.DataFrame({"A": [{"p": 1, "q": 2}]})

with pytest.raises(pl.ComputeError, match=r"expected 2 names, got 1"):
df.select(pl.col("A").struct.rename_fields(["x"]))

# Additional cases
# too many fields
with pytest.raises(pl.ComputeError, match=r"expected 2 names, got 3"):
df.select(pl.col("A").struct.rename_fields(["too", "many", "fields"]))
# during schema evaluation
with pytest.raises(pl.ComputeError, match=r"expected 2 names, got 1"):
df.lazy().select(pl.col("A").struct.rename_fields(["x"])).schema
Loading