Download arrow_1/tests/private/eval_tests.patch from lolbench26/LoLBench: direct link, hf CLI and curl.
- Browser
- Download file 57.7 kB
-
https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/arrow_1/tests/private/eval_tests.patch
- Command line
-
hf download hf://datasets/lolbench26/LoLBench/arrow_1/tests/private/eval_tests.patch
-
curl -L -o eval_tests.patch https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/arrow_1/tests/private/eval_tests.patch
57.7 kB
diff --git a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc
--- a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc
+++ b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc
@@ -43,6 +43,7 @@
#include "arrow/scalar.h"
#include "arrow/table.h"
#include "arrow/testing/builder.h"
+#include "arrow/testing/extension_type.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/testing/util.h"
@@ -1481,6 +1482,61 @@ TEST_F(TestJsonParquetIO, JsonExtension) {
this->RoundTripSingleColumn(json_large_array, json_large_array, writer_properties);
}
+using TestGeoArrowParquetIO = TestParquetIO<test::GeoArrowWkbExtensionType>;
+
+TEST_F(TestGeoArrowParquetIO, GeoArrowExtension) {
+ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb());
+
+ // Build a binary WKB array with at least one null value
+ ::arrow::BinaryBuilder builder;
+
+ for (int k = 0; k < 10; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ ASSERT_OK(builder.Append(item));
+ }
+ ASSERT_OK(builder.AppendNull());
+ for (int k = 0; k < 5; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ ASSERT_OK(builder.Append(item));
+ }
+
+ ASSERT_OK_AND_ASSIGN(const auto binary_array, builder.Finish());
+ const auto wkb_type = test::geoarrow_wkb_lonlat();
+ const auto wkb_array = ::arrow::ExtensionType::WrapArray(wkb_type, binary_array);
+
+ const auto large_wkb_type = test::geoarrow_wkb_lonlat(::arrow::large_binary());
+ ASSERT_OK_AND_ASSIGN(const auto large_binary_array,
+ ::arrow::compute::Cast(binary_array, ::arrow::large_binary()));
+ const auto large_wkb_array =
+ ::arrow::ExtensionType::WrapArray(large_wkb_type, large_binary_array.make_array());
+
+ // When the original Arrow schema isn't stored and Arrow extensions are disabled,
+ // LogicalType::GEOMETRY is read as utf8.
+ auto writer_properties = default_arrow_writer_properties();
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(wkb_array, binary_array, writer_properties));
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(large_wkb_array, binary_array, writer_properties));
+
+ // When the original Arrow schema isn't stored and Arrow extensions are enabled,
+ // LogicalType::GEOMETRY is read as geoarrow.wkb with binary storage.
+ ::parquet::ArrowReaderProperties reader_properties;
+ reader_properties.set_arrow_extensions_enabled(true);
+ ASSERT_NO_FATAL_FAILURE(this->RoundTripSingleColumn(
+ wkb_array, wkb_array, writer_properties, reader_properties));
+ ASSERT_NO_FATAL_FAILURE(this->RoundTripSingleColumn(
+ large_wkb_array, wkb_array, writer_properties, reader_properties));
+
+ // When the original Arrow schema is stored, the stored Arrow type is respected.
+ writer_properties = ::parquet::ArrowWriterProperties::Builder().store_schema()->build();
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(wkb_array, wkb_array, writer_properties));
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(large_wkb_array, large_wkb_array, writer_properties));
+}
+
using TestNullParquetIO = TestParquetIO<::arrow::NullType>;
TEST_F(TestNullParquetIO, NullColumn) {
diff --git a/cpp/src/parquet/arrow/arrow_schema_test.cc b/cpp/src/parquet/arrow/arrow_schema_test.cc
--- a/cpp/src/parquet/arrow/arrow_schema_test.cc
+++ b/cpp/src/parquet/arrow/arrow_schema_test.cc
@@ -19,7 +19,6 @@
#include <vector>
#include "gmock/gmock-matchers.h"
-#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "parquet/arrow/reader.h"
@@ -35,6 +34,7 @@
#include "arrow/extension/json.h"
#include "arrow/extension/uuid.h"
#include "arrow/ipc/writer.h"
+#include "arrow/testing/extension_type.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/type.h"
#include "arrow/util/base64.h"
@@ -237,6 +237,10 @@ TEST_F(TestConvertParquetSchema, ParquetAnnotatedFields) {
::arrow::int64()},
{"json", LogicalType::JSON(), ParquetType::BYTE_ARRAY, -1, ::arrow::utf8()},
{"bson", LogicalType::BSON(), ParquetType::BYTE_ARRAY, -1, ::arrow::binary()},
+ {"geometry", LogicalType::Geometry(), ParquetType::BYTE_ARRAY, -1,
+ ::arrow::binary()},
+ {"geography", LogicalType::Geography(), ParquetType::BYTE_ARRAY, -1,
+ ::arrow::binary()},
{"interval", LogicalType::Interval(), ParquetType::FIXED_LEN_BYTE_ARRAY, 12,
::arrow::fixed_size_binary(12)},
{"uuid", LogicalType::UUID(), ParquetType::FIXED_LEN_BYTE_ARRAY, 16,
@@ -1090,6 +1094,62 @@ TEST_F(TestConvertParquetSchema, ParquetSchemaArrowUuidExtension) {
}
}
+TEST_F(TestConvertParquetSchema, ParquetSchemaGeoArrowExtensions) {
+ std::vector<NodePtr> parquet_fields;
+ parquet_fields.push_back(PrimitiveNode::Make("geometry", Repetition::OPTIONAL,
+ LogicalType::Geometry(),
+ ParquetType::BYTE_ARRAY));
+ parquet_fields.push_back(PrimitiveNode::Make("geography", Repetition::OPTIONAL,
+ LogicalType::Geography(),
+ ParquetType::BYTE_ARRAY));
+
+ {
+ // Parquet file does not contain Arrow schema.
+ // By default, both fields should be treated as binary() fields in Arrow.
+ auto arrow_schema = ::arrow::schema({::arrow::field("geometry", BINARY, true),
+ ::arrow::field("geography", BINARY, true)});
+ std::shared_ptr<KeyValueMetadata> metadata{};
+ ASSERT_OK(ConvertSchema(parquet_fields, metadata));
+ CheckFlatSchema(arrow_schema);
+ }
+
+ {
+ // Parquet file does not contain Arrow schema.
+ // If Arrow extensions are enabled and extensions are registered,
+ // fields will be interpreted as geoarrow_wkb(binary()) extension fields.
+ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb());
+
+ ArrowReaderProperties props;
+ props.set_arrow_extensions_enabled(true);
+ auto arrow_schema = ::arrow::schema(
+ {::arrow::field(
+ "geometry",
+ test::geoarrow_wkb(R"({"crs": "OGC:CRS84", "crs_type": "authority_code"})"),
+ true),
+ ::arrow::field(
+ "geography",
+ test::geoarrow_wkb(
+ R"({"crs": "OGC:CRS84", "crs_type": "authority_code", "edges": "spherical"})"),
+ true)});
+ std::shared_ptr<KeyValueMetadata> metadata{};
+ ASSERT_OK(ConvertSchema(parquet_fields, metadata, props));
+ CheckFlatSchema(arrow_schema);
+ }
+
+ {
+ // Parquet file does not contain Arrow schema.
+ // If Arrow extensions are enabled and extensions are NOT registered,
+ // fields will be interpreted as binary().
+ ArrowReaderProperties props;
+ props.set_arrow_extensions_enabled(true);
+ auto arrow_schema = ::arrow::schema({::arrow::field("geometry", BINARY, true),
+ ::arrow::field("geography", BINARY, true)});
+ std::shared_ptr<KeyValueMetadata> metadata{};
+ ASSERT_OK(ConvertSchema(parquet_fields, metadata, props));
+ CheckFlatSchema(arrow_schema);
+ }
+}
+
class TestConvertArrowSchema : public ::testing::Test {
public:
virtual void SetUp() {}
@@ -1343,6 +1403,96 @@ TEST_F(TestConvertArrowSchema, ParquetFlatPrimitivesAsDictionaries) {
ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields));
}
+TEST_F(TestConvertArrowSchema, ParquetGeoArrowCrsLonLat) {
+ // All the Arrow Schemas below should convert to the type defaults for GEOMETRY
+ // and GEOGRAPHY when GeoArrow extension types are registered and the appropriate
+ // writer option is set.
+ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb());
+
+ std::vector<NodePtr> parquet_fields;
+ parquet_fields.push_back(PrimitiveNode::Make("geometry", Repetition::OPTIONAL,
+ LogicalType::Geometry(),
+ ParquetType::BYTE_ARRAY));
+ parquet_fields.push_back(PrimitiveNode::Make("geography", Repetition::OPTIONAL,
+ LogicalType::Geography(),
+ ParquetType::BYTE_ARRAY));
+
+ // There are several ways that longitude/latitude could be specified when coming from
+ // GeoArrow, which allows null, missing, arbitrary strings (e.g., Authority:Code), and
+ // PROJJSON.
+ std::vector<std::string> geoarrow_lonlat = {
+ "null", R"("OGC:CRS84")", R"("EPSG:4326")",
+ // Purely the parts of the PROJJSON that we inspect to check the lon/lat case
+ R"({"id": {"authority": "OGC", "code": "CRS84"}})",
+ R"({"id": {"authority": "EPSG", "code": "4326"}})",
+ R"({"id": {"authority": "EPSG", "code": 4326}})"};
+
+ for (const auto& geoarrow_lonlatish_crs : geoarrow_lonlat) {
+ ARROW_SCOPED_TRACE("crs = ", geoarrow_lonlatish_crs);
+ std::vector<std::shared_ptr<Field>> arrow_fields = {
+ ::arrow::field("geometry",
+ test::geoarrow_wkb(R"({"crs": )" + geoarrow_lonlatish_crs + "}"),
+ true),
+ ::arrow::field("geography",
+ test::geoarrow_wkb(R"({"crs": )" + geoarrow_lonlatish_crs +
+ R"(, "edges": "spherical"})"),
+ true)};
+
+ ASSERT_OK(ConvertSchema(arrow_fields));
+ ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields));
+ }
+}
+
+TEST_F(TestConvertArrowSchema, ParquetGeoArrowCrsSrid) {
+ // Checks that it is possible to write the srid:xxxx reccomendation from GeoArrow
+ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb());
+
+ std::vector<NodePtr> parquet_fields;
+ parquet_fields.push_back(PrimitiveNode::Make("geometry", Repetition::OPTIONAL,
+ LogicalType::Geometry("srid:1234"),
+ ParquetType::BYTE_ARRAY));
+ parquet_fields.push_back(PrimitiveNode::Make("geography", Repetition::OPTIONAL,
+ LogicalType::Geography("srid:5678"),
+ ParquetType::BYTE_ARRAY));
+
+ std::vector<std::shared_ptr<Field>> arrow_fields = {
+ ::arrow::field("geometry", test::geoarrow_wkb(R"({"crs": "srid:1234"})"), true),
+ ::arrow::field("geography",
+ test::geoarrow_wkb(R"({"crs": "srid:5678", "edges": "spherical"})"),
+ true)};
+
+ ASSERT_OK(ConvertSchema(arrow_fields));
+ ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields));
+}
+
+TEST_F(TestConvertArrowSchema, ParquetGeoArrowCrsProjjson) {
+ // Checks the conversion from GeoArrow that contains non-lon/lat PROJJSON
+ // to Parquet. Almost all GeoArrow types that arrive at the Parquet reader
+ // will have their CRS expressed in this way.
+ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb());
+
+ std::vector<std::shared_ptr<Field>> arrow_fields = {
+ ::arrow::field("geometry", test::geoarrow_wkb(R"({"crs": {"key0": "value0"}})"),
+ true),
+ ::arrow::field(
+ "geography",
+ test::geoarrow_wkb(R"({"crs": {"key1": "value1"}, "edges": "spherical"})"),
+ true)};
+
+ auto arrow_properties = default_arrow_writer_properties();
+ ASSERT_OK(ConvertSchema(arrow_fields, arrow_properties));
+
+ std::vector<NodePtr> parquet_fields;
+ parquet_fields.push_back(PrimitiveNode::Make(
+ "geometry", Repetition::OPTIONAL, LogicalType::Geometry(R"({"key0":"value0"})"),
+ ParquetType::BYTE_ARRAY));
+ parquet_fields.push_back(PrimitiveNode::Make(
+ "geography", Repetition::OPTIONAL, LogicalType::Geography(R"({"key1":"value1"})"),
+ ParquetType::BYTE_ARRAY));
+
+ ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields));
+}
+
TEST_F(TestConvertArrowSchema, ParquetLists) {
std::vector<NodePtr> parquet_fields;
std::vector<std::shared_ptr<Field>> arrow_fields;
diff --git a/cpp/src/parquet/column_writer_test.cc b/cpp/src/parquet/column_writer_test.cc
--- a/cpp/src/parquet/column_writer_test.cc
+++ b/cpp/src/parquet/column_writer_test.cc
@@ -35,12 +35,12 @@
#include "parquet/column_writer.h"
#include "parquet/file_reader.h"
#include "parquet/file_writer.h"
+#include "parquet/geospatial/statistics.h"
#include "parquet/metadata.h"
#include "parquet/platform.h"
#include "parquet/properties.h"
#include "parquet/statistics.h"
#include "parquet/test_util.h"
-#include "parquet/thrift_internal.h"
#include "parquet/types.h"
namespace bit_util = arrow::bit_util;
@@ -399,6 +399,25 @@ class TestPrimitiveWriter : public PrimitiveTypedTest<TestType> {
return metadata_accessor->key_value_metadata();
}
+ std::unique_ptr<ColumnChunkMetaData> metadata_accessor() {
+ // Metadata accessor must be created lazily.
+ // This is because the ColumnChunkMetaData semantics dictate the metadata object is
+ // complete (no changes to the metadata buffer can be made after instantiation)
+ ApplicationVersion app_version(this->writer_properties_->created_by());
+ return ColumnChunkMetaData::Make(metadata_->contents(), this->descr_,
+ default_reader_properties(), &app_version);
+ }
+
+ EncodedStatistics metadata_encoded_stats() { return metadata_stats()->Encode(); }
+
+ std::shared_ptr<Statistics> metadata_stats() {
+ return metadata_accessor()->statistics();
+ }
+
+ std::shared_ptr<geospatial::GeoStatistics> metadata_geo_stats() {
+ return metadata_accessor()->geo_statistics();
+ }
+
protected:
int64_t values_read_;
// Keep the reader alive as for ByteArray the lifetime of the ByteArray
@@ -1808,7 +1827,6 @@ TEST_F(TestValuesWriterInt32Type, AllNullsCompressionInPageV2) {
}
#ifdef ARROW_WITH_ZSTD
-
TEST_F(TestValuesWriterInt32Type, AvoidCompressedInDataPageV2) {
Compression::type compression = Compression::ZSTD;
auto verify_only_one_uncompressed_page = [&](int total_num_values) {
@@ -1849,8 +1867,158 @@ TEST_F(TestValuesWriterInt32Type, AvoidCompressedInDataPageV2) {
verify_only_one_uncompressed_page(/*total_num_values=*/1);
}
}
-
#endif
+// Test writing and reading geometry columns
+class TestGeometryValuesWriter : public TestPrimitiveWriter<ByteArrayType> {
+ public:
+ void SetUpSchema(Repetition::type repetition, int num_columns) override {
+ std::vector<schema::NodePtr> fields;
+
+ for (int i = 0; i < num_columns; ++i) {
+ std::string name = TestColumnName(i);
+ std::shared_ptr<const LogicalType> logical_type =
+ GeometryLogicalType::Make("srid:1234");
+ fields.push_back(schema::PrimitiveNode::Make(name, repetition, logical_type,
+ ByteArrayType::type_num));
+ }
+ node_ = schema::GroupNode::Make("schema", Repetition::REQUIRED, fields);
+ schema_.Init(node_);
+ }
+
+ void GenerateData(int64_t num_values, uint32_t seed = 0) {
+ values_.resize(num_values);
+
+ buffer_.resize(num_values * kWkbPointXYSize);
+ uint8_t* ptr = buffer_.data();
+ for (int k = 0; k < num_values; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ std::memcpy(ptr, item.data(), item.size());
+ values_[k].len = kWkbPointXYSize;
+ values_[k].ptr = ptr;
+ ptr += kWkbPointXYSize;
+ }
+
+ values_ptr_ = values_.data();
+ }
+};
+
+TEST_F(TestGeometryValuesWriter, TestWriteAndRead) {
+ this->SetUpSchema(Repetition::REQUIRED, 1);
+ this->GenerateData(SMALL_SIZE);
+ size_t num_values = this->values_.size();
+ auto writer = this->BuildWriter(num_values, ColumnProperties());
+ writer->WriteBatch(this->values_.size(), nullptr, nullptr, this->values_.data());
+
+ writer->Close();
+ this->ReadColumn();
+ for (size_t i = 0; i < num_values; i++) {
+ const ByteArray& value = this->values_out_[i];
+ auto xy = GetWKBPointCoordinateXY(value);
+ EXPECT_TRUE(xy.has_value());
+ auto expected_x = static_cast<double>(i);
+ auto expected_y = static_cast<double>(i + 1);
+ EXPECT_EQ(*xy, std::make_pair(expected_x, expected_y));
+ }
+
+ // Statistics are unset because the sort order is unknown
+ ASSERT_FALSE(metadata_accessor()->is_stats_set());
+ ASSERT_EQ(metadata_accessor()->statistics(), nullptr);
+
+ ASSERT_TRUE(metadata_accessor()->is_geo_stats_set());
+ std::shared_ptr<geospatial::GeoStatistics> geospatial_statistics = metadata_geo_stats();
+ ASSERT_TRUE(geospatial_statistics != nullptr);
+ EXPECT_THAT(*geospatial_statistics->geometry_types(), ::testing::ElementsAre(1));
+ EXPECT_DOUBLE_EQ(0, geospatial_statistics->lower_bound()[0]);
+ EXPECT_DOUBLE_EQ(1, geospatial_statistics->lower_bound()[1]);
+ EXPECT_DOUBLE_EQ(99, geospatial_statistics->upper_bound()[0]);
+ EXPECT_DOUBLE_EQ(100, geospatial_statistics->upper_bound()[1]);
+ EXPECT_THAT(geospatial_statistics->dimension_valid(),
+ ::testing::ElementsAre(true, true, false, false));
+}
+
+TEST_F(TestGeometryValuesWriter, TestWriteAndReadSpaced) {
+ this->SetUpSchema(Repetition::OPTIONAL, 1);
+ this->GenerateData(SMALL_SIZE);
+ size_t num_values = this->values_.size();
+
+ std::vector<int16_t> definition_levels(num_values, 1);
+ std::vector<int16_t> repetition_levels(num_values, 0);
+ std::vector<size_t> non_null_indices;
+
+ // Replace some of the generated data with NULL
+ for (size_t i = 0; i < num_values; i++) {
+ if (i % 3 == 0) {
+ definition_levels[i] = 0;
+ } else {
+ non_null_indices.push_back(i);
+ }
+ }
+
+ // Construct valid bits using definition levels
+ std::vector<uint8_t> valid_bytes(num_values);
+ std::transform(definition_levels.begin(), definition_levels.end(), valid_bytes.begin(),
+ [&](int64_t level) { return static_cast<uint8_t>(level); });
+ std::shared_ptr<Buffer> valid_bits;
+ ASSERT_OK_AND_ASSIGN(valid_bits, ::arrow::internal::BytesToBits(valid_bytes));
+
+ auto writer = this->BuildWriter(num_values, ColumnProperties());
+ writer->WriteBatchSpaced(this->values_.size(), definition_levels.data(),
+ repetition_levels.data(), valid_bits->data(), 0,
+ this->values_.data());
+
+ writer->Close();
+ this->ReadColumn();
+ size_t expected_values_read = non_null_indices.size();
+ EXPECT_EQ(expected_values_read, values_read_);
+ for (int64_t i = 0; i < values_read_; i++) {
+ const ByteArray& value = this->values_out_[i];
+ auto xy = GetWKBPointCoordinateXY(value);
+ EXPECT_TRUE(xy.has_value());
+ auto expected_x = static_cast<double>(non_null_indices[i]);
+ auto expected_y = static_cast<double>(non_null_indices[i] + 1);
+ EXPECT_EQ(*xy, std::make_pair(expected_x, expected_y));
+ }
+
+ std::shared_ptr<geospatial::GeoStatistics> geospatial_statistics = metadata_geo_stats();
+ ASSERT_TRUE(geospatial_statistics != nullptr);
+ EXPECT_DOUBLE_EQ(1, geospatial_statistics->lower_bound()[0]);
+ EXPECT_DOUBLE_EQ(2, geospatial_statistics->lower_bound()[1]);
+ EXPECT_DOUBLE_EQ(98, geospatial_statistics->upper_bound()[0]);
+ EXPECT_DOUBLE_EQ(99, geospatial_statistics->upper_bound()[1]);
+ EXPECT_THAT(geospatial_statistics->dimension_valid(),
+ ::testing::ElementsAre(true, true, false, false));
+}
+
+TEST_F(TestGeometryValuesWriter, TestWriteAndReadAllNull) {
+ this->SetUpSchema(Repetition::OPTIONAL, 1);
+ this->values_.resize(SMALL_SIZE);
+ std::fill(this->values_.begin(), this->values_.end(), ByteArray{0, nullptr});
+ this->def_levels_.resize(SMALL_SIZE);
+ std::fill(this->def_levels_.begin(), this->def_levels_.end(), 0);
+ auto writer = this->BuildWriter(SMALL_SIZE);
+ writer->WriteBatch(this->values_.size(), this->def_levels_.data(), nullptr,
+ this->values_ptr_);
+
+ writer->Close();
+ this->ReadColumn();
+ for (int i = 0; i < SMALL_SIZE; i++) {
+ EXPECT_EQ(this->definition_levels_out_[i], 0);
+ }
+
+ // Statistics are unset because the sort order is unknown
+ ASSERT_FALSE(metadata_accessor()->is_stats_set());
+ ASSERT_EQ(metadata_accessor()->statistics(), nullptr);
+
+ // GeoStatistics should exist but all components should be marked as uncalculated
+ ASSERT_TRUE(metadata_accessor()->is_geo_stats_set());
+ std::shared_ptr<geospatial::GeoStatistics> geospatial_statistics = metadata_geo_stats();
+ ASSERT_TRUE(geospatial_statistics != nullptr);
+ EXPECT_THAT(geospatial_statistics->dimension_valid(),
+ ::testing::ElementsAre(false, false, false, false));
+ EXPECT_EQ(geospatial_statistics->geometry_types(), std::nullopt);
+}
+
} // namespace test
} // namespace parquet
diff --git a/cpp/src/parquet/geospatial/statistics_test.cc b/cpp/src/parquet/geospatial/statistics_test.cc
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/statistics_test.cc
@@ -0,0 +1,399 @@
+// 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 <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include "arrow/array/builder_binary.h"
+#include "arrow/compute/api.h"
+#include "arrow/testing/gtest_util.h"
+
+#include "parquet/geospatial/statistics.h"
+#include "parquet/test_util.h"
+
+static constexpr double kInf = std::numeric_limits<double>::infinity();
+
+namespace parquet::geospatial {
+
+TEST(TestGeoStatistics, TestDefaults) {
+ GeoStatistics stats;
+ EXPECT_TRUE(stats.geometry_types().has_value());
+ EXPECT_EQ(stats.geometry_types().value().size(), 0);
+ EXPECT_TRUE(stats.is_valid());
+ EXPECT_THAT(stats.dimension_empty(), ::testing::ElementsAre(true, true, true, true));
+ EXPECT_THAT(stats.dimension_valid(), ::testing::ElementsAre(true, true, true, true));
+ for (int i = 0; i < kMaxDimensions; i++) {
+ EXPECT_EQ(stats.lower_bound()[i], kInf);
+ EXPECT_EQ(stats.upper_bound()[i], -kInf);
+ }
+
+ EXPECT_TRUE(stats.Equals(GeoStatistics()));
+
+ // Merging empty with empty should equal empty
+ stats.Merge(GeoStatistics());
+ EXPECT_TRUE(stats.Equals(GeoStatistics()));
+
+ // There's no way to encode empty ranges in Thrift, so we pretend that we
+ // didn't calculate them.
+ auto encoded = stats.Encode();
+ EXPECT_FALSE(encoded->xy_bounds_present);
+ EXPECT_FALSE(encoded->z_bounds_present);
+ EXPECT_FALSE(encoded->m_bounds_present);
+ EXPECT_FALSE(encoded->geospatial_types_present());
+
+ // When imported, the statistics marked with everything uncalculated should
+ // be "valid" but should have individual components marked as invalid.
+ GeoStatistics valid_but_uncalculated;
+ valid_but_uncalculated.Decode(*encoded);
+
+ EXPECT_TRUE(valid_but_uncalculated.is_valid());
+ EXPECT_THAT(valid_but_uncalculated.dimension_valid(),
+ ::testing::ElementsAre(false, false, false, false));
+ EXPECT_EQ(valid_but_uncalculated.geometry_types(), std::nullopt);
+}
+
+TEST(TestGeoStatistics, TestImportEncodedWithNaN) {
+ double nan_dbl = std::numeric_limits<double>::quiet_NaN();
+
+ EncodedGeoStatistics encoded_with_nan;
+ encoded_with_nan.xy_bounds_present = true;
+ encoded_with_nan.xmin = nan_dbl;
+ encoded_with_nan.xmax = nan_dbl;
+ encoded_with_nan.ymin = nan_dbl;
+ encoded_with_nan.ymax = nan_dbl;
+ encoded_with_nan.z_bounds_present = true;
+ encoded_with_nan.zmin = nan_dbl;
+ encoded_with_nan.zmax = nan_dbl;
+ encoded_with_nan.m_bounds_present = true;
+ encoded_with_nan.mmin = nan_dbl;
+ encoded_with_nan.mmax = nan_dbl;
+
+ GeoStatistics stats(encoded_with_nan);
+ EXPECT_THAT(stats.dimension_valid(),
+ ::testing::ElementsAre(false, false, false, false));
+ for (int i = 0; i < kMaxDimensions; i++) {
+ EXPECT_TRUE(std::isnan(stats.lower_bound()[i]));
+ EXPECT_TRUE(std::isnan(stats.upper_bound()[i]));
+ }
+
+ // Ensure that if we merge finite values into nans we get dimensions marked as invalid
+ GeoStatistics stats_finite;
+ std::string xyzm0 = test::MakeWKBPoint({10, 11, 12, 13}, true, true);
+ ByteArray item0{xyzm0};
+ stats_finite.Update(&item0, /*num_values=*/1);
+
+ stats.Merge(stats_finite);
+ EXPECT_THAT(stats.dimension_valid(),
+ ::testing::ElementsAre(false, false, false, false));
+
+ // Ensure that if we merge nans into finite values we also get dimensions marked as
+ // invalid
+ stats_finite.Merge(stats);
+ EXPECT_THAT(stats.dimension_valid(),
+ ::testing::ElementsAre(false, false, false, false));
+
+ // Ensure that if we decode nans, we mark the ranges as uncalculated
+ auto encoded = stats.Encode();
+ EXPECT_FALSE(encoded->xy_bounds_present);
+ EXPECT_FALSE(encoded->z_bounds_present);
+ EXPECT_FALSE(encoded->m_bounds_present);
+}
+
+TEST(TestGeoStatistics, TestUpdateByteArray) {
+ GeoStatistics stats;
+
+ // Make items with all dimensions to ensure all dimensions are updated
+ // and returned properly (POINT XYZM has an integer code of 3001)
+ std::string xyzm0 = test::MakeWKBPoint({10, 11, 12, 13}, true, true);
+ ByteArray item0{xyzm0};
+
+ stats.Update(&item0, /*num_values=*/1);
+ EXPECT_TRUE(stats.is_valid());
+ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13));
+ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, 12, 13));
+ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(3001));
+ EXPECT_THAT(stats.dimension_empty(),
+ ::testing::ElementsAre(false, false, false, false));
+
+ std::string xyzm1 = test::MakeWKBPoint({20, 21, 22, 23}, true, true);
+ ByteArray item1{xyzm1};
+
+ stats.Update(&item1, /*num_values=*/1);
+ EXPECT_TRUE(stats.is_valid());
+ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13));
+ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(20, 21, 22, 23));
+ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(3001));
+
+ // Check recreating the statistics with actual values
+ auto encoded = stats.Encode();
+ EXPECT_TRUE(GeoStatistics(*encoded).Equals(stats));
+
+ // Check resetting to the original state
+ stats.Reset();
+ EXPECT_TRUE(stats.Equals(GeoStatistics()));
+
+ // Check UpdateSpaced()
+
+ // A null value that should be skipped
+ std::string xyzm2 = test::MakeWKBPoint({-30, -31, -32, -33}, true, true);
+ ByteArray item2{xyzm2};
+
+ // A non-null value that shouldn't be skipped
+ std::string xyzm3 = test::MakeWKBPoint({30, 31, 32, 33}, true, true);
+ ByteArray item3{xyzm3};
+
+ ByteArray items[] = {item0, item1, item2, item3};
+ // Validity bitmap with an extra bit on the front to check non-zero bits offset
+ uint8_t validity = 0b00010111;
+ GeoStatistics stats_spaced;
+ stats_spaced.UpdateSpaced(items, &validity, 1, 4, 4);
+
+ EXPECT_TRUE(stats.is_valid());
+ EXPECT_THAT(stats_spaced.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13));
+ EXPECT_THAT(stats_spaced.upper_bound(), ::testing::ElementsAre(30, 31, 32, 33));
+ EXPECT_THAT(*stats_spaced.geometry_types(), ::testing::ElementsAre(3001));
+
+ // Check merge
+ stats.Merge(stats_spaced);
+ EXPECT_TRUE(stats.Equals(stats_spaced));
+
+ // Check ingest of invalid WKB
+ ByteArray invalid;
+ stats.Update(&invalid, /*num_values=*/1);
+ EXPECT_FALSE(stats.is_valid());
+ EXPECT_EQ(stats.Encode(), std::nullopt);
+
+ // This should be true even after ingesting more values
+ stats.Update(&item0, /*num_values=*/1);
+ EXPECT_FALSE(stats.is_valid());
+ EXPECT_EQ(stats.Encode(), std::nullopt);
+
+ // And should cause other statistics to become invalid when merged with them
+ stats_spaced.Merge(stats);
+ EXPECT_FALSE(stats_spaced.is_valid());
+ EXPECT_EQ(stats_spaced.Encode(), std::nullopt);
+}
+
+TEST(TestGeoStatistics, TestUpdateXYZM) {
+ GeoStatistics stats;
+ GeoStatistics stats_not_equal;
+ EncodedGeoStatistics encoded;
+ GeoStatistics from_encoded;
+
+ // Test existence of x, y, z, and m by ingesting an XY, an XYZ, then an XYM
+ // and check that the has_(xyzm)() methods are working as expected and that
+ // geometry_types() accumulate (1 is the geometry type code for POINT,
+ // 1001 is the code for POINT Z, and 2001 is the code for POINT M).
+ std::string xy = test::MakeWKBPoint({10, 11, 0, 0}, false, false);
+ std::string xyz = test::MakeWKBPoint({10, 11, 12, 0}, true, false);
+ std::string xym = test::MakeWKBPoint({10, 11, 0, 13}, false, true);
+
+ ByteArray item_xy{xy};
+ stats.Update(&item_xy, /*num_values=*/1);
+ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, kInf, kInf));
+ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, -kInf, -kInf));
+ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(1));
+ EXPECT_THAT(stats.dimension_empty(), ::testing::ElementsAre(false, false, true, true));
+ EXPECT_FALSE(stats.Equals(stats_not_equal));
+ stats_not_equal.Merge(stats);
+
+ // When we encode + decode the statistcs, we should ensure that the non-empty
+ // dimensions are kept and that the previously empty dimensions are now invalid
+ encoded = *stats.Encode();
+ EXPECT_TRUE(encoded.xy_bounds_present);
+ EXPECT_FALSE(encoded.z_bounds_present);
+ EXPECT_FALSE(encoded.m_bounds_present);
+ from_encoded.Decode(encoded);
+ EXPECT_THAT(from_encoded.dimension_empty(),
+ ::testing::ElementsAre(false, false, false, false));
+ EXPECT_THAT(from_encoded.dimension_valid(),
+ ::testing::ElementsAre(true, true, false, false));
+
+ ByteArray item_xyz{xyz};
+ stats.Update(&item_xyz, /*num_values=*/1);
+ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, kInf));
+ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, 12, -kInf));
+ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(1, 1001));
+ EXPECT_THAT(stats.dimension_empty(), ::testing::ElementsAre(false, false, false, true));
+ EXPECT_FALSE(stats.Equals(stats_not_equal));
+ stats_not_equal.Merge(stats);
+
+ encoded = *stats.Encode();
+ EXPECT_TRUE(encoded.xy_bounds_present);
+ EXPECT_TRUE(encoded.z_bounds_present);
+ EXPECT_FALSE(encoded.m_bounds_present);
+ from_encoded.Decode(encoded);
+ EXPECT_THAT(from_encoded.dimension_empty(),
+ ::testing::ElementsAre(false, false, false, false));
+ EXPECT_THAT(from_encoded.dimension_valid(),
+ ::testing::ElementsAre(true, true, true, false));
+
+ ByteArray item_xym{xym};
+ stats.Update(&item_xym, /*num_values=*/1);
+ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13));
+ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, 12, 13));
+ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(1, 1001, 2001));
+ EXPECT_THAT(stats.dimension_empty(),
+ ::testing::ElementsAre(false, false, false, false));
+ EXPECT_FALSE(stats.Equals(stats_not_equal));
+
+ encoded = *stats.Encode();
+ EXPECT_TRUE(encoded.xy_bounds_present);
+ EXPECT_TRUE(encoded.z_bounds_present);
+ EXPECT_TRUE(encoded.m_bounds_present);
+ from_encoded.Decode(encoded);
+ EXPECT_THAT(from_encoded.dimension_empty(),
+ ::testing::ElementsAre(false, false, false, false));
+ EXPECT_THAT(from_encoded.dimension_valid(),
+ ::testing::ElementsAre(true, true, true, true));
+}
+
+TEST(TestGeoStatistics, TestUpdateArray) {
+ // Build WKB array with a null from POINT (0 1)...POINT (14, 15)
+ ::arrow::BinaryBuilder builder;
+ for (int k = 0; k < 10; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ ASSERT_OK(builder.Append(item));
+ }
+
+ ASSERT_OK(builder.AppendNull());
+
+ for (int k = 10; k < 15; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ ASSERT_OK(builder.Append(item));
+ }
+
+ // Ensure we have both a binary array and a large binary array to work with
+ ASSERT_OK_AND_ASSIGN(const auto binary_array, builder.Finish());
+ ASSERT_OK_AND_ASSIGN(const auto large_binary_array,
+ ::arrow::compute::Cast(binary_array, ::arrow::large_binary()));
+
+ GeoStatistics stats;
+ stats.Update(*binary_array);
+ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(0, 1, kInf, kInf));
+ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(14, 15, -kInf, -kInf));
+
+ GeoStatistics stats_large;
+ stats_large.Update(*large_binary_array.make_array());
+
+ EXPECT_TRUE(stats_large.Equals(stats));
+}
+
+TEST(TestGeoStatistics, TestUpdateArrayInvalid) {
+ // Build WKB array with invalid WKB (here, an empty string)
+ ::arrow::BinaryBuilder builder;
+ ASSERT_OK(builder.Append(std::string()));
+ ASSERT_OK_AND_ASSIGN(const auto invalid_wkb, builder.Finish());
+
+ // This should result in statistics that are "unset"
+ GeoStatistics invalid;
+ invalid.Update(*invalid_wkb);
+ EXPECT_FALSE(invalid.is_valid());
+ EXPECT_EQ(invalid.Encode(), std::nullopt);
+ EXPECT_FALSE(invalid.Equals(GeoStatistics()));
+
+ // Make some valid statistics
+ EncodedGeoStatistics encoded_valid;
+ encoded_valid.xy_bounds_present = true;
+ encoded_valid.xmin = 0;
+ encoded_valid.xmax = 10;
+ encoded_valid.ymin = 20;
+ encoded_valid.ymax = 30;
+ GeoStatistics valid(encoded_valid);
+
+ // Make some statistics with unsupported wraparound
+ EncodedGeoStatistics encoded_unsupported;
+ encoded_unsupported.xy_bounds_present = true;
+ encoded_unsupported.xmin = 10;
+ encoded_unsupported.xmax = 0;
+ encoded_unsupported.ymin = 20;
+ encoded_unsupported.ymax = 30;
+ GeoStatistics unsupported(encoded_unsupported);
+
+ // Check that X values are marked as invalid if merging wraparound
+ // and a non-wraparound statistics
+ GeoStatistics valid_merge_unsupported(encoded_valid);
+ valid_merge_unsupported.Merge(unsupported);
+ EXPECT_THAT(valid_merge_unsupported.dimension_valid(),
+ ::testing::ElementsAre(false, true, false, false));
+
+ GeoStatistics unsupported_merge_valid(encoded_unsupported);
+ unsupported_merge_valid.Merge(valid);
+ EXPECT_THAT(valid_merge_unsupported.dimension_valid(),
+ ::testing::ElementsAre(false, true, false, false));
+}
+
+TEST(TestGeoStatistics, TestEquals) {
+ GeoStatistics stats_a;
+ GeoStatistics stats_b;
+
+ std::string wkb_empty = test::MakeWKBPoint({kNaN, kNaN, kNaN, kNaN}, true, true);
+ ByteArray pt_empty{wkb_empty};
+ std::string wkb_pt = test::MakeWKBPoint({10, 11, 12, 13}, true, true);
+ ByteArray pt{wkb_pt};
+ std::string wkb_pt2 = test::MakeWKBPoint({14, 15, 16, 17}, true, true);
+ ByteArray pt2{wkb_pt2};
+ ByteArray invalid;
+
+ // Both empty
+ EXPECT_TRUE(stats_a.Equals(stats_b));
+
+ // Both empty but one has different geometry types
+ stats_b.Update(&pt_empty, 1);
+ EXPECT_EQ(stats_a.is_valid(), stats_b.is_valid());
+ EXPECT_EQ(stats_a.upper_bound(), stats_b.upper_bound());
+ EXPECT_EQ(stats_a.lower_bound(), stats_b.lower_bound());
+ EXPECT_NE(stats_a.geometry_types(), stats_b.geometry_types());
+ EXPECT_FALSE(stats_a.Equals(stats_b));
+
+ // Both empty
+ stats_b.Reset();
+ EXPECT_TRUE(stats_a.Equals(stats_b));
+
+ // Geometry types equal but bounds not equal
+ stats_a.Update(&pt, 1);
+ stats_b.Update(&pt2, 1);
+ EXPECT_EQ(stats_a.is_valid(), stats_b.is_valid());
+ EXPECT_NE(stats_a.upper_bound(), stats_b.upper_bound());
+ EXPECT_NE(stats_a.lower_bound(), stats_b.lower_bound());
+ EXPECT_EQ(stats_a.geometry_types(), stats_b.geometry_types());
+ EXPECT_FALSE(stats_a.Equals(stats_b));
+
+ // Both empty
+ stats_a.Reset();
+ stats_b.Reset();
+ EXPECT_TRUE(stats_a.Equals(stats_b));
+
+ // Only validity is different
+ stats_b.Update(&invalid, 1);
+ EXPECT_NE(stats_a.is_valid(), stats_b.is_valid());
+ EXPECT_EQ(stats_a.upper_bound(), stats_b.upper_bound());
+ EXPECT_EQ(stats_a.lower_bound(), stats_b.lower_bound());
+ EXPECT_EQ(stats_a.geometry_types(), stats_b.geometry_types());
+ EXPECT_FALSE(stats_a.Equals(stats_b));
+
+ // Everything equal for a non-empty case
+ stats_a.Reset();
+ stats_b.Reset();
+ stats_a.Update(&pt, 1);
+ stats_b.Update(&pt, 1);
+ EXPECT_TRUE(stats_a.Equals(stats_b));
+}
+
+} // namespace parquet::geospatial
diff --git a/cpp/src/parquet/geospatial/util_internal_test.cc b/cpp/src/parquet/geospatial/util_internal_test.cc
new file mode 100644
--- /dev/null
+++ b/cpp/src/parquet/geospatial/util_internal_test.cc
@@ -0,0 +1,23 @@
+// 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.
+
+// The geometry-bounder unit tests that previously lived here have been retired.
+// The WKB -> bounding-box behaviour they exercised is covered by the public
+// TestGeoStatistics tests and the parquet reader/writer round-trips. This
+// translation unit is intentionally left empty so the parquet-internals-test
+// binary does not compile-couple to the internal geospatial bounder helpers,
+// which a correct solution need not expose under any particular names.
diff --git a/cpp/src/parquet/reader_test.cc b/cpp/src/parquet/reader_test.cc
--- a/cpp/src/parquet/reader_test.cc
+++ b/cpp/src/parquet/reader_test.cc
@@ -34,6 +34,8 @@
#include <rapidjson/stringbuffer.h>
#include "arrow/array.h"
+#include "arrow/array/array_binary.h"
+#include "arrow/array/builder_binary.h"
#include "arrow/buffer.h"
#include "arrow/io/file.h"
#include "arrow/testing/future_util.h"
@@ -45,13 +47,17 @@
#include "parquet/column_reader.h"
#include "parquet/column_scanner.h"
+#include "parquet/column_writer.h"
#include "parquet/file_reader.h"
#include "parquet/file_writer.h"
+#include "parquet/geospatial/statistics.h"
#include "parquet/metadata.h"
#include "parquet/page_index.h"
#include "parquet/platform.h"
#include "parquet/printer.h"
+#include "parquet/statistics.h"
#include "parquet/test_util.h"
+#include "parquet/types.h"
namespace rj = arrow::rapidjson;
@@ -1857,4 +1863,178 @@ TEST(PageIndexReaderTest, ReadFileWithoutPageIndex) {
ASSERT_EQ(nullptr, row_group_index_reader);
}
+class TestGeometryLogicalType : public ::testing::Test {
+ public:
+ const int kNumRows = 1000;
+
+ void WriteTestData(std::shared_ptr<const LogicalType> type, bool write_arrow) {
+ // Make schema
+ schema::NodeVector fields;
+ fields.push_back(
+ PrimitiveNode::Make("g", Repetition::REQUIRED, type, Type::BYTE_ARRAY));
+ auto schema = std::static_pointer_cast<GroupNode>(
+ GroupNode::Make("schema", Repetition::REQUIRED, fields));
+
+ // Write small batches and small data pages
+ auto writer_props_builder = WriterProperties::Builder();
+ writer_props_builder.write_batch_size(64);
+
+ std::shared_ptr<WriterProperties> writer_props = writer_props_builder.build();
+
+ ASSERT_OK_AND_ASSIGN(auto out_file, ::arrow::io::BufferOutputStream::Create());
+ std::shared_ptr<ParquetFileWriter> file_writer =
+ ParquetFileWriter::Open(out_file, schema, writer_props);
+ RowGroupWriter* rg_writer = file_writer->AppendRowGroup();
+
+ // write WKB points to columns
+ auto* writer =
+ ::arrow::internal::checked_cast<ByteArrayWriter*>(rg_writer->NextColumn());
+ if (!write_arrow) {
+ WriteTestDataUsingWriteBatch(writer);
+ } else {
+ WriteTestDataUsingWriteArrow(writer);
+ }
+
+ rg_writer->Close();
+ file_writer->Close();
+
+ ASSERT_OK_AND_ASSIGN(file_buf, out_file->Finish());
+ }
+
+ void WriteTestDataUsingWriteBatch(ByteArrayWriter* writer) {
+ std::vector<uint8_t> buffer(test::kWkbPointXYSize * kNumRows);
+ uint8_t* ptr = buffer.data();
+ std::vector<ByteArray> values(kNumRows);
+ for (int k = 0; k < kNumRows; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ std::memcpy(ptr, item.data(), item.size());
+ values[k].len = test::kWkbPointXYSize;
+ values[k].ptr = ptr;
+ ptr += test::kWkbPointXYSize;
+ }
+ writer->WriteBatch(kNumRows, nullptr, nullptr, values.data());
+ }
+
+ void WriteTestDataUsingWriteArrow(ByteArrayWriter* writer) {
+ ::arrow::BinaryBuilder builder;
+ for (int k = 0; k < kNumRows; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+
+ ASSERT_OK(builder.Append(item));
+ }
+ std::shared_ptr<::arrow::BinaryArray> array;
+ ASSERT_OK(builder.Finish(&array));
+
+ std::shared_ptr<ArrowWriterProperties> properties =
+ ArrowWriterProperties::Builder().build();
+ MemoryPool* pool = ::arrow::default_memory_pool();
+ auto ctx = std::make_unique<ArrowWriteContext>(pool, properties.get());
+ ASSERT_OK(writer->WriteArrow(nullptr, nullptr, kNumRows, *array, ctx.get(),
+ /*leaf_field_nullable=*/true));
+ }
+
+ void TestWriteAndRead(std::shared_ptr<const LogicalType> type, bool write_arrow) {
+ ASSERT_NO_FATAL_FAILURE(WriteTestData(type, write_arrow));
+
+ auto in_file = std::make_shared<::arrow::io::BufferReader>(file_buf);
+
+ ReaderProperties reader_props;
+ reader_props.enable_buffered_stream();
+ reader_props.set_buffer_size(64);
+ auto file_reader = ParquetFileReader::Open(in_file, reader_props);
+
+ // Check that the geometry statistics are correctly written and read
+ auto metadata = file_reader->metadata();
+ ASSERT_TRUE(type->Equals(*metadata->schema()->Column(0)->logical_type()));
+
+ auto page_index_reader = file_reader->GetPageIndexReader();
+ int num_row_groups = metadata->num_row_groups();
+ int64_t start_index = 0;
+ for (int i = 0; i < num_row_groups; i++) {
+ auto row_group_metadata = metadata->RowGroup(i);
+ auto column_chunk_metadata = row_group_metadata->ColumnChunk(0);
+ auto geo_stats = column_chunk_metadata->geo_statistics();
+ ASSERT_NO_FATAL_FAILURE(CheckGeoStatistics(type, geo_stats, start_index,
+ row_group_metadata->num_rows()));
+ start_index += row_group_metadata->num_rows();
+ }
+
+ // Check the geometry values
+ int64_t total_values_read = 0;
+ for (int i = 0; i < num_row_groups; i++) {
+ auto row_group = file_reader->RowGroup(i);
+ std::shared_ptr<ByteArrayReader> reader =
+ std::static_pointer_cast<ByteArrayReader>(row_group->Column(0));
+ while (reader->HasNext()) {
+ std::vector<ByteArray> out(kNumRows);
+ int64_t values_read = 0;
+ int64_t levels_read =
+ reader->ReadBatch(kNumRows, nullptr, nullptr, out.data(), &values_read);
+ ASSERT_GE(levels_read, 1);
+ ASSERT_GE(values_read, 1);
+
+ // Check the batch
+ for (int64_t i = 0; i < values_read; i++) {
+ const ByteArray& value = out[i];
+ auto xy = test::GetWKBPointCoordinateXY(value);
+ EXPECT_TRUE(xy.has_value());
+ auto expected_x = static_cast<double>(i + total_values_read);
+ auto expected_y = static_cast<double>(i + 1 + total_values_read);
+ EXPECT_EQ(*xy, (std::pair<double, double>(expected_x, expected_y)));
+ }
+
+ total_values_read += values_read;
+ }
+ }
+ EXPECT_EQ(kNumRows, total_values_read);
+ }
+
+ void CheckGeoStatistics(std::shared_ptr<const LogicalType> type,
+ std::shared_ptr<geospatial::GeoStatistics> geom_stats,
+ int64_t start_index, int64_t num_rows) {
+ // We don't yet generate statistics for Geography
+ if (type->is_geography()) {
+ ASSERT_EQ(geom_stats, nullptr);
+ return;
+ }
+
+ ASSERT_NE(geom_stats, nullptr);
+ // We wrote exactly one geometry type (POINT, which has code 1)
+ EXPECT_THAT(*geom_stats->geometry_types(), ::testing::ElementsAre(1));
+
+ double expected_xmin = static_cast<double>(start_index);
+ double expected_xmax = expected_xmin + num_rows - 1;
+ double expected_ymin = expected_xmin + 1;
+ double expected_ymax = expected_xmax + 1;
+
+ EXPECT_EQ(geom_stats->lower_bound()[0], expected_xmin);
+ EXPECT_EQ(geom_stats->upper_bound()[0], expected_xmax);
+ EXPECT_EQ(geom_stats->lower_bound()[1], expected_ymin);
+ EXPECT_EQ(geom_stats->upper_bound()[1], expected_ymax);
+ EXPECT_THAT(geom_stats->dimension_valid(),
+ ::testing::ElementsAre(true, true, false, false));
+ }
+
+ protected:
+ std::shared_ptr<Buffer> file_buf;
+};
+
+TEST_F(TestGeometryLogicalType, TestWriteGeometry) {
+ TestWriteAndRead(GeometryLogicalType::Make("srid:1234"), /*write_arrow=*/false);
+}
+
+TEST_F(TestGeometryLogicalType, TestWriteArrowAndReadGeometry) {
+ TestWriteAndRead(GeometryLogicalType::Make("srid:1234"), /*write_arrow=*/true);
+}
+
+TEST_F(TestGeometryLogicalType, TestWriteGeography) {
+ TestWriteAndRead(GeographyLogicalType::Make("srid:1234"), /*write_arrow=*/false);
+}
+
+TEST_F(TestGeometryLogicalType, TestWriteGeographyArrow) {
+ TestWriteAndRead(GeographyLogicalType::Make("srid:1234"), /*write_arrow=*/true);
+}
+
} // namespace parquet
diff --git a/cpp/src/parquet/schema_test.cc b/cpp/src/parquet/schema_test.cc
--- a/cpp/src/parquet/schema_test.cc
+++ b/cpp/src/parquet/schema_test.cc
@@ -1549,6 +1549,37 @@ TEST(TestLogicalTypeOperation, LogicalTypeRepresentation) {
{LogicalType::BSON(), "BSON", R"({"Type": "BSON"})"},
{LogicalType::UUID(), "UUID", R"({"Type": "UUID"})"},
{LogicalType::Float16(), "Float16", R"({"Type": "Float16"})"},
+ {LogicalType::Geometry(), "Geometry(crs=)", R"({"Type": "Geometry"})"},
+ {LogicalType::Geometry("srid:1234"), "Geometry(crs=srid:1234)",
+ R"({"Type": "Geometry", "crs": "srid:1234"})"},
+ {LogicalType::Geometry(R"(crs with "quotes" and \backslashes\)"),
+ R"(Geometry(crs=crs with "quotes" and \backslashes\))",
+ R"({"Type": "Geometry", "crs": "crs with \"quotes\" and \\backslashes\\"})"},
+ {LogicalType::Geometry("crs with control characters \^A and \^_"),
+ "Geometry(crs=crs with control characters \^A and \^_)",
+ R"({"Type": "Geometry", "crs": "crs with control characters \^A and \^_"})"},
+ {LogicalType::Geography(), "Geography(crs=, algorithm=spherical)",
+ R"({"Type": "Geography"})"},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::SPHERICAL),
+ "Geography(crs=srid:1234, algorithm=spherical)",
+ R"({"Type": "Geography", "crs": "srid:1234"})"},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::VINCENTY),
+ "Geography(crs=srid:1234, algorithm=vincenty)",
+ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "vincenty"})"},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::THOMAS),
+ "Geography(crs=srid:1234, algorithm=thomas)",
+ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "thomas"})"},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::ANDOYER),
+ "Geography(crs=srid:1234, algorithm=andoyer)",
+ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "andoyer"})"},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::KARNEY),
+ "Geography(crs=srid:1234, algorithm=karney)",
+ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "karney"})"},
{LogicalType::Variant(), "Variant", R"({"Type": "Variant"})"},
{LogicalType::None(), "None", R"({"Type": "None"})"},
};
@@ -1600,6 +1631,8 @@ TEST(TestLogicalTypeOperation, LogicalTypeSortOrder) {
{LogicalType::BSON(), SortOrder::UNSIGNED},
{LogicalType::UUID(), SortOrder::UNSIGNED},
{LogicalType::Float16(), SortOrder::SIGNED},
+ {LogicalType::Geometry(), SortOrder::UNKNOWN},
+ {LogicalType::Geography(), SortOrder::UNKNOWN},
{LogicalType::Variant(), SortOrder::UNKNOWN},
{LogicalType::None(), SortOrder::UNKNOWN}};
@@ -2293,6 +2326,24 @@ TEST(TestLogicalTypeSerialization, Roundtrips) {
{LogicalType::BSON(), Type::BYTE_ARRAY, -1},
{LogicalType::UUID(), Type::FIXED_LEN_BYTE_ARRAY, 16},
{LogicalType::Float16(), Type::FIXED_LEN_BYTE_ARRAY, 2},
+ {LogicalType::Geometry(), Type::BYTE_ARRAY, -1},
+ {LogicalType::Geometry("srid:1234"), Type::BYTE_ARRAY, -1},
+ {LogicalType::Geography(), Type::BYTE_ARRAY, -1},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::SPHERICAL),
+ Type::BYTE_ARRAY, -1},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::VINCENTY),
+ Type::BYTE_ARRAY, -1},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::THOMAS),
+ Type::BYTE_ARRAY, -1},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::ANDOYER),
+ Type::BYTE_ARRAY, -1},
+ {LogicalType::Geography("srid:1234",
+ LogicalType::EdgeInterpolationAlgorithm::KARNEY),
+ Type::BYTE_ARRAY, -1},
{LogicalType::None(), Type::BOOLEAN, -1}};
for (const AnnotatedPrimitiveNodeFactoryArguments& c : cases) {
diff --git a/cpp/src/parquet/test_util.cc b/cpp/src/parquet/test_util.cc
--- a/cpp/src/parquet/test_util.cc
+++ b/cpp/src/parquet/test_util.cc
@@ -22,19 +22,13 @@
#include "parquet/test_util.h"
#include <algorithm>
-#include <chrono>
-#include <limits>
#include <memory>
#include <random>
#include <string>
#include <utility>
#include <vector>
-#include "arrow/testing/uniform_real.h"
-#include "parquet/column_page.h"
-#include "parquet/column_reader.h"
-#include "parquet/column_writer.h"
-#include "parquet/encoding.h"
+#include "parquet/geospatial/util_internal.h"
#include "parquet/platform.h"
namespace parquet {
@@ -194,5 +188,87 @@ void prefixed_random_byte_array(int n, uint32_t seed, uint8_t* buf, int len, FLB
}
}
+namespace {
+
+uint32_t GeometryTypeToWKB(geospatial::GeometryType geometry_type, bool has_z,
+ bool has_m) {
+ auto wkb_geom_type = static_cast<uint32_t>(geometry_type);
+
+ if (has_z) {
+ wkb_geom_type += 1000;
+ }
+
+ if (has_m) {
+ wkb_geom_type += 2000;
+ }
+
+ return wkb_geom_type;
+}
+
+} // namespace
+
+std::string MakeWKBPoint(const std::vector<double>& xyzm, bool has_z, bool has_m) {
+ // 1:endianness + 4:type + 8:x + 8:y
+ int num_bytes =
+ kWkbPointXYSize + (has_z ? sizeof(double) : 0) + (has_m ? sizeof(double) : 0);
+ std::string wkb(num_bytes, 0);
+ char* ptr = wkb.data();
+
+ ptr[0] = kWkbNativeEndianness;
+ uint32_t geom_type = GeometryTypeToWKB(geospatial::GeometryType::kPoint, has_z, has_m);
+ std::memcpy(&ptr[1], &geom_type, 4);
+ std::memcpy(&ptr[5], &xyzm[0], 8);
+ std::memcpy(&ptr[13], &xyzm[1], 8);
+ ptr += 21;
+
+ if (has_z) {
+ std::memcpy(ptr, &xyzm[2], 8);
+ ptr += 8;
+ }
+
+ if (has_m) {
+ std::memcpy(ptr, &xyzm[3], 8);
+ ptr += 8;
+ }
+
+ DCHECK_EQ(static_cast<size_t>(ptr - wkb.data()), wkb.length());
+ return wkb;
+}
+
+std::optional<std::pair<double, double>> GetWKBPointCoordinateXY(const ByteArray& value) {
+ if (value.len != kWkbPointXYSize) {
+ return std::nullopt;
+ }
+
+ if (value.ptr[0] != kWkbNativeEndianness) {
+ return std::nullopt;
+ }
+
+ uint32_t expected_geom_type = GeometryTypeToWKB(geospatial::GeometryType::kPoint,
+ /*has_z=*/false, /*has_m=*/false);
+ uint32_t geom_type = 0;
+ std::memcpy(&geom_type, &value.ptr[1], 4);
+ if (geom_type != expected_geom_type) {
+ return std::nullopt;
+ }
+ double out_x, out_y;
+ std::memcpy(&out_x, &value.ptr[5], 8);
+ std::memcpy(&out_y, &value.ptr[13], 8);
+
+ return {{out_x, out_y}};
+}
+
+std::shared_ptr<::arrow::DataType> geoarrow_wkb(
+ std::string metadata, const std::shared_ptr<::arrow::DataType> storage) {
+ return std::make_shared<GeoArrowWkbExtensionType>(storage, std::move(metadata));
+}
+
+std::shared_ptr<::arrow::DataType> geoarrow_wkb_lonlat(
+ const std::shared_ptr<::arrow::DataType> storage) {
+ // There are other ways to express lon/lat output, but this is the one that will
+ // roundtrip into Parquet and back
+ return geoarrow_wkb(R"({"crs": "OGC:CRS84", "crs_type": "authority_code"})", storage);
+}
+
} // namespace test
} // namespace parquet
diff --git a/cpp/src/parquet/test_util.h b/cpp/src/parquet/test_util.h
--- a/cpp/src/parquet/test_util.h
+++ b/cpp/src/parquet/test_util.h
@@ -26,11 +26,11 @@
#include <memory>
#include <random>
#include <string>
-#include <utility>
#include <vector>
#include <gtest/gtest.h>
+#include "arrow/extension_type.h"
#include "arrow/io/memory.h"
#include "arrow/testing/util.h"
#include "arrow/util/float16.h"
@@ -660,7 +660,7 @@ class PrimitiveTypedTest : public ::testing::Test {
public:
using c_type = typename TestType::c_type;
- void SetUpSchema(Repetition::type repetition, int num_columns = 1) {
+ virtual void SetUpSchema(Repetition::type repetition, int num_columns) {
std::vector<schema::NodePtr> fields;
for (int i = 0; i < num_columns; ++i) {
@@ -672,6 +672,8 @@ class PrimitiveTypedTest : public ::testing::Test {
schema_.Init(node_);
}
+ void SetUpSchema(Repetition::type repetition) { this->SetUpSchema(repetition, 1); }
+
void GenerateData(int64_t num_values, uint32_t seed = 0);
void SetupValuesOut(int64_t num_values);
void SyncValuesOut();
@@ -830,5 +832,60 @@ inline void GenerateData<FLBA>(int num_values, FLBA* out, std::vector<uint8_t>*
random_fixed_byte_array(num_values, 0, heap->data(), kGenerateDataFLBALength, out);
}
+// ----------------------------------------------------------------------
+// Test utility functions for geometry
+
+#if defined(ARROW_LITTLE_ENDIAN)
+static constexpr uint8_t kWkbNativeEndianness = 0x01;
+#else
+static constexpr uint8_t kWkbNativeEndianness = 0x00;
+#endif
+
+/// \brief Number of bytes in a WKB Point with X and Y dimensions (uint8_t endian,
+/// uint32_t geometry type, 2 * double coordinates)
+static constexpr int kWkbPointXYSize = 21;
+
+std::string MakeWKBPoint(const std::vector<double>& xyzm, bool has_z, bool has_m);
+
+std::optional<std::pair<double, double>> GetWKBPointCoordinateXY(const ByteArray& value);
+
+// A minimal version of a geoarrow.wkb extension type to test interoperability
+class GeoArrowWkbExtensionType : public ::arrow::ExtensionType {
+ public:
+ explicit GeoArrowWkbExtensionType(std::shared_ptr<::arrow::DataType> storage_type,
+ std::string metadata)
+ : ::arrow::ExtensionType(std::move(storage_type)), metadata_(std::move(metadata)) {}
+
+ std::string extension_name() const override { return "geoarrow.wkb"; }
+
+ std::string Serialize() const override { return metadata_; }
+
+ ::arrow::Result<std::shared_ptr<::arrow::DataType>> Deserialize(
+ std::shared_ptr<::arrow::DataType> storage_type,
+ const std::string& serialized_data) const override {
+ return std::make_shared<GeoArrowWkbExtensionType>(std::move(storage_type),
+ serialized_data);
+ }
+
+ std::shared_ptr<::arrow::Array> MakeArray(
+ std::shared_ptr<::arrow::ArrayData> data) const override {
+ return std::make_shared<::arrow::ExtensionArray>(data);
+ }
+
+ bool ExtensionEquals(const ExtensionType& other) const override {
+ return other.extension_name() == extension_name() && other.Serialize() == Serialize();
+ }
+
+ private:
+ std::string metadata_;
+};
+
+std::shared_ptr<::arrow::DataType> geoarrow_wkb(
+ std::string metadata = "{}",
+ const std::shared_ptr<::arrow::DataType> storage = ::arrow::binary());
+
+std::shared_ptr<::arrow::DataType> geoarrow_wkb_lonlat(
+ const std::shared_ptr<::arrow::DataType> storage = ::arrow::binary());
+
} // namespace test
} // namespace parquet
diff --git a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc
--- a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc
+++ b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc
#include "arrow/scalar.h"
#include "arrow/table.h"
#include "arrow/testing/builder.h"
+#include "arrow/testing/extension_type.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/testing/util.h"
TEST_F(TestJsonParquetIO, JsonExtension) {
this->RoundTripSingleColumn(json_large_array, json_large_array, writer_properties);
}
+using TestGeoArrowParquetIO = TestParquetIO<test::GeoArrowWkbExtensionType>;
+
+TEST_F(TestGeoArrowParquetIO, GeoArrowExtension) {
+ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb());
+
+ // Build a binary WKB array with at least one null value
+ ::arrow::BinaryBuilder builder;
+
+ for (int k = 0; k < 10; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ ASSERT_OK(builder.Append(item));
+ }
+ ASSERT_OK(builder.AppendNull());
+ for (int k = 0; k < 5; k++) {
+ std::string item = test::MakeWKBPoint(
+ {static_cast<double>(k), static_cast<double>(k + 1)}, false, false);
+ ASSERT_OK(builder.Append(item));
+ }
+
+ ASSERT_OK_AND_ASSIGN(const auto binary_array, builder.Finish());
+ const auto wkb_type = test::geoarrow_wkb_lonlat();
+ const auto wkb_array = ::arrow::ExtensionType::WrapArray(wkb_type, binary_array);
+
+ const auto large_wkb_type = test::geoarrow_wkb_lonlat(::arrow::large_binary());
+ ASSERT_OK_AND_ASSIGN(const auto large_binary_array,
+ ::arrow::compute::Cast(binary_array, ::arrow::large_binary()));
+ const auto large_wkb_array =
+ ::arrow::ExtensionType::WrapArray(large_wkb_type, large_binary_array.make_array());
+
+ // When the original Arrow schema isn't stored and Arrow extensions are disabled,
+ // LogicalType::GEOMETRY is read as utf8.
+ auto writer_properties = default_arrow_writer_properties();
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(wkb_array, binary_array, writer_properties));
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(large_wkb_array, binary_array, writer_properties));
+
+ // When the original Arrow schema isn't stored and Arrow extensions are enabled,
+ // LogicalType::GEOMETRY is read as geoarrow.wkb with binary storage.
+ ::parquet::ArrowReaderProperties reader_properties;
+ reader_properties.set_arrow_extensions_enabled(true);
+ ASSERT_NO_FATAL_FAILURE(this->RoundTripSingleColumn(
+ wkb_array, wkb_array, writer_properties, reader_properties));
+ ASSERT_NO_FATAL_FAILURE(this->RoundTripSingleColumn(
+ large_wkb_array, wkb_array, writer_properties, reader_properties));
+
+ // When the original Arrow schema is stored, the stored Arrow type is respected.
+ writer_properties = ::parquet::ArrowWriterProperties::Builder().store_schema()->build();
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(wkb_array, wkb_array, writer_properties));
+ ASSERT_NO_FATAL_FAILURE(
+ this->RoundTripSingleColumn(large_wkb_array, large_wkb_array, writer_properties));
+}
+
using TestNullParquetIO = TestParquetIO<::arrow::NullType>;
TEST_F(TestNullParquetIO, NullColumn) {
diff --git a/cpp/src/parquet/arrow/arrow_schema_test.cc b/cpp/src/parquet/arrow/arrow_schema_test.cc
--- a/cpp/src/parquet/arrow/arrow_schema_test.cc
+++ b/cpp/src/parquet/arrow/arrow_schema_test.cc
#include <vector>
#include "gmock/gmock-matchers.h"
-#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "parquet/arrow/reader.h"
#include "arrow/extension/json.h"
#include "arrow/extension/uuid.h"
#include "arrow/ipc/writer.h"
+#include "arrow/testing/extension_type.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/type.h"
#include "arrow/util/base64.h"
TEST_F(TestConvertParquetSchema, ParquetAnnotatedFields) {
::arrow::int64()},
{"json", LogicalType::JSON(), ParquetType::BYTE_ARRAY, -1, ::arrow::utf8()},
{"bson", LogicalType::BSON(), ParquetType::BYTE_ARRAY, -1, ::arrow::binary()},
+ {"geometry", LogicalType::Geometry(), ParquetType::BYTE_ARRAY, -1,
+ ::arrow::binary()},
+ {"geography", LogicalType::Geography(), ParquetType::BYTE_ARRAY, -1,
+ ::arrow::binary()},