From d761c5e40c24cbd0dba9f730c25cfd1ca5603830 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Wed, 28 Oct 2026 08:11:39 +0000 Subject: [PATCH 1/6] feat(view): add view metadata types and validation Deliver the view format v1 metadata model beside its table equivalent: - ViewVersion carries version-id, schema-id, timestamp-ms, summary, representations, optional default catalog, and required default namespace. - Representations are SQL (sql, dialect) or opaque unknown types preserved for round trips, modeled as a variant with GetSql and RepresentationType helpers. - ViewMetadata carries view-uuid, format-version, location, schemas, current-version-id, versions, version-log, and properties, with CurrentVersion/VersionById/CurrentSchema/SchemaById accessors returning NotFound for missing entries. - Validate() checks view-v1 invariants without applying table-format schema restrictions: supported format version, non-empty UUID/location, listed schemas/versions with unique IDs, current-version and schema references, non-empty default namespaces, non-empty SQL representations with at most one per dialect under ASCII case folding, and non-empty unknown representation types. - Add StringUtils::EqualsIgnoreCaseAscii for the ASCII-only dialect folding; existing Unicode-aware EqualsIgnoreCase is unchanged. - view_metadata_test validates synthetic metadata: every invariant violated one at a time with asserted error kinds, accepted shapes including unknown representations, accessor NotFound behavior, and equality. --- src/iceberg/CMakeLists.txt | 4 +- src/iceberg/cpp20_compatibility_internal.h | 2 + src/iceberg/test/CMakeLists.txt | 2 + src/iceberg/test/view_metadata_test.cc | 279 +++++++++++++++++++++ src/iceberg/type_fwd.h | 7 + src/iceberg/util/string_util.h | 18 ++ src/iceberg/view_metadata.cc | 161 ++++++++++++ src/iceberg/view_metadata.h | 124 +++++++++ src/iceberg/view_version.cc | 43 ++++ src/iceberg/view_version.h | 121 +++++++++ 10 files changed, 760 insertions(+), 1 deletion(-) create mode 100644 src/iceberg/test/view_metadata_test.cc create mode 100644 src/iceberg/view_metadata.cc create mode 100644 src/iceberg/view_metadata.h create mode 100644 src/iceberg/view_version.cc create mode 100644 src/iceberg/view_version.h diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 4d3bc3facf..3956ac3b5c 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -177,7 +177,9 @@ set(ICEBERG_SOURCES util/truncate_util.cc util/type_util.cc util/url_encoder.cc - util/uuid.cc) + util/uuid.cc + view_metadata.cc + view_version.cc) set(ICEBERG_STATIC_BUILD_INTERFACE_LIBS) set(ICEBERG_SHARED_BUILD_INTERFACE_LIBS) diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index ef7ac765d4..32111d657f 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -208,6 +208,8 @@ #include "iceberg/util/uuid.h" #include "iceberg/util/visit_type.h" #include "iceberg/util/visitor_generate.h" +#include "iceberg/view_metadata.h" +#include "iceberg/view_version.h" #ifdef ICEBERG_PUBLIC_HEADERS_BUNDLE # include "iceberg/arrow/arrow_io_util.h" diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 020797be82..2aeb5a170b 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -161,6 +161,8 @@ endif() add_iceberg_test(scheduled_executor_test SOURCES scheduled_executor_test.cc) set_tests_properties(scheduled_executor_test PROPERTIES TIMEOUT 60) +add_iceberg_test(view_metadata_test SOURCES view_metadata_test.cc) + add_iceberg_test(util_test USE_DATA SOURCES diff --git a/src/iceberg/test/view_metadata_test.cc b/src/iceberg/test/view_metadata_test.cc new file mode 100644 index 0000000000..51228755f4 --- /dev/null +++ b/src/iceberg/test/view_metadata_test.cc @@ -0,0 +1,279 @@ +/* + * 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 "iceberg/view_metadata.h" + +#include +#include +#include + +#include + +#include "iceberg/schema.h" +#include "iceberg/schema_field.h" +#include "iceberg/test/matchers.h" +#include "iceberg/type.h" + +namespace iceberg { +namespace { + +ViewRepresentation SqlRepr(std::string sql, std::string dialect) { + return SqlViewRepresentation{.sql = std::move(sql), .dialect = std::move(dialect)}; +} + +std::shared_ptr MakeSchema(int32_t schema_id) { + return std::make_shared( + std::vector{SchemaField::MakeRequired(1, "customer_id", int64()), + SchemaField::MakeOptional(2, "country", string())}, + schema_id); +} + +ViewVersion MakeVersion(int32_t version_id, int32_t schema_id, + std::vector representations) { + return ViewVersion{ + .version_id = version_id, + .schema_id = schema_id, + .timestamp_ms = TimePointMs{std::chrono::milliseconds(1600000000000)}, + .summary = {{"engine-name", "test"}}, + .representations = std::move(representations), + .default_catalog = "prod", + .default_namespace = Namespace{{"analytics"}}, + }; +} + +ViewMetadata MakeValidMetadata() { + ViewMetadata metadata; + metadata.format_version = ViewMetadata::kDefaultViewFormatVersion; + metadata.view_uuid = "fa6506c3-7681-40c8-86dc-e36561f83385"; + metadata.location = "s3://bucket/warehouse/analytics.db/active_customers"; + metadata.schemas = {MakeSchema(0)}; + metadata.current_version_id = 0; + metadata.versions = {std::make_shared( + MakeVersion(0, 0, {SqlRepr("SELECT customer_id FROM customers", "spark")}))}; + metadata.version_log = {ViewHistoryEntry{ + .timestamp_ms = TimePointMs{std::chrono::milliseconds(1600000000000)}, + .version_id = 0, + }}; + metadata.properties = {{"comment", "active customers"}}; + return metadata; +} + +TEST(ViewMetadataTest, ValidateAcceptsValidMetadata) { + ViewMetadata metadata = MakeValidMetadata(); + EXPECT_THAT(metadata.Validate(), IsOk()); + + auto current = metadata.CurrentVersion(); + ASSERT_THAT(current, IsOk()); + EXPECT_EQ(current->get()->version_id, 0); + + auto current_schema = metadata.CurrentSchema(); + ASSERT_THAT(current_schema, IsOk()); + EXPECT_EQ(current_schema->get()->schema_id(), 0); +} + +TEST(ViewMetadataTest, ValidateAcceptsUnknownRepresentation) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->representations.push_back( + UnknownViewRepresentation{.type = "cypher"}); + EXPECT_THAT(metadata.Validate(), IsOk()); +} + +TEST(ViewMetadataTest, ValidateAcceptsMultipleVersionsAndDialects) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.schemas.push_back(MakeSchema(1)); + metadata.current_version_id = 1; + metadata.versions[0]->representations.push_back( + SqlRepr("SELECT customer_id, country FROM customers WHERE active = true", "trino")); + metadata.versions.push_back(std::make_shared(MakeVersion( + 1, 1, + {SqlRepr("SELECT customer_id, country FROM customers WHERE active = true", + "Trino")}))); + metadata.version_log.push_back(ViewHistoryEntry{ + .timestamp_ms = TimePointMs{std::chrono::milliseconds(1600000001000)}, + .version_id = 1, + }); + EXPECT_THAT(metadata.Validate(), IsOk()); + + auto current_schema = metadata.CurrentSchema(); + ASSERT_THAT(current_schema, IsOk()); + EXPECT_EQ(current_schema->get()->schema_id(), 1); +} + +TEST(ViewMetadataTest, ValidateRejectsUnsupportedFormatVersion) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.format_version = 2; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsEmptyUuid) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.view_uuid.clear(); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsEmptyLocation) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.location.clear(); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsMissingSchemas) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.schemas.clear(); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsNullSchema) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.schemas.push_back(nullptr); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsDuplicateSchemaIds) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.schemas.push_back(MakeSchema(0)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsMissingVersions) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions.clear(); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsNullVersion) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions.push_back(nullptr); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsDuplicateVersionIds) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions.push_back(std::make_shared( + MakeVersion(0, 0, {SqlRepr("SELECT customer_id FROM customers", "trino")}))); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsUnlistedCurrentVersion) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.current_version_id = 7; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + + auto current = metadata.CurrentVersion(); + EXPECT_THAT(current, IsError(ErrorKind::kNotFound)); +} + +TEST(ViewMetadataTest, ValidateRejectsUnlistedSchemaReference) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->schema_id = 5; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsEmptyDefaultNamespace) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->default_namespace = Namespace{}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsDuplicateDialects) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->representations.push_back( + SqlRepr("SELECT customer_id FROM customers", "spark")); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsDuplicateDialectsWithCaseFolding) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->representations.push_back( + SqlRepr("SELECT customer_id FROM customers", "SPARK")); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsSqlRepresentationWithoutSql) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->representations = {SqlRepr("", "spark")}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsSqlRepresentationWithoutDialect) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->representations = {SqlRepr("SELECT 1", "")}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsUnknownRepresentationWithoutType) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->representations = {UnknownViewRepresentation{.type = ""}}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, AccessorsReturnNotFoundForMissingEntries) { + ViewMetadata metadata = MakeValidMetadata(); + EXPECT_THAT(metadata.VersionById(999), IsError(ErrorKind::kNotFound)); + EXPECT_THAT(metadata.SchemaById(999), IsError(ErrorKind::kNotFound)); + + metadata.versions.push_back(nullptr); + EXPECT_THAT(metadata.VersionById(999), IsError(ErrorKind::kNotFound)); +} + +TEST(ViewMetadataTest, EqualityComparesAllFields) { + ViewMetadata lhs = MakeValidMetadata(); + ViewMetadata rhs = MakeValidMetadata(); + EXPECT_EQ(lhs, rhs); + + rhs.properties.at("comment") = "changed"; + EXPECT_NE(lhs, rhs); + + ViewMetadata changed = MakeValidMetadata(); + changed.versions[0]->representations.push_back( + UnknownViewRepresentation{.type = "cypher"}); + EXPECT_NE(lhs, changed); + + ViewMetadata unknown = lhs; + unknown.versions[0]->representations.push_back( + UnknownViewRepresentation{.type = "cypher"}); + EXPECT_EQ(unknown, changed); +} + +TEST(ViewVersionTest, EqualityComparesAllFields) { + ViewVersion lhs = MakeVersion(0, 0, {SqlRepr("SELECT 1", "spark")}); + ViewVersion rhs = MakeVersion(0, 0, {SqlRepr("SELECT 1", "spark")}); + EXPECT_EQ(lhs, rhs); + + rhs.representations[0] = SqlRepr("SELECT 1", "trino"); + EXPECT_NE(lhs, rhs); + + rhs.representations[0] = SqlRepr("SELECT 2", "spark"); + EXPECT_NE(lhs, rhs); +} + +TEST(ViewRepresentationTest, Helpers) { + const ViewRepresentation sql = SqlRepr("SELECT 1", "spark"); + const auto* sql_repr = GetSql(sql); + ASSERT_NE(sql_repr, nullptr); + EXPECT_EQ(sql_repr->dialect, "spark"); + EXPECT_EQ(RepresentationType(sql), kSqlRepresentationType); + + const ViewRepresentation unknown = UnknownViewRepresentation{.type = "cypher"}; + EXPECT_EQ(GetSql(unknown), nullptr); + EXPECT_EQ(RepresentationType(unknown), "cypher"); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/type_fwd.h b/src/iceberg/type_fwd.h index 354495e387..a42479c9ef 100644 --- a/src/iceberg/type_fwd.h +++ b/src/iceberg/type_fwd.h @@ -148,6 +148,13 @@ struct TableMetadata; class InheritableMetadata; class SnapshotSummaryBuilder; +/// \brief View metadata. +struct SqlViewRepresentation; +struct UnknownViewRepresentation; +struct ViewHistoryEntry; +struct ViewMetadata; +struct ViewVersion; + /// \brief Expression. class BoundPredicate; class BoundReference; diff --git a/src/iceberg/util/string_util.h b/src/iceberg/util/string_util.h index f1431e49d4..09e7d96488 100644 --- a/src/iceberg/util/string_util.h +++ b/src/iceberg/util/string_util.h @@ -98,6 +98,24 @@ class ICEBERG_EXPORT StringUtils { return ToLower(str).starts_with(ToLower(prefix)); } + /// \brief Case-insensitive equality folding only ASCII letters (A-Z, a-z). + /// + /// Non-ASCII bytes compare unchanged, so folding never changes the length + /// of either operand. Use this for identifiers, such as SQL dialects, whose + /// comparison rules specify ASCII folding; use EqualsIgnoreCase for + /// Unicode-aware comparison. + static bool EqualsIgnoreCaseAscii(std::string_view a, std::string_view b) { + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < a.size(); ++i) { + if (ToLowerAscii(a[i]) != ToLowerAscii(b[i])) { + return false; + } + } + return true; + } + /// \brief Count the number of code points in a UTF-8 string. static size_t CodePointCount(std::string_view str) { size_t count = 0; diff --git a/src/iceberg/view_metadata.cc b/src/iceberg/view_metadata.cc new file mode 100644 index 0000000000..ae757bc501 --- /dev/null +++ b/src/iceberg/view_metadata.cc @@ -0,0 +1,161 @@ +/* + * 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 "iceberg/view_metadata.h" + +#include +#include + +#include "iceberg/schema.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/string_util.h" + +namespace iceberg { + +Status ViewMetadata::Validate() const { + if (format_version != kSupportedViewFormatVersion) { + return Invalid("Unsupported view format version: {}", + static_cast(format_version)); + } + if (view_uuid.empty()) { + return Invalid("View UUID must not be empty"); + } + if (location.empty()) { + return Invalid("View location must not be empty"); + } + if (schemas.empty()) { + return Invalid("View metadata must list at least one schema"); + } + + std::unordered_set schema_ids; + for (const auto& schema : schemas) { + if (schema == nullptr) { + return Invalid("View schemas must not be null"); + } + if (!schema_ids.insert(schema->schema_id()).second) { + return Invalid("Duplicate view schema ID: {}", schema->schema_id()); + } + } + + if (versions.empty()) { + return Invalid("View metadata must list at least one version"); + } + std::unordered_set version_ids; + for (const auto& version : versions) { + if (version == nullptr) { + return Invalid("View versions must not be null"); + } + if (!version_ids.insert(version->version_id).second) { + return Invalid("Duplicate view version ID: {}", version->version_id); + } + } + if (!version_ids.contains(current_version_id)) { + return Invalid("Current version ID {} is not a listed view version", + current_version_id); + } + + for (const auto& version : versions) { + if (!schema_ids.contains(version->schema_id)) { + return Invalid("View version {} references unlisted schema ID {}", + version->version_id, version->schema_id); + } + if (version->default_namespace.levels.empty()) { + return Invalid("View version {} must have a non-empty default namespace", + version->version_id); + } + + std::vector dialects; + for (const auto& repr : version->representations) { + if (const auto* sql = GetSql(repr)) { + if (sql->sql.empty()) { + return Invalid("View version {} has an SQL representation without SQL", + version->version_id); + } + if (sql->dialect.empty()) { + return Invalid("View version {} has an SQL representation without a dialect", + version->version_id); + } + for (const auto& dialect : dialects) { + if (StringUtils::EqualsIgnoreCaseAscii(dialect, sql->dialect)) { + return Invalid( + "View version {} has multiple SQL representations for dialect '{}'", + version->version_id, sql->dialect); + } + } + dialects.push_back(sql->dialect); + } else { + const auto& unknown = std::get(repr); + if (unknown.type.empty()) { + return Invalid("View version {} has an unknown representation without a type", + version->version_id); + } + } + } + } + return {}; +} + +Result> ViewMetadata::CurrentVersion() const { + return VersionById(current_version_id); +} + +Result> ViewMetadata::VersionById(int32_t version_id) const { + auto iter = std::ranges::find_if(versions, [version_id](const auto& version) { + return version != nullptr && version->version_id == version_id; + }); + if (iter == versions.end()) { + return NotFound("View version with ID {} is not found", version_id); + } + return *iter; +} + +Result> ViewMetadata::CurrentSchema() const { + ICEBERG_ASSIGN_OR_RAISE(auto version, CurrentVersion()); + return SchemaById(version->schema_id); +} + +Result> ViewMetadata::SchemaById(int32_t schema_id) const { + auto iter = std::ranges::find_if(schemas, [schema_id](const auto& schema) { + return schema != nullptr && schema->schema_id() == schema_id; + }); + if (iter == schemas.end()) { + return NotFound("View schema with ID {} is not found", schema_id); + } + return *iter; +} + +bool ViewMetadata::Equals(const ViewMetadata& other) const { + auto shared_ptr_equals = [](const auto& lhs, const auto& rhs) { + if (lhs == nullptr || rhs == nullptr) { + return lhs == rhs; + } + return *lhs == *rhs; + }; + return format_version == other.format_version && view_uuid == other.view_uuid && + location == other.location && schemas.size() == other.schemas.size() && + std::equal(schemas.begin(), schemas.end(), other.schemas.begin(), + shared_ptr_equals) && + current_version_id == other.current_version_id && + versions.size() == other.versions.size() && + std::equal(versions.begin(), versions.end(), other.versions.begin(), + shared_ptr_equals) && + version_log == other.version_log && properties == other.properties; +} + +} // namespace iceberg diff --git a/src/iceberg/view_metadata.h b/src/iceberg/view_metadata.h new file mode 100644 index 0000000000..988157ed0e --- /dev/null +++ b/src/iceberg/view_metadata.h @@ -0,0 +1,124 @@ +/* + * 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 + +/// \file iceberg/view_metadata.h +/// View metadata for Iceberg views. + +#include +#include +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" +#include "iceberg/util/timepoint.h" +#include "iceberg/view_version.h" + +namespace iceberg { + +/// \brief Represents a view history entry, which records a change to the +/// current version of a view. +struct ICEBERG_EXPORT ViewHistoryEntry { + /// The timestamp in milliseconds of the change to the current version. + TimePointMs timestamp_ms; + /// ID of the view version that was made current. + int32_t version_id; + + /// \brief Compare two view history entries for equality. + friend bool operator==(const ViewHistoryEntry& lhs, const ViewHistoryEntry& rhs) { + return lhs.timestamp_ms == rhs.timestamp_ms && lhs.version_id == rhs.version_id; + } +}; + +/// \brief Represents the metadata for an Iceberg view. +/// +/// View metadata follows view format version 1. Table-format schema +/// restrictions are deliberately not applied to the view's schemas: view +/// schemas are projections of the referenced tables' columns and may use +/// types or nullability that table data would reject. +struct ICEBERG_EXPORT ViewMetadata { + static constexpr int8_t kDefaultViewFormatVersion = 1; + static constexpr int8_t kSupportedViewFormatVersion = 1; + + /// An integer version number for the view format; must be 1. + int8_t format_version; + /// A UUID that identifies the view, generated when the view is created. + std::string view_uuid; + /// The view's base location; used to create metadata file locations. + std::string location; + /// A list of known schemas. + std::vector> schemas; + /// ID of the current version of the view. + int32_t current_version_id; + /// A list of known versions of the view. + std::vector> versions; + /// A list of timestamp and version ID pairs that encodes changes to the + /// current version. + std::vector version_log; + /// A string to string map of view properties. + std::unordered_map properties; + + /// \brief Validate view format v1 invariants. + /// + /// Checks referential integrity, required fields, and per-dialect + /// uniqueness of SQL representations, without applying table-format schema + /// restrictions. Never modifies the metadata. + /// + /// \return Status indicating success, or ErrorKind::kInvalid with the first + /// violated invariant. + Status Validate() const; + + /// \brief Get the current view version. + /// \return the current version or ErrorKind::kNotFound if it is not listed. + /// \note The returned version is guaranteed to be not null. + Result> CurrentVersion() const; + + /// \brief Get a view version by ID. + /// \param version_id ID of the view version to look up + /// \return the version or ErrorKind::kNotFound if it is not listed. + /// \note The returned version is guaranteed to be not null. + Result> VersionById(int32_t version_id) const; + + /// \brief Get the schema of the current view version. + /// \return the current schema or ErrorKind::kNotFound if the current + /// version or its schema is not listed. + /// \note The returned schema is guaranteed to be not null. + Result> CurrentSchema() const; + + /// \brief Get a view schema by ID. + /// \param schema_id ID of the schema to look up + /// \return the schema or ErrorKind::kNotFound if it is not listed. + /// \note The returned schema is guaranteed to be not null. + Result> SchemaById(int32_t schema_id) const; + + /// \brief Compare two view metadata for equality. + friend bool operator==(const ViewMetadata& lhs, const ViewMetadata& rhs) { + return lhs.Equals(rhs); + } + + private: + /// \brief Compare two view metadata for equality. + bool Equals(const ViewMetadata& other) const; +}; + +} // namespace iceberg diff --git a/src/iceberg/view_version.cc b/src/iceberg/view_version.cc new file mode 100644 index 0000000000..691b304eea --- /dev/null +++ b/src/iceberg/view_version.cc @@ -0,0 +1,43 @@ +/* + * 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 "iceberg/view_version.h" + +namespace iceberg { + +const SqlViewRepresentation* GetSql(const ViewRepresentation& repr) { + return std::get_if(&repr); +} + +std::string_view RepresentationType(const ViewRepresentation& repr) { + if (const auto* sql = GetSql(repr)) { + return kSqlRepresentationType; + } + return std::get(repr).type; +} + +bool ViewVersion::Equals(const ViewVersion& other) const { + return version_id == other.version_id && schema_id == other.schema_id && + timestamp_ms == other.timestamp_ms && summary == other.summary && + representations == other.representations && + default_catalog == other.default_catalog && + default_namespace == other.default_namespace; +} + +} // namespace iceberg diff --git a/src/iceberg/view_version.h b/src/iceberg/view_version.h new file mode 100644 index 0000000000..3626c817df --- /dev/null +++ b/src/iceberg/view_version.h @@ -0,0 +1,121 @@ +/* + * 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 + +/// \file iceberg/view_version.h +/// A version of an Iceberg view. + +#include +#include +#include +#include +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/table_identifier.h" +#include "iceberg/util/timepoint.h" + +namespace iceberg { + +/// \brief The SQL representation of a view version's definition. +/// +/// Each SQL representation pairs a query with its engine dialect, such as +/// "spark". Dialect strings are preserved verbatim and compared with ASCII +/// case folding. +struct ICEBERG_EXPORT SqlViewRepresentation { + /// The SQL SELECT statement that defines the view. + std::string sql; + /// The dialect of the SELECT statement, such as "spark" or "trino". + std::string dialect; + + /// \brief Compare two SQL representations for equality. + friend bool operator==(const SqlViewRepresentation& lhs, + const SqlViewRepresentation& rhs) = default; +}; + +/// \brief An opaque representation type this library does not interpret. +/// +/// Unknown representations are preserved so that metadata round trips and +/// property edits do not lose them. Definition changes that involve them are +/// rejected instead of being partially rewritten. +struct ICEBERG_EXPORT UnknownViewRepresentation { + /// The representation type identifier from the metadata, such as "cypher". + std::string type; + + /// \brief Compare two unknown representations for equality. + friend bool operator==(const UnknownViewRepresentation& lhs, + const UnknownViewRepresentation& rhs) = default; +}; + +/// \brief A representation of a view version's definition: SQL or opaque. +using ViewRepresentation = std::variant; + +/// \brief The type identifier of the SQL representation. +inline constexpr std::string_view kSqlRepresentationType = "sql"; + +/// \brief Get the SQL representation. +/// +/// \return the SQL representation, or nullptr when the representation is not +/// a SQL representation. The pointer remains valid until the representation +/// is modified or destroyed. +ICEBERG_EXPORT const SqlViewRepresentation* GetSql(const ViewRepresentation& repr); + +/// \brief Get the representation's type identifier. +/// +/// Returns kSqlRepresentationType for SQL representations and the opaque +/// type identifier otherwise. +ICEBERG_EXPORT std::string_view RepresentationType(const ViewRepresentation& repr); + +/// \brief A view version, the state of a view's definition at a point in time. +/// +/// View versions are immutable: a definition change creates a new version. +/// A version can carry more than one representation, but at most one SQL +/// representation per dialect. +struct ICEBERG_EXPORT ViewVersion { + /// ID of the view version. + int32_t version_id; + /// ID of the schema for this view version. + int32_t schema_id; + /// Timestamp in milliseconds from the unix epoch when the version was created. + TimePointMs timestamp_ms; + /// Summary metadata about the version, such as "engine-name" and + /// "engine-version". + std::unordered_map summary; + /// A list of representations for the view definition. + std::vector representations; + /// Catalog name to use when a reference in the SELECT does not contain a + /// catalog. When unset, the catalog in which the view is stored is used. + std::optional default_catalog; + /// Namespace to use when a reference in the SELECT is a single identifier. + Namespace default_namespace; + + /// \brief Compare two view versions for equality. + friend bool operator==(const ViewVersion& lhs, const ViewVersion& rhs) { + return lhs.Equals(rhs); + } + + private: + /// \brief Compare two view versions for equality. + bool Equals(const ViewVersion& other) const; +}; + +} // namespace iceberg From 25280fbedaeafc945c2c4d55f07bf0b942fae623 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 9 Nov 2026 07:39:08 +0000 Subject: [PATCH 2/6] fix(view): validate version log references --- src/iceberg/test/view_metadata_test.cc | 21 +++++++++++++++++++++ src/iceberg/view_metadata.cc | 5 +++++ 2 files changed, 26 insertions(+) diff --git a/src/iceberg/test/view_metadata_test.cc b/src/iceberg/test/view_metadata_test.cc index 51228755f4..9aa0ba3426 100644 --- a/src/iceberg/test/view_metadata_test.cc +++ b/src/iceberg/test/view_metadata_test.cc @@ -185,6 +185,27 @@ TEST(ViewMetadataTest, ValidateRejectsUnlistedSchemaReference) { EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); } +TEST(ViewMetadataTest, ValidateRejectsUnlistedHistoryVersion) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.version_log[0].version_id = 999; + auto result = metadata.Validate(); + EXPECT_THAT(result, IsError(ErrorKind::kInvalid)); + EXPECT_THAT(result, HasErrorMessage("View history references unlisted version ID 999")); +} + +TEST(ViewMetadataTest, ValidateAcceptsHistoryWithRollback) { + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions.push_back(std::make_shared( + MakeVersion(1, 0, {SqlRepr("SELECT country FROM customers", "spark")}))); + metadata.version_log.push_back(ViewHistoryEntry{ + .timestamp_ms = TimePointMsFromUnixMs(1600000001000), .version_id = 1}); + metadata.version_log.push_back(ViewHistoryEntry{ + .timestamp_ms = TimePointMsFromUnixMs(1600000002000), .version_id = 0}); + ViewMetadata before = metadata; + EXPECT_THAT(metadata.Validate(), IsOk()); + EXPECT_EQ(metadata, before); +} + TEST(ViewMetadataTest, ValidateRejectsEmptyDefaultNamespace) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->default_namespace = Namespace{}; diff --git a/src/iceberg/view_metadata.cc b/src/iceberg/view_metadata.cc index ae757bc501..88fb6ae2ba 100644 --- a/src/iceberg/view_metadata.cc +++ b/src/iceberg/view_metadata.cc @@ -69,6 +69,11 @@ Status ViewMetadata::Validate() const { return Invalid("Current version ID {} is not a listed view version", current_version_id); } + for (const auto& entry : version_log) { + if (!version_ids.contains(entry.version_id)) { + return Invalid("View history references unlisted version ID {}", entry.version_id); + } + } for (const auto& version : versions) { if (!schema_ids.contains(version->schema_id)) { From f660122beceb5f14f9ba4cfc80cefe23904b276e Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 9 Nov 2026 07:56:05 +0000 Subject: [PATCH 3/6] ci: retry checks after dependency download failures From 9e06fcddd7f62095f533a9ea33461a90ee1d9cfe Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 9 Nov 2026 08:03:13 +0000 Subject: [PATCH 4/6] style(view): use emplace_back for representations --- src/iceberg/test/view_metadata_test.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/iceberg/test/view_metadata_test.cc b/src/iceberg/test/view_metadata_test.cc index 9aa0ba3426..3f3b03bba6 100644 --- a/src/iceberg/test/view_metadata_test.cc +++ b/src/iceberg/test/view_metadata_test.cc @@ -89,7 +89,7 @@ TEST(ViewMetadataTest, ValidateAcceptsValidMetadata) { TEST(ViewMetadataTest, ValidateAcceptsUnknownRepresentation) { ViewMetadata metadata = MakeValidMetadata(); - metadata.versions[0]->representations.push_back( + metadata.versions[0]->representations.emplace_back( UnknownViewRepresentation{.type = "cypher"}); EXPECT_THAT(metadata.Validate(), IsOk()); } @@ -262,12 +262,12 @@ TEST(ViewMetadataTest, EqualityComparesAllFields) { EXPECT_NE(lhs, rhs); ViewMetadata changed = MakeValidMetadata(); - changed.versions[0]->representations.push_back( + changed.versions[0]->representations.emplace_back( UnknownViewRepresentation{.type = "cypher"}); EXPECT_NE(lhs, changed); ViewMetadata unknown = lhs; - unknown.versions[0]->representations.push_back( + unknown.versions[0]->representations.emplace_back( UnknownViewRepresentation{.type = "cypher"}); EXPECT_EQ(unknown, changed); } From b2bdbdae45bb1b250379adabdb6af75fc7520566 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Sat, 28 Nov 2026 05:08:00 +0000 Subject: [PATCH 5/6] refactor(view): move view metadata into iceberg/view and harden validation - Move view metadata and version sources and headers into a view subdirectory with its own type_fwd.h. - Reject temporary variants in GetSql and RepresentationType. - Default-initialize scalar members of view metadata, versions, and history entries. - Accept an empty default namespace, as Java writes it. - Reject duplicate field IDs in view schemas. - Reserve the SQL representation type for SQL representations, including Java's case-insensitive variants. - Validate view UUIDs with the UUID parser. - Normalize SQL dialects with Unicode case folding before checking for duplicates. Co-authored-by: Isaac --- src/iceberg/CMakeLists.txt | 5 +- src/iceberg/cpp20_compatibility_internal.h | 5 +- src/iceberg/test/view_metadata_test.cc | 100 ++++++++++++++++++++- src/iceberg/type_fwd.h | 7 -- src/iceberg/util/string_util.h | 18 ---- src/iceberg/view/CMakeLists.txt | 18 ++++ src/iceberg/view/type_fwd.h | 33 +++++++ src/iceberg/{ => view}/view_metadata.cc | 41 +++++---- src/iceberg/{ => view}/view_metadata.h | 13 +-- src/iceberg/{ => view}/view_version.cc | 2 +- src/iceberg/{ => view}/view_version.h | 18 ++-- 11 files changed, 199 insertions(+), 61 deletions(-) create mode 100644 src/iceberg/view/CMakeLists.txt create mode 100644 src/iceberg/view/type_fwd.h rename src/iceberg/{ => view}/view_metadata.cc (80%) rename src/iceberg/{ => view}/view_metadata.h (94%) rename src/iceberg/{ => view}/view_version.cc (97%) rename src/iceberg/{ => view}/view_version.h (90%) diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 3956ac3b5c..72932049be 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -178,8 +178,8 @@ set(ICEBERG_SOURCES util/type_util.cc util/url_encoder.cc util/uuid.cc - view_metadata.cc - view_version.cc) + view/view_metadata.cc + view/view_version.cc) set(ICEBERG_STATIC_BUILD_INTERFACE_LIBS) set(ICEBERG_SHARED_BUILD_INTERFACE_LIBS) @@ -313,6 +313,7 @@ add_subdirectory(util) add_subdirectory(inspect) add_subdirectory(metrics) add_subdirectory(logging) +add_subdirectory(view) if(ICEBERG_BUILD_BUNDLE) set(ICEBERG_BUNDLE_SOURCES diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 32111d657f..5f730f3210 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -208,8 +208,9 @@ #include "iceberg/util/uuid.h" #include "iceberg/util/visit_type.h" #include "iceberg/util/visitor_generate.h" -#include "iceberg/view_metadata.h" -#include "iceberg/view_version.h" +#include "iceberg/view/type_fwd.h" +#include "iceberg/view/view_metadata.h" +#include "iceberg/view/view_version.h" #ifdef ICEBERG_PUBLIC_HEADERS_BUNDLE # include "iceberg/arrow/arrow_io_util.h" diff --git a/src/iceberg/test/view_metadata_test.cc b/src/iceberg/test/view_metadata_test.cc index 3f3b03bba6..29b3496f37 100644 --- a/src/iceberg/test/view_metadata_test.cc +++ b/src/iceberg/test/view_metadata_test.cc @@ -17,10 +17,11 @@ * under the License. */ -#include "iceberg/view_metadata.h" +#include "iceberg/view/view_metadata.h" #include #include +#include #include #include @@ -33,6 +34,27 @@ namespace iceberg { namespace { +template +concept CanGetSql = requires(T&& repr) { GetSql(std::forward(repr)); }; + +template +concept CanGetRepresentationType = + requires(T&& repr) { RepresentationType(std::forward(repr)); }; + +static_assert(CanGetSql); +static_assert(CanGetSql); +static_assert(!CanGetSql); +static_assert(!CanGetSql); +static_assert(!CanGetSql); +static_assert(!CanGetSql); +static_assert(!CanGetSql); +static_assert(CanGetRepresentationType); +static_assert(CanGetRepresentationType); +static_assert(!CanGetRepresentationType); +static_assert(!CanGetRepresentationType); +static_assert(!CanGetRepresentationType); +static_assert(!CanGetRepresentationType); + ViewRepresentation SqlRepr(std::string sql, std::string dialect) { return SqlViewRepresentation{.sql = std::move(sql), .dialect = std::move(dialect)}; } @@ -121,12 +143,42 @@ TEST(ViewMetadataTest, ValidateRejectsUnsupportedFormatVersion) { EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); } +TEST(ViewMetadataTest, DefaultConstructionInitializesScalars) { + ViewMetadata metadata; + EXPECT_EQ(metadata.format_version, ViewMetadata::kDefaultViewFormatVersion); + EXPECT_EQ(metadata.current_version_id, -1); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + ViewVersion version; + EXPECT_EQ(version.version_id, 0); + EXPECT_EQ(version.schema_id, 0); + EXPECT_EQ(version.timestamp_ms, TimePointMs{}); + ViewHistoryEntry entry; + EXPECT_EQ(entry.version_id, 0); + EXPECT_EQ(entry.timestamp_ms, TimePointMs{}); +} + TEST(ViewMetadataTest, ValidateRejectsEmptyUuid) { ViewMetadata metadata = MakeValidMetadata(); metadata.view_uuid.clear(); EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); } +TEST(ViewMetadataTest, ValidateRejectsMalformedUuid) { + for (const auto* uuid : {"x", "fa6506c3-7681-40c8-86dc-e36561f8338g", + "fa6506c3-7681-40c8-86dc-e36561f8338"}) { + SCOPED_TRACE(uuid); + auto metadata = MakeValidMetadata(); + metadata.view_uuid = uuid; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + } +} + +TEST(ViewMetadataTest, ValidateAcceptsUppercaseUuid) { + auto metadata = MakeValidMetadata(); + metadata.view_uuid = "FA6506C3-7681-40C8-86DC-E36561F83385"; + EXPECT_THAT(metadata.Validate(), IsOk()); +} + TEST(ViewMetadataTest, ValidateRejectsEmptyLocation) { ViewMetadata metadata = MakeValidMetadata(); metadata.location.clear(); @@ -151,6 +203,32 @@ TEST(ViewMetadataTest, ValidateRejectsDuplicateSchemaIds) { EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); } +TEST(ViewMetadataTest, ValidateRejectsDuplicateFieldIds) { + auto metadata = MakeValidMetadata(); + metadata.schemas = {std::make_shared( + std::vector{SchemaField::MakeOptional(1, "first", int32()), + SchemaField::MakeOptional(1, "second", string())})}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateRejectsNestedDuplicateFieldIds) { + auto metadata = MakeValidMetadata(); + auto nested = std::make_shared( + std::vector{SchemaField::MakeOptional(1, "inner", string())}); + metadata.schemas = {std::make_shared( + std::vector{SchemaField::MakeOptional(1, "outer", int32()), + SchemaField::MakeOptional(2, "nested", nested)})}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataTest, ValidateDoesNotApplyTableSchemaRestrictions) { + auto metadata = MakeValidMetadata(); + metadata.schemas = {std::make_shared(std::vector{ + SchemaField::MakeRequired(1, "unknown", unknown()), + SchemaField::MakeOptional(2, "timestamp", timestamp_ns())})}; + EXPECT_THAT(metadata.Validate(), IsOk()); +} + TEST(ViewMetadataTest, ValidateRejectsMissingVersions) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions.clear(); @@ -206,10 +284,10 @@ TEST(ViewMetadataTest, ValidateAcceptsHistoryWithRollback) { EXPECT_EQ(metadata, before); } -TEST(ViewMetadataTest, ValidateRejectsEmptyDefaultNamespace) { +TEST(ViewMetadataTest, ValidateAcceptsEmptyDefaultNamespace) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->default_namespace = Namespace{}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsOk()); } TEST(ViewMetadataTest, ValidateRejectsDuplicateDialects) { @@ -226,6 +304,13 @@ TEST(ViewMetadataTest, ValidateRejectsDuplicateDialectsWithCaseFolding) { EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); } +TEST(ViewMetadataTest, ValidateRejectsUnicodeDuplicateDialects) { + auto metadata = MakeValidMetadata(); + metadata.versions[0]->representations = {SqlRepr("SELECT 1", "Éngine"), + SqlRepr("SELECT 2", "éngine")}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); +} + TEST(ViewMetadataTest, ValidateRejectsSqlRepresentationWithoutSql) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->representations = {SqlRepr("", "spark")}; @@ -244,6 +329,15 @@ TEST(ViewMetadataTest, ValidateRejectsUnknownRepresentationWithoutType) { EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); } +TEST(ViewMetadataTest, ValidateRejectsUnknownSqlRepresentation) { + for (const auto* type : {"sql", "SQL", "SqL", "ſql"}) { + SCOPED_TRACE(type); + auto metadata = MakeValidMetadata(); + metadata.versions[0]->representations = {UnknownViewRepresentation{.type = type}}; + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + } +} + TEST(ViewMetadataTest, AccessorsReturnNotFoundForMissingEntries) { ViewMetadata metadata = MakeValidMetadata(); EXPECT_THAT(metadata.VersionById(999), IsError(ErrorKind::kNotFound)); diff --git a/src/iceberg/type_fwd.h b/src/iceberg/type_fwd.h index a42479c9ef..354495e387 100644 --- a/src/iceberg/type_fwd.h +++ b/src/iceberg/type_fwd.h @@ -148,13 +148,6 @@ struct TableMetadata; class InheritableMetadata; class SnapshotSummaryBuilder; -/// \brief View metadata. -struct SqlViewRepresentation; -struct UnknownViewRepresentation; -struct ViewHistoryEntry; -struct ViewMetadata; -struct ViewVersion; - /// \brief Expression. class BoundPredicate; class BoundReference; diff --git a/src/iceberg/util/string_util.h b/src/iceberg/util/string_util.h index 09e7d96488..f1431e49d4 100644 --- a/src/iceberg/util/string_util.h +++ b/src/iceberg/util/string_util.h @@ -98,24 +98,6 @@ class ICEBERG_EXPORT StringUtils { return ToLower(str).starts_with(ToLower(prefix)); } - /// \brief Case-insensitive equality folding only ASCII letters (A-Z, a-z). - /// - /// Non-ASCII bytes compare unchanged, so folding never changes the length - /// of either operand. Use this for identifiers, such as SQL dialects, whose - /// comparison rules specify ASCII folding; use EqualsIgnoreCase for - /// Unicode-aware comparison. - static bool EqualsIgnoreCaseAscii(std::string_view a, std::string_view b) { - if (a.size() != b.size()) { - return false; - } - for (size_t i = 0; i < a.size(); ++i) { - if (ToLowerAscii(a[i]) != ToLowerAscii(b[i])) { - return false; - } - } - return true; - } - /// \brief Count the number of code points in a UTF-8 string. static size_t CodePointCount(std::string_view str) { size_t count = 0; diff --git a/src/iceberg/view/CMakeLists.txt b/src/iceberg/view/CMakeLists.txt new file mode 100644 index 0000000000..3adf7fd584 --- /dev/null +++ b/src/iceberg/view/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. + +iceberg_install_all_headers(iceberg/view) diff --git a/src/iceberg/view/type_fwd.h b/src/iceberg/view/type_fwd.h new file mode 100644 index 0000000000..cafd0d0415 --- /dev/null +++ b/src/iceberg/view/type_fwd.h @@ -0,0 +1,33 @@ +/* + * 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 + +/// \file iceberg/view/type_fwd.h +/// Forward declarations for view metadata. + +namespace iceberg { + +struct SqlViewRepresentation; +struct UnknownViewRepresentation; +struct ViewHistoryEntry; +struct ViewMetadata; +struct ViewVersion; + +} // namespace iceberg diff --git a/src/iceberg/view_metadata.cc b/src/iceberg/view/view_metadata.cc similarity index 80% rename from src/iceberg/view_metadata.cc rename to src/iceberg/view/view_metadata.cc index 88fb6ae2ba..72069d0b24 100644 --- a/src/iceberg/view_metadata.cc +++ b/src/iceberg/view/view_metadata.cc @@ -17,14 +17,19 @@ * under the License. */ -#include "iceberg/view_metadata.h" +#include "iceberg/view/view_metadata.h" #include +#include +#include #include #include "iceberg/schema.h" #include "iceberg/util/macros.h" #include "iceberg/util/string_util.h" +#include "iceberg/util/type_util.h" +#include "iceberg/util/uuid.h" +#include "iceberg/util/visit_type.h" namespace iceberg { @@ -33,8 +38,8 @@ Status ViewMetadata::Validate() const { return Invalid("Unsupported view format version: {}", static_cast(format_version)); } - if (view_uuid.empty()) { - return Invalid("View UUID must not be empty"); + if (auto uuid = Uuid::FromString(view_uuid); !uuid.has_value()) { + return Invalid("Invalid view UUID '{}': {}", view_uuid, uuid.error().message); } if (location.empty()) { return Invalid("View location must not be empty"); @@ -51,6 +56,12 @@ Status ViewMetadata::Validate() const { if (!schema_ids.insert(schema->schema_id()).second) { return Invalid("Duplicate view schema ID: {}", schema->schema_id()); } + std::unordered_map> fields; + IdToFieldVisitor visitor(fields); + if (auto status = VisitTypeInline(*schema, &visitor); !status.has_value()) { + return Invalid("Invalid view schema {}: {}", schema->schema_id(), + status.error().message); + } } if (versions.empty()) { @@ -80,12 +91,7 @@ Status ViewMetadata::Validate() const { return Invalid("View version {} references unlisted schema ID {}", version->version_id, version->schema_id); } - if (version->default_namespace.levels.empty()) { - return Invalid("View version {} must have a non-empty default namespace", - version->version_id); - } - - std::vector dialects; + std::unordered_set dialects; for (const auto& repr : version->representations) { if (const auto* sql = GetSql(repr)) { if (sql->sql.empty()) { @@ -96,20 +102,23 @@ Status ViewMetadata::Validate() const { return Invalid("View version {} has an SQL representation without a dialect", version->version_id); } - for (const auto& dialect : dialects) { - if (StringUtils::EqualsIgnoreCaseAscii(dialect, sql->dialect)) { - return Invalid( - "View version {} has multiple SQL representations for dialect '{}'", - version->version_id, sql->dialect); - } + if (!dialects.insert(StringUtils::ToLower(sql->dialect)).second) { + return Invalid( + "View version {} has multiple SQL representations for dialect '{}'", + version->version_id, sql->dialect); } - dialects.push_back(sql->dialect); } else { const auto& unknown = std::get(repr); if (unknown.type.empty()) { return Invalid("View version {} has an unknown representation without a type", version->version_id); } + // Java's equalsIgnoreCase also recognizes the long s (U+017F) as 's'. + if (StringUtils::EqualsIgnoreCase(unknown.type, kSqlRepresentationType) || + StringUtils::EqualsIgnoreCase(unknown.type, "ſql")) { + return Invalid("View version {} must use an SQL representation for type '{}'", + version->version_id, unknown.type); + } } } } diff --git a/src/iceberg/view_metadata.h b/src/iceberg/view/view_metadata.h similarity index 94% rename from src/iceberg/view_metadata.h rename to src/iceberg/view/view_metadata.h index 988157ed0e..566b451f4e 100644 --- a/src/iceberg/view_metadata.h +++ b/src/iceberg/view/view_metadata.h @@ -19,7 +19,7 @@ #pragma once -/// \file iceberg/view_metadata.h +/// \file iceberg/view/view_metadata.h /// View metadata for Iceberg views. #include @@ -32,7 +32,8 @@ #include "iceberg/result.h" #include "iceberg/type_fwd.h" #include "iceberg/util/timepoint.h" -#include "iceberg/view_version.h" +#include "iceberg/view/type_fwd.h" +#include "iceberg/view/view_version.h" namespace iceberg { @@ -40,9 +41,9 @@ namespace iceberg { /// current version of a view. struct ICEBERG_EXPORT ViewHistoryEntry { /// The timestamp in milliseconds of the change to the current version. - TimePointMs timestamp_ms; + TimePointMs timestamp_ms{}; /// ID of the view version that was made current. - int32_t version_id; + int32_t version_id = 0; /// \brief Compare two view history entries for equality. friend bool operator==(const ViewHistoryEntry& lhs, const ViewHistoryEntry& rhs) { @@ -61,7 +62,7 @@ struct ICEBERG_EXPORT ViewMetadata { static constexpr int8_t kSupportedViewFormatVersion = 1; /// An integer version number for the view format; must be 1. - int8_t format_version; + int8_t format_version = kDefaultViewFormatVersion; /// A UUID that identifies the view, generated when the view is created. std::string view_uuid; /// The view's base location; used to create metadata file locations. @@ -69,7 +70,7 @@ struct ICEBERG_EXPORT ViewMetadata { /// A list of known schemas. std::vector> schemas; /// ID of the current version of the view. - int32_t current_version_id; + int32_t current_version_id = -1; /// A list of known versions of the view. std::vector> versions; /// A list of timestamp and version ID pairs that encodes changes to the diff --git a/src/iceberg/view_version.cc b/src/iceberg/view/view_version.cc similarity index 97% rename from src/iceberg/view_version.cc rename to src/iceberg/view/view_version.cc index 691b304eea..17f64024af 100644 --- a/src/iceberg/view_version.cc +++ b/src/iceberg/view/view_version.cc @@ -17,7 +17,7 @@ * under the License. */ -#include "iceberg/view_version.h" +#include "iceberg/view/view_version.h" namespace iceberg { diff --git a/src/iceberg/view_version.h b/src/iceberg/view/view_version.h similarity index 90% rename from src/iceberg/view_version.h rename to src/iceberg/view/view_version.h index 3626c817df..22236c28d9 100644 --- a/src/iceberg/view_version.h +++ b/src/iceberg/view/view_version.h @@ -19,7 +19,7 @@ #pragma once -/// \file iceberg/view_version.h +/// \file iceberg/view/view_version.h /// A version of an Iceberg view. #include @@ -39,8 +39,8 @@ namespace iceberg { /// \brief The SQL representation of a view version's definition. /// /// Each SQL representation pairs a query with its engine dialect, such as -/// "spark". Dialect strings are preserved verbatim and compared with ASCII -/// case folding. +/// "spark". Dialect strings are preserved verbatim and compared after Unicode +/// lower-casing with StringUtils::ToLower. struct ICEBERG_EXPORT SqlViewRepresentation { /// The SQL SELECT statement that defines the view. std::string sql; @@ -79,12 +79,18 @@ inline constexpr std::string_view kSqlRepresentationType = "sql"; /// is modified or destroyed. ICEBERG_EXPORT const SqlViewRepresentation* GetSql(const ViewRepresentation& repr); +/// \brief Reject temporary variants whose borrowed SQL representation would dangle. +const SqlViewRepresentation* GetSql(const ViewRepresentation&& repr) = delete; + /// \brief Get the representation's type identifier. /// /// Returns kSqlRepresentationType for SQL representations and the opaque /// type identifier otherwise. ICEBERG_EXPORT std::string_view RepresentationType(const ViewRepresentation& repr); +/// \brief Reject temporary variants whose borrowed type identifier would dangle. +std::string_view RepresentationType(const ViewRepresentation&& repr) = delete; + /// \brief A view version, the state of a view's definition at a point in time. /// /// View versions are immutable: a definition change creates a new version. @@ -92,11 +98,11 @@ ICEBERG_EXPORT std::string_view RepresentationType(const ViewRepresentation& rep /// representation per dialect. struct ICEBERG_EXPORT ViewVersion { /// ID of the view version. - int32_t version_id; + int32_t version_id = 0; /// ID of the schema for this view version. - int32_t schema_id; + int32_t schema_id = 0; /// Timestamp in milliseconds from the unix epoch when the version was created. - TimePointMs timestamp_ms; + TimePointMs timestamp_ms{}; /// Summary metadata about the version, such as "engine-name" and /// "engine-version". std::unordered_map summary; From 7f7fd9e65e1dd629f33760de7049de7aaa4e02e2 Mon Sep 17 00:00:00 2001 From: Gang Wu Date: Mon, 30 Nov 2026 23:33:13 +0800 Subject: [PATCH 6/6] harden metadata validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reject missing field types, duplicate field paths, and required unknown fields. Accept ſql as an unknown representation and report invalid view metadata with kValidationFailed. --- src/iceberg/test/view_metadata_test.cc | 93 +++++++++++++++++--------- src/iceberg/util/type_util.cc | 3 + src/iceberg/view/view_metadata.cc | 88 +++++++++++++++--------- src/iceberg/view/view_metadata.h | 23 +++---- src/iceberg/view/view_version.h | 9 +-- 5 files changed, 135 insertions(+), 81 deletions(-) diff --git a/src/iceberg/test/view_metadata_test.cc b/src/iceberg/test/view_metadata_test.cc index 29b3496f37..2776a110b8 100644 --- a/src/iceberg/test/view_metadata_test.cc +++ b/src/iceberg/test/view_metadata_test.cc @@ -110,10 +110,13 @@ TEST(ViewMetadataTest, ValidateAcceptsValidMetadata) { } TEST(ViewMetadataTest, ValidateAcceptsUnknownRepresentation) { - ViewMetadata metadata = MakeValidMetadata(); - metadata.versions[0]->representations.emplace_back( - UnknownViewRepresentation{.type = "cypher"}); - EXPECT_THAT(metadata.Validate(), IsOk()); + for (const auto* type : {"cypher", "ſql"}) { + SCOPED_TRACE(type); + ViewMetadata metadata = MakeValidMetadata(); + metadata.versions[0]->representations.emplace_back( + UnknownViewRepresentation{.type = type}); + EXPECT_THAT(metadata.Validate(), IsOk()); + } } TEST(ViewMetadataTest, ValidateAcceptsMultipleVersionsAndDialects) { @@ -140,14 +143,14 @@ TEST(ViewMetadataTest, ValidateAcceptsMultipleVersionsAndDialects) { TEST(ViewMetadataTest, ValidateRejectsUnsupportedFormatVersion) { ViewMetadata metadata = MakeValidMetadata(); metadata.format_version = 2; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, DefaultConstructionInitializesScalars) { ViewMetadata metadata; EXPECT_EQ(metadata.format_version, ViewMetadata::kDefaultViewFormatVersion); EXPECT_EQ(metadata.current_version_id, -1); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); ViewVersion version; EXPECT_EQ(version.version_id, 0); EXPECT_EQ(version.schema_id, 0); @@ -160,7 +163,7 @@ TEST(ViewMetadataTest, DefaultConstructionInitializesScalars) { TEST(ViewMetadataTest, ValidateRejectsEmptyUuid) { ViewMetadata metadata = MakeValidMetadata(); metadata.view_uuid.clear(); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsMalformedUuid) { @@ -169,7 +172,7 @@ TEST(ViewMetadataTest, ValidateRejectsMalformedUuid) { SCOPED_TRACE(uuid); auto metadata = MakeValidMetadata(); metadata.view_uuid = uuid; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } } @@ -182,25 +185,25 @@ TEST(ViewMetadataTest, ValidateAcceptsUppercaseUuid) { TEST(ViewMetadataTest, ValidateRejectsEmptyLocation) { ViewMetadata metadata = MakeValidMetadata(); metadata.location.clear(); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsMissingSchemas) { ViewMetadata metadata = MakeValidMetadata(); metadata.schemas.clear(); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsNullSchema) { ViewMetadata metadata = MakeValidMetadata(); metadata.schemas.push_back(nullptr); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsDuplicateSchemaIds) { ViewMetadata metadata = MakeValidMetadata(); metadata.schemas.push_back(MakeSchema(0)); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsDuplicateFieldIds) { @@ -208,7 +211,7 @@ TEST(ViewMetadataTest, ValidateRejectsDuplicateFieldIds) { metadata.schemas = {std::make_shared( std::vector{SchemaField::MakeOptional(1, "first", int32()), SchemaField::MakeOptional(1, "second", string())})}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsNestedDuplicateFieldIds) { @@ -218,13 +221,43 @@ TEST(ViewMetadataTest, ValidateRejectsNestedDuplicateFieldIds) { metadata.schemas = {std::make_shared( std::vector{SchemaField::MakeOptional(1, "outer", int32()), SchemaField::MakeOptional(2, "nested", nested)})}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); +} + +TEST(ViewMetadataTest, ValidateRejectsMissingNestedFieldType) { + auto metadata = MakeValidMetadata(); + auto nested = std::make_shared( + std::vector{SchemaField::MakeOptional(2, "inner", nullptr)}); + metadata.schemas = {std::make_shared( + std::vector{SchemaField::MakeOptional(1, "nested", nested)})}; + auto result = metadata.Validate(); + EXPECT_THAT(result, IsError(ErrorKind::kValidationFailed)); + EXPECT_THAT(result, HasErrorMessage("Field 'inner' has no type")); +} + +TEST(ViewMetadataTest, ValidateRejectsDuplicateFieldNames) { + auto metadata = MakeValidMetadata(); + metadata.schemas = {std::make_shared( + std::vector{SchemaField::MakeOptional(1, "column", int32()), + SchemaField::MakeOptional(2, "column", string())})}; + auto result = metadata.Validate(); + EXPECT_THAT(result, IsError(ErrorKind::kValidationFailed)); + EXPECT_THAT(result, HasErrorMessage("Duplicate path found: column")); +} + +TEST(ViewMetadataTest, ValidateRejectsRequiredUnknownField) { + auto metadata = MakeValidMetadata(); + metadata.schemas = {std::make_shared( + std::vector{SchemaField::MakeRequired(1, "unknown", unknown())})}; + auto result = metadata.Validate(); + EXPECT_THAT(result, IsError(ErrorKind::kValidationFailed)); + EXPECT_THAT(result, HasErrorMessage("Unknown type field 'unknown' must be optional")); } -TEST(ViewMetadataTest, ValidateDoesNotApplyTableSchemaRestrictions) { +TEST(ViewMetadataTest, ValidateAcceptsTypesFromLaterTableVersions) { auto metadata = MakeValidMetadata(); metadata.schemas = {std::make_shared(std::vector{ - SchemaField::MakeRequired(1, "unknown", unknown()), + SchemaField::MakeOptional(1, "unknown", unknown()), SchemaField::MakeOptional(2, "timestamp", timestamp_ns())})}; EXPECT_THAT(metadata.Validate(), IsOk()); } @@ -232,26 +265,26 @@ TEST(ViewMetadataTest, ValidateDoesNotApplyTableSchemaRestrictions) { TEST(ViewMetadataTest, ValidateRejectsMissingVersions) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions.clear(); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsNullVersion) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions.push_back(nullptr); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsDuplicateVersionIds) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions.push_back(std::make_shared( MakeVersion(0, 0, {SqlRepr("SELECT customer_id FROM customers", "trino")}))); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsUnlistedCurrentVersion) { ViewMetadata metadata = MakeValidMetadata(); metadata.current_version_id = 7; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); auto current = metadata.CurrentVersion(); EXPECT_THAT(current, IsError(ErrorKind::kNotFound)); @@ -260,14 +293,14 @@ TEST(ViewMetadataTest, ValidateRejectsUnlistedCurrentVersion) { TEST(ViewMetadataTest, ValidateRejectsUnlistedSchemaReference) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->schema_id = 5; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsUnlistedHistoryVersion) { ViewMetadata metadata = MakeValidMetadata(); metadata.version_log[0].version_id = 999; auto result = metadata.Validate(); - EXPECT_THAT(result, IsError(ErrorKind::kInvalid)); + EXPECT_THAT(result, IsError(ErrorKind::kValidationFailed)); EXPECT_THAT(result, HasErrorMessage("View history references unlisted version ID 999")); } @@ -294,47 +327,47 @@ TEST(ViewMetadataTest, ValidateRejectsDuplicateDialects) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->representations.push_back( SqlRepr("SELECT customer_id FROM customers", "spark")); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsDuplicateDialectsWithCaseFolding) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->representations.push_back( SqlRepr("SELECT customer_id FROM customers", "SPARK")); - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsUnicodeDuplicateDialects) { auto metadata = MakeValidMetadata(); metadata.versions[0]->representations = {SqlRepr("SELECT 1", "Éngine"), SqlRepr("SELECT 2", "éngine")}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsSqlRepresentationWithoutSql) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->representations = {SqlRepr("", "spark")}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsSqlRepresentationWithoutDialect) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->representations = {SqlRepr("SELECT 1", "")}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsUnknownRepresentationWithoutType) { ViewMetadata metadata = MakeValidMetadata(); metadata.versions[0]->representations = {UnknownViewRepresentation{.type = ""}}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataTest, ValidateRejectsUnknownSqlRepresentation) { - for (const auto* type : {"sql", "SQL", "SqL", "ſql"}) { + for (const auto* type : {"sql", "SQL", "SqL"}) { SCOPED_TRACE(type); auto metadata = MakeValidMetadata(); metadata.versions[0]->representations = {UnknownViewRepresentation{.type = type}}; - EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata.Validate(), IsError(ErrorKind::kValidationFailed)); } } diff --git a/src/iceberg/util/type_util.cc b/src/iceberg/util/type_util.cc index 5f96a28fe7..5cdabb58f0 100644 --- a/src/iceberg/util/type_util.cc +++ b/src/iceberg/util/type_util.cc @@ -48,6 +48,9 @@ Status IdToFieldVisitor::Visit(const NestedType& type) { if (!it.second) { return InvalidSchema("Duplicate field id found: {}", field.field_id()); } + if (field.type() == nullptr) { + return InvalidSchema("Field '{}' has no type", field.name()); + } ICEBERG_RETURN_UNEXPECTED(VisitTypeInline(*field.type(), this)); } return {}; diff --git a/src/iceberg/view/view_metadata.cc b/src/iceberg/view/view_metadata.cc index 72069d0b24..9953828b4d 100644 --- a/src/iceberg/view/view_metadata.cc +++ b/src/iceberg/view/view_metadata.cc @@ -25,6 +25,7 @@ #include #include "iceberg/schema.h" +#include "iceberg/type.h" #include "iceberg/util/macros.h" #include "iceberg/util/string_util.h" #include "iceberg/util/type_util.h" @@ -33,91 +34,114 @@ namespace iceberg { +namespace { + +Status ValidateViewSchema(const Schema& schema) { + std::unordered_map> fields; + IdToFieldVisitor id_visitor(fields); + ICEBERG_RETURN_UNEXPECTED(VisitTypeInline(schema, &id_visitor)); + + for (const auto& [id, field_ref] : fields) { + const auto& field = field_ref.get(); + if (!field.optional() && field.type()->type_id() == TypeId::kUnknown) { + return InvalidSchema("Unknown type field '{}' must be optional", field.name()); + } + } + + std::unordered_map> name_to_id; + NameToIdVisitor name_visitor(name_to_id, /*id_to_name=*/nullptr); + return VisitTypeInline(schema, &name_visitor, /*path=*/"", /*short_path=*/""); +} + +} // namespace + +/// TODO(view): Current validation is much stricter than Java implementation. Status ViewMetadata::Validate() const { if (format_version != kSupportedViewFormatVersion) { - return Invalid("Unsupported view format version: {}", - static_cast(format_version)); + return ValidationFailed("Unsupported view format version: {}", + static_cast(format_version)); } if (auto uuid = Uuid::FromString(view_uuid); !uuid.has_value()) { - return Invalid("Invalid view UUID '{}': {}", view_uuid, uuid.error().message); + return ValidationFailed("Invalid view UUID '{}': {}", view_uuid, + uuid.error().message); } if (location.empty()) { - return Invalid("View location must not be empty"); + return ValidationFailed("View location must not be empty"); } if (schemas.empty()) { - return Invalid("View metadata must list at least one schema"); + return ValidationFailed("View metadata must list at least one schema"); } std::unordered_set schema_ids; for (const auto& schema : schemas) { if (schema == nullptr) { - return Invalid("View schemas must not be null"); + return ValidationFailed("View schemas must not be null"); } if (!schema_ids.insert(schema->schema_id()).second) { - return Invalid("Duplicate view schema ID: {}", schema->schema_id()); + return ValidationFailed("Duplicate view schema ID: {}", schema->schema_id()); } - std::unordered_map> fields; - IdToFieldVisitor visitor(fields); - if (auto status = VisitTypeInline(*schema, &visitor); !status.has_value()) { - return Invalid("Invalid view schema {}: {}", schema->schema_id(), - status.error().message); + if (auto status = ValidateViewSchema(*schema); !status.has_value()) { + return ValidationFailed("Invalid view schema {}: {}", schema->schema_id(), + status.error().message); } } if (versions.empty()) { - return Invalid("View metadata must list at least one version"); + return ValidationFailed("View metadata must list at least one version"); } std::unordered_set version_ids; for (const auto& version : versions) { if (version == nullptr) { - return Invalid("View versions must not be null"); + return ValidationFailed("View versions must not be null"); } if (!version_ids.insert(version->version_id).second) { - return Invalid("Duplicate view version ID: {}", version->version_id); + return ValidationFailed("Duplicate view version ID: {}", version->version_id); } } if (!version_ids.contains(current_version_id)) { - return Invalid("Current version ID {} is not a listed view version", - current_version_id); + return ValidationFailed("Current version ID {} is not a listed view version", + current_version_id); } for (const auto& entry : version_log) { if (!version_ids.contains(entry.version_id)) { - return Invalid("View history references unlisted version ID {}", entry.version_id); + return ValidationFailed("View history references unlisted version ID {}", + entry.version_id); } } for (const auto& version : versions) { if (!schema_ids.contains(version->schema_id)) { - return Invalid("View version {} references unlisted schema ID {}", - version->version_id, version->schema_id); + return ValidationFailed("View version {} references unlisted schema ID {}", + version->version_id, version->schema_id); } std::unordered_set dialects; for (const auto& repr : version->representations) { if (const auto* sql = GetSql(repr)) { if (sql->sql.empty()) { - return Invalid("View version {} has an SQL representation without SQL", - version->version_id); + return ValidationFailed("View version {} has an SQL representation without SQL", + version->version_id); } if (sql->dialect.empty()) { - return Invalid("View version {} has an SQL representation without a dialect", - version->version_id); + return ValidationFailed( + "View version {} has an SQL representation without a dialect", + version->version_id); } if (!dialects.insert(StringUtils::ToLower(sql->dialect)).second) { - return Invalid( + return ValidationFailed( "View version {} has multiple SQL representations for dialect '{}'", version->version_id, sql->dialect); } } else { const auto& unknown = std::get(repr); if (unknown.type.empty()) { - return Invalid("View version {} has an unknown representation without a type", - version->version_id); + return ValidationFailed( + "View version {} has an unknown representation without a type", + version->version_id); } - // Java's equalsIgnoreCase also recognizes the long s (U+017F) as 's'. - if (StringUtils::EqualsIgnoreCase(unknown.type, kSqlRepresentationType) || - StringUtils::EqualsIgnoreCase(unknown.type, "ſql")) { - return Invalid("View version {} must use an SQL representation for type '{}'", - version->version_id, unknown.type); + if (StringUtils::EqualsIgnoreCase(unknown.type, kSqlRepresentationType)) { + return ValidationFailed( + "View version {} must use an SQL representation for type '{}'", + version->version_id, unknown.type); } } } diff --git a/src/iceberg/view/view_metadata.h b/src/iceberg/view/view_metadata.h index 566b451f4e..c8f1385a1c 100644 --- a/src/iceberg/view/view_metadata.h +++ b/src/iceberg/view/view_metadata.h @@ -53,10 +53,8 @@ struct ICEBERG_EXPORT ViewHistoryEntry { /// \brief Represents the metadata for an Iceberg view. /// -/// View metadata follows view format version 1. Table-format schema -/// restrictions are deliberately not applied to the view's schemas: view -/// schemas are projections of the referenced tables' columns and may use -/// types or nullability that table data would reject. +/// View metadata follows view format version 1. View schemas may use types +/// introduced in later table format versions. struct ICEBERG_EXPORT ViewMetadata { static constexpr int8_t kDefaultViewFormatVersion = 1; static constexpr int8_t kSupportedViewFormatVersion = 1; @@ -68,7 +66,7 @@ struct ICEBERG_EXPORT ViewMetadata { /// The view's base location; used to create metadata file locations. std::string location; /// A list of known schemas. - std::vector> schemas; + std::vector> schemas; /// ID of the current version of the view. int32_t current_version_id = -1; /// A list of known versions of the view. @@ -77,16 +75,17 @@ struct ICEBERG_EXPORT ViewMetadata { /// current version. std::vector version_log; /// A string to string map of view properties. + /// TODO(view): Add a ViewProperties class to encapsulate view-specific + /// properties just like TableProperties. std::unordered_map properties; /// \brief Validate view format v1 invariants. /// - /// Checks referential integrity, required fields, and per-dialect - /// uniqueness of SQL representations, without applying table-format schema - /// restrictions. Never modifies the metadata. + /// Checks referential integrity, schema structure, required fields, and + /// uniqueness of SQL dialects. Never modifies the metadata. /// - /// \return Status indicating success, or ErrorKind::kInvalid with the first - /// violated invariant. + /// \return Status indicating success, or ErrorKind::kValidationFailed with + /// the first violated invariant. Status Validate() const; /// \brief Get the current view version. @@ -104,13 +103,13 @@ struct ICEBERG_EXPORT ViewMetadata { /// \return the current schema or ErrorKind::kNotFound if the current /// version or its schema is not listed. /// \note The returned schema is guaranteed to be not null. - Result> CurrentSchema() const; + Result> CurrentSchema() const; /// \brief Get a view schema by ID. /// \param schema_id ID of the schema to look up /// \return the schema or ErrorKind::kNotFound if it is not listed. /// \note The returned schema is guaranteed to be not null. - Result> SchemaById(int32_t schema_id) const; + Result> SchemaById(int32_t schema_id) const; /// \brief Compare two view metadata for equality. friend bool operator==(const ViewMetadata& lhs, const ViewMetadata& rhs) { diff --git a/src/iceberg/view/view_version.h b/src/iceberg/view/view_version.h index 22236c28d9..476194b024 100644 --- a/src/iceberg/view/view_version.h +++ b/src/iceberg/view/view_version.h @@ -39,8 +39,7 @@ namespace iceberg { /// \brief The SQL representation of a view version's definition. /// /// Each SQL representation pairs a query with its engine dialect, such as -/// "spark". Dialect strings are preserved verbatim and compared after Unicode -/// lower-casing with StringUtils::ToLower. +/// "spark". View validation uses Unicode lowercase dialects to detect duplicates. struct ICEBERG_EXPORT SqlViewRepresentation { /// The SQL SELECT statement that defines the view. std::string sql; @@ -52,11 +51,7 @@ struct ICEBERG_EXPORT SqlViewRepresentation { const SqlViewRepresentation& rhs) = default; }; -/// \brief An opaque representation type this library does not interpret. -/// -/// Unknown representations are preserved so that metadata round trips and -/// property edits do not lose them. Definition changes that involve them are -/// rejected instead of being partially rewritten. +/// \brief Stores the type identifier of an unsupported representation. struct ICEBERG_EXPORT UnknownViewRepresentation { /// The representation type identifier from the metadata, such as "cypher". std::string type;