parquet 58.3.0

Apache Parquet implementation in Rust
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
// 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.

use std::collections::HashMap;
use std::sync::Arc;

use crate::arrow::schema::extension::try_add_extension_type;
use crate::arrow::schema::primitive::convert_primitive;
use crate::arrow::schema::virtual_type::{RowGroupIndex, RowNumber};
use crate::arrow::{PARQUET_FIELD_ID_META_KEY, ProjectionMask};
use crate::basic::{ConvertedType, Repetition};
use crate::errors::ParquetError;
use crate::errors::Result;
use crate::schema::types::{SchemaDescriptor, Type, TypePtr};
use arrow_schema::{DataType, Field, Fields, SchemaBuilder, extension::ExtensionType};

fn get_repetition(t: &Type) -> Repetition {
    let info = t.get_basic_info();
    match info.has_repetition() {
        true => info.repetition(),
        false => Repetition::REQUIRED,
    }
}

/// Representation of a parquet schema element, in terms of arrow schema elements
#[derive(Debug, Clone)]
pub struct ParquetField {
    /// The level which represents an insertion into the current list
    /// i.e. guaranteed to be > 0 for an element of list type
    pub rep_level: i16,
    /// The level at which this field is fully defined,
    /// i.e. guaranteed to be > 0 for a nullable type or child of a
    /// nullable type
    pub def_level: i16,
    /// Whether this field is nullable
    pub nullable: bool,
    /// The arrow type of the column data
    ///
    /// Note: In certain cases the data stored in parquet may have been coerced
    /// to a different type and will require conversion on read (e.g. Date64 and Interval)
    pub arrow_type: DataType,
    /// The type of this field
    pub field_type: ParquetFieldType,
}

impl ParquetField {
    /// Converts `self` into an arrow list, with its current type as the field type
    ///
    /// This is used to convert repeated columns, into their arrow representation
    fn into_list(self, name: &str) -> Self {
        ParquetField {
            rep_level: self.rep_level,
            def_level: self.def_level,
            nullable: false,
            arrow_type: DataType::List(Arc::new(Field::new(name, self.arrow_type.clone(), false))),
            field_type: ParquetFieldType::Group {
                children: vec![self],
            },
        }
    }

    /// Converts `self` into an arrow list, with its current type as the field type
    /// accept an optional `list_data_type` to specify the type of list to create
    ///
    /// This is used to convert [deprecated repeated columns] (not in a list), into their arrow representation
    ///
    /// [deprecated repeated columns]: https://github.com/apache/parquet-format/blob/9fd57b59e0ce1a82a69237dcf8977d3e72a2965d/LogicalTypes.md?plain=1#L649-L650
    fn into_list_with_arrow_list_hint(
        self,
        parquet_field_type: &Type,
        list_data_type: Option<DataType>,
    ) -> Result<Self, ParquetError> {
        let arrow_field = match &list_data_type {
            Some(DataType::List(field_hint))
            | Some(DataType::LargeList(field_hint))
            | Some(DataType::FixedSizeList(field_hint, _)) => Some(field_hint.as_ref()),
            Some(_) => {
                return Err(general_err!(
                    "Internal error: should be validated earlier that list_data_type is only a type of list"
                ));
            }
            None => None,
        };

        let arrow_field = convert_field(
            parquet_field_type,
            &self,
            arrow_field,
            // Only add the field id to the list and not to the element
            false,
        )?
        .with_nullable(false);

        Ok(ParquetField {
            rep_level: self.rep_level,
            def_level: self.def_level,
            nullable: false,
            arrow_type: match list_data_type {
                Some(DataType::List(_)) => DataType::List(Arc::new(arrow_field)),
                Some(DataType::LargeList(_)) => DataType::LargeList(Arc::new(arrow_field)),
                Some(DataType::FixedSizeList(_, len)) => {
                    DataType::FixedSizeList(Arc::new(arrow_field), len)
                }
                _ => DataType::List(Arc::new(arrow_field)),
            },
            field_type: ParquetFieldType::Group {
                children: vec![self],
            },
        })
    }

    /// Returns a list of [`ParquetField`] children if this is a group type
    pub fn children(&self) -> Option<&[Self]> {
        match &self.field_type {
            ParquetFieldType::Primitive { .. } => None,
            ParquetFieldType::Group { children } => Some(children),
            ParquetFieldType::Virtual(_) => None,
        }
    }
}

/// Types of virtual columns that can be computed at read time
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VirtualColumnType {
    /// Row number within the file
    RowNumber,
    /// Row group index
    RowGroupIndex,
}

#[derive(Debug, Clone)]
pub enum ParquetFieldType {
    Primitive {
        /// The index of the column in parquet
        col_idx: usize,
        /// The type of the column in parquet
        primitive_type: TypePtr,
    },
    Group {
        children: Vec<ParquetField>,
    },
    /// Virtual column that doesn't exist in the parquet file
    /// but is computed at read time (e.g., row_number)
    Virtual(VirtualColumnType),
}

/// Encodes the context of the parent of the field currently under consideration
struct VisitorContext {
    rep_level: i16,
    def_level: i16,
    /// An optional [`DataType`] sourced from the embedded arrow schema
    data_type: Option<DataType>,

    /// Whether to treat repeated types as list from arrow types
    /// when true, if data_type provided it should be DataType::List() (or other list type)
    /// and the list field data type would be treated as the hint for the parquet type
    ///
    /// when false, if data_type provided it will be treated as the hint without unwrapping
    ///
    /// This is for supporting [deprecated parquet list representation][1]
    ///
    /// [1]: https://github.com/apache/parquet-format/blob/38818fa0e7efd54b535001a4448030a40619c2a3/LogicalTypes.md?plain=1#L718-L806
    treat_repeated_as_list_arrow_hint: bool,
}

impl VisitorContext {
    /// Compute the resulting definition level, repetition level and nullability
    /// for a child field with the given [`Repetition`]
    fn levels(&self, repetition: Repetition) -> (i16, i16, bool) {
        match repetition {
            Repetition::OPTIONAL => (self.def_level + 1, self.rep_level, true),
            Repetition::REQUIRED => (self.def_level, self.rep_level, false),
            Repetition::REPEATED => (self.def_level + 1, self.rep_level + 1, false),
        }
    }
}

/// Walks the parquet schema in a depth-first fashion in order to map it to arrow data structures
///
/// See [Logical Types] for more information on the conversion algorithm
///
/// [Logical Types]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md
struct Visitor {
    /// The column index of the next leaf column
    next_col_idx: usize,

