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
/*!
 * Manifest lists
*/

use std::{
    io::Read,
    iter::{repeat, Map, Repeat, Zip},
};

use apache_avro::{types::Value as AvroValue, Reader as AvroReader, Schema as AvroSchema};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;

use crate::error::Error;

use self::_serde::{FieldSummarySerde, ManifestListEntryV1, ManifestListEntryV2};

use super::{
    manifest::Content,
    table_metadata::{FormatVersion, TableMetadata},
    types::Type,
    values::Value,
};

/// Iterator of ManifestFileEntries
pub struct ManifestListReader<'a, 'metadata, R: Read> {
    reader: Map<
        Zip<AvroReader<'a, R>, Repeat<&'metadata TableMetadata>>,
        fn(
            (Result<AvroValue, apache_avro::Error>, &TableMetadata),
        ) -> Result<ManifestListEntry, Error>,
    >,
}

impl<'a, 'metadata, R: Read> Iterator for ManifestListReader<'a, 'metadata, R> {
    type Item = Result<ManifestListEntry, Error>;
    fn next(&mut self) -> Option<Self::Item> {
        self.reader.next()
    }
}

impl<'a, 'metadata, R: Read> ManifestListReader<'a, 'metadata, R> {
    /// Create a new ManifestFile reader
    pub fn new(
        reader: R,
        table_metadata: &'metadata TableMetadata,
    ) -> Result<Self, apache_avro::Error> {
        Ok(Self {
            reader: AvroReader::new(reader)?
                .zip(repeat(table_metadata))
                .map(avro_value_to_manifest_file),
        })
    }
}

#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
#[serde(into = "ManifestListEntryEnum")]
/// A manifest list includes summary metadata that can be used to avoid scanning all of the manifests in a snapshot when planning a table scan.
/// This includes the number of added, existing, and deleted files, and a summary of values for each field of the partition spec used to write the manifest.
pub struct ManifestListEntry {
    /// Table format version
    pub format_version: FormatVersion,
    /// Location of the manifest file
    pub manifest_path: String,
    /// Length of the manifest file in bytes
    pub manifest_length: i64,
    /// ID of a partition spec used to write the manifest; must be listed in table metadata partition-specs
    pub partition_spec_id: i32,
    /// The type of files tracked by the manifest, either data or delete files; 0 for all v1 manifests
    pub content: Content,
    /// The sequence number when the manifest was added to the table; use 0 when reading v1 manifest lists
    pub sequence_number: i64,
    /// The minimum sequence number of all data or delete files in the manifest; use 0 when reading v1 manifest lists
    pub min_sequence_number: i64,
    /// ID of the snapshot where the manifest file was added
    pub added_snapshot_id: i64,
    /// Number of entries in the manifest that have status ADDED (1), when null this is assumed to be non-zero
    pub added_files_count: Option<i32>,
    /// Number of entries in the manifest that have status EXISTING (0), when null this is assumed to be non-zero
    pub existing_files_count: Option<i32>,
    /// Number of entries in the manifest that have status DELETED (2), when null this is assumed to be non-zero
    pub deleted_files_count: Option<i32>,
    /// Number of rows in all of files in the manifest that have status ADDED, when null this is assumed to be non-zero
    pub added_rows_count: Option<i64>,
    /// Number of rows in all of files in the manifest that have status EXISTING, when null this is assumed to be non-zero
    pub existing_rows_count: Option<i64>,
    /// Number of rows in all of files in the manifest that have status DELETED, when null this is assumed to be non-zero
    pub deleted_rows_count: Option<i64>,
    /// A list of field summaries for each partition field in the spec. Each field in the list corresponds to a field in the manifest file’s partition spec.
    pub partitions: Option<Vec<FieldSummary>>,
    /// Implementation-specific key metadata for encryption
    pub key_metadata: Option<ByteBuf>,
}

