diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake --- a/cpp/cmake_modules/ThirdpartyToolchain.cmake +++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake @@ -374,16 +374,13 @@ target_include_directories(arrow::flatbuffers # ---------------------------------------------------------------------- # Some EP's require other EP's -if(PARQUET_REQUIRE_ENCRYPTION) - set(ARROW_JSON ON) -endif() - if(ARROW_WITH_OPENTELEMETRY) set(ARROW_WITH_NLOHMANN_JSON ON) set(ARROW_WITH_PROTOBUF ON) endif() if(ARROW_PARQUET) + set(ARROW_WITH_RAPIDJSON ON) set(ARROW_WITH_THRIFT ON) endif() diff --git a/cpp/src/parquet/arrow/schema.cc b/cpp/src/parquet/arrow/schema.cc --- a/cpp/src/parquet/arrow/schema.cc +++ b/cpp/src/parquet/arrow/schema.cc @@ -38,6 +38,7 @@ #include "parquet/arrow/schema_internal.h" #include "parquet/arrow/variant_internal.h" #include "parquet/exception.h" +#include "parquet/geospatial/util_json_internal.h" #include "parquet/metadata.h" #include "parquet/properties.h" #include "parquet/types.h" @@ -288,8 +289,8 @@ int FieldIdFromMetadata( if (::arrow::internal::ParseValue<::arrow::Int32Type>( field_id_str.c_str(), field_id_str.length(), &field_id)) { if (field_id < 0) { - // Thrift should convert any negative value to null but normalize to -1 here in case - // we later check this in logic. + // Thrift should convert any negative value to null but normalize to -1 here in + // case we later check this in logic. return -1; } return field_id; @@ -449,9 +450,9 @@ Status FieldToNode(const std::string& name, const std::shared_ptr& field, } case ArrowTypeId::EXTENSION: { auto ext_type = std::static_pointer_cast<::arrow::ExtensionType>(field->type()); - // Built-in JSON extension is handled differently. - if (ext_type->extension_name() == std::string("arrow.json")) { - // Set physical and logical types and instantiate primitive node. + // Set physical and logical types and instantiate primitive node + // for extension types + if (ext_type->extension_name() == std::string_view("arrow.json")) { type = ParquetType::BYTE_ARRAY; logical_type = LogicalType::JSON(); break; @@ -460,6 +461,11 @@ Status FieldToNode(const std::string& name, const std::shared_ptr& field, 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(field->type()); @@ -495,6 +501,7 @@ struct SchemaTreeContext { SchemaManifest* manifest; ArrowReaderProperties properties; const SchemaDescriptor* schema; + std::shared_ptr metadata; void LinkParent(const SchemaField* child, const SchemaField* parent) { manifest->child_to_parent[child] = parent; @@ -517,7 +524,7 @@ ::arrow::Result> GetTypeForNode( int column_index, const schema::PrimitiveNode& primitive_node, SchemaTreeContext* ctx) { ARROW_ASSIGN_OR_RAISE(std::shared_ptr storage_type, - GetArrowType(primitive_node, ctx->properties)); + GetArrowType(primitive_node, ctx->properties, ctx->metadata)); if (ctx->properties.read_dictionary(column_index) && IsDictionaryReadSupported(*storage_type)) { return ::arrow::dictionary(::arrow::int32(), storage_type); @@ -610,8 +617,8 @@ Status MapToSchemaField(const GroupNode& group, LevelInfo current_levels, return Status::Invalid("Map keys must be annotated as required."); } // Arrow doesn't support 1 column maps (i.e. Sets). The options are to either - // make the values column nullable, or process the map as a list. We choose the latter - // as it is simpler. + // make the values column nullable, or process the map as a list. We choose the + // latter as it is simpler. if (key_value.field_count() == 1) { return ListToSchemaField(group, current_levels, ctx, parent, out); } @@ -1197,6 +1204,7 @@ Status SchemaManifest::Make(const SchemaDescriptor* schema, ctx.manifest = manifest; ctx.properties = properties; ctx.schema = schema; + ctx.metadata = metadata; const GroupNode& schema_node = *schema->group_node(); manifest->descr = schema; manifest->schema_fields.resize(schema_node.field_count()); diff --git a/cpp/src/parquet/arrow/schema_internal.cc b/cpp/src/parquet/arrow/schema_internal.cc --- a/cpp/src/parquet/arrow/schema_internal.cc +++ b/cpp/src/parquet/arrow/schema_internal.cc @@ -20,7 +20,10 @@ #include "arrow/extension/json.h" #include "arrow/extension/uuid.h" #include "arrow/type.h" +#include "arrow/util/key_value_metadata.h" +#include "arrow/util/string.h" +#include "parquet/geospatial/util_json_internal.h" #include "parquet/properties.h" using ArrowType = ::arrow::DataType; @@ -112,7 +115,8 @@ Result> MakeArrowTimestamp(const LogicalType& logical } Result> FromByteArray( - const LogicalType& logical_type, const ArrowReaderProperties& reader_properties) { + const LogicalType& logical_type, const ArrowReaderProperties& reader_properties, + const std::shared_ptr& metadata) { switch (logical_type.type()) { case LogicalType::Type::STRING: return ::arrow::utf8(); @@ -129,6 +133,18 @@ Result> FromByteArray( // When the original Arrow schema isn't stored and Arrow extensions are disabled, // LogicalType::JSON is read as utf8(). return ::arrow::utf8(); + case LogicalType::Type::GEOMETRY: + case LogicalType::Type::GEOGRAPHY: + if (reader_properties.get_arrow_extensions_enabled()) { + // Attempt creating a GeoArrow extension type (or return binary() if types are not + // registered) + return GeoArrowTypeFromLogicalType(logical_type, metadata); + } + + // When the original Arrow schema isn't stored, Arrow extensions are disabled, or + // the geoarrow.wkb extension type isn't registered, LogicalType::GEOMETRY and + // LogicalType::GEOGRAPHY are as binary(). + return ::arrow::binary(); default: return Status::NotImplemented("Unhandled logical logical_type ", logical_type.ToString(), " for binary array"); @@ -196,7 +212,8 @@ Result> FromInt64(const LogicalType& logical_type) { Result> GetArrowType( Type::type physical_type, const LogicalType& logical_type, int type_length, - const ArrowReaderProperties& reader_properties) { + const ArrowReaderProperties& reader_properties, + const std::shared_ptr& metadata) { if (logical_type.is_null()) { return ::arrow::null(); } @@ -220,7 +237,7 @@ Result> GetArrowType( case ParquetType::DOUBLE: return ::arrow::float64(); case ParquetType::BYTE_ARRAY: - return FromByteArray(logical_type, reader_properties); + return FromByteArray(logical_type, reader_properties, metadata); case ParquetType::FIXED_LEN_BYTE_ARRAY: return FromFLBA(logical_type, type_length, reader_properties); default: { @@ -233,9 +250,10 @@ Result> GetArrowType( Result> GetArrowType( const schema::PrimitiveNode& primitive, - const ArrowReaderProperties& reader_properties) { + const ArrowReaderProperties& reader_properties, + const std::shared_ptr& metadata) { return GetArrowType(primitive.physical_type(), *primitive.logical_type(), - primitive.type_length(), reader_properties); + primitive.type_length(), reader_properties, metadata); } } // namespace parquet::arrow diff --git a/cpp/src/parquet/arrow/schema_internal.h b/cpp/src/parquet/arrow/schema_internal.h --- a/cpp/src/parquet/arrow/schema_internal.h +++ b/cpp/src/parquet/arrow/schema_internal.h @@ -29,19 +29,22 @@ namespace parquet::arrow { using ::arrow::Result; -Result> FromByteArray(const LogicalType& logical_type, - bool use_known_arrow_extensions); +Result> FromByteArray( + const LogicalType& logical_type, bool use_known_arrow_extensions, + const std::shared_ptr& metadata = nullptr); Result> FromFLBA(const LogicalType& logical_type, int32_t physical_length); Result> FromInt32(const LogicalType& logical_type); Result> FromInt64(const LogicalType& logical_type); Result> GetArrowType( Type::type physical_type, const LogicalType& logical_type, int type_length, - const ArrowReaderProperties& reader_properties); + const ArrowReaderProperties& reader_properties, + const std::shared_ptr& metadata = nullptr); Result> GetArrowType( const schema::PrimitiveNode& primitive, - const ArrowReaderProperties& reader_properties); + const ArrowReaderProperties& reader_properties, + const std::shared_ptr& metadata = nullptr); } // namespace parquet::arrow diff --git a/cpp/src/parquet/column_writer.cc b/cpp/src/parquet/column_writer.cc --- a/cpp/src/parquet/column_writer.cc +++ b/cpp/src/parquet/column_writer.cc @@ -788,6 +788,9 @@ class ColumnWriterImpl { // Plain-encoded statistics of the whole chunk virtual StatisticsPair GetChunkStatistics() = 0; + // Geospatial statistics of the whole chunk + virtual std::optional GetChunkGeoStatistics() = 0; + // Merges page statistics into chunk statistics, then resets the values virtual void ResetPageStatistics() = 0; @@ -1104,9 +1107,18 @@ int64_t ColumnWriterImpl::Close() { if (rows_written_ > 0 && chunk_statistics.is_set()) { metadata_->SetStatistics(chunk_statistics); } + if (rows_written_ > 0 && chunk_size_statistics.is_set()) { metadata_->SetSizeStatistics(chunk_size_statistics); } + + if (descr_->logical_type() != nullptr && descr_->logical_type()->is_geometry()) { + std::optional geo_stats = GetChunkGeoStatistics(); + if (geo_stats) { + metadata_->SetGeoStatistics(std::move(*geo_stats)); + } + } + metadata_->SetKeyValueMetadata(key_value_metadata_); pager_->Close(has_dictionary_, fallback_); } @@ -1230,11 +1242,19 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, current_dict_encoder_ = dynamic_cast*>(current_encoder_.get()); - if (properties->statistics_enabled(descr_->path()) && - (SortOrder::UNKNOWN != descr_->sort_order())) { - page_statistics_ = MakeStatistics(descr_, allocator_); - chunk_statistics_ = MakeStatistics(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(descr_, allocator_); + chunk_statistics_ = MakeStatistics(descr_, allocator_); + } + if (descr_->logical_type() != nullptr && descr_->logical_type()->is_geometry()) { + chunk_geospatial_statistics_ = std::make_shared(); + } } + if (properties->size_statistics_level() == SizeStatisticsLevel::ColumnChunk || properties->size_statistics_level() == SizeStatisticsLevel::PageAndColumnChunk) { page_size_statistics_ = SizeStatistics::Make(descr_); @@ -1430,6 +1450,14 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, return result; } + std::optional GetChunkGeoStatistics() override { + if (chunk_geospatial_statistics_) { + return chunk_geospatial_statistics_->Encode(); + } else { + return std::nullopt; + } + } + void ResetPageStatistics() override { if (chunk_statistics_ != nullptr) { chunk_statistics_->Merge(*page_statistics_); @@ -1494,6 +1522,7 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, std::shared_ptr chunk_statistics_; std::unique_ptr page_size_statistics_; std::shared_ptr chunk_size_statistics_; + std::shared_ptr chunk_geospatial_statistics_; bool pages_change_on_record_boundaries_; // If writing a sequence of ::arrow::DictionaryArray to the writer, we keep the @@ -1719,7 +1748,14 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, if (page_statistics_ != nullptr) { page_statistics_->Update(values, num_values, num_nulls); } + UpdateUnencodedDataBytes(); + + if constexpr (std::is_same::value) { + if (chunk_geospatial_statistics_ != nullptr) { + chunk_geospatial_statistics_->Update(values, num_values); + } + } } /// \brief Write values with spaces and update page statistics accordingly. @@ -1748,7 +1784,15 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, page_statistics_->UpdateSpaced(values, valid_bits, valid_bits_offset, num_spaced_values, num_values, num_nulls); } + UpdateUnencodedDataBytes(); + + if constexpr (std::is_same::value) { + if (chunk_geospatial_statistics_ != nullptr) { + chunk_geospatial_statistics_->UpdateSpaced(values, valid_bits, valid_bits_offset, + num_spaced_values, num_values); + } + } } }; @@ -1826,6 +1870,12 @@ Status TypedColumnWriterImpl::WriteArrowDictionary( page_statistics_->IncrementNullCount(num_chunk_levels - non_null_count); page_statistics_->IncrementNumValues(non_null_count); page_statistics_->Update(*referenced_dictionary, /*update_counts=*/false); + + if (chunk_geospatial_statistics_ != nullptr) { + throw ParquetException( + "Writing dictionary-encoded GEOMETRY or GEOGRAPHY with statistics is not " + "supported"); + } }; int64_t value_offset = 0; @@ -2305,7 +2355,12 @@ Status TypedColumnWriterImpl::WriteArrowDense( page_statistics_->IncrementNullCount(batch_size - non_null); page_statistics_->IncrementNumValues(non_null); } + UpdateUnencodedDataBytes(); + + if (chunk_geospatial_statistics_ != nullptr) { + chunk_geospatial_statistics_->Update(*data_slice); + } CommitWriteAndCheckPageLimit(batch_size, batch_num_values, batch_size - non_null, check_page); CheckDictionarySizeLimit(); diff --git a/cpp/src/parquet/geospatial/CMakeLists.txt b/cpp/src/parquet/geospatial/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/cpp/src/parquet/geospatial/CMakeLists.txt @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +arrow_install_all_headers("parquet/geospatial") diff --git a/cpp/src/parquet/geospatial/statistics.cc b/cpp/src/parquet/geospatial/statistics.cc new file mode 100644 --- /dev/null +++ b/cpp/src/parquet/geospatial/statistics.cc @@ -0,0 +1,393 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "parquet/geospatial/statistics.h" + +#include +#include +#include + +#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 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(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(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& lower_bound() const { + return bounder_.Bounds().min; + } + + const std::array& upper_bound() const { + return bounder_.Bounds().max; + } + + std::optional> 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 + void UpdateArrayImpl(const ::arrow::Array& values) { + const auto& binary_array = static_cast(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()) {} + +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 GeoStatistics::Encode() const { + if (is_valid()) { + return impl_->Encode(); + } else { + return std::nullopt; + } +} + +void GeoStatistics::Decode(const EncodedGeoStatistics& encoded) { + impl_->Decode(encoded); +} + +std::array GeoStatistics::lower_bound() const { return impl_->lower_bound(); } + +std::array GeoStatistics::upper_bound() const { return impl_->upper_bound(); } + +std::array GeoStatistics::dimension_empty() const { + return {impl_->bound_empty(0), impl_->bound_empty(1), impl_->bound_empty(2), + impl_->bound_empty(3)}; +} + +std::array GeoStatistics::dimension_valid() const { + return {impl_->bound_valid(0), impl_->bound_valid(1), impl_->bound_valid(2), + impl_->bound_valid(3)}; +} + +std::optional> GeoStatistics::geometry_types() const { + return impl_->geometry_types(); +} + +std::string GeoStatistics::ToString() const { + if (!is_valid()) { + return " invalid"; + } + + std::stringstream ss; + ss << ""; + + 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> maybe_geometry_types = geometry_types(); + ss << " geometry_types: "; + if (maybe_geometry_types.has_value()) { + ss << "["; + std::string sep(""); + for (int32_t geometry_type : *maybe_geometry_types) { + ss << sep << geometry_type; + sep = ", "; + } + ss << "]"; + } else { + ss << "invalid"; + } + + return ss.str(); +} + +} // namespace parquet::geospatial diff --git a/cpp/src/parquet/geospatial/statistics.h b/cpp/src/parquet/geospatial/statistics.h new file mode 100644 --- /dev/null +++ b/cpp/src/parquet/geospatial/statistics.h @@ -0,0 +1,194 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#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::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 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 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 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 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 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 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> geometry_types() const; + + /// \brief Return a string representation of these statistics + std::string ToString() const; + + private: + std::unique_ptr impl_; +}; + +} // namespace parquet::geospatial diff --git a/cpp/src/parquet/geospatial/util_internal.cc b/cpp/src/parquet/geospatial/util_internal.cc new file mode 100644 --- /dev/null +++ b/cpp/src/parquet/geospatial/util_internal.cc @@ -0,0 +1,242 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "parquet/geospatial/util_internal.h" + +#include + +#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(); } + + uint32_t ReadUInt32(bool swap) { + auto value = ReadChecked(); + if (swap) { + return ::arrow::bit_util::ByteSwap(value); + } else { + return value; + } + } + + template + 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(); + for (auto& c : coord) { + c = ::arrow::bit_util::ByteSwap(c); + } + + visit(coord); + } + } else { + for (uint32_t i = 0; i < n_coords; i++) { + visit(ReadUnchecked()); + } + } + } + + size_t size() { return size_; } + + private: + const uint8_t* data_; + size_t size_; + + template + T ReadChecked() { + if (ARROW_PREDICT_FALSE(size_ < sizeof(T))) { + throw ParquetException("Can't read ", sizeof(T), " bytes from WKBBuffer with ", + size_, " remaining"); + } + + return ReadUnchecked(); + } + + template + T ReadUnchecked() { + T out = ::arrow::util::SafeLoadAs(data_); + data_ += sizeof(T); + size_ -= sizeof(T); + return out; + } +}; + +using GeometryTypeAndDimensions = std::pair; + +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(GeometryType::kValueMin); + auto max_geometry_type_value = static_cast(GeometryType::kValueMax); + auto min_dimension_value = static_cast(Dimensions::kValueMin); + auto max_dimension_value = static_cast(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(geometry_type_component), + static_cast(dimensions_component)}; +} + +} // namespace + +std::vector WKBGeometryBounder::GeometryTypes() const { + std::vector 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(bytes_wkb.data()), + bytes_wkb.size())); +} + +void WKBGeometryBounder::MergeGeometry(::arrow::util::span bytes_wkb) { + WKBBuffer src{bytes_wkb.data(), static_cast(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(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( + n_coords, swap, [&](BoundingBox::XY coord) { box_.UpdateXY(coord); }); + break; + case Dimensions::kXYZ: + src->ReadCoords( + n_coords, swap, [&](BoundingBox::XYZ coord) { box_.UpdateXYZ(coord); }); + break; + case Dimensions::kXYM: + src->ReadCoords( + n_coords, swap, [&](BoundingBox::XYM coord) { box_.UpdateXYM(coord); }); + break; + case Dimensions::kXYZM: + src->ReadCoords( + n_coords, swap, [&](BoundingBox::XYZM coord) { box_.UpdateXYZM(coord); }); + break; + default: + throw ParquetException("Unknown dimensions"); + } +} + +} // namespace parquet::geospatial diff --git a/cpp/src/parquet/geospatial/util_internal.h b/cpp/src/parquet/geospatial/util_internal.h new file mode 100644 --- /dev/null +++ b/cpp/src/parquet/geospatial/util_internal.h @@ -0,0 +1,224 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#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::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; + using XYZ = std::array; + using XYM = std::array; + using XYZM = std::array; + + 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 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 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 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 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::quiet_NaN(); + max[i] = std::numeric_limits::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 + 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 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 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 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 geospatial_types_; + + void MergeGeometryInternal(WKBBuffer* src, bool record_wkb_type); + + void MergeSequence(WKBBuffer* src, Dimensions dimensions, uint32_t n_coords, bool swap); +}; + +} // namespace parquet::geospatial diff --git a/cpp/src/parquet/geospatial/util_json_internal.cc b/cpp/src/parquet/geospatial/util_json_internal.cc new file mode 100644 --- /dev/null +++ b/cpp/src/parquet/geospatial/util_json_internal.cc @@ -0,0 +1,205 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "parquet/geospatial/util_json_internal.h" + +#include + +#include "arrow/extension_type.h" +#include "arrow/json/rapidjson_defs.h" // IWYU pragma: keep +#include "arrow/result.h" +#include "arrow/util/string.h" + +#include +#include + +#include "parquet/exception.h" +#include "parquet/types.h" + +namespace parquet { + +namespace { +::arrow::Result 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 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 MakeGeoArrowCrsMetadata( + std::string_view crs, + const std::shared_ptr& 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 writer(buffer); + rj::Value v; + v.SetString(crs.data(), static_cast(crs.size())); + v.Accept(writer); + return std::string(buffer.GetString()); + } else { + return std::string(crs); + } +} + +} // namespace + +::arrow::Result> 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> GeoArrowTypeFromLogicalType( + const LogicalType& logical_type, + const std::shared_ptr& 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(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(logical_type); + ARROW_ASSIGN_OR_RAISE(std::string crs_metadata, + MakeGeoArrowCrsMetadata(geospatial_type.crs(), metadata)); + std::string edges_metadata = + R"("edges": ")" + std::string(geospatial_type.algorithm_name()) + R"(")"; + std::string serialized_data = + std::string("{") + crs_metadata + ", " + edges_metadata + "}"; + return maybe_geoarrow_wkb->Deserialize(::arrow::binary(), serialized_data); + } else { + throw ParquetException("Can't export logical type ", logical_type.ToString(), + " as GeoArrow"); + } +} + +} // namespace parquet diff --git a/cpp/src/parquet/geospatial/util_json_internal.h b/cpp/src/parquet/geospatial/util_json_internal.h new file mode 100644 --- /dev/null +++ b/cpp/src/parquet/geospatial/util_json_internal.h @@ -0,0 +1,45 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#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> 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> GeoArrowTypeFromLogicalType( + const LogicalType& logical_type, + const std::shared_ptr& metadata); + +} // namespace parquet diff --git a/cpp/src/parquet/metadata.cc b/cpp/src/parquet/metadata.cc --- a/cpp/src/parquet/metadata.cc +++ b/cpp/src/parquet/metadata.cc @@ -38,6 +38,7 @@ #include "parquet/schema.h" #include "parquet/schema_internal.h" #include "parquet/size_statistics.h" +#include "parquet/statistics.h" #include "parquet/thrift_internal.h" namespace parquet { @@ -108,6 +109,17 @@ static std::shared_ptr MakeTypedColumnStats( metadata.statistics.__isset.null_count, metadata.statistics.__isset.distinct_count); } +static std::shared_ptr 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(std::move(encoded_geo_stats)); + } else { + return nullptr; + } +} + std::shared_ptr MakeColumnStats(const format::ColumnMetaData& meta_data, const ColumnDescriptor* descr) { switch (static_cast(meta_data.type)) { @@ -268,6 +280,7 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { size_statistics_->Validate(descr_); } possible_stats_ = nullptr; + possible_geo_stats_ = nullptr; InitKeyValueMetadata(); } @@ -298,14 +311,29 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { descr_->sort_order() == SortOrder::UNKNOWN) { return false; } - if (possible_stats_ == nullptr) { - possible_stats_ = MakeColumnStats(*column_metadata_, descr_); + { + // Because we are modifying possible_stats_ in a const method + const std::lock_guard 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 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() const { return is_stats_set() ? possible_stats_ : nullptr; } @@ -314,6 +342,10 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { return size_statistics_; } + inline std::shared_ptr geospatial_statistics() const { + return is_geo_stats_set() ? possible_geo_stats_ : nullptr; + } + inline Compression::type compression() const { return LoadEnumSafe(&column_metadata_->codec); } @@ -392,7 +424,9 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { key_value_metadata_ = FromThriftKeyValueMetadata(*column_metadata_); } + mutable std::mutex stats_mutex_; mutable std::shared_ptr possible_stats_; + mutable std::shared_ptr possible_geo_stats_; std::vector encodings_; std::vector encoding_stats_; const format::ColumnChunk* column_; @@ -444,12 +478,18 @@ std::shared_ptr ColumnChunkMetaData::statistics() const { return impl_->statistics(); } +std::shared_ptr ColumnChunkMetaData::geo_statistics() const { + return impl_->geospatial_statistics(); +} + bool ColumnChunkMetaData::is_stats_set() const { return impl_->is_stats_set(); } std::shared_ptr ColumnChunkMetaData::size_statistics() const { return impl_->size_statistics(); } +bool ColumnChunkMetaData::is_geo_stats_set() const { return impl_->is_geo_stats_set(); } + std::optional ColumnChunkMetaData::bloom_filter_offset() const { return impl_->bloom_filter_offset(); } @@ -1558,6 +1598,10 @@ class ColumnChunkMetaDataBuilder::ColumnChunkMetaDataBuilderImpl { column_chunk_->meta_data.__set_size_statistics(ToThrift(size_stats)); } + void SetGeoStatistics(const geospatial::EncodedGeoStatistics& val) { + column_chunk_->meta_data.__set_geospatial_statistics(ToThrift(val)); + } + void Finish(int64_t num_values, int64_t dictionary_page_offset, int64_t index_page_offset, int64_t data_page_offset, int64_t compressed_size, int64_t uncompressed_size, bool has_dictionary, @@ -1771,6 +1815,11 @@ void ColumnChunkMetaDataBuilder::SetSizeStatistics(const SizeStatistics& size_st impl_->SetSizeStatistics(size_stats); } +void ColumnChunkMetaDataBuilder::SetGeoStatistics( + const geospatial::EncodedGeoStatistics& result) { + impl_->SetGeoStatistics(result); +} + void ColumnChunkMetaDataBuilder::SetKeyValueMetadata( std::shared_ptr key_value_metadata) { impl_->SetKeyValueMetadata(std::move(key_value_metadata)); diff --git a/cpp/src/parquet/metadata.h b/cpp/src/parquet/metadata.h --- a/cpp/src/parquet/metadata.h +++ b/cpp/src/parquet/metadata.h @@ -22,12 +22,12 @@ #include #include #include -#include #include #include "parquet/encryption/type_fwd.h" #include "parquet/platform.h" #include "parquet/properties.h" +#include "parquet/type_fwd.h" namespace parquet { @@ -141,8 +141,10 @@ class PARQUET_EXPORT ColumnChunkMetaData { int64_t num_values() const; std::shared_ptr path_in_schema() const; bool is_stats_set() const; + bool is_geo_stats_set() const; std::shared_ptr statistics() const; std::shared_ptr size_statistics() const; + std::shared_ptr geo_statistics() const; Compression::type compression() const; // Indicate if the ColumnChunk compression is supported by the current @@ -440,6 +442,9 @@ class PARQUET_EXPORT ColumnChunkMetaDataBuilder { void SetStatistics(const EncodedStatistics& stats); void SetSizeStatistics(const SizeStatistics& size_stats); + // column geometry statistics + void SetGeoStatistics(const geospatial::EncodedGeoStatistics& geo_stats); + void SetKeyValueMetadata(std::shared_ptr key_value_metadata); // get the column descriptor diff --git a/cpp/src/parquet/thrift_internal.h b/cpp/src/parquet/thrift_internal.h --- a/cpp/src/parquet/thrift_internal.h +++ b/cpp/src/parquet/thrift_internal.h @@ -41,6 +41,7 @@ #include "parquet/encryption/internal_file_decryptor.h" #include "parquet/encryption/internal_file_encryptor.h" #include "parquet/exception.h" +#include "parquet/geospatial/statistics.h" #include "parquet/platform.h" #include "parquet/properties.h" #include "parquet/size_statistics.h" @@ -232,6 +233,73 @@ static inline AadMetadata FromThrift(format::AesGcmCtrV1 aesGcmCtrV1) { aesGcmCtrV1.supply_aad_prefix}; } +static inline geospatial::EncodedGeoStatistics FromThrift( + const format::GeospatialStatistics& geo_stats) { + geospatial::EncodedGeoStatistics out; + + out.geospatial_types = geo_stats.geospatial_types; + + if (geo_stats.__isset.bbox) { + out.xmin = geo_stats.bbox.xmin; + out.xmax = geo_stats.bbox.xmax; + out.ymin = geo_stats.bbox.ymin; + out.ymax = geo_stats.bbox.ymax; + out.xy_bounds_present = true; + + if (geo_stats.bbox.__isset.zmin && geo_stats.bbox.__isset.zmax) { + out.zmin = geo_stats.bbox.zmin; + out.zmax = geo_stats.bbox.zmax; + out.z_bounds_present = true; + } + + if (geo_stats.bbox.__isset.mmin && geo_stats.bbox.__isset.mmax) { + out.mmin = geo_stats.bbox.mmin; + out.mmax = geo_stats.bbox.mmax; + out.m_bounds_present = true; + } + } + + return out; +} + +static inline format::EdgeInterpolationAlgorithm::type ToThrift( + LogicalType::EdgeInterpolationAlgorithm algorithm) { + switch (algorithm) { + case LogicalType::EdgeInterpolationAlgorithm::SPHERICAL: + return format::EdgeInterpolationAlgorithm::SPHERICAL; + case LogicalType::EdgeInterpolationAlgorithm::VINCENTY: + return format::EdgeInterpolationAlgorithm::VINCENTY; + case LogicalType::EdgeInterpolationAlgorithm::THOMAS: + return format::EdgeInterpolationAlgorithm::THOMAS; + case LogicalType::EdgeInterpolationAlgorithm::ANDOYER: + return format::EdgeInterpolationAlgorithm::ANDOYER; + case LogicalType::EdgeInterpolationAlgorithm::KARNEY: + return format::EdgeInterpolationAlgorithm::KARNEY; + default: + throw ParquetException("Unknown value for geometry algorithm: ", + static_cast(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(algorithm)); + } +} + static inline EncryptionAlgorithm FromThrift(format::EncryptionAlgorithm encryption) { EncryptionAlgorithm encryption_algorithm; @@ -332,6 +400,35 @@ static inline format::SortingColumn ToThrift(SortingColumn sorting_column) { return thrift_sorting_column; } +static inline format::GeospatialStatistics ToThrift( + const geospatial::EncodedGeoStatistics& encoded_geo_stats) { + format::GeospatialStatistics geospatial_statistics; + + geospatial_statistics.__set_geospatial_types(encoded_geo_stats.geospatial_types); + + if (encoded_geo_stats.xy_bounds_present) { + format::BoundingBox bbox; + bbox.__set_xmin(encoded_geo_stats.xmin); + bbox.__set_xmax(encoded_geo_stats.xmax); + bbox.__set_ymin(encoded_geo_stats.ymin); + bbox.__set_ymax(encoded_geo_stats.ymax); + + if (encoded_geo_stats.z_bounds_present) { + bbox.__set_zmin(encoded_geo_stats.zmin); + bbox.__set_zmax(encoded_geo_stats.zmax); + } + + if (encoded_geo_stats.m_bounds_present) { + bbox.__set_mmin(encoded_geo_stats.mmin); + bbox.__set_mmax(encoded_geo_stats.mmax); + } + + geospatial_statistics.__set_bbox(std::move(bbox)); + } + + return geospatial_statistics; +} + static inline format::Statistics ToThrift(const EncodedStatistics& stats) { format::Statistics statistics; if (stats.has_min) { diff --git a/cpp/src/parquet/type_fwd.h b/cpp/src/parquet/type_fwd.h --- a/cpp/src/parquet/type_fwd.h +++ b/cpp/src/parquet/type_fwd.h @@ -83,6 +83,11 @@ class EncodedStatistics; class Statistics; struct SizeStatistics; +namespace geospatial { +class GeoStatistics; +struct EncodedGeoStatistics; +} // namespace geospatial + class ColumnIndex; class OffsetIndex; diff --git a/cpp/src/parquet/types.cc b/cpp/src/parquet/types.cc --- a/cpp/src/parquet/types.cc +++ b/cpp/src/parquet/types.cc @@ -22,11 +22,16 @@ #include #include +#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 +#include + #include "parquet/exception.h" +#include "parquet/thrift_internal.h" #include "parquet/types.h" #include "generated/parquet_types.h" @@ -479,6 +484,27 @@ std::shared_ptr LogicalType::FromThrift( return UUIDLogicalType::Make(); } else if (type.__isset.FLOAT16) { return Float16LogicalType::Make(); + } else if (type.__isset.GEOMETRY) { + std::string crs; + if (type.GEOMETRY.__isset.crs) { + crs = type.GEOMETRY.crs; + } + + return GeometryLogicalType::Make(std::move(crs)); + } else if (type.__isset.GEOGRAPHY) { + std::string crs; + if (type.GEOGRAPHY.__isset.crs) { + crs = type.GEOGRAPHY.crs; + } + + LogicalType::EdgeInterpolationAlgorithm algorithm; + if (!type.GEOGRAPHY.__isset.algorithm) { + algorithm = LogicalType::EdgeInterpolationAlgorithm::SPHERICAL; + } else { + algorithm = ::parquet::FromThrift(type.GEOGRAPHY.algorithm); + } + + return GeographyLogicalType::Make(std::move(crs), algorithm); } else if (type.__isset.VARIANT) { return VariantLogicalType::Make(); } else { @@ -539,6 +565,15 @@ std::shared_ptr LogicalType::Float16() { return Float16LogicalType::Make(); } +std::shared_ptr LogicalType::Geometry(std::string crs) { + return GeometryLogicalType::Make(std::move(crs)); +} + +std::shared_ptr LogicalType::Geography( + std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm) { + return GeographyLogicalType::Make(std::move(crs), algorithm); +} + std::shared_ptr LogicalType::Variant() { return VariantLogicalType::Make(); } @@ -625,6 +660,8 @@ class LogicalType::Impl { class BSON; class UUID; class Float16; + class Geometry; + class Geography; class Variant; class No; class Undefined; @@ -698,6 +735,12 @@ bool LogicalType::is_UUID() const { return impl_->type() == LogicalType::Type::U bool LogicalType::is_float16() const { return impl_->type() == LogicalType::Type::FLOAT16; } +bool LogicalType::is_geometry() const { + return impl_->type() == LogicalType::Type::GEOMETRY; +} +bool LogicalType::is_geography() const { + return impl_->type() == LogicalType::Type::GEOGRAPHY; +} bool LogicalType::is_variant() const { return impl_->type() == LogicalType::Type::VARIANT; } @@ -1630,6 +1673,200 @@ class LogicalType::Impl::Float16 final : public LogicalType::Impl::Incompatible, GENERATE_MAKE(Float16) +namespace { +void WriteCrsKeyAndValue(const std::string_view crs, std::ostream& json) { + // There is no restriction on the crs value here, and it may contain quotes + // or backslashes that would result in invalid JSON if unescaped. + namespace rj = ::arrow::rapidjson; + rj::StringBuffer buffer; + rj::Writer writer(buffer); + rj::Value v; + v.SetString(crs.data(), static_cast(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(other); + return crs() == other_geometry.crs(); + } else { + return false; + } +} + +const std::string& GeometryLogicalType::crs() const { + return (dynamic_cast(*impl_)).crs(); +} + +std::shared_ptr GeometryLogicalType::Make(std::string crs) { + auto logical_type = std::shared_ptr(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(other); + return crs() == other_geography.crs() && algorithm() == other_geography.algorithm(); + } else { + return false; + } +} + +const std::string& GeographyLogicalType::crs() const { + return (dynamic_cast(*impl_)).crs(); +} + +LogicalType::EdgeInterpolationAlgorithm GeographyLogicalType::algorithm() const { + return (dynamic_cast(*impl_)).algorithm(); +} + +std::string_view GeographyLogicalType::algorithm_name() const { + return (dynamic_cast(*impl_)).algorithm_name(); +} + +std::shared_ptr GeographyLogicalType::Make( + std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm) { + auto logical_type = std::shared_ptr(new GeographyLogicalType()); + logical_type->impl_.reset(new LogicalType::Impl::Geography(std::move(crs), algorithm)); + return logical_type; +} class LogicalType::Impl::Variant final : public LogicalType::Impl::Incompatible, public LogicalType::Impl::Inapplicable { public: diff --git a/cpp/src/parquet/types.h b/cpp/src/parquet/types.h --- a/cpp/src/parquet/types.h +++ b/cpp/src/parquet/types.h @@ -158,6 +158,8 @@ class PARQUET_EXPORT LogicalType { BSON, UUID, FLOAT16, + GEOMETRY, + GEOGRAPHY, VARIANT, NONE // Not a real logical type; should always be last element }; @@ -167,6 +169,15 @@ class PARQUET_EXPORT LogicalType { enum unit { UNKNOWN = 0, MILLIS = 1, MICROS, NANOS }; }; + enum class EdgeInterpolationAlgorithm { + UNKNOWN = 0, + SPHERICAL = 1, + VINCENTY = 2, + THOMAS = 3, + ANDOYER = 4, + KARNEY = 5 + }; + /// \brief If possible, return a logical type equivalent to the given legacy /// converted type (and decimal metadata if applicable). static std::shared_ptr FromConvertedType( @@ -215,6 +226,12 @@ class PARQUET_EXPORT LogicalType { static std::shared_ptr Float16(); static std::shared_ptr Variant(); + static std::shared_ptr Geometry(std::string crs = ""); + + static std::shared_ptr Geography( + std::string crs = "", LogicalType::EdgeInterpolationAlgorithm algorithm = + EdgeInterpolationAlgorithm::SPHERICAL); + /// \brief Create a placeholder for when no logical type is specified static std::shared_ptr None(); @@ -268,6 +285,8 @@ class PARQUET_EXPORT LogicalType { bool is_BSON() const; bool is_UUID() const; bool is_float16() const; + bool is_geometry() const; + bool is_geography() const; bool is_variant() const; bool is_none() const; /// \brief Return true if this logical type is of a known type. @@ -449,6 +468,30 @@ class PARQUET_EXPORT Float16LogicalType : public LogicalType { Float16LogicalType() = default; }; +class PARQUET_EXPORT GeometryLogicalType : public LogicalType { + public: + static std::shared_ptr Make(std::string crs = ""); + + const std::string& crs() const; + + private: + GeometryLogicalType() = default; +}; + +class PARQUET_EXPORT GeographyLogicalType : public LogicalType { + public: + static std::shared_ptr Make( + std::string crs = "", LogicalType::EdgeInterpolationAlgorithm algorithm = + EdgeInterpolationAlgorithm::SPHERICAL); + + const std::string& crs() const; + LogicalType::EdgeInterpolationAlgorithm algorithm() const; + std::string_view algorithm_name() const; + + private: + GeographyLogicalType() = default; +}; + /// \brief Allowed for group nodes only. class PARQUET_EXPORT VariantLogicalType : public LogicalType { public: diff --git a/cpp/src/parquet/CMakeLists.txt b/cpp/src/parquet/CMakeLists.txt index bc7e4f3..735653d 100644 --- a/cpp/src/parquet/CMakeLists.txt +++ b/cpp/src/parquet/CMakeLists.txt @@ -171,6 +171,9 @@ set(PARQUET_SRCS exception.cc file_reader.cc file_writer.cc + geospatial/statistics.cc + geospatial/util_internal.cc + geospatial/util_json_internal.cc level_comparison.cc level_conversion.cc metadata.cc @@ -257,6 +260,10 @@ endif() if(NOT PARQUET_MINIMAL_DEPENDENCY) list(APPEND PARQUET_SHARED_LINK_LIBS arrow_shared) + # Add RapidJSON libraries + list(APPEND PARQUET_SHARED_PRIVATE_LINK_LIBS RapidJSON) + list(APPEND PARQUET_STATIC_LINK_LIBS RapidJSON) + # These are libraries that we will link privately with parquet_shared (as they # do not need to be linked transitively by other linkers) list(APPEND PARQUET_SHARED_PRIVATE_LINK_LIBS thrift::thrift) @@ -352,6 +359,7 @@ endif() add_subdirectory(api) add_subdirectory(arrow) add_subdirectory(encryption) +add_subdirectory(geospatial) arrow_install_all_headers("parquet") @@ -362,15 +370,17 @@ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/parquet_version.h" add_parquet_test(internals-test SOURCES - bloom_filter_test.cc bloom_filter_reader_test.cc - properties_test.cc - statistics_test.cc + bloom_filter_test.cc encoding_test.cc + geospatial/statistics_test.cc + geospatial/util_internal_test.cc metadata_test.cc page_index_test.cc + properties_test.cc public_api_test.cc size_statistics_test.cc + statistics_test.cc types_test.cc) set_source_files_properties(public_api_test.cc PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON)