Skip to content

Commit

Permalink
Don't omit schema metadata when removing column (#5328)
Browse files Browse the repository at this point in the history
* Don't omit schema metadata when removing column

* Add test

* Update arrow-schema/src/schema.rs

Co-authored-by: Andrew Lamb <[email protected]>

---------

Co-authored-by: Andrew Lamb <[email protected]>
  • Loading branch information
kylebarron and alamb authored Feb 12, 2024
1 parent 0b45993 commit c9029c5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
31 changes: 30 additions & 1 deletion arrow-array/src/record_batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ impl RecordBatch {
/// assert_eq!(batch.num_columns(), 1);
/// ```
pub fn remove_column(&mut self, index: usize) -> ArrayRef {
let mut builder = SchemaBuilder::from(self.schema.fields());
let mut builder = SchemaBuilder::from(self.schema.as_ref());
builder.remove(index);
self.schema = Arc::new(builder.finish());
self.columns.remove(index)
Expand Down Expand Up @@ -618,6 +618,8 @@ where

#[cfg(test)]
mod tests {
use std::collections::HashMap;

use super::*;
use crate::{BooleanArray, Int32Array, Int64Array, Int8Array, ListArray, StringArray};
use arrow_buffer::{Buffer, ToByteSlice};
Expand Down Expand Up @@ -1155,4 +1157,31 @@ mod tests {
let size = get_size(reader);
assert_eq!(size, 0);
}

#[test]
fn test_remove_column_maintains_schema_metadata() {
let id_array = Int32Array::from(vec![1, 2, 3, 4, 5]);
let bool_array = BooleanArray::from(vec![true, false, false, true, true]);

let mut metadata = HashMap::new();
metadata.insert("foo".to_string(), "bar".to_string());
let schema = Schema::new(vec![
Field::new("id", DataType::Int32, false),
Field::new("bool", DataType::Boolean, false),
])
.with_metadata(metadata);

let mut batch = RecordBatch::try_new(
Arc::new(schema),
vec![Arc::new(id_array), Arc::new(bool_array)],
)
.unwrap();

let _removed_column = batch.remove_column(0);
assert_eq!(batch.schema().metadata().len(), 1);
assert_eq!(
batch.schema().metadata().get("foo").unwrap().as_str(),
"bar"
);
}
}
6 changes: 6 additions & 0 deletions arrow-schema/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ impl From<Fields> for SchemaBuilder {
}
}

impl From<&Schema> for SchemaBuilder {
fn from(value: &Schema) -> Self {
Self::from(value.clone())
}
}

impl From<Schema> for SchemaBuilder {
fn from(value: Schema) -> Self {
Self {
Expand Down

0 comments on commit c9029c5

Please sign in to comment.