jvanstraten commented on a change in pull request #12279:
URL: https://github.com/apache/arrow/pull/12279#discussion_r797586534



##########
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:
       Ben's general take on this was that FromProto and ToProto should be 100% 
round-trippable, and anything that loses information should be rejected. He 
figured it'd be better to do Substrait plan manipulation to make a plan 
compatible with and optimized for Arrow in separate logic (or, at least, I 
asked him w.r.t. the optimization case and this was his answer; I'm 
extrapolating the compatibility point from that and his desire for everything 
to be perfectly round-trippable for testing and separation of concerns).
   
   Personally I'm inclined to agree with you, and think the better approach is 
to have FromProto do the best it reasonably can (i.e. without making the code 
more difficult than it needs to be to do any conversion at all) to consume 
whatever the producer throws at it and convert it to an efficient equivalent in 
Arrow, and just don't do round-trip testing for conversions with information 
loss. Because, like you say, producing Substrait from Arrow and round-tripping 
in general is only a development/testing aid, not (currently?) a use case, and 
even if it were, you'd want that to do the best it can at generating efficient 
Substrait for the Arrow plan rather than rejecting Arrow plans where metadata 
would be lost (like struct field names, I think there's currently a rejection 
for that too). I think things will become needlessly complex even for simple 
plans if you separate these things, and result in a lot of code duplication 
(and extra tree-walking and intermediate conversion results at 
 runtime, for as far as that is significant compared to the actual query 
execution). If round-tripping is expected to become a use-case down the line 
(communication between Arrow compute engines on different nodes, maybe?) we can 
also just add a flag to the convertors to enable checks for things that 
wouldn't round-trip.




-- 
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


Reply via email to