jvanstraten commented on a change in pull request #12279: URL: https://github.com/apache/arrow/pull/12279#discussion_r797665082
########## File path: cpp/src/arrow/engine/substrait/expression_internal.cc ########## @@ -0,0 +1,902 @@ +// 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. + +// This API is EXPERIMENTAL. + +#include "arrow/engine/substrait/expression_internal.h" + +#include <utility> + +#include "arrow/builder.h" +#include "arrow/compute/cast.h" +#include "arrow/compute/exec/expression.h" +#include "arrow/compute/exec/expression_internal.h" +#include "arrow/engine/substrait/extension_types.h" +#include "arrow/engine/substrait/type_internal.h" +#include "arrow/engine/visibility.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/make_unique.h" +#include "arrow/visit_scalar_inline.h" + +namespace arrow { + +using internal::checked_cast; + +namespace engine { + +namespace internal { +using ::arrow::internal::make_unique; +} // namespace internal + +namespace { + +std::shared_ptr<FixedSizeBinaryScalar> FixedSizeBinaryScalarFromBytes( + const std::string& bytes) { + auto buf = Buffer::FromString(bytes); + auto type = fixed_size_binary(static_cast<int>(buf->size())); + return std::make_shared<FixedSizeBinaryScalar>(std::move(buf), std::move(type)); +} + +} // namespace + +Result<compute::Expression> FromProto(const substrait::Expression& expr, + const ExtensionSet& ext_set) { + switch (expr.rex_type_case()) { + case substrait::Expression::kLiteral: { + ARROW_ASSIGN_OR_RAISE(auto datum, FromProto(expr.literal(), ext_set)); + return compute::literal(std::move(datum)); + } + + case substrait::Expression::kSelection: { + if (!expr.selection().has_direct_reference()) break; + + util::optional<compute::Expression> out; + if (expr.selection().has_expression()) { + ARROW_ASSIGN_OR_RAISE(out, FromProto(expr.selection().expression(), ext_set)); + } + + const auto* ref = &expr.selection().direct_reference(); + while (ref != nullptr) { + switch (ref->reference_type_case()) { + case substrait::Expression::ReferenceSegment::kStructField: { + auto index = ref->struct_field().field(); + if (!out) { + // Root StructField (column selection) + out = compute::field_ref(FieldRef(index)); + } else if (auto out_ref = out->field_ref()) { + // Nested StructFields on the root (selection of struct-typed column + // combined with selecting struct fields) + out = compute::field_ref(FieldRef(*out_ref, index)); + } else if (out->call() && out->call()->function_name == "struct_field") { + // Nested StructFields on top of an arbitrary expression + std::static_pointer_cast<arrow::compute::StructFieldOptions>( + out->call()->options) + ->indices.push_back(index); + } else { + // First StructField on top of an arbitrary expression + out = compute::call("struct_field", {std::move(*out)}, + arrow::compute::StructFieldOptions({index})); + } + + // Segment handled, continue with child segment (if any) + if (ref->struct_field().has_child()) { + ref = &ref->struct_field().child(); + } else { + ref = nullptr; + } + break; + } + case substrait::Expression::ReferenceSegment::kListElement: { + if (!out) { + // Root ListField (illegal) + return Status::Invalid( + "substrait::ListElement cannot take a Relation as an argument"); + } + + // ListField on top of an arbitrary expression + out = compute::call( + "list_element", + {std::move(*out), compute::literal(ref->list_element().offset())}); + + // Segment handled, continue with child segment (if any) + if (ref->list_element().has_child()) { + ref = &ref->list_element().child(); + } else { + ref = nullptr; + } + break; + } + default: + // Unimplemented construct, break out of loop + out.reset(); + ref = nullptr; + } + } + if (out) { + return *std::move(out); + } + break; + } + + case substrait::Expression::kIfThen: { + const auto& if_then = expr.if_then(); + if (!if_then.has_else_()) break; + if (if_then.ifs_size() == 0) break; + + if (if_then.ifs_size() == 1) { + ARROW_ASSIGN_OR_RAISE(auto if_, FromProto(if_then.ifs(0).if_(), ext_set)); + ARROW_ASSIGN_OR_RAISE(auto then, FromProto(if_then.ifs(0).then(), ext_set)); + ARROW_ASSIGN_OR_RAISE(auto else_, FromProto(if_then.else_(), ext_set)); + return compute::call("if_else", + {std::move(if_), std::move(then), std::move(else_)}); + } + + std::vector<compute::Expression> conditions, args; + std::vector<std::string> condition_names; + conditions.reserve(if_then.ifs_size()); + condition_names.reserve(if_then.ifs_size()); + size_t name_counter = 0; + args.reserve(if_then.ifs_size() + 2); + args.emplace_back(); + for (auto if_ : if_then.ifs()) { + ARROW_ASSIGN_OR_RAISE(auto compute_if, FromProto(if_.if_(), ext_set)); + ARROW_ASSIGN_OR_RAISE(auto compute_then, FromProto(if_.then(), ext_set)); + conditions.emplace_back(std::move(compute_if)); + args.emplace_back(std::move(compute_then)); + condition_names.emplace_back("cond" + std::to_string(++name_counter)); + } + ARROW_ASSIGN_OR_RAISE(auto compute_else, FromProto(if_then.else_(), ext_set)); + args.emplace_back(std::move(compute_else)); + args[0] = compute::call("make_struct", std::move(conditions), + compute::MakeStructOptions(condition_names)); + return compute::call("case_when", std::move(args)); + } + + case substrait::Expression::kScalarFunction: { + const auto& scalar_fn = expr.scalar_function(); + + auto id = ext_set.function_ids()[scalar_fn.function_reference()]; + + std::vector<compute::Expression> arguments(scalar_fn.args_size()); + for (int i = 0; i < scalar_fn.args_size(); ++i) { + ARROW_ASSIGN_OR_RAISE(arguments[i], FromProto(scalar_fn.args(i), ext_set)); + } + + return compute::call(id.name.to_string(), std::move(arguments)); + } + + default: + break; + } + + return Status::NotImplemented("conversion to arrow::compute::Expression from ", + expr.DebugString()); +} + +Result<Datum> FromProto(const substrait::Expression::Literal& lit, + const ExtensionSet& ext_set) { + if (lit.nullable()) { + // FIXME not sure how this field should be interpreted and there's no way to round + // trip it through arrow + return Status::Invalid( + "Nullable Literals - Literal.nullable must be left at the default"); + } + + switch (lit.literal_type_case()) { + case substrait::Expression::Literal::kBoolean: + return Datum(lit.boolean()); + + case substrait::Expression::Literal::kI8: + return Datum(static_cast<int8_t>(lit.i8())); + case substrait::Expression::Literal::kI16: + return Datum(static_cast<int16_t>(lit.i16())); + case substrait::Expression::Literal::kI32: + return Datum(static_cast<int32_t>(lit.i32())); + case substrait::Expression::Literal::kI64: + return Datum(static_cast<int64_t>(lit.i64())); + + case substrait::Expression::Literal::kFp32: + return Datum(lit.fp32()); + case substrait::Expression::Literal::kFp64: + return Datum(lit.fp64()); + + case substrait::Expression::Literal::kString: + return Datum(lit.string()); + case substrait::Expression::Literal::kBinary: + return Datum(BinaryScalar(Buffer::FromString(lit.binary()))); + + case substrait::Expression::Literal::kTimestamp: + return Datum( + TimestampScalar(static_cast<int64_t>(lit.timestamp()), TimeUnit::MICRO)); + + case substrait::Expression::Literal::kTimestampTz: + return Datum(TimestampScalar(static_cast<int64_t>(lit.timestamp_tz()), + TimeUnit::MICRO, TimestampTzTimezoneString())); + + case substrait::Expression::Literal::kDate: + return Datum(Date64Scalar(static_cast<int64_t>(lit.date()))); + case substrait::Expression::Literal::kTime: + return Datum(Time64Scalar(static_cast<int64_t>(lit.time()), TimeUnit::MICRO)); + + case substrait::Expression::Literal::kIntervalYearToMonth: + case substrait::Expression::Literal::kIntervalDayToSecond: { Review comment: Ben's reasoning here was probably that they don't map exactly: - Substrait `interval_year` is specified to store any combination of years and months independently, so 1 year 0 months is technically allowed to mean something different than 0 years 12 months, or -9999 years 120000 months, or whatever. Arrow `YEAR_MONTH` instead stores these intervals as a single integer for months, so it cannot represent this. - Substrait `interval_day` is any combination of days and microseconds, while Arrow's `MONTH_DAY_NANO` is any combination of months, days, and nanoseconds. Arrow's format could represent all of Substrait's possible representations, but only with math involved and not the other way around. One might argue that this makes no sense and semantically these different representations should always mean the same thing for every function anyone is ever allowed to define, and I would very much be inclined to agree, but neither Substrait nor Arrow (for `MONTH_DAY_NANO`) assert this in their format specifications. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: github-unsubscr...@arrow.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org