    /// Mask of columns to include
    mask: ProjectionMask,
}

impl Visitor {
    fn visit_primitive(
        &mut self,
        primitive_type: &TypePtr,
        context: VisitorContext,
    ) -> Result<Option<ParquetField>> {
        let col_idx = self.next_col_idx;
        self.next_col_idx += 1;

        if !self.mask.leaf_included(col_idx) {
            return Ok(None);
        }

        let repetition = get_repetition(primitive_type);
        let (def_level, rep_level, nullable) = context.levels(repetition);

        let primitive_arrow_data_type = match repetition {
            Repetition::REPEATED if context.treat_repeated_as_list_arrow_hint => {
                let arrow_field = match &context.data_type {
                    Some(DataType::List(f)) => Some(f.as_ref()),
                    Some(DataType::LargeList(f)) => Some(f.as_ref()),
                    Some(DataType::FixedSizeList(f, _)) => Some(f.as_ref()),
                    Some(d) => {
                        return Err(arrow_err!(
                            "incompatible arrow schema, expected list got {} for repeated primitive field",
                            d
                        ));
                    }
                    None => None,
                };

                arrow_field.map(|f| f.data_type().clone())
            }
            _ => context.data_type.clone(),
        };

        let arrow_type = convert_primitive(primitive_type, primitive_arrow_data_type)?;

        let primitive_field = ParquetField {
            rep_level,
            def_level,
            nullable,
            arrow_type,
            field_type: ParquetFieldType::Primitive {
                primitive_type: primitive_type.clone(),
                col_idx,
            },
        };

        Ok(Some(match repetition {
            Repetition::REPEATED if context.treat_repeated_as_list_arrow_hint => {
                primitive_field.into_list_with_arrow_list_hint(primitive_type, context.data_type)?
            }
            Repetition::REPEATED => primitive_field.into_list(primitive_type.name()),
            _ => primitive_field,
        }))
    }

    fn visit_struct(
        &mut self,
        struct_type: &TypePtr,
        context: VisitorContext,
    ) -> Result<Option<ParquetField>> {
        // The root type will not have a repetition level
        let repetition = get_repetition(struct_type);
        let (def_level, rep_level, nullable) = context.levels(repetition);

        let parquet_fields = struct_type.get_fields();

        // Extract any arrow fields from the hints
        let arrow_struct = match repetition {
            Repetition::REPEATED if context.treat_repeated_as_list_arrow_hint => {
                let arrow_field = match &context.data_type {
                    Some(DataType::List(f)) => Some(f.as_ref()),
                    Some(DataType::LargeList(f)) => Some(f.as_ref()),
                    Some(DataType::FixedSizeList(f, _)) => Some(f.as_ref()),
                    Some(d) => {
                        return Err(arrow_err!(
                            "incompatible arrow schema, expected list got {} for repeated struct field",
                            d
                        ));
                    }
                    None => None,
                };

                arrow_field.map(|f| f.data_type())
            }
            _ => context.data_type.as_ref(),
        };

        let arrow_fields = match &arrow_struct {
            Some(DataType::Struct(fields)) => {
                if fields.len() != parquet_fields.len() {
                    return Err(arrow_err!(
                        "incompatible arrow schema, expected {} struct fields got {}",
                        parquet_fields.len(),
                        fields.len()
                    ));
                }
                Some(fields)
            }
            Some(d) => {
                return Err(arrow_err!(
                    "incompatible arrow schema, expected struct got {}",
                    d
                ));
            }
            None => None,
        };

        let mut child_fields = SchemaBuilder::with_capacity(parquet_fields.len());
        let mut children = Vec::with_capacity(parquet_fields.len());

        // Perform a DFS of children
        for (idx, parquet_field) in parquet_fields.iter().enumerate() {
            let data_type = match arrow_fields {
                Some(fields) => {
                    let field = &fields[idx];
                    if field.name() != parquet_field.name() {
                        return Err(arrow_err!(
                            "incompatible arrow schema, expected field named {} got {}",
                            parquet_field.name(),
                            field.name()
                        ));
                    }
                    Some(field.data_type().clone())
                }
                None => None,
            };

            let arrow_field = arrow_fields.map(|x| &*x[idx]);
            let child_ctx = VisitorContext {
                rep_level,
                def_level,
                data_type,

                // Always true: each child is independently responsible for its own
                // repeated-to-list conversion. The parent's flag may be false when
                // this struct's own repetition is consumed by an outer visit_list
                // backward-compat path, but that only applies to the struct itself,
                // not its children. A repeated child's arrow hint will be List<...>
                // and needs to be unwrapped accordingly.
                treat_repeated_as_list_arrow_hint: true,
            };

            if let Some(child) = self.dispatch(parquet_field, child_ctx)? {
                // The child type returned may be different from what is encoded in the arrow
                // schema in the event of a mismatch or a projection
                child_fields.push(convert_field(parquet_field, &child, arrow_field, true)?);
                children.push(child);
            }
        }

        if children.is_empty() {
            return Ok(None);
        }

        let struct_field = ParquetField {
            rep_level,
            def_level,
            nullable,
            arrow_type: DataType::Struct(child_fields.finish().fields),
            field_type: ParquetFieldType::Group { children },
        };

        Ok(Some(match repetition {
            Repetition::REPEATED if context.treat_repeated_as_list_arrow_hint => {
                struct_field.into_list_with_arrow_list_hint(struct_type, context.data_type)?
            }
            Repetition::REPEATED => struct_field.into_list(struct_type.name()),
            _ => struct_field,
        }))
    }

