Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Core/FormatFactorySettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -1742,6 +1742,22 @@ Use geo column parser to convert Array(UInt8) into Point/MultiPoint/Linestring/P
)", 0) \
DECLARE(Bool, input_format_parquet_detect_variant_by_structure, true, R"(
Read a Parquet group that has no `VARIANT` logical type, but has the layout of an unshredded variant (a `metadata` and a `value` field of type `BYTE_ARRAY`), as a variant, i.e. as `Dynamic`, instead of `Tuple`. Spark 4.0 writes variant columns this way. Groups annotated with the `VARIANT` logical type are always read as a variant.
)", 0) \
DECLARE(Bool, allow_aggregate_function_states_in_open_formats, false, R"(
Apply the ClickHouse types recorded in Parquet files and Iceberg tables, and allow writing `AggregateFunction` states to
them. A state is stored as binary, with its ClickHouse type recorded in `clickhouse.column_types` (Parquet file metadata)
or `clickhouse.type.<field-id>.<schema-id>` (Iceberg table properties). The recorded type chooses the deserializer for
the stored bytes, so enable the setting only for trusted sources.

When disabled, the recorded types are not applied, so a `SimpleAggregateFunction(f, T)` column is `T` and a state column
reads as `String`. Writing an `AggregateFunction` column throws `SUPPORT_IS_DISABLED`. `SimpleAggregateFunction` types are
recorded on write either way.

A table (for example with the `S3`, `File` or `IcebergS3` engine) takes the value from the `SETTINGS` clause of its
engine, or the server's value (from the server settings profile) without one. The query's value does not apply to a
table, only to a table function.
More [in Parquet](/reference/formats/Parquet/Parquet#aggregate-function-states) and
[in Iceberg](/reference/engines/table-engines/integrations/iceberg#aggregate-function-states).
)", 0) \
DECLARE(Bool, output_format_parquet_geometadata, true, R"(
Allow to write information about geo columns in parquet metadata and encode columns in WKB format.
Expand Down
1 change: 1 addition & 0 deletions src/Core/SettingsChangesHistory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory()
});
addSettingsChanges(settings_changes_history, "26.8.39.20001.altinityantalya",
{
{"allow_aggregate_function_states_in_open_formats", false, false, "New setting allowing aggregate function states in Parquet files and Iceberg tables. With it disabled, the ClickHouse types recorded in them are not applied, a state column reads as `String`, and writing a state throws `SUPPORT_IS_DISABLED`."},
{"export_merge_tree_part_check_destination_schema_staleness_ms", 0, 5000, "New setting: how stale the latest Iceberg destination metadata version may be when each part export task checks that the destination schema and partition spec did not change since the export was scheduled."},
{"export_merge_tree_part_allow_lossy_cast", false, false, "The setting is obsolete. `EXPORT PART` and `EXPORT PARTITION` cast values the way `INSERT ... SELECT` does."},
});
Expand Down
26 changes: 24 additions & 2 deletions src/DataTypes/DataTypeAggregateFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -534,12 +534,16 @@ combinator.
});
}

bool hasAggregateFunctionType(const DataTypePtr & type)
namespace
{

template <typename Predicate>
bool hasTypeMatching(const DataTypePtr & type, Predicate && predicate)
{
auto result = false;
auto check = [&](const IDataType & t)
{
result |= WhichDataType(t).isAggregateFunction();
result |= predicate(t);
};

check(*type);
Expand All @@ -548,3 +552,21 @@ bool hasAggregateFunctionType(const DataTypePtr & type)
}

}

bool hasAggregateFunctionType(const DataTypePtr & type)
{
return hasTypeMatching(type, [](const IDataType & t) { return WhichDataType(t).isAggregateFunction(); });
}

