westonpace commented on a change in pull request #12279: URL: https://github.com/apache/arrow/pull/12279#discussion_r798199309
########## 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"); + } Review comment: I'm not sure I can accept the rationale here. The Arrow consumer shouldn't reject a plan because it has elements that we don't care about in Arrow. This case would probably be less egregious than the "hints" case in `CheckRelCommon` but I think both situations are probably going to be pretty common. I could buy the "sanitize the plan first" argument if we had some kind of representation other than Substrait that made sense. Hmm...we could add a "deserialization options" object with a "safe" flag or something like that which rejected plans that can't be round tripped only if that flag is true. That would quickly become painful however as we'd have to propagate that options object to a lot of function calls (probably the best approach would be to make the extension set an "option" so that we still have only one piece of tramp data). Given the situation I'll create a follow-up JIRA for this. I don't think it will take long for producers like Ibis to start creating plans with hints and it would be a shame if we couldn't process them. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
