-
Notifications
You must be signed in to change notification settings - Fork 842
/
Copy pathwriter.rs
2836 lines (2507 loc) · 103 KB
/
writer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Arrow IPC File and Stream Writers
//!
//! The `FileWriter` and `StreamWriter` have similar interfaces,
//! however the `FileWriter` expects a reader that supports `Seek`ing
use std::cmp::min;
use std::collections::HashMap;
use std::io::{BufWriter, Write};
use std::mem::size_of;
use std::sync::Arc;
use flatbuffers::FlatBufferBuilder;
use arrow_array::builder::BufferBuilder;
use arrow_array::cast::*;
use arrow_array::types::{Int16Type, Int32Type, Int64Type, RunEndIndexType};
use arrow_array::*;
use arrow_buffer::bit_util;
use arrow_buffer::{ArrowNativeType, Buffer, MutableBuffer};
use arrow_data::{layout, ArrayData, ArrayDataBuilder, BufferSpec};
use arrow_schema::*;
use crate::compression::CompressionCodec;
use crate::convert::IpcSchemaEncoder;
use crate::CONTINUATION_MARKER;
/// IPC write options used to control the behaviour of the [`IpcDataGenerator`]
#[derive(Debug, Clone)]
pub struct IpcWriteOptions {
/// Write padding after memory buffers to this multiple of bytes.
/// Must be 8, 16, 32, or 64 - defaults to 64.
alignment: u8,
/// The legacy format is for releases before 0.15.0, and uses metadata V4
write_legacy_ipc_format: bool,
/// The metadata version to write. The Rust IPC writer supports V4+
///
/// *Default versions per crate*
///
/// When creating the default IpcWriteOptions, the following metadata versions are used:
///
/// version 2.0.0: V4, with legacy format enabled
/// version 4.0.0: V5
metadata_version: crate::MetadataVersion,
/// Compression, if desired. Will result in a runtime error
/// if the corresponding feature is not enabled
batch_compression_type: Option<crate::CompressionType>,
/// Flag indicating whether the writer should preserve the dictionary IDs defined in the
/// schema or generate unique dictionary IDs internally during encoding.
///
/// Defaults to `true`
preserve_dict_id: bool,
}
impl IpcWriteOptions {
/// Configures compression when writing IPC files.
///
/// Will result in a runtime error if the corresponding feature
/// is not enabled
pub fn try_with_compression(
mut self,
batch_compression_type: Option<crate::CompressionType>,
) -> Result<Self, ArrowError> {
self.batch_compression_type = batch_compression_type;
if self.batch_compression_type.is_some()
&& self.metadata_version < crate::MetadataVersion::V5
{
return Err(ArrowError::InvalidArgumentError(
"Compression only supported in metadata v5 and above".to_string(),
));
}
Ok(self)
}
/// Try to create IpcWriteOptions, checking for incompatible settings
pub fn try_new(
alignment: usize,
write_legacy_ipc_format: bool,
metadata_version: crate::MetadataVersion,
) -> Result<Self, ArrowError> {
let is_alignment_valid =
alignment == 8 || alignment == 16 || alignment == 32 || alignment == 64;
if !is_alignment_valid {
return Err(ArrowError::InvalidArgumentError(
"Alignment should be 8, 16, 32, or 64.".to_string(),
));
}
let alignment: u8 = u8::try_from(alignment).expect("range already checked");
match metadata_version {
crate::MetadataVersion::V1
| crate::MetadataVersion::V2
| crate::MetadataVersion::V3 => Err(ArrowError::InvalidArgumentError(
"Writing IPC metadata version 3 and lower not supported".to_string(),
)),
crate::MetadataVersion::V4 => Ok(Self {
alignment,
write_legacy_ipc_format,
metadata_version,
batch_compression_type: None,
preserve_dict_id: true,
}),
crate::MetadataVersion::V5 => {
if write_legacy_ipc_format {
Err(ArrowError::InvalidArgumentError(
"Legacy IPC format only supported on metadata version 4".to_string(),
))
} else {
Ok(Self {
alignment,
write_legacy_ipc_format,
metadata_version,
batch_compression_type: None,
preserve_dict_id: true,
})
}
}
z => Err(ArrowError::InvalidArgumentError(format!(
"Unsupported crate::MetadataVersion {z:?}"
))),
}
}
/// Return whether the writer is configured to preserve the dictionary IDs
/// defined in the schema
pub fn preserve_dict_id(&self) -> bool {
self.preserve_dict_id
}
/// Set whether the IPC writer should preserve the dictionary IDs in the schema
/// or auto-assign unique dictionary IDs during encoding (defaults to true)
///
/// If this option is true, the application must handle assigning ids
/// to the dictionary batches in order to encode them correctly
///
/// The default will change to `false` in future releases
pub fn with_preserve_dict_id(mut self, preserve_dict_id: bool) -> Self {
self.preserve_dict_id = preserve_dict_id;
self
}
}
impl Default for IpcWriteOptions {
fn default() -> Self {
Self {
alignment: 64,
write_legacy_ipc_format: false,
metadata_version: crate::MetadataVersion::V5,
batch_compression_type: None,
preserve_dict_id: true,
}
}
}
#[derive(Debug, Default)]
/// Handles low level details of encoding [`Array`] and [`Schema`] into the
/// [Arrow IPC Format].
///
/// # Example:
/// ```
/// # fn run() {
/// # use std::sync::Arc;
/// # use arrow_array::UInt64Array;
/// # use arrow_array::RecordBatch;
/// # use arrow_ipc::writer::{DictionaryTracker, IpcDataGenerator, IpcWriteOptions};
///
/// // Create a record batch
/// let batch = RecordBatch::try_from_iter(vec![
/// ("col2", Arc::new(UInt64Array::from_iter([10, 23, 33])) as _)
/// ]).unwrap();
///
/// // Error of dictionary ids are replaced.
/// let error_on_replacement = true;
/// let options = IpcWriteOptions::default();
/// let mut dictionary_tracker = DictionaryTracker::new(error_on_replacement);
///
/// // encode the batch into zero or more encoded dictionaries
/// // and the data for the actual array.
/// let data_gen = IpcDataGenerator::default();
/// let (encoded_dictionaries, encoded_message) = data_gen
/// .encoded_batch(&batch, &mut dictionary_tracker, &options)
/// .unwrap();
/// # }
/// ```
///
/// [Arrow IPC Format]: https://arrow.apache.org/docs/format/Columnar.html#serialization-and-interprocess-communication-ipc
pub struct IpcDataGenerator {}
impl IpcDataGenerator {
/// Converts a schema to an IPC message along with `dictionary_tracker`
/// and returns it encoded inside [EncodedData] as a flatbuffer
///
/// Preferred method over [IpcDataGenerator::schema_to_bytes] since it's
/// deprecated since Arrow v54.0.0
pub fn schema_to_bytes_with_dictionary_tracker(
&self,
schema: &Schema,
dictionary_tracker: &mut DictionaryTracker,
write_options: &IpcWriteOptions,
) -> EncodedData {
let mut fbb = FlatBufferBuilder::new();
let schema = {
let fb = IpcSchemaEncoder::new()
.with_dictionary_tracker(dictionary_tracker)
.schema_to_fb_offset(&mut fbb, schema);
fb.as_union_value()
};
let mut message = crate::MessageBuilder::new(&mut fbb);
message.add_version(write_options.metadata_version);
message.add_header_type(crate::MessageHeader::Schema);
message.add_bodyLength(0);
message.add_header(schema);
// TODO: custom metadata
let data = message.finish();
fbb.finish(data, None);
let data = fbb.finished_data();
EncodedData {
ipc_message: data.to_vec(),
arrow_data: vec![],
}
}
#[deprecated(
since = "54.0.0",
note = "Use `schema_to_bytes_with_dictionary_tracker` instead. This function signature of `schema_to_bytes_with_dictionary_tracker` in the next release."
)]
/// Converts a schema to an IPC message and returns it encoded inside [EncodedData] as a flatbuffer
pub fn schema_to_bytes(&self, schema: &Schema, write_options: &IpcWriteOptions) -> EncodedData {
let mut fbb = FlatBufferBuilder::new();
let schema = {
#[allow(deprecated)]
// This will be replaced with the IpcSchemaConverter in the next release.
let fb = crate::convert::schema_to_fb_offset(&mut fbb, schema);
fb.as_union_value()
};
let mut message = crate::MessageBuilder::new(&mut fbb);
message.add_version(write_options.metadata_version);
message.add_header_type(crate::MessageHeader::Schema);
message.add_bodyLength(0);
message.add_header(schema);
// TODO: custom metadata
let data = message.finish();
fbb.finish(data, None);
let data = fbb.finished_data();
EncodedData {
ipc_message: data.to_vec(),
arrow_data: vec![],
}
}
fn _encode_dictionaries<I: Iterator<Item = i64>>(
&self,
column: &ArrayRef,
encoded_dictionaries: &mut Vec<EncodedData>,
dictionary_tracker: &mut DictionaryTracker,
write_options: &IpcWriteOptions,
dict_id: &mut I,
) -> Result<(), ArrowError> {
match column.data_type() {
DataType::Struct(fields) => {
let s = as_struct_array(column);
for (field, column) in fields.iter().zip(s.columns()) {
self.encode_dictionaries(
field,
column,
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
}
}
DataType::RunEndEncoded(_, values) => {
let data = column.to_data();
if data.child_data().len() != 2 {
return Err(ArrowError::InvalidArgumentError(format!(
"The run encoded array should have exactly two child arrays. Found {}",
data.child_data().len()
)));
}
// The run_ends array is not expected to be dictionary encoded. Hence encode dictionaries
// only for values array.
let values_array = make_array(data.child_data()[1].clone());
self.encode_dictionaries(
values,
&values_array,
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
}
DataType::List(field) => {
let list = as_list_array(column);
self.encode_dictionaries(
field,
list.values(),
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
}
DataType::LargeList(field) => {
let list = as_large_list_array(column);
self.encode_dictionaries(
field,
list.values(),
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
}
DataType::FixedSizeList(field, _) => {
let list = column
.as_any()
.downcast_ref::<FixedSizeListArray>()
.expect("Unable to downcast to fixed size list array");
self.encode_dictionaries(
field,
list.values(),
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
}
DataType::Map(field, _) => {
let map_array = as_map_array(column);
let (keys, values) = match field.data_type() {
DataType::Struct(fields) if fields.len() == 2 => (&fields[0], &fields[1]),
_ => panic!("Incorrect field data type {:?}", field.data_type()),
};
// keys
self.encode_dictionaries(
keys,
map_array.keys(),
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
// values
self.encode_dictionaries(
values,
map_array.values(),
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
}
DataType::Union(fields, _) => {
let union = as_union_array(column);
for (type_id, field) in fields.iter() {
let column = union.child(type_id);
self.encode_dictionaries(
field,
column,
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id,
)?;
}
}
_ => (),
}
Ok(())
}
fn encode_dictionaries<I: Iterator<Item = i64>>(
&self,
field: &Field,
column: &ArrayRef,
encoded_dictionaries: &mut Vec<EncodedData>,
dictionary_tracker: &mut DictionaryTracker,
write_options: &IpcWriteOptions,
dict_id_seq: &mut I,
) -> Result<(), ArrowError> {
match column.data_type() {
DataType::Dictionary(_key_type, _value_type) => {
let dict_data = column.to_data();
let dict_values = &dict_data.child_data()[0];
let values = make_array(dict_data.child_data()[0].clone());
self._encode_dictionaries(
&values,
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id_seq,
)?;
// It's importnat to only take the dict_id at this point, because the dict ID
// sequence is assigned depth-first, so we need to first encode children and have
// them take their assigned dict IDs before we take the dict ID for this field.
let dict_id = dict_id_seq
.next()
.or_else(|| field.dict_id())
.ok_or_else(|| {
ArrowError::IpcError(format!("no dict id for field {}", field.name()))
})?;
let emit = dictionary_tracker.insert(dict_id, column)?;
if emit {
encoded_dictionaries.push(self.dictionary_batch_to_bytes(
dict_id,
dict_values,
write_options,
)?);
}
}
_ => self._encode_dictionaries(
column,
encoded_dictionaries,
dictionary_tracker,
write_options,
dict_id_seq,
)?,
}
Ok(())
}
/// Encodes a batch to a number of [EncodedData] items (dictionary batches + the record batch).
/// The [DictionaryTracker] keeps track of dictionaries with new `dict_id`s (so they are only sent once)
/// Make sure the [DictionaryTracker] is initialized at the start of the stream.
pub fn encoded_batch(
&self,
batch: &RecordBatch,
dictionary_tracker: &mut DictionaryTracker,
write_options: &IpcWriteOptions,
) -> Result<(Vec<EncodedData>, EncodedData), ArrowError> {
let schema = batch.schema();
let mut encoded_dictionaries = Vec::with_capacity(schema.flattened_fields().len());
let mut dict_id = dictionary_tracker.dict_ids.clone().into_iter();
for (i, field) in schema.fields().iter().enumerate() {
let column = batch.column(i);
self.encode_dictionaries(
field,
column,
&mut encoded_dictionaries,
dictionary_tracker,
write_options,
&mut dict_id,
)?;
}
let encoded_message = self.record_batch_to_bytes(batch, write_options)?;
Ok((encoded_dictionaries, encoded_message))
}
/// Write a `RecordBatch` into two sets of bytes, one for the header (crate::Message) and the
/// other for the batch's data
fn record_batch_to_bytes(
&self,
batch: &RecordBatch,
write_options: &IpcWriteOptions,
) -> Result<EncodedData, ArrowError> {
let mut fbb = FlatBufferBuilder::new();
let mut nodes: Vec<crate::FieldNode> = vec![];
let mut buffers: Vec<crate::Buffer> = vec![];
let mut arrow_data: Vec<u8> = vec![];
let mut offset = 0;
// get the type of compression
let batch_compression_type = write_options.batch_compression_type;
let compression = batch_compression_type.map(|batch_compression_type| {
let mut c = crate::BodyCompressionBuilder::new(&mut fbb);
c.add_method(crate::BodyCompressionMethod::BUFFER);
c.add_codec(batch_compression_type);
c.finish()
});
let compression_codec: Option<CompressionCodec> =
batch_compression_type.map(TryInto::try_into).transpose()?;
let mut variadic_buffer_counts = vec![];
for array in batch.columns() {
let array_data = array.to_data();
offset = write_array_data(
&array_data,
&mut buffers,
&mut arrow_data,
&mut nodes,
offset,
array.len(),
array.null_count(),
compression_codec,
write_options,
)?;
append_variadic_buffer_counts(&mut variadic_buffer_counts, &array_data);
}
// pad the tail of body data
let len = arrow_data.len();
let pad_len = pad_to_alignment(write_options.alignment, len);
arrow_data.extend_from_slice(&PADDING[..pad_len]);
// write data
let buffers = fbb.create_vector(&buffers);
let nodes = fbb.create_vector(&nodes);
let variadic_buffer = if variadic_buffer_counts.is_empty() {
None
} else {
Some(fbb.create_vector(&variadic_buffer_counts))
};
let root = {
let mut batch_builder = crate::RecordBatchBuilder::new(&mut fbb);
batch_builder.add_length(batch.num_rows() as i64);
batch_builder.add_nodes(nodes);
batch_builder.add_buffers(buffers);
if let Some(c) = compression {
batch_builder.add_compression(c);
}
if let Some(v) = variadic_buffer {
batch_builder.add_variadicBufferCounts(v);
}
let b = batch_builder.finish();
b.as_union_value()
};
// create an crate::Message
let mut message = crate::MessageBuilder::new(&mut fbb);
message.add_version(write_options.metadata_version);
message.add_header_type(crate::MessageHeader::RecordBatch);
message.add_bodyLength(arrow_data.len() as i64);
message.add_header(root);
let root = message.finish();
fbb.finish(root, None);
let finished_data = fbb.finished_data();
Ok(EncodedData {
ipc_message: finished_data.to_vec(),
arrow_data,
})
}
/// Write dictionary values into two sets of bytes, one for the header (crate::Message) and the
/// other for the data
fn dictionary_batch_to_bytes(
&self,
dict_id: i64,
array_data: &ArrayData,
write_options: &IpcWriteOptions,
) -> Result<EncodedData, ArrowError> {
let mut fbb = FlatBufferBuilder::new();
let mut nodes: Vec<crate::FieldNode> = vec![];
let mut buffers: Vec<crate::Buffer> = vec![];
let mut arrow_data: Vec<u8> = vec![];
// get the type of compression
let batch_compression_type = write_options.batch_compression_type;
let compression = batch_compression_type.map(|batch_compression_type| {
let mut c = crate::BodyCompressionBuilder::new(&mut fbb);
c.add_method(crate::BodyCompressionMethod::BUFFER);
c.add_codec(batch_compression_type);
c.finish()
});
let compression_codec: Option<CompressionCodec> = batch_compression_type
.map(|batch_compression_type| batch_compression_type.try_into())
.transpose()?;
write_array_data(
array_data,
&mut buffers,
&mut arrow_data,
&mut nodes,
0,
array_data.len(),
array_data.null_count(),
compression_codec,
write_options,
)?;
let mut variadic_buffer_counts = vec![];
append_variadic_buffer_counts(&mut variadic_buffer_counts, array_data);
// pad the tail of body data
let len = arrow_data.len();
let pad_len = pad_to_alignment(write_options.alignment, len);
arrow_data.extend_from_slice(&PADDING[..pad_len]);
// write data
let buffers = fbb.create_vector(&buffers);
let nodes = fbb.create_vector(&nodes);
let variadic_buffer = if variadic_buffer_counts.is_empty() {
None
} else {
Some(fbb.create_vector(&variadic_buffer_counts))
};
let root = {
let mut batch_builder = crate::RecordBatchBuilder::new(&mut fbb);
batch_builder.add_length(array_data.len() as i64);
batch_builder.add_nodes(nodes);
batch_builder.add_buffers(buffers);
if let Some(c) = compression {
batch_builder.add_compression(c);
}
if let Some(v) = variadic_buffer {
batch_builder.add_variadicBufferCounts(v);
}
batch_builder.finish()
};
let root = {
let mut batch_builder = crate::DictionaryBatchBuilder::new(&mut fbb);
batch_builder.add_id(dict_id);
batch_builder.add_data(root);
batch_builder.finish().as_union_value()
};
let root = {
let mut message_builder = crate::MessageBuilder::new(&mut fbb);
message_builder.add_version(write_options.metadata_version);
message_builder.add_header_type(crate::MessageHeader::DictionaryBatch);
message_builder.add_bodyLength(arrow_data.len() as i64);
message_builder.add_header(root);
message_builder.finish()
};
fbb.finish(root, None);
let finished_data = fbb.finished_data();
Ok(EncodedData {
ipc_message: finished_data.to_vec(),
arrow_data,
})
}
}
fn append_variadic_buffer_counts(counts: &mut Vec<i64>, array: &ArrayData) {
match array.data_type() {
DataType::BinaryView | DataType::Utf8View => {
// The spec documents the counts only includes the variadic buffers, not the view/null buffers.
// https://arrow.apache.org/docs/format/Columnar.html#variadic-buffers
counts.push(array.buffers().len() as i64 - 1);
}
DataType::Dictionary(_, _) => {
// Do nothing
// Dictionary types are handled in `encode_dictionaries`.
}
_ => {
for child in array.child_data() {
append_variadic_buffer_counts(counts, child)
}
}
}
}
pub(crate) fn unslice_run_array(arr: ArrayData) -> Result<ArrayData, ArrowError> {
match arr.data_type() {
DataType::RunEndEncoded(k, _) => match k.data_type() {
DataType::Int16 => {
Ok(into_zero_offset_run_array(RunArray::<Int16Type>::from(arr))?.into_data())
}
DataType::Int32 => {
Ok(into_zero_offset_run_array(RunArray::<Int32Type>::from(arr))?.into_data())
}
DataType::Int64 => {
Ok(into_zero_offset_run_array(RunArray::<Int64Type>::from(arr))?.into_data())
}
d => unreachable!("Unexpected data type {d}"),
},
d => Err(ArrowError::InvalidArgumentError(format!(
"The given array is not a run array. Data type of given array: {d}"
))),
}
}
// Returns a `RunArray` with zero offset and length matching the last value
// in run_ends array.
fn into_zero_offset_run_array<R: RunEndIndexType>(
run_array: RunArray<R>,
) -> Result<RunArray<R>, ArrowError> {
let run_ends = run_array.run_ends();
if run_ends.offset() == 0 && run_ends.max_value() == run_ends.len() {
return Ok(run_array);
}
// The physical index of original run_ends array from which the `ArrayData`is sliced.
let start_physical_index = run_ends.get_start_physical_index();
// The physical index of original run_ends array until which the `ArrayData`is sliced.
let end_physical_index = run_ends.get_end_physical_index();
let physical_length = end_physical_index - start_physical_index + 1;
// build new run_ends array by subtracting offset from run ends.
let offset = R::Native::usize_as(run_ends.offset());
let mut builder = BufferBuilder::<R::Native>::new(physical_length);
for run_end_value in &run_ends.values()[start_physical_index..end_physical_index] {
builder.append(run_end_value.sub_wrapping(offset));
}
builder.append(R::Native::from_usize(run_array.len()).unwrap());
let new_run_ends = unsafe {
// Safety:
// The function builds a valid run_ends array and hence need not be validated.
ArrayDataBuilder::new(R::DATA_TYPE)
.len(physical_length)
.add_buffer(builder.finish())
.build_unchecked()
};
// build new values by slicing physical indices.
let new_values = run_array
.values()
.slice(start_physical_index, physical_length)
.into_data();
let builder = ArrayDataBuilder::new(run_array.data_type().clone())
.len(run_array.len())
.add_child_data(new_run_ends)
.add_child_data(new_values);
let array_data = unsafe {
// Safety:
// This function builds a valid run array and hence can skip validation.
builder.build_unchecked()
};
Ok(array_data.into())
}
/// Keeps track of dictionaries that have been written, to avoid emitting the same dictionary
/// multiple times.
///
/// Can optionally error if an update to an existing dictionary is attempted, which
/// isn't allowed in the `FileWriter`.
#[derive(Debug)]
pub struct DictionaryTracker {
written: HashMap<i64, ArrayData>,
dict_ids: Vec<i64>,
error_on_replacement: bool,
preserve_dict_id: bool,
}
impl DictionaryTracker {
/// Create a new [`DictionaryTracker`].
///
/// If `error_on_replacement`
/// is true, an error will be generated if an update to an
/// existing dictionary is attempted.
///
/// If `preserve_dict_id` is true, the dictionary ID defined in the schema
/// is used, otherwise a unique dictionary ID will be assigned by incrementing
/// the last seen dictionary ID (or using `0` if no other dictionary IDs have been
/// seen)
pub fn new(error_on_replacement: bool) -> Self {
Self {
written: HashMap::new(),
dict_ids: Vec::new(),
error_on_replacement,
preserve_dict_id: true,
}
}
/// Create a new [`DictionaryTracker`].
///
/// If `error_on_replacement`
/// is true, an error will be generated if an update to an
/// existing dictionary is attempted.
pub fn new_with_preserve_dict_id(error_on_replacement: bool, preserve_dict_id: bool) -> Self {
Self {
written: HashMap::new(),
dict_ids: Vec::new(),
error_on_replacement,
preserve_dict_id,
}
}
/// Set the dictionary ID for `field`.
///
/// If `preserve_dict_id` is true, this will return the `dict_id` in `field` (or panic if `field` does
/// not have a `dict_id` defined).
///
/// If `preserve_dict_id` is false, this will return the value of the last `dict_id` assigned incremented by 1
/// or 0 in the case where no dictionary IDs have yet been assigned
pub fn set_dict_id(&mut self, field: &Field) -> i64 {
let next = if self.preserve_dict_id {
field.dict_id().expect("no dict_id in field")
} else {
self.dict_ids
.last()
.copied()
.map(|i| i + 1)
.unwrap_or_default()
};
self.dict_ids.push(next);
next
}
/// Return the sequence of dictionary IDs in the order they should be observed while
/// traversing the schema
pub fn dict_id(&mut self) -> &[i64] {
&self.dict_ids
}
/// Keep track of the dictionary with the given ID and values. Behavior:
///
/// * If this ID has been written already and has the same data, return `Ok(false)` to indicate
/// that the dictionary was not actually inserted (because it's already been seen).
/// * If this ID has been written already but with different data, and this tracker is
/// configured to return an error, return an error.
/// * If the tracker has not been configured to error on replacement or this dictionary
/// has never been seen before, return `Ok(true)` to indicate that the dictionary was just
/// inserted.
pub fn insert(&mut self, dict_id: i64, column: &ArrayRef) -> Result<bool, ArrowError> {
let dict_data = column.to_data();
let dict_values = &dict_data.child_data()[0];
// If a dictionary with this id was already emitted, check if it was the same.
if let Some(last) = self.written.get(&dict_id) {
if ArrayData::ptr_eq(&last.child_data()[0], dict_values) {
// Same dictionary values => no need to emit it again
return Ok(false);
}
if self.error_on_replacement {
// If error on replacement perform a logical comparison
if last.child_data()[0] == *dict_values {
// Same dictionary values => no need to emit it again
return Ok(false);
}
return Err(ArrowError::InvalidArgumentError(
"Dictionary replacement detected when writing IPC file format. \
Arrow IPC files only support a single dictionary for a given field \
across all batches."
.to_string(),
));
}
}
self.written.insert(dict_id, dict_data);
Ok(true)
}
}
/// Writer for an IPC file
pub struct FileWriter<W> {
/// The object to write to
writer: W,
/// IPC write options
write_options: IpcWriteOptions,
/// A reference to the schema, used in validating record batches
schema: SchemaRef,
/// The number of bytes between each block of bytes, as an offset for random access
block_offsets: usize,
/// Dictionary blocks that will be written as part of the IPC footer
dictionary_blocks: Vec<crate::Block>,
/// Record blocks that will be written as part of the IPC footer
record_blocks: Vec<crate::Block>,
/// Whether the writer footer has been written, and the writer is finished
finished: bool,
/// Keeps track of dictionaries that have been written
dictionary_tracker: DictionaryTracker,
/// User level customized metadata
custom_metadata: HashMap<String, String>,
data_gen: IpcDataGenerator,
}
impl<W: Write> FileWriter<BufWriter<W>> {
/// Try to create a new file writer with the writer wrapped in a BufWriter.
///
/// See [`FileWriter::try_new`] for an unbuffered version.
pub fn try_new_buffered(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
Self::try_new(BufWriter::new(writer), schema)
}
}
impl<W: Write> FileWriter<W> {
/// Try to create a new writer, with the schema written as part of the header
///
/// Note the created writer is not buffered. See [`FileWriter::try_new_buffered`] for details.
///
/// # Errors
///
/// An ['Err'](Result::Err) may be returned if writing the header to the writer fails.
pub fn try_new(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
let write_options = IpcWriteOptions::default();
Self::try_new_with_options(writer, schema, write_options)
}
/// Try to create a new writer with IpcWriteOptions
///
/// Note the created writer is not buffered. See [`FileWriter::try_new_buffered`] for details.
///
/// # Errors
///
/// An ['Err'](Result::Err) may be returned if writing the header to the writer fails.
pub fn try_new_with_options(
mut writer: W,
schema: &Schema,
write_options: IpcWriteOptions,
) -> Result<Self, ArrowError> {
let data_gen = IpcDataGenerator::default();
// write magic to header aligned on alignment boundary
let pad_len = pad_to_alignment(write_options.alignment, super::ARROW_MAGIC.len());
let header_size = super::ARROW_MAGIC.len() + pad_len;
writer.write_all(&super::ARROW_MAGIC)?;
writer.write_all(&PADDING[..pad_len])?;
// write the schema, set the written bytes to the schema + header
let preserve_dict_id = write_options.preserve_dict_id;
let mut dictionary_tracker =
DictionaryTracker::new_with_preserve_dict_id(true, preserve_dict_id);
let encoded_message = data_gen.schema_to_bytes_with_dictionary_tracker(
schema,
&mut dictionary_tracker,
&write_options,
);
let (meta, data) = write_message(&mut writer, encoded_message, &write_options)?;
Ok(Self {
writer,
write_options,
schema: Arc::new(schema.clone()),
block_offsets: meta + data + header_size,
dictionary_blocks: vec![],
record_blocks: vec![],
finished: false,
dictionary_tracker,
custom_metadata: HashMap::new(),
data_gen,
})
}
/// Adds a key-value pair to the [FileWriter]'s custom metadata
pub fn write_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.custom_metadata.insert(key.into(), value.into());
}
/// Write a record batch to the file
pub fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
if self.finished {
return Err(ArrowError::IpcError(
"Cannot write record batch to file writer as it is closed".to_string(),
));
}
let (encoded_dictionaries, encoded_message) = self.data_gen.encoded_batch(
batch,
&mut self.dictionary_tracker,
&self.write_options,
)?;
for encoded_dictionary in encoded_dictionaries {
let (meta, data) =
write_message(&mut self.writer, encoded_dictionary, &self.write_options)?;
let block = crate::Block::new(self.block_offsets as i64, meta as i32, data as i64);
self.dictionary_blocks.push(block);
self.block_offsets += meta + data;
}
let (meta, data) = write_message(&mut self.writer, encoded_message, &self.write_options)?;
// add a record block for the footer
let block = crate::Block::new(
self.block_offsets as i64,
meta as i32, // TODO: is this still applicable?
data as i64,
);
self.record_blocks.push(block);
self.block_offsets += meta + data;
Ok(())
}