    fn visit_map(
        &mut self,
        map_type: &TypePtr,
        context: VisitorContext,
    ) -> Result<Option<ParquetField>> {
        let rep_level = context.rep_level + 1;
        let (def_level, nullable) = match get_repetition(map_type) {
            Repetition::REQUIRED => (context.def_level + 1, false),
            Repetition::OPTIONAL => (context.def_level + 2, true),
            Repetition::REPEATED => return Err(arrow_err!("Map cannot be repeated")),
        };

        if map_type.get_fields().len() != 1 {
            return Err(arrow_err!(
                "Map field must have exactly one key_value child, found {}",
                map_type.get_fields().len()
            ));
        }

        // Add map entry (key_value) to context
        let map_key_value = &map_type.get_fields()[0];
        if map_key_value.get_basic_info().repetition() != Repetition::REPEATED {
            return Err(arrow_err!("Child of map field must be repeated"));
        }

        // According to the specification the values are optional (#1642).
        // In this case, return the keys as a list.
        if map_key_value.get_fields().len() == 1 {
            return self.visit_list(map_type, context);
        }

        if map_key_value.get_fields().len() != 2 {
            return Err(arrow_err!(
                "Child of map field must have two children, found {}",
                map_key_value.get_fields().len()
            ));
        }

        // Get key and value, and create context for each
        let map_key = &map_key_value.get_fields()[0];
        let map_value = &map_key_value.get_fields()[1];

        match map_key.get_basic_info().repetition() {
            Repetition::REPEATED => {
                return Err(arrow_err!("Map keys cannot be repeated"));
            }
            Repetition::REQUIRED | Repetition::OPTIONAL => {
                // Relaxed check for having repetition REQUIRED as there exists
                // parquet writers and files that do not conform to this standard.
                // This allows us to consume a broader range of existing files even
                // if they are out of spec.
            }
        }

        if map_value.get_basic_info().repetition() == Repetition::REPEATED {
            return Err(arrow_err!("Map values cannot be repeated"));
        }

        // Extract the arrow fields
        let (arrow_map, arrow_key, arrow_value, sorted) = match &context.data_type {
            Some(DataType::Map(field, sorted)) => match field.data_type() {
                DataType::Struct(fields) => {
                    if fields.len() != 2 {
                        return Err(arrow_err!(
                            "Map data type should contain struct with two children, got {}",
                            fields.len()
                        ));
                    }

                    (Some(field), Some(&*fields[0]), Some(&*fields[1]), *sorted)
                }
                d => {
                    return Err(arrow_err!("Map data type should contain struct got {}", d));
                }
            },
            Some(d) => {
                return Err(arrow_err!(
                    "incompatible arrow schema, expected map got {}",
                    d
                ));
            }
            None => (None, None, None, false),
        };

        let maybe_key = {
            let context = VisitorContext {
                rep_level,
                def_level,
                data_type: arrow_key.map(|x| x.data_type().clone()),
                // Key is not repeated
                treat_repeated_as_list_arrow_hint: false,
            };

            self.dispatch(map_key, context)?
        };

        let maybe_value = {
            let context = VisitorContext {
                rep_level,
                def_level,
                data_type: arrow_value.map(|x| x.data_type().clone()),
                // Value type can be repeated
                treat_repeated_as_list_arrow_hint: true,
            };

            self.dispatch(map_value, context)?
        };

        // Need both columns to be projected
        match (maybe_key, maybe_value) {
            (Some(key), Some(value)) => {
                let key_field = Arc::new(
                    convert_field(map_key, &key, arrow_key, true)?
                        // The key is always non-nullable (#5630)
                        .with_nullable(false),
                );
                let value_field = Arc::new(convert_field(map_value, &value, arrow_value, true)?);
                let field_metadata = match arrow_map {
                    Some(field) => field.metadata().clone(),
                    _ => HashMap::default(),
                };

                let map_field = Field::new_struct(
                    map_key_value.name(),
                    [key_field, value_field],
                    false, // The inner map field is always non-nullable (#1697)
                )
                .with_metadata(field_metadata);

                Ok(Some(ParquetField {
                    rep_level,
                    def_level,
                    nullable,
                    arrow_type: DataType::Map(Arc::new(map_field), sorted),
                    field_type: ParquetFieldType::Group {
                        children: vec![key, value],
                    },
                }))
            }
            _ => Ok(None),
        }
    }

    fn visit_list(
        &mut self,
        list_type: &TypePtr,
        context: VisitorContext,
    ) -> Result<Option<ParquetField>> {
        if list_type.is_primitive() {
            return Err(arrow_err!(
                "{:?} is a list type and can't be processed as primitive.",
                list_type
            ));
        }

        let fields = list_type.get_fields();
        if fields.len() != 1 {
            return Err(arrow_err!(
                "list type must have a single child, found {}",
                fields.len()
            ));
        }

        let repeated_field = &fields[0];
        if get_repetition(repeated_field) != Repetition::REPEATED {
            return Err(arrow_err!("List child must be repeated"));
        }

        // If the list is nullable
        let (def_level, nullable) = match list_type.get_basic_info().repetition() {
            Repetition::REQUIRED => (context.def_level, false),
            Repetition::OPTIONAL => (context.def_level + 1, true),
            Repetition::REPEATED => return Err(arrow_err!("List type cannot be repeated")),
        };

        let arrow_field = match &context.data_type {
            Some(DataType::List(f)) => Some(f.as_ref()),
            Some(DataType::LargeList(f)) => Some(f.as_ref()),
            Some(DataType::FixedSizeList(f, _)) => Some(f.as_ref()),
            Some(DataType::ListView(f)) => Some(f.as_ref()),
            Some(DataType::LargeListView(f)) => Some(f.as_ref()),
            Some(d) => {
                return Err(arrow_err!(
                    "incompatible arrow schema, expected list got {}",
                    d
                ));
            }
            None => None,
        };

        if repeated_field.is_primitive() {
            // If the repeated field is not a group, then its type is the element type and elements are required.
            //
            // required/optional group my_list (LIST) {
            //   repeated int32 element;
            // }
            //
            let context = VisitorContext {
                rep_level: context.rep_level,
                def_level,
                data_type: arrow_field.map(|f| f.data_type().clone()),
                treat_repeated_as_list_arrow_hint: false,
            };

            return match self.visit_primitive(repeated_field, context) {
                Ok(Some(mut field)) => {
                    // visit_primitive will infer a non-nullable list, update if necessary
                    field.nullable = nullable;
                    Ok(Some(field))
                }
                r => r,
            };
        }

        // test to see if the repeated field is a struct or one-tuple
        let items = repeated_field.get_fields();
        if items.len() != 1
            || (!repeated_field.is_list()
                && !repeated_field.has_single_repeated_child()
                && (repeated_field.name() == "array"
                    || repeated_field.name() == format!("{}_tuple", list_type.name())))
        {
            // If the repeated field is a group with multiple fields, then its type is the element
            // type and elements are required.
            //
            // If the repeated field is a group with one field and is named either array or uses
            // the LIST-annotated group's name with _tuple appended then the repeated type is the
            // element type and elements are required. But this rule only applies if the
            // repeated field is not annotated, and the single child field is not `repeated`.
            let context = VisitorContext {
                rep_level: context.rep_level,
                def_level,
                data_type: arrow_field.map(|f| f.data_type().clone()),
                treat_repeated_as_list_arrow_hint: false,
            };

            return match self.visit_struct(repeated_field, context) {
                Ok(Some(mut field)) => {
                    field.nullable = nullable;
                    Ok(Some(field))
                }
                r => r,
            };
        }

        // Regular list handling logic
        let item_type = &items[0];
        let rep_level = context.rep_level + 1;
        let def_level = def_level + 1;

        let new_context = VisitorContext {
            def_level,
            rep_level,
            data_type: arrow_field.map(|f| f.data_type().clone()),
            treat_repeated_as_list_arrow_hint: true,
        };

        match self.dispatch(item_type, new_context) {
            Ok(Some(item)) => {
                let item_field = Arc::new(convert_field(item_type, &item, arrow_field, true)?);

                // Use arrow type as hint for index size
                let arrow_type = match context.data_type {
                    Some(DataType::LargeList(_)) => DataType::LargeList(item_field),
                    Some(DataType::FixedSizeList(_, len)) => {
                        DataType::FixedSizeList(item_field, len)
                    }
                    Some(DataType::ListView(_)) => DataType::ListView(item_field),
                    Some(DataType::LargeListView(_)) => DataType::LargeListView(item_field),
                    _ => DataType::List(item_field),
                };

                Ok(Some(ParquetField {
                    rep_level,
                    def_level,
                    nullable,
                    arrow_type,
                    field_type: ParquetFieldType::Group {
                        children: vec![item],
                    },
                }))
            }
            r => r,
        }
    }

