File size: 91,499 Bytes
d0faac4 | 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 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 | diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake
--- a/cpp/cmake_modules/ThirdpartyToolchain.cmake
+++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake
@@ -374,16 +374,13 @@ target_include_directories(arrow::flatbuffers
# ----------------------------------------------------------------------
# Some EP's require other EP's
-if(PARQUET_REQUIRE_ENCRYPTION)
- set(ARROW_JSON ON)
-endif()
-
if(ARROW_WITH_OPENTELEMETRY)
set(ARROW_WITH_NLOHMANN_JSON ON)
set(ARROW_WITH_PROTOBUF ON)
endif()
if(ARROW_PARQUET)
+ set(ARROW_WITH_RAPIDJSON ON)
set(ARROW_WITH_THRIFT ON)
endif()
diff --git a/cpp/src/parquet/arrow/schema.cc b/cpp/src/parquet/arrow/schema.cc
--- a/cpp/src/parquet/arrow/schema.cc
+++ b/cpp/src/parquet/arrow/schema.cc
@@ -38,6 +38,7 @@
#include "parquet/arrow/schema_internal.h"
#include "parquet/arrow/variant_internal.h"
#include "parquet/exception.h"
+#include "parquet/geospatial/util_json_internal.h"
#include "parquet/metadata.h"
#include "parquet/properties.h"
#include "parquet/types.h"
@@ -288,8 +289,8 @@ int FieldIdFromMetadata(
if (::arrow::internal::ParseValue<::arrow::Int32Type>(
field_id_str.c_str(), field_id_str.length(), &field_id)) {
if (field_id < 0) {
- // Thrift should convert any negative value to null but normalize to -1 here in case
- // we later check this in logic.
+ // Thrift should convert any negative value to null but normalize to -1 here in
+ // case we later check this in logic.
return -1;
}
return field_id;
@@ -449,9 +450,9 @@ Status FieldToNode(const std::string& name, const std::shared_ptr<Field>& field,
}
case ArrowTypeId::EXTENSION: {
auto ext_type = std::static_pointer_cast<::arrow::ExtensionType>(field->type());
- // Built-in JSON extension is handled differently.
- if (ext_type->extension_name() == std::string("arrow.json")) {
- // Set physical and logical types and instantiate primitive node.
+ // Set physical and logical types and instantiate primitive node
+ // for extension types
+ if (ext_type->extension_name() == std::string_view("arrow.json")) {
type = ParquetType::BYTE_ARRAY;
logical_type = LogicalType::JSON();
break;
@@ -460,6 +461,11 @@ Status FieldToNode(const std::string& name, const std::shared_ptr<Field>& field,
logical_type = LogicalType::UUID();
length = 16;
break;
+ } else if (ext_type->extension_name() == std::string_view("geoarrow.wkb")) {
+ type = ParquetType::BYTE_ARRAY;
+ ARROW_ASSIGN_OR_RAISE(logical_type,
+ LogicalTypeFromGeoArrowMetadata(ext_type->Serialize()));
+ break;
} else if (ext_type->extension_name() == std::string("parquet.variant")) {
auto variant_type = std::static_pointer_cast<VariantExtensionType>(field->type());
@@ -495,6 +501,7 @@ struct SchemaTreeContext {
SchemaManifest* manifest;
ArrowReaderProperties properties;
const SchemaDescriptor* schema;
+ std::shared_ptr<const KeyValueMetadata> metadata;
void LinkParent(const SchemaField* child, const SchemaField* parent) {
manifest->child_to_parent[child] = parent;
@@ -517,7 +524,7 @@ ::arrow::Result<std::shared_ptr<ArrowType>> GetTypeForNode(
int column_index, const schema::PrimitiveNode& primitive_node,
SchemaTreeContext* ctx) {
ARROW_ASSIGN_OR_RAISE(std::shared_ptr<ArrowType> storage_type,
- GetArrowType(primitive_node, ctx->properties));
+ GetArrowType(primitive_node, ctx->properties, ctx->metadata));
if (ctx->properties.read_dictionary(column_index) &&
IsDictionaryReadSupported(*storage_type)) {
return ::arrow::dictionary(::arrow::int32(), storage_type);
@@ -610,8 +617,8 @@ Status MapToSchemaField(const GroupNode& group, LevelInfo current_levels,
return Status::Invalid("Map keys must be annotated as required.");
}
// Arrow doesn't support 1 column maps (i.e. Sets). The options are to either
- // make the values column nullable, or process the map as a list. We choose the latter
- // as it is simpler.
+ // make the values column nullable, or process the map as a list. We choose the
+ // latter as it is simpler.
if (key_value.field_count() == 1) {
return ListToSchemaField(group, current_levels, ctx, parent, out);
}
@@ -1197,6 +1204,7 @@ Status SchemaManifest::Make(const SchemaDescriptor* schema,
ctx.manifest = manifest;
ctx.properties = properties;
ctx.schema = schema;
+ ctx.metadata = metadata;
const GroupNode& schema_node = *schema->group_node();
manifest->descr = schema;
manifest->schema_fields.resize(schema_node.field_count());
diff --git a/cpp/src/parquet/arrow/schema_internal.cc b/cpp/src/parquet/arrow/schema_internal.cc
--- a/cpp/src/parquet/arrow/schema_internal.cc
+++ b/cpp/src/parquet/arrow/schema_internal.cc
@@ -20,7 +20,10 @@
#include "arrow/extension/json.h"
#include "arrow/extension/uuid.h"
#include "arrow/type.h"
+#include "arrow/util/key_value_metadata.h"
+#include "arrow/util/string.h"
+#include "parquet/geospatial/util_json_internal.h"
#include "parquet/properties.h"
using ArrowType = ::arrow::DataType;
@@ -112,7 +115,8 @@ Result<std::shared_ptr<ArrowType>> MakeArrowTimestamp(const LogicalType& logical
}
Result<std::shared_ptr<ArrowType>> FromByteArray(
- const LogicalType& logical_type, const ArrowReaderProperties& reader_properties) {
+ const LogicalType& logical_type, const ArrowReaderProperties& reader_properties,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata) {
switch (logical_type.type()) {
case LogicalType::Type::STRING:
return ::arrow::utf8();
@@ -129,6 +133,18 @@ Result<std::shared_ptr<ArrowType>> FromByteArray(
// When the original Arrow schema isn't stored and Arrow extensions are disabled,
// LogicalType::JSON is read as utf8().
return ::arrow::utf8();
+ case LogicalType::Type::GEOMETRY:
+ case LogicalType::Type::GEOGRAPHY:
+ if (reader_properties.get_arrow_extensions_enabled()) {
+ // Attempt creating a GeoArrow extension type (or return binary() if types are not
+ // registered)
+ return GeoArrowTypeFromLogicalType(logical_type, metadata);
+ }
+
+ // When the original Arrow schema isn't stored, Arrow extensions are disabled, or
+ // the geoarrow.wkb extension type isn't registered, LogicalType::GEOMETRY and
+ // LogicalType::GEOGRAPHY are as binary().
+ return ::arrow::binary();
default:
return Status::NotImplemented("Unhandled logical logical_type ",
logical_type.ToString(), " for binary array");
@@ -196,7 +212,8 @@ Result<std::shared_ptr<ArrowType>> FromInt64(const LogicalType& logical_type) {
Result<std::shared_ptr<ArrowType>> GetArrowType(
Type::type physical_type, const LogicalType& logical_type, int type_length,
- const ArrowReaderProperties& reader_properties) {
+ const ArrowReaderProperties& reader_properties,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata) {
if (logical_type.is_null()) {
return ::arrow::null();
}
@@ -220,7 +237,7 @@ Result<std::shared_ptr<ArrowType>> GetArrowType(
case ParquetType::DOUBLE:
return ::arrow::float64();
case ParquetType::BYTE_ARRAY:
- return FromByteArray(logical_type, reader_properties);
+ return FromByteArray(logical_type, reader_properties, metadata);
case ParquetType::FIXED_LEN_BYTE_ARRAY:
return FromFLBA(logical_type, type_length, reader_properties);
default: {
@@ -233,9 +250,10 @@ Result<std::shared_ptr<ArrowType>> GetArrowType(
Result<std::shared_ptr<ArrowType>> GetArrowType(
const schema::PrimitiveNode& primitive,
- const ArrowReaderProperties& reader_properties) {
+ const ArrowReaderProperties& reader_properties,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata) {
return GetArrowType(primitive.physical_type(), *primitive.logical_type(),
- primitive.type_length(), reader_properties);
+ primitive.type_length(), reader_properties, metadata);
}
} // namespace parquet::arrow
diff --git a/cpp/src/parquet/arrow/schema_internal.h b/cpp/src/parquet/arrow/schema_internal.h
--- a/cpp/src/parquet/arrow/schema_internal.h
+++ b/cpp/src/parquet/arrow/schema_internal.h
@@ -29,19 +29,22 @@ namespace parquet::arrow {
using ::arrow::Result;
-Result<std::shared_ptr<::arrow::DataType>> FromByteArray(const LogicalType& logical_type,
- bool use_known_arrow_extensions);
+Result<std::shared_ptr<::arrow::DataType>> FromByteArray(
+ const LogicalType& logical_type, bool use_known_arrow_extensions,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata = nullptr);
Result<std::shared_ptr<::arrow::DataType>> FromFLBA(const LogicalType& logical_type,
int32_t physical_length);
Result<std::shared_ptr<::arrow::DataType>> FromInt32(const LogicalType& logical_type);
Result<std::shared_ptr<::arrow::DataType>> FromInt64(const LogicalType& logical_type);
Result<std::shared_ptr<::arrow::DataType>> GetArrowType(
Type::type physical_type, const LogicalType& logical_type, int type_length,
- const ArrowReaderProperties& reader_properties);
+ const ArrowReaderProperties& reader_properties,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata = nullptr);
Result<std::shared_ptr<::arrow::DataType>> GetArrowType(
const schema::PrimitiveNode& primitive,
- const ArrowReaderProperties& reader_properties);
+ const ArrowReaderProperties& reader_properties,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata = nullptr);
} // namespace parquet::arrow
diff --git a/cpp/src/parquet/column_writer.cc b/cpp/src/parquet/column_writer.cc
--- a/cpp/src/parquet/column_writer.cc
+++ b/cpp/src/parquet/column_writer.cc
@@ -788,6 +788,9 @@ class ColumnWriterImpl {
// Plain-encoded statistics of the whole chunk
virtual StatisticsPair GetChunkStatistics() = 0;
+ // Geospatial statistics of the whole chunk
+ virtual std::optional<geospatial::EncodedGeoStatistics> GetChunkGeoStatistics() = 0;
+
// Merges page statistics into chunk statistics, then resets the values
virtual void ResetPageStatistics() = 0;
@@ -1104,9 +1107,18 @@ int64_t ColumnWriterImpl::Close() {
if (rows_written_ > 0 && chunk_statistics.is_set()) {
metadata_->SetStatistics(chunk_statistics);
}
+
if (rows_written_ > 0 && chunk_size_statistics.is_set()) {
metadata_->SetSizeStatistics(chunk_size_statistics);
}
+
+ if (descr_->logical_type() != nullptr && descr_->logical_type()->is_geometry()) {
+ std::optional<geospatial::EncodedGeoStatistics> geo_stats = GetChunkGeoStatistics();
+ if (geo_stats) {
+ metadata_->SetGeoStatistics(std::move(*geo_stats));
+ }
+ }
+
metadata_->SetKeyValueMetadata(key_value_metadata_);
pager_->Close(has_dictionary_, fallback_);
}
@@ -1230,11 +1242,19 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
current_dict_encoder_ =
dynamic_cast<DictEncoder<ParquetType>*>(current_encoder_.get());
- if (properties->statistics_enabled(descr_->path()) &&
- (SortOrder::UNKNOWN != descr_->sort_order())) {
- page_statistics_ = MakeStatistics<ParquetType>(descr_, allocator_);
- chunk_statistics_ = MakeStatistics<ParquetType>(descr_, allocator_);
+ // GH-46205: Geometry/Geography are the first non-nested logical types to have a
+ // SortOrder::UNKNOWN. Currently, the presence of statistics is tied to
+ // having a known sort order and so null counts will be missing.
+ if (properties->statistics_enabled(descr_->path())) {
+ if (SortOrder::UNKNOWN != descr_->sort_order()) {
+ page_statistics_ = MakeStatistics<ParquetType>(descr_, allocator_);
+ chunk_statistics_ = MakeStatistics<ParquetType>(descr_, allocator_);
+ }
+ if (descr_->logical_type() != nullptr && descr_->logical_type()->is_geometry()) {
+ chunk_geospatial_statistics_ = std::make_shared<geospatial::GeoStatistics>();
+ }
}
+
if (properties->size_statistics_level() == SizeStatisticsLevel::ColumnChunk ||
properties->size_statistics_level() == SizeStatisticsLevel::PageAndColumnChunk) {
page_size_statistics_ = SizeStatistics::Make(descr_);
@@ -1430,6 +1450,14 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
return result;
}
+ std::optional<geospatial::EncodedGeoStatistics> GetChunkGeoStatistics() override {
+ if (chunk_geospatial_statistics_) {
+ return chunk_geospatial_statistics_->Encode();
+ } else {
+ return std::nullopt;
+ }
+ }
+
void ResetPageStatistics() override {
if (chunk_statistics_ != nullptr) {
chunk_statistics_->Merge(*page_statistics_);
@@ -1494,6 +1522,7 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
std::shared_ptr<TypedStats> chunk_statistics_;
std::unique_ptr<SizeStatistics> page_size_statistics_;
std::shared_ptr<SizeStatistics> chunk_size_statistics_;
+ std::shared_ptr<geospatial::GeoStatistics> chunk_geospatial_statistics_;
bool pages_change_on_record_boundaries_;
// If writing a sequence of ::arrow::DictionaryArray to the writer, we keep the
@@ -1719,7 +1748,14 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
if (page_statistics_ != nullptr) {
page_statistics_->Update(values, num_values, num_nulls);
}
+
UpdateUnencodedDataBytes();
+
+ if constexpr (std::is_same<T, ByteArray>::value) {
+ if (chunk_geospatial_statistics_ != nullptr) {
+ chunk_geospatial_statistics_->Update(values, num_values);
+ }
+ }
}
/// \brief Write values with spaces and update page statistics accordingly.
@@ -1748,7 +1784,15 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
page_statistics_->UpdateSpaced(values, valid_bits, valid_bits_offset,
num_spaced_values, num_values, num_nulls);
}
+
UpdateUnencodedDataBytes();
+
+ if constexpr (std::is_same<T, ByteArray>::value) {
+ if (chunk_geospatial_statistics_ != nullptr) {
+ chunk_geospatial_statistics_->UpdateSpaced(values, valid_bits, valid_bits_offset,
+ num_spaced_values, num_values);
+ }
+ }
}
};
@@ -1826,6 +1870,12 @@ Status TypedColumnWriterImpl<ParquetType>::WriteArrowDictionary(
page_statistics_->IncrementNullCount(num_chunk_levels - non_null_count);
page_statistics_->IncrementNumValues(non_null_count);
page_statistics_->Update(*referenced_dictionary, /*update_counts=*/false);
+
+ if (chunk_geospatial_statistics_ != nullptr) {
+ throw ParquetException(
+ "Writing dictionary-encoded GEOMETRY or GEOGRAPHY with statistics is not "
+ "supported");
+ }
};
int64_t value_offset = 0;
@@ -2305,7 +2355,12 @@ Status TypedColumnWriterImpl<ByteArrayType>::WriteArrowDense(
page_statistics_->IncrementNullCount(batch_size - non_null);
page_statistics_->IncrementNumValues(non_null);
}
+
UpdateUnencodedDataBytes();
+
+ if (chunk_geospatial_statistics_ != nullptr) {
+ chunk_geospatial_statistics_->Update(*data_slice);
+ }
CommitWriteAndCheckPageLimit(batch_size, batch_num_values, batch_size - non_null,
check_page);
CheckDictionarySizeLimit();
diff --git a/cpp/src/parquet/geospatial/CMakeLists.txt b/cpp/src/parquet/geospatial/CMakeLists.txt
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/CMakeLists.txt
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+arrow_install_all_headers("parquet/geospatial")
diff --git a/cpp/src/parquet/geospatial/statistics.cc b/cpp/src/parquet/geospatial/statistics.cc
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/statistics.cc
@@ -0,0 +1,393 @@
+// 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.
+
+#include "parquet/geospatial/statistics.h"
+
+#include <cmath>
+#include <memory>
+#include <optional>
+
+#include "arrow/array.h"
+#include "arrow/type.h"
+#include "arrow/util/bit_run_reader.h"
+#include "parquet/exception.h"
+#include "parquet/geospatial/util_internal.h"
+
+using arrow::util::SafeLoad;
+
+namespace parquet::geospatial {
+
+class GeoStatisticsImpl {
+ public:
+ bool Equals(const GeoStatisticsImpl& other) const {
+ return is_valid_ == other.is_valid_ &&
+ bounder_.GeometryTypes() == other.bounder_.GeometryTypes() &&
+ bounder_.Bounds() == other.bounder_.Bounds();
+ }
+
+ void Merge(const GeoStatisticsImpl& other) {
+ is_valid_ = is_valid_ && other.is_valid_;
+ if (!is_valid_) {
+ return;
+ }
+
+ // We don't yet support updating wraparound bounds. Rather than throw,
+ // we just mark the X bounds as invalid such that they are not used.
+ auto other_bounds = other.bounder_.Bounds();
+ if (is_wraparound_x() || other.is_wraparound_x()) {
+ other_bounds.min[0] = kNaN;
+ other_bounds.max[0] = kNaN;
+ }
+
+ bounder_.MergeBox(other_bounds);
+ std::vector<int32_t> other_geometry_types = other.bounder_.GeometryTypes();
+ bounder_.MergeGeometryTypes(other_geometry_types);
+ }
+
+ void Update(const ByteArray* values, int64_t num_values) {
+ if (!is_valid_) {
+ return;
+ }
+
+ if (is_wraparound_x()) {
+ throw ParquetException("Wraparound X is not suppored by GeoStatistics::Update()");
+ }
+
+ for (int64_t i = 0; i < num_values; i++) {
+ const ByteArray& item = values[i];
+ try {
+ bounder_.MergeGeometry({reinterpret_cast<const char*>(item.ptr), item.len});
+ } catch (ParquetException&) {
+ is_valid_ = false;
+ return;
+ }
+ }
+ }
+
+ void UpdateSpaced(const ByteArray* values, const uint8_t* valid_bits,
+ int64_t valid_bits_offset, int64_t num_spaced_values,
+ int64_t num_values) {
+ DCHECK_GT(num_spaced_values, 0);
+
+ if (!is_valid_) {
+ return;
+ }
+
+ if (is_wraparound_x()) {
+ throw ParquetException("Wraparound X is not suppored by GeoStatistics::Update()");
+ }
+
+ ::arrow::Status status = ::arrow::internal::VisitSetBitRuns(
+ valid_bits, valid_bits_offset, num_spaced_values,
+ [&](int64_t position, int64_t length) {
+ for (int64_t i = 0; i < length; i++) {
+ ByteArray item = SafeLoad(values + i + position);
+ PARQUET_CATCH_NOT_OK(bounder_.MergeGeometry(
+ {reinterpret_cast<const char*>(item.ptr), item.len}));
+ }
+
+ return ::arrow::Status::OK();
+ });
+
+ if (!status.ok()) {
+ is_valid_ = false;
+ }
+ }
+
+ void Update(const ::arrow::Array& values) {
+ if (!is_valid_) {
+ return;
+ }
+
+ if (is_wraparound_x()) {
+ throw ParquetException("Wraparound X is not suppored by GeoStatistics::Update()");
+ }
+
+ // Note that ::arrow::Type::EXTENSION seems to be handled before this is called
+ switch (values.type_id()) {
+ case ::arrow::Type::BINARY:
+ UpdateArrayImpl<::arrow::BinaryArray>(values);
+ break;
+ case ::arrow::Type::LARGE_BINARY:
+ UpdateArrayImpl<::arrow::LargeBinaryArray>(values);
+ break;
+ // This does not currently handle run-end encoded, dictionary encodings, or views
+ default:
+ throw ParquetException("Unsupported Array type in GeoStatistics::Update(Array): ",
+ values.type()->ToString());
+ }
+ }
+
+ void Reset() {
+ bounder_.Reset();
+ is_valid_ = true;
+ has_geometry_types_ = true;
+ }
+
+ EncodedGeoStatistics Encode() const {
+ if (!is_valid_) {
+ return {};
+ }
+
+ const geospatial::BoundingBox::XYZM& mins = bounder_.Bounds().min;
+ const geospatial::BoundingBox::XYZM& maxes = bounder_.Bounds().max;
+
+ EncodedGeoStatistics out;
+
+ if (has_geometry_types_) {
+ out.geospatial_types = bounder_.GeometryTypes();
+ }
+
+ bool write_x = !bound_empty(0) && bound_valid(0);
+ bool write_y = !bound_empty(1) && bound_valid(1);
+ bool write_z = write_x && write_y && !bound_empty(2) && bound_valid(2);
+ bool write_m = write_x && write_y && !bound_empty(3) && bound_valid(3);
+
+ if (write_x && write_y) {
+ out.xmin = mins[0];
+ out.xmax = maxes[0];
+ out.ymin = mins[1];
+ out.ymax = maxes[1];
+ out.xy_bounds_present = true;
+ }
+
+ if (write_z) {
+ out.zmin = mins[2];
+ out.zmax = maxes[2];
+ out.z_bounds_present = true;
+ }
+
+ if (write_m) {
+ out.mmin = mins[3];
+ out.mmax = maxes[3];
+ out.m_bounds_present = true;
+ }
+
+ return out;
+ }
+
+ void Decode(const EncodedGeoStatistics& encoded) {
+ Reset();
+
+ geospatial::BoundingBox box;
+ if (encoded.xy_bounds_present) {
+ box.min[0] = encoded.xmin;
+ box.max[0] = encoded.xmax;
+ box.min[1] = encoded.ymin;
+ box.max[1] = encoded.ymax;
+ } else {
+ box.min[0] = kNaN;
+ box.max[0] = kNaN;
+ box.min[1] = kNaN;
+ box.max[1] = kNaN;
+ }
+
+ if (encoded.z_bounds_present) {
+ box.min[2] = encoded.zmin;
+ box.max[2] = encoded.zmax;
+ } else {
+ box.min[2] = kNaN;
+ box.max[2] = kNaN;
+ }
+
+ if (encoded.m_bounds_present) {
+ box.min[3] = encoded.mmin;
+ box.max[3] = encoded.mmax;
+ } else {
+ box.min[3] = kNaN;
+ box.max[3] = kNaN;
+ }
+
+ bounder_.MergeBox(box);
+ bounder_.MergeGeometryTypes(encoded.geospatial_types);
+ has_geometry_types_ = has_geometry_types_ && encoded.geospatial_types_present();
+ }
+
+ bool is_wraparound_x() const {
+ return is_wraparound(lower_bound()[0], upper_bound()[0]);
+ }
+
+ bool is_valid() const { return is_valid_; }
+
+ bool bounds_empty() const {
+ for (int i = 0; i < kMaxDimensions; i++) {
+ if (!bound_empty(i)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ bool bound_empty(int i) const {
+ return std::isinf(bounder_.Bounds().min[i] - bounder_.Bounds().max[i]);
+ }
+
+ bool bound_valid(int i) const {
+ return !std::isnan(bounder_.Bounds().min[i]) && !std::isnan(bounder_.Bounds().max[i]);
+ }
+
+ const std::array<double, kMaxDimensions>& lower_bound() const {
+ return bounder_.Bounds().min;
+ }
+
+ const std::array<double, kMaxDimensions>& upper_bound() const {
+ return bounder_.Bounds().max;
+ }
+
+ std::optional<std::vector<int32_t>> geometry_types() const {
+ if (has_geometry_types_) {
+ return bounder_.GeometryTypes();
+ } else {
+ return std::nullopt;
+ }
+ }
+
+ private:
+ geospatial::WKBGeometryBounder bounder_;
+ bool is_valid_ = true;
+ bool has_geometry_types_ = true;
+
+ template <typename ArrayType>
+ void UpdateArrayImpl(const ::arrow::Array& values) {
+ const auto& binary_array = static_cast<const ArrayType&>(values);
+ for (int64_t i = 0; i < binary_array.length(); ++i) {
+ if (!binary_array.IsNull(i)) {
+ try {
+ bounder_.MergeGeometry(binary_array.GetView(i));
+ } catch (ParquetException&) {
+ is_valid_ = false;
+ return;
+ }
+ }
+ }
+ }
+
+ // The Parquet specification allows X bounds to be "wraparound" to allow for
+ // more compact bounding boxes when a geometry happens to include components
+ // on both sides of the antimeridian (e.g., the nation of Fiji). This function
+ // checks for that case (see GeoStatistics::lower_bound/upper_bound for more
+ // details).
+ static bool is_wraparound(double xmin, double xmax) {
+ return !std::isinf(xmin - xmax) && xmin > xmax;
+ }
+};
+
+GeoStatistics::GeoStatistics() : impl_(std::make_unique<GeoStatisticsImpl>()) {}
+
+GeoStatistics::GeoStatistics(const EncodedGeoStatistics& encoded) : GeoStatistics() {
+ Decode(encoded);
+}
+
+GeoStatistics::~GeoStatistics() = default;
+
+bool GeoStatistics::Equals(const GeoStatistics& other) const {
+ return impl_->Equals(*other.impl_);
+}
+
+void GeoStatistics::Merge(const GeoStatistics& other) { impl_->Merge(*other.impl_); }
+
+void GeoStatistics::Update(const ByteArray* values, int64_t num_values) {
+ impl_->Update(values, num_values);
+}
+
+void GeoStatistics::UpdateSpaced(const ByteArray* values, const uint8_t* valid_bits,
+ int64_t valid_bits_offset, int64_t num_spaced_values,
+ int64_t num_values) {
+ impl_->UpdateSpaced(values, valid_bits, valid_bits_offset, num_spaced_values,
+ num_values);
+}
+
+void GeoStatistics::Update(const ::arrow::Array& values) { impl_->Update(values); }
+
+void GeoStatistics::Reset() { impl_->Reset(); }
+
+bool GeoStatistics::is_valid() const { return impl_->is_valid(); }
+
+std::optional<EncodedGeoStatistics> GeoStatistics::Encode() const {
+ if (is_valid()) {
+ return impl_->Encode();
+ } else {
+ return std::nullopt;
+ }
+}
+
+void GeoStatistics::Decode(const EncodedGeoStatistics& encoded) {
+ impl_->Decode(encoded);
+}
+
+std::array<double, 4> GeoStatistics::lower_bound() const { return impl_->lower_bound(); }
+
+std::array<double, 4> GeoStatistics::upper_bound() const { return impl_->upper_bound(); }
+
+std::array<bool, 4> GeoStatistics::dimension_empty() const {
+ return {impl_->bound_empty(0), impl_->bound_empty(1), impl_->bound_empty(2),
+ impl_->bound_empty(3)};
+}
+
+std::array<bool, 4> GeoStatistics::dimension_valid() const {
+ return {impl_->bound_valid(0), impl_->bound_valid(1), impl_->bound_valid(2),
+ impl_->bound_valid(3)};
+}
+
+std::optional<std::vector<int32_t>> GeoStatistics::geometry_types() const {
+ return impl_->geometry_types();
+}
+
+std::string GeoStatistics::ToString() const {
+ if (!is_valid()) {
+ return "<GeoStatistics> invalid";
+ }
+
+ std::stringstream ss;
+ ss << "<GeoStatistics>";
+
+ std::string dim_label("xyzm");
+ auto dim_valid = dimension_valid();
+ auto dim_empty = dimension_empty();
+ auto lower = lower_bound();
+ auto upper = upper_bound();
+
+ for (int i = 0; i < kMaxDimensions; i++) {
+ ss << " " << dim_label[i] << ": ";
+ if (!dim_valid[i]) {
+ ss << "invalid";
+ } else if (dim_empty[i]) {
+ ss << "empty";
+ } else {
+ ss << "[" << lower[i] << ", " << upper[i] << "]";
+ }
+ }
+
+ std::optional<std::vector<int32_t>> maybe_geometry_types = geometry_types();
+ ss << " geometry_types: ";
+ if (maybe_geometry_types.has_value()) {
+ ss << "[";
+ std::string sep("");
+ for (int32_t geometry_type : *maybe_geometry_types) {
+ ss << sep << geometry_type;
+ sep = ", ";
+ }
+ ss << "]";
+ } else {
+ ss << "invalid";
+ }
+
+ return ss.str();
+}
+
+} // namespace parquet::geospatial
diff --git a/cpp/src/parquet/geospatial/statistics.h b/cpp/src/parquet/geospatial/statistics.h
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/statistics.h
@@ -0,0 +1,194 @@
+// 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.
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+#include <optional>
+
+#include "parquet/platform.h"
+#include "parquet/types.h"
+
+namespace parquet::geospatial {
+
+/// \brief The maximum number of dimensions represented by a geospatial type
+/// (i.e., X, Y, Z, and M)
+inline constexpr int kMaxDimensions = 4;
+
+/// \brief NaN, used to represent bounds for which predicate pushdown cannnot
+/// be applied (e.g., because a writer did not provide bounds for a given dimension)
+inline constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
+
+/// \brief Structure represented encoded statistics to be written to and read from Parquet
+/// serialized metadata.
+///
+/// See the Parquet Thrift definition and GeoStatistics for the specific definition
+/// of field values.
+struct PARQUET_EXPORT EncodedGeoStatistics {
+ bool xy_bounds_present{false};
+ double xmin{kNaN};
+ double xmax{kNaN};
+ double ymin{kNaN};
+ double ymax{kNaN};
+
+ bool z_bounds_present{false};
+ double zmin{kNaN};
+ double zmax{kNaN};
+
+ bool m_bounds_present{false};
+ double mmin{kNaN};
+ double mmax{kNaN};
+
+ bool geospatial_types_present() const { return !geospatial_types.empty(); }
+ std::vector<int32_t> geospatial_types;
+};
+
+class GeoStatisticsImpl;
+
+/// \brief Base type for computing geospatial column statistics while writing a file
+/// or representing them when reading a file
+///
+/// Note that NaN values that were encountered within coordinates are omitted; however,
+/// NaN values that were obtained via decoding encoded statistics are propagated. This
+/// behaviour ensures C++ clients that are inspecting statistics via the column metadata
+/// can detect the case where a writer generated NaNs (even though this implementation
+/// does not generate them).
+///
+/// The handling of NaN values in coordinates is not well-defined among bounding
+/// implementations except for the WKB convention for POINT EMPTY, which is consistently
+/// represented as a point whose ordinates are all NaN. Any other geometry that contains
+/// NaNs cannot expect defined behaviour here or elsewhere; however, a row group that
+/// contains both NaN-containing and normal (completely finite) geometries should not be
+/// excluded from predicate pushdown.
+///
+/// EXPERIMENTAL
+class PARQUET_EXPORT GeoStatistics {
+ public:
+ GeoStatistics();
+ explicit GeoStatistics(const EncodedGeoStatistics& encoded);
+
+ ~GeoStatistics();
+
+ /// \brief Return true if bounds, geometry types, and validity are identical
+ bool Equals(const GeoStatistics& other) const;
+
+ /// \brief Update these statistics based on previously calculated or decoded statistics
+ ///
+ /// Merging statistics with wraparound X values is not currently supported. Merging
+ /// two GeoStatistics where one or both has a wraparound X range will result in these
+ /// statistics having an X dimension marked as invalid.
+ void Merge(const GeoStatistics& other);
+
+ /// \brief Update these statistics based on values
+ void Update(const ByteArray* values, int64_t num_values);
+
+ /// \brief Update these statistics based on the non-null elements of values
+ void UpdateSpaced(const ByteArray* values, const uint8_t* valid_bits,
+ int64_t valid_bits_offset, int64_t num_spaced_values,
+ int64_t num_values);
+
+ /// \brief Update these statistics based on the non-null elements of values
+ ///
+ /// Currently, BinaryArray and LargeBinaryArray input is supported.
+ void Update(const ::arrow::Array& values);
+
+ /// \brief Return these statistics to an empty state
+ void Reset();
+
+ /// \brief Encode the statistics for serializing to Thrift
+ ///
+ /// If invalid WKB was encountered or if the statistics contain NaN
+ /// for any reason, Encode() will return nullopt to indicate that
+ /// statistics should not be written to thrift.
+ std::optional<EncodedGeoStatistics> Encode() const;
+
+ /// \brief Returns false if invalid WKB was encountered
+ bool is_valid() const;
+
+ /// \brief Reset existing statistics and populate them from previously-encoded ones
+ void Decode(const EncodedGeoStatistics& encoded);
+
+ /// \brief Minimum values in XYZM order
+ ///
+ /// For dimensions where dimension_valid() is false, the value will be NaN. For
+ /// dimensions where dimension_empty() is true, the value will be +Inf.
+ ///
+ /// For the first dimension (X) only, wraparound bounds apply where xmin > xmax. In this
+ /// case, these bounds represent the union of the intervals [xmax, Inf] and [-Inf,
+ /// xmin]. This implementation does not yet generate these types of bounds but they may
+ /// be encountered in statistics when reading a Parquet file.
+ std::array<double, kMaxDimensions> lower_bound() const;
+
+ /// \brief Maximum values in XYZM order
+ ///
+ /// For dimensions where dimension_valid() is false, the value will be NaN. For
+ /// dimensions where dimension_empty() is true, the value will be -Inf.
+ ///
+ /// For the first dimension (X) only, wraparound bounds apply where xmin > xmax. In this
+ /// case, these bounds represent the union of the intervals [xmax, Inf] and [-Inf,
+ /// xmin]. This implementation does not yet generate these types of bounds but they may
+ /// be encountered in statistics when reading a Parquet file.
+ std::array<double, kMaxDimensions> upper_bound() const;
+
+ /// \brief Dimension emptiness in XYZM order
+ ///
+ /// True for a given dimension if and only if zero non-NaN values were encountered
+ /// in that dimension and dimension_valid() is true for that dimension.
+ ///
+ /// When calculating statistics, zero or more of these values may be true because
+ /// this implementation calculates bounds for all dimensions; however, it may be
+ /// true that zero coordinates were encountered in a given dimension. For example,
+ /// dimension_empty() will return four true values if Update() was not called
+ /// or if Update() was called with only null values. If Update() was provided
+ /// one or more geometries with X and Y dimensions but not Z or M dimensions,
+ /// dimension_empty() will return true, true, false, false.
+ ///
+ /// For statistics read from a Parquet file, dimension_empty() will always contain
+ /// false values because there is no mechanism to communicate an empty interval
+ /// in the Thrift metadata.
+ std::array<bool, kMaxDimensions> dimension_empty() const;
+
+ /// \brief Dimension validity (i.e. presence) in XYZM order
+ ///
+ /// When calculating statistics, this will always be true because this implementation
+ /// calculates statistics for all dimensions. When reading a Parquet file, one or more
+ /// of these values may be false because the file may not have provided bounds for all
+ /// dimensions.
+ ///
+ /// See documentation for dimension_empty(), lower_bound(), and/or upper_bound() for the
+ /// canonical values of those outputs for the dimensions where dimension_valid() is
+ /// false.
+ std::array<bool, kMaxDimensions> dimension_valid() const;
+
+ /// \brief Return the geometry type codes
+ ///
+ /// This implementation always returns sorted output with no duplicates. When
+ /// calculating statistics, a value will always be returned (although the returned
+ /// vector may be empty if Update() was never called or was only called with null
+ /// values). When reading a Parquet file, std::nullopt may be returned because
+ /// the file may not have provided this information.
+ std::optional<std::vector<int32_t>> geometry_types() const;
+
+ /// \brief Return a string representation of these statistics
+ std::string ToString() const;
+
+ private:
+ std::unique_ptr<GeoStatisticsImpl> impl_;
+};
+
+} // namespace parquet::geospatial
diff --git a/cpp/src/parquet/geospatial/util_internal.cc b/cpp/src/parquet/geospatial/util_internal.cc
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/util_internal.cc
@@ -0,0 +1,242 @@
+// 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.
+
+#include "parquet/geospatial/util_internal.h"
+
+#include <sstream>
+
+#include "arrow/util/endian.h"
+#include "arrow/util/macros.h"
+#include "arrow/util/ubsan.h"
+#include "parquet/exception.h"
+
+namespace parquet::geospatial {
+
+std::string BoundingBox::ToString() const {
+ std::stringstream ss;
+ ss << "BoundingBox" << std::endl;
+ ss << " x: [" << min[0] << ", " << max[0] << "]" << std::endl;
+ ss << " y: [" << min[1] << ", " << max[1] << "]" << std::endl;
+ ss << " z: [" << min[2] << ", " << max[2] << "]" << std::endl;
+ ss << " m: [" << min[3] << ", " << max[3] << "]" << std::endl;
+
+ return ss.str();
+}
+
+/// \brief Object to keep track of the low-level consumption of a well-known binary
+/// geometry
+///
+/// Briefly, ISO well-known binary supported by the Parquet spec is an endian byte
+/// (0x01 or 0x00), followed by geometry type + dimensions encoded as a (uint32_t),
+/// followed by geometry-specific data. Coordinate sequences are represented by a
+/// uint32_t (the number of coordinates) plus a sequence of doubles (number of coordinates
+/// multiplied by the number of dimensions).
+class WKBBuffer {
+ public:
+ WKBBuffer() : data_(nullptr), size_(0) {}
+ WKBBuffer(const uint8_t* data, int64_t size) : data_(data), size_(size) {}
+
+ uint8_t ReadUInt8() { return ReadChecked<uint8_t>(); }
+
+ uint32_t ReadUInt32(bool swap) {
+ auto value = ReadChecked<uint32_t>();
+ if (swap) {
+ return ::arrow::bit_util::ByteSwap(value);
+ } else {
+ return value;
+ }
+ }
+
+ template <typename Coord, typename Visit>
+ void ReadCoords(uint32_t n_coords, bool swap, Visit&& visit) {
+ size_t total_bytes = n_coords * sizeof(Coord);
+ if (size_ < total_bytes) {
+ throw ParquetException("Can't read coordinate sequence of ", total_bytes,
+ " bytes from WKBBuffer with ", size_, " remaining");
+ }
+
+ if (swap) {
+ Coord coord;
+ for (uint32_t i = 0; i < n_coords; i++) {
+ coord = ReadUnchecked<Coord>();
+ for (auto& c : coord) {
+ c = ::arrow::bit_util::ByteSwap(c);
+ }
+
+ visit(coord);
+ }
+ } else {
+ for (uint32_t i = 0; i < n_coords; i++) {
+ visit(ReadUnchecked<Coord>());
+ }
+ }
+ }
+
+ size_t size() { return size_; }
+
+ private:
+ const uint8_t* data_;
+ size_t size_;
+
+ template <typename T>
+ T ReadChecked() {
+ if (ARROW_PREDICT_FALSE(size_ < sizeof(T))) {
+ throw ParquetException("Can't read ", sizeof(T), " bytes from WKBBuffer with ",
+ size_, " remaining");
+ }
+
+ return ReadUnchecked<T>();
+ }
+
+ template <typename T>
+ T ReadUnchecked() {
+ T out = ::arrow::util::SafeLoadAs<T>(data_);
+ data_ += sizeof(T);
+ size_ -= sizeof(T);
+ return out;
+ }
+};
+
+using GeometryTypeAndDimensions = std::pair<GeometryType, Dimensions>;
+
+namespace {
+
+GeometryTypeAndDimensions ParseGeometryType(uint32_t wkb_geometry_type) {
+ // The number 1000 can be used because WKB geometry types are constructed
+ // on purpose such that this relationship is true (e.g., LINESTRING ZM maps
+ // to 3002).
+ uint32_t geometry_type_component = wkb_geometry_type % 1000;
+ uint32_t dimensions_component = wkb_geometry_type / 1000;
+
+ auto min_geometry_type_value = static_cast<uint32_t>(GeometryType::kValueMin);
+ auto max_geometry_type_value = static_cast<uint32_t>(GeometryType::kValueMax);
+ auto min_dimension_value = static_cast<uint32_t>(Dimensions::kValueMin);
+ auto max_dimension_value = static_cast<uint32_t>(Dimensions::kValueMax);
+
+ if (geometry_type_component < min_geometry_type_value ||
+ geometry_type_component > max_geometry_type_value ||
+ dimensions_component < min_dimension_value ||
+ dimensions_component > max_dimension_value) {
+ throw ParquetException("Invalid WKB geometry type: ", wkb_geometry_type);
+ }
+
+ return {static_cast<GeometryType>(geometry_type_component),
+ static_cast<Dimensions>(dimensions_component)};
+}
+
+} // namespace
+
+std::vector<int32_t> WKBGeometryBounder::GeometryTypes() const {
+ std::vector<int32_t> out(geospatial_types_.begin(), geospatial_types_.end());
+ std::sort(out.begin(), out.end());
+ return out;
+}
+
+void WKBGeometryBounder::MergeGeometry(std::string_view bytes_wkb) {
+ MergeGeometry(::arrow::util::span(reinterpret_cast<const uint8_t*>(bytes_wkb.data()),
+ bytes_wkb.size()));
+}
+
+void WKBGeometryBounder::MergeGeometry(::arrow::util::span<const uint8_t> bytes_wkb) {
+ WKBBuffer src{bytes_wkb.data(), static_cast<int64_t>(bytes_wkb.size())};
+ MergeGeometryInternal(&src, /*record_wkb_type=*/true);
+ if (src.size() != 0) {
+ throw ParquetException("Exepcted zero bytes after consuming WKB but got ",
+ src.size());
+ }
+}
+
+void WKBGeometryBounder::MergeGeometryInternal(WKBBuffer* src, bool record_wkb_type) {
+ uint8_t endian = src->ReadUInt8();
+#if defined(ARROW_LITTLE_ENDIAN)
+ bool swap = endian != 0x01;
+#else
+ bool swap = endian != 0x00;
+#endif
+
+ uint32_t wkb_geometry_type = src->ReadUInt32(swap);
+ auto geometry_type_and_dimensions = ParseGeometryType(wkb_geometry_type);
+ auto [geometry_type, dimensions] = geometry_type_and_dimensions;
+
+ // Keep track of geometry types encountered if at the top level
+ if (record_wkb_type) {
+ geospatial_types_.insert(static_cast<int32_t>(wkb_geometry_type));
+ }
+
+ switch (geometry_type) {
+ case GeometryType::kPoint:
+ MergeSequence(src, dimensions, 1, swap);
+ break;
+
+ case GeometryType::kLinestring: {
+ uint32_t n_coords = src->ReadUInt32(swap);
+ MergeSequence(src, dimensions, n_coords, swap);
+ break;
+ }
+ case GeometryType::kPolygon: {
+ uint32_t n_parts = src->ReadUInt32(swap);
+ for (uint32_t i = 0; i < n_parts; i++) {
+ uint32_t n_coords = src->ReadUInt32(swap);
+ MergeSequence(src, dimensions, n_coords, swap);
+ }
+ break;
+ }
+
+ // These are all encoded the same in WKB, even though this encoding would
+ // allow for parts to be of a different geometry type or different dimensions.
+ // For the purposes of bounding, this does not cause us problems. We pass
+ // record_wkb_type = false because we do not want the child geometry to be
+ // added to the geometry_types list (e.g., for a MultiPoint, we only want
+ // the code for MultiPoint to be added, not the code for Point).
+ case GeometryType::kMultiPoint:
+ case GeometryType::kMultiLinestring:
+ case GeometryType::kMultiPolygon:
+ case GeometryType::kGeometryCollection: {
+ uint32_t n_parts = src->ReadUInt32(swap);
+ for (uint32_t i = 0; i < n_parts; i++) {
+ MergeGeometryInternal(src, /*record_wkb_type*/ false);
+ }
+ break;
+ }
+ }
+}
+
+void WKBGeometryBounder::MergeSequence(WKBBuffer* src, Dimensions dimensions,
+ uint32_t n_coords, bool swap) {
+ switch (dimensions) {
+ case Dimensions::kXY:
+ src->ReadCoords<BoundingBox::XY>(
+ n_coords, swap, [&](BoundingBox::XY coord) { box_.UpdateXY(coord); });
+ break;
+ case Dimensions::kXYZ:
+ src->ReadCoords<BoundingBox::XYZ>(
+ n_coords, swap, [&](BoundingBox::XYZ coord) { box_.UpdateXYZ(coord); });
+ break;
+ case Dimensions::kXYM:
+ src->ReadCoords<BoundingBox::XYM>(
+ n_coords, swap, [&](BoundingBox::XYM coord) { box_.UpdateXYM(coord); });
+ break;
+ case Dimensions::kXYZM:
+ src->ReadCoords<BoundingBox::XYZM>(
+ n_coords, swap, [&](BoundingBox::XYZM coord) { box_.UpdateXYZM(coord); });
+ break;
+ default:
+ throw ParquetException("Unknown dimensions");
+ }
+}
+
+} // namespace parquet::geospatial
diff --git a/cpp/src/parquet/geospatial/util_internal.h b/cpp/src/parquet/geospatial/util_internal.h
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/util_internal.h
@@ -0,0 +1,224 @@
+// 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.
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <iostream>
+#include <limits>
+#include <string>
+#include <unordered_set>
+
+#include "arrow/util/logging_internal.h"
+#include "parquet/platform.h"
+
+namespace parquet::geospatial {
+
+/// \brief Infinity, used to define bounds of empty bounding boxes
+constexpr double kInf = std::numeric_limits<double>::infinity();
+
+/// \brief Valid combinations of dimensions allowed by ISO well-known binary
+///
+/// These values correspond to the 0, 1000, 2000, 3000 component of the WKB integer
+/// geometry type (i.e., the value of geometry_type // 1000).
+enum class Dimensions {
+ kXY = 0,
+ kXYZ = 1,
+ kXYM = 2,
+ kXYZM = 3,
+ kValueMin = 0,
+ kValueMax = 3
+};
+
+/// \brief The supported set of geometry types allowed by ISO well-known binary
+///
+/// These values correspond to the 1, 2, ..., 7 component of the WKB integer
+/// geometry type (i.e., the value of geometry_type % 1000).
+enum class GeometryType {
+ kPoint = 1,
+ kLinestring = 2,
+ kPolygon = 3,
+ kMultiPoint = 4,
+ kMultiLinestring = 5,
+ kMultiPolygon = 6,
+ kGeometryCollection = 7,
+ kValueMin = 1,
+ kValueMax = 7
+};
+
+/// \brief A collection of intervals representing the encountered ranges of values
+/// in each dimension.
+///
+/// The Parquet specification also supports wraparound bounding boxes in the X
+/// dimension; however, this structure assumes min < max always as it is used for
+/// the purposes of accumulating this type of bounds.
+///
+/// This class will ignore any NaN values it visits via UpdateXY[Z[M]](). This is
+/// consistent with GEOS and ensures that ranges are accumulated in the same way that
+/// other statistics in Parquet are accumulated (e.g., statistics of a double column will
+/// return a min/max of all non-NaN values). In WKB specifically, POINT EMPTY is
+/// represented by convention as all ordinate values filled with NaN, so this behaviour
+/// allows for no special-casing of POINT EMPTY in the WKB reader.
+///
+/// This class will propagate any NaN values (per dimension) that were explicitly
+/// specified via setting mins/maxes directly or by merging another BoundingBox that
+/// contained NaN values. This definition ensures that NaN bounds obtained via
+/// EncodedGeoStatistics (which may have been written by some other writer that generated
+/// NaNs, either on purpose or by accident) are not silently overwritten.
+struct PARQUET_EXPORT BoundingBox {
+ using XY = std::array<double, 2>;
+ using XYZ = std::array<double, 3>;
+ using XYM = std::array<double, 3>;
+ using XYZM = std::array<double, 4>;
+
+ BoundingBox(const XYZM& mins, const XYZM& maxes) : min(mins), max(maxes) {}
+ BoundingBox() : min{kInf, kInf, kInf, kInf}, max{-kInf, -kInf, -kInf, -kInf} {}
+
+ BoundingBox(const BoundingBox& other) = default;
+ BoundingBox& operator=(const BoundingBox&) = default;
+
+ /// \brief Update the X and Y bounds to ensure these bounds contain coord
+ void UpdateXY(::arrow::util::span<const double> coord) {
+ DCHECK_EQ(coord.size(), 2);
+ UpdateInternal(coord);
+ }
+
+ /// \brief Update the X, Y, and Z bounds to ensure these bounds contain coord
+ void UpdateXYZ(::arrow::util::span<const double> coord) {
+ DCHECK_EQ(coord.size(), 3);
+ UpdateInternal(coord);
+ }
+
+ /// \brief Update the X, Y, and M bounds to ensure these bounds contain coord
+ void UpdateXYM(::arrow::util::span<const double> coord) {
+ DCHECK_EQ(coord.size(), 3);
+ min[0] = std::min(min[0], coord[0]);
+ min[1] = std::min(min[1], coord[1]);
+ min[3] = std::min(min[3], coord[2]);
+ max[0] = std::max(max[0], coord[0]);
+ max[1] = std::max(max[1], coord[1]);
+ max[3] = std::max(max[3], coord[2]);
+ }
+
+ /// \brief Update the X, Y, Z, and M bounds to ensure these bounds contain coord
+ void UpdateXYZM(::arrow::util::span<const double> coord) {
+ DCHECK_EQ(coord.size(), 4);
+ UpdateInternal(coord);
+ }
+
+ /// \brief Reset these bounds to an empty state such that they contain no coordinates
+ void Reset() {
+ for (int i = 0; i < 4; i++) {
+ min[i] = kInf;
+ max[i] = -kInf;
+ }
+ }
+
+ /// \brief Update these bounds such they also contain other
+ void Merge(const BoundingBox& other) {
+ for (int i = 0; i < 4; i++) {
+ if (std::isnan(min[i]) || std::isnan(max[i]) || std::isnan(other.min[i]) ||
+ std::isnan(other.max[i])) {
+ min[i] = std::numeric_limits<double>::quiet_NaN();
+ max[i] = std::numeric_limits<double>::quiet_NaN();
+ } else {
+ min[i] = std::min(min[i], other.min[i]);
+ max[i] = std::max(max[i], other.max[i]);
+ }
+ }
+ }
+
+ std::string ToString() const;
+
+ XYZM min;
+ XYZM max;
+
+ private:
+ // This works for XY, XYZ, and XYZM
+ template <typename Coord>
+ void UpdateInternal(Coord coord) {
+ for (size_t i = 0; i < coord.size(); i++) {
+ min[i] = std::min(min[i], coord[i]);
+ max[i] = std::max(max[i], coord[i]);
+ }
+ }
+};
+
+inline bool operator==(const BoundingBox& lhs, const BoundingBox& rhs) {
+ return lhs.min == rhs.min && lhs.max == rhs.max;
+}
+
+inline bool operator!=(const BoundingBox& lhs, const BoundingBox& rhs) {
+ return !(lhs == rhs);
+}
+
+inline std::ostream& operator<<(std::ostream& os, const BoundingBox& obj) {
+ os << obj.ToString();
+ return os;
+}
+
+class WKBBuffer;
+
+/// \brief Accumulate a BoundingBox and geometry types based on zero or more well-known
+/// binary blobs
+///
+/// Note that this class is NOT appropriate for bounding a GEOGRAPHY,
+/// whose bounds are not a function purely of the vertices. Geography bounding
+/// is not yet implemented.
+class PARQUET_EXPORT WKBGeometryBounder {
+ public:
+ /// \brief Accumulate the bounds of a serialized well-known binary geometry
+ ///
+ /// Throws ParquetException for any parse errors encountered. Bounds for
+ /// any encountered coordinates are accumulated and the geometry type of
+ /// the geometry is added to the internal geometry type list.
+ void MergeGeometry(std::string_view bytes_wkb);
+
+ void MergeGeometry(::arrow::util::span<const uint8_t> bytes_wkb);
+
+ /// \brief Accumulate the bounds of a previously-calculated BoundingBox
+ void MergeBox(const BoundingBox& box) { box_.Merge(box); }
+
+ /// \brief Accumulate a previously-calculated list of geometry types
+ void MergeGeometryTypes(::arrow::util::span<const int32_t> geospatial_types) {
+ geospatial_types_.insert(geospatial_types.begin(), geospatial_types.end());
+ }
+
+ /// \brief Retrieve the accumulated bounds
+ const BoundingBox& Bounds() const { return box_; }
+
+ /// \brief Retrieve the accumulated geometry types
+ std::vector<int32_t> GeometryTypes() const;
+
+ /// \brief Reset the internal bounds and geometry types list to an empty state
+ void Reset() {
+ box_.Reset();
+ geospatial_types_.clear();
+ }
+
+ private:
+ BoundingBox box_;
+ std::unordered_set<int32_t> geospatial_types_;
+
+ void MergeGeometryInternal(WKBBuffer* src, bool record_wkb_type);
+
+ void MergeSequence(WKBBuffer* src, Dimensions dimensions, uint32_t n_coords, bool swap);
+};
+
+} // namespace parquet::geospatial
diff --git a/cpp/src/parquet/geospatial/util_json_internal.cc b/cpp/src/parquet/geospatial/util_json_internal.cc
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/util_json_internal.cc
@@ -0,0 +1,205 @@
+// 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.
+
+#include "parquet/geospatial/util_json_internal.h"
+
+#include <string>
+
+#include "arrow/extension_type.h"
+#include "arrow/json/rapidjson_defs.h" // IWYU pragma: keep
+#include "arrow/result.h"
+#include "arrow/util/string.h"
+
+#include <rapidjson/document.h>
+#include <rapidjson/writer.h>
+
+#include "parquet/exception.h"
+#include "parquet/types.h"
+
+namespace parquet {
+
+namespace {
+::arrow::Result<std::string> GeospatialGeoArrowCrsToParquetCrs(
+ const ::arrow::rapidjson::Document& document) {
+ namespace rj = ::arrow::rapidjson;
+
+ if (!document.HasMember("crs") || document["crs"].IsNull()) {
+ // Parquet GEOMETRY/GEOGRAPHY do not have a concept of a null/missing
+ // CRS, but an omitted one is more likely to have meant "lon/lat" than
+ // a truly unspecified one (i.e., Engineering CRS with arbitrary XY units)
+ return "";
+ }
+
+ const auto& json_crs = document["crs"];
+ if (json_crs.IsString() && (json_crs == "EPSG:4326" || json_crs == "OGC:CRS84")) {
+ // crs can be left empty because these cases both correspond to
+ // longitude/latitude in WGS84 according to the Parquet specification
+ return "";
+ } else if (json_crs.IsObject()) {
+ // Attempt to detect common PROJJSON representations of longitude/latitude and return
+ // an empty crs to maximize compatibility with readers that do not implement CRS
+ // support. PROJJSON stores this in the "id" member like:
+ // {..., "id": {"authority": "...", "code": "..."}}
+ if (json_crs.HasMember("id")) {
+ const auto& identifier = json_crs["id"];
+ if (identifier.HasMember("authority") && identifier.HasMember("code")) {
+ if (identifier["authority"] == "OGC" && identifier["code"] == "CRS84") {
+ return "";
+ } else if (identifier["authority"] == "EPSG" && identifier["code"] == "4326") {
+ return "";
+ } else if (identifier["authority"] == "EPSG" && identifier["code"] == 4326) {
+ return "";
+ }
+ }
+ }
+ }
+
+ // If we could not detect a longitude/latitude CRS, just write the string to the
+ // LogicalType crs (being sure to unescape a JSON string into a regular string)
+ if (json_crs.IsString()) {
+ return json_crs.GetString();
+ } else {
+ rj::StringBuffer buffer;
+ rj::Writer<rj::StringBuffer> writer(buffer);
+ json_crs.Accept(writer);
+ return buffer.GetString();
+ }
+}
+
+// Utility for ensuring that a Parquet CRS is valid JSON when written to
+// GeoArrow metadata (without escaping it if it is already valid JSON such as
+// a PROJJSON string)
+std::string EscapeCrsAsJsonIfRequired(std::string_view crs);
+
+::arrow::Result<std::string> MakeGeoArrowCrsMetadata(
+ std::string_view crs,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata) {
+ const std::string kSridPrefix{"srid:"};
+ const std::string kProjjsonPrefix{"projjson:"};
+
+ // Two recommendations are explicitly mentioned in the Parquet format for the
+ // LogicalType crs:
+ //
+ // - "srid:XXXX" as a way to encode an application-specific integer identifier
+ // - "projjson:some_field_name" as a way to avoid repeating PROJJSON strings
+ // unnecessarily (with a suggestion to place them in the file metadata)
+ //
+ // While we don't currently generate those values to reduce the complexity
+ // of the writer, we do interpret these values according to the suggestion in
+ // the format and pass on this information to GeoArrow.
+ if (crs.empty()) {
+ return R"("crs": "OGC:CRS84", "crs_type": "authority_code")";
+ } else if (::arrow::internal::StartsWith(crs, kSridPrefix)) {
+ return R"("crs": ")" + std::string(crs.substr(kSridPrefix.size())) +
+ R"(", "crs_type": "srid")";
+ } else if (::arrow::internal::StartsWith(crs, kProjjsonPrefix)) {
+ std::string_view metadata_field = crs.substr(kProjjsonPrefix.size());
+ if (metadata && metadata->Contains(metadata_field)) {
+ ARROW_ASSIGN_OR_RAISE(std::string projjson_value, metadata->Get(metadata_field));
+ // This value should be valid JSON, but if it is not, we escape it as a string such
+ // that it can be inspected by the consumer of GeoArrow.
+ return R"("crs": )" + EscapeCrsAsJsonIfRequired(projjson_value) +
+ R"(, "crs_type": "projjson")";
+ }
+ }
+
+ // Pass on the string directly to GeoArrow. If the string is already valid JSON,
+ // insert it directly into GeoArrow's "crs" field. Otherwise, escape it and pass it as a
+ // string value.
+ return R"("crs": )" + EscapeCrsAsJsonIfRequired(crs);
+}
+
+std::string EscapeCrsAsJsonIfRequired(std::string_view crs) {
+ namespace rj = ::arrow::rapidjson;
+ rj::Document document;
+ if (document.Parse(crs.data(), crs.length()).HasParseError()) {
+ rj::StringBuffer buffer;
+ rj::Writer<rj::StringBuffer> writer(buffer);
+ rj::Value v;
+ v.SetString(crs.data(), static_cast<int32_t>(crs.size()));
+ v.Accept(writer);
+ return std::string(buffer.GetString());
+ } else {
+ return std::string(crs);
+ }
+}
+
+} // namespace
+
+::arrow::Result<std::shared_ptr<const LogicalType>> LogicalTypeFromGeoArrowMetadata(
+ std::string_view serialized_data) {
+ // Parquet has no way to interpret a null or missing CRS, so we choose the most likely
+ // intent here (that the user meant to use the default Parquet CRS)
+ if (serialized_data.empty() || serialized_data == "{}") {
+ return LogicalType::Geometry();
+ }
+
+ namespace rj = ::arrow::rapidjson;
+ rj::Document document;
+ if (document.Parse(serialized_data.data(), serialized_data.length()).HasParseError()) {
+ return ::arrow::Status::Invalid("Invalid serialized JSON data: ", serialized_data);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(std::string crs, GeospatialGeoArrowCrsToParquetCrs(document));
+
+ if (document.HasMember("edges") && document["edges"] == "planar") {
+ return LogicalType::Geometry(crs);
+ } else if (document.HasMember("edges") && document["edges"] == "spherical") {
+ return LogicalType::Geography(crs,
+ LogicalType::EdgeInterpolationAlgorithm::SPHERICAL);
+ } else if (document.HasMember("edges")) {
+ return ::arrow::Status::Invalid("Unsupported GeoArrow edge type: ", serialized_data);
+ }
+
+ return LogicalType::Geometry(crs);
+}
+
+::arrow::Result<std::shared_ptr<::arrow::DataType>> GeoArrowTypeFromLogicalType(
+ const LogicalType& logical_type,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata) {
+ // Check if we have a registered GeoArrow type to read into
+ std::shared_ptr<::arrow::ExtensionType> maybe_geoarrow_wkb =
+ ::arrow::GetExtensionType("geoarrow.wkb");
+ if (!maybe_geoarrow_wkb) {
+ return ::arrow::binary();
+ }
+
+ if (logical_type.is_geometry()) {
+ const auto& geospatial_type =
+ ::arrow::internal::checked_cast<const GeometryLogicalType&>(logical_type);
+ ARROW_ASSIGN_OR_RAISE(std::string crs_metadata,
+ MakeGeoArrowCrsMetadata(geospatial_type.crs(), metadata));
+
+ std::string serialized_data = std::string("{") + crs_metadata + "}";
+ return maybe_geoarrow_wkb->Deserialize(::arrow::binary(), serialized_data);
+ } else if (logical_type.is_geography()) {
+ const auto& geospatial_type =
+ ::arrow::internal::checked_cast<const GeographyLogicalType&>(logical_type);
+ ARROW_ASSIGN_OR_RAISE(std::string crs_metadata,
+ MakeGeoArrowCrsMetadata(geospatial_type.crs(), metadata));
+ std::string edges_metadata =
+ R"("edges": ")" + std::string(geospatial_type.algorithm_name()) + R"(")";
+ std::string serialized_data =
+ std::string("{") + crs_metadata + ", " + edges_metadata + "}";
+ return maybe_geoarrow_wkb->Deserialize(::arrow::binary(), serialized_data);
+ } else {
+ throw ParquetException("Can't export logical type ", logical_type.ToString(),
+ " as GeoArrow");
+ }
+}
+
+} // namespace parquet
diff --git a/cpp/src/parquet/geospatial/util_json_internal.h b/cpp/src/parquet/geospatial/util_json_internal.h
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/util_json_internal.h
@@ -0,0 +1,45 @@
+// 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.
+
+#pragma once
+
+#include <string_view>
+
+#include "arrow/util/key_value_metadata.h"
+
+#include "parquet/types.h"
+
+namespace parquet {
+
+/// \brief Compute a Parquet Logical type (Geometry(...) or Geography(...)) from
+/// GeoArrow `ARROW:extension:metadata` (JSON-encoded extension type metadata)
+///
+/// Returns the appropriate LogicalType or Invalid if the metadata was invalid.
+::arrow::Result<std::shared_ptr<const LogicalType>> LogicalTypeFromGeoArrowMetadata(
+ std::string_view serialized_data);
+
+/// \brief Compute a suitable DataType into which a GEOMETRY or GEOGRAPHY type should be
+/// read
+///
+/// The result of this function depends on whether or not "geoarrow.wkb" has been
+/// registered: if it has, the result will be the registered ExtensionType; if it has not,
+/// the result will be binary().
+::arrow::Result<std::shared_ptr<::arrow::DataType>> GeoArrowTypeFromLogicalType(
+ const LogicalType& logical_type,
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata);
+
+} // namespace parquet
diff --git a/cpp/src/parquet/metadata.cc b/cpp/src/parquet/metadata.cc
--- a/cpp/src/parquet/metadata.cc
+++ b/cpp/src/parquet/metadata.cc
@@ -38,6 +38,7 @@
#include "parquet/schema.h"
#include "parquet/schema_internal.h"
#include "parquet/size_statistics.h"
+#include "parquet/statistics.h"
#include "parquet/thrift_internal.h"
namespace parquet {
@@ -108,6 +109,17 @@ static std::shared_ptr<Statistics> MakeTypedColumnStats(
metadata.statistics.__isset.null_count, metadata.statistics.__isset.distinct_count);
}
+static std::shared_ptr<geospatial::GeoStatistics> MakeColumnGeometryStats(
+ const format::ColumnMetaData& metadata, const ColumnDescriptor* descr) {
+ if (metadata.__isset.geospatial_statistics) {
+ geospatial::EncodedGeoStatistics encoded_geo_stats =
+ FromThrift(metadata.geospatial_statistics);
+ return std::make_shared<geospatial::GeoStatistics>(std::move(encoded_geo_stats));
+ } else {
+ return nullptr;
+ }
+}
+
std::shared_ptr<Statistics> MakeColumnStats(const format::ColumnMetaData& meta_data,
const ColumnDescriptor* descr) {
switch (static_cast<Type::type>(meta_data.type)) {
@@ -268,6 +280,7 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl {
size_statistics_->Validate(descr_);
}
possible_stats_ = nullptr;
+ possible_geo_stats_ = nullptr;
InitKeyValueMetadata();
}
@@ -298,14 +311,29 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl {
descr_->sort_order() == SortOrder::UNKNOWN) {
return false;
}
- if (possible_stats_ == nullptr) {
- possible_stats_ = MakeColumnStats(*column_metadata_, descr_);
+ {
+ // Because we are modifying possible_stats_ in a const method
+ const std::lock_guard<std::mutex> guard(stats_mutex_);
+ if (possible_stats_ == nullptr) {
+ possible_stats_ = MakeColumnStats(*column_metadata_, descr_);
+ }
}
EncodedStatistics encodedStatistics = possible_stats_->Encode();
return writer_version_->HasCorrectStatistics(type(), encodedStatistics,
descr_->sort_order());
}
+ inline bool is_geo_stats_set() const {
+ // Because we are modifying possible_geo_stats_ in a const method
+ const std::lock_guard<std::mutex> guard(stats_mutex_);
+ if (possible_geo_stats_ == nullptr &&
+ column_metadata_->__isset.geospatial_statistics) {
+ possible_geo_stats_ = MakeColumnGeometryStats(*column_metadata_, descr_);
+ }
+
+ return possible_geo_stats_ != nullptr && possible_geo_stats_->is_valid();
+ }
+
inline std::shared_ptr<Statistics> statistics() const {
return is_stats_set() ? possible_stats_ : nullptr;
}
@@ -314,6 +342,10 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl {
return size_statistics_;
}
+ inline std::shared_ptr<geospatial::GeoStatistics> geospatial_statistics() const {
+ return is_geo_stats_set() ? possible_geo_stats_ : nullptr;
+ }
+
inline Compression::type compression() const {
return LoadEnumSafe(&column_metadata_->codec);
}
@@ -392,7 +424,9 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl {
key_value_metadata_ = FromThriftKeyValueMetadata(*column_metadata_);
}
+ mutable std::mutex stats_mutex_;
mutable std::shared_ptr<Statistics> possible_stats_;
+ mutable std::shared_ptr<geospatial::GeoStatistics> possible_geo_stats_;
std::vector<Encoding::type> encodings_;
std::vector<PageEncodingStats> encoding_stats_;
const format::ColumnChunk* column_;
@@ -444,12 +478,18 @@ std::shared_ptr<Statistics> ColumnChunkMetaData::statistics() const {
return impl_->statistics();
}
+std::shared_ptr<geospatial::GeoStatistics> ColumnChunkMetaData::geo_statistics() const {
+ return impl_->geospatial_statistics();
+}
+
bool ColumnChunkMetaData::is_stats_set() const { return impl_->is_stats_set(); }
std::shared_ptr<SizeStatistics> ColumnChunkMetaData::size_statistics() const {
return impl_->size_statistics();
}
+bool ColumnChunkMetaData::is_geo_stats_set() const { return impl_->is_geo_stats_set(); }
+
std::optional<int64_t> ColumnChunkMetaData::bloom_filter_offset() const {
return impl_->bloom_filter_offset();
}
@@ -1558,6 +1598,10 @@ class ColumnChunkMetaDataBuilder::ColumnChunkMetaDataBuilderImpl {
column_chunk_->meta_data.__set_size_statistics(ToThrift(size_stats));
}
+ void SetGeoStatistics(const geospatial::EncodedGeoStatistics& val) {
+ column_chunk_->meta_data.__set_geospatial_statistics(ToThrift(val));
+ }
+
void Finish(int64_t num_values, int64_t dictionary_page_offset,
int64_t index_page_offset, int64_t data_page_offset,
int64_t compressed_size, int64_t uncompressed_size, bool has_dictionary,
@@ -1771,6 +1815,11 @@ void ColumnChunkMetaDataBuilder::SetSizeStatistics(const SizeStatistics& size_st
impl_->SetSizeStatistics(size_stats);
}
+void ColumnChunkMetaDataBuilder::SetGeoStatistics(
+ const geospatial::EncodedGeoStatistics& result) {
+ impl_->SetGeoStatistics(result);
+}
+
void ColumnChunkMetaDataBuilder::SetKeyValueMetadata(
std::shared_ptr<const KeyValueMetadata> key_value_metadata) {
impl_->SetKeyValueMetadata(std::move(key_value_metadata));
diff --git a/cpp/src/parquet/metadata.h b/cpp/src/parquet/metadata.h
--- a/cpp/src/parquet/metadata.h
+++ b/cpp/src/parquet/metadata.h
@@ -22,12 +22,12 @@
#include <memory>
#include <optional>
#include <string>
-#include <utility>
#include <vector>
#include "parquet/encryption/type_fwd.h"
#include "parquet/platform.h"
#include "parquet/properties.h"
+#include "parquet/type_fwd.h"
namespace parquet {
@@ -141,8 +141,10 @@ class PARQUET_EXPORT ColumnChunkMetaData {
int64_t num_values() const;
std::shared_ptr<schema::ColumnPath> path_in_schema() const;
bool is_stats_set() const;
+ bool is_geo_stats_set() const;
std::shared_ptr<Statistics> statistics() const;
std::shared_ptr<SizeStatistics> size_statistics() const;
+ std::shared_ptr<geospatial::GeoStatistics> geo_statistics() const;
Compression::type compression() const;
// Indicate if the ColumnChunk compression is supported by the current
@@ -440,6 +442,9 @@ class PARQUET_EXPORT ColumnChunkMetaDataBuilder {
void SetStatistics(const EncodedStatistics& stats);
void SetSizeStatistics(const SizeStatistics& size_stats);
+ // column geometry statistics
+ void SetGeoStatistics(const geospatial::EncodedGeoStatistics& geo_stats);
+
void SetKeyValueMetadata(std::shared_ptr<const KeyValueMetadata> key_value_metadata);
// get the column descriptor
diff --git a/cpp/src/parquet/thrift_internal.h b/cpp/src/parquet/thrift_internal.h
--- a/cpp/src/parquet/thrift_internal.h
+++ b/cpp/src/parquet/thrift_internal.h
@@ -41,6 +41,7 @@
#include "parquet/encryption/internal_file_decryptor.h"
#include "parquet/encryption/internal_file_encryptor.h"
#include "parquet/exception.h"
+#include "parquet/geospatial/statistics.h"
#include "parquet/platform.h"
#include "parquet/properties.h"
#include "parquet/size_statistics.h"
@@ -232,6 +233,73 @@ static inline AadMetadata FromThrift(format::AesGcmCtrV1 aesGcmCtrV1) {
aesGcmCtrV1.supply_aad_prefix};
}
+static inline geospatial::EncodedGeoStatistics FromThrift(
+ const format::GeospatialStatistics& geo_stats) {
+ geospatial::EncodedGeoStatistics out;
+
+ out.geospatial_types = geo_stats.geospatial_types;
+
+ if (geo_stats.__isset.bbox) {
+ out.xmin = geo_stats.bbox.xmin;
+ out.xmax = geo_stats.bbox.xmax;
+ out.ymin = geo_stats.bbox.ymin;
+ out.ymax = geo_stats.bbox.ymax;
+ out.xy_bounds_present = true;
+
+ if (geo_stats.bbox.__isset.zmin && geo_stats.bbox.__isset.zmax) {
+ out.zmin = geo_stats.bbox.zmin;
+ out.zmax = geo_stats.bbox.zmax;
+ out.z_bounds_present = true;
+ }
+
+ if (geo_stats.bbox.__isset.mmin && geo_stats.bbox.__isset.mmax) {
+ out.mmin = geo_stats.bbox.mmin;
+ out.mmax = geo_stats.bbox.mmax;
+ out.m_bounds_present = true;
+ }
+ }
+
+ return out;
+}
+
+static inline format::EdgeInterpolationAlgorithm::type ToThrift(
+ LogicalType::EdgeInterpolationAlgorithm algorithm) {
+ switch (algorithm) {
+ case LogicalType::EdgeInterpolationAlgorithm::SPHERICAL:
+ return format::EdgeInterpolationAlgorithm::SPHERICAL;
+ case LogicalType::EdgeInterpolationAlgorithm::VINCENTY:
+ return format::EdgeInterpolationAlgorithm::VINCENTY;
+ case LogicalType::EdgeInterpolationAlgorithm::THOMAS:
+ return format::EdgeInterpolationAlgorithm::THOMAS;
+ case LogicalType::EdgeInterpolationAlgorithm::ANDOYER:
+ return format::EdgeInterpolationAlgorithm::ANDOYER;
+ case LogicalType::EdgeInterpolationAlgorithm::KARNEY:
+ return format::EdgeInterpolationAlgorithm::KARNEY;
+ default:
+ throw ParquetException("Unknown value for geometry algorithm: ",
+ static_cast<int>(algorithm));
+ }
+}
+
+static inline LogicalType::EdgeInterpolationAlgorithm FromThrift(
+ const format::EdgeInterpolationAlgorithm::type algorithm) {
+ switch (algorithm) {
+ case format::EdgeInterpolationAlgorithm::SPHERICAL:
+ return LogicalType::EdgeInterpolationAlgorithm::SPHERICAL;
+ case format::EdgeInterpolationAlgorithm::VINCENTY:
+ return LogicalType::EdgeInterpolationAlgorithm::VINCENTY;
+ case format::EdgeInterpolationAlgorithm::THOMAS:
+ return LogicalType::EdgeInterpolationAlgorithm::THOMAS;
+ case format::EdgeInterpolationAlgorithm::ANDOYER:
+ return LogicalType::EdgeInterpolationAlgorithm::ANDOYER;
+ case format::EdgeInterpolationAlgorithm::KARNEY:
+ return LogicalType::EdgeInterpolationAlgorithm::KARNEY;
+ default:
+ throw ParquetException("Unknown value for geometry algorithm: ",
+ static_cast<int>(algorithm));
+ }
+}
+
static inline EncryptionAlgorithm FromThrift(format::EncryptionAlgorithm encryption) {
EncryptionAlgorithm encryption_algorithm;
@@ -332,6 +400,35 @@ static inline format::SortingColumn ToThrift(SortingColumn sorting_column) {
return thrift_sorting_column;
}
+static inline format::GeospatialStatistics ToThrift(
+ const geospatial::EncodedGeoStatistics& encoded_geo_stats) {
+ format::GeospatialStatistics geospatial_statistics;
+
+ geospatial_statistics.__set_geospatial_types(encoded_geo_stats.geospatial_types);
+
+ if (encoded_geo_stats.xy_bounds_present) {
+ format::BoundingBox bbox;
+ bbox.__set_xmin(encoded_geo_stats.xmin);
+ bbox.__set_xmax(encoded_geo_stats.xmax);
+ bbox.__set_ymin(encoded_geo_stats.ymin);
+ bbox.__set_ymax(encoded_geo_stats.ymax);
+
+ if (encoded_geo_stats.z_bounds_present) {
+ bbox.__set_zmin(encoded_geo_stats.zmin);
+ bbox.__set_zmax(encoded_geo_stats.zmax);
+ }
+
+ if (encoded_geo_stats.m_bounds_present) {
+ bbox.__set_mmin(encoded_geo_stats.mmin);
+ bbox.__set_mmax(encoded_geo_stats.mmax);
+ }
+
+ geospatial_statistics.__set_bbox(std::move(bbox));
+ }
+
+ return geospatial_statistics;
+}
+
static inline format::Statistics ToThrift(const EncodedStatistics& stats) {
format::Statistics statistics;
if (stats.has_min) {
diff --git a/cpp/src/parquet/type_fwd.h b/cpp/src/parquet/type_fwd.h
--- a/cpp/src/parquet/type_fwd.h
+++ b/cpp/src/parquet/type_fwd.h
@@ -83,6 +83,11 @@ class EncodedStatistics;
class Statistics;
struct SizeStatistics;
+namespace geospatial {
+class GeoStatistics;
+struct EncodedGeoStatistics;
+} // namespace geospatial
+
class ColumnIndex;
class OffsetIndex;
diff --git a/cpp/src/parquet/types.cc b/cpp/src/parquet/types.cc
--- a/cpp/src/parquet/types.cc
+++ b/cpp/src/parquet/types.cc
@@ -22,11 +22,16 @@
#include <sstream>
#include <string>
+#include "arrow/json/rapidjson_defs.h" // IWYU pragma: keep
#include "arrow/util/checked_cast.h"
#include "arrow/util/compression.h"
#include "arrow/util/logging_internal.h"
+#include <rapidjson/document.h>
+#include <rapidjson/writer.h>
+
#include "parquet/exception.h"
+#include "parquet/thrift_internal.h"
#include "parquet/types.h"
#include "generated/parquet_types.h"
@@ -479,6 +484,27 @@ std::shared_ptr<const LogicalType> LogicalType::FromThrift(
return UUIDLogicalType::Make();
} else if (type.__isset.FLOAT16) {
return Float16LogicalType::Make();
+ } else if (type.__isset.GEOMETRY) {
+ std::string crs;
+ if (type.GEOMETRY.__isset.crs) {
+ crs = type.GEOMETRY.crs;
+ }
+
+ return GeometryLogicalType::Make(std::move(crs));
+ } else if (type.__isset.GEOGRAPHY) {
+ std::string crs;
+ if (type.GEOGRAPHY.__isset.crs) {
+ crs = type.GEOGRAPHY.crs;
+ }
+
+ LogicalType::EdgeInterpolationAlgorithm algorithm;
+ if (!type.GEOGRAPHY.__isset.algorithm) {
+ algorithm = LogicalType::EdgeInterpolationAlgorithm::SPHERICAL;
+ } else {
+ algorithm = ::parquet::FromThrift(type.GEOGRAPHY.algorithm);
+ }
+
+ return GeographyLogicalType::Make(std::move(crs), algorithm);
} else if (type.__isset.VARIANT) {
return VariantLogicalType::Make();
} else {
@@ -539,6 +565,15 @@ std::shared_ptr<const LogicalType> LogicalType::Float16() {
return Float16LogicalType::Make();
}
+std::shared_ptr<const LogicalType> LogicalType::Geometry(std::string crs) {
+ return GeometryLogicalType::Make(std::move(crs));
+}
+
+std::shared_ptr<const LogicalType> LogicalType::Geography(
+ std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm) {
+ return GeographyLogicalType::Make(std::move(crs), algorithm);
+}
+
std::shared_ptr<const LogicalType> LogicalType::Variant() {
return VariantLogicalType::Make();
}
@@ -625,6 +660,8 @@ class LogicalType::Impl {
class BSON;
class UUID;
class Float16;
+ class Geometry;
+ class Geography;
class Variant;
class No;
class Undefined;
@@ -698,6 +735,12 @@ bool LogicalType::is_UUID() const { return impl_->type() == LogicalType::Type::U
bool LogicalType::is_float16() const {
return impl_->type() == LogicalType::Type::FLOAT16;
}
+bool LogicalType::is_geometry() const {
+ return impl_->type() == LogicalType::Type::GEOMETRY;
+}
+bool LogicalType::is_geography() const {
+ return impl_->type() == LogicalType::Type::GEOGRAPHY;
+}
bool LogicalType::is_variant() const {
return impl_->type() == LogicalType::Type::VARIANT;
}
@@ -1630,6 +1673,200 @@ class LogicalType::Impl::Float16 final : public LogicalType::Impl::Incompatible,
GENERATE_MAKE(Float16)
+namespace {
+void WriteCrsKeyAndValue(const std::string_view crs, std::ostream& json) {
+ // There is no restriction on the crs value here, and it may contain quotes
+ // or backslashes that would result in invalid JSON if unescaped.
+ namespace rj = ::arrow::rapidjson;
+ rj::StringBuffer buffer;
+ rj::Writer<rj::StringBuffer> writer(buffer);
+ rj::Value v;
+ v.SetString(crs.data(), static_cast<int32_t>(crs.size()));
+ v.Accept(writer);
+ json << R"(, "crs": )" << buffer.GetString();
+}
+} // namespace
+
+class LogicalType::Impl::Geometry final : public LogicalType::Impl::Incompatible,
+ public LogicalType::Impl::SimpleApplicable {
+ public:
+ friend class GeometryLogicalType;
+
+ std::string ToString() const override;
+ std::string ToJSON() const override;
+ format::LogicalType ToThrift() const override;
+ bool Equals(const LogicalType& other) const override;
+
+ const std::string& crs() const { return crs_; }
+
+ private:
+ explicit Geometry(std::string crs)
+ : LogicalType::Impl(LogicalType::Type::GEOMETRY, SortOrder::UNKNOWN),
+ LogicalType::Impl::SimpleApplicable(parquet::Type::BYTE_ARRAY),
+ crs_(std::move(crs)) {}
+
+ std::string crs_;
+};
+
+std::string LogicalType::Impl::Geometry::ToString() const {
+ std::stringstream type;
+ type << "Geometry(crs=" << crs_ << ")";
+ return type.str();
+}
+
+std::string LogicalType::Impl::Geometry::ToJSON() const {
+ std::stringstream json;
+ json << R"({"Type": "Geometry")";
+
+ if (!crs_.empty()) {
+ WriteCrsKeyAndValue(crs_, json);
+ }
+
+ json << "}";
+ return json.str();
+}
+
+format::LogicalType LogicalType::Impl::Geometry::ToThrift() const {
+ format::LogicalType type;
+ format::GeometryType geometry_type;
+
+ // Canonially export crs of "" as an unset CRS
+ if (!crs_.empty()) {
+ geometry_type.__set_crs(crs_);
+ }
+
+ type.__set_GEOMETRY(geometry_type);
+ return type;
+}
+
+bool LogicalType::Impl::Geometry::Equals(const LogicalType& other) const {
+ if (other.is_geometry()) {
+ const auto& other_geometry = checked_cast<const GeometryLogicalType&>(other);
+ return crs() == other_geometry.crs();
+ } else {
+ return false;
+ }
+}
+
+const std::string& GeometryLogicalType::crs() const {
+ return (dynamic_cast<const LogicalType::Impl::Geometry&>(*impl_)).crs();
+}
+
+std::shared_ptr<const LogicalType> GeometryLogicalType::Make(std::string crs) {
+ auto logical_type = std::shared_ptr<GeometryLogicalType>(new GeometryLogicalType());
+ logical_type->impl_.reset(new LogicalType::Impl::Geometry(std::move(crs)));
+ return logical_type;
+}
+
+class LogicalType::Impl::Geography final : public LogicalType::Impl::Incompatible,
+ public LogicalType::Impl::SimpleApplicable {
+ public:
+ friend class GeographyLogicalType;
+
+ std::string ToString() const override;
+ std::string ToJSON() const override;
+ format::LogicalType ToThrift() const override;
+ bool Equals(const LogicalType& other) const override;
+
+ const std::string& crs() const { return crs_; }
+ LogicalType::EdgeInterpolationAlgorithm algorithm() const { return algorithm_; }
+
+ std::string_view algorithm_name() const {
+ switch (algorithm_) {
+ case LogicalType::EdgeInterpolationAlgorithm::SPHERICAL:
+ return "spherical";
+ case LogicalType::EdgeInterpolationAlgorithm::VINCENTY:
+ return "vincenty";
+ case LogicalType::EdgeInterpolationAlgorithm::THOMAS:
+ return "thomas";
+ case LogicalType::EdgeInterpolationAlgorithm::ANDOYER:
+ return "andoyer";
+ case LogicalType::EdgeInterpolationAlgorithm::KARNEY:
+ return "karney";
+ default:
+ return "unknown";
+ }
+ }
+
+ private:
+ Geography(std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm)
+ : LogicalType::Impl(LogicalType::Type::GEOGRAPHY, SortOrder::UNKNOWN),
+ LogicalType::Impl::SimpleApplicable(parquet::Type::BYTE_ARRAY),
+ crs_(std::move(crs)),
+ algorithm_(algorithm) {}
+
+ std::string crs_;
+ LogicalType::EdgeInterpolationAlgorithm algorithm_;
+};
+
+std::string LogicalType::Impl::Geography::ToString() const {
+ std::stringstream type;
+ type << "Geography(crs=" << crs_ << ", algorithm=" << algorithm_name() << ")";
+ return type.str();
+}
+
+std::string LogicalType::Impl::Geography::ToJSON() const {
+ std::stringstream json;
+ json << R"({"Type": "Geography")";
+
+ if (!crs_.empty()) {
+ WriteCrsKeyAndValue(crs_, json);
+ }
+
+ if (algorithm_ != LogicalType::EdgeInterpolationAlgorithm::SPHERICAL) {
+ json << R"(, "algorithm": ")" << algorithm_name() << R"(")";
+ }
+
+ json << "}";
+ return json.str();
+}
+
+format::LogicalType LogicalType::Impl::Geography::ToThrift() const {
+ format::LogicalType type;
+ format::GeographyType geography_type;
+
+ // Canonially export crs of "" as an unset CRS
+ if (!crs_.empty()) {
+ geography_type.__set_crs(crs_);
+ }
+
+ if (algorithm_ == LogicalType::EdgeInterpolationAlgorithm::SPHERICAL) {
+ // Canonically export spherical algorithm as unset
+ } else {
+ geography_type.__set_algorithm(::parquet::ToThrift(algorithm_));
+ }
+
+ type.__set_GEOGRAPHY(geography_type);
+ return type;
+}
+
+bool LogicalType::Impl::Geography::Equals(const LogicalType& other) const {
+ if (other.is_geography()) {
+ const auto& other_geography = checked_cast<const GeographyLogicalType&>(other);
+ return crs() == other_geography.crs() && algorithm() == other_geography.algorithm();
+ } else {
+ return false;
+ }
+}
+
+const std::string& GeographyLogicalType::crs() const {
+ return (dynamic_cast<const LogicalType::Impl::Geography&>(*impl_)).crs();
+}
+
+LogicalType::EdgeInterpolationAlgorithm GeographyLogicalType::algorithm() const {
+ return (dynamic_cast<const LogicalType::Impl::Geography&>(*impl_)).algorithm();
+}
+
+std::string_view GeographyLogicalType::algorithm_name() const {
+ return (dynamic_cast<const LogicalType::Impl::Geography&>(*impl_)).algorithm_name();
+}
+
+std::shared_ptr<const LogicalType> GeographyLogicalType::Make(
+ std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm) {
+ auto logical_type = std::shared_ptr<GeographyLogicalType>(new GeographyLogicalType());
+ logical_type->impl_.reset(new LogicalType::Impl::Geography(std::move(crs), algorithm));
+ return logical_type;
+}
class LogicalType::Impl::Variant final : public LogicalType::Impl::Incompatible,
public LogicalType::Impl::Inapplicable {
public:
diff --git a/cpp/src/parquet/types.h b/cpp/src/parquet/types.h
--- a/cpp/src/parquet/types.h
+++ b/cpp/src/parquet/types.h
@@ -158,6 +158,8 @@ class PARQUET_EXPORT LogicalType {
BSON,
UUID,
FLOAT16,
+ GEOMETRY,
+ GEOGRAPHY,
VARIANT,
NONE // Not a real logical type; should always be last element
};
@@ -167,6 +169,15 @@ class PARQUET_EXPORT LogicalType {
enum unit { UNKNOWN = 0, MILLIS = 1, MICROS, NANOS };
};
+ enum class EdgeInterpolationAlgorithm {
+ UNKNOWN = 0,
+ SPHERICAL = 1,
+ VINCENTY = 2,
+ THOMAS = 3,
+ ANDOYER = 4,
+ KARNEY = 5
+ };
+
/// \brief If possible, return a logical type equivalent to the given legacy
/// converted type (and decimal metadata if applicable).
static std::shared_ptr<const LogicalType> FromConvertedType(
@@ -215,6 +226,12 @@ class PARQUET_EXPORT LogicalType {
static std::shared_ptr<const LogicalType> Float16();
static std::shared_ptr<const LogicalType> Variant();
+ static std::shared_ptr<const LogicalType> Geometry(std::string crs = "");
+
+ static std::shared_ptr<const LogicalType> Geography(
+ std::string crs = "", LogicalType::EdgeInterpolationAlgorithm algorithm =
+ EdgeInterpolationAlgorithm::SPHERICAL);
+
/// \brief Create a placeholder for when no logical type is specified
static std::shared_ptr<const LogicalType> None();
@@ -268,6 +285,8 @@ class PARQUET_EXPORT LogicalType {
bool is_BSON() const;
bool is_UUID() const;
bool is_float16() const;
+ bool is_geometry() const;
+ bool is_geography() const;
bool is_variant() const;
bool is_none() const;
/// \brief Return true if this logical type is of a known type.
@@ -449,6 +468,30 @@ class PARQUET_EXPORT Float16LogicalType : public LogicalType {
Float16LogicalType() = default;
};
+class PARQUET_EXPORT GeometryLogicalType : public LogicalType {
+ public:
+ static std::shared_ptr<const LogicalType> Make(std::string crs = "");
+
+ const std::string& crs() const;
+
+ private:
+ GeometryLogicalType() = default;
+};
+
+class PARQUET_EXPORT GeographyLogicalType : public LogicalType {
+ public:
+ static std::shared_ptr<const LogicalType> Make(
+ std::string crs = "", LogicalType::EdgeInterpolationAlgorithm algorithm =
+ EdgeInterpolationAlgorithm::SPHERICAL);
+
+ const std::string& crs() const;
+ LogicalType::EdgeInterpolationAlgorithm algorithm() const;
+ std::string_view algorithm_name() const;
+
+ private:
+ GeographyLogicalType() = default;
+};
+
/// \brief Allowed for group nodes only.
class PARQUET_EXPORT VariantLogicalType : public LogicalType {
public:
diff --git a/cpp/src/parquet/CMakeLists.txt b/cpp/src/parquet/CMakeLists.txt
index bc7e4f3..735653d 100644
--- a/cpp/src/parquet/CMakeLists.txt
+++ b/cpp/src/parquet/CMakeLists.txt
@@ -171,6 +171,9 @@ set(PARQUET_SRCS
exception.cc
file_reader.cc
file_writer.cc
+ geospatial/statistics.cc
+ geospatial/util_internal.cc
+ geospatial/util_json_internal.cc
level_comparison.cc
level_conversion.cc
metadata.cc
@@ -257,6 +260,10 @@ endif()
if(NOT PARQUET_MINIMAL_DEPENDENCY)
list(APPEND PARQUET_SHARED_LINK_LIBS arrow_shared)
+ # Add RapidJSON libraries
+ list(APPEND PARQUET_SHARED_PRIVATE_LINK_LIBS RapidJSON)
+ list(APPEND PARQUET_STATIC_LINK_LIBS RapidJSON)
+
# These are libraries that we will link privately with parquet_shared (as they
# do not need to be linked transitively by other linkers)
list(APPEND PARQUET_SHARED_PRIVATE_LINK_LIBS thrift::thrift)
@@ -352,6 +359,7 @@ endif()
add_subdirectory(api)
add_subdirectory(arrow)
add_subdirectory(encryption)
+add_subdirectory(geospatial)
arrow_install_all_headers("parquet")
@@ -362,15 +370,17 @@ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/parquet_version.h"
add_parquet_test(internals-test
SOURCES
- bloom_filter_test.cc
bloom_filter_reader_test.cc
- properties_test.cc
- statistics_test.cc
+ bloom_filter_test.cc
encoding_test.cc
+ geospatial/statistics_test.cc
+ geospatial/util_internal_test.cc
metadata_test.cc
page_index_test.cc
+ properties_test.cc
public_api_test.cc
size_statistics_test.cc
+ statistics_test.cc
types_test.cc)
set_source_files_properties(public_api_test.cc PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON)
|