/// Entry in manifest file.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(untagged)]
pub enum ManifestListEntryEnum {
    /// Version 2 of the manifest file
    V2(ManifestListEntryV2),
    /// Version 1 of the manifest file
    V1(ManifestListEntryV1),
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(into = "FieldSummarySerde")]
/// DataFile found in Manifest.
pub struct FieldSummary {
    /// Whether the manifest contains at least one partition with a null value for the field
    pub contains_null: bool,
    /// Whether the manifest contains at least one partition with a NaN value for the field
    pub contains_nan: Option<bool>,
    /// Lower bound for the non-null, non-NaN values in the partition field, or null if all values are null or NaN.
    /// If -0.0 is a value of the partition field, the lower_bound must not be +0.0
    pub lower_bound: Option<Value>,
    /// Upper bound for the non-null, non-NaN values in the partition field, or null if all values are null or NaN .
    /// If +0.0 is a value of the partition field, the upper_bound must not be -0.0.
    pub upper_bound: Option<Value>,
}

mod _serde {
    use crate::spec::table_metadata::FormatVersion;

    use super::{Content, FieldSummary, ManifestListEntry, ManifestListEntryEnum};
    use serde::{Deserialize, Serialize};
    use serde_bytes::ByteBuf;

    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
    /// A manifest list includes summary metadata that can be used to avoid scanning all of the manifests in a snapshot when planning a table scan.
    /// This includes the number of added, existing, and deleted files, and a summary of values for each field of the partition spec used to write the manifest.
    pub struct ManifestListEntryV2 {
        /// Location of the manifest file
        pub manifest_path: String,
        /// Length of the manifest file in bytes
        pub manifest_length: i64,
        /// ID of a partition spec used to write the manifest; must be listed in table metadata partition-specs
        pub partition_spec_id: i32,
        /// The type of files tracked by the manifest, either data or delete files; 0 for all v1 manifests
        pub content: Content,
        /// The sequence number when the manifest was added to the table; use 0 when reading v1 manifest lists
        pub sequence_number: i64,
        /// The minimum sequence number of all data or delete files in the manifest; use 0 when reading v1 manifest lists
        pub min_sequence_number: i64,
        /// ID of the snapshot where the manifest file was added
        pub added_snapshot_id: i64,
        /// Number of entries in the manifest that have status ADDED (1), when null this is assumed to be non-zero
        pub added_files_count: i32,
        /// Number of entries in the manifest that have status EXISTING (0), when null this is assumed to be non-zero
        pub existing_files_count: i32,
        /// Number of entries in the manifest that have status DELETED (2), when null this is assumed to be non-zero
        pub deleted_files_count: i32,
        /// Number of rows in all of files in the manifest that have status ADDED, when null this is assumed to be non-zero
        pub added_rows_count: i64,
        /// Number of rows in all of files in the manifest that have status EXISTING, when null this is assumed to be non-zero
        pub existing_rows_count: i64,
        /// Number of rows in all of files in the manifest that have status DELETED, when null this is assumed to be non-zero
        pub deleted_rows_count: i64,
        /// A list of field summaries for each partition field in the spec. Each field in the list corresponds to a field in the manifest file’s partition spec.
        pub partitions: Option<Vec<FieldSummarySerde>>,
        /// Implementation-specific key metadata for encryption
        pub key_metadata: Option<ByteBuf>,
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
    /// A manifest list includes summary metadata that can be used to avoid scanning all of the manifests in a snapshot when planning a table scan.
    /// This includes the number of added, existing, and deleted files, and a summary of values for each field of the partition spec used to write the manifest.
    pub struct ManifestListEntryV1 {
        /// Location of the manifest file
        pub manifest_path: String,
        /// Length of the manifest file in bytes
        pub manifest_length: i64,
        /// ID of a partition spec used to write the manifest; must be listed in table metadata partition-specs
        pub partition_spec_id: i32,
        /// ID of the snapshot where the manifest file was added
        pub added_snapshot_id: i64,
        /// Number of entries in the manifest that have status ADDED (1), when null this is assumed to be non-zero
        pub added_files_count: Option<i32>,
        /// Number of entries in the manifest that have status EXISTING (0), when null this is assumed to be non-zero
        pub existing_files_count: Option<i32>,
        /// Number of entries in the manifest that have status DELETED (2), when null this is assumed to be non-zero
        pub deleted_files_count: Option<i32>,
        /// Number of rows in all of files in the manifest that have status ADDED, when null this is assumed to be non-zero
        pub added_rows_count: Option<i64>,
        /// Number of rows in all of files in the manifest that have status EXISTING, when null this is assumed to be non-zero
        pub existing_rows_count: Option<i64>,
        /// Number of rows in all of files in the manifest that have status DELETED, when null this is assumed to be non-zero
        pub deleted_rows_count: Option<i64>,
        /// A list of field summaries for each partition field in the spec. Each field in the list corresponds to a field in the manifest file’s partition spec.
        pub partitions: Option<Vec<FieldSummarySerde>>,
        /// Implementation-specific key metadata for encryption
        pub key_metadata: Option<ByteBuf>,
    }