    fn dispatch(
        &mut self,
        cur_type: &TypePtr,
        context: VisitorContext,
    ) -> Result<Option<ParquetField>> {
        if cur_type.is_primitive() {
            self.visit_primitive(cur_type, context)
        } else {
            match cur_type.get_basic_info().converted_type() {
                ConvertedType::LIST => self.visit_list(cur_type, context),
                ConvertedType::MAP | ConvertedType::MAP_KEY_VALUE => {
                    self.visit_map(cur_type, context)
                }
                _ => self.visit_struct(cur_type, context),
            }
        }
    }
}

/// Converts a virtual Arrow [`Field`] to a [`ParquetField`]
///
/// Virtual fields don't correspond to any data in the parquet file,
/// but are computed at read time (e.g., row_number)
///
/// The levels are computed based on the parent context:
/// - If nullable: def_level = parent_def_level + 1
/// - If required: def_level = parent_def_level
/// - rep_level = parent_rep_level (virtual fields are not repeated)
pub(super) fn convert_virtual_field(
    arrow_field: &Field,
    parent_rep_level: i16,
    parent_def_level: i16,
) -> Result<ParquetField> {
    let nullable = arrow_field.is_nullable();
    let def_level = if nullable {
        parent_def_level + 1
    } else {
        parent_def_level
    };

    // Determine the virtual column type based on the extension type name
    let extension_name = arrow_field.extension_type_name().ok_or_else(|| {
        ParquetError::ArrowError(format!(
            "virtual column field '{}' must have an extension type",
            arrow_field.name()
        ))
    })?;

    let virtual_type = match extension_name {
        RowNumber::NAME => VirtualColumnType::RowNumber,
        RowGroupIndex::NAME => VirtualColumnType::RowGroupIndex,
        _ => {
            return Err(ParquetError::ArrowError(format!(
                "unsupported virtual column type '{}' for field '{}'",
                extension_name,
                arrow_field.name()
            )));
        }
    };

    Ok(ParquetField {
        rep_level: parent_rep_level,
        def_level,
        nullable,
        arrow_type: arrow_field.data_type().clone(),
        field_type: ParquetFieldType::Virtual(virtual_type),
    })
}

/// Computes the Arrow [`Field`] for a child column
///
/// The resulting Arrow [`Field`] will have the type dictated by the Parquet `field`, a name
/// dictated by the `parquet_type`, and any metadata from `arrow_hint`
fn convert_field(
    parquet_type: &Type,
    field: &ParquetField,
    arrow_hint: Option<&Field>,
    add_field_id: bool,
) -> Result<Field, ParquetError> {
    let name = parquet_type.name();
    let data_type = field.arrow_type.clone();
    let nullable = field.nullable;

    match arrow_hint {
        Some(hint) => {
            // If the inferred type is a dictionary, preserve dictionary metadata
            #[allow(deprecated)]
            let field = match (&data_type, hint.dict_id(), hint.dict_is_ordered()) {
                (DataType::Dictionary(_, _), Some(id), Some(ordered)) =>
                {
                    #[allow(deprecated)]
                    Field::new_dict(name, data_type, nullable, id, ordered)
                }
                _ => Field::new(name, data_type, nullable),
            };

            Ok(field.with_metadata(hint.metadata().clone()))
        }
        None => {
            let mut ret = Field::new(name, data_type, nullable);
            let basic_info = parquet_type.get_basic_info();
            if add_field_id && basic_info.has_id() {
                let mut meta = HashMap::with_capacity(1);
                meta.insert(
                    PARQUET_FIELD_ID_META_KEY.to_string(),
                    basic_info.id().to_string(),
                );
                ret.set_metadata(meta);
            }
            try_add_extension_type(ret, parquet_type)
        }
    }
}

/// Computes the [`ParquetField`] for the provided [`SchemaDescriptor`] with `leaf_columns` listing
/// the indexes of leaf columns to project, and `embedded_arrow_schema` the optional
/// [`Fields`] embedded in the parquet metadata
///
/// Note: This does not support out of order column projection
pub fn convert_schema(
    schema: &SchemaDescriptor,
    mask: ProjectionMask,
    embedded_arrow_schema: Option<&Fields>,
) -> Result<Option<ParquetField>> {
    let mut visitor = Visitor {
        next_col_idx: 0,
        mask,
    };

    let context = VisitorContext {
        rep_level: 0,
        def_level: 0,
        data_type: embedded_arrow_schema.map(|fields| DataType::Struct(fields.clone())),
        treat_repeated_as_list_arrow_hint: true,
    };

    visitor.dispatch(&schema.root_schema_ptr(), context)
}

/// Computes the [`ParquetField`] for the provided `parquet_type`
pub fn convert_type(parquet_type: &TypePtr) -> Result<ParquetField> {
    let mut visitor = Visitor {
        next_col_idx: 0,
        mask: ProjectionMask::all(),
    };

    let context = VisitorContext {
        rep_level: 0,
        def_level: 0,
        data_type: None,
        // We might be inside list
        treat_repeated_as_list_arrow_hint: false,
    };

    Ok(visitor.dispatch(parquet_type, context)?.unwrap())
}

