Download arrow_1/solution/solution.patch from lolbench26/LoLBench: direct link, hf CLI and curl.
- Browser
- Download file 91.5 kB
-
https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/arrow_1/solution/solution.patch
- Command line
-
hf download hf://datasets/lolbench26/LoLBench/arrow_1/solution/solution.patch
-
curl -L -o solution.patch https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/arrow_1/solution/solution.patch
91.5 kB
| 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 | |
| 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 | |
| #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" | |
| 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; | |
| 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; | |
| 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()); | |
| 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; | |
| ::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); | |
| 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); | |
| } | |
| 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 | |
| #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; | |
| 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(); | |
| 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"); | |
| 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(); | |
| } | |
| 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: { | |
| 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 | |
| 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 | |
| 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; | |
| 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_); | |
| } | |
| 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_); | |
| 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_); | |
| 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 | |
| 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. | |
| 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); | |
| + } | |
| + } | |
| } | |
| }; | |
| 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; | |
| 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 | |
| +# 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 | |
| +// 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 | |
| +// 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 | |
| +// 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 | |
| +// 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 | |
| +// 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 | |
| +// 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 | |
| #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 { | |
| 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)) { | |
| class ColumnChunkMetaData::ColumnChunkMetaDataImpl { | |
| size_statistics_->Validate(descr_); | |
| } | |
| possible_stats_ = nullptr; | |
| + possible_geo_stats_ = nullptr; | |
| InitKeyValueMetadata(); | |
| } | |
| 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; | |
| } | |
| 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); | |
| } | |
| 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_; | |
| 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(); | |
| } | |
| 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, | |
| 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 | |
| #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 { | |
| 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 | |
| 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 | |
| #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" | |
| 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; | |
| 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 | |
| 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 | |
| #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" | |
| 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 { | |
| 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(); | |
| } | |
| class LogicalType::Impl { | |
| class BSON; | |
| class UUID; | |
| class Float16; | |
| + class Geometry; | |
| + class Geography; | |
| class Variant; | |
| class No; | |
| class Undefined; | |
| 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; | |
| } | |
| 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 | |
| class PARQUET_EXPORT LogicalType { | |
| BSON, | |
| UUID, | |
| FLOAT16, | |
| + GEOMETRY, | |
| + GEOGRAPHY, | |
| VARIANT, | |
| NONE // Not a real logical type; should always be last element | |
| }; | |
| 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( | |
| 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(); | |
| 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. | |
| 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 | |
| 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 | |
| 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) | |
| endif() | |
| add_subdirectory(api) | |
| add_subdirectory(arrow) | |
| add_subdirectory(encryption) | |
| +add_subdirectory(geospatial) | |
| arrow_install_all_headers("parquet") | |
| 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) | |