    impl From<ManifestListEntry> for ManifestListEntryEnum {
        fn from(value: ManifestListEntry) -> Self {
            match &value.format_version {
                FormatVersion::V2 => ManifestListEntryEnum::V2(value.into()),
                FormatVersion::V1 => ManifestListEntryEnum::V1(value.into()),
            }
        }
    }

    impl From<ManifestListEntry> for ManifestListEntryV1 {
        fn from(value: ManifestListEntry) -> Self {
            ManifestListEntryV1 {
                manifest_path: value.manifest_path,
                manifest_length: value.manifest_length,
                partition_spec_id: value.partition_spec_id,
                added_snapshot_id: value.added_snapshot_id,
                added_files_count: value.added_files_count,
                existing_files_count: value.existing_files_count,
                deleted_files_count: value.deleted_files_count,
                added_rows_count: value.added_rows_count,
                existing_rows_count: value.existing_rows_count,
                deleted_rows_count: value.deleted_rows_count,
                partitions: value
                    .partitions
                    .map(|v| v.into_iter().map(Into::into).collect()),
                key_metadata: value.key_metadata,
            }
        }
    }

    impl From<ManifestListEntry> for ManifestListEntryV2 {
        fn from(value: ManifestListEntry) -> Self {
            ManifestListEntryV2 {
                manifest_path: value.manifest_path,
                manifest_length: value.manifest_length,
                partition_spec_id: value.partition_spec_id,
                content: value.content,
                sequence_number: value.sequence_number,
                min_sequence_number: value.min_sequence_number,
                added_snapshot_id: value.added_snapshot_id,
                added_files_count: value.added_files_count.unwrap(),
                existing_files_count: value.existing_files_count.unwrap(),
                deleted_files_count: value.deleted_files_count.unwrap(),
                added_rows_count: value.added_rows_count.unwrap(),
                existing_rows_count: value.existing_rows_count.unwrap(),
                deleted_rows_count: value.deleted_rows_count.unwrap(),
                partitions: value
                    .partitions
                    .map(|v| v.into_iter().map(Into::into).collect()),
                key_metadata: value.key_metadata,
            }
        }
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
    /// DataFile found in Manifest.
    pub struct FieldSummarySerde {
        /// Whether the manifest contains at least one partition with a null value for the field
        pub contains_null: bool,
        /// Whether the manifest contains at least one partition with a NaN value for the field
        pub contains_nan: Option<bool>,
        /// Lower bound for the non-null, non-NaN values in the partition field, or null if all values are null or NaN.
        /// If -0.0 is a value of the partition field, the lower_bound must not be +0.0
        pub lower_bound: Option<ByteBuf>,
        /// Upper bound for the non-null, non-NaN values in the partition field, or null if all values are null or NaN .
        /// If +0.0 is a value of the partition field, the upper_bound must not be -0.0.
        pub upper_bound: Option<ByteBuf>,
    }

