-
Notifications
You must be signed in to change notification settings - Fork 793
/
writer.rs
1831 lines (1634 loc) · 67.6 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.
//! Contains file writer API, and provides methods to write row groups and columns by
//! using row group writers and column writers respectively.
use crate::bloom_filter::Sbbf;
use crate::format as parquet;
use crate::format::{ColumnIndex, OffsetIndex, RowGroup};
use crate::thrift::TSerializable;
use std::fmt::Debug;
use std::io::{BufWriter, IoSlice, Read};
use std::{io::Write, sync::Arc};
use thrift::protocol::TCompactOutputProtocol;
use crate::column::writer::{get_typed_column_writer_mut, ColumnCloseResult, ColumnWriterImpl};
use crate::column::{
page::{CompressedPage, PageWriteSpec, PageWriter},
writer::{get_column_writer, ColumnWriter},
};
use crate::data_type::DataType;
use crate::errors::{ParquetError, Result};
use crate::file::reader::ChunkReader;
use crate::file::{metadata::*, properties::WriterPropertiesPtr, PARQUET_MAGIC};
use crate::schema::types::{self, ColumnDescPtr, SchemaDescPtr, SchemaDescriptor, TypePtr};
/// A wrapper around a [`Write`] that keeps track of the number
/// of bytes that have been written. The given [`Write`] is wrapped
/// with a [`BufWriter`] to optimize writing performance.
pub struct TrackedWrite<W: Write> {
inner: BufWriter<W>,
bytes_written: usize,
}
impl<W: Write> TrackedWrite<W> {
/// Create a new [`TrackedWrite`] from a [`Write`]
pub fn new(inner: W) -> Self {
let buf_write = BufWriter::new(inner);
Self {
inner: buf_write,
bytes_written: 0,
}
}
/// Returns the number of bytes written to this instance
pub fn bytes_written(&self) -> usize {
self.bytes_written
}
/// Returns a reference to the underlying writer.
pub fn inner(&self) -> &W {
self.inner.get_ref()
}
/// Returns a mutable reference to the underlying writer.
///
/// It is inadvisable to directly write to the underlying writer, doing so
/// will likely result in data corruption
pub fn inner_mut(&mut self) -> &mut W {
self.inner.get_mut()
}
/// Returns the underlying writer.
pub fn into_inner(self) -> Result<W> {
self.inner.into_inner().map_err(|err| {
ParquetError::General(format!("fail to get inner writer: {:?}", err.to_string()))
})
}
}
impl<W: Write> Write for TrackedWrite<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let bytes = self.inner.write(buf)?;
self.bytes_written += bytes;
Ok(bytes)
}
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> std::io::Result<usize> {
let bytes = self.inner.write_vectored(bufs)?;
self.bytes_written += bytes;
Ok(bytes)
}
fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
self.inner.write_all(buf)?;
self.bytes_written += buf.len();
Ok(())
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
/// Callback invoked on closing a column chunk
pub type OnCloseColumnChunk<'a> = Box<dyn FnOnce(ColumnCloseResult) -> Result<()> + 'a>;
/// Callback invoked on closing a row group, arguments are:
///
/// - the row group metadata
/// - the column index for each column chunk
/// - the offset index for each column chunk
pub type OnCloseRowGroup<'a> = Box<
dyn FnOnce(
RowGroupMetaDataPtr,
Vec<Option<Sbbf>>,
Vec<Option<ColumnIndex>>,
Vec<Option<OffsetIndex>>,
) -> Result<()>
+ 'a
+ Send,
>;
// ----------------------------------------------------------------------
// Serialized impl for file & row group writers
/// Parquet file writer API.
/// Provides methods to write row groups sequentially.
///
/// The main workflow should be as following:
/// - Create file writer, this will open a new file and potentially write some metadata.
/// - Request a new row group writer by calling `next_row_group`.
/// - Once finished writing row group, close row group writer by calling `close`
/// - Write subsequent row groups, if necessary.
/// - After all row groups have been written, close the file writer using `close` method.
pub struct SerializedFileWriter<W: Write> {
buf: TrackedWrite<W>,
schema: TypePtr,
descr: SchemaDescPtr,
props: WriterPropertiesPtr,
row_groups: Vec<RowGroupMetaDataPtr>,
bloom_filters: Vec<Vec<Option<Sbbf>>>,
column_indexes: Vec<Vec<Option<ColumnIndex>>>,
offset_indexes: Vec<Vec<Option<OffsetIndex>>>,
row_group_index: usize,
// kv_metadatas will be appended to `props` when `write_metadata`
kv_metadatas: Vec<KeyValue>,
finished: bool,
}
impl<W: Write> Debug for SerializedFileWriter<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// implement Debug so this can be used with #[derive(Debug)]
// in client code rather than actually listing all the fields
f.debug_struct("SerializedFileWriter")
.field("descr", &self.descr)
.field("row_group_index", &self.row_group_index)
.field("kv_metadatas", &self.kv_metadatas)
.finish_non_exhaustive()
}
}
impl<W: Write + Send> SerializedFileWriter<W> {
/// Creates new file writer.
pub fn new(buf: W, schema: TypePtr, properties: WriterPropertiesPtr) -> Result<Self> {
let mut buf = TrackedWrite::new(buf);
Self::start_file(&mut buf)?;
Ok(Self {
buf,
schema: schema.clone(),
descr: Arc::new(SchemaDescriptor::new(schema)),
props: properties,
row_groups: vec![],
bloom_filters: vec![],
column_indexes: Vec::new(),
offset_indexes: Vec::new(),
row_group_index: 0,
kv_metadatas: Vec::new(),
finished: false,
})
}
/// Creates new row group from this file writer.
/// In case of IO error or Thrift error, returns `Err`.
///
/// There is no limit on a number of row groups in a file; however, row groups have
/// to be written sequentially. Every time the next row group is requested, the
/// previous row group must be finalised and closed using `RowGroupWriter::close` method.
pub fn next_row_group(&mut self) -> Result<SerializedRowGroupWriter<'_, W>> {
self.assert_previous_writer_closed()?;
let ordinal = self.row_group_index;
self.row_group_index += 1;
let row_groups = &mut self.row_groups;
let row_bloom_filters = &mut self.bloom_filters;
let row_column_indexes = &mut self.column_indexes;
let row_offset_indexes = &mut self.offset_indexes;
let on_close =
|metadata, row_group_bloom_filter, row_group_column_index, row_group_offset_index| {
row_groups.push(metadata);
row_bloom_filters.push(row_group_bloom_filter);
row_column_indexes.push(row_group_column_index);
row_offset_indexes.push(row_group_offset_index);
Ok(())
};
let row_group_writer = SerializedRowGroupWriter::new(
self.descr.clone(),
self.props.clone(),
&mut self.buf,
ordinal as i16,
Some(Box::new(on_close)),
);
Ok(row_group_writer)
}
/// Returns metadata for any flushed row groups
pub fn flushed_row_groups(&self) -> &[RowGroupMetaDataPtr] {
&self.row_groups
}
/// Close and finalize the underlying Parquet writer
///
/// Unlike [`Self::close`] this does not consume self
///
/// Attempting to write after calling finish will result in an error
pub fn finish(&mut self) -> Result<parquet::FileMetaData> {
self.assert_previous_writer_closed()?;
let metadata = self.write_metadata()?;
self.buf.flush()?;
Ok(metadata)
}
/// Closes and finalises file writer, returning the file metadata.
pub fn close(mut self) -> Result<parquet::FileMetaData> {
self.finish()
}
/// Writes magic bytes at the beginning of the file.
fn start_file(buf: &mut TrackedWrite<W>) -> Result<()> {
buf.write_all(&PARQUET_MAGIC)?;
Ok(())
}
/// Serialize all the offset index to the file
fn write_offset_indexes(&mut self, row_groups: &mut [RowGroup]) -> Result<()> {
// iter row group
// iter each column
// write offset index to the file
for (row_group_idx, row_group) in row_groups.iter_mut().enumerate() {
for (column_idx, column_metadata) in row_group.columns.iter_mut().enumerate() {
match &self.offset_indexes[row_group_idx][column_idx] {
Some(offset_index) => {
let start_offset = self.buf.bytes_written();
let mut protocol = TCompactOutputProtocol::new(&mut self.buf);
offset_index.write_to_out_protocol(&mut protocol)?;
let end_offset = self.buf.bytes_written();
// set offset and index for offset index
column_metadata.offset_index_offset = Some(start_offset as i64);
column_metadata.offset_index_length =
Some((end_offset - start_offset) as i32);
}
None => {}
}
}
}
Ok(())
}
/// Serialize all the bloom filter to the file
fn write_bloom_filters(&mut self, row_groups: &mut [RowGroup]) -> Result<()> {
// iter row group
// iter each column
// write bloom filter to the file
for (row_group_idx, row_group) in row_groups.iter_mut().enumerate() {
for (column_idx, column_chunk) in row_group.columns.iter_mut().enumerate() {
match &self.bloom_filters[row_group_idx][column_idx] {
Some(bloom_filter) => {
let start_offset = self.buf.bytes_written();
bloom_filter.write(&mut self.buf)?;
let end_offset = self.buf.bytes_written();
// set offset and index for bloom filter
let column_chunk_meta = column_chunk
.meta_data
.as_mut()
.expect("can't have bloom filter without column metadata");
column_chunk_meta.bloom_filter_offset = Some(start_offset as i64);
column_chunk_meta.bloom_filter_length =
Some((end_offset - start_offset) as i32);
}
None => {}
}
}
}
Ok(())
}
/// Serialize all the column index to the file
fn write_column_indexes(&mut self, row_groups: &mut [RowGroup]) -> Result<()> {
// iter row group
// iter each column
// write column index to the file
for (row_group_idx, row_group) in row_groups.iter_mut().enumerate() {
for (column_idx, column_metadata) in row_group.columns.iter_mut().enumerate() {
match &self.column_indexes[row_group_idx][column_idx] {
Some(column_index) => {
let start_offset = self.buf.bytes_written();
let mut protocol = TCompactOutputProtocol::new(&mut self.buf);
column_index.write_to_out_protocol(&mut protocol)?;
let end_offset = self.buf.bytes_written();
// set offset and index for offset index
column_metadata.column_index_offset = Some(start_offset as i64);
column_metadata.column_index_length =
Some((end_offset - start_offset) as i32);
}
None => {}
}
}
}
Ok(())
}
/// Assembles and writes metadata at the end of the file.
fn write_metadata(&mut self) -> Result<parquet::FileMetaData> {
self.finished = true;
let num_rows = self.row_groups.iter().map(|x| x.num_rows()).sum();
let mut row_groups = self
.row_groups
.as_slice()
.iter()
.map(|v| v.to_thrift())
.collect::<Vec<_>>();
self.write_bloom_filters(&mut row_groups)?;
// Write column indexes and offset indexes
self.write_column_indexes(&mut row_groups)?;
self.write_offset_indexes(&mut row_groups)?;
let key_value_metadata = match self.props.key_value_metadata() {
Some(kv) => Some(kv.iter().chain(&self.kv_metadatas).cloned().collect()),
None if self.kv_metadatas.is_empty() => None,
None => Some(self.kv_metadatas.clone()),
};
// We only include ColumnOrder for leaf nodes.
// Currently only supported ColumnOrder is TypeDefinedOrder so we set this
// for all leaf nodes.
// Even if the column has an undefined sort order, such as INTERVAL, this
// is still technically the defined TYPEORDER so it should still be set.
let column_orders = (0..self.schema_descr().num_columns())
.map(|_| parquet::ColumnOrder::TYPEORDER(parquet::TypeDefinedOrder {}))
.collect();
// This field is optional, perhaps in cases where no min/max fields are set
// in any Statistics or ColumnIndex object in the whole file.
// But for simplicity we always set this field.
let column_orders = Some(column_orders);
let file_metadata = parquet::FileMetaData {
num_rows,
row_groups,
key_value_metadata,
version: self.props.writer_version().as_num(),
schema: types::to_thrift(self.schema.as_ref())?,
created_by: Some(self.props.created_by().to_owned()),
column_orders,
encryption_algorithm: None,
footer_signing_key_metadata: None,
};
// Write file metadata
let start_pos = self.buf.bytes_written();
{
let mut protocol = TCompactOutputProtocol::new(&mut self.buf);
file_metadata.write_to_out_protocol(&mut protocol)?;
}
let end_pos = self.buf.bytes_written();
// Write footer
let metadata_len = (end_pos - start_pos) as u32;
self.buf.write_all(&metadata_len.to_le_bytes())?;
self.buf.write_all(&PARQUET_MAGIC)?;
Ok(file_metadata)
}
#[inline]
fn assert_previous_writer_closed(&self) -> Result<()> {
if self.finished {
return Err(general_err!("SerializedFileWriter already finished"));
}
if self.row_group_index != self.row_groups.len() {
Err(general_err!("Previous row group writer was not closed"))
} else {
Ok(())
}
}
pub fn append_key_value_metadata(&mut self, kv_metadata: KeyValue) {
self.kv_metadatas.push(kv_metadata);
}
/// Returns a reference to schema descriptor.
pub fn schema_descr(&self) -> &SchemaDescriptor {
&self.descr
}
/// Returns a reference to the writer properties
pub fn properties(&self) -> &WriterPropertiesPtr {
&self.props
}
/// Returns a reference to the underlying writer.
pub fn inner(&self) -> &W {
self.buf.inner()
}
/// Returns a mutable reference to the underlying writer.
///
/// It is inadvisable to directly write to the underlying writer.
pub fn inner_mut(&mut self) -> &mut W {
self.buf.inner_mut()
}
/// Writes the file footer and returns the underlying writer.
pub fn into_inner(mut self) -> Result<W> {
self.assert_previous_writer_closed()?;
let _ = self.write_metadata()?;
self.buf.into_inner()
}
/// Returns the number of bytes written to this instance
pub fn bytes_written(&self) -> usize {
self.buf.bytes_written()
}
}
/// Parquet row group writer API.
/// Provides methods to access column writers in an iterator-like fashion, order is
/// guaranteed to match the order of schema leaves (column descriptors).
///
/// All columns should be written sequentially; the main workflow is:
/// - Request the next column using `next_column` method - this will return `None` if no
/// more columns are available to write.
/// - Once done writing a column, close column writer with `close`
/// - Once all columns have been written, close row group writer with `close` method -
/// it will return row group metadata and is no-op on already closed row group.
pub struct SerializedRowGroupWriter<'a, W: Write> {
descr: SchemaDescPtr,
props: WriterPropertiesPtr,
buf: &'a mut TrackedWrite<W>,
total_rows_written: Option<u64>,
total_bytes_written: u64,
total_uncompressed_bytes: i64,
column_index: usize,
row_group_metadata: Option<RowGroupMetaDataPtr>,
column_chunks: Vec<ColumnChunkMetaData>,
bloom_filters: Vec<Option<Sbbf>>,
column_indexes: Vec<Option<ColumnIndex>>,
offset_indexes: Vec<Option<OffsetIndex>>,
row_group_index: i16,
file_offset: i64,
on_close: Option<OnCloseRowGroup<'a>>,
}
impl<'a, W: Write + Send> SerializedRowGroupWriter<'a, W> {
/// Creates a new `SerializedRowGroupWriter` with:
///
/// - `schema_descr` - the schema to write
/// - `properties` - writer properties
/// - `buf` - the buffer to write data to
/// - `row_group_index` - row group index in this parquet file.
/// - `file_offset` - file offset of this row group in this parquet file.
/// - `on_close` - an optional callback that will invoked on [`Self::close`]
pub fn new(
schema_descr: SchemaDescPtr,
properties: WriterPropertiesPtr,
buf: &'a mut TrackedWrite<W>,
row_group_index: i16,
on_close: Option<OnCloseRowGroup<'a>>,
) -> Self {
let num_columns = schema_descr.num_columns();
let file_offset = buf.bytes_written() as i64;
Self {
buf,
row_group_index,
file_offset,
on_close,
total_rows_written: None,
descr: schema_descr,
props: properties,
column_index: 0,
row_group_metadata: None,
column_chunks: Vec::with_capacity(num_columns),
bloom_filters: Vec::with_capacity(num_columns),
column_indexes: Vec::with_capacity(num_columns),
offset_indexes: Vec::with_capacity(num_columns),
total_bytes_written: 0,
total_uncompressed_bytes: 0,
}
}
/// Advance `self.column_index` returning the next [`ColumnDescPtr`] if any
fn next_column_desc(&mut self) -> Option<ColumnDescPtr> {
let ret = self.descr.columns().get(self.column_index)?.clone();
self.column_index += 1;
Some(ret)
}
/// Returns [`OnCloseColumnChunk`] for the next writer
fn get_on_close(&mut self) -> (&mut TrackedWrite<W>, OnCloseColumnChunk<'_>) {
let total_bytes_written = &mut self.total_bytes_written;
let total_uncompressed_bytes = &mut self.total_uncompressed_bytes;
let total_rows_written = &mut self.total_rows_written;
let column_chunks = &mut self.column_chunks;
let column_indexes = &mut self.column_indexes;
let offset_indexes = &mut self.offset_indexes;
let bloom_filters = &mut self.bloom_filters;
let on_close = |r: ColumnCloseResult| {
// Update row group writer metrics
*total_bytes_written += r.bytes_written;
*total_uncompressed_bytes += r.metadata.uncompressed_size();
column_chunks.push(r.metadata);
bloom_filters.push(r.bloom_filter);
column_indexes.push(r.column_index);
offset_indexes.push(r.offset_index);
if let Some(rows) = *total_rows_written {
if rows != r.rows_written {
return Err(general_err!(
"Incorrect number of rows, expected {} != {} rows",
rows,
r.rows_written
));
}
} else {
*total_rows_written = Some(r.rows_written);
}
Ok(())
};
(self.buf, Box::new(on_close))
}
/// Returns the next column writer, if available, using the factory function;
/// otherwise returns `None`.
pub(crate) fn next_column_with_factory<'b, F, C>(&'b mut self, factory: F) -> Result<Option<C>>
where
F: FnOnce(
ColumnDescPtr,
WriterPropertiesPtr,
Box<dyn PageWriter + 'b>,
OnCloseColumnChunk<'b>,
) -> Result<C>,
{
self.assert_previous_writer_closed()?;
Ok(match self.next_column_desc() {
Some(column) => {
let props = self.props.clone();
let (buf, on_close) = self.get_on_close();
let page_writer = Box::new(SerializedPageWriter::new(buf));
Some(factory(column, props, page_writer, Box::new(on_close))?)
}
None => None,
})
}
/// Returns the next column writer, if available; otherwise returns `None`.
/// In case of any IO error or Thrift error, or if row group writer has already been
/// closed returns `Err`.
pub fn next_column(&mut self) -> Result<Option<SerializedColumnWriter<'_>>> {
self.next_column_with_factory(|descr, props, page_writer, on_close| {
let column_writer = get_column_writer(descr, props, page_writer);
Ok(SerializedColumnWriter::new(column_writer, Some(on_close)))
})
}
/// Append an encoded column chunk from another source without decoding it
///
/// This can be used for efficiently concatenating or projecting parquet data,
/// or encoding parquet data to temporary in-memory buffers
///
/// See [`Self::next_column`] for writing data that isn't already encoded
pub fn append_column<R: ChunkReader>(
&mut self,
reader: &R,
mut close: ColumnCloseResult,
) -> Result<()> {
self.assert_previous_writer_closed()?;
let desc = self
.next_column_desc()
.ok_or_else(|| general_err!("exhausted columns in SerializedRowGroupWriter"))?;
let metadata = close.metadata;
if metadata.column_descr() != desc.as_ref() {
return Err(general_err!(
"column descriptor mismatch, expected {:?} got {:?}",
desc,
metadata.column_descr()
));
}
let src_dictionary_offset = metadata.dictionary_page_offset();
let src_data_offset = metadata.data_page_offset();
let src_offset = src_dictionary_offset.unwrap_or(src_data_offset);
let src_length = metadata.compressed_size();
let write_offset = self.buf.bytes_written();
let mut read = reader.get_read(src_offset as _)?.take(src_length as _);
let write_length = std::io::copy(&mut read, &mut self.buf)?;
if src_length as u64 != write_length {
return Err(general_err!(
"Failed to splice column data, expected {read_length} got {write_length}"
));
}
let file_offset = self.buf.bytes_written() as i64;
let map_offset = |x| x - src_offset + write_offset as i64;
let mut builder = ColumnChunkMetaData::builder(metadata.column_descr_ptr())
.set_compression(metadata.compression())
.set_encodings(metadata.encodings().clone())
.set_file_offset(file_offset)
.set_total_compressed_size(metadata.compressed_size())
.set_total_uncompressed_size(metadata.uncompressed_size())
.set_num_values(metadata.num_values())
.set_data_page_offset(map_offset(src_data_offset))
.set_dictionary_page_offset(src_dictionary_offset.map(map_offset));
if let Some(statistics) = metadata.statistics() {
builder = builder.set_statistics(statistics.clone())
}
close.metadata = builder.build()?;
if let Some(offsets) = close.offset_index.as_mut() {
for location in &mut offsets.page_locations {
location.offset = map_offset(location.offset)
}
}
SerializedPageWriter::new(self.buf).write_metadata(&metadata)?;
let (_, on_close) = self.get_on_close();
on_close(close)
}
/// Closes this row group writer and returns row group metadata.
pub fn close(mut self) -> Result<RowGroupMetaDataPtr> {
if self.row_group_metadata.is_none() {
self.assert_previous_writer_closed()?;
let column_chunks = std::mem::take(&mut self.column_chunks);
let row_group_metadata = RowGroupMetaData::builder(self.descr.clone())
.set_column_metadata(column_chunks)
.set_total_byte_size(self.total_uncompressed_bytes)
.set_num_rows(self.total_rows_written.unwrap_or(0) as i64)
.set_sorting_columns(self.props.sorting_columns().cloned())
.set_ordinal(self.row_group_index)
.set_file_offset(self.file_offset)
.build()?;
let metadata = Arc::new(row_group_metadata);
self.row_group_metadata = Some(metadata.clone());
if let Some(on_close) = self.on_close.take() {
on_close(
metadata,
self.bloom_filters,
self.column_indexes,
self.offset_indexes,
)?
}
}
let metadata = self.row_group_metadata.as_ref().unwrap().clone();
Ok(metadata)
}
#[inline]
fn assert_previous_writer_closed(&self) -> Result<()> {
if self.column_index != self.column_chunks.len() {
Err(general_err!("Previous column writer was not closed"))
} else {
Ok(())
}
}
}
/// A wrapper around a [`ColumnWriter`] that invokes a callback on [`Self::close`]
pub struct SerializedColumnWriter<'a> {
inner: ColumnWriter<'a>,
on_close: Option<OnCloseColumnChunk<'a>>,
}
impl<'a> SerializedColumnWriter<'a> {
/// Create a new [`SerializedColumnWriter`] from a [`ColumnWriter`] and an
/// optional callback to be invoked on [`Self::close`]
pub fn new(inner: ColumnWriter<'a>, on_close: Option<OnCloseColumnChunk<'a>>) -> Self {
Self { inner, on_close }
}
/// Returns a reference to an untyped [`ColumnWriter`]
pub fn untyped(&mut self) -> &mut ColumnWriter<'a> {
&mut self.inner
}
/// Returns a reference to a typed [`ColumnWriterImpl`]
pub fn typed<T: DataType>(&mut self) -> &mut ColumnWriterImpl<'a, T> {
get_typed_column_writer_mut(&mut self.inner)
}
/// Close this [`SerializedColumnWriter`]
pub fn close(mut self) -> Result<()> {
let r = self.inner.close()?;
if let Some(on_close) = self.on_close.take() {
on_close(r)?
}
Ok(())
}
}
/// A serialized implementation for Parquet [`PageWriter`].
/// Writes and serializes pages and metadata into output stream.
///
/// `SerializedPageWriter` should not be used after calling `close()`.
pub struct SerializedPageWriter<'a, W: Write> {
sink: &'a mut TrackedWrite<W>,
}
impl<'a, W: Write> SerializedPageWriter<'a, W> {
/// Creates new page writer.
pub fn new(sink: &'a mut TrackedWrite<W>) -> Self {
Self { sink }
}
/// Serializes page header into Thrift.
/// Returns number of bytes that have been written into the sink.
#[inline]
fn serialize_page_header(&mut self, header: parquet::PageHeader) -> Result<usize> {
let start_pos = self.sink.bytes_written();
{
let mut protocol = TCompactOutputProtocol::new(&mut self.sink);
header.write_to_out_protocol(&mut protocol)?;
}
Ok(self.sink.bytes_written() - start_pos)
}
}
impl<'a, W: Write + Send> PageWriter for SerializedPageWriter<'a, W> {
fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> {
let page_type = page.page_type();
let start_pos = self.sink.bytes_written() as u64;
let page_header = page.to_thrift_header();
let header_size = self.serialize_page_header(page_header)?;
self.sink.write_all(page.data())?;
let mut spec = PageWriteSpec::new();
spec.page_type = page_type;
spec.uncompressed_size = page.uncompressed_size() + header_size;
spec.compressed_size = page.compressed_size() + header_size;
spec.offset = start_pos;
spec.bytes_written = self.sink.bytes_written() as u64 - start_pos;
spec.num_values = page.num_values();
Ok(spec)
}
fn write_metadata(&mut self, metadata: &ColumnChunkMetaData) -> Result<()> {
let mut protocol = TCompactOutputProtocol::new(&mut self.sink);
metadata
.to_column_metadata_thrift()
.write_to_out_protocol(&mut protocol)?;
Ok(())
}
fn close(&mut self) -> Result<()> {
self.sink.flush()?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use bytes::Bytes;
use std::fs::File;
use crate::basic::{
ColumnOrder, Compression, ConvertedType, Encoding, LogicalType, Repetition, SortOrder, Type,
};
use crate::column::page::{Page, PageReader};
use crate::column::reader::get_typed_column_reader;
use crate::compression::{create_codec, Codec, CodecOptionsBuilder};
use crate::data_type::{BoolType, Int32Type};
use crate::file::page_index::index::Index;
use crate::file::properties::EnabledStatistics;
use crate::file::serialized_reader::ReadOptionsBuilder;
use crate::file::{
properties::{ReaderProperties, WriterProperties, WriterVersion},
reader::{FileReader, SerializedFileReader, SerializedPageReader},
statistics::{from_thrift, to_thrift, Statistics},
};
use crate::format::SortingColumn;
use crate::record::{Row, RowAccessor};
use crate::schema::parser::parse_message_type;
use crate::schema::types::{ColumnDescriptor, ColumnPath};
#[test]
fn test_row_group_writer_error_not_all_columns_written() {
let file = tempfile::tempfile().unwrap();
let schema = Arc::new(
types::Type::group_type_builder("schema")
.with_fields(vec![Arc::new(
types::Type::primitive_type_builder("col1", Type::INT32)
.build()
.unwrap(),
)])
.build()
.unwrap(),
);
let props = Default::default();
let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();
let row_group_writer = writer.next_row_group().unwrap();
let res = row_group_writer.close();
assert!(res.is_err());
if let Err(err) = res {
assert_eq!(
format!("{err}"),
"Parquet error: Column length mismatch: 1 != 0"
);
}
}
#[test]
fn test_row_group_writer_num_records_mismatch() {
let file = tempfile::tempfile().unwrap();
let schema = Arc::new(
types::Type::group_type_builder("schema")
.with_fields(vec![
Arc::new(
types::Type::primitive_type_builder("col1", Type::INT32)
.with_repetition(Repetition::REQUIRED)
.build()
.unwrap(),
),
Arc::new(
types::Type::primitive_type_builder("col2", Type::INT32)
.with_repetition(Repetition::REQUIRED)
.build()
.unwrap(),
),
])
.build()
.unwrap(),
);
let props = Default::default();
let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();
let mut row_group_writer = writer.next_row_group().unwrap();
let mut col_writer = row_group_writer.next_column().unwrap().unwrap();
col_writer
.typed::<Int32Type>()
.write_batch(&[1, 2, 3], None, None)
.unwrap();
col_writer.close().unwrap();
let mut col_writer = row_group_writer.next_column().unwrap().unwrap();
col_writer
.typed::<Int32Type>()
.write_batch(&[1, 2], None, None)
.unwrap();
let err = col_writer.close().unwrap_err();
assert_eq!(
err.to_string(),
"Parquet error: Incorrect number of rows, expected 3 != 2 rows"
);
}
#[test]
fn test_file_writer_empty_file() {
let file = tempfile::tempfile().unwrap();
let schema = Arc::new(
types::Type::group_type_builder("schema")
.with_fields(vec![Arc::new(
types::Type::primitive_type_builder("col1", Type::INT32)
.build()
.unwrap(),
)])
.build()
.unwrap(),
);
let props = Default::default();
let writer = SerializedFileWriter::new(file.try_clone().unwrap(), schema, props).unwrap();
writer.close().unwrap();
let reader = SerializedFileReader::new(file).unwrap();
assert_eq!(reader.get_row_iter(None).unwrap().count(), 0);
}
#[test]
fn test_file_writer_column_orders_populated() {
let file = tempfile::tempfile().unwrap();
let schema = Arc::new(
types::Type::group_type_builder("schema")
.with_fields(vec![
Arc::new(
types::Type::primitive_type_builder("col1", Type::INT32)
.build()
.unwrap(),
),
Arc::new(
types::Type::primitive_type_builder("col2", Type::FIXED_LEN_BYTE_ARRAY)
.with_converted_type(ConvertedType::INTERVAL)
.with_length(12)
.build()
.unwrap(),
),
Arc::new(
types::Type::group_type_builder("nested")
.with_repetition(Repetition::REQUIRED)
.with_fields(vec![
Arc::new(
types::Type::primitive_type_builder(
"col3",
Type::FIXED_LEN_BYTE_ARRAY,
)
.with_logical_type(Some(LogicalType::Float16))
.with_length(2)
.build()
.unwrap(),
),
Arc::new(
types::Type::primitive_type_builder("col4", Type::BYTE_ARRAY)
.with_logical_type(Some(LogicalType::String))
.build()
.unwrap(),
),
])
.build()
.unwrap(),
),
])
.build()
.unwrap(),
);
let props = Default::default();
let writer = SerializedFileWriter::new(file.try_clone().unwrap(), schema, props).unwrap();
writer.close().unwrap();
let reader = SerializedFileReader::new(file).unwrap();
// only leaves
let expected = vec![
// INT32
ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::SIGNED),
// INTERVAL
ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::UNDEFINED),
// Float16
ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::SIGNED),
// String
ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::UNSIGNED),
];
let actual = reader.metadata().file_metadata().column_orders();
assert!(actual.is_some());
let actual = actual.unwrap();
assert_eq!(*actual, expected);
}
#[test]
fn test_file_writer_with_metadata() {
let file = tempfile::tempfile().unwrap();
let schema = Arc::new(
types::Type::group_type_builder("schema")
.with_fields(vec![Arc::new(
types::Type::primitive_type_builder("col1", Type::INT32)
.build()
.unwrap(),
)])
.build()
.unwrap(),
);