-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathmanifest.rs
2469 lines (2308 loc) · 89.4 KB
/
manifest.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.
//! Manifest for Iceberg.
use std::cmp::min;
use std::collections::HashMap;
use std::io::{Read, Write};
use std::str::FromStr;
use std::sync::Arc;
use apache_avro::{from_value, to_value, Reader as AvroReader, Writer as AvroWriter};
use bytes::Bytes;
use itertools::Itertools;
use serde_derive::{Deserialize, Serialize};
use serde_json::to_vec;
use serde_with::{DeserializeFromStr, SerializeDisplay};
use typed_builder::TypedBuilder;
use self::_const_schema::{manifest_schema_v1, manifest_schema_v2};
use super::{
Datum, FieldSummary, FormatVersion, ManifestContentType, ManifestFile, PartitionSpec,
PrimitiveLiteral, PrimitiveType, Schema, SchemaId, SchemaRef, Struct, StructType,
INITIAL_SEQUENCE_NUMBER, UNASSIGNED_SEQUENCE_NUMBER,
};
use crate::error::Result;
use crate::io::OutputFile;
use crate::spec::PartitionField;
use crate::{Error, ErrorKind};
/// A manifest contains metadata and a list of entries.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Manifest {
metadata: ManifestMetadata,
entries: Vec<ManifestEntryRef>,
}
impl Manifest {
/// Parse manifest metadata and entries from bytes of avro file.
pub(crate) fn try_from_avro_bytes(bs: &[u8]) -> Result<(ManifestMetadata, Vec<ManifestEntry>)> {
let reader = AvroReader::new(bs)?;
// Parse manifest metadata
let meta = reader.user_metadata();
let metadata = ManifestMetadata::parse(meta)?;
// Parse manifest entries
let partition_type = metadata.partition_spec.partition_type(&metadata.schema)?;
let entries = match metadata.format_version {
FormatVersion::V1 => {
let schema = manifest_schema_v1(&partition_type)?;
let reader = AvroReader::with_schema(&schema, bs)?;
reader
.into_iter()
.map(|value| {
from_value::<_serde::ManifestEntryV1>(&value?)?
.try_into(&partition_type, &metadata.schema)
})
.collect::<Result<Vec<_>>>()?
}
FormatVersion::V2 => {
let schema = manifest_schema_v2(&partition_type)?;
let reader = AvroReader::with_schema(&schema, bs)?;
reader
.into_iter()
.map(|value| {
from_value::<_serde::ManifestEntryV2>(&value?)?
.try_into(&partition_type, &metadata.schema)
})
.collect::<Result<Vec<_>>>()?
}
};
Ok((metadata, entries))
}
/// Parse manifest from bytes of avro file.
pub fn parse_avro(bs: &[u8]) -> Result<Self> {
let (metadata, entries) = Self::try_from_avro_bytes(bs)?;
Ok(Self::new(metadata, entries))
}
/// Entries slice.
pub fn entries(&self) -> &[ManifestEntryRef] {
&self.entries
}
/// Consume this Manifest, returning its constituent parts
pub fn into_parts(self) -> (Vec<ManifestEntryRef>, ManifestMetadata) {
let Self { entries, metadata } = self;
(entries, metadata)
}
/// Constructor from [`ManifestMetadata`] and [`ManifestEntry`]s.
pub fn new(metadata: ManifestMetadata, entries: Vec<ManifestEntry>) -> Self {
Self {
metadata,
entries: entries.into_iter().map(Arc::new).collect(),
}
}
}
/// A manifest writer.
pub struct ManifestWriter {
output: OutputFile,
snapshot_id: i64,
added_files: u32,
added_rows: u64,
existing_files: u32,
existing_rows: u64,
deleted_files: u32,
deleted_rows: u64,
min_seq_num: Option<i64>,
key_metadata: Vec<u8>,
partitions: Vec<Struct>,
}
struct PartitionFieldStats {
partition_type: PrimitiveType,
summary: FieldSummary,
}
impl PartitionFieldStats {
pub(crate) fn new(partition_type: PrimitiveType) -> Self {
Self {
partition_type,
summary: FieldSummary::default(),
}
}
pub(crate) fn update(&mut self, value: Option<PrimitiveLiteral>) -> Result<()> {
let Some(value) = value else {
self.summary.contains_null = true;
return Ok(());
};
if !self.partition_type.compatible(&value) {
return Err(Error::new(
ErrorKind::DataInvalid,
"value is not compatitable with type",
));
}
let value = Datum::new(self.partition_type.clone(), value);
if value.is_nan() {
self.summary.contains_nan = Some(true);
return Ok(());
}
self.summary.lower_bound = Some(self.summary.lower_bound.take().map_or(
value.clone(),
|original| {
if value < original {
value.clone()
} else {
original
}
},
));
self.summary.upper_bound = Some(self.summary.upper_bound.take().map_or(
value.clone(),
|original| {
if value > original {
value
} else {
original
}
},
));
Ok(())
}
pub(crate) fn finish(mut self) -> FieldSummary {
// Always set contains_nan
self.summary.contains_nan = self.summary.contains_nan.or(Some(false));
self.summary
}
}
impl ManifestWriter {
/// Create a new manifest writer.
pub fn new(output: OutputFile, snapshot_id: i64, key_metadata: Vec<u8>) -> Self {
Self {
output,
snapshot_id,
added_files: 0,
added_rows: 0,
existing_files: 0,
existing_rows: 0,
deleted_files: 0,
deleted_rows: 0,
min_seq_num: None,
key_metadata,
partitions: vec![],
}
}
fn construct_partition_summaries(
&mut self,
partition_type: &StructType,
) -> Result<Vec<FieldSummary>> {
let partitions = std::mem::take(&mut self.partitions);
let mut field_stats: Vec<_> = partition_type
.fields()
.iter()
.map(|f| PartitionFieldStats::new(f.field_type.as_primitive_type().unwrap().clone()))
.collect();
for partition in partitions {
for (literal, stat) in partition.into_iter().zip_eq(field_stats.iter_mut()) {
let primitive_literal = literal.map(|v| v.as_primitive_literal().unwrap());
stat.update(primitive_literal)?;
}
}
Ok(field_stats.into_iter().map(|stat| stat.finish()).collect())
}
/// Write a manifest.
pub async fn write(mut self, manifest: Manifest) -> Result<ManifestFile> {
// Create the avro writer
let partition_type = manifest
.metadata
.partition_spec
.partition_type(&manifest.metadata.schema)?;
let table_schema = &manifest.metadata.schema;
let avro_schema = match manifest.metadata.format_version {
FormatVersion::V1 => manifest_schema_v1(&partition_type)?,
FormatVersion::V2 => manifest_schema_v2(&partition_type)?,
};
let mut avro_writer = AvroWriter::new(&avro_schema, Vec::new());
avro_writer.add_user_metadata(
"schema".to_string(),
to_vec(table_schema).map_err(|err| {
Error::new(ErrorKind::DataInvalid, "Fail to serialize table schema")
.with_source(err)
})?,
)?;
avro_writer.add_user_metadata(
"schema-id".to_string(),
table_schema.schema_id().to_string(),
)?;
avro_writer.add_user_metadata(
"partition-spec".to_string(),
to_vec(&manifest.metadata.partition_spec.fields()).map_err(|err| {
Error::new(ErrorKind::DataInvalid, "Fail to serialize partition spec")
.with_source(err)
})?,
)?;
avro_writer.add_user_metadata(
"partition-spec-id".to_string(),
manifest.metadata.partition_spec.spec_id().to_string(),
)?;
avro_writer.add_user_metadata(
"format-version".to_string(),
(manifest.metadata.format_version as u8).to_string(),
)?;
if manifest.metadata.format_version == FormatVersion::V2 {
avro_writer
.add_user_metadata("content".to_string(), manifest.metadata.content.to_string())?;
}
// Write manifest entries
for entry in manifest.entries {
if (entry.status == ManifestStatus::Deleted || entry.status == ManifestStatus::Existing)
&& (entry.sequence_number.is_none() || entry.file_sequence_number.is_none())
{
return Err(Error::new(
ErrorKind::DataInvalid,
"Manifest entry with status Existing or Deleted should have sequence number",
));
}
match entry.status {
ManifestStatus::Added => {
self.added_files += 1;
self.added_rows += entry.data_file.record_count;
}
ManifestStatus::Deleted => {
self.deleted_files += 1;
self.deleted_rows += entry.data_file.record_count;
}
ManifestStatus::Existing => {
self.existing_files += 1;
self.existing_rows += entry.data_file.record_count;
}
}
if entry.is_alive() {
if let Some(seq_num) = entry.sequence_number {
self.min_seq_num = Some(self.min_seq_num.map_or(seq_num, |v| min(v, seq_num)));
}
}
self.partitions.push(entry.data_file.partition.clone());
let value = match manifest.metadata.format_version {
FormatVersion::V1 => to_value(_serde::ManifestEntryV1::try_from(
(*entry).clone(),
&partition_type,
)?)?
.resolve(&avro_schema)?,
FormatVersion::V2 => to_value(_serde::ManifestEntryV2::try_from(
(*entry).clone(),
&partition_type,
)?)?
.resolve(&avro_schema)?,
};
avro_writer.append(value)?;
}
let content = avro_writer.into_inner()?;
let length = content.len();
self.output.write(Bytes::from(content)).await?;
let partition_summary = self.construct_partition_summaries(&partition_type)?;
Ok(ManifestFile {
manifest_path: self.output.location().to_string(),
manifest_length: length as i64,
partition_spec_id: manifest.metadata.partition_spec.spec_id(),
content: manifest.metadata.content,
// sequence_number and min_sequence_number with UNASSIGNED_SEQUENCE_NUMBER will be replace with
// real sequence number in `ManifestListWriter`.
sequence_number: UNASSIGNED_SEQUENCE_NUMBER,
min_sequence_number: self.min_seq_num.unwrap_or(UNASSIGNED_SEQUENCE_NUMBER),
added_snapshot_id: self.snapshot_id,
added_files_count: Some(self.added_files),
existing_files_count: Some(self.existing_files),
deleted_files_count: Some(self.deleted_files),
added_rows_count: Some(self.added_rows),
existing_rows_count: Some(self.existing_rows),
deleted_rows_count: Some(self.deleted_rows),
partitions: partition_summary,
key_metadata: self.key_metadata,
})
}
}
/// This is a helper module that defines the schema field of the manifest list entry.
mod _const_schema {
use std::sync::Arc;
use apache_avro::Schema as AvroSchema;
use once_cell::sync::Lazy;
use crate::avro::schema_to_avro_schema;
use crate::spec::{
ListType, MapType, NestedField, NestedFieldRef, PrimitiveType, Schema, StructType, Type,
};
use crate::Error;
static STATUS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
0,
"status",
Type::Primitive(PrimitiveType::Int),
))
})
};
static SNAPSHOT_ID_V1: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
1,
"snapshot_id",
Type::Primitive(PrimitiveType::Long),
))
})
};
static SNAPSHOT_ID_V2: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
1,
"snapshot_id",
Type::Primitive(PrimitiveType::Long),
))
})
};
static SEQUENCE_NUMBER: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
3,
"sequence_number",
Type::Primitive(PrimitiveType::Long),
))
})
};
static FILE_SEQUENCE_NUMBER: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
4,
"file_sequence_number",
Type::Primitive(PrimitiveType::Long),
))
})
};
static CONTENT: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
134,
"content",
Type::Primitive(PrimitiveType::Int),
))
})
};
static FILE_PATH: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
100,
"file_path",
Type::Primitive(PrimitiveType::String),
))
})
};
static FILE_FORMAT: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
101,
"file_format",
Type::Primitive(PrimitiveType::String),
))
})
};
static RECORD_COUNT: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
103,
"record_count",
Type::Primitive(PrimitiveType::Long),
))
})
};
static FILE_SIZE_IN_BYTES: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
104,
"file_size_in_bytes",
Type::Primitive(PrimitiveType::Long),
))
})
};
// Deprecated. Always write a default in v1. Do not write in v2.
static BLOCK_SIZE_IN_BYTES: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::required(
105,
"block_size_in_bytes",
Type::Primitive(PrimitiveType::Long),
))
})
};
static COLUMN_SIZES: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
108,
"column_sizes",
Type::Map(MapType {
key_field: Arc::new(NestedField::required(
117,
"key",
Type::Primitive(PrimitiveType::Int),
)),
value_field: Arc::new(NestedField::required(
118,
"value",
Type::Primitive(PrimitiveType::Long),
)),
}),
))
})
};
static VALUE_COUNTS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
109,
"value_counts",
Type::Map(MapType {
key_field: Arc::new(NestedField::required(
119,
"key",
Type::Primitive(PrimitiveType::Int),
)),
value_field: Arc::new(NestedField::required(
120,
"value",
Type::Primitive(PrimitiveType::Long),
)),
}),
))
})
};
static NULL_VALUE_COUNTS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
110,
"null_value_counts",
Type::Map(MapType {
key_field: Arc::new(NestedField::required(
121,
"key",
Type::Primitive(PrimitiveType::Int),
)),
value_field: Arc::new(NestedField::required(
122,
"value",
Type::Primitive(PrimitiveType::Long),
)),
}),
))
})
};
static NAN_VALUE_COUNTS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
137,
"nan_value_counts",
Type::Map(MapType {
key_field: Arc::new(NestedField::required(
138,
"key",
Type::Primitive(PrimitiveType::Int),
)),
value_field: Arc::new(NestedField::required(
139,
"value",
Type::Primitive(PrimitiveType::Long),
)),
}),
))
})
};
static LOWER_BOUNDS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
125,
"lower_bounds",
Type::Map(MapType {
key_field: Arc::new(NestedField::required(
126,
"key",
Type::Primitive(PrimitiveType::Int),
)),
value_field: Arc::new(NestedField::required(
127,
"value",
Type::Primitive(PrimitiveType::Binary),
)),
}),
))
})
};
static UPPER_BOUNDS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
128,
"upper_bounds",
Type::Map(MapType {
key_field: Arc::new(NestedField::required(
129,
"key",
Type::Primitive(PrimitiveType::Int),
)),
value_field: Arc::new(NestedField::required(
130,
"value",
Type::Primitive(PrimitiveType::Binary),
)),
}),
))
})
};
static KEY_METADATA: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
131,
"key_metadata",
Type::Primitive(PrimitiveType::Binary),
))
})
};
static SPLIT_OFFSETS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
132,
"split_offsets",
Type::List(ListType {
element_field: Arc::new(NestedField::required(
133,
"element",
Type::Primitive(PrimitiveType::Long),
)),
}),
))
})
};
static EQUALITY_IDS: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
135,
"equality_ids",
Type::List(ListType {
element_field: Arc::new(NestedField::required(
136,
"element",
Type::Primitive(PrimitiveType::Int),
)),
}),
))
})
};
static SORT_ORDER_ID: Lazy<NestedFieldRef> = {
Lazy::new(|| {
Arc::new(NestedField::optional(
140,
"sort_order_id",
Type::Primitive(PrimitiveType::Int),
))
})
};
fn data_file_fields_v2(partition_type: &StructType) -> Vec<NestedFieldRef> {
vec![
CONTENT.clone(),
FILE_PATH.clone(),
FILE_FORMAT.clone(),
Arc::new(NestedField::required(
102,
"partition",
Type::Struct(partition_type.clone()),
)),
RECORD_COUNT.clone(),
FILE_SIZE_IN_BYTES.clone(),
COLUMN_SIZES.clone(),
VALUE_COUNTS.clone(),
NULL_VALUE_COUNTS.clone(),
NAN_VALUE_COUNTS.clone(),
LOWER_BOUNDS.clone(),
UPPER_BOUNDS.clone(),
KEY_METADATA.clone(),
SPLIT_OFFSETS.clone(),
EQUALITY_IDS.clone(),
SORT_ORDER_ID.clone(),
]
}
pub(super) fn data_file_schema_v2(partition_type: &StructType) -> Result<AvroSchema, Error> {
let schema = Schema::builder()
.with_fields(data_file_fields_v2(partition_type))
.build()?;
schema_to_avro_schema("data_file", &schema)
}
pub(super) fn manifest_schema_v2(partition_type: &StructType) -> Result<AvroSchema, Error> {
let fields = vec![
STATUS.clone(),
SNAPSHOT_ID_V2.clone(),
SEQUENCE_NUMBER.clone(),
FILE_SEQUENCE_NUMBER.clone(),
Arc::new(NestedField::required(
2,
"data_file",
Type::Struct(StructType::new(data_file_fields_v2(partition_type))),
)),
];
let schema = Schema::builder().with_fields(fields).build()?;
schema_to_avro_schema("manifest_entry", &schema)
}
fn data_file_fields_v1(partition_type: &StructType) -> Vec<NestedFieldRef> {
vec![
FILE_PATH.clone(),
FILE_FORMAT.clone(),
Arc::new(NestedField::required(
102,
"partition",
Type::Struct(partition_type.clone()),
)),
RECORD_COUNT.clone(),
FILE_SIZE_IN_BYTES.clone(),
BLOCK_SIZE_IN_BYTES.clone(),
COLUMN_SIZES.clone(),
VALUE_COUNTS.clone(),
NULL_VALUE_COUNTS.clone(),
NAN_VALUE_COUNTS.clone(),
LOWER_BOUNDS.clone(),
UPPER_BOUNDS.clone(),
KEY_METADATA.clone(),
SPLIT_OFFSETS.clone(),
SORT_ORDER_ID.clone(),
]
}
pub(super) fn data_file_schema_v1(partition_type: &StructType) -> Result<AvroSchema, Error> {
let schema = Schema::builder()
.with_fields(data_file_fields_v1(partition_type))
.build()?;
schema_to_avro_schema("data_file", &schema)
}
pub(super) fn manifest_schema_v1(partition_type: &StructType) -> Result<AvroSchema, Error> {
let fields = vec![
STATUS.clone(),
SNAPSHOT_ID_V1.clone(),
Arc::new(NestedField::required(
2,
"data_file",
Type::Struct(StructType::new(data_file_fields_v1(partition_type))),
)),
];
let schema = Schema::builder().with_fields(fields).build()?;
schema_to_avro_schema("manifest_entry", &schema)
}
}
/// Meta data of a manifest that is stored in the key-value metadata of the Avro file
#[derive(Debug, PartialEq, Clone, Eq, TypedBuilder)]
pub struct ManifestMetadata {
/// The table schema at the time the manifest
/// was written
schema: SchemaRef,
/// ID of the schema used to write the manifest as a string
schema_id: SchemaId,
/// The partition spec used to write the manifest
partition_spec: PartitionSpec,
/// Table format version number of the manifest as a string
format_version: FormatVersion,
/// Type of content files tracked by the manifest: “data” or “deletes”
content: ManifestContentType,
}
impl ManifestMetadata {
/// Parse from metadata in avro file.
pub fn parse(meta: &HashMap<String, Vec<u8>>) -> Result<Self> {
let schema = Arc::new({
let bs = meta.get("schema").ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
"schema is required in manifest metadata but not found",
)
})?;
serde_json::from_slice::<Schema>(bs).map_err(|err| {
Error::new(
ErrorKind::DataInvalid,
"Fail to parse schema in manifest metadata",
)
.with_source(err)
})?
});
let schema_id: i32 = meta
.get("schema-id")
.map(|bs| {
String::from_utf8_lossy(bs).parse().map_err(|err| {
Error::new(
ErrorKind::DataInvalid,
"Fail to parse schema id in manifest metadata",
)
.with_source(err)
})
})
.transpose()?
.unwrap_or(0);
let partition_spec = {
let fields = {
let bs = meta.get("partition-spec").ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
"partition-spec is required in manifest metadata but not found",
)
})?;
serde_json::from_slice::<Vec<PartitionField>>(bs).map_err(|err| {
Error::new(
ErrorKind::DataInvalid,
"Fail to parse partition spec in manifest metadata",
)
.with_source(err)
})?
};
let spec_id = meta
.get("partition-spec-id")
.map(|bs| {
String::from_utf8_lossy(bs).parse().map_err(|err| {
Error::new(
ErrorKind::DataInvalid,
"Fail to parse partition spec id in manifest metadata",
)
.with_source(err)
})
})
.transpose()?
.unwrap_or(0);
PartitionSpec::builder(schema.clone())
.with_spec_id(spec_id)
.add_unbound_fields(fields.into_iter().map(|f| f.into_unbound()))?
.build()?
};
let format_version = if let Some(bs) = meta.get("format-version") {
serde_json::from_slice::<FormatVersion>(bs).map_err(|err| {
Error::new(
ErrorKind::DataInvalid,
"Fail to parse format version in manifest metadata",
)
.with_source(err)
})?
} else {
FormatVersion::V1
};
let content = if let Some(v) = meta.get("content") {
let v = String::from_utf8_lossy(v);
v.parse()?
} else {
ManifestContentType::Data
};
Ok(ManifestMetadata {
schema,
schema_id,
partition_spec,
format_version,
content,
})
}
}
/// Reference to [`ManifestEntry`].
pub type ManifestEntryRef = Arc<ManifestEntry>;
/// A manifest is an immutable Avro file that lists data files or delete
/// files, along with each file’s partition data tuple, metrics, and tracking
/// information.
#[derive(Debug, PartialEq, Eq, Clone, TypedBuilder)]
pub struct ManifestEntry {
/// field: 0
///
/// Used to track additions and deletions.
status: ManifestStatus,
/// field id: 1
///
/// Snapshot id where the file was added, or deleted if status is 2.
/// Inherited when null.
#[builder(default, setter(strip_option(fallback = snapshot_id_opt)))]
snapshot_id: Option<i64>,
/// field id: 3
///
/// Data sequence number of the file.
/// Inherited when null and status is 1 (added).
#[builder(default, setter(strip_option(fallback = sequence_number_opt)))]
sequence_number: Option<i64>,
/// field id: 4
///
/// File sequence number indicating when the file was added.
/// Inherited when null and status is 1 (added).
#[builder(default, setter(strip_option(fallback = file_sequence_number_opt)))]
file_sequence_number: Option<i64>,
/// field id: 2
///
/// File path, partition tuple, metrics, …
data_file: DataFile,
}
impl ManifestEntry {
/// Check if this manifest entry is deleted.
pub fn is_alive(&self) -> bool {
matches!(
self.status,
ManifestStatus::Added | ManifestStatus::Existing
)
}
/// Status of this manifest entry
pub fn status(&self) -> ManifestStatus {
self.status
}
/// Content type of this manifest entry.
#[inline]
pub fn content_type(&self) -> DataContentType {
self.data_file.content
}
/// File format of this manifest entry.
#[inline]
pub fn file_format(&self) -> DataFileFormat {
self.data_file.file_format
}
/// Data file path of this manifest entry.
#[inline]
pub fn file_path(&self) -> &str {
&self.data_file.file_path
}
/// Data file record count of the manifest entry.
#[inline]
pub fn record_count(&self) -> u64 {
self.data_file.record_count
}
/// Inherit data from manifest list, such as snapshot id, sequence number.
pub(crate) fn inherit_data(&mut self, snapshot_entry: &ManifestFile) {
if self.snapshot_id.is_none() {
self.snapshot_id = Some(snapshot_entry.added_snapshot_id);
}
if self.sequence_number.is_none()
&& (self.status == ManifestStatus::Added
|| snapshot_entry.sequence_number == INITIAL_SEQUENCE_NUMBER)
{
self.sequence_number = Some(snapshot_entry.sequence_number);
}
if self.file_sequence_number.is_none()
&& (self.status == ManifestStatus::Added
|| snapshot_entry.sequence_number == INITIAL_SEQUENCE_NUMBER)
{
self.file_sequence_number = Some(snapshot_entry.sequence_number);
}
}
/// Snapshot id
#[inline]
pub fn snapshot_id(&self) -> Option<i64> {
self.snapshot_id
}
/// Data sequence number.
#[inline]
pub fn sequence_number(&self) -> Option<i64> {
self.sequence_number
}
/// File size in bytes.
#[inline]
pub fn file_size_in_bytes(&self) -> u64 {
self.data_file.file_size_in_bytes
}
/// get a reference to the actual data file
#[inline]
pub fn data_file(&self) -> &DataFile {
&self.data_file
}
}
/// Used to track additions and deletions in ManifestEntry.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ManifestStatus {
/// Value: 0
Existing = 0,
/// Value: 1
Added = 1,
/// Value: 2
///
/// Deletes are informational only and not used in scans.
Deleted = 2,
}
impl TryFrom<i32> for ManifestStatus {
type Error = Error;
fn try_from(v: i32) -> Result<ManifestStatus> {
match v {
0 => Ok(ManifestStatus::Existing),