    impl From<FieldSummary> for FieldSummarySerde {
        fn from(value: FieldSummary) -> Self {
            FieldSummarySerde {
                contains_null: value.contains_null,
                contains_nan: value.contains_nan,
                lower_bound: value.lower_bound.map(Into::into),
                upper_bound: value.upper_bound.map(Into::into),
            }
        }
    }
}

impl ManifestListEntry {
    pub fn try_from_enum(
        entry: ManifestListEntryEnum,
        table_metadata: &TableMetadata,
    ) -> Result<ManifestListEntry, Error> {
        match entry {
            ManifestListEntryEnum::V2(entry) => {
                ManifestListEntry::try_from_v2(entry, table_metadata)
            }
            ManifestListEntryEnum::V1(entry) => {
                ManifestListEntry::try_from_v1(entry, table_metadata)
            }
        }
    }

    pub(crate) fn try_from_v2(
        entry: _serde::ManifestListEntryV2,
        table_metadata: &TableMetadata,
    ) -> Result<ManifestListEntry, Error> {
        let partition_types = table_metadata.default_partition_spec()?.data_types(
            &table_metadata
                .current_schema(None)
                .or(table_metadata
                    .refs
                    .values()
                    .next()
                    .ok_or(Error::NotFound("Current".to_string(), "schema".to_string()))
                    .and_then(|x| table_metadata.schema(x.snapshot_id)))
                .unwrap()
                .fields,
        )?;
        Ok(ManifestListEntry {
            format_version: FormatVersion::V2,
            manifest_path: entry.manifest_path,
            manifest_length: entry.manifest_length,
            partition_spec_id: entry.partition_spec_id,
            content: entry.content,
            sequence_number: entry.sequence_number,
            min_sequence_number: entry.min_sequence_number,
            added_snapshot_id: entry.added_snapshot_id,
            added_files_count: Some(entry.added_files_count),
            existing_files_count: Some(entry.existing_files_count),
            deleted_files_count: Some(entry.deleted_files_count),
            added_rows_count: Some(entry.added_rows_count),
            existing_rows_count: Some(entry.existing_rows_count),
            deleted_rows_count: Some(entry.deleted_rows_count),
            partitions: entry
                .partitions
                .map(|v| {
                    v.into_iter()
                        .zip(partition_types.iter())
                        .map(|(x, d)| FieldSummary::try_from(x, d))
                        .collect::<Result<Vec<_>, Error>>()
                })
                .transpose()?,
            key_metadata: entry.key_metadata,
        })
    }