bool hasAggregateFunctionOrSimpleAggregateFunctionType(const DataTypePtr & type)
{
return hasTypeMatching(
type,
[](const IDataType & t)
{
return WhichDataType(t).isAggregateFunction()
|| typeid_cast<const DataTypeCustomSimpleAggregateFunction *>(t.getCustomName()) != nullptr;
});
}

}
3 changes: 3 additions & 0 deletions src/DataTypes/DataTypeAggregateFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,7 @@ void pinCurrentStateVersionToAggregateFunctions(DataTypePtr & type);
/// Checks type of any nested type is DataTypeAggregateFunction.
bool hasAggregateFunctionType(const DataTypePtr & type);

/// Checks type or any nested type is `AggregateFunction` or `SimpleAggregateFunction`.
bool hasAggregateFunctionOrSimpleAggregateFunctionType(const DataTypePtr & type);

}
7 changes: 6 additions & 1 deletion src/Databases/DataLake/GlueCatalog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ namespace DB::FailPoints
namespace DB::Setting
{
extern const SettingsBool allow_experimental_geo_types_in_iceberg;
extern const SettingsBool allow_aggregate_function_states_in_open_formats;
extern const SettingsUInt64 s3_max_connections;
extern const SettingsUInt64 s3_max_redirects;
extern const SettingsUInt64 s3_retry_attempts;
Expand Down Expand Up @@ -724,7 +725,10 @@ bool GlueCatalog::tryGetTableMetadata(
auto metadata_object = getOrFetchMetadataObject(client, table_specific_properties->iceberg_metadata_file_location, result);
const bool allow_geo_parser
= getContext()->getSettingsRef()[DB::Setting::allow_experimental_geo_types_in_iceberg].value;
auto schema_processor = DB::Iceberg::IcebergSchemaProcessor(context_, allow_geo_parser);
auto schema_processor = DB::Iceberg::IcebergSchemaProcessor(
context_,
allow_geo_parser,
context_->getSettingsRef()[DB::Setting::allow_aggregate_function_states_in_open_formats].value);
auto id = DB::IcebergMetadata::parseTableSchema(metadata_object, schema_processor, context_, log);
auto parsed_schema = schema_processor.getClickHouseTableSchemaById(id);
if (parsed_schema)
Expand Down Expand Up @@ -1345,6 +1349,7 @@ bool GlueCatalog::updateSchema(
Int32 /*previous_schema_id*/,
Int32 /*new_last_column_id*/,
Poco::JSON::Object::Ptr /*metadata*/,
Poco::JSON::Object::Ptr /*previous_properties*/,
const DB::ForwardedAuthTokenPtr & auth_token) const
{
std::vector<Aws::Glue::Model::Column> columns;
Expand Down
1 change: 1 addition & 0 deletions src/Databases/DataLake/GlueCatalog.h
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ class GlueCatalog final : public ICatalog, private DB::WithContext
Int32 previous_schema_id,
Int32 new_last_column_id,
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr previous_properties,
const DB::ForwardedAuthTokenPtr & auth_token) const override;

void dropTable(
Expand Down
1 change: 1 addition & 0 deletions src/Databases/DataLake/ICatalog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@ bool ICatalog::updateSchema(
Int32 /*previous_schema_id*/,
Int32 /*new_last_column_id*/,
Poco::JSON::Object::Ptr /*metadata*/,
Poco::JSON::Object::Ptr /*previous_properties*/,
const DB::ForwardedAuthTokenPtr & /*auth_token*/) const
{
throw DB::Exception(DB::ErrorCodes::NOT_IMPLEMENTED, "updateSchema is not implemented");
Expand Down
2 changes: 2 additions & 0 deletions src/Databases/DataLake/ICatalog.h
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ class ICatalog
/// `new_schema` is the full new schema object and `previous_schema_id` is the schema id that the
/// catalog is expected to currently have - used to build the optimistic-concurrency requirement
/// (`assert-current-schema-id`) on transactional catalogs (e.g. Iceberg REST).
/// `previous_properties` are the table properties before the change.
/// Returns `false` on a recoverable conflict so the caller can retry, throws otherwise.
virtual bool updateSchema(
const String & namespace_name,
Expand All @@ -374,6 +375,7 @@ class ICatalog
Int32 previous_schema_id,
Int32 new_last_column_id,
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr previous_properties,
const DB::ForwardedAuthTokenPtr & auth_token) const;

/// Drop table from catalog.
Expand Down
94 changes: 88 additions & 6 deletions src/Databases/DataLake/RestCatalog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ namespace DB::ErrorCodes
namespace DB::Setting
{
extern const SettingsBool allow_experimental_geo_types_in_iceberg;
extern const SettingsBool allow_aggregate_function_states_in_open_formats;
}

namespace DB::FailPoints
Expand Down Expand Up @@ -356,7 +357,8 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody(
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr new_schema,
Int32 previous_schema_id,
Int32 new_last_column_id)
Int32 new_last_column_id,
Poco::JSON::Object::Ptr previous_properties)
{
Poco::JSON::Object::Ptr request_body = new Poco::JSON::Object;
{
Expand Down Expand Up @@ -384,11 +386,14 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody(
schema_for_rest->set(IDENTIFIER_FIELD_IDS, empty_identifier_field_ids);
}

const auto new_schema_id = new_schema->getValue<Int32>(DB::Iceberg::f_schema_id);
/// The change keeps the current schema and touches only the table properties.
const bool schema_unchanged = new_schema_id == previous_schema_id;

std::optional<Int32> existing_equivalent_schema_id;
if (metadata && metadata->has(DB::Iceberg::f_schemas))
if (!schema_unchanged && metadata && metadata->has(DB::Iceberg::f_schemas))
{
auto schemas = metadata->getArray(DB::Iceberg::f_schemas);
auto new_schema_id = new_schema->getValue<Int32>(DB::Iceberg::f_schema_id);
for (UInt32 i = 0; i < schemas->size(); ++i)
{
auto existing_schema = schemas->getObject(i);
Expand All @@ -402,6 +407,36 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody(
}
}

/// The catalog keeps the id of the equivalent schema, so the ClickHouse type annotations recorded for the new id

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure I understand what this means, can you clarify?

/// are not sent and the ones in effect for the equivalent schema must already be the same.
std::unordered_set<String> skipped_properties;
if (existing_equivalent_schema_id.has_value())
{
const auto fields = DB::Iceberg::IcebergSchemaProcessor::traverseSchema(new_schema->getArray(DB::Iceberg::f_fields));
const auto existing_annotations = DB::Iceberg::getClickHouseTypeAnnotations(metadata, *existing_equivalent_schema_id);
const auto new_annotations = DB::Iceberg::getClickHouseTypeAnnotations(metadata, new_schema_id);
for (const auto & [name, field_id] : fields)
{
const auto existing_it = existing_annotations.find(static_cast<Int32>(field_id));
const auto new_it = new_annotations.find(static_cast<Int32>(field_id));
const String existing_annotation = existing_it == existing_annotations.end() ? String{} : existing_it->second.type_name;
const String new_annotation = new_it == new_annotations.end() ? String{} : new_it->second.type_name;
if (existing_annotation != new_annotation)
throw DB::Exception(
DB::ErrorCodes::NOT_IMPLEMENTED,
"Cannot commit schema {} of table {}.{}: the catalog reuses the equivalent schema {} for it, "
"where column '{}' has ClickHouse type annotation '{}' instead of '{}'",
new_schema_id,
namespace_name,
table_name,
*existing_equivalent_schema_id,
name,
existing_annotation,
new_annotation);
skipped_properties.insert(DB::Iceberg::getClickHouseTypePropertyKey(static_cast<Int32>(field_id), new_schema_id));
}
}

Poco::JSON::Array::Ptr updates = new Poco::JSON::Array;
if (existing_equivalent_schema_id.has_value())
{
Expand All @@ -410,7 +445,7 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody(
set_current_schema->set("schema-id", *existing_equivalent_schema_id);
updates->add(set_current_schema);
}
else
else if (!schema_unchanged)
Comment thread
zvonand marked this conversation as resolved.
Resolved
{
{
Poco::JSON::Object::Ptr add_schema = new Poco::JSON::Object;
Expand All @@ -427,6 +462,45 @@ Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody(
}
}

if (previous_properties && metadata)
{
Poco::JSON::Object::Ptr properties
= metadata->has(DB::Iceberg::f_properties) ? metadata->getObject(DB::Iceberg::f_properties) : nullptr;

Poco::JSON::Object::Ptr changed = new Poco::JSON::Object;
if (properties)
{
for (const auto & [key, value] : *properties)
{
if (skipped_properties.contains(key))
continue;
if (!previous_properties->has(key) || previous_properties->get(key).toString() != value.toString())
changed->set(key, value);
}
}
if (changed->size() > 0)
{
Poco::JSON::Object::Ptr set_properties = new Poco::JSON::Object;
set_properties->set("action", "set-properties");
set_properties->set("updates", changed);
updates->add(set_properties);
}

Poco::JSON::Array::Ptr removed = new Poco::JSON::Array;
for (const auto & [key, value] : *previous_properties)
{
if (!properties || !properties->has(key))
removed->add(key);
}
if (removed->size() > 0)
{
Poco::JSON::Object::Ptr remove_properties = new Poco::JSON::Object;
remove_properties->set("action", "remove-properties");
remove_properties->set("removals", removed);
updates->add(remove_properties);
}
}

request_body->set("updates", updates);
return request_body;
}
Expand Down Expand Up @@ -2490,7 +2564,8 @@ bool RestCatalog::getTableMetadataImpl(
{
const bool allow_geo_parser
= getContext()->getSettingsRef()[DB::Setting::allow_experimental_geo_types_in_iceberg].value;
auto schema_processor = DB::Iceberg::IcebergSchemaProcessor(context_, allow_geo_parser);
auto schema_processor = DB::Iceberg::IcebergSchemaProcessor(
context_, allow_geo_parser, context_->getSettingsRef()[DB::Setting::allow_aggregate_function_states_in_open_formats].value);
auto id = DB::IcebergMetadata::parseTableSchema(metadata_object, schema_processor, context_, log);
auto schema = schema_processor.getClickHouseTableSchemaById(id);
result.setSchema(*schema);
Expand Down Expand Up @@ -2746,6 +2821,12 @@ bool RestCatalog::createTable(
if (metadata_content->has("format-version"))
properties->set("format-version", std::to_string(metadata_content->getValue<int>("format-version")));

if (metadata_content->has(DB::Iceberg::f_properties))
{
for (const auto & [key, value] : *metadata_content->getObject(DB::Iceberg::f_properties))
properties->set(key, value);
}

request_body->set("properties", properties);

try
Expand Down Expand Up @@ -2846,6 +2927,7 @@ bool RestCatalog::updateSchema(
Int32 previous_schema_id,
Int32 new_last_column_id,
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr previous_properties,
const DB::ForwardedAuthTokenPtr & auth_token) const
{
fiu_do_on(DB::FailPoints::iceberg_alter_catalog_update_schema_fail, { return false; });
Expand All @@ -2856,7 +2938,7 @@ bool RestCatalog::updateSchema(
const std::string endpoint = (base_url / state_snapshot->config.prefix / NAMESPACES_ENDPOINT / encodeNamespaceForURI(namespace_name) / "tables" / table_name).generic_string();

auto request_body = buildUpdateSchemaRequestBody(
namespace_name, table_name, metadata, new_schema, previous_schema_id, new_last_column_id);
namespace_name, table_name, metadata, new_schema, previous_schema_id, new_last_column_id, previous_properties);

try
{
Expand Down
7 changes: 5 additions & 2 deletions src/Databases/DataLake/RestCatalog.h
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ class RestCatalog : public ICatalog, public DB::WithContext
Int32 previous_schema_id,
Int32 new_last_column_id,
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr previous_properties,
const DB::ForwardedAuthTokenPtr & auth_token) const override;

bool isTransactional() const override { return true; }
Expand Down Expand Up @@ -608,14 +609,16 @@ class HorizonCatalog : public RestCatalog
/// Builds the JSON body for a schema-update commit via the Iceberg REST catalog.
/// Includes an assert-current-schema-id requirement (when previous_schema_id >= 0),
/// schema deduplication against existing schemas in metadata, and last-column-id
/// propagation when adding a new schema.
/// propagation when adding a new schema, and property changes since `previous_properties`.
/// No schema update is sent when `new_schema` is the schema `previous_schema_id`.
Poco::JSON::Object::Ptr buildUpdateSchemaRequestBody(
const String & namespace_name,
const String & table_name,
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr new_schema,
Int32 previous_schema_id,
Int32 new_last_column_id);
Int32 new_last_column_id,
Poco::JSON::Object::Ptr previous_properties = nullptr);

/// Builds the JSON body that commits `new_snapshot` (and sets `properties_to_set` in the same commit)
/// via the Iceberg REST catalog.
Expand Down
4 changes: 3 additions & 1 deletion src/Databases/DataLake/UnityV2Catalog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -462,12 +462,14 @@ bool UnityV2Catalog::updateSchema(
Int32 previous_schema_id,
Int32 new_last_column_id,
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr previous_properties,
const DB::ForwardedAuthTokenPtr & auth_token) const
{
return requestWithRetry([&](bool force_refresh)
{
return getIcebergRestCatalog(force_refresh)->updateSchema(
namespace_name, table_name, new_metadata_path, new_schema, previous_schema_id, new_last_column_id, metadata, auth_token);
namespace_name, table_name, new_metadata_path, new_schema, previous_schema_id, new_last_column_id, metadata,
previous_properties, auth_token);
});
}

Expand Down
1 change: 1 addition & 0 deletions src/Databases/DataLake/UnityV2Catalog.h
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ class UnityV2Catalog final : public ICatalog, private DB::WithContext
Int32 previous_schema_id,
Int32 new_last_column_id,
Poco::JSON::Object::Ptr metadata,
Poco::JSON::Object::Ptr previous_properties,
const DB::ForwardedAuthTokenPtr & auth_token) const override;

private:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,28 @@ TEST(RestCatalogUpdateSchemaBody, NonEmptyIdentifierFieldIdsPreventDeduplication
EXPECT_EQ(set_schema->getValue<Int32>("schema-id"), -1);
}

TEST(RestCatalogUpdateSchemaBody, UnchangedSchemaSendsOnlyThePropertyChanges)
{
/// A `MODIFY COLUMN` that changes only the ClickHouse type annotation keeps the current schema.
auto schema = makeSingleColumnSchema(0, std::nullopt);
auto metadata = makeMetadataWithSchemas({schema});
Poco::JSON::Object::Ptr properties = new Poco::JSON::Object;
properties->set("clickhouse.type.1.0", "SimpleAggregateFunction(max, Int32)");
metadata->set(Iceberg::f_properties, properties);
Poco::JSON::Object::Ptr previous_properties = new Poco::JSON::Object;
previous_properties->set("clickhouse.type.1.0", "SimpleAggregateFunction(sum, Int32)");

auto body = DataLake::buildUpdateSchemaRequestBody("ns", "t", metadata, schema, 0, 1, previous_properties);
ASSERT_TRUE(body);

auto updates = body->getArray("updates");
ASSERT_EQ(updates->size(), 1u);
auto set_properties = findUpdateByAction(updates, "set-properties");
ASSERT_TRUE(set_properties);
EXPECT_EQ(
set_properties->getObject("updates")->getValue<std::string>("clickhouse.type.1.0"), "SimpleAggregateFunction(max, Int32)");
}

TEST(RestCatalogUpdateSchemaBody, NormalPathEmitsAddSchema)
{
Poco::JSON::Object::Ptr metadata = new Poco::JSON::Object;
Expand Down
Loading
Loading