Don't allow duplicate column names in Rename (#19196)

## Description

Rename allows renaming columns of a table with duplicate names, even
though duplicate column names are disallowed.

I fixed this by checking the column names for duplicates using a
HashSet. Otherwise valid records are discarded and a
nu::shell::column_defined_twice error is thrown if there are duplicates.

## User-facing changes (Release notes)

Fixed an issue where rename allowed setting duplicate column names on a
table

## Additional notes

Closes https://github.com/nushell/nushell/issues/19195
This commit is contained in:
Tino authored and GitHub committed 2026-10-09 06:24:51 -05:00
1 parent 67edfb6eca
commit 04a0444435
1 file changed
+36 -1
+36 -1
View File
@@ -1,6 +1,7 @@
use indexmap::IndexMap;
use nu_engine::{ClosureEval, command_prelude::*};
use nu_protocol::engine::Closure;
use std::collections::HashSet;
#[derive(Clone)]
pub struct Rename;
@@ -210,7 +211,10 @@ fn rename(
}
};
match record {
match record.and_then(|record| {
ensure_unique_columns(&record, span)?;
Ok(record)
}) {
Ok(record) => Value::record(record, span),
Err(err) => Value::error(err, span),
}
@@ -233,12 +237,43 @@ fn rename(
.map(|data| data.set_metadata(metadata))
}
/// Reject a rename whose result would use the same column name twice
fn ensure_unique_columns(record: &Record, span: Span) -> Result<(), ShellError> {
let mut seen = HashSet::new();
for column in record.columns() {
if !seen.insert(column) {
return Err(ShellError::ColumnDefinedTwice {
col_name: column.clone(),
second_use: span,
first_use: span,
});
}
}
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
use nu_test_support::TestResultExt;
#[test]
fn test_examples() -> nu_test_support::Result {
nu_test_support::test().examples(Rename)
}
#[test]
fn test_duplicate_column_name_as_input() -> nu_test_support::Result {
nu_test_support::test()
.run("[[a b]; [6 7]] | rename x x")
.expect_error_code_eq("nu::shell::column_defined_twice")
}
#[test]
fn test_duplicate_column_name_after_eval() -> nu_test_support::Result {
nu_test_support::test()
.run("[[a x]; [6 7]] | rename x")
.expect_error_code_eq("nu::shell::column_defined_twice")
}
}