    pub(crate) fn try_from_v1(
        entry: _serde::ManifestListEntryV1,
        table_metadata: &TableMetadata,
    ) -> Result<ManifestListEntry, Error> {
        let partition_types = table_metadata.default_partition_spec()?.data_types(
            &table_metadata
                .current_schema(None)
                .or(table_metadata
                    .refs
                    .values()
                    .next()
                    .ok_or(Error::NotFound("Current".to_string(), "schema".to_string()))
                    .and_then(|x| table_metadata.schema(x.snapshot_id)))
                .unwrap()
                .fields,
        )?;
        Ok(ManifestListEntry {
            format_version: FormatVersion::V1,
            manifest_path: entry.manifest_path,
            manifest_length: entry.manifest_length,
            partition_spec_id: entry.partition_spec_id,
            content: Content::Data,
            sequence_number: 0,
            min_sequence_number: 0,
            added_snapshot_id: entry.added_snapshot_id,
            added_files_count: entry.added_files_count,
            existing_files_count: entry.existing_files_count,
            deleted_files_count: entry.deleted_files_count,
            added_rows_count: entry.added_rows_count,
            existing_rows_count: entry.existing_rows_count,
            deleted_rows_count: entry.deleted_rows_count,
            partitions: entry
                .partitions
                .map(|v| {
                    v.into_iter()
                        .zip(partition_types.iter())
                        .map(|(x, d)| FieldSummary::try_from(x, d))
                        .collect::<Result<Vec<_>, Error>>()
                })
                .transpose()?,
            key_metadata: entry.key_metadata,
        })
    }
}

impl FieldSummary {
    fn try_from(value: _serde::FieldSummarySerde, data_type: &Type) -> Result<Self, Error> {
        Ok(FieldSummary {
            contains_null: value.contains_null,
            contains_nan: value.contains_nan,
            lower_bound: value
                .lower_bound
                .map(|x| Value::try_from_bytes(&x, data_type))
                .transpose()?,
            upper_bound: value
                .upper_bound
                .map(|x| Value::try_from_bytes(&x, data_type))
                .transpose()?,
        })
    }
}

impl ManifestListEntry {
    /// Get schema of the manifest list
    pub fn schema(format_version: &FormatVersion) -> Result<AvroSchema, Error> {
        let schema = match format_version {
            FormatVersion::V1 => r#"
        {
            "type": "record",
            "name": "manifest_list",
            "fields": [
                {
                    "name": "manifest_path",
                    "type": "string",
                    "field_id": 500
                },
                {
                    "name": "manifest_length",
                    "type": "long",
                    "field_id": 501
                },
                {
                    "name": "partition_spec_id",
                    "type": "int",
                    "field_id": 502
                },
                {
                    "name": "added_snapshot_id",
                    "type": "long",
                    "field_id": 503
                },
                {
                    "name": "added_files_count",
                    "type": [
                        "null",
                        "int"
                    ],
                    "default": null,
                    "field_id": 504
                },
                {
                    "name": "existing_files_count",
                    "type": [
                        "null",
                        "int"
                    ],
                    "default": null,
                    "field_id": 505
                },
                {
                    "name": "deleted_files_count",
                    "type": [
                        "null",
                        "int"
                    ],
                    "default": null,
                    "field_id": 506
                },
                {
                    "name": "added_rows_count",
                    "type": [
                        "null",
                        "long"
                    ],
                    "default": null,
                    "field_id": 512
                },
                {
                    "name": "existing_rows_count",
                    "type": [
                        "null",
                        "long"
                    ],
                    "default": null,
                    "field_id": 513
                },
                {
                    "name": "deleted_rows_count",
                    "type": [
                        "null",
                        "long"
                    ],
                    "default": null,
                    "field_id": 514
                },
                {
                    "name": "partitions",
                    "type": [
                        "null",
                        {
                            "type": "array",
                            "items": {
                                "type": "record",
                                "name": "field_summary",
                                "fields": [
                                    {
                                        "name": "contains_null",
                                        "type": "boolean",
                                        "field_id": 509
                                    },
                                    {
                                        "name": "contains_nan",
                                        "type": [
                                            "null",
                                            "boolean"
                                        ],
                                        "field_id": 518
                                    },
                                    {
                                        "name": "lower_bound",
                                        "type": [
                                            "null",
                                            "bytes"
                                        ],
                                        "field_id": 510
                                    },
                                    {
                                        "name": "upper_bound",
                                        "type": [
                                            "null",
                                            "bytes"
                                        ],
                                        "field_id": 511
                                    }
                                ]
                            },
                            "element-id": 112
                        }
                    ],
                    "default": null,
                    "field_id": 507
                },
                {
                    "name": "key_metadata",
                    "type": [
                        "null",
                        "bytes"
                    ],
                    "field_id": 519
                }
            ]
        }
        "#
            .to_owned(),
            &FormatVersion::V2 => r#"
        {
            "type": "record",
            "name": "manifest_list",
            "fields": [
                {
                    "name": "manifest_path",
                    "type": "string",
                    "field_id": 500
                },
                {
                    "name": "manifest_length",
                    "type": "long",
                    "field_id": 501
                },
                {
                    "name": "partition_spec_id",
                    "type": "int",
                    "field_id": 502
                },
                {
                    "name": "content",
                    "type": "int",
                    "field_id": 517
                },
                {
                    "name": "sequence_number",
                    "type": "long",
                    "field_id": 515
                },
                {
                    "name": "min_sequence_number",
                    "type": "long",
                    "field_id": 516
                },
                {
                    "name": "added_snapshot_id",
                    "type": "long",
                    "field_id": 503
                },
                {
                    "name": "added_files_count",
                    "type": "int",
                    "field_id": 504
                },
                {
                    "name": "existing_files_count",
                    "type": "int",
                    "field_id": 505
                },
                {
                    "name": "deleted_files_count",
                    "type": "int",
                    "field_id": 506
                },
                {
                    "name": "added_rows_count",
                    "type": "long",
                    "field_id": 512
                },
                {
                    "name": "existing_rows_count",
                    "type": "long",
                    "field_id": 513
                },
                {
                    "name": "deleted_rows_count",
                    "type": "long",
                    "field_id": 514
                },
                {
                    "name": "partitions",
                    "type": [
                        "null",
                        {
                            "type": "array",
                            "items": {
                                "type": "record",
                                "name": "field_summary",
                                "fields": [
                                    {
                                        "name": "contains_null",
                                        "type": "boolean",
                                        "field_id": 509
                                    },
                                    {
                                        "name": "contains_nan",
                                        "type": [
                                            "null",
                                            "boolean"
                                        ],
                                        "field_id": 518
                                    },
                                    {
                                        "name": "lower_bound",
                                        "type": [
                                            "null",
                                            "bytes"
                                        ],
                                        "field_id": 510
                                    },
                                    {
                                        "name": "upper_bound",
                                        "type": [
                                            "null",
                                            "bytes"
                                        ],
                                        "field_id": 511
                                    }
                                ]
                            },
                            "element-id": 112
                        }
                    ],
                    "default": null,
                    "field_id": 507
                },
                {
                    "name": "key_metadata",
                    "type": [
                        "null",
                        "bytes"
                    ],
                    "field_id": 519
                }
            ]
        }
        "#
            .to_owned(),
        };
        AvroSchema::parse_str(&schema).map_err(Into::into)
    }
}

/// Convert an avro value to a [ManifestFile] according to the provided format version
pub(crate) fn avro_value_to_manifest_file(
    value: (Result<AvroValue, apache_avro::Error>, &TableMetadata),
) -> Result<ManifestListEntry, Error> {
    let entry = value.0?;
    let table_metadata = value.1;
    match table_metadata.format_version {
        FormatVersion::V1 => ManifestListEntry::try_from_v1(
            apache_avro::from_value::<_serde::ManifestListEntryV1>(&entry)?,
            table_metadata,
        ),
        FormatVersion::V2 => ManifestListEntry::try_from_v2(
            apache_avro::from_value::<_serde::ManifestListEntryV2>(&entry)?,
            table_metadata,
        ),
    }
}

#[cfg(test)]
mod tests {