#[cfg(test)]
mod tests {
    use crate::arrow::schema::complex::convert_schema;
    use crate::arrow::{PARQUET_FIELD_ID_META_KEY, ProjectionMask};
    use crate::schema::parser::parse_message_type;
    use crate::schema::types::SchemaDescriptor;
    use arrow_schema::{DataType, Field, Fields};
    use std::sync::Arc;

    trait WithFieldId {
        fn with_field_id(self, id: i32) -> Self;
    }
    impl WithFieldId for arrow_schema::Field {
        fn with_field_id(self, id: i32) -> Self {
            let mut metadata = self.metadata().clone();
            metadata.insert(PARQUET_FIELD_ID_META_KEY.to_string(), id.to_string());
            self.with_metadata(metadata)
        }
    }

    fn test_roundtrip(message_type: &str) -> crate::errors::Result<()> {
        let parsed_input_schema = Arc::new(parse_message_type(message_type)?);
        let schema = SchemaDescriptor::new(parsed_input_schema);

        let converted = convert_schema(&schema, ProjectionMask::all(), None)?.unwrap();

        let DataType::Struct(schema_fields) = &converted.arrow_type else {
            panic!("Expected struct from convert_schema");
        };

        // Should be able to convert the same thing
        let converted_again =
            convert_schema(&schema, ProjectionMask::all(), Some(schema_fields))?.unwrap();

        // Assert that we changed to Utf8
        assert_eq!(converted_again.arrow_type, converted.arrow_type);

        Ok(())
    }

    fn test_expected_type(
        message_type: &str,
        expected_fields: Fields,
    ) -> crate::errors::Result<()> {
        test_roundtrip(message_type)?;

        let parsed_input_schema = Arc::new(parse_message_type(message_type)?);
        let schema = SchemaDescriptor::new(parsed_input_schema);

        let converted = convert_schema(&schema, ProjectionMask::all(), None)?.unwrap();

        let DataType::Struct(schema_fields) = &converted.arrow_type else {
            panic!("Expected struct from convert_schema");
        };

        assert_eq!(schema_fields, &expected_fields);

        Ok(())
    }

