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
44 changes: 25 additions & 19 deletions src/iceberg/arrow/literal_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -166,29 +166,35 @@ Result<std::shared_ptr<::arrow::Scalar>> ToArrowScalar(const Literal& literal,
}
}

Result<std::shared_ptr<::arrow::Array>> MakeDefaultArray(
Result<std::shared_ptr<::arrow::Scalar>> ToArrowStorageScalar(
const Literal& literal, const std::shared_ptr<::arrow::DataType>& type,
int64_t num_rows, ::arrow::MemoryPool* pool) {
// An extension type (e.g. `arrow.uuid` for an Iceberg UUID) is backed by a storage
// type, and compute::Cast has no kernel that casts a storage array into an extension
// type. Materialize the array as the storage type and wrap it in the extension type.
if (type->id() == ::arrow::Type::EXTENSION) {
const auto& extension_type =
internal::checked_cast<const ::arrow::ExtensionType&>(*type);
ICEBERG_ASSIGN_OR_RAISE(
std::shared_ptr<::arrow::Array> storage,
MakeDefaultArray(literal, extension_type.storage_type(), num_rows, pool));
return ::arrow::ExtensionType::WrapArray(type, storage);
::arrow::MemoryPool* pool) {
const auto& storage_type =
type->id() == ::arrow::Type::EXTENSION
? internal::checked_cast<const ::arrow::ExtensionType&>(*type).storage_type()
: type;
if (literal.IsNull()) {
return ::arrow::MakeNullScalar(storage_type);
}
ICEBERG_ASSIGN_OR_RAISE(auto scalar, ToArrowScalar(literal, pool));
if (scalar->type->Equals(*storage_type)) {
return scalar;
}
::arrow::compute::ExecContext context(pool);
ICEBERG_ARROW_ASSIGN_OR_RETURN(
auto cast, ::arrow::compute::Cast(scalar, storage_type,
::arrow::compute::CastOptions::Safe(), &context));
return cast.scalar();
}

ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<::arrow::Scalar> scalar,
ToArrowScalar(literal, pool));
ICEBERG_ARROW_ASSIGN_OR_RETURN(std::shared_ptr<::arrow::Array> array,
Result<std::shared_ptr<::arrow::Array>> MakeDefaultArray(
const Literal& literal, const std::shared_ptr<::arrow::DataType>& type,
int64_t num_rows, ::arrow::MemoryPool* pool) {
ICEBERG_ASSIGN_OR_RAISE(auto scalar, ToArrowStorageScalar(literal, type, pool));
ICEBERG_ARROW_ASSIGN_OR_RETURN(auto array,
::arrow::MakeArrayFromScalar(*scalar, num_rows, pool));
if (!array->type()->Equals(*type)) {
ICEBERG_ARROW_ASSIGN_OR_RETURN(::arrow::Datum cast_result,
::arrow::compute::Cast(array, type));
return cast_result.make_array();
if (type->id() == ::arrow::Type::EXTENSION) {
return ::arrow::ExtensionType::WrapArray(type, array);
}
return array;
}
Expand Down
7 changes: 6 additions & 1 deletion src/iceberg/arrow/literal_util_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,15 @@ namespace iceberg::arrow {
Result<std::shared_ptr<::arrow::Scalar>> ToArrowScalar(const Literal& literal,
::arrow::MemoryPool* pool);

/// \brief Convert a literal to the requested Arrow type (storage type for extensions).
Result<std::shared_ptr<::arrow::Scalar>> ToArrowStorageScalar(
const Literal& literal, const std::shared_ptr<::arrow::DataType>& type,
::arrow::MemoryPool* pool);

/// \brief Create an Arrow array of `num_rows` rows where every row holds the literal
/// value, e.g. to materialize a missing column with a default value.
///
/// The array is cast to `type` when the literal's canonical Arrow type differs.
/// The literal is converted to `type` before it is repeated.
Result<std::shared_ptr<::arrow::Array>> MakeDefaultArray(
const Literal& literal, const std::shared_ptr<::arrow::DataType>& type,
int64_t num_rows, ::arrow::MemoryPool* pool);
Expand Down
42 changes: 12 additions & 30 deletions src/iceberg/avro/avro_data_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ Status AppendStructToBuilder(const ::avro::NodePtr& avro_node,
metadata_context, field_builder));
} else if (field_projection.kind == FieldProjection::Kind::kNull) {
ICEBERG_ARROW_RETURN_NOT_OK(field_builder->AppendNull());
} else if (field_projection.kind == FieldProjection::Kind::kDefault) {
} else if (field_projection.kind == FieldProjection::Kind::kDefault ||
field_projection.kind == FieldProjection::Kind::kConstant) {
ICEBERG_RETURN_UNEXPECTED(AppendDefaultToBuilder(field_projection, field_builder));
} else if (field_projection.kind == FieldProjection::Kind::kMetadata) {
int32_t field_id = expected_field.field_id();
Expand Down Expand Up @@ -477,7 +478,8 @@ Status AppendFieldToBuilder(const ::avro::NodePtr& avro_node,
return {};
}

if (projection.kind == FieldProjection::Kind::kDefault) {
if (projection.kind == FieldProjection::Kind::kDefault ||
projection.kind == FieldProjection::Kind::kConstant) {
return AppendDefaultToBuilder(projection, array_builder);
}

Expand Down Expand Up @@ -514,29 +516,6 @@ Status AppendFieldToBuilder(const ::avro::NodePtr& avro_node,

namespace {

Result<std::shared_ptr<::arrow::Scalar>> MakeDefaultScalar(
const Literal& literal, const std::shared_ptr<::arrow::DataType>& builder_type) {
// The builder's own memory pool is not exposed, so the small scalar buffer uses the
// default pool.
ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<::arrow::Scalar> scalar,
arrow::ToArrowScalar(literal, ::arrow::default_memory_pool()));

// For an extension builder (e.g. `arrow.uuid`) target its storage type: ToArrowScalar
// yields the storage scalar (fixed_size_binary(16) for uuid) and Scalar::CastTo has no
// kernel that targets an extension type. This mirrors MakeDefaultArray's extension
// handling.
std::shared_ptr<::arrow::DataType> target_type = builder_type;
if (target_type->id() == ::arrow::Type::EXTENSION) {
target_type = internal::checked_cast<const ::arrow::ExtensionType&>(*target_type)
.storage_type();
}

if (!scalar->type->Equals(*target_type)) {
ICEBERG_ARROW_ASSIGN_OR_RETURN(scalar, scalar->CastTo(target_type));
}
return scalar;
}

Status PrepareStructDefaultScalars(std::span<FieldProjection> projections,
::arrow::ArrayBuilder* builder);

Expand Down Expand Up @@ -594,7 +573,8 @@ Status PrepareStructDefaultScalars(std::span<FieldProjection> projections,
auto& field_projection = projections[i];
auto* field_builder = struct_builder->field_builder(static_cast<int>(i));

if (field_projection.kind == FieldProjection::Kind::kDefault) {
if (field_projection.kind == FieldProjection::Kind::kDefault ||
field_projection.kind == FieldProjection::Kind::kConstant) {
Comment thread
wgtmac marked this conversation as resolved.
Resolved
// Get-or-create the single Avro attributes container: another Avro attribute may
// have created it already, so guard on `default_scalar` being unset rather than on
// the container's presence (otherwise a pre-existing container would skip
Expand All @@ -613,8 +593,9 @@ Status PrepareStructDefaultScalars(std::span<FieldProjection> projections,
if (attrs->default_scalar == nullptr) {
ICEBERG_ASSIGN_OR_RAISE(
attrs->default_scalar,
MakeDefaultScalar(std::get<Literal>(field_projection.from),
field_builder->type()));
arrow::ToArrowStorageScalar(std::get<Literal>(field_projection.from),
field_builder->type(),
::arrow::default_memory_pool()));
}
continue;
}
Expand All @@ -633,8 +614,9 @@ Status PrepareDefaultScalars(SchemaProjection& projection,
}

Status AppendDefaultToBuilder(const Literal& literal, ::arrow::ArrayBuilder* builder) {
ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<::arrow::Scalar> scalar,
MakeDefaultScalar(literal, builder->type()));
ICEBERG_ASSIGN_OR_RAISE(auto scalar,
arrow::ToArrowStorageScalar(literal, builder->type(),
::arrow::default_memory_pool()));
ICEBERG_ARROW_RETURN_NOT_OK(builder->AppendScalar(*scalar));
return {};
}
Expand Down
3 changes: 2 additions & 1 deletion src/iceberg/avro/avro_direct_decoder.cc
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,8 @@ Status DecodeStructToBuilder(const ::avro::NodePtr& avro_node, ::avro::Decoder&
auto* field_builder = struct_builder->field_builder(static_cast<int>(proj_idx));
if (field_projection.kind == FieldProjection::Kind::kNull) {
ICEBERG_ARROW_RETURN_NOT_OK(field_builder->AppendNull());
} else if (field_projection.kind == FieldProjection::Kind::kDefault) {
} else if (field_projection.kind == FieldProjection::Kind::kDefault ||
field_projection.kind == FieldProjection::Kind::kConstant) {
ICEBERG_RETURN_UNEXPECTED(AppendDefaultToBuilder(field_projection, field_builder));
} else if (field_projection.kind == FieldProjection::Kind::kMetadata) {
int32_t field_id = expected_field.field_id();
Expand Down
18 changes: 10 additions & 8 deletions src/iceberg/avro/avro_reader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,10 @@ class AvroReader::Impl {
}

// Project the read schema on top of the file schema.
ICEBERG_ASSIGN_OR_RAISE(projection_, Project(*read_schema_, file_schema.root(),
/*prune_source=*/false));
ICEBERG_ASSIGN_OR_RAISE(projection_,
Project(*read_schema_, file_schema.root(),
/*prune_source=*/false, options.id_to_constant,
/*ids_from_name_mapping=*/has_id_visitor.HasNoIds()));

ICEBERG_RETURN_UNEXPECTED(backend_->InitWithSchema(file_schema, options.split));

Expand Down Expand Up @@ -434,7 +436,7 @@ class AvroReader::Impl {

private:
Status InitReadContext() {
context_ = std::make_unique<ReadContext>();
auto context = std::make_unique<ReadContext>();

ArrowSchema arrow_schema;
ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*read_schema_, &arrow_schema));
Expand All @@ -443,21 +445,21 @@ class AvroReader::Impl {
return InvalidSchema("Failed to import the arrow schema: {}",
import_result.status().message());
}
context_->arrow_schema_ = import_result.MoveValueUnsafe();
context->arrow_schema_ = import_result.MoveValueUnsafe();

auto arrow_struct_type =
internal::checked_pointer_cast<::arrow::StructType>(StorageTypeForBuilder(
std::make_shared<::arrow::StructType>(context_->arrow_schema_->fields())));
std::make_shared<::arrow::StructType>(context->arrow_schema_->fields())));
auto builder_result = ::arrow::MakeBuilder(arrow_struct_type);
if (!builder_result.ok()) {
return InvalidSchema("Failed to make the arrow builder: {}",
builder_result.status().message());
}
context_->builder_ = builder_result.MoveValueUnsafe();
context->builder_ = builder_result.MoveValueUnsafe();
ICEBERG_RETURN_UNEXPECTED(
PrepareDefaultScalars(projection_, context_->builder_.get()));
PrepareDefaultScalars(projection_, context->builder_.get()));
backend_->InitReadContext(backend_->GetReaderSchema());

context_ = std::move(context);
return {};
}

Expand Down
69 changes: 45 additions & 24 deletions src/iceberg/avro/avro_schema_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -683,14 +683,21 @@ Status UnwrapUnion(const ::avro::NodePtr& node, ::avro::NodePtr* result) {
return {};
}

struct ProjectionOptions {
bool prune_source;
bool ids_from_name_mapping;
const std::unordered_map<int32_t, Literal>& id_to_constant;
};

// Forward declaration
Result<FieldProjection> ProjectNested(const Type& expected_type,
const ::avro::NodePtr& avro_node,
bool prune_source);
const ProjectionOptions& options);

Result<FieldProjection> ProjectField(const SchemaField& expected_field,
const ::avro::NodePtr& avro_node,
size_t source_index, bool prune_source) {
size_t source_index,
const ProjectionOptions& options) {
const Type& expected_type = *expected_field.type();
::avro::NodePtr field_node;
ICEBERG_RETURN_UNEXPECTED(UnwrapUnion(avro_node, &field_node));
Expand All @@ -708,7 +715,7 @@ Result<FieldProjection> ProjectField(const SchemaField& expected_field,

if (expected_type.is_nested()) {
ICEBERG_ASSIGN_OR_RAISE(projection,
ProjectNested(expected_type, field_node, prune_source));
ProjectNested(expected_type, field_node, options));
} else {
ICEBERG_RETURN_UNEXPECTED(ValidateAvroSchemaEvolution(expected_type, field_node));
}
Expand All @@ -719,7 +726,7 @@ Result<FieldProjection> ProjectField(const SchemaField& expected_field,

Result<FieldProjection> ProjectStruct(const StructType& struct_type,
const ::avro::NodePtr& avro_node,
bool prune_source) {
const ProjectionOptions& options) {
if (avro_node->type() != ::avro::AVRO_RECORD) {
return InvalidSchema("Expected AVRO_RECORD type, but got {}", ToString(avro_node));
}
Expand All @@ -735,6 +742,10 @@ Result<FieldProjection> ProjectStruct(const StructType& struct_type,

for (size_t i = 0; i < avro_node->leaves(); ++i) {
ICEBERG_ASSIGN_OR_RAISE(int32_t field_id, GetFieldId(avro_node, i));
// A partition value takes precedence over a field ID supplied by name mapping.
if (options.ids_from_name_mapping && options.id_to_constant.contains(field_id)) {
continue;
}
::avro::NodePtr field_node = avro_node->leafAt(i);
if (const auto [iter, inserted] = node_info_map.emplace(
std::piecewise_construct, std::forward_as_tuple(field_id),
Expand All @@ -744,17 +755,21 @@ Result<FieldProjection> ProjectStruct(const StructType& struct_type,
}
}

FieldProjection result;
FieldProjection result{.kind = FieldProjection::Kind::kProjected};
result.children.reserve(expected_fields.size());

for (const auto& expected_field : expected_fields) {
int32_t field_id = expected_field.field_id();
FieldProjection child_projection;

if (auto iter = node_info_map.find(field_id); iter != node_info_map.cend()) {
if (auto source = node_info_map.find(field_id); source != node_info_map.end()) {
ICEBERG_ASSIGN_OR_RAISE(child_projection,
ProjectField(expected_field, iter->second.field_node,
iter->second.local_index, prune_source));
ProjectField(expected_field, source->second.field_node,
source->second.local_index, options));
} else if (auto constant = options.id_to_constant.find(field_id);
constant != options.id_to_constant.end()) {
child_projection.kind = FieldProjection::Kind::kConstant;
child_projection.from = constant->second;
} else if (MetadataColumns::IsMetadataColumn(field_id)) {
child_projection.kind = FieldProjection::Kind::kMetadata;
} else if (expected_field.initial_default() != nullptr) {
Expand All @@ -770,15 +785,16 @@ Result<FieldProjection> ProjectStruct(const StructType& struct_type,
result.children.emplace_back(std::move(child_projection));
}

if (prune_source) {
if (options.prune_source) {
PruneFieldProjection(result);
}

return result;
}

Result<FieldProjection> ProjectList(const ListType& list_type,
const ::avro::NodePtr& avro_node, bool prune_source) {
const ::avro::NodePtr& avro_node,
const ProjectionOptions& options) {
if (avro_node->type() != ::avro::AVRO_ARRAY) {
return InvalidSchema("Expected AVRO_ARRAY type, but got {}", ToString(avro_node));
}
Expand All @@ -797,19 +813,20 @@ Result<FieldProjection> ProjectList(const ListType& list_type,
FieldProjection element_projection;
ICEBERG_ASSIGN_OR_RAISE(element_projection,
ProjectField(expected_element_field, avro_node->leafAt(0),
/*source_index*/ size_t{0}, prune_source));
/*source_index*/ size_t{0}, options));

FieldProjection result;
FieldProjection result{.kind = FieldProjection::Kind::kProjected};
result.children.emplace_back(std::move(element_projection));
return result;
}

Result<FieldProjection> ProjectMap(const MapType& map_type,
const ::avro::NodePtr& avro_node, bool prune_source) {
const ::avro::NodePtr& avro_node,
const ProjectionOptions& options) {
const auto& expected_key_field = map_type.key();
const auto& expected_value_field = map_type.value();

FieldProjection result;
FieldProjection result{.kind = FieldProjection::Kind::kProjected};
int32_t avro_key_id;
int32_t avro_value_id;
::avro::NodePtr map_node;
Expand Down Expand Up @@ -856,7 +873,7 @@ Result<FieldProjection> ProjectMap(const MapType& map_type,
const auto& expected_sub_field = map_type.fields()[i];
ICEBERG_ASSIGN_OR_RAISE(
sub_projection,
ProjectField(expected_sub_field, map_node->leafAt(i), i, prune_source));
ProjectField(expected_sub_field, map_node->leafAt(i), i, options));
result.children.emplace_back(std::move(sub_projection));
}

Expand All @@ -865,21 +882,21 @@ Result<FieldProjection> ProjectMap(const MapType& map_type,

Result<FieldProjection> ProjectNested(const Type& expected_type,
const ::avro::NodePtr& avro_node,
bool prune_source) {
const ProjectionOptions& options) {
if (!expected_type.is_nested()) {
return InvalidSchema("Expected a nested type, but got {}", expected_type);
}

switch (expected_type.type_id()) {
case TypeId::kStruct:
return ProjectStruct(internal::checked_cast<const StructType&>(expected_type),
avro_node, prune_source);
avro_node, options);
case TypeId::kList:
return ProjectList(internal::checked_cast<const ListType&>(expected_type),
avro_node, prune_source);
avro_node, options);
case TypeId::kMap:
return ProjectMap(internal::checked_cast<const MapType&>(expected_type), avro_node,
prune_source);
options);
default:
return InvalidSchema("Unsupported nested type: {}", expected_type);
}
Expand All @@ -893,11 +910,15 @@ bool HasMapLogicalType(const ::avro::NodePtr& node) {
node->logicalType().customLogicalType()->name() == "map";
}

Result<SchemaProjection> Project(const Schema& expected_schema,
const ::avro::NodePtr& avro_node, bool prune_source) {
ICEBERG_ASSIGN_OR_RAISE(
auto field_projection,
ProjectNested(static_cast<const Type&>(expected_schema), avro_node, prune_source));
Result<SchemaProjection> Project(
const Schema& expected_schema, const ::avro::NodePtr& avro_node, bool prune_source,
const std::unordered_map<int32_t, Literal>& id_to_constant,
bool ids_from_name_mapping) {
const ProjectionOptions options{.prune_source = prune_source,
.ids_from_name_mapping = ids_from_name_mapping,
.id_to_constant = id_to_constant};
ICEBERG_ASSIGN_OR_RAISE(auto field_projection,
ProjectNested(expected_schema, avro_node, options));
return SchemaProjection{std::move(field_projection.children)};
}

Expand Down
Loading
Loading