    use std::collections::HashMap;

    use super::*;

    use crate::spec::{
        partition::{PartitionField, PartitionSpecBuilder, Transform},
        schema::Schema,
        table_metadata::TableMetadataBuilder,
        types::{PrimitiveType, StructField, StructTypeBuilder},
    };

    #[test]
    pub fn test_manifest_list_v2() {
        let table_metadata = TableMetadataBuilder::default()
            .location("/")
            .current_schema_id(1)
            .schemas(HashMap::from_iter(vec![(
                1,
                Schema {
                    schema_id: 1,
                    identifier_field_ids: None,
                    fields: StructTypeBuilder::default()
                        .with_struct_field(StructField {
                            id: 0,
                            name: "date".to_string(),
                            required: true,
                            field_type: Type::Primitive(PrimitiveType::Date),
                            doc: None,
                        })
                        .build()
                        .unwrap(),
                },
            )]))
            .default_spec_id(1)
            .partition_specs(HashMap::from_iter(vec![(
                1,
                PartitionSpecBuilder::default()
                    .spec_id(1)
                    .with_partition_field(PartitionField {
                        source_id: 0,
                        field_id: 1000,
                        name: "day".to_string(),
                        transform: Transform::Day,
                    })
                    .build()
                    .unwrap(),
            )]))
            .build()
            .unwrap();

        let manifest_file = ManifestListEntry {
            format_version: FormatVersion::V2,
            manifest_path: "".to_string(),
            manifest_length: 1200,
            partition_spec_id: 0,
            content: Content::Data,
            sequence_number: 566,
            min_sequence_number: 0,
            added_snapshot_id: 39487483032,
            added_files_count: Some(1),
            existing_files_count: Some(2),
            deleted_files_count: Some(0),
            added_rows_count: Some(1000),
            existing_rows_count: Some(8000),
            deleted_rows_count: Some(0),
            partitions: Some(vec![FieldSummary {
                contains_null: true,
                contains_nan: Some(false),
                lower_bound: Some(Value::Date(1234)),
                upper_bound: Some(Value::Date(76890)),
            }]),
            key_metadata: None,
        };

        let schema = ManifestListEntry::schema(&FormatVersion::V2).unwrap();

        let mut writer = apache_avro::Writer::new(&schema, Vec::new());

        writer.append_ser(manifest_file.clone()).unwrap();

        let encoded = writer.into_inner().unwrap();

        let reader = apache_avro::Reader::new(&*encoded).unwrap();

        for record in reader {
            let result =
                apache_avro::from_value::<_serde::ManifestListEntryV2>(&record.unwrap()).unwrap();
            assert_eq!(
                manifest_file,
                ManifestListEntry::try_from_v2(result, &table_metadata).unwrap()
            );
        }
    }

