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



##########
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: {
+      Int32Builder builder;
+      std::shared_ptr<DataType> type;
+      if (lit.has_interval_year_to_month()) {
+        RETURN_NOT_OK(builder.Append(lit.interval_year_to_month().years()));
+        RETURN_NOT_OK(builder.Append(lit.interval_year_to_month().months()));
+        type = interval_year();
+      } else {
+        RETURN_NOT_OK(builder.Append(lit.interval_day_to_second().days()));
+        RETURN_NOT_OK(builder.Append(lit.interval_day_to_second().seconds()));
+        type = interval_day();
+      }
+      ARROW_ASSIGN_OR_RAISE(auto array, builder.Finish());
+      return Datum(
+          ExtensionScalar(FixedSizeListScalar(std::move(array)), 
std::move(type)));
+    }
+
+    case substrait::Expression::Literal::kUuid:
+      return Datum(ExtensionScalar(FixedSizeBinaryScalarFromBytes(lit.uuid()), 
uuid()));
+
+    case substrait::Expression::Literal::kFixedChar:
+      return Datum(
+          ExtensionScalar(FixedSizeBinaryScalarFromBytes(lit.fixed_char()),
+                          
fixed_char(static_cast<int32_t>(lit.fixed_char().size()))));
+
+    case substrait::Expression::Literal::kVarChar:
+      return Datum(
+          ExtensionScalar(StringScalar(lit.var_char().value()),
+                          
varchar(static_cast<int32_t>(lit.var_char().length()))));
+
+    case substrait::Expression::Literal::kFixedBinary:
+      return Datum(FixedSizeBinaryScalarFromBytes(lit.fixed_binary()));
+
+    case substrait::Expression::Literal::kDecimal: {
+      if (lit.decimal().value().size() != sizeof(Decimal128)) {
+        return Status::Invalid("Decimal literal had ", 
lit.decimal().value().size(),
+                               " bytes (expected ", sizeof(Decimal128), ")");
+      }
+
+      Decimal128 value;
+      std::memcpy(value.mutable_native_endian_bytes(), 
lit.decimal().value().data(),
+                  sizeof(Decimal128));
+#if !ARROW_LITTLE_ENDIAN
+      std::reverse(value.mutable_native_endian_bytes(),
+                   value.mutable_native_endian_bytes() + sizeof(Decimal128));
+#endif
+      auto type = decimal128(lit.decimal().precision(), lit.decimal().scale());
+      return Datum(Decimal128Scalar(value, std::move(type)));
+    }
+
+    case substrait::Expression::Literal::kStruct: {
+      const auto& struct_ = lit.struct_();
+
+      ScalarVector fields(struct_.fields_size());
+      std::vector<std::string> field_names(fields.size(), "");
+      for (int i = 0; i < struct_.fields_size(); ++i) {
+        ARROW_ASSIGN_OR_RAISE(auto field, FromProto(struct_.fields(i), 
ext_set));
+        DCHECK(field.is_scalar());
+        fields[i] = field.scalar();
+      }
+      ARROW_ASSIGN_OR_RAISE(
+          auto scalar, StructScalar::Make(std::move(fields), 
std::move(field_names)));
+      return Datum(std::move(scalar));
+    }
+
+    case substrait::Expression::Literal::kList: {
+      const auto& list = lit.list();
+      if (list.values_size() == 0) {
+        return Status::Invalid(
+            "substrait::Expression::Literal::List had no values; should have 
been an "
+            "substrait::Expression::Literal::EmptyList");
+      }
+
+      std::shared_ptr<DataType> element_type;
+
+      ScalarVector values(list.values_size());
+      for (int i = 0; i < list.values_size(); ++i) {
+        ARROW_ASSIGN_OR_RAISE(auto value, FromProto(list.values(i), ext_set));
+        DCHECK(value.is_scalar());
+        values[i] = value.scalar();
+        if (element_type) {
+          if (!value.type()->Equals(*element_type)) {
+            return Status::Invalid(
+                list.DebugString(),
+                " has a value whose type doesn't match the other list values");
+          }
+        } else {
+          element_type = value.type();
+        }
+      }
+
+      ARROW_ASSIGN_OR_RAISE(auto builder, 
MakeBuilder(std::move(element_type)));
+      RETURN_NOT_OK(builder->AppendScalars(values));
+      ARROW_ASSIGN_OR_RAISE(auto arr, builder->Finish());
+      return Datum(ListScalar(std::move(arr)));
+    }
+
+    case substrait::Expression::Literal::kMap: {
+      const auto& map = lit.map();
+      if (map.key_values_size() == 0) {
+        return Status::Invalid(
+            "substrait::Expression::Literal::Map had no values; should have 
been an "
+            "substrait::Expression::Literal::EmptyMap");
+      }
+
+      std::shared_ptr<DataType> key_type, value_type;
+      ScalarVector keys(map.key_values_size()), values(map.key_values_size());
+      for (int i = 0; i < map.key_values_size(); ++i) {
+        const auto& kv = map.key_values(i);
+
+        static const std::array<char const*, 4> kMissing = {"key and value", 
"value",
+                                                            "key", nullptr};
+        if (auto missing = kMissing[kv.has_key() + kv.has_value() * 2]) {
+          return Status::Invalid("While converting to MapScalar encountered 
missing ",
+                                 missing, " in ", map.DebugString());
+        }
+        ARROW_ASSIGN_OR_RAISE(auto key, FromProto(kv.key(), ext_set));
+        ARROW_ASSIGN_OR_RAISE(auto value, FromProto(kv.value(), ext_set));
+
+        DCHECK(key.is_scalar());
+        DCHECK(value.is_scalar());
+
+        keys[i] = key.scalar();
+        values[i] = value.scalar();
+
+        if (key_type) {
+          if (!key.type()->Equals(*key_type)) {
+            return Status::Invalid(map.DebugString(),
+                                   " has a key whose type doesn't match 
key_type");
+          }
+        } else {
+          key_type = value.type();
+        }
+
+        if (value_type) {
+          if (!value.type()->Equals(*value_type)) {
+            return Status::Invalid(map.DebugString(),
+                                   " has a value whose type doesn't match 
value_type");
+          }
+        } else {
+          value_type = value.type();
+        }
+      }
+
+      ARROW_ASSIGN_OR_RAISE(auto key_builder, MakeBuilder(key_type));
+      ARROW_ASSIGN_OR_RAISE(auto value_builder, MakeBuilder(value_type));
+      RETURN_NOT_OK(key_builder->AppendScalars(keys));
+      RETURN_NOT_OK(value_builder->AppendScalars(values));
+      ARROW_ASSIGN_OR_RAISE(auto key_arr, key_builder->Finish());
+      ARROW_ASSIGN_OR_RAISE(auto value_arr, value_builder->Finish());
+      ARROW_ASSIGN_OR_RAISE(
+          auto kv_arr,
+          StructArray::Make(ArrayVector{std::move(key_arr), 
std::move(value_arr)},
+                            std::vector<std::string>{"key", "value"}));
+      return Datum(std::make_shared<MapScalar>(std::move(kv_arr)));
+    }
+
+    case substrait::Expression::Literal::kEmptyList: {
+      ARROW_ASSIGN_OR_RAISE(auto type_nullable,
+                            FromProto(lit.empty_list().type(), ext_set));
+      ARROW_ASSIGN_OR_RAISE(auto values, MakeEmptyArray(type_nullable.first));
+      return ListScalar{std::move(values)};
+    }
+
+    case substrait::Expression::Literal::kEmptyMap: {
+      ARROW_ASSIGN_OR_RAISE(auto key_type_nullable,
+                            FromProto(lit.empty_map().key(), ext_set));
+      ARROW_ASSIGN_OR_RAISE(auto keys,
+                            
MakeEmptyArray(std::move(key_type_nullable.first)));
+
+      ARROW_ASSIGN_OR_RAISE(auto value_type_nullable,
+                            FromProto(lit.empty_map().value(), ext_set));
+      ARROW_ASSIGN_OR_RAISE(auto values,
+                            
MakeEmptyArray(std::move(value_type_nullable.first)));
+
+      auto map_type = std::make_shared<MapType>(keys->type(), values->type());
+      ARROW_ASSIGN_OR_RAISE(
+          auto key_values,
+          StructArray::Make(
+              {std::move(keys), std::move(values)},
+              checked_cast<const 
ListType&>(*map_type).value_type()->fields()));
+
+      return MapScalar{std::move(key_values)};
+    }
+
+    case substrait::Expression::Literal::kNull: {
+      ARROW_ASSIGN_OR_RAISE(auto type_nullable, FromProto(lit.null(), 
ext_set));
+      if (!type_nullable.second) {
+        return Status::Invalid("Null literal ", lit.DebugString(),
+                               " is of non-nullable type");
+      }
+
+      return Datum(MakeNullScalar(std::move(type_nullable.first)));
+    }
+
+    default:
+      break;
+  }
+
+  return Status::NotImplemented("conversion to arrow::Datum from ", 
lit.DebugString());

Review comment:
       I improved the messages slightly (including your suggestion) in bdb0b74, 
but in general I think that proper error handling is a whole project in its own 
right, and not something we should be focusing on yet. On the shorter term, we 
might want to instead investigate a good way to just emit the whole JSON 
representation of the unsupported Substrait message to the user to aid 
debugging, but I'm not familiar enough with Arrow to know how to do that right 
now (short of *very* long error messages).




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