From 8ca7331f6e213ede5e0581201589a0b89a250705 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 30 Nov 2026 05:40:23 +0000 Subject: [PATCH 1/3] feat(view): add metadata JSON serialization --- src/iceberg/CMakeLists.txt | 1 + src/iceberg/json_serde.cc | 4 + src/iceberg/test/CMakeLists.txt | 3 +- .../test/view_metadata_json_fixtures.h | 856 ++++++++++++++++++ src/iceberg/test/view_metadata_json_test.cc | 460 ++++++++++ src/iceberg/view/json_serde.cc | 283 ++++++ src/iceberg/view/json_serde_internal.h | 62 ++ src/iceberg/view/view_metadata.cc | 3 + src/iceberg/view/view_version.h | 4 + 9 files changed, 1675 insertions(+), 1 deletion(-) create mode 100644 src/iceberg/test/view_metadata_json_fixtures.h create mode 100644 src/iceberg/test/view_metadata_json_test.cc create mode 100644 src/iceberg/view/json_serde.cc create mode 100644 src/iceberg/view/json_serde_internal.h diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 71c7a4018..41be635d5 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -178,6 +178,7 @@ set(ICEBERG_SOURCES util/type_util.cc util/url_encoder.cc util/uuid.cc + view/json_serde.cc view/view_metadata.cc view/view_version.cc) diff --git a/src/iceberg/json_serde.cc b/src/iceberg/json_serde.cc index b47a35fd8..4de4ea552 100644 --- a/src/iceberg/json_serde.cc +++ b/src/iceberg/json_serde.cc @@ -757,6 +757,10 @@ namespace { Result> StructTypeFromJson(const nlohmann::json& json) { ICEBERG_ASSIGN_OR_RAISE(auto json_fields, GetJsonValue(json, kFields)); + if (!json_fields.is_array()) { + return JsonParseError("'fields' must be an array, but is {}", + json_fields.type_name()); + } std::vector fields; for (const auto& field_json : json_fields) { diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index c69ad54c7..98b60f61e 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -161,7 +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(view_metadata_test SOURCES view_metadata_test.cc + view_metadata_json_test.cc) add_iceberg_test(util_test USE_DATA diff --git a/src/iceberg/test/view_metadata_json_fixtures.h b/src/iceberg/test/view_metadata_json_fixtures.h new file mode 100644 index 000000000..2f77f1723 --- /dev/null +++ b/src/iceberg/test/view_metadata_json_fixtures.h @@ -0,0 +1,856 @@ +/* + * 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 + +namespace iceberg::test { + +// Pinned fixtures: +// https://github.com/apache/iceberg/tree/524fe9ef1b4aa72be19623f667738b21a02b23b2/core/src/test/resources/org/apache/iceberg/view +inline constexpr std::string_view kJavaValidViewMetadata = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/test/location", + "properties": {"some-key": "some-value", "comment": "some-comment"}, + "current-schema-id": 0, + "schemas": [ + { + "type": "struct", + "schema-id": 0, + "fields": [ + { + "id": 1, + "name": "x", + "required": true, + "type": "long" + }, + { + "id": 2, + "name": "y", + "required": true, + "type": "long", + "doc": "comment" + }, + { + "id": 3, + "name": "z", + "required": true, + "type": "long" + } + ] + } + ], + "current-version-id": 2, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 4353, + "summary": {"user": "some-user"}, + "schema-id": 0, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 'foo' foo", + "dialect": "spark-sql" + } + ] + }, + { + "version-id": 2, + "timestamp-ms": 5555, + "summary": {"user": "some-user"}, + "schema-id": 0, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 1 id, 'abc' data", + "dialect": "spark-sql" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 4353, + "version-id": 1 + }, + { + "timestamp-ms": 5555, + "version-id": 2 + } + ] +} +)json"; + +inline constexpr std::string_view kJavaViewMetadataInvalidCurrentSchema = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/test/location", + "properties": {"some-key": "some-value"}, + "schemas": [ + { + "type": "struct", + "schema-id": 1, + "fields": [ + { + "id": 1, + "name": "x", + "required": true, + "type": "long" + }, + { + "id": 2, + "name": "y", + "required": true, + "type": "long", + "doc": "comment" + }, + { + "id": 3, + "name": "z", + "required": true, + "type": "long" + } + ] + } + ], + "current-version-id": 2, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 4353, + "summary": {"user": "some-user"}, + "schema-id": 1, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 'foo' foo", + "dialect": "spark-sql" + } + ] + }, + { + "version-id": 2, + "timestamp-ms": 5555, + "summary": {"user": "some-user"}, + "schema-id": 1234, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 1 id, 'abc' data", + "dialect": "spark-sql" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 4353, + "version-id": 1 + }, + { + "timestamp-ms": 5555, + "version-id": 2 + } + ] +} +)json"; + +inline constexpr std::string_view kJavaViewMetadataInvalidCurrentVersion = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/test/location", + "properties": {"some-key": "some-value"}, + "current-schema-id": 1, + "current-version-id": 1234, + "schemas": [ + { + "type": "struct", + "schema-id": 1, + "fields": [ + { + "id": 1, + "name": "x", + "required": true, + "type": "long" + }, + { + "id": 2, + "name": "y", + "required": true, + "type": "long", + "doc": "comment" + }, + { + "id": 3, + "name": "z", + "required": true, + "type": "long" + } + ] + } + ], + "versions": [ + { + "version-id": 1, + "timestamp-ms": 4353, + "summary": {"user": "some-user"}, + "schema-id": 1, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 'foo' foo", + "dialect": "spark-sql" + } + ] + }, + { + "version-id": 2, + "timestamp-ms": 5555, + "summary": {"user": "some-user"}, + "schema-id": 1, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 1 id, 'abc' data", + "dialect": "spark-sql" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 4353, + "version-id": 1 + }, + { + "timestamp-ms": 5555, + "version-id": 2 + } + ] +} +)json"; + +inline constexpr std::string_view kJavaViewMetadataMissingCurrentVersion = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/test/location", + "properties": {"some-key": "some-value"}, + "current-schema-id": 1, + "schemas": [ + { + "type": "struct", + "schema-id": 1, + "fields": [ + { + "id": 1, + "name": "x", + "required": true, + "type": "long" + }, + { + "id": 2, + "name": "y", + "required": true, + "type": "long", + "doc": "comment" + }, + { + "id": 3, + "name": "z", + "required": true, + "type": "long" + } + ] + } + ], + "versions": [ + { + "version-id": 1, + "timestamp-ms": 4353, + "summary": {"user": "some-user"}, + "schema-id": 1, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 'foo' foo", + "dialect": "spark-sql" + } + ] + }, + { + "version-id": 2, + "timestamp-ms": 5555, + "summary": {"user": "some-user"}, + "schema-id": 1, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 1 id, 'abc' data", + "dialect": "spark-sql" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 4353, + "version-id": 1 + }, + { + "timestamp-ms": 5555, + "version-id": 2 + } + ] +} +)json"; + +inline constexpr std::string_view kJavaViewMetadataMissingLocation = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "properties": {"some-key": "some-value"}, + "current-schema-id": 1, + "current-version-id": 2, + "schemas": [ + { + "type": "struct", + "schema-id": 1, + "fields": [ + { + "id": 1, + "name": "x", + "required": true, + "type": "long" + }, + { + "id": 2, + "name": "y", + "required": true, + "type": "long", + "doc": "comment" + }, + { + "id": 3, + "name": "z", + "required": true, + "type": "long" + } + ] + } + ], + "versions": [ + { + "version-id": 1, + "timestamp-ms": 4353, + "summary": {"user": "some-user"}, + "schema-id": 1, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 'foo' foo", + "dialect": "spark-sql" + } + ] + }, + { + "version-id": 2, + "timestamp-ms": 5555, + "summary": {"user": "some-user"}, + "schema-id": 1, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 1 id, 'abc' data", + "dialect": "spark-sql" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 4353, + "version-id": 1 + }, + { + "timestamp-ms": 5555, + "version-id": 2 + } + ] +} +)json"; + +inline constexpr std::string_view kJavaViewMetadataMultipleSQLsForDialect = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/test/location", + "properties": {"some-key": "some-value"}, + "current-schema-id": 0, + "schemas": [ + { + "type": "struct", + "schema-id": 0, + "fields": [ + { + "id": 1, + "name": "x", + "required": true, + "type": "long" + }, + { + "id": 2, + "name": "y", + "required": true, + "type": "long", + "doc": "comment" + }, + { + "id": 3, + "name": "z", + "required": true, + "type": "long" + } + ] + } + ], + "current-version-id": 1, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 4353, + "summary": {"user": "some-user"}, + "schema-id": 0, + "default-catalog": "some-catalog", + "default-namespace": [], + "representations": [ + { + "type": "sql", + "sql": "select 'foo' foo", + "dialect": "spark-sql" + }, + { + "type": "sql", + "sql": "select * from foo", + "dialect": "spark-sql" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 4353, + "version-id": 1 + } + ] +} +)json"; + +// Pinned fixtures: +// https://github.com/apache/iceberg-rust/tree/697abcee75b503fc106f445dae8bcfc401524dcc/crates/iceberg/testdata/view_metadata +inline constexpr std::string_view kRustViewMetadataUnsupportedVersion = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 2, + "location": "s3://bucket/warehouse/default.db/event_agg", + "current-version-id": 1, + "properties": { + "comment": "Daily event counts" + }, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 1573518431292, + "schema-id": 1, + "default-catalog": "prod", + "default-namespace": [ + "default" + ], + "summary": { + "engine-name": "Spark", + "engineVersion": "3.3.2" + }, + "representations": [ + { + "type": "sql", + "sql": "SELECT\n COUNT(1), CAST(event_ts AS DATE)\nFROM events\nGROUP BY 2", + "dialect": "spark" + } + ] + } + ], + "schemas": [ + { + "schema-id": 1, + "type": "struct", + "fields": [ + { + "id": 1, + "name": "event_count", + "required": false, + "type": "int", + "doc": "Count of events" + }, + { + "id": 2, + "name": "event_date", + "required": false, + "type": "date" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 1573518431292, + "version-id": 1 + } + ] +} +)json"; + +inline constexpr std::string_view kRustViewMetadataV1CurrentVersionNotFound = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/warehouse/default.db/event_agg", + "current-version-id": 2, + "properties": { + "comment": "Daily event counts" + }, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 1573518431292, + "schema-id": 1, + "default-catalog": "prod", + "default-namespace": [ + "default" + ], + "summary": { + "engine-name": "Spark", + "engineVersion": "3.3.2" + }, + "representations": [ + { + "type": "sql", + "sql": "SELECT\n COUNT(1), CAST(event_ts AS DATE)\nFROM events\nGROUP BY 2", + "dialect": "spark" + } + ] + } + ], + "schemas": [ + { + "schema-id": 1, + "type": "struct", + "fields": [ + { + "id": 1, + "name": "event_count", + "required": false, + "type": "int", + "doc": "Count of events" + }, + { + "id": 2, + "name": "event_date", + "required": false, + "type": "date" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 1573518431292, + "version-id": 1 + } + ] +} +)json"; + +inline constexpr std::string_view kRustViewMetadataV1MissingCurrentVersion = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/warehouse/default.db/event_agg", + "properties": { + "comment": "Daily event counts" + }, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 1573518431292, + "schema-id": 1, + "default-catalog": "prod", + "default-namespace": [ + "default" + ], + "summary": { + "engine-name": "Spark", + "engineVersion": "3.3.2" + }, + "representations": [ + { + "type": "sql", + "sql": "SELECT\n COUNT(1), CAST(event_ts AS DATE)\nFROM events\nGROUP BY 2", + "dialect": "spark" + } + ] + } + ], + "schemas": [ + { + "schema-id": 1, + "type": "struct", + "fields": [ + { + "id": 1, + "name": "event_count", + "required": false, + "type": "int", + "doc": "Count of events" + }, + { + "id": 2, + "name": "event_date", + "required": false, + "type": "date" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 1573518431292, + "version-id": 1 + } + ] +} +)json"; + +inline constexpr std::string_view kRustViewMetadataV1MissingSchema = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/warehouse/default.db/event_agg", + "properties": { + "comment": "Daily event counts" + }, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 1573518431292, + "default-catalog": "prod", + "default-namespace": [ + "default" + ], + "summary": { + "engine-name": "Spark", + "engineVersion": "3.3.2" + }, + "representations": [ + { + "type": "sql", + "sql": "SELECT\n COUNT(1), CAST(event_ts AS DATE)\nFROM events\nGROUP BY 2", + "dialect": "spark" + } + ] + } + ], + "schemas": [ + { + "schema-id": 1, + "type": "struct", + "fields": [ + { + "id": 1, + "name": "event_count", + "required": false, + "type": "int", + "doc": "Count of events" + }, + { + "id": 2, + "name": "event_date", + "required": false, + "type": "date" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 1573518431292, + "version-id": 1 + } + ] +} +)json"; + +inline constexpr std::string_view kRustViewMetadataV1SchemaNotFound = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/warehouse/default.db/event_agg", + "current-version-id": 1, + "properties": { + "comment": "Daily event counts" + }, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 1573518431292, + "schema-id": 2, + "default-catalog": "prod", + "default-namespace": [ + "default" + ], + "summary": { + "engine-name": "Spark", + "engineVersion": "3.3.2" + }, + "representations": [ + { + "type": "sql", + "sql": "SELECT\n COUNT(1), CAST(event_ts AS DATE)\nFROM events\nGROUP BY 2", + "dialect": "spark" + } + ] + } + ], + "schemas": [ + { + "schema-id": 1, + "type": "struct", + "fields": [ + { + "id": 1, + "name": "event_count", + "required": false, + "type": "int", + "doc": "Count of events" + }, + { + "id": 2, + "name": "event_date", + "required": false, + "type": "date" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 1573518431292, + "version-id": 1 + } + ] +} +)json"; + +inline constexpr std::string_view kRustViewMetadataV1Valid = R"json( +{ + "view-uuid": "fa6506c3-7681-40c8-86dc-e36561f83385", + "format-version": 1, + "location": "s3://bucket/warehouse/default.db/event_agg", + "current-version-id": 1, + "properties": { + "comment": "Daily event counts" + }, + "versions": [ + { + "version-id": 1, + "timestamp-ms": 1573518431292, + "schema-id": 1, + "default-catalog": "prod", + "default-namespace": [ + "default" + ], + "summary": { + "engine-name": "Spark", + "engineVersion": "3.3.2" + }, + "representations": [ + { + "type": "sql", + "sql": "SELECT\n COUNT(1), CAST(event_ts AS DATE)\nFROM events\nGROUP BY 2", + "dialect": "spark" + } + ] + } + ], + "schemas": [ + { + "schema-id": 1, + "type": "struct", + "fields": [ + { + "id": 1, + "name": "event_count", + "required": false, + "type": "int", + "doc": "Count of events" + }, + { + "id": 2, + "name": "event_date", + "required": false, + "type": "date" + } + ] + } + ], + "version-log": [ + { + "timestamp-ms": 1573518431292, + "version-id": 1 + } + ] +} +)json"; + +} // namespace iceberg::test diff --git a/src/iceberg/test/view_metadata_json_test.cc b/src/iceberg/test/view_metadata_json_test.cc new file mode 100644 index 000000000..2ebcef217 --- /dev/null +++ b/src/iceberg/test/view_metadata_json_test.cc @@ -0,0 +1,460 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "iceberg/schema.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/view_metadata_json_fixtures.h" +#include "iceberg/util/json_util_internal.h" +#include "iceberg/util/timepoint.h" +#include "iceberg/view/json_serde_internal.h" + +namespace iceberg { +namespace { + +using nlohmann::json; + +json ValidMetadataJson() { return json::parse(test::kRustViewMetadataV1Valid); } + +std::string MetadataWithUnknownPayload(std::string_view payload) { + auto value = ValidMetadataJson(); + value["versions"][0]["representations"].push_back( + {{"type", "future"}, {"payload", "raw-payload-placeholder"}}); + auto source = value.dump(); + constexpr std::string_view kPlaceholder = "\"raw-payload-placeholder\""; + source.replace(source.find(kPlaceholder), kPlaceholder.size(), payload); + return source; +} + +struct ReferenceFixture { + std::string name; + std::string_view source; + std::optional error; +}; + +class ViewMetadataReferenceJsonTest : public ::testing::TestWithParam { +}; + +TEST_P(ViewMetadataReferenceJsonTest, ParseAndRoundTrip) { + const auto& fixture = GetParam(); + auto parsed = ViewMetadataFromJsonString(fixture.source); + if (fixture.error.has_value()) { + EXPECT_THAT(parsed, IsError(*fixture.error)); + return; + } + ASSERT_THAT(parsed, IsOk()); + EXPECT_THAT((*parsed)->Validate(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(**parsed)); + auto expected = json::parse(fixture.source); + // Java's fixture carries a legacy field outside the view format. The current + // schema is derived from the current version instead of serializing that field. + expected.erase("current-schema-id"); + EXPECT_EQ(serialized, expected); + ICEBERG_UNWRAP_OR_FAIL(auto first, ToJsonString(**parsed)); + ICEBERG_UNWRAP_OR_FAIL(auto restored, ViewMetadataFromJsonString(first)); + EXPECT_EQ(**parsed, *restored); + ICEBERG_UNWRAP_OR_FAIL(auto second, ToJsonString(*restored)); + EXPECT_EQ(first, second); +} + +INSTANTIATE_TEST_SUITE_P( + JavaAndRust, ViewMetadataReferenceJsonTest, + ::testing::Values( + ReferenceFixture{"JavaValid", test::kJavaValidViewMetadata, std::nullopt}, + ReferenceFixture{"JavaInvalidSchema", test::kJavaViewMetadataInvalidCurrentSchema, + ErrorKind::kInvalid}, + ReferenceFixture{"JavaInvalidVersion", + test::kJavaViewMetadataInvalidCurrentVersion, + ErrorKind::kInvalid}, + ReferenceFixture{"JavaMissingVersion", + test::kJavaViewMetadataMissingCurrentVersion, + ErrorKind::kJsonParseError}, + ReferenceFixture{"JavaMissingLocation", test::kJavaViewMetadataMissingLocation, + ErrorKind::kJsonParseError}, + ReferenceFixture{"JavaDuplicateDialects", + test::kJavaViewMetadataMultipleSQLsForDialect, + ErrorKind::kInvalid}, + ReferenceFixture{"RustValid", test::kRustViewMetadataV1Valid, std::nullopt}, + ReferenceFixture{"RustUnsupportedVersion", + test::kRustViewMetadataUnsupportedVersion, + ErrorKind::kJsonParseError}, + ReferenceFixture{"RustVersionNotFound", + test::kRustViewMetadataV1CurrentVersionNotFound, + ErrorKind::kInvalid}, + ReferenceFixture{"RustMissingVersion", + test::kRustViewMetadataV1MissingCurrentVersion, + ErrorKind::kJsonParseError}, + ReferenceFixture{"RustMissingSchema", test::kRustViewMetadataV1MissingSchema, + ErrorKind::kJsonParseError}, + ReferenceFixture{"RustSchemaNotFound", test::kRustViewMetadataV1SchemaNotFound, + ErrorKind::kInvalid}), + [](const ::testing::TestParamInfo& info) { + return info.param.name; + }); + +TEST(ViewMetadataJsonTest, RequiresTopLevelFields) { + for (const auto* key : {"view-uuid", "format-version", "location", "schemas", + "current-version-id", "versions", "version-log"}) { + SCOPED_TRACE(key); + auto value = ValidMetadataJson(); + value.erase(key); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + value[key] = nullptr; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } +} + +TEST(ViewMetadataJsonTest, RequiresVersionFields) { + for (const auto* key : {"version-id", "schema-id", "timestamp-ms", "summary", + "representations", "default-namespace"}) { + SCOPED_TRACE(key); + auto value = ValidMetadataJson(); + value["versions"][0].erase(key); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + value["versions"][0][key] = nullptr; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } +} + +TEST(ViewMetadataJsonTest, RequiresHistoryAndSchemaIds) { + for (const auto* key : {"version-id", "timestamp-ms"}) { + auto value = ValidMetadataJson(); + value["version-log"][0].erase(key); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } + auto value = ValidMetadataJson(); + value["schemas"][0].erase("schema-id"); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); +} + +TEST(ViewMetadataJsonTest, RequiresSqlRepresentationFields) { + for (const auto* key : {"type", "sql", "dialect"}) { + SCOPED_TRACE(key); + auto value = ValidMetadataJson(); + value["versions"][0]["representations"][0].erase(key); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + value["versions"][0]["representations"][0][key] = nullptr; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } +} + +TEST(ViewMetadataJsonTest, RejectsWrongJsonShapes) { + for (const auto& value : + {json(nullptr), json(true), json(1), json("metadata"), json::array()}) { + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } + for (const auto* path : + {"/schemas", "/versions", "/version-log", "/versions/0/representations", + "/versions/0/default-namespace"}) { + SCOPED_TRACE(path); + auto value = ValidMetadataJson(); + value[json::json_pointer(path)] = json::object(); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } + for (const auto* path : + {"/schemas/0", "/versions/0", "/version-log/0", "/versions/0/representations/0", + "/properties", "/versions/0/summary"}) { + SCOPED_TRACE(path); + auto value = ValidMetadataJson(); + value[json::json_pointer(path)] = json::array(); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } +} + +TEST(ViewMetadataJsonTest, RejectsNonArraySchemaFields) { + auto value = ValidMetadataJson(); + const json field_map{{"field", value["schemas"][0]["fields"][0]}}; + for (const auto& fields : + {json::object(), field_map, json(nullptr), json(false), json(1), json("fields")}) { + SCOPED_TRACE(fields.dump()); + value["schemas"][0]["fields"] = fields; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + EXPECT_THAT(ViewMetadataFromJsonString(value.dump()), + IsError(ErrorKind::kJsonParseError)); + } + value["schemas"][0]["fields"] = json::array(); + EXPECT_THAT(ViewMetadataFromJson(value), IsOk()); +} + +TEST(ViewMetadataJsonTest, RejectsNonArrayNestedStructFields) { + const json structure{{"type", "struct"}, {"fields", json::array()}}; + const std::vector> types{{structure, "/fields"}, + {{{"type", "list"}, + {"element-id", 3}, + {"element-required", false}, + {"element", structure}}, + "/element/fields"}, + {{{"type", "map"}, + {"key-id", 3}, + {"key", structure}, + {"value-id", 4}, + {"value", "int"}, + {"value-required", false}}, + "/key/fields"}, + {{{"type", "map"}, + {"key-id", 3}, + {"key", "int"}, + {"value-id", 4}, + {"value", structure}, + {"value-required", false}}, + "/value/fields"}}; + for (const auto& [type, path] : types) { + SCOPED_TRACE(type.dump()); + auto value = ValidMetadataJson(); + value["schemas"][0]["fields"][0]["type"] = type; + ASSERT_THAT(ViewMetadataFromJson(value), IsOk()); + value["schemas"][0]["fields"][0]["type"][json::json_pointer(path)] = json::object(); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } +} + +TEST(ViewMetadataJsonTest, RejectsNonStringValues) { + for (const auto* path : + {"/view-uuid", "/location", "/properties/comment", "/versions/0/default-catalog", + "/versions/0/default-namespace/0", "/versions/0/summary/engine-name", + "/versions/0/representations/0/type", "/versions/0/representations/0/sql", + "/versions/0/representations/0/dialect"}) { + SCOPED_TRACE(path); + auto value = ValidMetadataJson(); + value[json::json_pointer(path)] = 1; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } +} + +TEST(ViewMetadataJsonTest, RejectsLossyIntegerConversions) { + for (const auto* path : + {"/format-version", "/current-version-id", "/schemas/0/schema-id", + "/schemas/0/fields/0/id", "/versions/0/version-id", "/versions/0/schema-id", + "/versions/0/timestamp-ms", "/version-log/0/version-id", + "/version-log/0/timestamp-ms"}) { + SCOPED_TRACE(path); + for (const auto& invalid : {json(true), json("1"), json(1.0), json(1.5), + json(std::numeric_limits::max())}) { + auto value = ValidMetadataJson(); + value[json::json_pointer(path)] = invalid; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + } + } + auto value = ValidMetadataJson(); + value["format-version"] = 257; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); + value = ValidMetadataJson(); + value["current-version-id"] = int64_t{1} << 32; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); +} + +TEST(ViewMetadataJsonTest, PreservesTimestampLimits) { + for (const auto timestamp : + {std::numeric_limits::min(), std::numeric_limits::max()}) { + auto value = ValidMetadataJson(); + value["versions"][0]["timestamp-ms"] = timestamp; + value["version-log"][0]["timestamp-ms"] = timestamp; + ICEBERG_UNWRAP_OR_FAIL(auto parsed, ViewMetadataFromJson(value)); + EXPECT_EQ(UnixMsFromTimePointMs(parsed->versions[0]->timestamp_ms), timestamp); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*parsed)); + EXPECT_EQ(serialized, value); + } +} + +TEST(ViewMetadataJsonTest, AcceptsOptionalFieldsAndEmptyNamespace) { + auto value = ValidMetadataJson(); + value.erase("properties"); + value["versions"][0].erase("default-catalog"); + value["versions"][0]["default-namespace"] = json::array(); + ICEBERG_UNWRAP_OR_FAIL(auto parsed, ViewMetadataFromJson(value)); + EXPECT_TRUE(parsed->properties.empty()); + EXPECT_FALSE(parsed->versions[0]->default_catalog.has_value()); + EXPECT_TRUE(parsed->versions[0]->default_namespace.levels.empty()); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*parsed)); + EXPECT_EQ(serialized, value); + value["versions"][0]["default-catalog"] = nullptr; + EXPECT_THAT(ViewMetadataFromJson(value), IsOk()); + value["properties"] = nullptr; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); +} + +TEST(ViewMetadataJsonTest, ValidatesReferencesAndMetadataValues) { + const std::vector> invalid_values{ + {"/view-uuid", "x"}, + {"/location", ""}, + {"/schemas", json::array()}, + {"/versions", json::array()}, + {"/current-version-id", 99}, + {"/versions/0/schema-id", 99}, + {"/version-log/0/version-id", 99}, + {"/versions/0/representations/0/sql", ""}, + {"/versions/0/representations/0/dialect", ""}, + {"/versions/0/representations/0/type", ""}}; + for (const auto& [path, invalid] : invalid_values) { + SCOPED_TRACE(path); + auto value = ValidMetadataJson(); + value[json::json_pointer(path)] = invalid; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); + } + for (const auto* key : {"schemas", "versions"}) { + auto value = ValidMetadataJson(); + value[key].push_back(value[key][0]); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); + } + auto value = ValidMetadataJson(); + value["schemas"][0]["fields"][1]["id"] = 1; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataJsonTest, RejectsUnicodeDuplicateDialects) { + auto value = ValidMetadataJson(); + auto& representations = value["versions"][0]["representations"]; + representations[0]["dialect"] = "Éngine"; + auto duplicate = representations[0]; + duplicate["dialect"] = "éngine"; + representations.push_back(std::move(duplicate)); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataJsonTest, PreservesUnknownRepresentationFieldsAndValueEquality) { + auto value = ValidMetadataJson(); + json unknown{{"type", "Cypher"}, + {"query", "MATCH (n) RETURN n"}, + {"settings", + {{"enabled", false}, + {"values", {1, nullptr, "x"}}, + {"large", std::numeric_limits::max()}}}, + {"empty", json::object()}}; + value["versions"][0]["representations"].push_back(unknown); + ICEBERG_UNWRAP_OR_FAIL(auto parsed, ViewMetadataFromJson(value)); + const auto& opaque = + std::get(parsed->versions[0]->representations[1]); + EXPECT_EQ(opaque.type, "Cypher"); + auto expected_fields = unknown; + expected_fields.erase("type"); + EXPECT_EQ(json(opaque.extra_fields), expected_fields); + auto changed = opaque; + changed.extra_fields["settings"]["enabled"] = true; + EXPECT_NE(opaque, changed); + parsed->properties["comment"] = "updated property"; + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*parsed)); + EXPECT_EQ(serialized["versions"][0]["representations"][1], unknown); + ICEBERG_UNWRAP_OR_FAIL(auto text, ToJsonString(*parsed)); + ICEBERG_UNWRAP_OR_FAIL(auto restored, ViewMetadataFromJsonString(text)); + EXPECT_EQ(*parsed, *restored); + ICEBERG_UNWRAP_OR_FAIL(auto again, ToJsonString(*restored)); + EXPECT_EQ(text, again); +} + +TEST(ViewMetadataJsonTest, RejectsOutOfRangeIntegerLiteralsInUnknownPayloads) { + for (const auto* number : + {"18446744073709551616", "18446744073709551617", "-9223372036854775809", + "340282366920938463463374607431768211455"}) { + SCOPED_TRACE(number); + EXPECT_THAT(ViewMetadataFromJsonString(MetadataWithUnknownPayload(number)), + IsError(ErrorKind::kJsonParseError)); + const auto nested = std::string("{\"nested\":[") + number + "]}"; + EXPECT_THAT(ViewMetadataFromJsonString(MetadataWithUnknownPayload(nested)), + IsError(ErrorKind::kJsonParseError)); + } +} + +TEST(ViewMetadataJsonTest, PreservesSupportedNumbersInUnknownPayloadsFromStrings) { + constexpr std::string_view kPayload = R"json({ + "limits": [-9223372036854775808, 9223372036854775807, 18446744073709551615], + "fraction": 1.25, + "exponent": -1.25e3, + "text": "18446744073709551617", + "escaped": "\"18446744073709551617\"" + })json"; + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, ViewMetadataFromJsonString(MetadataWithUnknownPayload(kPayload))); + metadata->properties["comment"] = "updated property"; + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJsonString(*metadata)); + EXPECT_EQ(json::parse(serialized)["versions"][0]["representations"][1]["payload"], + json::parse(kPayload)); + ICEBERG_UNWRAP_OR_FAIL(auto restored, ViewMetadataFromJsonString(serialized)); + EXPECT_EQ(*metadata, *restored); +} + +TEST(ViewMetadataJsonTest, ReservesTheSqlDiscriminator) { + for (const auto* type : {"sql", "SQL", "SqL", "ſql"}) { + SCOPED_TRACE(type); + const json value{{"type", type}, {"sql", "SELECT 1"}, {"dialect", "spark"}}; + ICEBERG_UNWRAP_OR_FAIL(auto representation, ViewRepresentationFromJson(value)); + ASSERT_NE(GetSql(representation), nullptr); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(representation)); + EXPECT_EQ(serialized["type"], "sql"); + EXPECT_THAT(ViewRepresentationFromJson(json{{"type", type}}), + IsError(ErrorKind::kJsonParseError)); + ViewRepresentation invalid = UnknownViewRepresentation{.type = type}; + EXPECT_THAT(ToJson(invalid), IsError(ErrorKind::kInvalid)); + } +} + +TEST(ViewMetadataJsonTest, RejectsAnUnknownPayloadThatOverridesType) { + ViewRepresentation invalid = UnknownViewRepresentation{ + .type = "cypher", .extra_fields = {{"type", "sql"}, {"sql", "SELECT 1"}}}; + EXPECT_THAT(ToJson(invalid), IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(ValidMetadataJson())); + metadata->versions[0]->representations.push_back(std::move(invalid)); + EXPECT_THAT(metadata->Validate(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataJsonTest, ValidatesBeforeSerializationAndDoesNotMutateMetadata) { + ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(ValidMetadataJson())); + ICEBERG_UNWRAP_OR_FAIL(auto before, ViewMetadataFromJson(ValidMetadataJson())); + EXPECT_THAT(ToJson(*metadata), IsOk()); + EXPECT_EQ(*metadata, *before); + metadata->schemas.push_back(nullptr); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ToJsonString(*metadata), IsError(ErrorKind::kInvalid)); + metadata->schemas.pop_back(); + metadata->versions.push_back(nullptr); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kInvalid)); +} + +TEST(ViewMetadataJsonTest, ReusesViewSchemaRules) { + auto value = ValidMetadataJson(); + value["schemas"][0]["fields"] = json::array( + {{{"id", 1}, {"name", "unknown"}, {"required", true}, {"type", "unknown"}}, + {{"id", 2}, {"name", "ts"}, {"required", false}, {"type", "timestamp_ns"}}}); + ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(value)); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*metadata)); + EXPECT_EQ(serialized, value); +} + +TEST(ViewMetadataJsonTest, RejectsMalformedStringsAndExcessiveNesting) { + for (const auto* text : {"", "{", "null", "[]", "{} trailing"}) { + EXPECT_THAT(ViewMetadataFromJsonString(text), IsError(ErrorKind::kJsonParseError)); + } + std::string nested(kMaxJsonNestingDepth + 1, '['); + nested += "0"; + nested.append(kMaxJsonNestingDepth + 1, ']'); + EXPECT_THAT(ViewMetadataFromJsonString(nested), IsError(ErrorKind::kJsonParseError)); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/view/json_serde.cc b/src/iceberg/view/json_serde.cc new file mode 100644 index 000000000..be4940cbf --- /dev/null +++ b/src/iceberg/view/json_serde.cc @@ -0,0 +1,283 @@ +/* + * 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 +#include +#include +#include +#include + +#include + +#include "iceberg/json_serde_internal.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/util/json_util_internal.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/string_util.h" +#include "iceberg/util/timepoint.h" +#include "iceberg/view/json_serde_internal.h" + +namespace iceberg { +namespace { + +constexpr std::string_view kType = "type"; +constexpr std::string_view kSql = "sql"; +constexpr std::string_view kDialect = "dialect"; +constexpr std::string_view kVersionId = "version-id"; +constexpr std::string_view kSchemaId = "schema-id"; +constexpr std::string_view kTimestampMs = "timestamp-ms"; +constexpr std::string_view kSummary = "summary"; +constexpr std::string_view kRepresentations = "representations"; +constexpr std::string_view kDefaultCatalog = "default-catalog"; +constexpr std::string_view kDefaultNamespace = "default-namespace"; +constexpr std::string_view kViewUuid = "view-uuid"; +constexpr std::string_view kFormatVersion = "format-version"; +constexpr std::string_view kLocation = "location"; +constexpr std::string_view kCurrentVersionId = "current-version-id"; +constexpr std::string_view kVersions = "versions"; +constexpr std::string_view kSchemas = "schemas"; +constexpr std::string_view kVersionLog = "version-log"; +constexpr std::string_view kProperties = "properties"; + +// The DOM parser converts overflowing integer literals to doubles. SAX still +// provides the original token, so distinguish them from floating-point literals. +class JsonIntegerValidator final : public nlohmann::json_sax { + public: + bool null() override { return true; } + bool boolean(bool) override { return true; } + bool number_integer(number_integer_t) override { return true; } + bool number_unsigned(number_unsigned_t) override { return true; } + bool number_float(number_float_t, const string_t& token) override { + return token.find_first_of(".eE") != std::string::npos; + } + bool string(string_t&) override { return true; } + bool binary(binary_t&) override { return true; } + bool start_object(std::size_t) override { return true; } + bool key(string_t&) override { return true; } + bool end_object() override { return true; } + bool start_array(std::size_t) override { return true; } + bool end_array() override { return true; } + bool parse_error(std::size_t, const std::string&, + const nlohmann::detail::exception&) override { + return false; + } +}; + +Status RequireObject(const nlohmann::json& json, std::string_view description) { + if (!json.is_object()) { + return JsonParseError("{} must be an object, but is {}", description, + json.type_name()); + } + return {}; +} + +Result RequiredArray(const nlohmann::json& json, std::string_view key) { + ICEBERG_ASSIGN_OR_RAISE(auto array, GetJsonValue(json, key)); + if (!array.is_array()) { + return JsonParseError("'{}' must be an array, but is {}", key, array.type_name()); + } + return array; +} + +bool IsSqlType(std::string_view type) { + return StringUtils::EqualsIgnoreCase(type, kSqlRepresentationType) || + StringUtils::EqualsIgnoreCase(type, "ſql"); +} + +Status ValidateRepresentation(const ViewRepresentation& representation) { + if (const auto* sql = GetSql(representation)) { + if (sql->sql.empty() || sql->dialect.empty()) { + return Invalid("SQL view representations require non-empty SQL and dialect"); + } + } else { + const auto& unknown = std::get(representation); + if (unknown.type.empty() || IsSqlType(unknown.type)) { + return Invalid("Unknown view representation must have a non-SQL type"); + } + if (unknown.extra_fields.contains("type")) { + return Invalid("Unknown view representation fields must not contain 'type'"); + } + } + return {}; +} + +} // namespace + +Result ToJson(const ViewRepresentation& representation) { + ICEBERG_RETURN_UNEXPECTED(ValidateRepresentation(representation)); + if (const auto* sql = GetSql(representation)) { + return nlohmann::json{ + {kType, kSqlRepresentationType}, {kSql, sql->sql}, {kDialect, sql->dialect}}; + } + const auto& unknown = std::get(representation); + nlohmann::json json = unknown.extra_fields; + json[kType] = unknown.type; + return json; +} + +Result ViewRepresentationFromJson(const nlohmann::json& json) { + ICEBERG_RETURN_UNEXPECTED(RequireObject(json, "View representation")); + ICEBERG_ASSIGN_OR_RAISE(auto type, GetJsonValue(json, kType)); + ViewRepresentation representation; + if (IsSqlType(type)) { + ICEBERG_ASSIGN_OR_RAISE(auto sql, GetJsonValue(json, kSql)); + ICEBERG_ASSIGN_OR_RAISE(auto dialect, GetJsonValue(json, kDialect)); + representation = + SqlViewRepresentation{.sql = std::move(sql), .dialect = std::move(dialect)}; + } else { + auto fields = json.get(); + fields.erase(std::string(kType)); + representation = UnknownViewRepresentation{.type = std::move(type), + .extra_fields = std::move(fields)}; + } + ICEBERG_RETURN_UNEXPECTED(ValidateRepresentation(representation)); + return representation; +} + +Result ToJson(const ViewVersion& version) { + nlohmann::json representations = nlohmann::json::array(); + for (const auto& representation : version.representations) { + ICEBERG_ASSIGN_OR_RAISE(auto value, ToJson(representation)); + representations.push_back(std::move(value)); + } + nlohmann::json json{{kVersionId, version.version_id}, + {kSchemaId, version.schema_id}, + {kTimestampMs, version.timestamp_ms.time_since_epoch().count()}, + {kSummary, version.summary}, + {kRepresentations, std::move(representations)}, + {kDefaultNamespace, ToJson(version.default_namespace)}}; + SetOptionalField(json, kDefaultCatalog, version.default_catalog); + return json; +} + +Result ViewVersionFromJson(const nlohmann::json& json) { + ICEBERG_RETURN_UNEXPECTED(RequireObject(json, "View version")); + ViewVersion version; + ICEBERG_ASSIGN_OR_RAISE(version.version_id, GetJsonInteger(json, kVersionId)); + ICEBERG_ASSIGN_OR_RAISE(version.schema_id, GetJsonInteger(json, kSchemaId)); + ICEBERG_ASSIGN_OR_RAISE(auto timestamp, GetJsonInteger(json, kTimestampMs)); + version.timestamp_ms = TimePointMsFromUnixMs(timestamp); + if (!json.contains(kSummary)) { + return JsonParseError("Missing 'summary' in view version"); + } + ICEBERG_ASSIGN_OR_RAISE(version.summary, FromJsonMap(json, kSummary)); + ICEBERG_ASSIGN_OR_RAISE(auto representations, RequiredArray(json, kRepresentations)); + for (const auto& representation : representations) { + ICEBERG_ASSIGN_OR_RAISE(auto value, ViewRepresentationFromJson(representation)); + version.representations.push_back(std::move(value)); + } + ICEBERG_ASSIGN_OR_RAISE(version.default_catalog, + GetJsonValueOptional(json, kDefaultCatalog)); + ICEBERG_ASSIGN_OR_RAISE(auto ns, GetJsonValue(json, kDefaultNamespace)); + ICEBERG_ASSIGN_OR_RAISE(version.default_namespace, NamespaceFromJson(ns)); + return version; +} + +nlohmann::json ToJson(const ViewHistoryEntry& entry) { + return {{kTimestampMs, entry.timestamp_ms.time_since_epoch().count()}, + {kVersionId, entry.version_id}}; +} + +Result ViewHistoryEntryFromJson(const nlohmann::json& json) { + ICEBERG_RETURN_UNEXPECTED(RequireObject(json, "View history entry")); + ICEBERG_ASSIGN_OR_RAISE(auto timestamp, GetJsonInteger(json, kTimestampMs)); + ICEBERG_ASSIGN_OR_RAISE(auto version, GetJsonInteger(json, kVersionId)); + return ViewHistoryEntry{.timestamp_ms = TimePointMsFromUnixMs(timestamp), + .version_id = version}; +} + +Result ToJson(const ViewMetadata& metadata) { + ICEBERG_RETURN_UNEXPECTED(metadata.Validate()); + nlohmann::json schemas = nlohmann::json::array(); + for (const auto& schema : metadata.schemas) { + ICEBERG_ASSIGN_OR_RAISE(auto value, ToJson(*schema)); + schemas.push_back(std::move(value)); + } + nlohmann::json versions = nlohmann::json::array(); + for (const auto& version : metadata.versions) { + ICEBERG_ASSIGN_OR_RAISE(auto value, ToJson(*version)); + versions.push_back(std::move(value)); + } + nlohmann::json history = nlohmann::json::array(); + for (const auto& entry : metadata.version_log) { + history.push_back(ToJson(entry)); + } + nlohmann::json json{ + {kViewUuid, metadata.view_uuid}, {kFormatVersion, metadata.format_version}, + {kLocation, metadata.location}, {kCurrentVersionId, metadata.current_version_id}, + {kSchemas, std::move(schemas)}, {kVersions, std::move(versions)}, + {kVersionLog, std::move(history)}}; + SetContainerField(json, kProperties, metadata.properties); + return json; +} + +Result ToJsonString(const ViewMetadata& metadata) { + ICEBERG_ASSIGN_OR_RAISE(auto json, ToJson(metadata)); + return ToJsonString(json); +} + +Result> ViewMetadataFromJson(const nlohmann::json& json) { + ICEBERG_RETURN_UNEXPECTED(RequireObject(json, "View metadata")); + auto metadata = std::make_unique(); + ICEBERG_ASSIGN_OR_RAISE(metadata->format_version, + GetJsonInteger(json, kFormatVersion)); + if (metadata->format_version != ViewMetadata::kSupportedViewFormatVersion) { + return JsonParseError("Unsupported view format version: {}", + static_cast(metadata->format_version)); + } + ICEBERG_ASSIGN_OR_RAISE(metadata->view_uuid, + GetJsonValue(json, kViewUuid)); + ICEBERG_ASSIGN_OR_RAISE(metadata->location, GetJsonValue(json, kLocation)); + ICEBERG_ASSIGN_OR_RAISE(metadata->current_version_id, + GetJsonInteger(json, kCurrentVersionId)); + ICEBERG_ASSIGN_OR_RAISE(auto schemas, RequiredArray(json, kSchemas)); + for (const auto& schema : schemas) { + ICEBERG_RETURN_UNEXPECTED(GetJsonInteger(schema, kSchemaId)); + ICEBERG_ASSIGN_OR_RAISE(auto value, SchemaFromJson(schema)); + metadata->schemas.push_back(std::move(value)); + } + ICEBERG_ASSIGN_OR_RAISE(auto versions, RequiredArray(json, kVersions)); + for (const auto& version : versions) { + ICEBERG_ASSIGN_OR_RAISE(auto value, ViewVersionFromJson(version)); + metadata->versions.push_back(std::make_shared(std::move(value))); + } + ICEBERG_ASSIGN_OR_RAISE(auto history, RequiredArray(json, kVersionLog)); + for (const auto& entry : history) { + ICEBERG_ASSIGN_OR_RAISE(auto value, ViewHistoryEntryFromJson(entry)); + metadata->version_log.push_back(value); + } + ICEBERG_ASSIGN_OR_RAISE(metadata->properties, FromJsonMap(json, kProperties)); + ICEBERG_RETURN_UNEXPECTED(metadata->Validate()); + return metadata; +} + +Result> ViewMetadataFromJsonString( + std::string_view json_string) { + ICEBERG_ASSIGN_OR_RAISE(auto json, ParseJsonString(json_string)); + // Syntax and nesting limits have already been checked. Validate the original + // number tokens before accepting payloads that the DOM cannot preserve. + JsonIntegerValidator validator; + if (!nlohmann::json::sax_parse(json_string, &validator)) { + return JsonParseError("JSON integer literal is outside the supported 64-bit range"); + } + return ViewMetadataFromJson(json); +} + +} // namespace iceberg diff --git a/src/iceberg/view/json_serde_internal.h b/src/iceberg/view/json_serde_internal.h new file mode 100644 index 000000000..1a8a46ae6 --- /dev/null +++ b/src/iceberg/view/json_serde_internal.h @@ -0,0 +1,62 @@ +/* + * 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 "iceberg/iceberg_export.h" +#include "iceberg/result.h" +#include "iceberg/view/view_metadata.h" + +namespace iceberg { + +/// \brief Serialize a representation, preserving unknown representation fields. +ICEBERG_EXPORT Result ToJson(const ViewRepresentation& representation); +ICEBERG_EXPORT Result ViewRepresentationFromJson( + const nlohmann::json& json); + +/// \brief Serialize the fields of a view version. +/// Metadata validation checks schema references and per-version dialect uniqueness. +ICEBERG_EXPORT Result ToJson(const ViewVersion& version); +ICEBERG_EXPORT Result ViewVersionFromJson(const nlohmann::json& json); + +ICEBERG_EXPORT nlohmann::json ToJson(const ViewHistoryEntry& entry); +ICEBERG_EXPORT Result ViewHistoryEntryFromJson( + const nlohmann::json& json); + +/// \brief Validate and serialize view metadata. +ICEBERG_EXPORT Result ToJson(const ViewMetadata& metadata); +ICEBERG_EXPORT Result ToJsonString(const ViewMetadata& metadata); + +/// \brief Parse structural JSON fields, then validate the complete metadata. +/// Structural errors return kJsonParseError; metadata invariants return kInvalid. +ICEBERG_EXPORT Result> ViewMetadataFromJson( + const nlohmann::json& json); + +/// \brief Parse view metadata, rejecting integer literals outside the signed or +/// unsigned 64-bit ranges rather than silently rounding unknown payload values. +ICEBERG_EXPORT Result> ViewMetadataFromJsonString( + std::string_view json_string); + +} // namespace iceberg diff --git a/src/iceberg/view/view_metadata.cc b/src/iceberg/view/view_metadata.cc index 9953828b4..43fb02bcf 100644 --- a/src/iceberg/view/view_metadata.cc +++ b/src/iceberg/view/view_metadata.cc @@ -138,6 +138,9 @@ Status ViewMetadata::Validate() const { "View version {} has an unknown representation without a type", version->version_id); } + if (unknown.extra_fields.contains("type")) { + return ValidationFailed("Unknown view representation fields must not contain 'type'"); + } if (StringUtils::EqualsIgnoreCase(unknown.type, kSqlRepresentationType)) { return ValidationFailed( "View version {} must use an SQL representation for type '{}'", diff --git a/src/iceberg/view/view_version.h b/src/iceberg/view/view_version.h index 476194b02..43cc04039 100644 --- a/src/iceberg/view/view_version.h +++ b/src/iceberg/view/view_version.h @@ -30,6 +30,8 @@ #include #include +#include + #include "iceberg/iceberg_export.h" #include "iceberg/table_identifier.h" #include "iceberg/util/timepoint.h" @@ -55,6 +57,8 @@ struct ICEBERG_EXPORT SqlViewRepresentation { struct ICEBERG_EXPORT UnknownViewRepresentation { /// The representation type identifier from the metadata, such as "cypher". std::string type; + /// Representation-specific JSON fields, excluding the type discriminator. + nlohmann::json::object_t extra_fields; /// \brief Compare two unknown representations for equality. friend bool operator==(const UnknownViewRepresentation& lhs, From b563189a5ab3b7b8c4eacb227ebcc466bc6f73e6 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 30 Nov 2026 21:44:54 +0000 Subject: [PATCH 2/3] fix(view): separate serde validation and add typed properties --- src/iceberg/CMakeLists.txt | 1 + src/iceberg/cpp20_compatibility_internal.h | 1 + src/iceberg/test/CMakeLists.txt | 7 +- src/iceberg/test/view_metadata_json_test.cc | 119 ++++++++++++++++---- src/iceberg/test/view_properties_test.cc | 87 ++++++++++++++ src/iceberg/view/json_serde.cc | 20 ++-- src/iceberg/view/json_serde_internal.h | 10 +- src/iceberg/view/type_fwd.h | 1 + src/iceberg/view/view_metadata.cc | 60 ++++++---- src/iceberg/view/view_metadata.h | 8 +- src/iceberg/view/view_metadata_internal.h | 33 ++++++ src/iceberg/view/view_properties.cc | 33 ++++++ src/iceberg/view/view_properties.h | 58 ++++++++++ 13 files changed, 374 insertions(+), 64 deletions(-) create mode 100644 src/iceberg/test/view_properties_test.cc create mode 100644 src/iceberg/view/view_metadata_internal.h create mode 100644 src/iceberg/view/view_properties.cc create mode 100644 src/iceberg/view/view_properties.h diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 41be635d5..f09db1b28 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -180,6 +180,7 @@ set(ICEBERG_SOURCES util/uuid.cc view/json_serde.cc view/view_metadata.cc + view/view_properties.cc view/view_version.cc) set(ICEBERG_STATIC_BUILD_INTERFACE_LIBS) diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 5c2115c21..7cc349807 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -211,6 +211,7 @@ #include "iceberg/util/visitor_generate.h" #include "iceberg/view/type_fwd.h" #include "iceberg/view/view_metadata.h" +#include "iceberg/view/view_properties.h" #include "iceberg/view/view_version.h" #ifdef ICEBERG_PUBLIC_HEADERS_BUNDLE diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 98b60f61e..89df6b49c 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -161,8 +161,11 @@ 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 - view_metadata_json_test.cc) +add_iceberg_test(view_metadata_test + SOURCES + view_metadata_test.cc + view_metadata_json_test.cc + view_properties_test.cc) add_iceberg_test(util_test USE_DATA diff --git a/src/iceberg/test/view_metadata_json_test.cc b/src/iceberg/test/view_metadata_json_test.cc index 2ebcef217..4ffb54cca 100644 --- a/src/iceberg/test/view_metadata_json_test.cc +++ b/src/iceberg/test/view_metadata_json_test.cc @@ -34,6 +34,7 @@ #include "iceberg/util/json_util_internal.h" #include "iceberg/util/timepoint.h" #include "iceberg/view/json_serde_internal.h" +#include "iceberg/view/view_properties.h" namespace iceberg { namespace { @@ -56,6 +57,7 @@ struct ReferenceFixture { std::string name; std::string_view source; std::optional error; + bool valid_for_creation = true; }; class ViewMetadataReferenceJsonTest : public ::testing::TestWithParam { @@ -69,7 +71,11 @@ TEST_P(ViewMetadataReferenceJsonTest, ParseAndRoundTrip) { return; } ASSERT_THAT(parsed, IsOk()); - EXPECT_THAT((*parsed)->Validate(), IsOk()); + if (fixture.valid_for_creation) { + EXPECT_THAT((*parsed)->Validate(), IsOk()); + } else { + EXPECT_THAT((*parsed)->Validate(), IsError(ErrorKind::kValidationFailed)); + } ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(**parsed)); auto expected = json::parse(fixture.source); // Java's fixture carries a legacy field outside the view format. The current @@ -88,32 +94,32 @@ INSTANTIATE_TEST_SUITE_P( ::testing::Values( ReferenceFixture{"JavaValid", test::kJavaValidViewMetadata, std::nullopt}, ReferenceFixture{"JavaInvalidSchema", test::kJavaViewMetadataInvalidCurrentSchema, - ErrorKind::kInvalid}, + std::nullopt, false}, ReferenceFixture{"JavaInvalidVersion", - test::kJavaViewMetadataInvalidCurrentVersion, - ErrorKind::kInvalid}, + test::kJavaViewMetadataInvalidCurrentVersion, std::nullopt, + false}, ReferenceFixture{"JavaMissingVersion", test::kJavaViewMetadataMissingCurrentVersion, ErrorKind::kJsonParseError}, ReferenceFixture{"JavaMissingLocation", test::kJavaViewMetadataMissingLocation, ErrorKind::kJsonParseError}, ReferenceFixture{"JavaDuplicateDialects", - test::kJavaViewMetadataMultipleSQLsForDialect, - ErrorKind::kInvalid}, + test::kJavaViewMetadataMultipleSQLsForDialect, std::nullopt, + false}, ReferenceFixture{"RustValid", test::kRustViewMetadataV1Valid, std::nullopt}, ReferenceFixture{"RustUnsupportedVersion", test::kRustViewMetadataUnsupportedVersion, ErrorKind::kJsonParseError}, ReferenceFixture{"RustVersionNotFound", - test::kRustViewMetadataV1CurrentVersionNotFound, - ErrorKind::kInvalid}, + test::kRustViewMetadataV1CurrentVersionNotFound, std::nullopt, + false}, ReferenceFixture{"RustMissingVersion", test::kRustViewMetadataV1MissingCurrentVersion, ErrorKind::kJsonParseError}, ReferenceFixture{"RustMissingSchema", test::kRustViewMetadataV1MissingSchema, ErrorKind::kJsonParseError}, ReferenceFixture{"RustSchemaNotFound", test::kRustViewMetadataV1SchemaNotFound, - ErrorKind::kInvalid}), + std::nullopt, false}), [](const ::testing::TestParamInfo& info) { return info.param.name; }); @@ -299,7 +305,7 @@ TEST(ViewMetadataJsonTest, AcceptsOptionalFieldsAndEmptyNamespace) { EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kJsonParseError)); } -TEST(ViewMetadataJsonTest, ValidatesReferencesAndMetadataValues) { +TEST(ViewMetadataJsonTest, PreservesValuesRejectedByCreationValidation) { const std::vector> invalid_values{ {"/view-uuid", "x"}, {"/location", ""}, @@ -315,26 +321,40 @@ TEST(ViewMetadataJsonTest, ValidatesReferencesAndMetadataValues) { SCOPED_TRACE(path); auto value = ValidMetadataJson(); value[json::json_pointer(path)] = invalid; - EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(value)); + EXPECT_THAT(metadata->Validate(), IsError(ErrorKind::kValidationFailed)); + metadata->properties["comment"] = "updated property"; + value["properties"]["comment"] = "updated property"; + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*metadata)); + EXPECT_EQ(serialized, value); + ICEBERG_UNWRAP_OR_FAIL(auto text, ToJsonString(*metadata)); + ICEBERG_UNWRAP_OR_FAIL(auto restored, ViewMetadataFromJsonString(text)); + EXPECT_EQ(*metadata, *restored); } +} + +TEST(ViewMetadataJsonTest, RejectsAmbiguousIdsAndMalformedSchemaStructure) { for (const auto* key : {"schemas", "versions"}) { auto value = ValidMetadataJson(); value[key].push_back(value[key][0]); - EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kValidationFailed)); } auto value = ValidMetadataJson(); value["schemas"][0]["fields"][1]["id"] = 1; - EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kValidationFailed)); } -TEST(ViewMetadataJsonTest, RejectsUnicodeDuplicateDialects) { +TEST(ViewMetadataJsonTest, ReadsUnicodeDuplicateDialectsButCreationRejectsThem) { auto value = ValidMetadataJson(); auto& representations = value["versions"][0]["representations"]; representations[0]["dialect"] = "Éngine"; auto duplicate = representations[0]; duplicate["dialect"] = "éngine"; representations.push_back(std::move(duplicate)); - EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(value)); + EXPECT_THAT(metadata->Validate(), IsError(ErrorKind::kValidationFailed)); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*metadata)); + EXPECT_EQ(serialized, value); } TEST(ViewMetadataJsonTest, PreservesUnknownRepresentationFieldsAndValueEquality) { @@ -409,18 +429,18 @@ TEST(ViewMetadataJsonTest, ReservesTheSqlDiscriminator) { EXPECT_THAT(ViewRepresentationFromJson(json{{"type", type}}), IsError(ErrorKind::kJsonParseError)); ViewRepresentation invalid = UnknownViewRepresentation{.type = type}; - EXPECT_THAT(ToJson(invalid), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ToJson(invalid), IsError(ErrorKind::kValidationFailed)); } } TEST(ViewMetadataJsonTest, RejectsAnUnknownPayloadThatOverridesType) { ViewRepresentation invalid = UnknownViewRepresentation{ .type = "cypher", .extra_fields = {{"type", "sql"}, {"sql", "SELECT 1"}}}; - EXPECT_THAT(ToJson(invalid), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ToJson(invalid), IsError(ErrorKind::kValidationFailed)); ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(ValidMetadataJson())); metadata->versions[0]->representations.push_back(std::move(invalid)); - EXPECT_THAT(metadata->Validate(), IsError(ErrorKind::kInvalid)); - EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(metadata->Validate(), IsError(ErrorKind::kValidationFailed)); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataJsonTest, ValidatesBeforeSerializationAndDoesNotMutateMetadata) { @@ -429,23 +449,76 @@ TEST(ViewMetadataJsonTest, ValidatesBeforeSerializationAndDoesNotMutateMetadata) EXPECT_THAT(ToJson(*metadata), IsOk()); EXPECT_EQ(*metadata, *before); metadata->schemas.push_back(nullptr); - EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kInvalid)); - EXPECT_THAT(ToJsonString(*metadata), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kValidationFailed)); + EXPECT_THAT(ToJsonString(*metadata), IsError(ErrorKind::kValidationFailed)); metadata->schemas.pop_back(); metadata->versions.push_back(nullptr); - EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kValidationFailed)); } TEST(ViewMetadataJsonTest, ReusesViewSchemaRules) { auto value = ValidMetadataJson(); value["schemas"][0]["fields"] = json::array( - {{{"id", 1}, {"name", "unknown"}, {"required", true}, {"type", "unknown"}}, + {{{"id", 1}, {"name", "unknown"}, {"required", false}, {"type", "unknown"}}, {{"id", 2}, {"name", "ts"}, {"required", false}, {"type", "timestamp_ns"}}}); ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(value)); ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*metadata)); EXPECT_EQ(serialized, value); } +TEST(ViewMetadataJsonTest, DefersMissingReferencesUntilAccess) { + auto value = ValidMetadataJson(); + value["versions"][0]["schema-id"] = 99; + ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(value)); + EXPECT_THAT(metadata->CurrentVersion(), IsOk()); + EXPECT_THAT(metadata->CurrentSchema(), IsError(ErrorKind::kNotFound)); + EXPECT_THAT(metadata->SchemaById(99), IsError(ErrorKind::kNotFound)); + value["current-version-id"] = 99; + ICEBERG_UNWRAP_OR_FAIL(auto missing_version, ViewMetadataFromJson(value)); + EXPECT_THAT(missing_version->CurrentVersion(), IsError(ErrorKind::kNotFound)); + EXPECT_THAT(missing_version->CurrentSchema(), IsError(ErrorKind::kNotFound)); + EXPECT_THAT(missing_version->VersionById(99), IsError(ErrorKind::kNotFound)); +} + +TEST(ViewMetadataJsonTest, PreservesLegacyRepresentationsInStandaloneSerde) { + for (const auto& value : {json{{"type", "sql"}, {"sql", ""}, {"dialect", ""}}, + json{{"type", ""}, {"payload", "future"}}}) { + ICEBERG_UNWRAP_OR_FAIL(auto representation, ViewRepresentationFromJson(value)); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(representation)); + EXPECT_EQ(serialized, value); + } +} + +TEST(ViewMetadataJsonTest, RejectsRequiredUnknownFieldsAndDuplicateNames) { + auto value = ValidMetadataJson(); + value["schemas"][0]["fields"][0]["required"] = true; + value["schemas"][0]["fields"][0]["type"] = "unknown"; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kValidationFailed)); + value = ValidMetadataJson(); + value["schemas"][0]["fields"][1]["name"] = value["schemas"][0]["fields"][0]["name"]; + EXPECT_THAT(ViewMetadataFromJson(value), IsError(ErrorKind::kValidationFailed)); +} + +TEST(ViewMetadataJsonTest, UsesTypedPropertiesWithoutChangingStringMapRepresentation) { + ICEBERG_UNWRAP_OR_FAIL(auto metadata, ViewMetadataFromJson(ValidMetadataJson())); + auto properties = ViewProperties::FromMap(metadata->properties); + EXPECT_EQ(properties.Get(ViewProperties::kVersionHistorySize), 10); + EXPECT_EQ(properties.Get(ViewProperties::kMetadataCompression), "gzip"); + properties.Set(ViewProperties::kVersionHistorySize, 25); + properties.Set(ViewProperties::kReplaceDropDialectAllowed, true); + properties.mutable_configs()["custom.property"] = "preserved"; + metadata->properties = properties.configs(); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*metadata)); + EXPECT_EQ(serialized["properties"]["version.history.num-entries"], "25"); + EXPECT_EQ(serialized["properties"]["replace.drop-dialect.allowed"], "true"); + EXPECT_FALSE(serialized["properties"].contains("write.metadata.compression-codec")); + ICEBERG_UNWRAP_OR_FAIL(auto restored, ViewMetadataFromJson(serialized)); + const auto restored_properties = ViewProperties::FromMap(restored->properties); + EXPECT_EQ(restored_properties.Get(ViewProperties::kVersionHistorySize), 25); + EXPECT_TRUE(restored_properties.Get(ViewProperties::kReplaceDropDialectAllowed)); + EXPECT_EQ(restored_properties.configs().at("custom.property"), "preserved"); +} + TEST(ViewMetadataJsonTest, RejectsMalformedStringsAndExcessiveNesting) { for (const auto* text : {"", "{", "null", "[]", "{} trailing"}) { EXPECT_THAT(ViewMetadataFromJsonString(text), IsError(ErrorKind::kJsonParseError)); diff --git a/src/iceberg/test/view_properties_test.cc b/src/iceberg/test/view_properties_test.cc new file mode 100644 index 000000000..aaedf6bab --- /dev/null +++ b/src/iceberg/test/view_properties_test.cc @@ -0,0 +1,87 @@ +/* + * 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/view_properties.h" + +#include +#include + +#include + +#include "iceberg/exception.h" + +namespace iceberg { +namespace { + +TEST(ViewPropertiesTest, DefaultsDoNotPopulateThePropertyMap) { + const auto properties = ViewProperties::FromMap({}); + EXPECT_EQ(properties.Get(ViewProperties::kVersionHistorySize), 10); + EXPECT_FALSE(properties.Get(ViewProperties::kReplaceDropDialectAllowed)); + EXPECT_EQ(properties.Get(ViewProperties::kMetadataCompression), "gzip"); + EXPECT_EQ(properties.Get(ViewProperties::kWriteMetadataLocation), ""); + EXPECT_EQ(properties.Get(ViewProperties::kComment), ""); + EXPECT_TRUE(properties.configs().empty()); +} + +TEST(ViewPropertiesTest, ReadsTypedOverridesAndPreservesUnknownProperties) { + const std::unordered_map values{ + {"version.history.num-entries", "25"}, + {"replace.drop-dialect.allowed", "true"}, + {"write.metadata.compression-codec", "none"}, + {"write.metadata.path", "s3://bucket/view-metadata"}, + {"comment", "View description"}, + {"custom.property", "custom value"}}; + const auto properties = ViewProperties::FromMap(values); + EXPECT_EQ(properties.Get(ViewProperties::kVersionHistorySize), 25); + EXPECT_TRUE(properties.Get(ViewProperties::kReplaceDropDialectAllowed)); + EXPECT_EQ(properties.Get(ViewProperties::kMetadataCompression), "none"); + EXPECT_EQ(properties.Get(ViewProperties::kWriteMetadataLocation), + "s3://bucket/view-metadata"); + EXPECT_EQ(properties.Get(ViewProperties::kComment), "View description"); + EXPECT_EQ(properties.configs(), values); +} + +TEST(ViewPropertiesTest, TypedUpdatesUseStringValuesAndUnsetRestoresDefaults) { + auto properties = ViewProperties::FromMap({{"custom.property", "preserved"}}); + properties.Set(ViewProperties::kVersionHistorySize, 30); + properties.Set(ViewProperties::kReplaceDropDialectAllowed, true); + properties.Set(ViewProperties::kMetadataCompression, std::string("none")); + EXPECT_EQ(properties.configs().at("version.history.num-entries"), "30"); + EXPECT_EQ(properties.configs().at("replace.drop-dialect.allowed"), "true"); + EXPECT_EQ(properties.Get(ViewProperties::kMetadataCompression), "none"); + properties.Unset(ViewProperties::kVersionHistorySize); + EXPECT_EQ(properties.Get(ViewProperties::kVersionHistorySize), 10); + EXPECT_FALSE(properties.configs().contains("version.history.num-entries")); + EXPECT_EQ(properties.configs().at("custom.property"), "preserved"); + properties.Reset(); + EXPECT_TRUE(properties.configs().empty()); + EXPECT_FALSE(properties.Get(ViewProperties::kReplaceDropDialectAllowed)); +} + +TEST(ViewPropertiesTest, ReportsMalformedNumericValuesWhenConsumed) { + for (const auto* value : {"many", "2147483648"}) { + SCOPED_TRACE(value); + const auto properties = + ViewProperties::FromMap({{"version.history.num-entries", value}}); + EXPECT_THROW(properties.Get(ViewProperties::kVersionHistorySize), IcebergError); + } +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/view/json_serde.cc b/src/iceberg/view/json_serde.cc index be4940cbf..ca5e75d01 100644 --- a/src/iceberg/view/json_serde.cc +++ b/src/iceberg/view/json_serde.cc @@ -33,6 +33,7 @@ #include "iceberg/util/string_util.h" #include "iceberg/util/timepoint.h" #include "iceberg/view/json_serde_internal.h" +#include "iceberg/view/view_metadata_internal.h" namespace iceberg { namespace { @@ -102,17 +103,14 @@ bool IsSqlType(std::string_view type) { } Status ValidateRepresentation(const ViewRepresentation& representation) { - if (const auto* sql = GetSql(representation)) { - if (sql->sql.empty() || sql->dialect.empty()) { - return Invalid("SQL view representations require non-empty SQL and dialect"); - } - } else { - const auto& unknown = std::get(representation); - if (unknown.type.empty() || IsSqlType(unknown.type)) { - return Invalid("Unknown view representation must have a non-SQL type"); + if (const auto* unknown_ptr = std::get_if(&representation)) { + const auto& unknown = *unknown_ptr; + if (IsSqlType(unknown.type)) { + return ValidationFailed("Unknown view representation must have a non-SQL type"); } if (unknown.extra_fields.contains("type")) { - return Invalid("Unknown view representation fields must not contain 'type'"); + return ValidationFailed( + "Unknown view representation fields must not contain 'type'"); } } return {}; @@ -204,7 +202,7 @@ Result ViewHistoryEntryFromJson(const nlohmann::json& json) { } Result ToJson(const ViewMetadata& metadata) { - ICEBERG_RETURN_UNEXPECTED(metadata.Validate()); + ICEBERG_RETURN_UNEXPECTED(internal::ValidateViewMetadataForRead(metadata)); nlohmann::json schemas = nlohmann::json::array(); for (const auto& schema : metadata.schemas) { ICEBERG_ASSIGN_OR_RAISE(auto value, ToJson(*schema)); @@ -264,7 +262,7 @@ Result> ViewMetadataFromJson(const nlohmann::json& metadata->version_log.push_back(value); } ICEBERG_ASSIGN_OR_RAISE(metadata->properties, FromJsonMap(json, kProperties)); - ICEBERG_RETURN_UNEXPECTED(metadata->Validate()); + ICEBERG_RETURN_UNEXPECTED(internal::ValidateViewMetadataForRead(*metadata)); return metadata; } diff --git a/src/iceberg/view/json_serde_internal.h b/src/iceberg/view/json_serde_internal.h index 1a8a46ae6..416acd39f 100644 --- a/src/iceberg/view/json_serde_internal.h +++ b/src/iceberg/view/json_serde_internal.h @@ -45,12 +45,16 @@ ICEBERG_EXPORT nlohmann::json ToJson(const ViewHistoryEntry& entry); ICEBERG_EXPORT Result ViewHistoryEntryFromJson( const nlohmann::json& json); -/// \brief Validate and serialize view metadata. +/// \brief Serialize view metadata using the same structural checks as parsing. +/// Does not enforce the stricter ViewMetadata::Validate() creation checks. ICEBERG_EXPORT Result ToJson(const ViewMetadata& metadata); ICEBERG_EXPORT Result ToJsonString(const ViewMetadata& metadata); -/// \brief Parse structural JSON fields, then validate the complete metadata. -/// Structural errors return kJsonParseError; metadata invariants return kInvalid. +/// \brief Parse view metadata, checking supported format, schema structure and IDs. +/// Missing references and duplicate dialects are accepted for compatibility with +/// existing metadata. Use ViewMetadata::Validate() for strict creation checks. +/// Structural JSON errors return kJsonParseError; invalid schema structure and +/// duplicate IDs return kValidationFailed. ICEBERG_EXPORT Result> ViewMetadataFromJson( const nlohmann::json& json); diff --git a/src/iceberg/view/type_fwd.h b/src/iceberg/view/type_fwd.h index cafd0d041..f1f79cbb8 100644 --- a/src/iceberg/view/type_fwd.h +++ b/src/iceberg/view/type_fwd.h @@ -28,6 +28,7 @@ struct SqlViewRepresentation; struct UnknownViewRepresentation; struct ViewHistoryEntry; struct ViewMetadata; +class ViewProperties; struct ViewVersion; } // namespace iceberg diff --git a/src/iceberg/view/view_metadata.cc b/src/iceberg/view/view_metadata.cc index 43fb02bcf..e084b9acb 100644 --- a/src/iceberg/view/view_metadata.cc +++ b/src/iceberg/view/view_metadata.cc @@ -31,6 +31,7 @@ #include "iceberg/util/type_util.h" #include "iceberg/util/uuid.h" #include "iceberg/util/visit_type.h" +#include "iceberg/view/view_metadata_internal.h" namespace iceberg { @@ -55,25 +56,15 @@ Status ValidateViewSchema(const Schema& schema) { } // namespace -/// TODO(view): Current validation is much stricter than Java implementation. -Status ViewMetadata::Validate() const { - if (format_version != kSupportedViewFormatVersion) { +namespace internal { + +Status ValidateViewMetadataForRead(const ViewMetadata& metadata) { + if (metadata.format_version != ViewMetadata::kSupportedViewFormatVersion) { return ValidationFailed("Unsupported view format version: {}", - static_cast(format_version)); - } - if (auto uuid = Uuid::FromString(view_uuid); !uuid.has_value()) { - return ValidationFailed("Invalid view UUID '{}': {}", view_uuid, - uuid.error().message); - } - if (location.empty()) { - return ValidationFailed("View location must not be empty"); - } - if (schemas.empty()) { - return ValidationFailed("View metadata must list at least one schema"); + static_cast(metadata.format_version)); } - std::unordered_set schema_ids; - for (const auto& schema : schemas) { + for (const auto& schema : metadata.schemas) { if (schema == nullptr) { return ValidationFailed("View schemas must not be null"); } @@ -85,12 +76,8 @@ Status ViewMetadata::Validate() const { status.error().message); } } - - if (versions.empty()) { - return ValidationFailed("View metadata must list at least one version"); - } std::unordered_set version_ids; - for (const auto& version : versions) { + for (const auto& version : metadata.versions) { if (version == nullptr) { return ValidationFailed("View versions must not be null"); } @@ -98,6 +85,34 @@ Status ViewMetadata::Validate() const { return ValidationFailed("Duplicate view version ID: {}", version->version_id); } } + return {}; +} + +} // namespace internal + +Status ViewMetadata::Validate() const { + ICEBERG_RETURN_UNEXPECTED(internal::ValidateViewMetadataForRead(*this)); + if (auto uuid = Uuid::FromString(view_uuid); !uuid.has_value()) { + return ValidationFailed("Invalid view UUID '{}': {}", view_uuid, + uuid.error().message); + } + if (location.empty()) { + return ValidationFailed("View location must not be empty"); + } + if (schemas.empty()) { + return ValidationFailed("View metadata must list at least one schema"); + } + if (versions.empty()) { + return ValidationFailed("View metadata must list at least one version"); + } + std::unordered_set schema_ids; + for (const auto& schema : schemas) { + schema_ids.insert(schema->schema_id()); + } + std::unordered_set version_ids; + for (const auto& version : versions) { + version_ids.insert(version->version_id); + } if (!version_ids.contains(current_version_id)) { return ValidationFailed("Current version ID {} is not a listed view version", current_version_id); @@ -139,7 +154,8 @@ Status ViewMetadata::Validate() const { version->version_id); } if (unknown.extra_fields.contains("type")) { - return ValidationFailed("Unknown view representation fields must not contain 'type'"); + return ValidationFailed( + "Unknown view representation fields must not contain 'type'"); } if (StringUtils::EqualsIgnoreCase(unknown.type, kSqlRepresentationType)) { return ValidationFailed( diff --git a/src/iceberg/view/view_metadata.h b/src/iceberg/view/view_metadata.h index c8f1385a1..6dd0a890f 100644 --- a/src/iceberg/view/view_metadata.h +++ b/src/iceberg/view/view_metadata.h @@ -75,14 +75,16 @@ 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. + /// Use ViewProperties for typed access to known properties and their defaults. std::unordered_map properties; - /// \brief Validate view format v1 invariants. + /// \brief Validate view format v1 invariants for creation and updates. /// /// Checks referential integrity, schema structure, required fields, and /// uniqueness of SQL dialects. Never modifies the metadata. + /// JSON serde applies only structural checks so existing metadata with missing + /// references or duplicate SQL dialects can still be read and round-tripped. + /// Accessors report missing references when they are used. /// /// \return Status indicating success, or ErrorKind::kValidationFailed with /// the first violated invariant. diff --git a/src/iceberg/view/view_metadata_internal.h b/src/iceberg/view/view_metadata_internal.h new file mode 100644 index 000000000..98d8ecbd8 --- /dev/null +++ b/src/iceberg/view/view_metadata_internal.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 + +#include "iceberg/result.h" +#include "iceberg/view/type_fwd.h" + +namespace iceberg::internal { + +// Shared by parsing and serialization so existing metadata can round trip even +// when strict creation checks fail. Require supported format, valid schema +// structure, unique IDs and non-null entries. References, UUID/location values, +// non-empty lists and SQL dialect constraints belong to ViewMetadata::Validate(). +Status ValidateViewMetadataForRead(const ViewMetadata& metadata); + +} // namespace iceberg::internal diff --git a/src/iceberg/view/view_properties.cc b/src/iceberg/view/view_properties.cc new file mode 100644 index 000000000..3fc712d32 --- /dev/null +++ b/src/iceberg/view/view_properties.cc @@ -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. + */ + +#include "iceberg/view/view_properties.h" + +#include + +namespace iceberg { + +ViewProperties ViewProperties::FromMap( + std::unordered_map properties) { + ViewProperties view_properties; + view_properties.configs_ = std::move(properties); + return view_properties; +} + +} // namespace iceberg diff --git a/src/iceberg/view/view_properties.h b/src/iceberg/view/view_properties.h new file mode 100644 index 000000000..967c2a94c --- /dev/null +++ b/src/iceberg/view/view_properties.h @@ -0,0 +1,58 @@ +/* + * 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/view_properties.h +/// \brief Define typed view property helpers. + +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/util/config.h" + +namespace iceberg { + +/// \brief Properties for creating, replacing and updating Iceberg views. +/// Values remain strings in metadata; typed access uses the Iceberg defaults. +class ICEBERG_EXPORT ViewProperties : public ConfigBase { + public: + template + using Entry = const ConfigBase::Entry; + + /// Number of view versions to retain when expiring version history. + inline static Entry kVersionHistorySize{"version.history.num-entries", 10}; + /// Whether replacing a view may remove an existing SQL dialect. + inline static Entry kReplaceDropDialectAllowed{"replace.drop-dialect.allowed", + false}; + /// Compression codec for newly written view metadata files. + inline static Entry kMetadataCompression{ + "write.metadata.compression-codec", "gzip"}; + /// Override for metadata file locations; empty uses the view's metadata directory. + inline static Entry kWriteMetadataLocation{"write.metadata.path", ""}; + /// User-supplied view description. + inline static Entry kComment{"comment", ""}; + + /// \brief Create typed properties from a string map, retaining unknown keys. + static ViewProperties FromMap(std::unordered_map properties); +}; + +} // namespace iceberg From 0a8bcea5e8e89aff8e91ffc860f17e0f5ae913ec Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Tue, 1 Dec 2026 08:56:27 +0000 Subject: [PATCH 3/3] ci: retry view PR checks after dependency download failure