    #[test]
    pub fn test_manifest_list_v1() {
        let table_metadata = TableMetadataBuilder::default()
            .format_version(FormatVersion::V1)
            .location("/")
            .current_schema_id(1)
            .schemas(HashMap::from_iter(vec![(
                1,
                Schema {
                    schema_id: 1,
                    identifier_field_ids: None,
                    fields: StructTypeBuilder::default()
                        .with_struct_field(StructField {
                            id: 0,
                            name: "date".to_string(),
                            required: true,
                            field_type: Type::Primitive(PrimitiveType::Date),
                            doc: None,
                        })
                        .build()
                        .unwrap(),
                },
            )]))
            .default_spec_id(1)
            .partition_specs(HashMap::from_iter(vec![(
                1,
                PartitionSpecBuilder::default()
                    .spec_id(1)
                    .with_partition_field(PartitionField {
                        source_id: 0,
                        field_id: 1000,
                        name: "day".to_string(),
                        transform: Transform::Day,
                    })
                    .build()
                    .unwrap(),
            )]))
            .build()
            .unwrap();

        let manifest_file = ManifestListEntry {
            format_version: FormatVersion::V1,
            manifest_path: "".to_string(),
            manifest_length: 1200,
            partition_spec_id: 0,
            content: Content::Data,
            sequence_number: 0,
            min_sequence_number: 0,
            added_snapshot_id: 39487483032,
            added_files_count: Some(1),
            existing_files_count: Some(2),
            deleted_files_count: Some(0),
            added_rows_count: Some(1000),
            existing_rows_count: Some(8000),
            deleted_rows_count: Some(0),
            partitions: Some(vec![FieldSummary {
                contains_null: true,
                contains_nan: Some(false),
                lower_bound: Some(Value::Date(1234)),
                upper_bound: Some(Value::Date(76890)),
            }]),
            key_metadata: None,
        };

        let schema = ManifestListEntry::schema(&FormatVersion::V1).unwrap();

        let mut writer = apache_avro::Writer::new(&schema, Vec::new());

        writer.append_ser(manifest_file.clone()).unwrap();

        let encoded = writer.into_inner().unwrap();

        let reader = apache_avro::Reader::new(&*encoded).unwrap();

        for record in reader {
            let result =
                apache_avro::from_value::<_serde::ManifestListEntryV1>(&record.unwrap()).unwrap();
            assert_eq!(
                manifest_file,
                ManifestListEntry::try_from_v1(result, &table_metadata).unwrap()
            );
        }
    }
}