wgtmac commented on code in PR #1166:
URL: https://github.com/apache/iceberg-cpp/pull/1166#discussion_r4702828545
##########
src/iceberg/expression/evaluator.cc:
##########
@@ -139,21 +156,417 @@ class EvalVisitor : public BoundVisitor<bool> {
const StructLike& row_;
};
-Evaluator::Evaluator(std::shared_ptr<Expression> bound_expr)
- : bound_expr_(std::move(bound_expr)) {}
+} // namespace
+
+namespace internal {
+
+/// \brief One node of a compiled bound expression, evaluated once per row.
+class EvaluatorNode {
+ public:
+ virtual ~EvaluatorNode() = default;
+ virtual Result<bool> Evaluate(const StructLike& row) const = 0;
+};
+
+} // namespace internal
+
+namespace {
+
+using internal::EvaluatorNode;
+using NodePtr = std::unique_ptr<const EvaluatorNode>;
+using Operation = Expression::Operation;
+
+class ConstantNode : public EvaluatorNode {
+ public:
+ explicit ConstantNode(bool value) : value_(value) {}
+ Result<bool> Evaluate(const StructLike& /*row*/) const override { return
value_; }
+
+ private:
+ bool value_;
+};
+
+class NotNode : public EvaluatorNode {
+ public:
+ explicit NotNode(NodePtr child) : child_(std::move(child)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto result, child_->Evaluate(row));
+ return !result;
+ }
+
+ private:
+ NodePtr child_;
+};
+
+// Evaluates both children, left first, like the expression visitor, so a row
that
+// fails to evaluate on either side still reports its error.
+class AndNode : public EvaluatorNode {
+ public:
+ AndNode(NodePtr left, NodePtr right)
+ : left_(std::move(left)), right_(std::move(right)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto left, left_->Evaluate(row));
+ ICEBERG_ASSIGN_OR_RAISE(auto right, right_->Evaluate(row));
+ return left && right;
+ }
+
+ private:
+ NodePtr left_;
+ NodePtr right_;
+};
+
+class OrNode : public EvaluatorNode {
+ public:
+ OrNode(NodePtr left, NodePtr right)
+ : left_(std::move(left)), right_(std::move(right)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto left, left_->Evaluate(row));
+ ICEBERG_ASSIGN_OR_RAISE(auto right, right_->Evaluate(row));
+ return left || right;
+ }
+
+ private:
+ NodePtr left_;
+ NodePtr right_;
+};
+
+// Evaluates an expression with EvalVisitor, which converts values to literals.
+// Used for expressions without a raw-value fast path, and as the fast path's
+// fallback, so both report identical results and errors.
+class VisitorNode : public EvaluatorNode {
+ public:
+ explicit VisitorNode(std::shared_ptr<Expression> expr) :
expr_(std::move(expr)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ EvalVisitor visitor(row);
+ return Visit<bool, EvalVisitor>(expr_, visitor);
+ }
+
+ private:
+ std::shared_ptr<Expression> expr_;
+};
+
+// Compares `lhs` with `rhs` as unsigned bytes, like std::vector<uint8_t> and
+// std::string comparisons.
+std::strong_ordering CompareBytes(std::string_view lhs, const void* rhs,
+ size_t rhs_size) {
+ const size_t common = std::min(lhs.size(), rhs_size);
+ if (common > 0) {
+ if (int result = std::memcmp(lhs.data(), rhs, common); result != 0) {
+ return result <=> 0;
+ }
+ }
+ return lhs.size() <=> rhs_size;
+}
+
+bool HasRawComparison(TypeId type_id) {
+ switch (type_id) {
+ case TypeId::kBoolean:
+ case TypeId::kInt:
+ case TypeId::kDate:
+ case TypeId::kLong:
+ case TypeId::kTime:
+ case TypeId::kTimestamp:
+ case TypeId::kTimestampTz:
+ case TypeId::kTimestampNs:
+ case TypeId::kTimestampTzNs:
+ case TypeId::kFloat:
+ case TypeId::kDouble:
+ case TypeId::kDecimal:
+ case TypeId::kString:
+ case TypeId::kBinary:
+ case TypeId::kFixed:
+ case TypeId::kUuid:
+ return true;
+ default:
+ return false;
+ }
+}
+
+int32_t DecimalScale(const Type& type) {
+ return type.type_id() == TypeId::kDecimal
+ ? internal::checked_cast<const DecimalType&>(type).scale()
+ : 0;
+}
+
+// A literal or unary predicate on a field reference, evaluated on the field's
raw
+// scalar instead of a Literal built for each row. Matches Literal ordering:
null
+// and out-of-range literals are unordered, floats use the total order,
decimals
+// compare across scales, and strings and bytes compare as unsigned bytes. Any
+// value it cannot compare that way is evaluated by the fallback.
+class ReferencePredicateNode : public EvaluatorNode {
+ public:
+ ReferencePredicateNode(const BoundReference& reference, Operation op,
+ const Literal* literal, std::shared_ptr<Expression>
predicate)
+ : accessor_(reference.accessor()),
+ type_id_(reference.type()->type_id()),
+ scale_(DecimalScale(*reference.type())),
+ op_(op),
+ literal_(literal),
+ literal_scale_(literal != nullptr ? DecimalScale(*literal->type()) :
0),
+ fallback_(std::move(predicate)) {}
+
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto value, accessor_.Get(row));
+ const bool is_null = std::holds_alternative<std::monostate>(value);
+ switch (op_) {
+ case Operation::kIsNull:
+ return is_null;
+ case Operation::kNotNull:
+ return !is_null;
+ case Operation::kIsNan:
+ case Operation::kNotNan: {
+ std::optional<bool> is_nan;
+ if (is_null) {
+ is_nan = false;
+ } else if (const auto* f = std::get_if<float>(&value)) {
Review Comment:
A `double` `Scalar` on a `float` field now passes this check, whereas
`GetLiteral` rejects it. Select the variant by the bound field type and use the
fallback for a mismatch.
##########
src/iceberg/test/evaluator_test.cc:
##########
@@ -1019,4 +1031,212 @@ TEST_F(EvaluatorTest, InExceptions) {
}
}
+namespace {
+
+// A row of raw scalars, one per top-level field.
+class ScalarRow : public StructLike {
+ public:
+ explicit ScalarRow(std::vector<Scalar> values) : values_(std::move(values))
{}
+ Result<Scalar> GetField(size_t pos) const override { return values_.at(pos);
}
+ size_t num_fields() const override { return values_.size(); }
+
+ private:
+ std::vector<Scalar> values_;
+};
+
+// One column under test: its type, row values, and literals to compare with.
+struct ColumnCase {
+ std::shared_ptr<PrimitiveType> type;
+ std::vector<Scalar> values;
+ std::vector<Literal> literals;
+};
+
+std::string Bytes(std::initializer_list<int> bytes) {
+ std::string result;
+ for (int byte : bytes) {
+ result.push_back(static_cast<char>(byte));
+ }
+ return result;
+}
+
+std::vector<uint8_t> ByteVector(std::string_view bytes) {
+ return {bytes.begin(), bytes.end()};
+}
+
+} // namespace
+
+// The evaluator compares raw scalars for reference predicates. It must match
the
+// literal-based semantics of BoundPredicate::Test for every type, operation,
and
+// edge value, including nulls, NaNs, signed zeros, and unsigned byte order.
+TEST(EvaluatorRawComparisonTest, MatchesLiteralSemantics) {
+ const float nan_f = std::numeric_limits<float>::quiet_NaN();
+ const double nan_d = std::numeric_limits<double>::quiet_NaN();
+ const double inf = std::numeric_limits<double>::infinity();
+ const std::string high = Bytes({0xff, 0x01});
+ const std::string low = Bytes({0x01, 0xff});
+ static const std::array<std::string, 7> kStrings = {"", "a", "ab", "abc",
+ "b", high, low};
+ auto uuid_a =
Uuid::FromString("123e4567-e89b-12d3-a456-426614174000").value();
+ auto uuid_b =
Uuid::FromString("f23e4567-e89b-12d3-a456-426614174000").value();
+ static std::string uuid_a_bytes;
+ static std::string uuid_b_bytes;
+ uuid_a_bytes.assign(reinterpret_cast<const char*>(uuid_a.bytes().data()),
16);
+ uuid_b_bytes.assign(reinterpret_cast<const char*>(uuid_b.bytes().data()),
16);
+
+ std::vector<ColumnCase> cases;
+ cases.push_back({.type = boolean(),
+ .values = {std::monostate{}, false, true},
+ .literals = {Literal::Boolean(false),
Literal::Boolean(true)}});
+ cases.push_back({.type = int32(),
+ .values = {std::monostate{}, int32_t{-5}, int32_t{0},
int32_t{7},
+ std::numeric_limits<int32_t>::max()},
+ .literals = {Literal::Int(0), Literal::Int(7),
Literal::Int(-100)}});
+ cases.push_back({.type = date(),
+ .values = {std::monostate{}, int32_t{18000},
int32_t{19000}},
+ .literals = {Literal::Date(18500), Literal::Date(18000)}});
+ cases.push_back(
+ {.type = int64(),
+ .values = {std::monostate{}, int64_t{-1}, int64_t{0}, int64_t{1} << 40},
+ .literals = {Literal::Long(0), Literal::Long(int64_t{1} << 40)}});
+ cases.push_back({.type = timestamp(),
+ .values = {std::monostate{}, int64_t{1000}, int64_t{2000}},
+ .literals = {Literal::Timestamp(1500),
Literal::Timestamp(2000)}});
+ cases.push_back({.type = timestamp_tz(),
+ .values = {std::monostate{}, int64_t{1000}},
+ .literals = {Literal::TimestampTz(1000)}});
+ cases.push_back({.type = time(),
+ .values = {std::monostate{}, int64_t{5}},
+ .literals = {Literal::Time(6)}});
+ cases.push_back(
+ {.type = float32(),
+ .values = {std::monostate{}, -0.0f, 0.0f, 1.5f, nan_f, -nan_f,
+ std::numeric_limits<float>::infinity()},
+ .literals = {Literal::Float(0.0f), Literal::Float(-0.0f),
Literal::Float(1.5f)}});
+ cases.push_back({.type = float64(),
+ .values = {std::monostate{}, -0.0, 0.0, -inf, inf, nan_d,
2.25},
+ .literals = {Literal::Double(0.0), Literal::Double(-0.0),
+ Literal::Double(2.25), Literal::Double(inf)}});
+ cases.push_back({.type = decimal(9, 2),
+ .values = {std::monostate{}, Decimal(int128_t{-150}),
+ Decimal(int128_t{0}), Decimal(int128_t{12345})},
+ .literals = {Literal::Decimal(0, 9, 2),
Literal::Decimal(12345, 9, 2),
+ Literal::Decimal(-151, 9, 2)}});
+ std::vector<Scalar> strings{std::monostate{}};
+ for (const auto& value : kStrings) {
+ strings.emplace_back(std::string_view(value));
+ }
+ cases.push_back(
+ {.type = string(),
+ .values = strings,
+ .literals = {Literal::String(""), Literal::String("a"),
Literal::String("ab"),
+ Literal::String(high), Literal::String("b")}});
+ cases.push_back({.type = binary(),
+ .values = strings,
+ .literals = {Literal::Binary({}),
Literal::Binary(ByteVector("ab")),
+ Literal::Binary(ByteVector(high)),
+ Literal::Binary(ByteVector(low))}});
+ static const std::array<std::string, 3> kFixed = {"abc", "abd",
+ Bytes({0xff, 0x00, 0x00})};
+ std::vector<Scalar> fixed_values{std::monostate{}};
+ for (const auto& value : kFixed) {
+ fixed_values.emplace_back(std::string_view(value));
+ }
+ cases.push_back({.type = fixed(3),
+ .values = fixed_values,
+ .literals = {Literal::Fixed(ByteVector("abd")),
+ Literal::Fixed(ByteVector(Bytes({0xff, 0x00,
0x00})))}});
+ cases.push_back({.type = uuid(),
+ .values = {std::monostate{}, std::string_view(uuid_a_bytes),
+ std::string_view(uuid_b_bytes)},
+ .literals = {Literal::UUID(uuid_a),
Literal::UUID(uuid_b)}});
+
+ using Op = Expression::Operation;
+ const std::array literal_ops = {Op::kLt, Op::kLtEq, Op::kGt,
+ Op::kGtEq, Op::kEq,
Op::kNotEq,
+ Op::kStartsWith, Op::kNotStartsWith};
+ const std::array unary_ops = {Op::kIsNull, Op::kNotNull, Op::kIsNan,
Op::kNotNan};
+
+ int checked = 0;
+ for (const auto& column : cases) {
+ Schema schema({SchemaField::MakeOptional(1, "c", column.type)});
+ std::vector<std::shared_ptr<Expression>> predicates;
+ for (Op op : unary_ops) {
+ predicates.push_back(Expressions::Predicate(op, "c"));
+ }
+ for (const auto& literal : column.literals) {
+ for (Op op : literal_ops) {
+ predicates.push_back(Expressions::Predicate(op, "c", literal));
+ }
+ }
+ for (const auto& unbound : predicates) {
+ auto bound = Binder::Bind(schema, unbound, /*case_sensitive=*/true);
+ auto evaluator = Evaluator::Make(schema, unbound);
+ if (!bound.has_value()) {
+ // Invalid for this type, e.g. starts_with on an int.
+ EXPECT_FALSE(evaluator.has_value()) << unbound->ToString();
+ continue;
+ }
+ ASSERT_TRUE(evaluator.has_value()) << evaluator.error().message;
+ for (const auto& value : column.values) {
+ ScalarRow row({value});
+ SCOPED_TRACE(
+ std::format("{} on {}", unbound->ToString(),
column.type->ToString()));
+ Result<bool> expected = false;
+ if ((*bound)->op() == Op::kTrue || (*bound)->op() == Op::kFalse) {
+ expected = (*bound)->op() == Op::kTrue;
+ } else {
+ const auto& predicate =
std::dynamic_pointer_cast<BoundPredicate>(*bound);
+ ASSERT_NE(predicate, nullptr) << (*bound)->ToString();
+ auto literal = predicate->term()->Evaluate(row);
+ ASSERT_TRUE(literal.has_value()) << literal.error().message;
+ expected = predicate->Test(*literal);
+ }
+ auto actual = (*evaluator)->Evaluate(row);
+ ASSERT_EQ(expected.has_value(), actual.has_value());
+ if (expected.has_value()) {
+ EXPECT_EQ(*expected, *actual)
+ << "row value index in " << column.type->ToString();
+ }
+ ++checked;
+ }
+ }
+ }
+ EXPECT_GT(checked, 1000);
+}
+
+TEST(EvaluatorRawComparisonTest, CompoundExpressionsKeepErrorsFromBothSides) {
+ Schema schema({SchemaField::MakeRequired(1, "id", int32()),
+ SchemaField::MakeOptional(2, "name", string())});
+ // A required field that is null is an error. The left side is false, but the
+ // right side is still evaluated, as before.
+ auto expr = Expressions::And(Expressions::Equal("name",
Literal::String("x")),
+ Expressions::GreaterThan("id",
Literal::Int(0)));
+ ICEBERG_UNWRAP_OR_FAIL(auto evaluator, Evaluator::Make(schema, expr));
+ ScalarRow bad_row({std::monostate{}, std::string_view("y")});
+ EXPECT_FALSE(evaluator->Evaluate(bad_row).has_value());
+ ScalarRow good_row({int32_t{1}, std::string_view("x")});
+ EXPECT_THAT(evaluator->Evaluate(good_row), HasValue(::testing::Eq(true)));
+}
+
+TEST(EvaluatorRawComparisonTest, TransformsAndSetsUseLiteralEvaluation) {
+ Schema schema({SchemaField::MakeOptional(1, "id", int32())});
+ auto in = Expressions::In("id", {Literal::Int(1), Literal::Int(3)});
+ ICEBERG_UNWRAP_OR_FAIL(auto in_evaluator, Evaluator::Make(schema, in));
+ EXPECT_THAT(in_evaluator->Evaluate(ScalarRow({int32_t{3}})),
+ HasValue(::testing::Eq(true)));
+ EXPECT_THAT(in_evaluator->Evaluate(ScalarRow({int32_t{2}})),
+ HasValue(::testing::Eq(false)));
+ EXPECT_THAT(in_evaluator->Evaluate(ScalarRow({std::monostate{}})),
+ HasValue(::testing::Eq(false)));
+
+ auto bucket = Expressions::Equal(
+ std::shared_ptr<UnboundTerm<BoundTransform>>(Expressions::Bucket("id",
4)),
+ Literal::Int(0));
+ ICEBERG_UNWRAP_OR_FAIL(auto bucket_evaluator, Evaluator::Make(schema,
bucket));
+ for (int32_t id = 0; id < 8; ++id) {
+ auto result = bucket_evaluator->Evaluate(ScalarRow({id}));
+ ASSERT_TRUE(result.has_value()) << result.error().message;
Review Comment:
This loop would pass with an evaluator that always returned true or false.
Assert a known bucket match and non-match.
##########
src/iceberg/expression/evaluator.cc:
##########
@@ -139,21 +156,417 @@ class EvalVisitor : public BoundVisitor<bool> {
const StructLike& row_;
};
-Evaluator::Evaluator(std::shared_ptr<Expression> bound_expr)
- : bound_expr_(std::move(bound_expr)) {}
+} // namespace
+
+namespace internal {
+
+/// \brief One node of a compiled bound expression, evaluated once per row.
+class EvaluatorNode {
+ public:
+ virtual ~EvaluatorNode() = default;
+ virtual Result<bool> Evaluate(const StructLike& row) const = 0;
+};
+
+} // namespace internal
+
+namespace {
+
+using internal::EvaluatorNode;
+using NodePtr = std::unique_ptr<const EvaluatorNode>;
+using Operation = Expression::Operation;
+
+class ConstantNode : public EvaluatorNode {
+ public:
+ explicit ConstantNode(bool value) : value_(value) {}
+ Result<bool> Evaluate(const StructLike& /*row*/) const override { return
value_; }
+
+ private:
+ bool value_;
+};
+
+class NotNode : public EvaluatorNode {
+ public:
+ explicit NotNode(NodePtr child) : child_(std::move(child)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto result, child_->Evaluate(row));
+ return !result;
+ }
+
+ private:
+ NodePtr child_;
+};
+
+// Evaluates both children, left first, like the expression visitor, so a row
that
+// fails to evaluate on either side still reports its error.
+class AndNode : public EvaluatorNode {
+ public:
+ AndNode(NodePtr left, NodePtr right)
+ : left_(std::move(left)), right_(std::move(right)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto left, left_->Evaluate(row));
+ ICEBERG_ASSIGN_OR_RAISE(auto right, right_->Evaluate(row));
+ return left && right;
+ }
+
+ private:
+ NodePtr left_;
+ NodePtr right_;
+};
+
+class OrNode : public EvaluatorNode {
+ public:
+ OrNode(NodePtr left, NodePtr right)
+ : left_(std::move(left)), right_(std::move(right)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto left, left_->Evaluate(row));
+ ICEBERG_ASSIGN_OR_RAISE(auto right, right_->Evaluate(row));
+ return left || right;
+ }
+
+ private:
+ NodePtr left_;
+ NodePtr right_;
+};
+
+// Evaluates an expression with EvalVisitor, which converts values to literals.
+// Used for expressions without a raw-value fast path, and as the fast path's
+// fallback, so both report identical results and errors.
+class VisitorNode : public EvaluatorNode {
+ public:
+ explicit VisitorNode(std::shared_ptr<Expression> expr) :
expr_(std::move(expr)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ EvalVisitor visitor(row);
+ return Visit<bool, EvalVisitor>(expr_, visitor);
+ }
+
+ private:
+ std::shared_ptr<Expression> expr_;
+};
+
+// Compares `lhs` with `rhs` as unsigned bytes, like std::vector<uint8_t> and
+// std::string comparisons.
+std::strong_ordering CompareBytes(std::string_view lhs, const void* rhs,
+ size_t rhs_size) {
+ const size_t common = std::min(lhs.size(), rhs_size);
+ if (common > 0) {
+ if (int result = std::memcmp(lhs.data(), rhs, common); result != 0) {
+ return result <=> 0;
+ }
+ }
+ return lhs.size() <=> rhs_size;
+}
+
+bool HasRawComparison(TypeId type_id) {
+ switch (type_id) {
+ case TypeId::kBoolean:
+ case TypeId::kInt:
+ case TypeId::kDate:
+ case TypeId::kLong:
+ case TypeId::kTime:
+ case TypeId::kTimestamp:
+ case TypeId::kTimestampTz:
+ case TypeId::kTimestampNs:
+ case TypeId::kTimestampTzNs:
+ case TypeId::kFloat:
+ case TypeId::kDouble:
+ case TypeId::kDecimal:
+ case TypeId::kString:
+ case TypeId::kBinary:
+ case TypeId::kFixed:
+ case TypeId::kUuid:
+ return true;
+ default:
+ return false;
+ }
+}
+
+int32_t DecimalScale(const Type& type) {
+ return type.type_id() == TypeId::kDecimal
+ ? internal::checked_cast<const DecimalType&>(type).scale()
+ : 0;
+}
+
+// A literal or unary predicate on a field reference, evaluated on the field's
raw
+// scalar instead of a Literal built for each row. Matches Literal ordering:
null
+// and out-of-range literals are unordered, floats use the total order,
decimals
+// compare across scales, and strings and bytes compare as unsigned bytes. Any
+// value it cannot compare that way is evaluated by the fallback.
+class ReferencePredicateNode : public EvaluatorNode {
+ public:
+ ReferencePredicateNode(const BoundReference& reference, Operation op,
+ const Literal* literal, std::shared_ptr<Expression>
predicate)
+ : accessor_(reference.accessor()),
+ type_id_(reference.type()->type_id()),
+ scale_(DecimalScale(*reference.type())),
+ op_(op),
+ literal_(literal),
+ literal_scale_(literal != nullptr ? DecimalScale(*literal->type()) :
0),
+ fallback_(std::move(predicate)) {}
+
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto value, accessor_.Get(row));
+ const bool is_null = std::holds_alternative<std::monostate>(value);
+ switch (op_) {
+ case Operation::kIsNull:
+ return is_null;
+ case Operation::kNotNull:
+ return !is_null;
+ case Operation::kIsNan:
+ case Operation::kNotNan: {
+ std::optional<bool> is_nan;
+ if (is_null) {
+ is_nan = false;
+ } else if (const auto* f = std::get_if<float>(&value)) {
+ is_nan = std::isnan(*f);
+ } else if (const auto* d = std::get_if<double>(&value)) {
+ is_nan = std::isnan(*d);
+ }
+ if (!is_nan.has_value()) {
+ return fallback_.Evaluate(row);
+ }
+ return op_ == Operation::kIsNan ? *is_nan : !*is_nan;
+ }
+ case Operation::kStartsWith:
+ case Operation::kNotStartsWith: {
+ const auto* prefix = std::get_if<std::string>(&literal_->value());
+ bool starts = false;
+ if (const auto* str = std::get_if<std::string_view>(&value);
+ str != nullptr && prefix != nullptr) {
+ starts = str->starts_with(*prefix);
+ } else if (!is_null) {
+ return fallback_.Evaluate(row);
+ }
+ return op_ == Operation::kStartsWith ? starts : !starts;
+ }
+ default:
+ break;
+ }
+
+ auto order = Compare(value);
+ if (!order.has_value()) {
+ return fallback_.Evaluate(row);
+ }
+ switch (op_) {
+ case Operation::kLt:
+ return *order < 0;
+ case Operation::kLtEq:
+ return *order <= 0;
+ case Operation::kGt:
+ return *order > 0;
+ case Operation::kGtEq:
+ return *order >= 0;
+ case Operation::kEq:
+ return *order == 0;
+ case Operation::kNotEq:
+ return !(*order == 0);
+ default:
+ return fallback_.Evaluate(row);
+ }
+ }
+
+ // Returns true when this node can evaluate `op` for a field of `type_id`.
+ static bool Supports(Operation op, TypeId type_id) {
+ switch (op) {
+ case Operation::kIsNull:
+ case Operation::kNotNull:
+ return true;
+ case Operation::kIsNan:
+ case Operation::kNotNan:
+ return type_id == TypeId::kFloat || type_id == TypeId::kDouble;
+ case Operation::kStartsWith:
+ case Operation::kNotStartsWith:
+ return type_id == TypeId::kString;
+ case Operation::kLt:
+ case Operation::kLtEq:
+ case Operation::kGt:
+ case Operation::kGtEq:
+ case Operation::kEq:
+ case Operation::kNotEq:
+ return HasRawComparison(type_id);
+ default:
+ return false;
+ }
+ }
+
+ private:
+ // Orders `value` against the literal like Literal::operator<=>, or returns
+ // std::nullopt when the scalar does not hold the field type's
representation.
+ std::optional<std::partial_ordering> Compare(const Scalar& value) const {
+ const auto& literal = literal_->value();
+ if (std::holds_alternative<std::monostate>(value) || literal_->IsNull() ||
+ literal_->IsAboveMax() || literal_->IsBelowMin()) {
+ return std::partial_ordering::unordered;
+ }
+ auto compare = [&]<typename ScalarT, typename LiteralT>(
+ auto&& order) -> std::optional<std::partial_ordering> {
+ const auto* lhs = std::get_if<ScalarT>(&value);
+ const auto* rhs = std::get_if<LiteralT>(&literal);
+ if (lhs == nullptr || rhs == nullptr) {
+ return std::nullopt;
+ }
+ return order(*lhs, *rhs);
+ };
+ auto three_way = [](const auto& lhs, const auto& rhs) ->
std::partial_ordering {
+ return lhs <=> rhs;
+ };
+ auto total_order = [](auto lhs, auto rhs) -> std::partial_ordering {
+ return std::strong_order(lhs, rhs);
+ };
+ auto bytes = [](std::string_view lhs, const auto& rhs) ->
std::partial_ordering {
+ return CompareBytes(lhs, rhs.data(), rhs.size());
+ };
+
+ switch (type_id_) {
+ case TypeId::kBoolean:
+ return compare.template operator()<bool, bool>(three_way);
+ case TypeId::kInt:
+ case TypeId::kDate:
+ return compare.template operator()<int32_t, int32_t>(three_way);
+ case TypeId::kLong:
+ case TypeId::kTime:
+ case TypeId::kTimestamp:
+ case TypeId::kTimestampTz:
+ case TypeId::kTimestampNs:
+ case TypeId::kTimestampTzNs:
+ return compare.template operator()<int64_t, int64_t>(three_way);
+ case TypeId::kFloat:
+ return compare.template operator()<float, float>(total_order);
+ case TypeId::kDouble:
+ return compare.template operator()<double, double>(total_order);
+ case TypeId::kDecimal:
+ return compare.template operator()<Decimal, Decimal>(
+ [this](const Decimal& lhs, const Decimal& rhs) {
+ return Decimal::Compare(lhs, rhs, scale_, literal_scale_);
+ });
+ case TypeId::kString:
+ return compare.template operator()<std::string_view,
std::string>(bytes);
+ case TypeId::kBinary:
+ case TypeId::kFixed:
+ return compare.template operator()<std::string_view,
std::vector<uint8_t>>(bytes);
+ case TypeId::kUuid: {
+ // Literal conversion rejects values that are not 16 bytes; let it
report that.
+ const auto* raw = std::get_if<std::string_view>(&value);
+ if (raw == nullptr || raw->size() != Uuid::kLength) {
+ return std::nullopt;
+ }
+ return compare.template operator()<std::string_view, Uuid>(
+ [](std::string_view lhs, const Uuid& rhs) -> std::partial_ordering
{
+ return CompareBytes(lhs, rhs.bytes().data(), Uuid::kLength);
+ });
+ }
+ default:
+ return std::nullopt;
+ }
+ }
+
+ // Reads the referenced field's raw scalar from a row. Owned by the bound
+ // reference, which the evaluator keeps alive through its bound expression.
+ const StructLikeAccessor& accessor_;
+ // The field's type, which selects the scalar representation to compare.
+ TypeId type_id_;
+ // The field's decimal scale, or 0 for other types.
+ int32_t scale_;
+ // The predicate operation, e.g. kLt or kIsNull.
+ Operation op_;
+ // The literal to compare with, or nullptr for unary predicates. Owned by the
+ // bound predicate, which the evaluator keeps alive.
+ const Literal* literal_;
+ // The literal's decimal scale, or 0 for other types or unary predicates.
+ int32_t literal_scale_;
+ // Evaluates the whole predicate with Literal semantics for rows whose scalar
+ // does not have the field type's representation, so they keep the same
result
+ // or error as before.
+ VisitorNode fallback_;
+};
+
+// Returns a fast node for a predicate on a field reference, or nullptr.
+NodePtr CompileReferencePredicate(const std::shared_ptr<Expression>& expr) {
+ const auto* predicate = dynamic_cast<const BoundPredicate*>(expr.get());
+ if (predicate == nullptr) {
+ return nullptr;
+ }
+ const auto* reference = dynamic_cast<const
BoundReference*>(predicate->term().get());
+ if (reference == nullptr) {
+ return nullptr;
+ }
+ const TypeId type_id = reference->type()->type_id();
+ if (!ReferencePredicateNode::Supports(predicate->op(), type_id)) {
+ return nullptr;
+ }
+
+ const Literal* literal = nullptr;
+ switch (predicate->kind()) {
Review Comment:
The vector overload of `Expressions::Predicate` can bind `IS_NULL` with one
literal as a literal predicate. The visitor returned `InvalidExpression` for
this pair. Check the operation against the predicate kind before taking the
fast path.
--
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]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]