@@ -204,6 +204,25 @@ impl RecordBatch {
204
204
} )
205
205
}
206
206
207
+ /// Override the schema of this [`RecordBatch`]
208
+ ///
209
+ /// Returns an error if `schema` is not a superset of the current schema
210
+ /// as determined by [`Schema::contains`]
211
+ pub fn with_schema ( self , schema : SchemaRef ) -> Result < Self , ArrowError > {
212
+ if !schema. contains ( self . schema . as_ref ( ) ) {
213
+ return Err ( ArrowError :: SchemaError ( format ! (
214
+ "{schema} is not a superset of {}" ,
215
+ self . schema
216
+ ) ) ) ;
217
+ }
218
+
219
+ Ok ( Self {
220
+ schema,
221
+ columns : self . columns ,
222
+ row_count : self . row_count ,
223
+ } )
224
+ }
225
+
207
226
/// Returns the [`Schema`](arrow_schema::Schema) of the record batch.
208
227
pub fn schema ( & self ) -> SchemaRef {
209
228
self . schema . clone ( )
@@ -1062,4 +1081,34 @@ mod tests {
1062
1081
) ) ;
1063
1082
let _ = RecordBatch :: from ( s) ;
1064
1083
}
1084
+
1085
+ #[ test]
1086
+ fn test_with_schema ( ) {
1087
+ let required_schema = Schema :: new ( vec ! [ Field :: new( "a" , DataType :: Int32 , false ) ] ) ;
1088
+ let required_schema = Arc :: new ( required_schema) ;
1089
+ let nullable_schema = Schema :: new ( vec ! [ Field :: new( "a" , DataType :: Int32 , true ) ] ) ;
1090
+ let nullable_schema = Arc :: new ( nullable_schema) ;
1091
+
1092
+ let batch = RecordBatch :: try_new (
1093
+ required_schema. clone ( ) ,
1094
+ vec ! [ Arc :: new( Int32Array :: from( vec![ 1 , 2 , 3 ] ) ) as _] ,
1095
+ )
1096
+ . unwrap ( ) ;
1097
+
1098
+ // Can add nullability
1099
+ let batch = batch. with_schema ( nullable_schema. clone ( ) ) . unwrap ( ) ;
1100
+
1101
+ // Cannot remove nullability
1102
+ batch. clone ( ) . with_schema ( required_schema) . unwrap_err ( ) ;
1103
+
1104
+ // Can add metadata
1105
+ let metadata = vec ! [ ( "foo" . to_string( ) , "bar" . to_string( ) ) ]
1106
+ . into_iter ( )
1107
+ . collect ( ) ;
1108
+ let metadata_schema = nullable_schema. as_ref ( ) . clone ( ) . with_metadata ( metadata) ;
1109
+ let batch = batch. with_schema ( Arc :: new ( metadata_schema) ) . unwrap ( ) ;
1110
+
1111
+ // Cannot remove metadata
1112
+ batch. with_schema ( nullable_schema) . unwrap_err ( ) ;
1113
+ }
1065
1114
}
0 commit comments