    /// Taken from the example in [Parquet Format - Nested Types - Lists - Backward-compatibility rules](https://github.com/apache/parquet-format/blob/9fd57b59e0ce1a82a69237dcf8977d3e72a2965d/LogicalTypes.md?plain=1#L766-L769)
    #[test]
    fn basic_backward_compatible_list_1() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
                optional group my_list (LIST) {
                  repeated int32 element;
                }
            }
        ",
            Fields::from(vec![
                // Rule 1: List<Integer> (nullable list, non-null elements)
                Field::new(
                    "my_list",
                    DataType::List(Arc::new(Field::new("element", DataType::Int32, false))),
                    true,
                ),
            ]),
        )
    }

    /// Taken from the example in [Parquet Format - Nested Types - Lists - Backward-compatibility rules](https://github.com/apache/parquet-format/blob/9fd57b59e0ce1a82a69237dcf8977d3e72a2965d/LogicalTypes.md?plain=1#L771-L777)
    #[test]
    fn basic_backward_compatible_list_2() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
              optional group my_list (LIST) {
                  repeated group element {
                    required binary str (STRING);
                    required int32 num;
                  }
              }
            }
        ",
            Fields::from(vec![
                // Rule 2: List<Tuple<String, Integer>> (nullable list, non-null elements)
                Field::new(
                    "my_list",
                    DataType::List(Arc::new(Field::new(
                        "element",
                        DataType::Struct(Fields::from(vec![
                            Field::new("str", DataType::Utf8, false),
                            Field::new("num", DataType::Int32, false),
                        ])),
                        false,
                    ))),
                    true,
                ),
            ]),
        )
    }

    /// Taken from the example in [Parquet Format - Nested Types - Lists - Backward-compatibility rules](https://github.com/apache/parquet-format/blob/9fd57b59e0ce1a82a69237dcf8977d3e72a2965d/LogicalTypes.md?plain=1#L779-L784)
    #[test]
    fn basic_backward_compatible_list_3() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
              optional group my_list (LIST) {
                  repeated group array (LIST) {
                    repeated int32 array;
                  }
              }
            }
        ",
            Fields::from(vec![
                // Rule 3: List<List<Integer>> (nullable outer list, non-null elements)
                Field::new(
                    "my_list",
                    DataType::List(Arc::new(Field::new(
                        "array",
                        DataType::List(Arc::new(Field::new("array", DataType::Int32, false))),
                        false,
                    ))),
                    true,
                ),
            ]),
        )
    }

    /// Taken from the example in [Parquet Format - Nested Types - Lists - Backward-compatibility rules](https://github.com/apache/parquet-format/blob/9fd57b59e0ce1a82a69237dcf8977d3e72a2965d/LogicalTypes.md?plain=1#L786-L791)
    #[test]
    fn basic_backward_compatible_list_4_1() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
              optional group my_list (LIST) {
                  repeated group array {
                    required binary str (STRING);
                  }
              }
            }
        ",
            Fields::from(vec![
                // Rule 4: List<OneTuple<String>> (nullable list, non-null elements)
                Field::new(
                    "my_list",
                    DataType::List(Arc::new(Field::new(
                        "array",
                        DataType::Struct(Fields::from(vec![Field::new(
                            "str",
                            DataType::Utf8,
                            false,
                        )])),
                        false,
                    ))),
                    true,
                ),
            ]),
        )
    }

    /// Taken from the example in [Parquet Format - Nested Types - Lists - Backward-compatibility rules](https://github.com/apache/parquet-format/blob/9fd57b59e0ce1a82a69237dcf8977d3e72a2965d/LogicalTypes.md?plain=1#L793-L798)
    #[test]
    fn basic_backward_compatible_list_4_2() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
                optional group my_list (LIST) {
                    repeated group my_list_tuple {
                        required binary str (STRING);
                    }
                }
            }
        ",
            Fields::from(vec![
                // Rule 4: List<OneTuple<String>> (nullable list, non-null elements)
                Field::new(
                    "my_list",
                    DataType::List(Arc::new(Field::new(
                        "my_list_tuple",
                        DataType::Struct(Fields::from(vec![Field::new(
                            "str",
                            DataType::Utf8,
                            false,
                        )])),
                        false,
                    ))),
                    true,
                ),
            ]),
        )
    }

    /// Taken from the example in [Parquet Format - Nested Types - Lists - Backward-compatibility rules](https://github.com/apache/parquet-format/blob/9fd57b59e0ce1a82a69237dcf8977d3e72a2965d/LogicalTypes.md?plain=1#L800-L805)
    #[test]
    fn basic_backward_compatible_list_5() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
                optional group my_list (LIST) {
                    repeated group element {
                        optional binary str (STRING);
                    }
                }
            }
        ",
            Fields::from(vec![
                // Rule 5: List<String>  (nullable list, nullable elements)
                Field::new(
                    "my_list",
                    DataType::List(Arc::new(Field::new("str", DataType::Utf8, true))),
                    true,
                ),
            ]),
        )
    }

    #[test]
    fn basic_backward_compatible_map_1() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
                optional group my_map (MAP) {
                  repeated group map {
                    required binary str (STRING);
                    required int32 num;
                  }
                }
            }
        ",
            Fields::from(vec![
                // Map<String, Integer> (nullable map, non-null values)
                Field::new(
                    "my_map",
                    DataType::Map(
                        Arc::new(Field::new(
                            "map",
                            DataType::Struct(Fields::from(vec![
                                Field::new("str", DataType::Utf8, false),
                                Field::new("num", DataType::Int32, false),
                            ])),
                            false,
                        )),
                        false,
                    ),
                    true,
                ),
            ]),
        )
    }

    #[test]
    fn basic_backward_compatible_map_2() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message schema {
                optional group my_map (MAP_KEY_VALUE) {
                  repeated group map {
                    required binary key (STRING);
                    optional int32 value;
                  }
                }
            }
        ",
            Fields::from(vec![
                // Map<String, Integer> (nullable map, nullable values)
                Field::new(
                    "my_map",
                    DataType::Map(
                        Arc::new(Field::new(
                            "map",
                            DataType::Struct(Fields::from(vec![
                                Field::new("key", DataType::Utf8, false),
                                Field::new("value", DataType::Int32, true),
                            ])),
                            false,
                        )),
                        false,
                    ),
                    true,
                ),
            ]),
        )
    }

    #[test]
    fn convert_schema_with_nested_list_repeated_primitive() -> crate::errors::Result<()> {
        test_roundtrip(
            "
            message schema {
                optional group f1 (LIST) {
                    repeated group element {
                        repeated int32 element;
                    }
                }
            }
        ",
        )
    }

    #[test]
    fn convert_schema_with_repeated_primitive_keep_field_id() -> crate::errors::Result<()> {
        let message_type = "
    message schema {
      repeated BYTE_ARRAY col_1 = 1;
    }
    ";

        let parsed_input_schema = Arc::new(parse_message_type(message_type)?);
        let schema = SchemaDescriptor::new(parsed_input_schema);

        let converted = convert_schema(&schema, ProjectionMask::all(), None)?.unwrap();

        let DataType::Struct(schema_fields) = &converted.arrow_type else {
            panic!("Expected struct from convert_schema");
        };

        assert_eq!(schema_fields.len(), 1);

        let expected_schema = DataType::Struct(Fields::from(vec![Arc::new(
            arrow_schema::Field::new(
                "col_1",
                DataType::List(Arc::new(
                    // No metadata on inner field
                    arrow_schema::Field::new("col_1", DataType::Binary, false),
                )),
                false,
            )
            // add the field id to the outer list
            .with_field_id(1),
        )]));

        assert_eq!(converted.arrow_type, expected_schema);

        Ok(())
    }

    #[test]
    fn convert_schema_with_repeated_primitive_should_use_inferred_schema()
    -> crate::errors::Result<()> {
        let message_type = "
    message schema {
      repeated BYTE_ARRAY col_1 = 1;
    }
    ";

        let parsed_input_schema = Arc::new(parse_message_type(message_type)?);
        let schema = SchemaDescriptor::new(parsed_input_schema);

        let converted = convert_schema(&schema, ProjectionMask::all(), None)?.unwrap();

        let DataType::Struct(schema_fields) = &converted.arrow_type else {
            panic!("Expected struct from convert_schema");
        };

        assert_eq!(schema_fields.len(), 1);

        let expected_schema = DataType::Struct(Fields::from(vec![Arc::new(
            arrow_schema::Field::new(
                "col_1",
                DataType::List(Arc::new(arrow_schema::Field::new(
                    "col_1",
                    DataType::Binary,
                    false,
                ))),
                false,
            )
            .with_metadata(schema_fields[0].metadata().clone()),
        )]));

        assert_eq!(converted.arrow_type, expected_schema);

        let utf8_instead_of_binary = Fields::from(vec![Arc::new(
            arrow_schema::Field::new(
                "col_1",
                DataType::List(Arc::new(arrow_schema::Field::new(
                    "col_1",
                    DataType::Utf8,
                    false,
                ))),
                false,
            )
            .with_metadata(schema_fields[0].metadata().clone()),
        )]);

        // Should be able to convert the same thing
        let converted_again = convert_schema(
            &schema,
            ProjectionMask::all(),
            Some(&utf8_instead_of_binary),
        )?
        .unwrap();

        // Assert that we changed to Utf8
        assert_eq!(
            converted_again.arrow_type,
            DataType::Struct(utf8_instead_of_binary)
        );

        Ok(())
    }

    #[test]
    fn convert_schema_with_repeated_primitive_should_use_inferred_schema_for_list_as_well()
    -> crate::errors::Result<()> {
        let message_type = "
    message schema {
      repeated BYTE_ARRAY col_1 = 1;
    }
    ";

        let parsed_input_schema = Arc::new(parse_message_type(message_type)?);
        let schema = SchemaDescriptor::new(parsed_input_schema);

        let converted = convert_schema(&schema, ProjectionMask::all(), None)?.unwrap();

        let DataType::Struct(schema_fields) = &converted.arrow_type else {
            panic!("Expected struct from convert_schema");
        };

        assert_eq!(schema_fields.len(), 1);

        let expected_schema = DataType::Struct(Fields::from(vec![Arc::new(
            arrow_schema::Field::new(
                "col_1",
                DataType::List(Arc::new(arrow_schema::Field::new(
                    "col_1",
                    DataType::Binary,
                    false,
                ))),
                false,
            )
            .with_metadata(schema_fields[0].metadata().clone()),
        )]));

        assert_eq!(converted.arrow_type, expected_schema);

        let utf8_instead_of_binary = Fields::from(vec![Arc::new(
            arrow_schema::Field::new(
                "col_1",
                // Inferring as LargeList instead of List
                DataType::LargeList(Arc::new(arrow_schema::Field::new(
                    "col_1",
                    DataType::Utf8,
                    false,
                ))),
                false,
            )
            .with_metadata(schema_fields[0].metadata().clone()),
        )]);

        // Should be able to convert the same thing
        let converted_again = convert_schema(
            &schema,
            ProjectionMask::all(),
            Some(&utf8_instead_of_binary),
        )?
        .unwrap();

        // Assert that we changed to Utf8
        assert_eq!(
            converted_again.arrow_type,
            DataType::Struct(utf8_instead_of_binary)
        );

        Ok(())
    }

    #[test]
    fn convert_schema_with_repeated_struct_and_inferred_schema() -> crate::errors::Result<()> {
        test_roundtrip(
            "
    message schema {
        repeated group my_col_1 = 1 {
          optional binary my_col_2 = 2;
          optional binary my_col_3 = 3;
          optional group my_col_4 = 4 {
            optional int64 my_col_5 = 5;
            optional int32 my_col_6 = 6;
          }
        }
    }
    ",
        )
    }

    #[test]
    fn convert_schema_with_repeated_struct_and_inferred_schema_and_field_id()
    -> crate::errors::Result<()> {
        let message_type = "
    message schema {
        repeated group my_col_1 = 1 {
          optional binary my_col_2 = 2;
          optional binary my_col_3 = 3;
          optional group my_col_4 = 4 {
            optional int64 my_col_5 = 5;
            optional int32 my_col_6 = 6;
          }
        }
    }
    ";

        let parsed_input_schema = Arc::new(parse_message_type(message_type)?);
        let schema = SchemaDescriptor::new(parsed_input_schema);

        let converted = convert_schema(&schema, ProjectionMask::all(), None)?.unwrap();

        let DataType::Struct(schema_fields) = &converted.arrow_type else {
            panic!("Expected struct from convert_schema");
        };

        assert_eq!(schema_fields.len(), 1);

        // Should be able to convert the same thing
        let converted_again =
            convert_schema(&schema, ProjectionMask::all(), Some(schema_fields))?.unwrap();

        // Assert that we changed to Utf8
        assert_eq!(converted_again.arrow_type, converted.arrow_type);

        Ok(())
    }

    #[test]
    fn convert_schema_with_nested_repeated_struct_and_primitives() -> crate::errors::Result<()> {
        let message_type = "
message schema {
    repeated group my_col_1 = 1 {
        optional binary my_col_2 = 2;
        repeated BYTE_ARRAY my_col_3 = 3;
        repeated group my_col_4 = 4 {
            optional int64 my_col_5 = 5;
            repeated binary my_col_6 = 6;
        }
    }
}
";

        let parsed_input_schema = Arc::new(parse_message_type(message_type)?);
        let schema = SchemaDescriptor::new(parsed_input_schema);

        let converted = convert_schema(&schema, ProjectionMask::all(), None)?.unwrap();

        let DataType::Struct(schema_fields) = &converted.arrow_type else {
            panic!("Expected struct from convert_schema");
        };

        assert_eq!(schema_fields.len(), 1);

        // Build expected schema
        let expected_schema = DataType::Struct(Fields::from(vec![Arc::new(
            arrow_schema::Field::new(
                "my_col_1",
                DataType::List(Arc::new(arrow_schema::Field::new(
                    "my_col_1",
                    DataType::Struct(Fields::from(vec![
                        Arc::new(
                            arrow_schema::Field::new("my_col_2", DataType::Binary, true)
                                .with_field_id(2),
                        ),
                        Arc::new(
                            arrow_schema::Field::new(
                                "my_col_3",
                                DataType::List(Arc::new(arrow_schema::Field::new(
                                    "my_col_3",
                                    DataType::Binary,
                                    false,
                                ))),
                                false,
                            )
                            // add the field id to the outer list
                            .with_field_id(3),
                        ),
                        Arc::new(
                            arrow_schema::Field::new(
                                "my_col_4",
                                DataType::List(Arc::new(arrow_schema::Field::new(
                                    "my_col_4",
                                    DataType::Struct(Fields::from(vec![
                                        Arc::new(
                                            arrow_schema::Field::new(
                                                "my_col_5",
                                                DataType::Int64,
                                                true,
                                            )
                                            // add the field id to the outer list
                                            .with_field_id(5),
                                        ),
                                        Arc::new(
                                            arrow_schema::Field::new(
                                                "my_col_6",
                                                DataType::List(Arc::new(arrow_schema::Field::new(
                                                    "my_col_6",
                                                    DataType::Binary,
                                                    false,
                                                ))),
                                                false,
                                            )
                                            // add the field id to the outer list
                                            .with_field_id(6),
                                        ),
                                    ])),
                                    false,
                                ))),
                                false,
                            )
                            // add the field id to the outer list
                            .with_field_id(4),
                        ),
                    ])),
                    false,
                ))),
                false,
            )
            // add the field id to the outer list
            .with_field_id(1),
        )]));

        assert_eq!(converted.arrow_type, expected_schema);

        // Test conversion with inferred schema
        let converted_again =
            convert_schema(&schema, ProjectionMask::all(), Some(schema_fields))?.unwrap();

        assert_eq!(converted_again.arrow_type, converted.arrow_type);

        // Test conversion with modified schema (change lists to either LargeList or FixedSizeList)
        // as well as changing Binary to Utf8 or BinaryView
        let modified_schema_fields = Fields::from(vec![Arc::new(
            arrow_schema::Field::new(
                "my_col_1",
                DataType::LargeList(Arc::new(arrow_schema::Field::new(
                    "my_col_1",
                    DataType::Struct(Fields::from(vec![
                        Arc::new(
                            arrow_schema::Field::new("my_col_2", DataType::LargeBinary, true)
                                .with_field_id(2),
                        ),
                        Arc::new(
                            arrow_schema::Field::new(
                                "my_col_3",
                                DataType::LargeList(Arc::new(arrow_schema::Field::new(
                                    "my_col_3",
                                    DataType::Utf8,
                                    false,
                                ))),
                                false,
                            )
                            // add the field id to the outer list
                            .with_field_id(3),
                        ),
                        Arc::new(
                            arrow_schema::Field::new(
                                "my_col_4",
                                DataType::FixedSizeList(
                                    Arc::new(arrow_schema::Field::new(
                                        "my_col_4",
                                        DataType::Struct(Fields::from(vec![
                                            Arc::new(
                                                arrow_schema::Field::new(
                                                    "my_col_5",
                                                    DataType::Int64,
                                                    true,
                                                )
                                                .with_field_id(5),
                                            ),
                                            Arc::new(
                                                arrow_schema::Field::new(
                                                    "my_col_6",
                                                    DataType::LargeList(Arc::new(
                                                        arrow_schema::Field::new(
                                                            "my_col_6",
                                                            DataType::BinaryView,
                                                            false,
                                                        ),
                                                    )),
                                                    false,
                                                )
                                                // add the field id to the outer list
                                                .with_field_id(6),
                                            ),
                                        ])),
                                        false,
                                    )),
                                    3,
                                ),
                                false,
                            )
                            // add the field id to the outer list
                            .with_field_id(4),
                        ),
                    ])),
                    false,
                ))),
                false,
            )
            // add the field id to the outer list
            .with_field_id(1),
        )]);

        let converted_with_modified = convert_schema(
            &schema,
            ProjectionMask::all(),
            Some(&modified_schema_fields),
        )?
        .unwrap();

        assert_eq!(
            converted_with_modified.arrow_type,
            DataType::Struct(modified_schema_fields)
        );

        Ok(())
    }

    /// Backwards-compatibility: LIST with nullable element type - 1 - standard
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L452-L466)
    #[test]
    fn list_nullable_element_standard() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated group list {
                  optional int32 element;
                }
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new("element", DataType::Int32, true))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: LIST with nullable element type - 2
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L468-L482)
    #[test]
    fn list_nullable_element_nested() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated group element {
                  optional int32 num;
                }
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new("num", DataType::Int32, true))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: LIST with non-nullable element type - 1 - standard
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L484-L495)
    #[test]
    fn list_required_element_standard() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated group list {
                  required int32 element;
                }
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new("element", DataType::Int32, false))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: LIST with non-nullable element type - 2
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L497-L508)
    #[test]
    fn list_required_element_nested() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated group element {
                  required int32 num;
                }
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new("num", DataType::Int32, false))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: LIST with non-nullable element type - 3
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L510-L519)
    #[test]
    fn list_required_element_primitive() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated int32 element;
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new("element", DataType::Int32, false))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: LIST with non-nullable element type - 4
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L521-L540)
    #[test]
    fn list_required_element_struct() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated group element {
                  required binary str (UTF8);
                  required int32 num;
                }
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new(
                    "element",
                    DataType::Struct(Fields::from(vec![
                        Field::new("str", DataType::Utf8, false),
                        Field::new("num", DataType::Int32, false),
                    ])),
                    false,
                ))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: LIST with non-nullable element type - 5 - parquet-avro style
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L542-L559)
    #[test]
    fn list_required_element_avro_style() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated group array {
                  required binary str (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new(
                    "array",
                    DataType::Struct(Fields::from(vec![Field::new("str", DataType::Utf8, false)])),
                    false,
                ))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: LIST with non-nullable element type - 6 - parquet-thrift style
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L561-L578)
    #[test]
    fn list_required_element_thrift_style() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (LIST) {
                repeated group f1_tuple {
                  required binary str (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new(
                "f1",
                DataType::List(Arc::new(Field::new(
                    "f1_tuple",
                    DataType::Struct(Fields::from(vec![Field::new("str", DataType::Utf8, false)])),
                    false,
                ))),
                true,
            )]),
        )
    }

    /// Backwards-compatibility: MAP with non-nullable value type - 1 - standard
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L652-L667)
    #[test]
    fn map_required_value_standard() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (MAP) {
                repeated group key_value {
                  required int32 key;
                  required binary value (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new_map(
                "f1",
                "key_value",
                Field::new("key", DataType::Int32, false),
                Field::new("value", DataType::Utf8, false),
                false,
                true,
            )]),
        )
    }

    /// Backwards-compatibility: MAP with non-nullable value type - 2
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L669-L684)
    #[test]
    fn map_required_value_map_key_value() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (MAP_KEY_VALUE) {
                repeated group map {
                  required int32 num;
                  required binary str (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new_map(
                "f1",
                "map",
                Field::new("num", DataType::Int32, false),
                Field::new("str", DataType::Utf8, false),
                false,
                true,
            )]),
        )
    }

    /// Backwards-compatibility: MAP with non-nullable value type - 3 - prior to 1.4.x
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L686-L701)
    #[test]
    fn map_required_value_legacy() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (MAP) {
                repeated group map (MAP_KEY_VALUE) {
                  required int32 key;
                  required binary value (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new_map(
                "f1",
                "map",
                Field::new("key", DataType::Int32, false),
                Field::new("value", DataType::Utf8, false),
                false,
                true,
            )]),
        )
    }

    /// Backwards-compatibility: MAP with nullable value type - 1 - standard
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L703-L718)
    #[test]
    fn map_optional_value_standard() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (MAP) {
                repeated group key_value {
                  required int32 key;
                  optional binary value (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new_map(
                "f1",
                "key_value",
                Field::new("key", DataType::Int32, false),
                Field::new("value", DataType::Utf8, true),
                false,
                true,
            )]),
        )
    }

    /// Backwards-compatibility: MAP with nullable value type - 2
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L720-L735)
    #[test]
    fn map_optional_value_map_key_value() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (MAP_KEY_VALUE) {
                repeated group map {
                  required int32 num;
                  optional binary str (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new_map(
                "f1",
                "map",
                Field::new("num", DataType::Int32, false),
                Field::new("str", DataType::Utf8, true),
                false,
                true,
            )]),
        )
    }

    /// Backwards-compatibility: MAP with nullable value type - 3 - parquet-avro style
    /// Taken from [Spark](https://github.com/apache/spark/blob/8ab50765cd793169091d983b50d87a391f6ac1f4/sql/core/src/test/scala/org/apache/spark/sql/parquet/ParquetSchemaSuite.scala#L737-L752)
    #[test]
    fn map_optional_value_avro_style() -> crate::errors::Result<()> {
        test_expected_type(
            "
            message root {
              optional group f1 (MAP) {
                repeated group map (MAP_KEY_VALUE) {
                  required int32 key;
                  optional binary value (UTF8);
                }
              }
            }",
            Fields::from(vec![Field::new_map(
                "f1",
                "map",
                Field::new("key", DataType::Int32, false),
                Field::new("value", DataType::Utf8, true),
                false,
                true,
            )]),
        )
    }
}