From 067a2c5d9fa26f48708d580da7f674479c67a6c2 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 17:50:46 +0800 Subject: [PATCH 01/10] Share table predicate operators between C++ TAG and FIELD filters --- cpp/src/reader/device_meta_iterator.cc | 6 +- cpp/src/reader/filter/aligned_field_filter.cc | 429 ++++++------------ cpp/src/reader/filter/aligned_field_filter.h | 47 +- cpp/src/reader/filter/table_predicate.h | 90 ++++ cpp/src/reader/filter/tag_filter.cc | 203 +++------ cpp/src/reader/filter/tag_filter.h | 38 +- .../filter/aligned_field_filter_test.cc | 19 + cpp/test/reader/filter/tag_filter_test.cc | 39 +- .../tsfile/references/properties-filters.md | 10 + 9 files changed, 413 insertions(+), 468 deletions(-) create mode 100644 cpp/src/reader/filter/table_predicate.h diff --git a/cpp/src/reader/device_meta_iterator.cc b/cpp/src/reader/device_meta_iterator.cc index e57111e32..5fb50dafd 100644 --- a/cpp/src/reader/device_meta_iterator.cc +++ b/cpp/src/reader/device_meta_iterator.cc @@ -171,8 +171,10 @@ int DeviceMetaIterator::load_internal_node(MetaIndexNode* meta_index_node) { void DeviceMetaIterator::try_setup_direct_lookup(MetaIndexNode* root_node) { if (id_filter_ == nullptr || root_node == nullptr) return; - const auto* eq = dynamic_cast(id_filter_); - if (eq == nullptr) return; + const auto* eq = dynamic_cast(id_filter_); + if (eq == nullptr || eq->kind() != TablePredicate::Kind::COMPARISON || + eq->compare_op() != TablePredicate::CompareOp::EQ || eq->col_idx_ != 1) + return; if (root_node->children_.empty()) return; diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index afa6bbb72..c4004b14b 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -32,25 +32,6 @@ namespace storage { namespace { -template -bool compare_values(T left, T right, AlignedFieldFilter::CompareOp op) { - switch (op) { - case AlignedFieldFilter::CompareOp::EQ: - return left == right; - case AlignedFieldFilter::CompareOp::NE: - return left != right; - case AlignedFieldFilter::CompareOp::LT: - return left < right; - case AlignedFieldFilter::CompareOp::LE: - return left <= right; - case AlignedFieldFilter::CompareOp::GT: - return left > right; - case AlignedFieldFilter::CompareOp::GE: - return left >= right; - } - return false; -} - AlignedFieldFilter::CompareOp negate_comparison( AlignedFieldFilter::CompareOp op) { using Op = AlignedFieldFilter::CompareOp; @@ -71,26 +52,6 @@ AlignedFieldFilter::CompareOp negate_comparison( return Op::EQ; } -int compare_string(const char* data, uint32_t len, const std::string& literal, - AlignedFieldFilter::CompareOp op) { - const std::string value(data, len); - switch (op) { - case AlignedFieldFilter::CompareOp::EQ: - return value == literal; - case AlignedFieldFilter::CompareOp::NE: - return value != literal; - case AlignedFieldFilter::CompareOp::LT: - return value < literal; - case AlignedFieldFilter::CompareOp::LE: - return value <= literal; - case AlignedFieldFilter::CompareOp::GT: - return value > literal; - case AlignedFieldFilter::CompareOp::GE: - return value >= literal; - } - return false; -} - // NaN values count as non-NULL, but may not change finite min/max values. // Their presence is retained in the sum, including after statistics merge. // A NaN sum can also result from opposite infinities; conservatively falling @@ -275,16 +236,13 @@ AlignedFieldFilter::Literal AlignedFieldFilter::Literal::string( } AlignedFieldFilter::AlignedFieldFilter(Kind kind, std::string column, - CompareOp op, Literal literal, - bool negated) - : kind_(kind), + CompareOp op, Literal literal) + : TablePredicate(kind, op), column_(std::move(column)), - compare_op_(op), - literal_(std::move(literal)), - negated_(negated) {} + literal_(std::move(literal)) {} AlignedFieldFilter::AlignedFieldFilter(Kind kind, Ptr left, Ptr right) - : kind_(kind), left_(std::move(left)), right_(std::move(right)) {} + : TablePredicate(kind, std::move(left), std::move(right)) {} AlignedFieldFilter::Ptr AlignedFieldFilter::compare(std::string column, CompareOp op, @@ -317,50 +275,12 @@ AlignedFieldFilter::Ptr AlignedFieldFilter::or_filter(Ptr left, Ptr right) { } AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { - return negate(std::move(child)); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::negate(Ptr node) { - if (node == nullptr) { - // Preserve the invalid operand so query validation cannot mistake - // this predicate for the optional "no FIELD filter" argument. - return Ptr(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); + if (child && child->kind() == Kind::NOT) { + // Keep NOT(NULL operand) invalid across repeated negations. + if (!child->left_) return child; + return Ptr(static_cast(child->left_.release())); } - switch (node->kind_) { - case Kind::COMPARISON: { - // The literal type does not identify the column type: an integer - // constant can bind to a floating-point column. Preserve ordered - // negation until binding so NOT (NaN < 5) remains true, while NULL - // remains unknown. Equality can still flip its operator directly. - const bool ordered = node->compare_op_ == CompareOp::LT || - node->compare_op_ == CompareOp::LE || - node->compare_op_ == CompareOp::GT || - node->compare_op_ == CompareOp::GE; - if (ordered) { - return Ptr(new AlignedFieldFilter( - Kind::COMPARISON, node->column_, node->compare_op_, - node->literal_, !node->negated_)); - } - return Ptr(new AlignedFieldFilter( - Kind::COMPARISON, node->column_, - negate_comparison(node->compare_op_), node->literal_)); - } - case Kind::IS_NULL: - return is_not_null(node->column_); - case Kind::IS_NOT_NULL: - return is_null(node->column_); - case Kind::NOT: - // Only invalid markers remain after NOT pushdown. Repeated - // negation must preserve them instead of erasing an invalid tree. - return node; - case Kind::AND: - return or_filter(negate(std::move(node->left_)), - negate(std::move(node->right_))); - case Kind::OR: - return and_filter(negate(std::move(node->left_)), - negate(std::move(node->right_))); - } - return node; + return Ptr(new AlignedFieldFilter(Kind::NOT, std::move(child), nullptr)); } std::vector AlignedFieldFilter::referenced_columns() const { @@ -379,8 +299,8 @@ std::vector AlignedFieldFilter::referenced_columns() const { } continue; } - if (node->right_) stack.push_back(node->right_.get()); - if (node->left_) stack.push_back(node->left_.get()); + if (node->right_) stack.push_back(node->right_field()); + if (node->left_) stack.push_back(node->left_field()); } return columns; } @@ -392,74 +312,93 @@ bool AlignedFieldFilter::is_valid() const { case Kind::IS_NOT_NULL: return true; case Kind::NOT: - // Valid NOTs are pushed to leaves; only invalid markers remain. + return left_ && left_field()->is_valid(); + case Kind::BETWEEN: + case Kind::NOT_BETWEEN: + case Kind::REGEXP: + case Kind::NOT_REGEXP: + case Kind::CUSTOM: return false; case Kind::AND: case Kind::OR: - return left_ != nullptr && right_ != nullptr && left_->is_valid() && - right_->is_valid(); + return left_ != nullptr && right_ != nullptr && + left_field()->is_valid() && right_field()->is_valid(); } return false; } int AlignedFieldFilter::bind(TableSchema& schema) { - if (kind_ == Kind::NOT) return common::E_INVALID_ARG; + if (kind_ == Kind::NOT) { + return left_ + ? static_cast(left_.get())->bind(schema) + : common::E_INVALID_ARG; + } if (kind_ == Kind::AND || kind_ == Kind::OR) { if (!left_ || !right_) return common::E_INVALID_ARG; - const int ret = left_->bind(schema); + const int ret = + static_cast(left_.get())->bind(schema); if (ret != common::E_OK) return ret; - return right_->bind(schema); + return static_cast(right_.get())->bind(schema); } const common::ColumnSchema column = schema.get_column_schema(column_); if (!column.is_valid()) return common::E_COLUMN_NOT_EXIST; if (column.column_category_ != common::ColumnCategory::FIELD) return common::E_INVALID_ARG; if (kind_ != Kind::COMPARISON) return common::E_OK; - const int ret = bind_literal(literal_, column.data_type_); - if (ret != common::E_OK) return ret; - // Integral, Boolean, and string columns have no NaN values. Canonicalize - // their bound operators once, retaining the existing execution fast path. - if (negated_ && column.data_type_ != common::FLOAT && - column.data_type_ != common::DOUBLE) { - compare_op_ = negate_comparison(compare_op_); - negated_ = false; - } - return common::E_OK; + return bind_literal(literal_, column.data_type_); } bool AlignedFieldFilter::may_match( const std::map& statistics, int64_t row_count) const { - if (kind_ == Kind::AND) { - return !left_ || !right_ || - (left_->may_match(statistics, row_count) && - right_->may_match(statistics, row_count)); - } - if (kind_ == Kind::OR) { - return !left_ || !right_ || - (left_->may_match(statistics, row_count) || - right_->may_match(statistics, row_count)); - } + return page_matches(statistics, row_count, false, false); +} + +bool AlignedFieldFilter::all_match( + const std::map& statistics, + int64_t row_count) const { + return page_matches(statistics, row_count, true, false); +} + +bool AlignedFieldFilter::page_matches( + const std::map& statistics, int64_t row_count, + bool require_all, bool negated) const { if (kind_ == Kind::NOT) { - // NOT can be pushed down to leaves in a future planner. Until then, - // never use page statistics to prune a negated predicate. - return true; + return left_ ? left_field()->page_matches(statistics, row_count, + require_all, !negated) + : !require_all; + } + if (kind_ == Kind::AND || kind_ == Kind::OR) { + if (!left_ || !right_) return !require_all; + const bool lhs = left_field()->page_matches(statistics, row_count, + require_all, negated); + if ((kind_ == Kind::AND) != negated) { + return lhs && right_field()->page_matches(statistics, row_count, + require_all, negated); + } + return lhs || right_field()->page_matches(statistics, row_count, + require_all, negated); } + return require_all ? leaf_all_match(statistics, row_count, negated) + : leaf_may_match(statistics, row_count, negated); +} +bool AlignedFieldFilter::leaf_may_match( + const std::map& statistics, int64_t row_count, + bool negated) const { const auto found = statistics.find(column_); if (found == statistics.end() || found->second == nullptr) return true; Statistic* statistic = found->second; - if (kind_ == Kind::IS_NULL) { - return row_count <= 0 || statistic->count_ < row_count; - } - if (kind_ == Kind::IS_NOT_NULL) { - return statistic->count_ > 0; + if (kind_ == Kind::IS_NULL || kind_ == Kind::IS_NOT_NULL) { + const bool selects_null = (kind_ == Kind::IS_NULL) != negated; + return selects_null ? (row_count <= 0 || statistic->count_ < row_count) + : statistic->count_ > 0; } if (statistic->count_ <= 0) return false; if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT32) return true; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ <= literal_.int32_value && literal_.int32_value <= typed->max_value_; @@ -479,7 +418,7 @@ bool AlignedFieldFilter::may_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT64) return true; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ <= literal_.int64_value && literal_.int64_value <= typed->max_value_; @@ -499,12 +438,13 @@ bool AlignedFieldFilter::may_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::FLOAT || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.float_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.float_value))) return true; // Complementing an ordered operator is safe only when neither the // page nor the literal can contain NaN. const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ <= literal_.float_value && @@ -525,10 +465,11 @@ bool AlignedFieldFilter::may_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::DOUBLE || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.double_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.double_value))) return true; const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ <= literal_.double_value && @@ -550,36 +491,16 @@ bool AlignedFieldFilter::may_match( return true; } -bool AlignedFieldFilter::all_match( - const std::map& statistics, - int64_t row_count) const { - if (row_count <= 0) return false; - if (kind_ == Kind::AND) { - return left_ && right_ && left_->all_match(statistics, row_count) && - right_->all_match(statistics, row_count); - } - if (kind_ == Kind::OR) { - // Both operands are required: a half-built OR must fall through to - // row evaluation, which reports E_INVALID_ARG, instead of matching a - // page through its remaining operand as a full-page pass. - return left_ && right_ && - (left_->all_match(statistics, row_count) || - right_->all_match(statistics, row_count)); - } - if (kind_ == Kind::NOT) { - // Physical plans may keep a NOT node for now. Do not infer a - // page-wide match from its child statistics. - return false; - } - +bool AlignedFieldFilter::leaf_all_match( + const std::map& statistics, int64_t row_count, + bool negated) const { const auto found = statistics.find(column_); if (found == statistics.end() || found->second == nullptr) return false; Statistic* statistic = found->second; - if (kind_ == Kind::IS_NULL) { - return statistic->count_ == 0; - } - if (kind_ == Kind::IS_NOT_NULL) { - return statistic->count_ == row_count; + if (kind_ == Kind::IS_NULL || kind_ == Kind::IS_NOT_NULL) { + const bool selects_null = (kind_ == Kind::IS_NULL) != negated; + return selects_null ? statistic->count_ == 0 + : statistic->count_ == row_count; } // Ordinary comparisons do not match NULL. A page-wide match requires that // every row has a non-NULL value and that the whole min/max range passes. @@ -587,7 +508,7 @@ bool AlignedFieldFilter::all_match( if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT32) return false; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ == literal_.int32_value && typed->max_value_ == literal_.int32_value; @@ -606,7 +527,7 @@ bool AlignedFieldFilter::all_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT64) return false; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ == literal_.int64_value && typed->max_value_ == literal_.int64_value; @@ -625,10 +546,11 @@ bool AlignedFieldFilter::all_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::FLOAT || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.float_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.float_value))) return false; const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ == literal_.float_value && @@ -648,10 +570,11 @@ bool AlignedFieldFilter::all_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::DOUBLE || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.double_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.double_value))) return false; const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ == literal_.double_value && @@ -680,62 +603,12 @@ int AlignedFieldFilter::evaluate(common::TsBlock& block, column_index[column_names[i]] = i + 1; } - struct Frame { - const AlignedFieldFilter* node; - uint8_t state; - }; - std::vector traversal; - std::vector postorder; - traversal.push_back({this, 0}); - while (!traversal.empty()) { - Frame& frame = traversal.back(); - const AlignedFieldFilter* node = frame.node; - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - postorder.push_back(node); - traversal.pop_back(); - } else if (node->kind_ == Kind::NOT) { - // Inverting a one-bit mask would incorrectly select NULL rows. - // Factory-built NOTs have already been pushed to the leaves. - return common::E_INVALID_ARG; - } else { - if (!node->left_ || !node->right_) return common::E_INVALID_ARG; - if (frame.state == 0) { - frame.state = 1; - traversal.push_back({node->left_.get(), 0}); - } else if (frame.state == 1) { - frame.state = 2; - traversal.push_back({node->right_.get(), 0}); - } else { - postorder.push_back(node); - traversal.pop_back(); - } - } - } - - std::vector masks; - masks.reserve(postorder.size()); - for (const auto* node : postorder) { - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - SelectionMask leaf_mask(block.get_row_count()); - int ret = node->evaluate_leaf(block, column_index, leaf_mask); - if (ret != common::E_OK) return ret; - masks.push_back(std::move(leaf_mask)); - } else { - if (masks.size() < 2) return common::E_INVALID_ARG; - SelectionMask right = std::move(masks.back()); - masks.pop_back(); - if (node->kind_ == Kind::AND) { - masks.back().and_with(right); - } else { - masks.back().or_with(right); - } - } - } - if (masks.size() != 1) return common::E_INVALID_ARG; - mask = std::move(masks.back()); - return common::E_OK; + return evaluate_tree(block.get_row_count(), mask, + [&](const AlignedFieldFilter& leaf, bool negated, + SelectionMask& result) { + return leaf.evaluate_leaf(block, column_index, + negated, result); + }); } int AlignedFieldFilter::evaluate_columns(const std::vector& columns, @@ -746,68 +619,62 @@ int AlignedFieldFilter::evaluate_columns(const std::vector& columns, column_index[columns[i].name] = i; } + return evaluate_tree(row_count, mask, + [&](const AlignedFieldFilter& leaf, bool negated, + SelectionMask& result) -> int { + const auto found = column_index.find(leaf.column_); + if (found == column_index.end()) + return common::E_COLUMN_NOT_EXIST; + return leaf.evaluate_leaf(columns[found->second], + row_count, negated, + result); + }); +} + +// Carry NOT down to the comparison. Complementing a completed one-bit mask +// would also select NULL rows; only non-null comparisons may be inverted. +template +int AlignedFieldFilter::evaluate_tree(uint32_t row_count, SelectionMask& mask, + EvaluateLeaf evaluate_leaf) const { struct Frame { const AlignedFieldFilter* node; - uint8_t state; + bool negated; + bool combine; }; - std::vector traversal{{this, 0}}; - std::vector postorder; - while (!traversal.empty()) { - Frame& frame = traversal.back(); - const AlignedFieldFilter* node = frame.node; - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - postorder.push_back(node); - traversal.pop_back(); - } else if (node->kind_ == Kind::NOT) { - // Inverting a one-bit mask would incorrectly select NULL rows. - // Factory-built NOTs have already been pushed to the leaves. - return common::E_INVALID_ARG; - } else { - if (!node->left_ || !node->right_) return common::E_INVALID_ARG; - if (frame.state == 0) { - frame.state = 1; - traversal.push_back({node->left_.get(), 0}); - } else if (frame.state == 1) { - frame.state = 2; - traversal.push_back({node->right_.get(), 0}); + std::vector pending{{this, false, false}}; + std::vector results; + while (!pending.empty()) { + const Frame frame = pending.back(); + pending.pop_back(); + const auto* node = frame.node; + if (!node) return common::E_INVALID_ARG; + if (frame.combine) { + SelectionMask rhs = std::move(results.back()); + results.pop_back(); + if ((node->kind_ == Kind::AND) != frame.negated) { + results.back().and_with(rhs); } else { - postorder.push_back(node); - traversal.pop_back(); + results.back().or_with(rhs); } - } - } - - std::vector masks; - masks.reserve(postorder.size()); - for (const auto* node : postorder) { - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - const auto found = column_index.find(node->column_); - if (found == column_index.end()) return common::E_COLUMN_NOT_EXIST; - SelectionMask leaf_mask(row_count); - int ret = node->evaluate_leaf(columns[found->second], row_count, - leaf_mask); - if (ret != common::E_OK) return ret; - masks.push_back(std::move(leaf_mask)); + } else if (node->kind_ == Kind::NOT) { + pending.push_back({node->left_field(), !frame.negated, false}); + } else if (node->kind_ == Kind::AND || node->kind_ == Kind::OR) { + if (!node->left_ || !node->right_) return common::E_INVALID_ARG; + pending.push_back({node, frame.negated, true}); + pending.push_back({node->right_field(), frame.negated, false}); + pending.push_back({node->left_field(), frame.negated, false}); } else { - if (masks.size() < 2) return common::E_INVALID_ARG; - SelectionMask right = std::move(masks.back()); - masks.pop_back(); - if (node->kind_ == Kind::AND) { - masks.back().and_with(right); - } else { - masks.back().or_with(right); - } + results.emplace_back(row_count); + const int ret = evaluate_leaf(*node, frame.negated, results.back()); + if (ret != common::E_OK) return ret; } } - if (masks.size() != 1) return common::E_INVALID_ARG; - mask = std::move(masks.back()); + mask = std::move(results.back()); return common::E_OK; } int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, - uint32_t row_count, + uint32_t row_count, bool negated, SelectionMask& mask) const { if (column.type == common::INVALID_DATATYPE) return common::E_INVALID_ARG; if ((column.notnull_bitmap != nullptr && @@ -855,9 +722,9 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, bool satisfied = false; if (kind_ == Kind::IS_NULL) { - satisfied = is_null; + satisfied = is_null != negated; } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = !is_null; + satisfied = is_null == negated; } else if (!is_null) { if (column.type == common::BOOLEAN && literal_.type == common::BOOLEAN) { @@ -893,13 +760,13 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, compare_values(value, literal_.double_value, compare_op_); } else if (is_string_type(column.type) && is_string_type(literal_.type)) { - satisfied = compare_string(data, len, literal_.string_value, - compare_op_); + satisfied = compare_values(std::string(data, len), + literal_.string_value, compare_op_); } else { return common::E_NOT_SUPPORT; } // NULL never satisfies a comparison, negated or not. - if (negated_) satisfied = !satisfied; + if (negated) satisfied = !satisfied; } if (satisfied) mask.set_one(row); } @@ -908,7 +775,7 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, int AlignedFieldFilter::evaluate_leaf( common::TsBlock& block, const std::map& column_index, - SelectionMask& mask) const { + bool negated, SelectionMask& mask) const { const auto found = column_index.find(column_); if (found == column_index.end()) return common::E_COLUMN_NOT_EXIST; @@ -926,9 +793,9 @@ int AlignedFieldFilter::evaluate_leaf( bool satisfied = false; if (kind_ == Kind::IS_NULL) { - satisfied = is_null; + satisfied = is_null != negated; } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = !is_null; + satisfied = is_null == negated; } else if (!is_null) { if (column_type == common::BOOLEAN && literal_.type == common::BOOLEAN) { @@ -964,13 +831,13 @@ int AlignedFieldFilter::evaluate_leaf( compare_values(value, literal_.double_value, compare_op_); } else if (is_string_type(column_type) && is_string_type(literal_.type)) { - satisfied = compare_string(data, len, literal_.string_value, - compare_op_); + satisfied = compare_values(std::string(data, len), + literal_.string_value, compare_op_); } else { return common::E_NOT_SUPPORT; } // NULL never satisfies a comparison, negated or not. - if (negated_) satisfied = !satisfied; + if (negated) satisfied = !satisfied; } if (satisfied) mask.set_one(row); iter.next(); diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 659d165b2..de621c0a2 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -28,8 +28,8 @@ #include #include "common/tsblock/tsblock.h" -#include "reader/filter/filter.h" #include "reader/filter/selection_mask.h" +#include "reader/filter/table_predicate.h" namespace storage { class TableSchema; @@ -38,12 +38,8 @@ class TableSchema; // pruning when possible; non-aligned sources use the table reader's timestamp // merge and typed row evaluation. Mixed-device files may use both paths. // It deliberately does not implement TableFieldFilter::satisfy_row(). -class AlignedFieldFilter : public Filter { +class AlignedFieldFilter : public TablePredicate { public: - enum class Kind { COMPARISON, IS_NULL, IS_NOT_NULL, AND, OR, NOT }; - - enum class CompareOp { EQ, NE, LT, LE, GT, GE }; - struct ColumnView { std::string name; common::TSDataType type = common::INVALID_DATATYPE; @@ -87,11 +83,8 @@ class AlignedFieldFilter : public Filter { static Ptr or_filter(Ptr left, Ptr right); static Ptr not_filter(Ptr child); - Kind kind() const { return kind_; } - CompareOp compare_op() const { return compare_op_; } const std::string& column() const { return column_; } const Literal& literal() const { return literal_; } - std::vector referenced_columns() const; // False when a composite node is missing one of its operands. Callers use @@ -123,29 +116,33 @@ class AlignedFieldFilter : public Filter { private: AlignedFieldFilter(Kind kind, std::string column, CompareOp op, - Literal literal, bool negated = false); + Literal literal); AlignedFieldFilter(Kind kind, Ptr left, Ptr right); - // Push NOT down to the leaves so negation keeps SQL three-valued NULL - // semantics; a single SelectionMask bit cannot represent NULL vs FALSE. - static Ptr negate(Ptr node); + const AlignedFieldFilter* left_field() const { + return static_cast(left()); + } + const AlignedFieldFilter* right_field() const { + return static_cast(right()); + } + + bool page_matches(const std::map& statistics, + int64_t row_count, bool require_all, bool negated) const; + bool leaf_may_match(const std::map& statistics, + int64_t row_count, bool negated) const; + bool leaf_all_match(const std::map& statistics, + int64_t row_count, bool negated) const; + + template + int evaluate_tree(uint32_t row_count, SelectionMask& mask, + EvaluateLeaf evaluate_leaf) const; int evaluate_leaf(common::TsBlock& block, const std::map& column_index, - SelectionMask& mask) const; + bool negated, SelectionMask& mask) const; int evaluate_leaf(const ColumnView& column, uint32_t row_count, - SelectionMask& mask) const; - Kind kind_; + bool negated, SelectionMask& mask) const; std::string column_; - CompareOp compare_op_ = CompareOp::EQ; Literal literal_; - // True when this leaf negates an ordered comparison. Preserve it until - // binding identifies the column type. Flipping the operator is not - // equivalent for FLOAT/DOUBLE: NaN makes - // every ordered comparison false, so the negation must be evaluated as - // !(value literal). NULL still never satisfies either form. - bool negated_ = false; - Ptr left_; - Ptr right_; }; } // namespace storage diff --git a/cpp/src/reader/filter/table_predicate.h b/cpp/src/reader/filter/table_predicate.h new file mode 100644 index 000000000..8f627c206 --- /dev/null +++ b/cpp/src/reader/filter/table_predicate.h @@ -0,0 +1,90 @@ +/* + * 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. + */ + +#ifndef READER_FILTER_TABLE_PREDICATE_H +#define READER_FILTER_TABLE_PREDICATE_H + +#include +#include + +#include "reader/filter/filter.h" + +namespace storage { + +// An operator tree for table predicates. The two builders supply different +// bound operands: a device-ID segment for TAG and a typed column for FIELD. +class TablePredicate : public Filter { + public: + enum class Kind { + COMPARISON, + IS_NULL, + IS_NOT_NULL, + AND, + OR, + NOT, + BETWEEN, + NOT_BETWEEN, + REGEXP, + NOT_REGEXP, + CUSTOM + }; + enum class CompareOp { EQ, NE, LT, LE, GT, GE }; + + Kind kind() const { return kind_; } + CompareOp compare_op() const { return compare_op_; } + const TablePredicate* left() const { return left_.get(); } + const TablePredicate* right() const { return right_.get(); } + + protected: + explicit TablePredicate(Kind kind, CompareOp op = CompareOp::EQ) + : kind_(kind), compare_op_(op) {} + TablePredicate(Kind kind, std::unique_ptr left, + std::unique_ptr right) + : kind_(kind), + compare_op_(CompareOp::EQ), + left_(std::move(left)), + right_(std::move(right)) {} + + template + static bool compare_values(const T& value, const T& literal, CompareOp op) { + switch (op) { + case CompareOp::EQ: + return value == literal; + case CompareOp::NE: + return value != literal; + case CompareOp::LT: + return value < literal; + case CompareOp::LE: + return value <= literal; + case CompareOp::GT: + return value > literal; + case CompareOp::GE: + return value >= literal; + } + return false; + } + + Kind kind_; + CompareOp compare_op_; + std::unique_ptr left_; + std::unique_ptr right_; +}; + +} // namespace storage +#endif // READER_FILTER_TABLE_PREDICATE_H diff --git a/cpp/src/reader/filter/tag_filter.cc b/cpp/src/reader/filter/tag_filter.cc index 03b8ae785..6c8398b52 100644 --- a/cpp/src/reader/filter/tag_filter.cc +++ b/cpp/src/reader/filter/tag_filter.cc @@ -24,84 +24,79 @@ namespace storage { -// TagFilter base class implementation -TagFilter::TagFilter(int col_idx, std::string tag_value) - : value_(std::move(tag_value)), value2_(""), col_idx_(col_idx) {} +TagFilter::TagFilter(int col_idx, std::string value) + : TagFilter(Kind::CUSTOM, col_idx, std::move(value)) {} + +TagFilter::TagFilter(Kind kind, int col_idx, std::string value, CompareOp op) + : TablePredicate(kind, op), value_(std::move(value)), col_idx_(col_idx) {} + +TagFilter::TagFilter(Kind kind, TagFilter* left, TagFilter* right) + : TablePredicate(kind, std::unique_ptr(left), + std::unique_ptr(right)), + col_idx_(-1) {} TagFilter::~TagFilter() = default; bool TagFilter::satisfyRow(int time, std::vector segments) const { - return satisfyRow(segments); + return satisfyRow(std::move(segments)); } bool TagFilter::satisfyRow(std::vector segments) const { - ASSERT(false); + switch (kind_) { + case Kind::AND: + return left_->satisfyRow(0, segments) && + right_->satisfyRow(0, std::move(segments)); + case Kind::OR: + return left_->satisfyRow(0, segments) || + right_->satisfyRow(0, std::move(segments)); + case Kind::NOT: + return !left_->satisfyRow(0, std::move(segments)); + case Kind::IS_NULL: + return col_idx_ >= segments.size() || !segments[col_idx_]; + case Kind::IS_NOT_NULL: + return col_idx_ < segments.size() && segments[col_idx_]; + case Kind::COMPARISON: + return col_idx_ < segments.size() && segments[col_idx_] && + compare_values(*segments[col_idx_], value_, compare_op_); + case Kind::BETWEEN: + case Kind::NOT_BETWEEN: { + if (col_idx_ >= segments.size() || !segments[col_idx_]) + return false; + const auto& value = *segments[col_idx_]; + const bool between = compare_values(value, value_, CompareOp::GE) && + compare_values(value, value2_, CompareOp::LE); + return kind_ == Kind::BETWEEN ? between : !between; + } + case Kind::REGEXP: + case Kind::NOT_REGEXP: + case Kind::CUSTOM: + ASSERT(false); + return false; + } return false; } -// TagEq implementation -TagEq::TagEq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagEq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] == value_; -} +TagEq::TagEq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::EQ) {} -// TagNeq implementation -TagNeq::TagNeq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} +TagNeq::TagNeq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::NE) {} -bool TagNeq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] != value_; -} +TagLt::TagLt(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::LT) {} -// TagLt implementation -TagLt::TagLt(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} +TagLteq::TagLteq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::LE) {} -bool TagLt::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] < value_; -} +TagGt::TagGt(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::GT) {} -// TagLteq implementation -TagLteq::TagLteq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagLteq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] <= value_; -} - -// TagGt implementation -TagGt::TagGt(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagGt::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] > value_; -} - -// TagGteq implementation -TagGteq::TagGteq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagGteq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] >= value_; -} +TagGteq::TagGteq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::GE) {} // TagRegExp implementation TagRegExp::TagRegExp(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) { + : TagFilter(Kind::REGEXP, col_idx, std::move(tag_value)) { try { pattern_ = std::regex(value_); is_valid_pattern_ = true; @@ -123,7 +118,7 @@ bool TagRegExp::satisfyRow(std::vector segments) const { // TagNotRegExp implementation TagNotRegExp::TagNotRegExp(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) { + : TagFilter(Kind::NOT_REGEXP, col_idx, std::move(tag_value)) { try { pattern_ = std::regex(value_); is_valid_pattern_ = true; @@ -143,84 +138,29 @@ bool TagNotRegExp::satisfyRow(std::vector segments) const { } } -// TagIsNull implementation -TagIsNull::TagIsNull(int col_idx) : TagFilter(col_idx, "") {} - -bool TagIsNull::satisfyRow(std::vector segments) const { - // A tag is null when its segment is an explicit null pointer or when the - // device id omits the (trailing) segment entirely. - return col_idx_ >= segments.size() || segments[col_idx_] == nullptr; -} - -// TagIsNotNull implementation -TagIsNotNull::TagIsNotNull(int col_idx) : TagFilter(col_idx, "") {} - -bool TagIsNotNull::satisfyRow(std::vector segments) const { - return col_idx_ < segments.size() && segments[col_idx_] != nullptr; -} +TagIsNull::TagIsNull(int col_idx) : TagFilter(Kind::IS_NULL, col_idx, "") {} +TagIsNotNull::TagIsNotNull(int col_idx) + : TagFilter(Kind::IS_NOT_NULL, col_idx, "") {} // TagBetween implementation TagBetween::TagBetween(int col_idx, std::string lower_value, std::string upper_value) - : TagFilter(col_idx, std::move(lower_value)) { + : TagFilter(Kind::BETWEEN, col_idx, std::move(lower_value)) { value2_ = std::move(upper_value); } -bool TagBetween::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - const std::string& segment_value = *segments[col_idx_]; - return segment_value >= value_ && segment_value <= value2_; -} - // TagNotBetween implementation TagNotBetween::TagNotBetween(int col_idx, std::string lower_value, std::string upper_value) - : TagFilter(col_idx, std::move(lower_value)) { + : TagFilter(Kind::NOT_BETWEEN, col_idx, std::move(lower_value)) { value2_ = std::move(upper_value); } -bool TagNotBetween::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - const std::string& segment_value = *segments[col_idx_]; - return segment_value < value_ || segment_value > value2_; -} - -// TagAnd implementation TagAnd::TagAnd(TagFilter* left, TagFilter* right) - : TagFilter(-1, ""), left_(left), right_(right) {} - -TagAnd::~TagAnd() { - delete left_; - delete right_; -} - -bool TagAnd::satisfyRow(std::vector segments) const { - return left_->satisfyRow(segments) && right_->satisfyRow(segments); -} - -// TagOr implementation + : TagFilter(Kind::AND, left, right) {} TagOr::TagOr(TagFilter* left, TagFilter* right) - : TagFilter(-1, ""), left_(left), right_(right) {} - -TagOr::~TagOr() { - delete left_; - delete right_; -} - -bool TagOr::satisfyRow(std::vector segments) const { - return left_->satisfyRow(segments) || right_->satisfyRow(segments); -} - -// TagNot implementation -TagNot::TagNot(TagFilter* filter) : TagFilter(-1, ""), filter_(filter) {} - -TagNot::~TagNot() { delete filter_; } - -bool TagNot::satisfyRow(std::vector segments) const { - return !filter_->satisfyRow(segments); -} + : TagFilter(Kind::OR, left, right) {} +TagNot::TagNot(TagFilter* child) : TagFilter(Kind::NOT, child, nullptr) {} // TagFilterBuilder implementation TagFilterBuilder::TagFilterBuilder(TableSchema* schema) @@ -311,17 +251,22 @@ Filter* TagFilterBuilder::not_between_and(const std::string& columnName, } Filter* TagFilterBuilder::and_filter(Filter* left, Filter* right) { - return new TagAnd(dynamic_cast(left), - dynamic_cast(right)); + auto* lhs = dynamic_cast(left); + auto* rhs = dynamic_cast(right); + if (!lhs || !rhs || lhs == rhs) return nullptr; + return new TagAnd(lhs, rhs); } Filter* TagFilterBuilder::or_filter(Filter* left, Filter* right) { - return new TagOr(dynamic_cast(left), - dynamic_cast(right)); + auto* lhs = dynamic_cast(left); + auto* rhs = dynamic_cast(right); + if (!lhs || !rhs || lhs == rhs) return nullptr; + return new TagOr(lhs, rhs); } Filter* TagFilterBuilder::not_filter(Filter* filter) { - return new TagNot(dynamic_cast(filter)); + auto* child = dynamic_cast(filter); + return child ? new TagNot(child) : nullptr; } int TagFilterBuilder::get_tag_column_index(const std::string& columnName) { diff --git a/cpp/src/reader/filter/tag_filter.h b/cpp/src/reader/filter/tag_filter.h index 50c750d44..2e22bb328 100644 --- a/cpp/src/reader/filter/tag_filter.h +++ b/cpp/src/reader/filter/tag_filter.h @@ -20,17 +20,17 @@ #ifndef READER_FILTER_TAG_FILTER_H #define READER_FILTER_TAG_FILTER_H -#include +#include #include #include #include "common/allocator/my_string.h" #include "common/schema.h" -#include "reader/filter/filter.h" +#include "reader/filter/table_predicate.h" struct table_schema; namespace storage { -class TagFilter : public Filter { +class TagFilter : public TablePredicate { public: TagFilter(int col_idx, std::string tag_value); ~TagFilter() override; @@ -42,48 +42,47 @@ class TagFilter : public Filter { std::string value_; std::string value2_; // For range queries int col_idx_; + + protected: + TagFilter(Kind kind, int col_idx, std::string value, + CompareOp op = CompareOp::EQ); + TagFilter(Kind kind, TagFilter* left, TagFilter* right); }; // Equality comparison class TagEq : public TagFilter { public: TagEq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Inequality comparison class TagNeq : public TagFilter { public: TagNeq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Less than comparison class TagLt : public TagFilter { public: TagLt(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Less than or equal comparison class TagLteq : public TagFilter { public: TagLteq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Greater than comparison class TagGt : public TagFilter { public: TagGt(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Greater than or equal comparison class TagGteq : public TagFilter { public: TagGteq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Regular expression match @@ -111,21 +110,18 @@ class TagNotRegExp : public TagFilter { class TagIsNull : public TagFilter { public: explicit TagIsNull(int col_idx); - bool satisfyRow(std::vector segments) const override; }; // IS NOT NULL: tag column has a concrete value for this device. class TagIsNotNull : public TagFilter { public: explicit TagIsNotNull(int col_idx); - bool satisfyRow(std::vector segments) const override; }; // Range query [value_, value2_] class TagBetween : public TagFilter { public: TagBetween(int col_idx, std::string lower_value, std::string upper_value); - bool satisfyRow(std::vector segments) const override; }; // Not in range @@ -133,42 +129,24 @@ class TagNotBetween : public TagFilter { public: TagNotBetween(int col_idx, std::string lower_value, std::string upper_value); - bool satisfyRow(std::vector segments) const override; }; // Logical AND operation (binary) class TagAnd : public TagFilter { public: TagAnd(TagFilter* left, TagFilter* right); - ~TagAnd() override; - bool satisfyRow(std::vector segments) const override; - - private: - TagFilter* left_; - TagFilter* right_; }; // Logical OR operation (binary) class TagOr : public TagFilter { public: TagOr(TagFilter* left, TagFilter* right); - ~TagOr() override; - bool satisfyRow(std::vector segments) const override; - - private: - TagFilter* left_; - TagFilter* right_; }; // Logical NOT operation class TagNot : public TagFilter { public: explicit TagNot(TagFilter* filter); - ~TagNot() override; - bool satisfyRow(std::vector segments) const override; - - private: - TagFilter* filter_; }; class TagFilterBuilder { diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/aligned_field_filter_test.cc index cb5a20040..da0636988 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/aligned_field_filter_test.cc @@ -59,6 +59,25 @@ TEST(AlignedFieldFilterTest, MissingNotOperandsStayInvalidAfterRewriting) { } } +TEST(AlignedFieldFilterTest, AlternatingNotPreservesNullSemanticsAfterBinding) { + using A = AlignedFieldFilter; + const int levels = 32; + auto expr = A::is_null("v"); + for (int height = 1; height < levels; ++height) { + expr = A::not_filter(A::and_filter(std::move(expr), A::is_null("v"))); + } + ASSERT_TRUE(expr->is_valid()); + TableSchema schema("t", {{"v", common::INT64, common::UNCOMPRESSED, + common::PLAIN, common::ColumnCategory::FIELD}}); + ASSERT_EQ(common::E_OK, expr->bind(schema)); + A::ColumnView v; + v.name = "v"; + v.type = common::INT64; + SelectionMask mask; + ASSERT_EQ(common::E_OK, expr->evaluate_columns({v}, 1, mask)); + EXPECT_EQ((levels % 2) == 1, mask.test(0)); +} + TEST(AlignedFieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { using namespace common; using A = AlignedFieldFilter; diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index 923bb920a..8c9450846 100644 --- a/cpp/test/reader/filter/tag_filter_test.cc +++ b/cpp/test/reader/filter/tag_filter_test.cc @@ -22,6 +22,7 @@ #include #include "common/schema.h" +#include "reader/filter/aligned_field_filter.h" using namespace storage; @@ -497,4 +498,40 @@ TEST_F(TagFilterTest, TagIsNotNullFilter) { delete filter; delete trailing; -} \ No newline at end of file +} +TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { + using Field = AlignedFieldFilter; + using Kind = TablePredicate::Kind; + std::unique_ptr tag( + builder_->not_filter(builder_->eq("name", "x"))); + auto field = Field::not_filter(Field::compare("name", Field::CompareOp::EQ, + Field::Literal::string("x"))); + + const auto* tag_expr = dynamic_cast(tag.get()); + ASSERT_NE(nullptr, tag_expr); + for (const TablePredicate* expr : + {tag_expr, static_cast(field.get())}) { + EXPECT_EQ(Kind::NOT, expr->kind()); + ASSERT_NE(nullptr, expr->left()); + EXPECT_EQ(Kind::COMPARISON, expr->left()->kind()); + EXPECT_EQ(TablePredicate::CompareOp::EQ, expr->left()->compare_op()); + } + + EXPECT_TRUE(tag->satisfyRow(0, {})); + EXPECT_TRUE(tag->satisfyRow(0, {nullptr, nullptr})); + Field::ColumnView column; + column.name = "name"; + column.type = common::STRING; + SelectionMask mask; + ASSERT_EQ(common::E_OK, field->evaluate_columns({column}, 1, mask)); + EXPECT_FALSE(mask.test(0)); +} + +TEST_F(TagFilterTest, TagCombinatorsRejectFieldOperandsWithoutTakingOwnership) { + std::unique_ptr tag(builder_->eq("name", "x")); + auto field = AlignedFieldFilter::is_null("name"); + EXPECT_EQ(nullptr, builder_->and_filter(tag.get(), field.get())); + EXPECT_EQ(nullptr, builder_->or_filter(field.get(), tag.get())); + EXPECT_EQ(nullptr, builder_->not_filter(field.get())); + EXPECT_EQ(nullptr, builder_->and_filter(tag.get(), tag.get())); +} diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 4bd8d4378..f6bc0d6e0 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -70,6 +70,16 @@ arguments. TAG values are strings; do not apply a TAG builder to FIELD columns. Do not translate operator names mechanically across bindings: Java additionally exposes LIKE, while current C++/Python expose explicit null predicates. +## C++ table predicates + +`TagFilterBuilder` and `AlignedFieldFilter` use the operator tree in +`cpp/src/reader/filter/table_predicate.h` for comparisons, null tests, and +logical combinations. Pass TAG and FIELD predicates to the corresponding +arguments of `TsFileReader::query` or `queryByRow`. TAG predicates inspect +device-ID segments. FIELD predicates evaluate column values and can use page +statistics to skip reads. For a missing TAG, `NOT(column = x)` matches. +For a NULL FIELD, the same negated comparison excludes the row. + ## Source Anchors - Java: `java/tsfile/src/main/java/org/apache/tsfile/read/filter/factory/TagFilterBuilder.java`, From 6bf86fddc14531ff4b27e0ddce2a8daf435366ed Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 18:33:12 +0800 Subject: [PATCH 02/10] Preserve TAG child dispatch and guard FIELD whole-page matches --- cpp/src/reader/filter/aligned_field_filter.cc | 1 + cpp/src/reader/filter/tag_filter.cc | 10 +++++----- cpp/src/reader/filter/tag_filter.h | 8 ++++++++ .../filter/aligned_field_filter_test.cc | 15 +++++++++++++++ cpp/test/reader/filter/tag_filter_test.cc | 19 +++++++++++++++++++ .../tsfile/references/properties-filters.md | 2 ++ 6 files changed, 50 insertions(+), 5 deletions(-) diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index c4004b14b..f1aa23bf7 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -357,6 +357,7 @@ bool AlignedFieldFilter::may_match( bool AlignedFieldFilter::all_match( const std::map& statistics, int64_t row_count) const { + if (row_count <= 0) return false; return page_matches(statistics, row_count, true, false); } diff --git a/cpp/src/reader/filter/tag_filter.cc b/cpp/src/reader/filter/tag_filter.cc index 6c8398b52..bd3411074 100644 --- a/cpp/src/reader/filter/tag_filter.cc +++ b/cpp/src/reader/filter/tag_filter.cc @@ -44,13 +44,13 @@ bool TagFilter::satisfyRow(int time, std::vector segments) const { bool TagFilter::satisfyRow(std::vector segments) const { switch (kind_) { case Kind::AND: - return left_->satisfyRow(0, segments) && - right_->satisfyRow(0, std::move(segments)); + return left_tag()->satisfyRow(segments) && + right_tag()->satisfyRow(std::move(segments)); case Kind::OR: - return left_->satisfyRow(0, segments) || - right_->satisfyRow(0, std::move(segments)); + return left_tag()->satisfyRow(segments) || + right_tag()->satisfyRow(std::move(segments)); case Kind::NOT: - return !left_->satisfyRow(0, std::move(segments)); + return !left_tag()->satisfyRow(std::move(segments)); case Kind::IS_NULL: return col_idx_ >= segments.size() || !segments[col_idx_]; case Kind::IS_NOT_NULL: diff --git a/cpp/src/reader/filter/tag_filter.h b/cpp/src/reader/filter/tag_filter.h index 2e22bb328..20231b2f1 100644 --- a/cpp/src/reader/filter/tag_filter.h +++ b/cpp/src/reader/filter/tag_filter.h @@ -47,6 +47,14 @@ class TagFilter : public TablePredicate { TagFilter(Kind kind, int col_idx, std::string value, CompareOp op = CompareOp::EQ); TagFilter(Kind kind, TagFilter* left, TagFilter* right); + + private: + const TagFilter* left_tag() const { + return static_cast(left()); + } + const TagFilter* right_tag() const { + return static_cast(right()); + } }; // Equality comparison diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/aligned_field_filter_test.cc index da0636988..ba6ce85ab 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/aligned_field_filter_test.cc @@ -314,6 +314,21 @@ TEST(AlignedFieldFilterTest, PageStatisticsAreConservative) { EXPECT_TRUE(missing->may_match(stats, 5)); } +TEST(AlignedFieldFilterTest, UnknownRowCountCannotProveWholePageMatches) { + using Field = AlignedFieldFilter; + Int64Statistic empty, values; + values.update(1, int64_t(5)); + values.update(2, int64_t(15)); + const std::map stats{{"a", &empty}, + {"b", &values}}; + auto filter = Field::or_filter( + Field::is_not_null("a"), + Field::compare("b", Field::CompareOp::GT, Field::Literal::int64(10))); + + EXPECT_TRUE(filter->may_match(stats, 0)); + EXPECT_FALSE(filter->all_match(stats, 0)); +} + TEST(AlignedFieldFilterTest, PageStatisticsAllMatchIsConservative) { Int64Statistic statistic; statistic.count_ = 5; diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index 8c9450846..a1628ff2d 100644 --- a/cpp/test/reader/filter/tag_filter_test.cc +++ b/cpp/test/reader/filter/tag_filter_test.cc @@ -499,6 +499,25 @@ TEST_F(TagFilterTest, TagIsNotNullFilter) { delete filter; delete trailing; } +TEST_F(TagFilterTest, LogicalOperatorsUseSegmentOverloadForChildren) { + class SegmentEquals : public TagEq { + public: + using TagEq::TagEq; + bool satisfyRow(int, std::vector) const override { + ADD_FAILURE() << "A TAG child should be evaluated by its segments"; + return false; + } + }; + std::string value = "x"; + const std::vector segments{nullptr, &value}; + TagAnd both(new SegmentEquals(1, "x"), new SegmentEquals(1, "x")); + TagOr either(new SegmentEquals(1, "y"), new SegmentEquals(1, "x")); + TagNot negated(new SegmentEquals(1, "x")); + EXPECT_TRUE(both.satisfyRow(0, segments)); + EXPECT_TRUE(either.satisfyRow(0, segments)); + EXPECT_FALSE(negated.satisfyRow(0, segments)); +} + TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { using Field = AlignedFieldFilter; using Kind = TablePredicate::Kind; diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index f6bc0d6e0..5ee10d180 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -79,6 +79,8 @@ arguments of `TsFileReader::query` or `queryByRow`. TAG predicates inspect device-ID segments. FIELD predicates evaluate column values and can use page statistics to skip reads. For a missing TAG, `NOT(column = x)` matches. For a NULL FIELD, the same negated comparison excludes the row. +TAG logical operators call each child's `satisfyRow(segments)` overload. +FIELD page pruning requires a known positive row count to accept a whole page. ## Source Anchors From 6ff3738c2ff1231335f7ebced7579794b9e6b646 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 19:35:22 +0800 Subject: [PATCH 03/10] Bind shared C++ expressions in table and tree queries --- cpp/src/cwrapper/tsfile_cwrapper.cc | 4 +- cpp/src/reader/device_meta_iterator.cc | 4 +- cpp/src/reader/expression.cc | 95 ++++++ cpp/src/reader/expression.h | 75 ++++- cpp/src/reader/filter/aligned_field_filter.cc | 285 +++++++++--------- cpp/src/reader/filter/aligned_field_filter.h | 35 ++- cpp/src/reader/filter/bind_expression.h | 54 ++++ .../{table_predicate.h => bound_predicate.h} | 43 +-- cpp/src/reader/filter/tag_filter.cc | 171 ++++++++--- cpp/src/reader/filter/tag_filter.h | 21 +- cpp/src/reader/qds_without_timegenerator.cc | 161 +++++++--- cpp/src/reader/qds_without_timegenerator.h | 7 + cpp/src/reader/table_query_executor.cc | 152 +++------- cpp/src/reader/table_query_executor.h | 9 + cpp/src/reader/task/device_task_iterator.h | 9 +- cpp/src/reader/tsfile_executor.cc | 36 +++ cpp/src/reader/tsfile_executor.h | 2 + cpp/src/reader/tsfile_reader.cc | 49 ++- cpp/src/reader/tsfile_reader.h | 18 ++ cpp/test/reader/filter/tag_filter_test.cc | 10 +- cpp/test/reader/table_field_filter_test.cc | 61 ++++ cpp/test/reader/tsfile_reader_test.cc | 64 ++++ .../tsfile/references/properties-filters.md | 44 ++- 23 files changed, 1011 insertions(+), 398 deletions(-) create mode 100644 cpp/src/reader/filter/bind_expression.h rename cpp/src/reader/filter/{table_predicate.h => bound_predicate.h} (64%) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index c2e6f2a0d..6f4717931 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -2836,7 +2836,7 @@ ERRNO tsfile_tag_filter_create_checked(TsFileReader reader, if (ret != common::E_OK) { return ret; } - storage::TagFilterBuilder builder(schema.get()); + auto builder = storage::TagFilterBuilder::for_query(schema.get()); storage::Filter* filter = nullptr; switch (op) { case TAG_FILTER_EQ: @@ -2921,7 +2921,7 @@ ERRNO tsfile_tag_filter_between_checked(TsFileReader reader, if (ret != common::E_OK) { return ret; } - storage::TagFilterBuilder builder(schema.get()); + auto builder = storage::TagFilterBuilder::for_query(schema.get()); storage::Filter* filter = is_not ? builder.not_between_and(column_name, lower, upper) : builder.between_and(column_name, lower, upper); diff --git a/cpp/src/reader/device_meta_iterator.cc b/cpp/src/reader/device_meta_iterator.cc index 5fb50dafd..32d6484b4 100644 --- a/cpp/src/reader/device_meta_iterator.cc +++ b/cpp/src/reader/device_meta_iterator.cc @@ -172,8 +172,8 @@ void DeviceMetaIterator::try_setup_direct_lookup(MetaIndexNode* root_node) { if (id_filter_ == nullptr || root_node == nullptr) return; const auto* eq = dynamic_cast(id_filter_); - if (eq == nullptr || eq->kind() != TablePredicate::Kind::COMPARISON || - eq->compare_op() != TablePredicate::CompareOp::EQ || eq->col_idx_ != 1) + if (eq == nullptr || eq->kind() != BoundPredicate::Kind::COMPARISON || + eq->compare_op() != BoundPredicate::CompareOp::EQ || eq->col_idx_ != 1) return; if (root_node->children_.empty()) return; diff --git a/cpp/src/reader/expression.cc b/cpp/src/reader/expression.cc index 3623b390e..2cb1ecbec 100644 --- a/cpp/src/reader/expression.cc +++ b/cpp/src/reader/expression.cc @@ -24,6 +24,101 @@ namespace storage { +Expression::Literal Expression::Literal::boolean(bool value) { + Literal literal; + literal.type = common::BOOLEAN; + literal.bool_value = value; + return literal; +} + +Expression::Literal Expression::Literal::int32(int32_t value) { + Literal literal; + literal.type = common::INT32; + literal.int32_value = value; + return literal; +} + +Expression::Literal Expression::Literal::int64(int64_t value) { + Literal literal; + literal.type = common::INT64; + literal.int64_value = value; + return literal; +} + +Expression::Literal Expression::Literal::float32(float value) { + Literal literal; + literal.type = common::FLOAT; + literal.float_value = value; + return literal; +} + +Expression::Literal Expression::Literal::float64(double value) { + Literal literal; + literal.type = common::DOUBLE; + literal.double_value = value; + return literal; +} + +Expression::Literal Expression::Literal::string(std::string value) { + Literal literal; + literal.type = common::STRING; + literal.string_value = std::move(value); + return literal; +} + +namespace { +Expression::Ptr named(ExpressionType type, std::string reference, + Expression::CompareOp op = Expression::CompareOp::EQ, + Expression::Literal value = {}, + Expression::Literal upper = {}) { + Expression::Ptr node(new Expression(type)); + node->filter_ = new Expression::Operand(std::move(reference), op, + std::move(value), std::move(upper)); + return node; +} +Expression::Ptr logical(ExpressionType type, Expression::Ptr left, + Expression::Ptr right) { + Expression::Ptr node(new Expression(type)); + node->left_ = left.release(); + node->right_ = right.release(); + return node; +} +} // namespace + +Expression::Ptr Expression::compare(std::string reference, CompareOp op, + Literal literal) { + return named(ExpressionType::COMPARISON, std::move(reference), op, + std::move(literal)); +} +Expression::Ptr Expression::is_null(std::string reference) { + return named(ExpressionType::IS_NULL, std::move(reference)); +} +Expression::Ptr Expression::is_not_null(std::string reference) { + return named(ExpressionType::IS_NOT_NULL, std::move(reference)); +} +Expression::Ptr Expression::and_filter(Ptr left, Ptr right) { + return logical(AND_EXPR, std::move(left), std::move(right)); +} +Expression::Ptr Expression::or_filter(Ptr left, Ptr right) { + return logical(OR_EXPR, std::move(left), std::move(right)); +} +Expression::Ptr Expression::not_filter(Ptr child) { + return logical(ExpressionType::NOT, std::move(child), nullptr); +} +Expression::Ptr Expression::between(std::string reference, Literal lower, + Literal upper, bool negated) { + return named( + negated ? ExpressionType::NOT_BETWEEN : ExpressionType::BETWEEN, + std::move(reference), CompareOp::EQ, std::move(lower), + std::move(upper)); +} +Expression::Ptr Expression::regexp(std::string reference, std::string pattern, + bool negated) { + return named(negated ? ExpressionType::NOT_REGEXP : ExpressionType::REGEXP, + std::move(reference), CompareOp::EQ, + Literal::string(std::move(pattern))); +} + void QueryExpression::add_time_filter_to_series_filter( Filter* time_filter, Expression* single_series_expr) { Filter* filter = new AndFilter(single_series_expr->filter_, time_filter); diff --git a/cpp/src/reader/expression.h b/cpp/src/reader/expression.h index 1cf72b6d2..0d6987bbc 100644 --- a/cpp/src/reader/expression.h +++ b/cpp/src/reader/expression.h @@ -19,6 +19,7 @@ #ifndef READER_EXPRESSION_H #define READER_EXPRESSION_H +#include #include #include @@ -35,10 +36,71 @@ enum ExpressionType { OR_EXPR, SERIES_EXPR, GLOBALTIME_EXPR, - INVALID_EXPR + INVALID_EXPR, + COMPARISON, + IS_NULL, + IS_NOT_NULL, + NOT, + BETWEEN, + NOT_BETWEEN, + REGEXP, + NOT_REGEXP, + CUSTOM, + AND = AND_EXPR, + OR = OR_EXPR }; struct Expression { + using Ptr = std::unique_ptr; + enum class CompareOp { EQ, NE, LT, LE, GT, GE }; + struct Literal { + common::TSDataType type = common::INVALID_DATATYPE; + bool bool_value = false; + int32_t int32_value = 0; + int64_t int64_value = 0; + float float_value = 0.0F; + double double_value = 0.0; + std::string string_value; + + static Literal boolean(bool value); + static Literal int32(int32_t value); + static Literal int64(int64_t value); + static Literal float32(float value); + static Literal float64(double value); + static Literal string(std::string value); + }; + + // Named operands retain their spelling and literal until query preparation. + // Table queries resolve column names. Tree queries resolve series paths. + static Ptr compare(std::string reference, CompareOp op, Literal literal); + static Ptr is_null(std::string reference); + static Ptr is_not_null(std::string reference); + static Ptr and_filter(Ptr left, Ptr right); + static Ptr or_filter(Ptr left, Ptr right); + static Ptr not_filter(Ptr child); + static Ptr between(std::string reference, Literal lower, Literal upper, + bool negated = false); + static Ptr regexp(std::string reference, std::string pattern, + bool negated = false); + + // A named leaf uses the existing owned leaf slot. It carries data only; + // readers replace it with a query-local executable filter when binding. + struct Operand final : Filter { + std::string reference; + CompareOp comparison; + Literal literal; + Literal upper; + Operand(std::string name, CompareOp op, Literal value, + Literal upper_bound) + : reference(std::move(name)), + comparison(op), + literal(std::move(value)), + upper(std::move(upper_bound)) {} + }; + const Operand* operand() const { + return dynamic_cast(filter_); + } + ExpressionType type_; Expression* left_; Expression* right_; @@ -79,9 +141,20 @@ struct Expression { right_ = nullptr; } } + Expression(const Expression&) = delete; + Expression& operator=(const Expression&) = delete; ~Expression() { destroy(); } }; +// Borrowed during query preparation. Each result owns its bound filters. +struct TablePredicates { + TablePredicates() : tag_filter(nullptr), field_filter(nullptr) {} + TablePredicates(const Expression* tag, const Expression* field) + : tag_filter(tag), field_filter(field) {} + const Expression* tag_filter; + const Expression* field_filter; +}; + class QueryExpression { public: QueryExpression() : has_filter_(false), expression_(nullptr) {} diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index f1aa23bf7..63a999cb1 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -26,8 +26,10 @@ #include #include +#include "common/row_record.h" #include "common/schema.h" #include "common/statistic.h" +#include "reader/filter/bind_expression.h" namespace storage { namespace { @@ -192,57 +194,14 @@ std::string normalize_column_name(const std::string& column) { } // namespace -AlignedFieldFilter::Literal AlignedFieldFilter::Literal::boolean(bool value) { - Literal literal; - literal.type = common::BOOLEAN; - literal.bool_value = value; - return literal; -} - -AlignedFieldFilter::Literal AlignedFieldFilter::Literal::int32(int32_t value) { - Literal literal; - literal.type = common::INT32; - literal.int32_value = value; - return literal; -} - -AlignedFieldFilter::Literal AlignedFieldFilter::Literal::int64(int64_t value) { - Literal literal; - literal.type = common::INT64; - literal.int64_value = value; - return literal; -} - -AlignedFieldFilter::Literal AlignedFieldFilter::Literal::float32(float value) { - Literal literal; - literal.type = common::FLOAT; - literal.float_value = value; - return literal; -} - -AlignedFieldFilter::Literal AlignedFieldFilter::Literal::float64(double value) { - Literal literal; - literal.type = common::DOUBLE; - literal.double_value = value; - return literal; -} - -AlignedFieldFilter::Literal AlignedFieldFilter::Literal::string( - std::string value) { - Literal literal; - literal.type = common::STRING; - literal.string_value = std::move(value); - return literal; -} - AlignedFieldFilter::AlignedFieldFilter(Kind kind, std::string column, CompareOp op, Literal literal) - : TablePredicate(kind, op), + : BoundPredicate(kind, op), column_(std::move(column)), literal_(std::move(literal)) {} AlignedFieldFilter::AlignedFieldFilter(Kind kind, Ptr left, Ptr right) - : TablePredicate(kind, std::move(left), std::move(right)) {} + : BoundPredicate(kind, std::move(left), std::move(right)) {} AlignedFieldFilter::Ptr AlignedFieldFilter::compare(std::string column, CompareOp op, @@ -283,6 +242,60 @@ AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { return Ptr(new AlignedFieldFilter(Kind::NOT, std::move(child), nullptr)); } +int AlignedFieldFilter::from_expression(const Expression& expr, Ptr& out, + bool table_columns) { + auto leaf = [&](ExpressionType type, const Expression::Operand& operand, + Ptr& result) -> int { + std::string name = table_columns + ? normalize_column_name(operand.reference) + : operand.reference; + switch (type) { + case Kind::IS_NULL: + case Kind::IS_NOT_NULL: + case Kind::COMPARISON: + break; + case ExpressionType::BETWEEN: + case ExpressionType::NOT_BETWEEN: { + Ptr lower(new AlignedFieldFilter( + Kind::COMPARISON, name, CompareOp::GE, operand.literal)); + Ptr upper(new AlignedFieldFilter(Kind::COMPARISON, name, + CompareOp::LE, operand.upper)); + result = and_filter(std::move(lower), std::move(upper)); + if (type == ExpressionType::NOT_BETWEEN) + result = not_filter(std::move(result)); + return common::E_OK; + } + default: + return common::E_NOT_SUPPORT; + } + result.reset(new AlignedFieldFilter( + type, std::move(name), operand.comparison, operand.literal)); + return common::E_OK; + }; + return bind_expression( + expr, out, leaf, [](ExpressionType type, Ptr left, Ptr right) { + if (type == ExpressionType::NOT) return not_filter(std::move(left)); + if (type == AND_EXPR) + return and_filter(std::move(left), std::move(right)); + return or_filter(std::move(left), std::move(right)); + }); +} + +int AlignedFieldFilter::bind_series(const SeriesBindings& bindings) { + if (left_) { + int ret = static_cast(left_.get()) + ->bind_series(bindings); + if (ret != common::E_OK || !right_) return ret; + return static_cast(right_.get()) + ->bind_series(bindings); + } + auto it = bindings.find(column_); + if (it == bindings.end()) return common::E_COLUMN_NOT_EXIST; + series_index_ = it->second.first; + return kind_ == Kind::COMPARISON ? bind_literal(literal_, it->second.second) + : common::E_OK; +} + std::vector AlignedFieldFilter::referenced_columns() const { std::vector columns; std::set seen_columns; @@ -318,6 +331,9 @@ bool AlignedFieldFilter::is_valid() const { case Kind::REGEXP: case Kind::NOT_REGEXP: case Kind::CUSTOM: + case SERIES_EXPR: + case GLOBALTIME_EXPR: + case INVALID_EXPR: return false; case Kind::AND: case Kind::OR: @@ -674,6 +690,81 @@ int AlignedFieldFilter::evaluate_tree(uint32_t row_count, SelectionMask& mask, return common::E_OK; } +int AlignedFieldFilter::evaluate_value(common::TSDataType column_type, + const char* data, uint32_t len, + bool is_null, bool negated, + bool& satisfied) const { + satisfied = false; + if (kind_ == Kind::IS_NULL) { + satisfied = is_null != negated; + } else if (kind_ == Kind::IS_NOT_NULL) { + satisfied = is_null == negated; + } else if (!is_null) { + if (column_type == common::BOOLEAN && + literal_.type == common::BOOLEAN) { + bool value; + std::memcpy(&value, data, sizeof(value)); + satisfied = compare_values(value, literal_.bool_value, compare_op_); + } else if ((column_type == common::INT32 || + column_type == common::DATE) && + literal_.type == common::INT32) { + int32_t value; + std::memcpy(&value, data, sizeof(value)); + satisfied = + compare_values(value, literal_.int32_value, compare_op_); + } else if ((column_type == common::INT64 || + column_type == common::TIMESTAMP) && + literal_.type == common::INT64) { + int64_t value; + std::memcpy(&value, data, sizeof(value)); + satisfied = + compare_values(value, literal_.int64_value, compare_op_); + } else if (column_type == common::FLOAT && + literal_.type == common::FLOAT) { + float value; + std::memcpy(&value, data, sizeof(value)); + satisfied = + compare_values(value, literal_.float_value, compare_op_); + } else if (column_type == common::DOUBLE && + literal_.type == common::DOUBLE) { + double value; + std::memcpy(&value, data, sizeof(value)); + satisfied = + compare_values(value, literal_.double_value, compare_op_); + } else if (is_string_type(column_type) && + is_string_type(literal_.type)) { + satisfied = compare_values(std::string(data ? data : "", len), + literal_.string_value, compare_op_); + } else { + return common::E_NOT_SUPPORT; + } + // NULL never satisfies a comparison, negated or not. + if (negated) satisfied = !satisfied; + } + return common::E_OK; +} + +int AlignedFieldFilter::evaluate_row(const std::vector& fields, + bool& accepted, bool negated) const { + if (kind_ == Kind::NOT) + return left_field()->evaluate_row(fields, accepted, !negated); + if (kind_ == Kind::AND || kind_ == Kind::OR) { + int ret = left_field()->evaluate_row(fields, accepted, negated); + const bool conjunction = (kind_ == Kind::AND) != negated; + if (ret != common::E_OK || accepted != conjunction) return ret; + return right_field()->evaluate_row(fields, accepted, negated); + } + const auto& field = *fields[series_index_]; + const char* data = reinterpret_cast(&field.value_); + uint32_t len = 0; + if (is_string_type(field.type_)) { + data = field.value_.strval_->buf_; + len = field.value_.strval_->len_; + } + return evaluate_value(field.type_, data, len, + field.type_ == common::NULL_TYPE, negated, accepted); +} + int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, uint32_t row_count, bool negated, SelectionMask& mask) const { @@ -721,54 +812,10 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, ++nonnull_index; } - bool satisfied = false; - if (kind_ == Kind::IS_NULL) { - satisfied = is_null != negated; - } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = is_null == negated; - } else if (!is_null) { - if (column.type == common::BOOLEAN && - literal_.type == common::BOOLEAN) { - bool value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.bool_value, compare_op_); - } else if ((column.type == common::INT32 || - column.type == common::DATE) && - literal_.type == common::INT32) { - int32_t value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.int32_value, compare_op_); - } else if ((column.type == common::INT64 || - column.type == common::TIMESTAMP) && - literal_.type == common::INT64) { - int64_t value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.int64_value, compare_op_); - } else if (column.type == common::FLOAT && - literal_.type == common::FLOAT) { - float value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.float_value, compare_op_); - } else if (column.type == common::DOUBLE && - literal_.type == common::DOUBLE) { - double value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.double_value, compare_op_); - } else if (is_string_type(column.type) && - is_string_type(literal_.type)) { - satisfied = compare_values(std::string(data, len), - literal_.string_value, compare_op_); - } else { - return common::E_NOT_SUPPORT; - } - // NULL never satisfies a comparison, negated or not. - if (negated) satisfied = !satisfied; - } + bool satisfied; + const int ret = + evaluate_value(column.type, data, len, is_null, negated, satisfied); + if (ret != common::E_OK) return ret; if (satisfied) mask.set_one(row); } return common::E_OK; @@ -792,54 +839,10 @@ int AlignedFieldFilter::evaluate_leaf( bool is_null = false; char* data = iter.read(&len, &is_null); - bool satisfied = false; - if (kind_ == Kind::IS_NULL) { - satisfied = is_null != negated; - } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = is_null == negated; - } else if (!is_null) { - if (column_type == common::BOOLEAN && - literal_.type == common::BOOLEAN) { - bool value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.bool_value, compare_op_); - } else if ((column_type == common::INT32 || - column_type == common::DATE) && - literal_.type == common::INT32) { - int32_t value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.int32_value, compare_op_); - } else if ((column_type == common::INT64 || - column_type == common::TIMESTAMP) && - literal_.type == common::INT64) { - int64_t value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.int64_value, compare_op_); - } else if (column_type == common::FLOAT && - literal_.type == common::FLOAT) { - float value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.float_value, compare_op_); - } else if (column_type == common::DOUBLE && - literal_.type == common::DOUBLE) { - double value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.double_value, compare_op_); - } else if (is_string_type(column_type) && - is_string_type(literal_.type)) { - satisfied = compare_values(std::string(data, len), - literal_.string_value, compare_op_); - } else { - return common::E_NOT_SUPPORT; - } - // NULL never satisfies a comparison, negated or not. - if (negated) satisfied = !satisfied; - } + bool satisfied; + const int ret = + evaluate_value(column_type, data, len, is_null, negated, satisfied); + if (ret != common::E_OK) return ret; if (satisfied) mask.set_one(row); iter.next(); } diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index de621c0a2..06434a320 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -28,17 +28,18 @@ #include #include "common/tsblock/tsblock.h" +#include "reader/filter/bound_predicate.h" #include "reader/filter/selection_mask.h" -#include "reader/filter/table_predicate.h" namespace storage { class TableSchema; +struct Field; // Column-aware FIELD predicate. Aligned sources use batch evaluation and page // pruning when possible; non-aligned sources use the table reader's timestamp // merge and typed row evaluation. Mixed-device files may use both paths. // It deliberately does not implement TableFieldFilter::satisfy_row(). -class AlignedFieldFilter : public TablePredicate { +class AlignedFieldFilter : public BoundPredicate { public: struct ColumnView { std::string name; @@ -53,25 +54,12 @@ class AlignedFieldFilter : public TablePredicate { uint32_t value_count = 0; }; - struct Literal { - common::TSDataType type = common::INVALID_DATATYPE; - bool bool_value = false; - int32_t int32_value = 0; - int64_t int64_value = 0; - float float_value = 0.0F; - double double_value = 0.0; - std::string string_value; - - static Literal boolean(bool value); - static Literal int32(int32_t value); - static Literal int64(int64_t value); - static Literal float32(float value); - static Literal float64(double value); - static Literal string(std::string value); - }; + using Literal = Expression::Literal; using Ptr = std::unique_ptr; + static int from_expression(const Expression& expr, Ptr& out, + bool table_columns); ~AlignedFieldFilter() override = default; static Ptr compare(std::string column, CompareOp op, Literal literal); @@ -115,6 +103,13 @@ class AlignedFieldFilter : public TablePredicate { uint32_t row_count, SelectionMask& mask) const; private: + friend class QDSWithoutTimeGenerator; + using SeriesBindings = + std::map>; + int bind_series(const SeriesBindings& bindings); + int evaluate_row(const std::vector& fields, bool& accepted, + bool negated = false) const; + AlignedFieldFilter(Kind kind, std::string column, CompareOp op, Literal literal); AlignedFieldFilter(Kind kind, Ptr left, Ptr right); @@ -141,6 +136,10 @@ class AlignedFieldFilter : public TablePredicate { bool negated, SelectionMask& mask) const; int evaluate_leaf(const ColumnView& column, uint32_t row_count, bool negated, SelectionMask& mask) const; + int evaluate_value(common::TSDataType column_type, const char* data, + uint32_t len, bool is_null, bool negated, + bool& satisfied) const; + size_t series_index_ = 0; std::string column_; Literal literal_; }; diff --git a/cpp/src/reader/filter/bind_expression.h b/cpp/src/reader/filter/bind_expression.h new file mode 100644 index 000000000..0a91b0006 --- /dev/null +++ b/cpp/src/reader/filter/bind_expression.h @@ -0,0 +1,54 @@ +/* + * 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. + */ +#ifndef READER_FILTER_BIND_EXPRESSION_H +#define READER_FILTER_BIND_EXPRESSION_H + +#include "reader/expression.h" +#include "utils/errno_define.h" + +namespace storage { + +// Bind the same logical nodes for device IDs, table fields and tree series. +// The leaf binder resolves names and literals for the query's schema. +template +int bind_expression(const Expression& expr, std::unique_ptr& result, + const BindLeaf& bind_leaf, const Combine& combine) { + const auto type = expr.type_; + if (type != AND_EXPR && type != OR_EXPR && type != ExpressionType::NOT) { + const auto* operand = expr.operand(); + if (expr.left_ || expr.right_ || !operand || operand->reference.empty()) + return common::E_INVALID_ARG; + return bind_leaf(type, *operand, result); + } + if (!expr.left_ || + ((type == ExpressionType::NOT) != (expr.right_ == nullptr))) + return common::E_INVALID_ARG; + std::unique_ptr left, right; + int ret = bind_expression(*expr.left_, left, bind_leaf, combine); + if (ret != common::E_OK) return ret; + if (expr.right_) { + ret = bind_expression(*expr.right_, right, bind_leaf, combine); + if (ret != common::E_OK) return ret; + } + result = combine(type, std::move(left), std::move(right)); + return common::E_OK; +} + +} // namespace storage +#endif // READER_FILTER_BIND_EXPRESSION_H diff --git a/cpp/src/reader/filter/table_predicate.h b/cpp/src/reader/filter/bound_predicate.h similarity index 64% rename from cpp/src/reader/filter/table_predicate.h rename to cpp/src/reader/filter/bound_predicate.h index 8f627c206..0f7f004a8 100644 --- a/cpp/src/reader/filter/table_predicate.h +++ b/cpp/src/reader/filter/bound_predicate.h @@ -17,45 +17,32 @@ * under the License. */ -#ifndef READER_FILTER_TABLE_PREDICATE_H -#define READER_FILTER_TABLE_PREDICATE_H +#ifndef READER_FILTER_BOUND_PREDICATE_H +#define READER_FILTER_BOUND_PREDICATE_H #include #include -#include "reader/filter/filter.h" +#include "reader/expression.h" namespace storage { -// An operator tree for table predicates. The two builders supply different -// bound operands: a device-ID segment for TAG and a typed column for FIELD. -class TablePredicate : public Filter { +// Execution nodes use the same operators as the named source expression. +class BoundPredicate : public Filter { public: - enum class Kind { - COMPARISON, - IS_NULL, - IS_NOT_NULL, - AND, - OR, - NOT, - BETWEEN, - NOT_BETWEEN, - REGEXP, - NOT_REGEXP, - CUSTOM - }; - enum class CompareOp { EQ, NE, LT, LE, GT, GE }; + using Kind = ExpressionType; + using CompareOp = Expression::CompareOp; Kind kind() const { return kind_; } CompareOp compare_op() const { return compare_op_; } - const TablePredicate* left() const { return left_.get(); } - const TablePredicate* right() const { return right_.get(); } + const BoundPredicate* left() const { return left_.get(); } + const BoundPredicate* right() const { return right_.get(); } protected: - explicit TablePredicate(Kind kind, CompareOp op = CompareOp::EQ) + explicit BoundPredicate(Kind kind, CompareOp op = CompareOp::EQ) : kind_(kind), compare_op_(op) {} - TablePredicate(Kind kind, std::unique_ptr left, - std::unique_ptr right) + BoundPredicate(Kind kind, std::unique_ptr left, + std::unique_ptr right) : kind_(kind), compare_op_(CompareOp::EQ), left_(std::move(left)), @@ -82,9 +69,9 @@ class TablePredicate : public Filter { Kind kind_; CompareOp compare_op_; - std::unique_ptr left_; - std::unique_ptr right_; + std::unique_ptr left_; + std::unique_ptr right_; }; } // namespace storage -#endif // READER_FILTER_TABLE_PREDICATE_H +#endif // READER_FILTER_BOUND_PREDICATE_H diff --git a/cpp/src/reader/filter/tag_filter.cc b/cpp/src/reader/filter/tag_filter.cc index bd3411074..b5d352bf1 100644 --- a/cpp/src/reader/filter/tag_filter.cc +++ b/cpp/src/reader/filter/tag_filter.cc @@ -22,16 +22,67 @@ #include #include +#include "reader/filter/bind_expression.h" + namespace storage { +int TagFilter::bind(const Expression& expr, TableSchema& schema, + std::unique_ptr& out) { + using Ptr = std::unique_ptr; + auto leaf = [&](ExpressionType type, const Expression::Operand& operand, + Ptr& result) -> int { + const int order = schema.find_id_column_order(operand.reference); + if (order < 0) return common::E_COLUMN_NOT_EXIST; + const int index = order + 1; + if (type == ExpressionType::IS_NULL || + type == ExpressionType::IS_NOT_NULL) { + result.reset(new TagFilter(type, index, "")); + return common::E_OK; + } + if (operand.literal.type != common::STRING) + return common::E_NOT_SUPPORT; + const auto& value = operand.literal.string_value; + if ((type == Kind::BETWEEN || type == Kind::NOT_BETWEEN) && + operand.upper.type != common::STRING) + return common::E_NOT_SUPPORT; + switch (type) { + case ExpressionType::COMPARISON: + result.reset(new TagFilter(Kind::COMPARISON, index, value, + operand.comparison)); + break; + case ExpressionType::BETWEEN: + result.reset( + new TagBetween(index, value, operand.upper.string_value)); + break; + case ExpressionType::NOT_BETWEEN: + result.reset(new TagNotBetween(index, value, + operand.upper.string_value)); + break; + case ExpressionType::REGEXP: + result.reset(new TagRegExp(index, value)); + break; + case ExpressionType::NOT_REGEXP: + result.reset(new TagNotRegExp(index, value)); + break; + default: + return common::E_NOT_SUPPORT; + } + return common::E_OK; + }; + return bind_expression( + expr, out, leaf, [](ExpressionType type, Ptr left, Ptr right) { + return Ptr(new TagFilter(type, left.release(), right.release())); + }); +} + TagFilter::TagFilter(int col_idx, std::string value) : TagFilter(Kind::CUSTOM, col_idx, std::move(value)) {} TagFilter::TagFilter(Kind kind, int col_idx, std::string value, CompareOp op) - : TablePredicate(kind, op), value_(std::move(value)), col_idx_(col_idx) {} + : BoundPredicate(kind, op), value_(std::move(value)), col_idx_(col_idx) {} TagFilter::TagFilter(Kind kind, TagFilter* left, TagFilter* right) - : TablePredicate(kind, std::unique_ptr(left), + : BoundPredicate(kind, std::unique_ptr(left), std::unique_ptr(right)), col_idx_(-1) {} @@ -70,6 +121,9 @@ bool TagFilter::satisfyRow(std::vector segments) const { case Kind::REGEXP: case Kind::NOT_REGEXP: case Kind::CUSTOM: + case SERIES_EXPR: + case GLOBALTIME_EXPR: + case INVALID_EXPR: ASSERT(false); return false; } @@ -166,88 +220,91 @@ TagNot::TagNot(TagFilter* child) : TagFilter(Kind::NOT, child, nullptr) {} TagFilterBuilder::TagFilterBuilder(TableSchema* schema) : table_schema_(schema) {} +Filter* TagFilterBuilder::build(Expression::Ptr expression) { + // The legacy builder also returns an immediately evaluable Filter. + // Keep the named operand for readers that bind against a different schema. + std::unique_ptr bound; + if (bind_for_standalone_use_) { + if (TagFilter::bind(*expression, *table_schema_, bound) != common::E_OK) + return nullptr; + } else { + if (table_schema_->find_id_column_order( + expression->operand()->reference) < 0) + return nullptr; + bound.reset(new TagFilter(-1, "")); + } + bound->source_ = std::move(expression); + return bound.release(); +} + Filter* TagFilterBuilder::eq(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagEq(idx, value); + return build(Expression::compare(columnName, Expression::CompareOp::EQ, + Expression::Literal::string(value))); } Filter* TagFilterBuilder::neq(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagNeq(idx, value); + return build(Expression::compare(columnName, Expression::CompareOp::NE, + Expression::Literal::string(value))); } Filter* TagFilterBuilder::lt(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagLt(idx, value); + return build(Expression::compare(columnName, Expression::CompareOp::LT, + Expression::Literal::string(value))); } Filter* TagFilterBuilder::lteq(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagLteq(idx, value); + return build(Expression::compare(columnName, Expression::CompareOp::LE, + Expression::Literal::string(value))); } Filter* TagFilterBuilder::gt(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagGt(idx, value); + return build(Expression::compare(columnName, Expression::CompareOp::GT, + Expression::Literal::string(value))); } Filter* TagFilterBuilder::gteq(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagGteq(idx, value); + return build(Expression::compare(columnName, Expression::CompareOp::GE, + Expression::Literal::string(value))); } Filter* TagFilterBuilder::reg_exp(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagRegExp(idx, value); + return build(Expression::regexp(columnName, value, false)); } Filter* TagFilterBuilder::not_reg_exp(const std::string& columnName, const std::string& value) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagNotRegExp(idx, value); + return build(Expression::regexp(columnName, value, true)); } Filter* TagFilterBuilder::is_null(const std::string& columnName) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagIsNull(idx); + return build(Expression::is_null(columnName)); } Filter* TagFilterBuilder::is_not_null(const std::string& columnName) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagIsNotNull(idx); + return build(Expression::is_not_null(columnName)); } Filter* TagFilterBuilder::between_and(const std::string& columnName, const std::string& lower, const std::string& upper) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagBetween(idx, lower, upper); + return build( + Expression::between(columnName, Expression::Literal::string(lower), + Expression::Literal::string(upper), false)); } Filter* TagFilterBuilder::not_between_and(const std::string& columnName, const std::string& lower, const std::string& upper) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagNotBetween(idx, lower, upper); + return build(Expression::between(columnName, + Expression::Literal::string(lower), + Expression::Literal::string(upper), true)); } Filter* TagFilterBuilder::and_filter(Filter* left, Filter* right) { @@ -269,12 +326,40 @@ Filter* TagFilterBuilder::not_filter(Filter* filter) { return child ? new TagNot(child) : nullptr; } -int TagFilterBuilder::get_tag_column_index(const std::string& columnName) { - int idColumnOrder = table_schema_->find_id_column_order(columnName); - if (idColumnOrder == -1) { - return -1; +namespace { +class BorrowedTagChild : public TagFilter { + public: + explicit BorrowedTagChild(const TagFilter* child) + : TagFilter(-1, ""), child_(child) {} + bool satisfyRow(std::vector segments) const override { + return child_->satisfyRow(std::move(segments)); } - return idColumnOrder + 1; + + private: + const TagFilter* child_; +}; +} // namespace + +int TagFilter::bind_for_query(const Filter* filter, TableSchema& schema, + std::unique_ptr& bound) { + const auto* tag = dynamic_cast(filter); + if (!tag) return common::E_OK; + if (tag->source_) return bind(*tag->source_, schema, bound); + // Only rebuild built-in logical nodes. Custom and explicitly indexed + // leaves retain their original segment overload and borrowing contract. + if (typeid(*tag) != typeid(TagAnd) && typeid(*tag) != typeid(TagOr) && + typeid(*tag) != typeid(TagNot)) + return common::E_OK; + std::unique_ptr left, right; + int ret = bind_for_query(tag->left_tag(), schema, left); + if (ret != common::E_OK) return ret; + ret = bind_for_query(tag->right_tag(), schema, right); + if (ret != common::E_OK || (!left && !right)) return ret; + if (!left) left.reset(new BorrowedTagChild(tag->left_tag())); + if (!right && tag->right_tag()) + right.reset(new BorrowedTagChild(tag->right_tag())); + bound.reset(new TagFilter(tag->kind(), left.release(), right.release())); + return common::E_OK; } } // namespace storage \ No newline at end of file diff --git a/cpp/src/reader/filter/tag_filter.h b/cpp/src/reader/filter/tag_filter.h index 20231b2f1..04023014c 100644 --- a/cpp/src/reader/filter/tag_filter.h +++ b/cpp/src/reader/filter/tag_filter.h @@ -26,12 +26,17 @@ #include "common/allocator/my_string.h" #include "common/schema.h" -#include "reader/filter/table_predicate.h" +#include "reader/filter/bound_predicate.h" struct table_schema; namespace storage { -class TagFilter : public TablePredicate { +class TagFilter : public BoundPredicate { public: + static int bind(const Expression& expr, TableSchema& schema, + std::unique_ptr& out); + + static int bind_for_query(const Filter* filter, TableSchema& schema, + std::unique_ptr& bound); TagFilter(int col_idx, std::string tag_value); ~TagFilter() override; @@ -49,6 +54,8 @@ class TagFilter : public TablePredicate { TagFilter(Kind kind, TagFilter* left, TagFilter* right); private: + friend class TagFilterBuilder; + Expression::Ptr source_; const TagFilter* left_tag() const { return static_cast(left()); } @@ -159,9 +166,17 @@ class TagNot : public TagFilter { class TagFilterBuilder { TableSchema* table_schema_; + bool bind_for_standalone_use_ = true; public: explicit TagFilterBuilder(TableSchema* schema); + // Checked handles validate names immediately and bind indices in the + // reader. + static TagFilterBuilder for_query(TableSchema* schema) { + TagFilterBuilder builder(schema); + builder.bind_for_standalone_use_ = false; + return builder; + } Filter* eq(const std::string& columnName, const std::string& value); Filter* neq(const std::string& columnName, const std::string& value); @@ -185,7 +200,7 @@ class TagFilterBuilder { static Filter* not_filter(Filter* filter); private: - int get_tag_column_index(const std::string& columnName); + Filter* build(Expression::Ptr expression); }; } // namespace storage diff --git a/cpp/src/reader/qds_without_timegenerator.cc b/cpp/src/reader/qds_without_timegenerator.cc index f4d869aaa..25d698760 100644 --- a/cpp/src/reader/qds_without_timegenerator.cc +++ b/cpp/src/reader/qds_without_timegenerator.cc @@ -91,6 +91,57 @@ int QDSWithoutTimeGenerator::init(TsFileIOReader* io_reader, return init_internal(io_reader, qe); } +int QDSWithoutTimeGenerator::init(TsFileIOReader* io_reader, + QueryExpression* query, + const Expression& predicate, int offset, + int limit) { + remaining_offset_ = offset; + remaining_limit_ = limit; + qe_ = query; + int ret = + AlignedFieldFilter::from_expression(predicate, row_predicate_, false); + if (ret != E_OK) return ret; + return init_internal(io_reader, query); +} + +namespace { +// Resolve short measurement names against the projection. A predicate may +// also name a full path on a device absent from the projection. +int resolve_series(const std::string& reference, + const std::vector& selected, Path& path) { + const Path* match = nullptr; + for (const auto& candidate : selected) { + if (candidate.full_path_ == reference) { + path = candidate; + return E_OK; + } + if (candidate.measurement_ == reference) { + if (match && match->full_path_ != candidate.full_path_) + return E_INVALID_ARG; + match = &candidate; + } + } + if (match) { + path = *match; + return E_OK; + } + try { + path = Path(reference); + } catch (const std::runtime_error&) { + return E_INVALID_PATH; + } + if (path.full_path_ != path.measurement_) return E_OK; + if (selected.empty()) return E_INVALID_PATH; + const auto device = selected.front().device_id_->get_device_name(); + for (const auto& candidate : selected) + if (candidate.device_id_->get_device_name() != device) + return E_INVALID_ARG; + path.device_id_ = selected.front().device_id_; + path.full_path_ = device + "." + path.measurement_; + return E_OK; +} +} // namespace + int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, QueryExpression* qe) { int ret = E_OK; // cppcheck-suppress unreadVariable @@ -100,7 +151,26 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, qe_ = qe; std::vector paths = qe_->selected_series_; - size_t origin_path_count = paths.size(); + const size_t selected_count = paths.size(); + size_t projected_count = 0; + std::map filter_paths; + if (row_predicate_) { + for (const auto& path : paths) { + if (!path.device_id_ || path.measurement_.empty()) + return E_INVALID_PATH; + } + for (const auto& name : row_predicate_->referenced_columns()) { + Path path; + int status = resolve_series(name, qe_->selected_series_, path); + if (status != E_OK) return status; + filter_paths[name] = path.full_path_; + if (std::none_of(paths.begin(), paths.end(), [&](const Path& p) { + return p.full_path_ == path.full_path_; + })) + paths.push_back(path); + } + } + const size_t origin_path_count = paths.size(); std::vector valid_paths; std::vector column_names; std::vector data_types; @@ -114,7 +184,7 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, ssi_data_types.reserve(origin_path_count); Expression* global_time_expression = qe->expression_; Filter* global_time_filter = nullptr; - if (global_time_expression != nullptr) { + if (!row_predicate_ && global_time_expression != nullptr) { global_time_filter = global_time_expression->filter_; } index_lookup_.insert({"time", 0}); @@ -131,45 +201,29 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, ret = E_OK; continue; } - if (ret == E_NO_MORE_DATA) { - // The series exists but has no data in the query time range. Keep - // its column (aligned with Java) so callers see a NULL value for it - // instead of a later column's value. No SSI is allocated, so a - // nullptr placeholder keeps the column indices aligned. - size_t col_idx = ssi_vec_.size(); - index_lookup_.insert({paths[i].measurement_, col_idx + 1}); - if (paths[i].full_path_ != paths[i].measurement_) { - index_lookup_.insert({paths[i].full_path_, col_idx + 1}); - } - ssi_vec_.push_back(nullptr); - valid_paths.push_back(paths[i]); - column_names.push_back(paths[i].full_path_); - ssi_data_types.push_back(empty_series_type); - ret = E_OK; - continue; - } - if (ret != E_OK) { - for (size_t j = 0; j < ssi_vec_.size(); j++) { - if (ssi_vec_[j] != nullptr) { - io_reader_->revert_ssi(ssi_vec_[j]); - } + if (ret != E_OK && ret != E_NO_MORE_DATA) { + for (auto* allocated : ssi_vec_) { + if (allocated) io_reader_->revert_ssi(allocated); } ssi_vec_.clear(); return ret; } - size_t col_idx = ssi_vec_.size(); - index_lookup_.insert({paths[i].measurement_, col_idx + 1}); - if (paths[i].full_path_ != paths[i].measurement_) { + const size_t col_idx = ssi_vec_.size(); + if (i < selected_count) { + ++projected_count; + index_lookup_.insert({paths[i].measurement_, col_idx + 1}); index_lookup_.insert({paths[i].full_path_, col_idx + 1}); + column_names.push_back(paths[i].full_path_); } - ssi_vec_.push_back(ssi); valid_paths.push_back(paths[i]); - column_names.push_back(paths[i].full_path_); - ssi_data_types.push_back(ssi->get_data_type()); + ssi_vec_.push_back(ssi); + ssi_data_types.push_back(ssi ? ssi->get_data_type() + : empty_series_type); + ret = E_OK; } size_t path_count = valid_paths.size(); - is_single_path_ = (path_count == 1); + is_single_path_ = (path_count == 1 && !row_predicate_); // Only push offset/limit to SSI for single-path; multi-path applies at // merge. for (size_t i = 0; i < path_count; i++) { @@ -178,15 +232,36 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, is_single_path_ ? remaining_limit_ : -1); } } - row_record_ = new RowRecord(path_count + 1); + row_record_ = new RowRecord(projected_count + 1); tsblocks_.resize(path_count); time_iters_.resize(path_count); value_iters_.resize(path_count); + if (row_predicate_) { + predicate_row_arena_.init(512, common::MOD_TSFILE_READER); + filter_only_row_.reset(new RowRecord(path_count - projected_count)); + AlignedFieldFilter::SeriesBindings bindings; + std::map indices; + for (size_t i = 0; i < path_count; ++i) { + indices.emplace(valid_paths[i].full_path_, i); + predicate_fields_.push_back( + i < projected_count + ? row_record_->get_field(i + 1) + : filter_only_row_->get_field(i - projected_count)); + } + for (const auto& entry : filter_paths) { + auto found = indices.find(entry.second); + if (found == indices.end()) return E_COLUMN_NOT_EXIST; + size_t i = found->second; + bindings.emplace(entry.first, std::make_pair(i, ssi_data_types[i])); + } + if (RET_FAIL(row_predicate_->bind_series(bindings))) return ret; + } + for (size_t i = 0; i < path_count; i++) { if (ssi_vec_[i] == nullptr) { // Empty-in-range column: keep it NULL with its real data type. - data_types.push_back(ssi_data_types[i]); + if (i < projected_count) data_types.push_back(ssi_data_types[i]); continue; } if (RET_FAIL(load_next_tsblock(i, true))) { @@ -200,7 +275,7 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, common::TSDataType col_type = value_iters_[i] != nullptr ? value_iters_[i]->get_data_type() : ssi_data_types[i]; - data_types.push_back(col_type); + if (i < projected_count) data_types.push_back(col_type); } // Single-path: SSI may have consumed offset/limit by skipping chunks/pages // during first load_next_tsblock(); sync so QDS does not double-apply. @@ -324,6 +399,10 @@ int QDSWithoutTimeGenerator::next(bool& has_next) { // Multi-path: apply offset/limit at merge layer. while (true) { row_record_->reset(); + if (filter_only_row_) { + filter_only_row_->reset(); + predicate_row_arena_.reset(); + } if (heap_time_.size() == 0) { has_next = false; return E_OK; @@ -348,8 +427,11 @@ int QDSWithoutTimeGenerator::next(bool& has_next) { void* val_ptr = value_iters_[iter->second]->read(&len, &is_null_val); if (!is_null_val) { - row_record_->get_field(iter->second + 1) - ->set_value(val_datatype, val_ptr, len, pa_); + auto* field = row_predicate_ + ? predicate_fields_[iter->second] + : row_record_->get_field(iter->second + 1); + field->set_value(val_datatype, val_ptr, len, + row_predicate_ ? predicate_row_arena_ : pa_); } value_iters_[iter->second]->next(); if (!time_iters_[iter->second]->end()) { @@ -370,6 +452,13 @@ int QDSWithoutTimeGenerator::next(bool& has_next) { iter = heap_time_.erase(iter); } + if (row_predicate_) { + bool accepted; + read_error_ = + row_predicate_->evaluate_row(predicate_fields_, accepted); + if (read_error_ != E_OK) return read_error_; + if (!accepted) continue; + } // Apply offset: skip this row. if (remaining_offset_ > 0) { remaining_offset_--; diff --git a/cpp/src/reader/qds_without_timegenerator.h b/cpp/src/reader/qds_without_timegenerator.h index 1c0fc9f03..a3735ce30 100644 --- a/cpp/src/reader/qds_without_timegenerator.h +++ b/cpp/src/reader/qds_without_timegenerator.h @@ -26,6 +26,7 @@ #include "expression.h" #include "file/tsfile_io_reader.h" +#include "reader/filter/aligned_field_filter.h" #include "result_set.h" namespace storage { @@ -50,6 +51,8 @@ class QDSWithoutTimeGenerator : public ResultSet { int init(TsFileIOReader* io_reader, QueryExpression* qe); int init(TsFileIOReader* io_reader, QueryExpression* qe, int offset, int limit); + int init(TsFileIOReader* io_reader, QueryExpression* query, + const Expression& predicate, int offset, int limit); int init_prepared(TsFileIOReader* io_reader, const std::shared_ptr& prepared, Filter* owned_time_filter, int offset, int limit, @@ -81,6 +84,10 @@ class QDSWithoutTimeGenerator : public ResultSet { int remaining_limit_; Filter* owned_time_filter_; bool is_single_path_; + AlignedFieldFilter::Ptr row_predicate_; + common::PageArena predicate_row_arena_; + std::unique_ptr filter_only_row_; + std::vector predicate_fields_; // A failed block load leaves the merge iterators unusable. Keep reporting // the failure until the result is closed, including subsequent next calls. int read_error_; diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 8ecc1256d..1eb526872 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -19,6 +19,7 @@ #include "reader/table_query_executor.h" +#include "reader/filter/tag_filter.h" #include "utils/db_utils.h" namespace storage { @@ -26,87 +27,8 @@ int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, Filter* time_filter, Filter* tag_filter, Filter* field_filter, ResultSet*& ret_qds) { - int ret = common::E_OK; - TsFileMeta* file_metadata = nullptr; - ret_qds = nullptr; - if (RET_FAIL(tsfile_io_reader_->get_tsfile_meta(file_metadata))) { - delete time_filter; - delete field_filter; - return ret; - } - common::PageArena pa; - pa.init(512, common::MOD_TSFILE_READER); - MetaIndexNode* table_root = nullptr; - std::shared_ptr table_schema; - // A schema-only table has no device-level index. Resolve the schema - // first, then leave table_root null so DeviceMetaIterator yields an empty - // result set with the correct columns instead of reporting "table does - // not exist". - if (RET_FAIL(file_metadata->get_table_schema(table_name, table_schema))) { - ret_qds = nullptr; - delete time_filter; - delete field_filter; - return ret; - } - file_metadata->get_table_metaindex_node(table_name, table_root); - std::vector lower_case_column_names(columns); - for (auto& column : lower_case_column_names) { - to_lowercase_inplace(column); - } - std::shared_ptr column_mapping = - std::make_shared(); - for (size_t i = 0; i < lower_case_column_names.size(); ++i) { - column_mapping->add(lower_case_column_names[i], static_cast(i), - *table_schema); - } - std::vector data_types; - data_types.reserve(lower_case_column_names.size()); - for (size_t i = 0; i < lower_case_column_names.size(); ++i) { - auto ind = table_schema->find_column_index(lower_case_column_names[i]); - if (ind < 0) { - delete time_filter; - delete field_filter; - return common::E_COLUMN_NOT_EXIST; - } - data_types.push_back(table_schema->get_data_types()[ind]); - } - if (auto* aligned_filter = - dynamic_cast(field_filter)) { - ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( - *aligned_filter, *table_schema) - : common::E_INVALID_ARG; - if (ret != common::E_OK) { - delete time_filter; - delete field_filter; - return ret; - } - } - - auto device_task_iterator = - std::unique_ptr(new DeviceTaskIterator( - lower_case_column_names, table_root, column_mapping, - meta_data_querier_, tag_filter, table_schema)); - - std::unique_ptr tsblock_reader; - switch (table_query_ordering_) { - case TableQueryOrdering::DEVICE: - tsblock_reader = std::unique_ptr( - new DeviceOrderedTsBlockReader( - std::move(device_task_iterator), meta_data_querier_, - block_size_, tsfile_io_reader_, time_filter, field_filter)); - break; - case TableQueryOrdering::TIME: - default: - delete time_filter; - delete field_filter; - ret_qds = nullptr; - return common::E_UNSUPPORTED_ORDER; - } - assert(tsblock_reader != nullptr); - ret_qds = - new TableResultSet(std::move(tsblock_reader), lower_case_column_names, - data_types, return_mode_); - return ret; + return query(table_name, columns, time_filter, tag_filter, field_filter, 0, + -1, ret_qds); } int TableQueryExecutor::query(const std::string& table_name, @@ -114,22 +36,34 @@ int TableQueryExecutor::query(const std::string& table_name, Filter* time_filter, Filter* tag_filter, Filter* field_filter, int offset, int limit, ResultSet*& ret_qds) { + return query_impl(table_name, columns, time_filter, tag_filter, + field_filter, {nullptr, nullptr}, offset, limit, ret_qds); +} + +int TableQueryExecutor::query(const std::string& table_name, + const std::vector& columns, + Filter* time_filter, TablePredicates predicates, + int offset, int limit, ResultSet*& ret_qds) { + return query_impl(table_name, columns, time_filter, nullptr, nullptr, + predicates, offset, limit, ret_qds); +} + +int TableQueryExecutor::query_impl(const std::string& table_name, + const std::vector& columns, + Filter* time_filter, Filter* tag_filter, + Filter* field_filter, + TablePredicates predicates, int offset, + int limit, ResultSet*& ret_qds) { + std::unique_ptr owned_time(time_filter), owned_field(field_filter); int ret = common::E_OK; TsFileMeta* file_metadata = nullptr; ret_qds = nullptr; if (RET_FAIL(tsfile_io_reader_->get_tsfile_meta(file_metadata))) { - delete time_filter; - delete field_filter; return ret; } - common::PageArena pa; - pa.init(512, common::MOD_TSFILE_READER); MetaIndexNode* table_root = nullptr; std::shared_ptr table_schema; if (RET_FAIL(file_metadata->get_table_schema(table_name, table_schema))) { - ret_qds = nullptr; - delete time_filter; - delete field_filter; return ret; } file_metadata->get_table_metaindex_node(table_name, table_root); @@ -148,43 +82,53 @@ int TableQueryExecutor::query(const std::string& table_name, for (size_t i = 0; i < lower_case_column_names.size(); ++i) { auto ind = table_schema->find_column_index(lower_case_column_names[i]); if (ind < 0) { - delete time_filter; - delete field_filter; return common::E_COLUMN_NOT_EXIST; } data_types.push_back(table_schema->get_data_types()[ind]); } + std::unique_ptr bound_tag; + ret = + predicates.tag_filter + ? TagFilter::bind(*predicates.tag_filter, *table_schema, bound_tag) + : TagFilter::bind_for_query(tag_filter, *table_schema, bound_tag); + if (ret != common::E_OK) { + return ret; + } + if (predicates.field_filter) { + AlignedFieldFilter::Ptr bound; + ret = AlignedFieldFilter::from_expression(*predicates.field_filter, + bound, true); + if (ret != common::E_OK) { + return ret; + } + owned_field = std::move(bound); + } if (auto* aligned_filter = - dynamic_cast(field_filter)) { + dynamic_cast(owned_field.get())) { ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( *aligned_filter, *table_schema) : common::E_INVALID_ARG; if (ret != common::E_OK) { - delete time_filter; - delete field_filter; return ret; } } - auto device_task_iterator = - std::unique_ptr(new DeviceTaskIterator( - lower_case_column_names, table_root, column_mapping, - meta_data_querier_, tag_filter, table_schema)); + auto device_task_iterator = std::unique_ptr( + new DeviceTaskIterator(lower_case_column_names, table_root, + column_mapping, meta_data_querier_, tag_filter, + table_schema, std::move(bound_tag))); std::unique_ptr tsblock_reader; switch (table_query_ordering_) { case TableQueryOrdering::DEVICE: tsblock_reader = std::unique_ptr( - new DeviceOrderedTsBlockReader(std::move(device_task_iterator), - meta_data_querier_, block_size_, - tsfile_io_reader_, time_filter, - field_filter, offset, limit)); + new DeviceOrderedTsBlockReader( + std::move(device_task_iterator), meta_data_querier_, + block_size_, tsfile_io_reader_, owned_time.release(), + owned_field.release(), offset, limit)); break; case TableQueryOrdering::TIME: default: - delete time_filter; - delete field_filter; - ret_qds = nullptr; return common::E_UNSUPPORTED_ORDER; } assert(tsblock_reader != nullptr); diff --git a/cpp/src/reader/table_query_executor.h b/cpp/src/reader/table_query_executor.h index e968c3601..3120903ba 100644 --- a/cpp/src/reader/table_query_executor.h +++ b/cpp/src/reader/table_query_executor.h @@ -84,6 +84,10 @@ class TableQueryExecutor { const std::vector& columns, Filter* time_filter, Filter* tag_filter, Filter* field_filter, int offset, int limit, ResultSet*& ret_qds); + int query(const std::string& table_name, + const std::vector& columns, Filter* time_filter, + TablePredicates predicates, int offset, int limit, + ResultSet*& result); int query_on_tree(const std::vector>& devices, const std::vector& tag_columns, const std::vector& field_columns, @@ -91,6 +95,11 @@ class TableQueryExecutor { void destroy_query_data_set(ResultSet* qds); private: + int query_impl(const std::string& table_name, + const std::vector& columns, Filter* time_filter, + Filter* tag_filter, Filter* field_filter, + TablePredicates predicates, int offset, int limit, + ResultSet*& result); IMetadataQuerier* meta_data_querier_; TsFileIOReader* tsfile_io_reader_; TableQueryOrdering table_query_ordering_; diff --git a/cpp/src/reader/task/device_task_iterator.h b/cpp/src/reader/task/device_task_iterator.h index ad86dbc1d..4afc27393 100644 --- a/cpp/src/reader/task/device_task_iterator.h +++ b/cpp/src/reader/task/device_task_iterator.h @@ -35,11 +35,13 @@ class DeviceTaskIterator { std::shared_ptr column_mapping, IMetadataQuerier* metadata_querier, const Filter* id_filter, - std::shared_ptr table_schema) + std::shared_ptr table_schema, + std::unique_ptr bound_tag = nullptr) : column_names_(column_names), column_mapping_(column_mapping), - device_meta_iterator_( - metadata_querier->device_iterator(index_root, id_filter)), + bound_tag_(std::move(bound_tag)), + device_meta_iterator_(metadata_querier->device_iterator( + index_root, bound_tag_ ? bound_tag_.get() : id_filter)), table_schema_(table_schema) { pa_.init(512, common::MOD_DEVICE_TASK_ITER); } @@ -79,6 +81,7 @@ class DeviceTaskIterator { private: std::vector column_names_; std::shared_ptr column_mapping_; + std::unique_ptr bound_tag_; std::unique_ptr device_meta_iterator_; std::shared_ptr table_schema_; common::PageArena pa_; diff --git a/cpp/src/reader/tsfile_executor.cc b/cpp/src/reader/tsfile_executor.cc index c2aa8d8cd..4be681a52 100644 --- a/cpp/src/reader/tsfile_executor.cc +++ b/cpp/src/reader/tsfile_executor.cc @@ -62,11 +62,43 @@ int TsFileExecutor::init(const std::string& file_path) { return ret; } +namespace { +bool has_named_operand(const Expression* expr) { + if (!expr) return false; + if (expr->type_ == AND_EXPR || expr->type_ == OR_EXPR) + return !expr->left_ || !expr->right_ || + has_named_operand(expr->left_) || + has_named_operand(expr->right_); + return expr->type_ != SERIES_EXPR && expr->type_ != GLOBALTIME_EXPR && + expr->type_ != INVALID_EXPR; +} +int execute_predicate(TsFileIOReader* reader, QueryExpression* query, + const Expression& predicate, ResultSet*& result, + int offset = 0, int limit = -1) { + result = nullptr; + std::unique_ptr rows( + new QDSWithoutTimeGenerator()); + int ret = rows->init(reader, query, predicate, offset, limit); + if (ret == E_OK) result = rows.release(); + return ret; +} +} // namespace + +int TsFileExecutor::execute(const std::vector& paths, + const Expression& predicate, ResultSet*& result) { + return execute_predicate(&io_reader_, + QueryExpression::create(paths, nullptr), predicate, + result); +} + int TsFileExecutor::execute(QueryExpression* query_expr, ResultSet*& ret_qds) { ASSERT(is_inited_); query_exprs_ = query_expr; std::vector paths = query_exprs_->selected_series_; Expression* origin_expr = query_exprs_->expression_; + if (has_named_operand(origin_expr)) + return execute_predicate(&io_reader_, query_expr, *origin_expr, + ret_qds); Expression* regular_expr = nullptr; if (query_exprs_->has_filter_) { regular_expr = query_exprs_->optimize(origin_expr, paths); @@ -95,6 +127,10 @@ int TsFileExecutor::execute(QueryExpression* query_expr, ResultSet*& ret_qds, ASSERT(is_inited_); query_exprs_ = query_expr; + if (has_named_operand(query_expr->expression_)) + return execute_predicate(&io_reader_, query_expr, + *query_expr->expression_, ret_qds, offset, + limit); int ret = E_OK; QDSWithoutTimeGenerator* qds = new QDSWithoutTimeGenerator; ret = qds->init(&io_reader_, query_expr, offset, limit); diff --git a/cpp/src/reader/tsfile_executor.h b/cpp/src/reader/tsfile_executor.h index 57927d5dc..12779f7ea 100644 --- a/cpp/src/reader/tsfile_executor.h +++ b/cpp/src/reader/tsfile_executor.h @@ -36,6 +36,8 @@ class TsFileExecutor // : public QueryExecutor int init(RandomAccessReadFile* read_file); int init(const std::string& file_path); int execute(QueryExpression* query_expr, ResultSet*& ret_qds); + int execute(const std::vector& paths, const Expression& predicate, + ResultSet*& result); int execute(QueryExpression* query_expr, ResultSet*& ret_qds, int offset, int limit); int prepare_series(const FileGeneration& generation, diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index 4a39a9f23..c256904cb 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -29,6 +29,7 @@ #include "device_meta_iterator.h" #include "file/local_random_access_read_file.h" #include "filter/time_operator.h" +#include "reader/filter/tag_filter.h" #include "tsfile_executor.h" using namespace common; @@ -343,7 +344,12 @@ int TsFileReader::prepare_table_series( common::PageArena pa; pa.init(512, common::MOD_TSFILE_READER); - DeviceMetaIterator device_iterator(io_reader, table_root, tag_filter); + std::unique_ptr bound_tag; + if (RET_FAIL( + TagFilter::bind_for_query(tag_filter, *table_schema, bound_tag))) + return ret; + DeviceMetaIterator device_iterator( + io_reader, table_root, bound_tag ? bound_tag.get() : tag_filter); bool has_next = false; if (RET_FAIL(device_iterator.has_next(has_next))) { return ret; @@ -480,6 +486,47 @@ int TsFileReader::queryByRow(const std::string& table_name, return ret; } +int TsFileReader::query(const std::vector& paths, + const Expression& predicate, ResultSet*& result) { + result = nullptr; + if (!tsfile_executor_) return E_INVALID_ARG; + return tsfile_executor_->execute(paths, predicate, result); +} + +int TsFileReader::query(const std::string& table_name, + const std::vector& columns, + int64_t start_time, int64_t end_time, + TablePredicates predicates, ResultSet*& result, + int batch_size) { + return query(table_name, columns, start_time, end_time, 0, -1, predicates, + result, batch_size); +} + +int TsFileReader::query(const std::string& table_name, + const std::vector& columns, + int64_t start_time, int64_t end_time, int offset, + int limit, TablePredicates predicates, + ResultSet*& result, int batch_size) { + result = nullptr; + if (!tsfile_executor_ || offset < 0) return E_INVALID_ARG; + ensure_table_query_executor(batch_size); + return table_query_executor_->query( + to_lower(table_name), columns, + new TimeBetween(start_time, end_time, false), predicates, offset, limit, + result); +} + +int TsFileReader::queryByRow(const std::string& table_name, + const std::vector& columns, + int offset, int limit, TablePredicates predicates, + ResultSet*& result, int batch_size) { + result = nullptr; + if (!tsfile_executor_ || offset < 0) return E_INVALID_ARG; + ensure_table_query_executor(batch_size); + return table_query_executor_->query(to_lower(table_name), columns, nullptr, + predicates, offset, limit, result); +} + int TsFileReader::query_table_on_tree( const std::vector& measurement_names, int64_t star_time, int64_t end_time, ResultSet*& result_set) { diff --git a/cpp/src/reader/tsfile_reader.h b/cpp/src/reader/tsfile_reader.h index 6f2c7d340..814359424 100644 --- a/cpp/src/reader/tsfile_reader.h +++ b/cpp/src/reader/tsfile_reader.h @@ -201,6 +201,24 @@ class TsFileReader { int limit, ResultSet*& result_set, Filter* tag_filter = nullptr, int batch_size = 0); + // Expressions are borrowed for query preparation; the result owns its + // bindings. + int query(const std::vector& selected_series, + const Expression& predicate, ResultSet*& result); + int query(const std::string& table_name, + const std::vector& columns, int64_t start_time, + int64_t end_time, TablePredicates predicates, ResultSet*& result, + int batch_size = 0); + int query(const std::string& table_name, + const std::vector& columns, int64_t start_time, + int64_t end_time, int offset, int limit, + TablePredicates predicates, ResultSet*& result, + int batch_size = 0); + int queryByRow(const std::string& table_name, + const std::vector& columns, int offset, + int limit, TablePredicates predicates, ResultSet*& result, + int batch_size = 0); + int query_table_on_tree(const std::vector& measurement_names, int64_t star_time, int64_t end_time, ResultSet*& result_set); diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index a1628ff2d..67b85d78f 100644 --- a/cpp/test/reader/filter/tag_filter_test.cc +++ b/cpp/test/reader/filter/tag_filter_test.cc @@ -520,20 +520,20 @@ TEST_F(TagFilterTest, LogicalOperatorsUseSegmentOverloadForChildren) { TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { using Field = AlignedFieldFilter; - using Kind = TablePredicate::Kind; + using Kind = BoundPredicate::Kind; std::unique_ptr tag( builder_->not_filter(builder_->eq("name", "x"))); auto field = Field::not_filter(Field::compare("name", Field::CompareOp::EQ, Field::Literal::string("x"))); - const auto* tag_expr = dynamic_cast(tag.get()); + const auto* tag_expr = dynamic_cast(tag.get()); ASSERT_NE(nullptr, tag_expr); - for (const TablePredicate* expr : - {tag_expr, static_cast(field.get())}) { + for (const BoundPredicate* expr : + {tag_expr, static_cast(field.get())}) { EXPECT_EQ(Kind::NOT, expr->kind()); ASSERT_NE(nullptr, expr->left()); EXPECT_EQ(Kind::COMPARISON, expr->left()->kind()); - EXPECT_EQ(TablePredicate::CompareOp::EQ, expr->left()->compare_op()); + EXPECT_EQ(BoundPredicate::CompareOp::EQ, expr->left()->compare_op()); } EXPECT_TRUE(tag->satisfyRow(0, {})); diff --git a/cpp/test/reader/table_field_filter_test.cc b/cpp/test/reader/table_field_filter_test.cc index a7c9aebc0..a5608d522 100644 --- a/cpp/test/reader/table_field_filter_test.cc +++ b/cpp/test/reader/table_field_filter_test.cc @@ -35,6 +35,7 @@ #include "reader/filter/time_filter.h" #include "reader/filter/time_operator.h" #include "reader/table_query_executor.h" +#include "reader/tsfile_reader.h" #include "writer/tsfile_table_writer.h" #ifdef _WIN32 @@ -323,6 +324,66 @@ class TableFieldFilterTest const int64_t base_ = INT64_C(1099511627776); }; +TEST_P(TableFieldFilterTest, ReuseNamedExpressionForTableAndTree) { + TsFileReader reader; + ASSERT_EQ(E_OK, reader.open(filename_)); + auto field = Expression::compare("v", Expression::CompareOp::EQ, + Expression::Literal::float64(5.9)); + auto tag = Expression::compare("id", Expression::CompareOp::EQ, + Expression::Literal::string("d0")); + ResultSet *table = nullptr, *tree = nullptr; + ASSERT_EQ(E_OK, reader.queryByRow("t", {"i"}, 0, -1, + {tag.get(), field.get()}, table)); + std::vector> devices; + ASSERT_EQ(E_OK, reader.get_all_devices("t", devices)); + ASSERT_EQ(2u, devices.size()); + Path path; + path.device_id_ = devices.front(); + path.measurement_ = "v"; + path.full_path_ = path.device_id_->get_device_name() + ".v"; + ASSERT_EQ(E_OK, reader.query({path}, *field, tree)); + EXPECT_EQ(common::DOUBLE, field->operand()->literal.type); + tag.reset(); + field.reset(); + for (auto* result : {table, tree}) { + bool next = false; + ASSERT_EQ(E_OK, result->next(next)); + ASSERT_TRUE(next); + EXPECT_EQ(base_ + 5, result->get_value(1)); + ASSERT_EQ(E_OK, result->next(next)); + EXPECT_FALSE(next); + reader.destroy_query_data_set(result); + } +} + +TEST_P(TableFieldFilterTest, BindTagAgainstQuerySchemaAndRejectWrongCategory) { + TsFileReader reader; + ASSERT_EQ(E_OK, reader.open(filename_)); + // The compatibility builder can validate against a different TAG order. + TableSchema schema("other", {{"unused", STRING, ColumnCategory::TAG}, + {"id", STRING, ColumnCategory::TAG}}); + TagFilterBuilder builder(&schema); + std::unique_ptr tag(builder.eq("id", "d1")); + ASSERT_TRUE(tag); + ResultSet* rows = nullptr; + ASSERT_EQ(E_OK, reader.queryByRow("t", {"v"}, 0, 1, rows, tag.get())); + tag.reset(); + bool next; + ASSERT_EQ(E_OK, rows->next(next)); + ASSERT_TRUE(next); + EXPECT_EQ(100, rows->get_value(2)); + reader.destroy_query_data_set(rows); + auto wrong = Expression::is_null("v"); + EXPECT_EQ( + E_COLUMN_NOT_EXIST, + reader.queryByRow("t", {"v"}, 0, 0, {wrong.get(), nullptr}, rows)); + EXPECT_EQ(nullptr, rows); + wrong = Expression::is_null("id"); + EXPECT_EQ(E_INVALID_ARG, + reader.query("t", {"v"}, 0, 0, {nullptr, wrong.get()}, rows)); + EXPECT_EQ(nullptr, rows); +} + TEST_P(TableFieldFilterTest, AlignedBatchFilterAndOrUsesFilterOnlyColumns) { auto left = AlignedFieldFilter::and_filter( AlignedFieldFilter::compare("i", AlignedFieldFilter::CompareOp::LE, diff --git a/cpp/test/reader/tsfile_reader_test.cc b/cpp/test/reader/tsfile_reader_test.cc index d611856a4..f00c2555b 100644 --- a/cpp/test/reader/tsfile_reader_test.cc +++ b/cpp/test/reader/tsfile_reader_test.cc @@ -2352,6 +2352,70 @@ TEST_F(TsFileReaderTest, RepeatedGetTimeseriesMetadataDoesNotLeakArena) { reader.close(); } +TEST_F(TsFileReaderTest, BindPredicateToSparseCaseSensitiveTreePaths) { + std::string device = "root.shared"; + for (const auto* name : {"v", "V"}) { + ASSERT_EQ(E_OK, + tsfile_writer_->register_timeseries( + device, MeasurementSchema( + name, TSDataType::DOUBLE, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED))); + } + for (int t = 1; t <= 4; ++t) { + TsRecord row(t, device); + if (t != 3) row.add_point("v", double(t)); + if (t != 2) row.add_point("V", double(t) + 0.5); + ASSERT_EQ(E_OK, tsfile_writer_->write_record(row)); + } + ASSERT_EQ(E_OK, tsfile_writer_->close()); + TsFileReader reader; + ASSERT_EQ(E_OK, reader.open(file_name_)); + auto condition = + Expression::or_filter(Expression::is_null("V"), + Expression::not_filter(Expression::compare( + "root.shared.V", Expression::CompareOp::LT, + Expression::Literal::float64(3.5)))); + ResultSet* result = nullptr; + ASSERT_EQ(E_OK, reader.query({Path("root.shared.v")}, *condition, result)); + condition.reset(); + EXPECT_EQ(2u, result->get_metadata()->get_column_count()); + for (int time : {2, 3, 4}) { + bool next; + ASSERT_EQ(E_OK, result->next(next)); + ASSERT_TRUE(next); + EXPECT_EQ(time, result->get_value(1)); + EXPECT_EQ(time == 3, result->is_null(2)); + EXPECT_EQ(2u, result->get_row_record()->get_col_num()); + } + bool next; + ASSERT_EQ(E_OK, result->next(next)); + EXPECT_FALSE(next); + reader.destroy_query_data_set(result); + auto range = Expression::between("V", Expression::Literal::float64(2.5), + Expression::Literal::float64(3.5)); + ASSERT_EQ(E_OK, reader.query(QueryExpression::create( + {Path("root.shared.v")}, range.release()), + result)); + ASSERT_EQ(E_OK, result->next(next)); + ASSERT_TRUE(next); + EXPECT_EQ(3, result->get_value(1)); + EXPECT_TRUE(result->is_null(2)); + ASSERT_EQ(E_OK, result->next(next)); + EXPECT_FALSE(next); + reader.destroy_query_data_set(result); + auto ambiguous = Expression::is_not_null("v"); + EXPECT_EQ(E_INVALID_ARG, + reader.query({Path("root.shared.v"), Path("root.other.v")}, + *ambiguous, result)); + EXPECT_EQ(nullptr, result); + EXPECT_EQ(E_INVALID_PATH, reader.query({Path()}, *ambiguous, result)); + EXPECT_EQ(nullptr, result); + auto missing = Expression::is_null("root.shared.unknown"); + EXPECT_EQ(E_COLUMN_NOT_EXIST, + reader.query({Path("root.shared.v")}, *missing, result)); + EXPECT_EQ(nullptr, result); +} + TEST_F(TsFileReaderTest, MultiPathKeepsNullColumnForSeriesEmptyInRange) { const std::string device = "root.t"; ASSERT_EQ(tsfile_writer_->register_timeseries( diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 5ee10d180..3368606b3 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -70,17 +70,39 @@ arguments. TAG values are strings; do not apply a TAG builder to FIELD columns. Do not translate operator names mechanically across bindings: Java additionally exposes LIKE, while current C++/Python expose explicit null predicates. -## C++ table predicates - -`TagFilterBuilder` and `AlignedFieldFilter` use the operator tree in -`cpp/src/reader/filter/table_predicate.h` for comparisons, null tests, and -logical combinations. Pass TAG and FIELD predicates to the corresponding -arguments of `TsFileReader::query` or `queryByRow`. TAG predicates inspect -device-ID segments. FIELD predicates evaluate column values and can use page -statistics to skip reads. For a missing TAG, `NOT(column = x)` matches. -For a NULL FIELD, the same negated comparison excludes the row. -TAG logical operators call each child's `satisfyRow(segments)` overload. -FIELD page pruning requires a known positive row count to accept a whole page. +## C++ table and tree predicates + +Build named conditions with `storage::Expression` from `reader/expression.h`. +A comparison retains its reference, operator and typed literal. Queries bind +their own copy, so an expression can be used against multiple schemas and +released once the query returns. + +```cpp +using E = storage::Expression; +auto hot = E::compare("temperature", E::CompareOp::GT, E::Literal::float64(22.5)); +auto site = E::compare("site", E::CompareOp::EQ, E::Literal::string("west")); +storage::ResultSet* rows = nullptr; +int ret = reader.queryByRow("weather", {"temperature"}, 0, 100, + {site.get(), hot.get()}, rows); +// Consume rows and call reader.destroy_query_data_set(rows) after success. +``` + +Table queries take separate `tag_filter` and `field_filter` expressions in +`TablePredicates`. TAG references bind to device-ID segments; FIELD references +bind to column types and support page pruning. TAG regular expressions operate +on strings. Comparisons, inclusive ranges, null tests and Boolean composition +are available for values. For a missing TAG, `NOT(column = x)` matches. For a +NULL FIELD or tree measurement it excludes the row. FIELD page pruning requires +a known positive row count to accept a whole page. + +For a tree query, pass selected `Path` objects and the same named expression +to `reader.query(paths, *hot, rows)`. Tree references are case-sensitive. +A full path can reference an unprojected series. A short name resolves to a +unique selected measurement, or to another measurement when the projection +identifies a single device. Ambiguous names fail binding. Rows are evaluated +after merging timestamps from projected and filter-only series. Only selected +series are exposed in the result. Existing path/time filter queries and +standalone TAG filter subclasses retain their original interfaces. ## Source Anchors From b270c2303f89e6d14c1816362942e5ba507b05ef Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 19:56:38 +0800 Subject: [PATCH 04/10] Move literal conversion and value predicate binding into the expression binder --- cpp/src/common/db_common.h | 4 + cpp/src/reader/filter/aligned_field_filter.cc | 309 +---------------- cpp/src/reader/filter/aligned_field_filter.h | 7 +- cpp/src/reader/filter/bind_expression.cc | 317 ++++++++++++++++++ cpp/src/reader/filter/bind_expression.h | 3 + .../aligned_field_filter_regression_test.cc | 2 +- .../filter/aligned_field_filter_test.cc | 4 +- 7 files changed, 331 insertions(+), 315 deletions(-) create mode 100644 cpp/src/reader/filter/bind_expression.cc diff --git a/cpp/src/common/db_common.h b/cpp/src/common/db_common.h index c2b394e00..a705ba227 100644 --- a/cpp/src/common/db_common.h +++ b/cpp/src/common/db_common.h @@ -121,6 +121,10 @@ struct hash { #endif namespace common { +FORCE_INLINE bool is_string_type(TSDataType type) { + return type == STRING || type == TEXT || type == BLOB; +} + FORCE_INLINE const char* get_data_type_name(TSDataType type) { ASSERT(type >= BOOLEAN && type <= STRING); return s_data_type_names[type]; diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index 63a999cb1..7ff0583ce 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -19,17 +19,12 @@ #include "reader/filter/aligned_field_filter.h" -#include -#include #include #include -#include #include #include "common/row_record.h" -#include "common/schema.h" #include "common/statistic.h" -#include "reader/filter/bind_expression.h" namespace storage { namespace { @@ -64,306 +59,8 @@ bool has_nan_statistics(const S& statistic) { std::isnan(statistic.min_value_) || std::isnan(statistic.max_value_); } -bool is_string_type(common::TSDataType type) { - return type == common::STRING || type == common::TEXT || - type == common::BLOB; -} - -bool is_numeric_type(common::TSDataType type) { - return type == common::INT32 || type == common::INT64 || - type == common::FLOAT || type == common::DOUBLE || - type == common::DATE || type == common::TIMESTAMP; -} - -template -T java_number_cast(S value) { - return static_cast(value); -} - -// Java narrows integral values by retaining the low bits, while narrowing a -// floating-point value saturates and maps NaN to zero. Avoid C++'s undefined -// floating-to-integer overflow and implementation-defined signed narrowing. -template <> -int32_t java_number_cast(int64_t value) { - const uint32_t bits = static_cast(value); - int32_t result; - std::memcpy(&result, &bits, sizeof(result)); - return result; -} - -template -T java_floating_to_integer(S value) { - if (std::isnan(value)) return 0; - if (value >= static_cast(std::numeric_limits::max())) - return std::numeric_limits::max(); - if (value <= static_cast(std::numeric_limits::min())) - return std::numeric_limits::min(); - return static_cast(value); -} - -template <> -int32_t java_number_cast(float value) { - return java_floating_to_integer(value); -} -template <> -int32_t java_number_cast(double value) { - return java_floating_to_integer(value); -} -template <> -int64_t java_number_cast(float value) { - return java_floating_to_integer(value); -} -template <> -int64_t java_number_cast(double value) { - return java_floating_to_integer(value); -} - -template <> -float java_number_cast(double value) { - const double maximum = std::numeric_limits::max(); - // Round values just above Float.MAX_VALUE back to the maximum; the - // halfway point to the next exponent rounds to infinity in Java. - const double overflow = - maximum + std::ldexp(1.0, std::numeric_limits::max_exponent - - std::numeric_limits::digits - 1); - if (value > maximum) - return value >= overflow ? std::numeric_limits::infinity() - : std::numeric_limits::max(); - if (value < -maximum) - return value <= -overflow ? -std::numeric_limits::infinity() - : -std::numeric_limits::max(); - return static_cast(value); -} - -template -T java_number_value(const AlignedFieldFilter::Literal& literal) { - switch (literal.type) { - case common::DATE: - case common::INT32: - return java_number_cast(literal.int32_value); - case common::TIMESTAMP: - case common::INT64: - return java_number_cast(literal.int64_value); - case common::FLOAT: - return java_number_cast(literal.float_value); - case common::DOUBLE: - return java_number_cast(literal.double_value); - default: - ASSERT(false); - return T(); - } -} - -int bind_literal(AlignedFieldFilter::Literal& literal, - common::TSDataType column_type) { - using Literal = AlignedFieldFilter::Literal; - if (is_numeric_type(column_type) && is_numeric_type(literal.type)) { - switch (column_type) { - case common::DATE: - case common::INT32: - literal = Literal::int32(java_number_value(literal)); - break; - case common::TIMESTAMP: - case common::INT64: - literal = Literal::int64(java_number_value(literal)); - break; - case common::FLOAT: - literal = Literal::float32(java_number_value(literal)); - break; - case common::DOUBLE: - literal = Literal::float64(java_number_value(literal)); - break; - default: - return common::E_NOT_SUPPORT; - } - return common::E_OK; - } - if ((column_type == common::BOOLEAN && literal.type == common::BOOLEAN) || - (is_string_type(column_type) && is_string_type(literal.type))) - return common::E_OK; - return common::E_NOT_SUPPORT; -} - -std::string normalize_column_name(const std::string& column) { - std::string normalized(column); - for (char& ch : normalized) { - ch = static_cast(std::tolower(static_cast(ch))); - } - return normalized; -} - } // namespace -AlignedFieldFilter::AlignedFieldFilter(Kind kind, std::string column, - CompareOp op, Literal literal) - : BoundPredicate(kind, op), - column_(std::move(column)), - literal_(std::move(literal)) {} - -AlignedFieldFilter::AlignedFieldFilter(Kind kind, Ptr left, Ptr right) - : BoundPredicate(kind, std::move(left), std::move(right)) {} - -AlignedFieldFilter::Ptr AlignedFieldFilter::compare(std::string column, - CompareOp op, - Literal literal) { - return Ptr(new AlignedFieldFilter(Kind::COMPARISON, - normalize_column_name(column), op, - std::move(literal))); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::is_null(std::string column) { - return Ptr(new AlignedFieldFilter(Kind::IS_NULL, - normalize_column_name(column), - CompareOp::EQ, Literal())); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::is_not_null(std::string column) { - return Ptr(new AlignedFieldFilter(Kind::IS_NOT_NULL, - normalize_column_name(column), - CompareOp::EQ, Literal())); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::and_filter(Ptr left, Ptr right) { - return Ptr( - new AlignedFieldFilter(Kind::AND, std::move(left), std::move(right))); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::or_filter(Ptr left, Ptr right) { - return Ptr( - new AlignedFieldFilter(Kind::OR, std::move(left), std::move(right))); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { - if (child && child->kind() == Kind::NOT) { - // Keep NOT(NULL operand) invalid across repeated negations. - if (!child->left_) return child; - return Ptr(static_cast(child->left_.release())); - } - return Ptr(new AlignedFieldFilter(Kind::NOT, std::move(child), nullptr)); -} - -int AlignedFieldFilter::from_expression(const Expression& expr, Ptr& out, - bool table_columns) { - auto leaf = [&](ExpressionType type, const Expression::Operand& operand, - Ptr& result) -> int { - std::string name = table_columns - ? normalize_column_name(operand.reference) - : operand.reference; - switch (type) { - case Kind::IS_NULL: - case Kind::IS_NOT_NULL: - case Kind::COMPARISON: - break; - case ExpressionType::BETWEEN: - case ExpressionType::NOT_BETWEEN: { - Ptr lower(new AlignedFieldFilter( - Kind::COMPARISON, name, CompareOp::GE, operand.literal)); - Ptr upper(new AlignedFieldFilter(Kind::COMPARISON, name, - CompareOp::LE, operand.upper)); - result = and_filter(std::move(lower), std::move(upper)); - if (type == ExpressionType::NOT_BETWEEN) - result = not_filter(std::move(result)); - return common::E_OK; - } - default: - return common::E_NOT_SUPPORT; - } - result.reset(new AlignedFieldFilter( - type, std::move(name), operand.comparison, operand.literal)); - return common::E_OK; - }; - return bind_expression( - expr, out, leaf, [](ExpressionType type, Ptr left, Ptr right) { - if (type == ExpressionType::NOT) return not_filter(std::move(left)); - if (type == AND_EXPR) - return and_filter(std::move(left), std::move(right)); - return or_filter(std::move(left), std::move(right)); - }); -} - -int AlignedFieldFilter::bind_series(const SeriesBindings& bindings) { - if (left_) { - int ret = static_cast(left_.get()) - ->bind_series(bindings); - if (ret != common::E_OK || !right_) return ret; - return static_cast(right_.get()) - ->bind_series(bindings); - } - auto it = bindings.find(column_); - if (it == bindings.end()) return common::E_COLUMN_NOT_EXIST; - series_index_ = it->second.first; - return kind_ == Kind::COMPARISON ? bind_literal(literal_, it->second.second) - : common::E_OK; -} - -std::vector AlignedFieldFilter::referenced_columns() const { - std::vector columns; - std::set seen_columns; - std::set seen_nodes; - std::vector stack{this}; - while (!stack.empty()) { - const AlignedFieldFilter* node = stack.back(); - stack.pop_back(); - if (node == nullptr || !seen_nodes.insert(node).second) continue; - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - if (seen_columns.insert(node->column_).second) { - columns.push_back(node->column_); - } - continue; - } - if (node->right_) stack.push_back(node->right_field()); - if (node->left_) stack.push_back(node->left_field()); - } - return columns; -} - -bool AlignedFieldFilter::is_valid() const { - switch (kind_) { - case Kind::COMPARISON: - case Kind::IS_NULL: - case Kind::IS_NOT_NULL: - return true; - case Kind::NOT: - return left_ && left_field()->is_valid(); - case Kind::BETWEEN: - case Kind::NOT_BETWEEN: - case Kind::REGEXP: - case Kind::NOT_REGEXP: - case Kind::CUSTOM: - case SERIES_EXPR: - case GLOBALTIME_EXPR: - case INVALID_EXPR: - return false; - case Kind::AND: - case Kind::OR: - return left_ != nullptr && right_ != nullptr && - left_field()->is_valid() && right_field()->is_valid(); - } - return false; -} - -int AlignedFieldFilter::bind(TableSchema& schema) { - if (kind_ == Kind::NOT) { - return left_ - ? static_cast(left_.get())->bind(schema) - : common::E_INVALID_ARG; - } - if (kind_ == Kind::AND || kind_ == Kind::OR) { - if (!left_ || !right_) return common::E_INVALID_ARG; - const int ret = - static_cast(left_.get())->bind(schema); - if (ret != common::E_OK) return ret; - return static_cast(right_.get())->bind(schema); - } - const common::ColumnSchema column = schema.get_column_schema(column_); - if (!column.is_valid()) return common::E_COLUMN_NOT_EXIST; - if (column.column_category_ != common::ColumnCategory::FIELD) - return common::E_INVALID_ARG; - if (kind_ != Kind::COMPARISON) return common::E_OK; - return bind_literal(literal_, column.data_type_); -} - bool AlignedFieldFilter::may_match( const std::map& statistics, int64_t row_count) const { @@ -731,8 +428,8 @@ int AlignedFieldFilter::evaluate_value(common::TSDataType column_type, std::memcpy(&value, data, sizeof(value)); satisfied = compare_values(value, literal_.double_value, compare_op_); - } else if (is_string_type(column_type) && - is_string_type(literal_.type)) { + } else if (common::is_string_type(column_type) && + common::is_string_type(literal_.type)) { satisfied = compare_values(std::string(data ? data : "", len), literal_.string_value, compare_op_); } else { @@ -757,7 +454,7 @@ int AlignedFieldFilter::evaluate_row(const std::vector& fields, const auto& field = *fields[series_index_]; const char* data = reinterpret_cast(&field.value_); uint32_t len = 0; - if (is_string_type(field.type_)) { + if (common::is_string_type(field.type_)) { data = field.value_.strval_->buf_; len = field.value_.strval_->len_; } diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 06434a320..484cb5514 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -80,11 +80,8 @@ class AlignedFieldFilter : public BoundPredicate { // as a full-page match and skip evaluation. bool is_valid() const; - // Bind once before execution: validate FIELD references and literal types, - // and convert numeric constants to the declared column type using Java's - // Number.intValue/longValue/floatValue/doubleValue rules. Comparisons and - // statistics pruning then use the same normalized constant, even on empty - // or all-NULL inputs. + // Resolve FIELD references and normalize literals to the declared column + // types before row evaluation or page pruning. int bind(TableSchema& schema); // Conservatively decides whether any row in a page can satisfy the filter. diff --git a/cpp/src/reader/filter/bind_expression.cc b/cpp/src/reader/filter/bind_expression.cc new file mode 100644 index 000000000..c224ddd57 --- /dev/null +++ b/cpp/src/reader/filter/bind_expression.cc @@ -0,0 +1,317 @@ +/* + * 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. + */ + +#include "reader/filter/bind_expression.h" + +#include +#include +#include +#include +#include + +#include "common/schema.h" +#include "reader/filter/aligned_field_filter.h" +#include "utils/storage_utils.h" + +namespace storage { +namespace { + +bool is_numeric_type(common::TSDataType type) { + return type == common::INT32 || type == common::INT64 || + type == common::FLOAT || type == common::DOUBLE || + type == common::DATE || type == common::TIMESTAMP; +} + +template +T numeric_cast(S value) { + return static_cast(value); +} + +// Narrowing a signed integer keeps its low 32 bits. +template <> +int32_t numeric_cast(int64_t value) { + const uint32_t bits = static_cast(value); + int32_t result; + std::memcpy(&result, &bits, sizeof(result)); + return result; +} + +template +T floating_to_integer(S value) { + // Truncate in range, clamp at the endpoints and map NaN to zero. + if (std::isnan(value)) return 0; + if (value >= static_cast(std::numeric_limits::max())) + return std::numeric_limits::max(); + if (value <= static_cast(std::numeric_limits::min())) + return std::numeric_limits::min(); + return static_cast(value); +} + +template <> +int32_t numeric_cast(float value) { + return floating_to_integer(value); +} +template <> +int32_t numeric_cast(double value) { + return floating_to_integer(value); +} +template <> +int64_t numeric_cast(float value) { + return floating_to_integer(value); +} +template <> +int64_t numeric_cast(double value) { + return floating_to_integer(value); +} + +template <> +float numeric_cast(double value) { + const double maximum = std::numeric_limits::max(); + // Above the largest finite float, round to infinity at the halfway + // point to the next exponent. + const double overflow = + maximum + std::ldexp(1.0, std::numeric_limits::max_exponent - + std::numeric_limits::digits - 1); + if (value > maximum) + return value >= overflow ? std::numeric_limits::infinity() + : std::numeric_limits::max(); + if (value < -maximum) + return value <= -overflow ? -std::numeric_limits::infinity() + : -std::numeric_limits::max(); + return static_cast(value); +} + +template +T numeric_value(const Expression::Literal& literal) { + switch (literal.type) { + case common::DATE: + case common::INT32: + return numeric_cast(literal.int32_value); + case common::TIMESTAMP: + case common::INT64: + return numeric_cast(literal.int64_value); + case common::FLOAT: + return numeric_cast(literal.float_value); + case common::DOUBLE: + return numeric_cast(literal.double_value); + default: + ASSERT(false); + return T(); + } +} + +} // namespace + +int bind_literal(Expression::Literal& literal, common::TSDataType column_type) { + using Literal = Expression::Literal; + if (is_numeric_type(column_type) && is_numeric_type(literal.type)) { + switch (column_type) { + case common::DATE: + case common::INT32: + literal = Literal::int32(numeric_value(literal)); + break; + case common::TIMESTAMP: + case common::INT64: + literal = Literal::int64(numeric_value(literal)); + break; + case common::FLOAT: + literal = Literal::float32(numeric_value(literal)); + break; + case common::DOUBLE: + literal = Literal::float64(numeric_value(literal)); + break; + default: + return common::E_NOT_SUPPORT; + } + return common::E_OK; + } + if ((column_type == common::BOOLEAN && literal.type == common::BOOLEAN) || + (common::is_string_type(column_type) && + common::is_string_type(literal.type))) + return common::E_OK; + return common::E_NOT_SUPPORT; +} + +AlignedFieldFilter::AlignedFieldFilter(Kind kind, std::string column, + CompareOp op, Literal literal) + : BoundPredicate(kind, op), + column_(std::move(column)), + literal_(std::move(literal)) {} + +AlignedFieldFilter::AlignedFieldFilter(Kind kind, Ptr left, Ptr right) + : BoundPredicate(kind, std::move(left), std::move(right)) {} + +AlignedFieldFilter::Ptr AlignedFieldFilter::compare(std::string column, + CompareOp op, + Literal literal) { + return Ptr(new AlignedFieldFilter(Kind::COMPARISON, to_lower(column), op, + std::move(literal))); +} + +AlignedFieldFilter::Ptr AlignedFieldFilter::is_null(std::string column) { + return Ptr(new AlignedFieldFilter(Kind::IS_NULL, to_lower(column), + CompareOp::EQ, Literal())); +} + +AlignedFieldFilter::Ptr AlignedFieldFilter::is_not_null(std::string column) { + return Ptr(new AlignedFieldFilter(Kind::IS_NOT_NULL, to_lower(column), + CompareOp::EQ, Literal())); +} + +AlignedFieldFilter::Ptr AlignedFieldFilter::and_filter(Ptr left, Ptr right) { + return Ptr( + new AlignedFieldFilter(Kind::AND, std::move(left), std::move(right))); +} + +AlignedFieldFilter::Ptr AlignedFieldFilter::or_filter(Ptr left, Ptr right) { + return Ptr( + new AlignedFieldFilter(Kind::OR, std::move(left), std::move(right))); +} + +AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { + if (child && child->kind() == Kind::NOT) { + // Keep NOT(NULL operand) invalid across repeated negations. + if (!child->left_) return child; + return Ptr(static_cast(child->left_.release())); + } + return Ptr(new AlignedFieldFilter(Kind::NOT, std::move(child), nullptr)); +} + +int AlignedFieldFilter::from_expression(const Expression& expr, Ptr& out, + bool table_columns) { + auto leaf = [&](ExpressionType type, const Expression::Operand& operand, + Ptr& result) -> int { + std::string name = + table_columns ? to_lower(operand.reference) : operand.reference; + switch (type) { + case Kind::IS_NULL: + case Kind::IS_NOT_NULL: + case Kind::COMPARISON: + break; + case ExpressionType::BETWEEN: + case ExpressionType::NOT_BETWEEN: { + Ptr lower(new AlignedFieldFilter( + Kind::COMPARISON, name, CompareOp::GE, operand.literal)); + Ptr upper(new AlignedFieldFilter(Kind::COMPARISON, name, + CompareOp::LE, operand.upper)); + result = and_filter(std::move(lower), std::move(upper)); + if (type == ExpressionType::NOT_BETWEEN) + result = not_filter(std::move(result)); + return common::E_OK; + } + default: + return common::E_NOT_SUPPORT; + } + result.reset(new AlignedFieldFilter( + type, std::move(name), operand.comparison, operand.literal)); + return common::E_OK; + }; + return bind_expression( + expr, out, leaf, [](ExpressionType type, Ptr left, Ptr right) { + if (type == ExpressionType::NOT) return not_filter(std::move(left)); + if (type == AND_EXPR) + return and_filter(std::move(left), std::move(right)); + return or_filter(std::move(left), std::move(right)); + }); +} + +int AlignedFieldFilter::bind_series(const SeriesBindings& bindings) { + if (left_) { + int ret = static_cast(left_.get()) + ->bind_series(bindings); + if (ret != common::E_OK || !right_) return ret; + return static_cast(right_.get()) + ->bind_series(bindings); + } + auto it = bindings.find(column_); + if (it == bindings.end()) return common::E_COLUMN_NOT_EXIST; + series_index_ = it->second.first; + return kind_ == Kind::COMPARISON ? bind_literal(literal_, it->second.second) + : common::E_OK; +} + +std::vector AlignedFieldFilter::referenced_columns() const { + std::vector columns; + std::set seen_columns; + std::set seen_nodes; + std::vector stack{this}; + while (!stack.empty()) { + const AlignedFieldFilter* node = stack.back(); + stack.pop_back(); + if (node == nullptr || !seen_nodes.insert(node).second) continue; + if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || + node->kind_ == Kind::IS_NOT_NULL) { + if (seen_columns.insert(node->column_).second) { + columns.push_back(node->column_); + } + continue; + } + if (node->right_) stack.push_back(node->right_field()); + if (node->left_) stack.push_back(node->left_field()); + } + return columns; +} + +bool AlignedFieldFilter::is_valid() const { + switch (kind_) { + case Kind::COMPARISON: + case Kind::IS_NULL: + case Kind::IS_NOT_NULL: + return true; + case Kind::NOT: + return left_ && left_field()->is_valid(); + case Kind::BETWEEN: + case Kind::NOT_BETWEEN: + case Kind::REGEXP: + case Kind::NOT_REGEXP: + case Kind::CUSTOM: + case SERIES_EXPR: + case GLOBALTIME_EXPR: + case INVALID_EXPR: + return false; + case Kind::AND: + case Kind::OR: + return left_ != nullptr && right_ != nullptr && + left_field()->is_valid() && right_field()->is_valid(); + } + return false; +} + +int AlignedFieldFilter::bind(TableSchema& schema) { + if (kind_ == Kind::NOT) { + return left_ + ? static_cast(left_.get())->bind(schema) + : common::E_INVALID_ARG; + } + if (kind_ == Kind::AND || kind_ == Kind::OR) { + if (!left_ || !right_) return common::E_INVALID_ARG; + const int ret = + static_cast(left_.get())->bind(schema); + if (ret != common::E_OK) return ret; + return static_cast(right_.get())->bind(schema); + } + const common::ColumnSchema column = schema.get_column_schema(column_); + if (!column.is_valid()) return common::E_COLUMN_NOT_EXIST; + if (column.column_category_ != common::ColumnCategory::FIELD) + return common::E_INVALID_ARG; + if (kind_ != Kind::COMPARISON) return common::E_OK; + return bind_literal(literal_, column.data_type_); +} + +} // namespace storage diff --git a/cpp/src/reader/filter/bind_expression.h b/cpp/src/reader/filter/bind_expression.h index 0a91b0006..4255a5119 100644 --- a/cpp/src/reader/filter/bind_expression.h +++ b/cpp/src/reader/filter/bind_expression.h @@ -24,6 +24,9 @@ namespace storage { +// Validate the literal and convert numeric values to the column's type. +int bind_literal(Expression::Literal& literal, common::TSDataType column_type); + // Bind the same logical nodes for device IDs, table fields and tree series. // The leaf binder resolves names and literals for the query's schema. template diff --git a/cpp/test/reader/aligned_field_filter_regression_test.cc b/cpp/test/reader/aligned_field_filter_regression_test.cc index 4abce065a..653c3a55e 100644 --- a/cpp/test/reader/aligned_field_filter_regression_test.cc +++ b/cpp/test/reader/aligned_field_filter_regression_test.cc @@ -521,7 +521,7 @@ TEST_P(AlignedFieldFilterRegressionTest, NotPreservesFloatingNaNRowSemantics) { } TEST_P(AlignedFieldFilterRegressionTest, - JavaNumericLiteralsUseTheDeclaredColumnType) { + NumericLiteralsUseTheDeclaredColumnType) { write_floats(); for (const std::string column : {"v", "f", "d"}) { for (const auto& literal : diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/aligned_field_filter_test.cc index ba6ce85ab..ac1cd6dfa 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/aligned_field_filter_test.cc @@ -118,7 +118,7 @@ TEST(AlignedFieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { } } -TEST(AlignedFieldFilterTest, NumericBindingMatchesJavaNumberConversions) { +TEST(AlignedFieldFilterTest, NumericBindingHandlesNarrowingAndRounding) { using namespace common; using A = AlignedFieldFilter; using L = A::Literal; @@ -127,8 +127,6 @@ TEST(AlignedFieldFilterTest, NumericBindingMatchesJavaNumberConversions) { const double nan = std::numeric_limits::quiet_NaN(); const float maximum = std::numeric_limits::max(); const double overflow = double(maximum) + std::ldexp(1.0, 103); - // Golden results verified against Java ValueFilterApi.eq, including - // narrowing, saturation, rounding, NaN, signed zero, and date aliases. const std::vector cases{ {INT64, L::int32(10), L::int64(10)}, {INT32, L::int64(4294967297LL), L::int32(1)}, From 3d927d5a002025b0fa6391c37ef037efb7a8e8e7 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 21:58:25 +0800 Subject: [PATCH 05/10] Pass TAG and FIELD expressions directly to table queries --- cpp/examples/cpp_examples/demo_read.cpp | 21 ++++------ cpp/src/reader/expression.h | 9 ----- cpp/src/reader/table_query_executor.cc | 27 ++++++------- cpp/src/reader/table_query_executor.h | 7 ++-- cpp/src/reader/tsfile_reader.cc | 29 +++++++------- cpp/src/reader/tsfile_reader.h | 32 +++++++++------- cpp/test/reader/table_field_filter_test.cc | 38 ++++++++++++++++--- .../tsfile/references/properties-filters.md | 7 ++-- 8 files changed, 95 insertions(+), 75 deletions(-) diff --git a/cpp/examples/cpp_examples/demo_read.cpp b/cpp/examples/cpp_examples/demo_read.cpp index 90e24c676..b851d1b03 100644 --- a/cpp/examples/cpp_examples/demo_read.cpp +++ b/cpp/examples/cpp_examples/demo_read.cpp @@ -18,7 +18,6 @@ */ #include -#include #include #include @@ -41,17 +40,12 @@ int demo_read() { columns.emplace_back("id2"); columns.emplace_back("s1"); - std::shared_ptr table_schema; - HANDLE_ERROR(reader.get_table_schema(table_name, table_schema)); - storage::Filter* tag_filter1 = - storage::TagFilterBuilder(table_schema.get()).eq("id1", "id1_filed_1"); - storage::Filter* tag_filter2 = - storage::TagFilterBuilder(table_schema.get()).eq("id2", "id1_filed_2"); - storage::Filter* tag_filter = storage::TagFilterBuilder(table_schema.get()) - .and_filter(tag_filter1, tag_filter2); - // Column vector contains the columns you want to select. - HANDLE_ERROR( - reader.query(table_name, columns, 0, 100, temp_ret, tag_filter)); + using E = storage::Expression; + auto tag_filter = E::and_filter( + E::compare("id1", E::CompareOp::EQ, E::Literal::string("id1_filed_1")), + E::compare("id2", E::CompareOp::EQ, E::Literal::string("id1_filed_2"))); + HANDLE_ERROR(reader.query(table_name, columns, 0, 100, temp_ret, + tag_filter.get(), nullptr)); // Get query handler. auto ret = dynamic_cast(temp_ret); @@ -104,10 +98,9 @@ int demo_read() { } // Close query result set. - ret->close(); + reader.destroy_query_data_set(ret); // Close reader. reader.close(); - delete tag_filter; return 0; } diff --git a/cpp/src/reader/expression.h b/cpp/src/reader/expression.h index 0d6987bbc..e78558cff 100644 --- a/cpp/src/reader/expression.h +++ b/cpp/src/reader/expression.h @@ -146,15 +146,6 @@ struct Expression { ~Expression() { destroy(); } }; -// Borrowed during query preparation. Each result owns its bound filters. -struct TablePredicates { - TablePredicates() : tag_filter(nullptr), field_filter(nullptr) {} - TablePredicates(const Expression* tag, const Expression* field) - : tag_filter(tag), field_filter(field) {} - const Expression* tag_filter; - const Expression* field_filter; -}; - class QueryExpression { public: QueryExpression() : has_filter_(false), expression_(nullptr) {} diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 1eb526872..d83e7e76c 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -37,23 +37,25 @@ int TableQueryExecutor::query(const std::string& table_name, Filter* field_filter, int offset, int limit, ResultSet*& ret_qds) { return query_impl(table_name, columns, time_filter, tag_filter, - field_filter, {nullptr, nullptr}, offset, limit, ret_qds); + field_filter, nullptr, nullptr, offset, limit, ret_qds); } int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, - Filter* time_filter, TablePredicates predicates, - int offset, int limit, ResultSet*& ret_qds) { + Filter* time_filter, int offset, int limit, + ResultSet*& ret_qds, const Expression* tag_filter, + const Expression* field_filter) { return query_impl(table_name, columns, time_filter, nullptr, nullptr, - predicates, offset, limit, ret_qds); + tag_filter, field_filter, offset, limit, ret_qds); } int TableQueryExecutor::query_impl(const std::string& table_name, const std::vector& columns, Filter* time_filter, Filter* tag_filter, Filter* field_filter, - TablePredicates predicates, int offset, - int limit, ResultSet*& ret_qds) { + const Expression* tag_expression, + const Expression* field_expression, + int offset, int limit, ResultSet*& ret_qds) { std::unique_ptr owned_time(time_filter), owned_field(field_filter); int ret = common::E_OK; TsFileMeta* file_metadata = nullptr; @@ -87,17 +89,16 @@ int TableQueryExecutor::query_impl(const std::string& table_name, data_types.push_back(table_schema->get_data_types()[ind]); } std::unique_ptr bound_tag; - ret = - predicates.tag_filter - ? TagFilter::bind(*predicates.tag_filter, *table_schema, bound_tag) - : TagFilter::bind_for_query(tag_filter, *table_schema, bound_tag); + ret = tag_expression + ? TagFilter::bind(*tag_expression, *table_schema, bound_tag) + : TagFilter::bind_for_query(tag_filter, *table_schema, bound_tag); if (ret != common::E_OK) { return ret; } - if (predicates.field_filter) { + if (field_expression) { AlignedFieldFilter::Ptr bound; - ret = AlignedFieldFilter::from_expression(*predicates.field_filter, - bound, true); + ret = + AlignedFieldFilter::from_expression(*field_expression, bound, true); if (ret != common::E_OK) { return ret; } diff --git a/cpp/src/reader/table_query_executor.h b/cpp/src/reader/table_query_executor.h index 3120903ba..fea6b1d3e 100644 --- a/cpp/src/reader/table_query_executor.h +++ b/cpp/src/reader/table_query_executor.h @@ -86,8 +86,8 @@ class TableQueryExecutor { ResultSet*& ret_qds); int query(const std::string& table_name, const std::vector& columns, Filter* time_filter, - TablePredicates predicates, int offset, int limit, - ResultSet*& result); + int offset, int limit, ResultSet*& result, + const Expression* tag_filter, const Expression* field_filter); int query_on_tree(const std::vector>& devices, const std::vector& tag_columns, const std::vector& field_columns, @@ -98,7 +98,8 @@ class TableQueryExecutor { int query_impl(const std::string& table_name, const std::vector& columns, Filter* time_filter, Filter* tag_filter, Filter* field_filter, - TablePredicates predicates, int offset, int limit, + const Expression* tag_expression, + const Expression* field_expression, int offset, int limit, ResultSet*& result); IMetadataQuerier* meta_data_querier_; TsFileIOReader* tsfile_io_reader_; diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index c256904cb..a7c1ff9dc 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -496,35 +496,38 @@ int TsFileReader::query(const std::vector& paths, int TsFileReader::query(const std::string& table_name, const std::vector& columns, int64_t start_time, int64_t end_time, - TablePredicates predicates, ResultSet*& result, - int batch_size) { - return query(table_name, columns, start_time, end_time, 0, -1, predicates, - result, batch_size); + ResultSet*& result_set, const Expression* tag_filter, + const Expression* field_filter, int batch_size) { + return query(table_name, columns, start_time, end_time, 0, -1, result_set, + tag_filter, field_filter, batch_size); } int TsFileReader::query(const std::string& table_name, const std::vector& columns, int64_t start_time, int64_t end_time, int offset, - int limit, TablePredicates predicates, - ResultSet*& result, int batch_size) { - result = nullptr; + int limit, ResultSet*& result_set, + const Expression* tag_filter, + const Expression* field_filter, int batch_size) { + result_set = nullptr; if (!tsfile_executor_ || offset < 0) return E_INVALID_ARG; ensure_table_query_executor(batch_size); return table_query_executor_->query( to_lower(table_name), columns, - new TimeBetween(start_time, end_time, false), predicates, offset, limit, - result); + new TimeBetween(start_time, end_time, false), offset, limit, result_set, + tag_filter, field_filter); } int TsFileReader::queryByRow(const std::string& table_name, const std::vector& columns, - int offset, int limit, TablePredicates predicates, - ResultSet*& result, int batch_size) { - result = nullptr; + int offset, int limit, ResultSet*& result_set, + const Expression* tag_filter, + const Expression* field_filter, int batch_size) { + result_set = nullptr; if (!tsfile_executor_ || offset < 0) return E_INVALID_ARG; ensure_table_query_executor(batch_size); return table_query_executor_->query(to_lower(table_name), columns, nullptr, - predicates, offset, limit, result); + offset, limit, result_set, tag_filter, + field_filter); } int TsFileReader::query_table_on_tree( diff --git a/cpp/src/reader/tsfile_reader.h b/cpp/src/reader/tsfile_reader.h index 814359424..73ea0df33 100644 --- a/cpp/src/reader/tsfile_reader.h +++ b/cpp/src/reader/tsfile_reader.h @@ -134,6 +134,18 @@ class TsFileReader { int64_t end_time, int offset, int limit, ResultSet*& result_set, Filter* tag_filter = nullptr, int batch_size = 0); + // Each expression may be null. The result owns its query-time bindings. + int query(const std::string& table_name, + const std::vector& columns, int64_t start_time, + int64_t end_time, ResultSet*& result_set, + const Expression* tag_filter, const Expression* field_filter, + int batch_size = 0); + int query(const std::string& table_name, + const std::vector& columns, int64_t start_time, + int64_t end_time, int offset, int limit, ResultSet*& result_set, + const Expression* tag_filter, const Expression* field_filter, + int batch_size = 0); + /** * @brief Query tree-model time series by row with offset and limit. * @@ -201,24 +213,16 @@ class TsFileReader { int limit, ResultSet*& result_set, Filter* tag_filter = nullptr, int batch_size = 0); - // Expressions are borrowed for query preparation; the result owns its - // bindings. - int query(const std::vector& selected_series, - const Expression& predicate, ResultSet*& result); - int query(const std::string& table_name, - const std::vector& columns, int64_t start_time, - int64_t end_time, TablePredicates predicates, ResultSet*& result, - int batch_size = 0); - int query(const std::string& table_name, - const std::vector& columns, int64_t start_time, - int64_t end_time, int offset, int limit, - TablePredicates predicates, ResultSet*& result, - int batch_size = 0); int queryByRow(const std::string& table_name, const std::vector& columns, int offset, - int limit, TablePredicates predicates, ResultSet*& result, + int limit, ResultSet*& result_set, + const Expression* tag_filter, const Expression* field_filter, int batch_size = 0); + // Expressions are borrowed for query preparation; the result owns its + // bindings. + int query(const std::vector& selected_series, + const Expression& predicate, ResultSet*& result); int query_table_on_tree(const std::vector& measurement_names, int64_t star_time, int64_t end_time, ResultSet*& result_set); diff --git a/cpp/test/reader/table_field_filter_test.cc b/cpp/test/reader/table_field_filter_test.cc index a5608d522..529ded3b7 100644 --- a/cpp/test/reader/table_field_filter_test.cc +++ b/cpp/test/reader/table_field_filter_test.cc @@ -332,8 +332,8 @@ TEST_P(TableFieldFilterTest, ReuseNamedExpressionForTableAndTree) { auto tag = Expression::compare("id", Expression::CompareOp::EQ, Expression::Literal::string("d0")); ResultSet *table = nullptr, *tree = nullptr; - ASSERT_EQ(E_OK, reader.queryByRow("t", {"i"}, 0, -1, - {tag.get(), field.get()}, table)); + ASSERT_EQ(E_OK, reader.queryByRow("t", {"i"}, 0, -1, table, tag.get(), + field.get())); std::vector> devices; ASSERT_EQ(E_OK, reader.get_all_devices("t", devices)); ASSERT_EQ(2u, devices.size()); @@ -356,6 +356,33 @@ TEST_P(TableFieldFilterTest, ReuseNamedExpressionForTableAndTree) { } } +TEST_P(TableFieldFilterTest, PageAfterTimeRangeAndOptionalFilters) { + TsFileReader reader; + ASSERT_EQ(E_OK, reader.open(filename_)); + auto tag = Expression::compare("id", Expression::CompareOp::EQ, + Expression::Literal::string("d1")); + auto field = Expression::compare("flag", Expression::CompareOp::EQ, + Expression::Literal::boolean(true)); + // In [2, 7] the matching odd timestamps are 3, 5 and 7 on each device. + auto check = [&](const Expression* tag_filter, + const Expression* field_filter, int64_t expected_value) { + ResultSet* rows = nullptr; + ASSERT_EQ(E_OK, reader.query("t", {"v"}, base_ + 2, base_ + 7, 1, 1, + rows, tag_filter, field_filter)); + bool next = false; + ASSERT_EQ(E_OK, rows->next(next)); + ASSERT_TRUE(next); + EXPECT_EQ(expected_value, rows->get_value(2)); + ASSERT_EQ(E_OK, rows->next(next)); + EXPECT_FALSE(next); + reader.destroy_query_data_set(rows); + }; + check(nullptr, nullptr, 3); + check(tag.get(), nullptr, 103); + check(nullptr, field.get(), 5); + check(tag.get(), field.get(), 105); +} + TEST_P(TableFieldFilterTest, BindTagAgainstQuerySchemaAndRejectWrongCategory) { TsFileReader reader; ASSERT_EQ(E_OK, reader.open(filename_)); @@ -374,13 +401,12 @@ TEST_P(TableFieldFilterTest, BindTagAgainstQuerySchemaAndRejectWrongCategory) { EXPECT_EQ(100, rows->get_value(2)); reader.destroy_query_data_set(rows); auto wrong = Expression::is_null("v"); - EXPECT_EQ( - E_COLUMN_NOT_EXIST, - reader.queryByRow("t", {"v"}, 0, 0, {wrong.get(), nullptr}, rows)); + EXPECT_EQ(E_COLUMN_NOT_EXIST, + reader.queryByRow("t", {"v"}, 0, 0, rows, wrong.get(), nullptr)); EXPECT_EQ(nullptr, rows); wrong = Expression::is_null("id"); EXPECT_EQ(E_INVALID_ARG, - reader.query("t", {"v"}, 0, 0, {nullptr, wrong.get()}, rows)); + reader.query("t", {"v"}, 0, 0, rows, nullptr, wrong.get())); EXPECT_EQ(nullptr, rows); } diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 3368606b3..e8c64d285 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -83,12 +83,13 @@ auto hot = E::compare("temperature", E::CompareOp::GT, E::Literal::float64(22.5) auto site = E::compare("site", E::CompareOp::EQ, E::Literal::string("west")); storage::ResultSet* rows = nullptr; int ret = reader.queryByRow("weather", {"temperature"}, 0, 100, - {site.get(), hot.get()}, rows); + rows, site.get(), hot.get()); // Consume rows and call reader.destroy_query_data_set(rows) after success. ``` -Table queries take separate `tag_filter` and `field_filter` expressions in -`TablePredicates`. TAG references bind to device-ID segments; FIELD references +Pass `nullptr` for either `tag_filter` or `field_filter` to omit that condition. +Time bounds restrict the timestamps scanned. Offset and limit count rows that +pass the filters. TAG references bind to device-ID segments. FIELD references bind to column types and support page pruning. TAG regular expressions operate on strings. Comparisons, inclusive ranges, null tests and Boolean composition are available for values. For a missing TAG, `NOT(column = x)` matches. For a From e2267e6d4f410f2b765e9a729848705cdc5c9f3a Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 23:17:06 +0800 Subject: [PATCH 06/10] Remove the C++ TAG filter builder and use named expressions --- cpp/src/cwrapper/tsfile_cwrapper.cc | 164 +++++++-------- cpp/src/reader/filter/tag_filter.cc | 147 -------------- cpp/src/reader/filter/tag_filter.h | 44 ---- cpp/src/reader/table_query_executor.cc | 8 +- cpp/src/reader/tsfile_reader.cc | 8 +- cpp/test/cwrapper/cwrapper_extended_test.cc | 6 +- cpp/test/reader/filter/tag_filter_test.cc | 189 ++++++++---------- cpp/test/reader/table_field_filter_test.cc | 12 +- cpp/test/reader/table_read_failure_test.cc | 12 +- .../table_view/tsfile_reader_table_test.cc | 29 +-- cpp/test/tools/model_format_e2e_test.cc | 2 + cpp/tools/commands/commands.h | 5 - cpp/tools/commands/row_query.cc | 67 +++---- skills/tsfile/references/docs-map.yaml | 1 + .../tsfile/references/properties-filters.md | 13 +- 15 files changed, 235 insertions(+), 472 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 6f4717931..65db26edb 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -109,6 +109,55 @@ ERRNO validate_table_schema(const TableSchema* schema) { return common::E_OK; } +storage::Expression::Ptr tag_expression(const char* column, const char* value, + TagFilterOp op) { + using E = storage::Expression; + E::CompareOp comparison; + switch (op) { + case TAG_FILTER_EQ: + comparison = E::CompareOp::EQ; + break; + case TAG_FILTER_NEQ: + comparison = E::CompareOp::NE; + break; + case TAG_FILTER_LT: + comparison = E::CompareOp::LT; + break; + case TAG_FILTER_LTEQ: + comparison = E::CompareOp::LE; + break; + case TAG_FILTER_GT: + comparison = E::CompareOp::GT; + break; + case TAG_FILTER_GTEQ: + comparison = E::CompareOp::GE; + break; + case TAG_FILTER_REGEXP: + case TAG_FILTER_NOT_REGEXP: + return E::regexp(column, value, op == TAG_FILTER_NOT_REGEXP); + case TAG_FILTER_IS_NULL: + return E::is_null(column); + case TAG_FILTER_IS_NOT_NULL: + return E::is_not_null(column); + default: + return nullptr; + } + return E::compare(column, comparison, E::Literal::string(value)); +} + +TagFilterHandle combine_tag_filters(storage::ExpressionType op, + TagFilterHandle left, + TagFilterHandle right) { + try { + // The C caller retains both operands if allocating the parent fails. + return new storage::Expression( + op, static_cast(left), + static_cast(right)); + } catch (...) { + return nullptr; + } +} + } // namespace #ifdef __cplusplus @@ -699,10 +748,19 @@ PreparedSeriesHandle tsfile_reader_prepare_table_series( } try { std::shared_ptr prepared; - *err_code = - static_cast(reader)->prepare_table_series( - table_name, column_name, - static_cast(tag_filter), prepared); + auto* r = static_cast(reader); + std::unique_ptr bound; + if (tag_filter) { + std::shared_ptr schema; + *err_code = r->get_table_schema(table_name, schema); + if (*err_code != common::E_OK) return nullptr; + *err_code = storage::TagFilter::bind( + *static_cast(tag_filter), *schema, + bound); + if (*err_code != common::E_OK) return nullptr; + } + *err_code = r->prepare_table_series(table_name, column_name, + bound.get(), prepared); if (*err_code != common::E_OK) { return nullptr; } @@ -947,7 +1005,8 @@ ResultSet tsfile_reader_query_table_by_row( *err_code = r->queryByRow( table_name == nullptr ? "" : table_name, columns, offset, limit, - result_set, static_cast(tag_filter), batch_size); + result_set, static_cast(tag_filter), + nullptr, batch_size); return result_set; } @@ -979,7 +1038,8 @@ ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, const int normalized_limit = limit < 0 ? -1 : limit; *err_code = static_cast(reader)->query( table_name, columns, start_time, end_time, offset, normalized_limit, - result_set, static_cast(tag_filter), batch_size); + result_set, static_cast(tag_filter), + nullptr, batch_size); return result_set; } catch (const std::bad_alloc&) { *err_code = common::E_OOM; @@ -1003,7 +1063,8 @@ ResultSet tsfile_query_table_batch(TsFileReader reader, const char* table_name, } *err_code = r->query(table_name, column_names, start_time, end_time, table_result_set, - static_cast(tag_filter), batch_size); + static_cast(tag_filter), + nullptr, batch_size); return table_result_set; } @@ -2836,46 +2897,11 @@ ERRNO tsfile_tag_filter_create_checked(TsFileReader reader, if (ret != common::E_OK) { return ret; } - auto builder = storage::TagFilterBuilder::for_query(schema.get()); - storage::Filter* filter = nullptr; - switch (op) { - case TAG_FILTER_EQ: - filter = builder.eq(column_name, value); - break; - case TAG_FILTER_NEQ: - filter = builder.neq(column_name, value); - break; - case TAG_FILTER_LT: - filter = builder.lt(column_name, value); - break; - case TAG_FILTER_LTEQ: - filter = builder.lteq(column_name, value); - break; - case TAG_FILTER_GT: - filter = builder.gt(column_name, value); - break; - case TAG_FILTER_GTEQ: - filter = builder.gteq(column_name, value); - break; - case TAG_FILTER_REGEXP: - filter = builder.reg_exp(column_name, value); - break; - case TAG_FILTER_NOT_REGEXP: - filter = builder.not_reg_exp(column_name, value); - break; - case TAG_FILTER_IS_NULL: - filter = builder.is_null(column_name); - break; - case TAG_FILTER_IS_NOT_NULL: - filter = builder.is_not_null(column_name); - break; - default: - return common::E_INVALID_ARG; - } - if (filter == nullptr) { + auto expr = tag_expression(column_name, value, op); + if (!expr) return common::E_INVALID_ARG; + if (schema->find_id_column_order(column_name) < 0) return common::E_COLUMN_NOT_EXIST; - } - *out_filter = static_cast(filter); + *out_filter = expr.release(); return common::E_OK; } catch (const std::bad_alloc&) { return common::E_OOM; @@ -2921,14 +2947,12 @@ ERRNO tsfile_tag_filter_between_checked(TsFileReader reader, if (ret != common::E_OK) { return ret; } - auto builder = storage::TagFilterBuilder::for_query(schema.get()); - storage::Filter* filter = - is_not ? builder.not_between_and(column_name, lower, upper) - : builder.between_and(column_name, lower, upper); - if (filter == nullptr) { + if (schema->find_id_column_order(column_name) < 0) return common::E_COLUMN_NOT_EXIST; - } - *out_filter = static_cast(filter); + using E = storage::Expression; + *out_filter = E::between(column_name, E::Literal::string(lower), + E::Literal::string(upper), is_not) + .release(); return common::E_OK; } catch (const std::bad_alloc&) { return common::E_OOM; @@ -2956,42 +2980,23 @@ TagFilterHandle tsfile_tag_filter_between(TsFileReader reader, TagFilterHandle tsfile_tag_filter_and(TagFilterHandle left, TagFilterHandle right) { - if (!left || !right) return nullptr; - try { - return storage::TagFilterBuilder::and_filter( - static_cast(left), - static_cast(right)); - } catch (...) { - return nullptr; - } + if (!left || !right || left == right) return nullptr; + return combine_tag_filters(storage::AND_EXPR, left, right); } TagFilterHandle tsfile_tag_filter_or(TagFilterHandle left, TagFilterHandle right) { - if (!left || !right) return nullptr; - try { - return storage::TagFilterBuilder::or_filter( - static_cast(left), - static_cast(right)); - } catch (...) { - return nullptr; - } + if (!left || !right || left == right) return nullptr; + return combine_tag_filters(storage::OR_EXPR, left, right); } TagFilterHandle tsfile_tag_filter_not(TagFilterHandle filter) { if (!filter) return nullptr; - try { - return storage::TagFilterBuilder::not_filter( - static_cast(filter)); - } catch (...) { - return nullptr; - } + return combine_tag_filters(storage::ExpressionType::NOT, filter, nullptr); } void tsfile_tag_filter_free(TagFilterHandle filter) { - if (filter) { - delete static_cast(filter); - } + delete static_cast(filter); } ResultSet tsfile_query_table_with_tag_filter( @@ -3006,7 +3011,8 @@ ResultSet tsfile_query_table_with_tag_filter( } *err_code = r->query(table_name, column_names, start_time, end_time, table_result_set, - static_cast(tag_filter), batch_size); + static_cast(tag_filter), + nullptr, batch_size); return table_result_set; } diff --git a/cpp/src/reader/filter/tag_filter.cc b/cpp/src/reader/filter/tag_filter.cc index b5d352bf1..b7e3c07c9 100644 --- a/cpp/src/reader/filter/tag_filter.cc +++ b/cpp/src/reader/filter/tag_filter.cc @@ -19,7 +19,6 @@ #include "tag_filter.h" -#include #include #include "reader/filter/bind_expression.h" @@ -216,150 +215,4 @@ TagOr::TagOr(TagFilter* left, TagFilter* right) : TagFilter(Kind::OR, left, right) {} TagNot::TagNot(TagFilter* child) : TagFilter(Kind::NOT, child, nullptr) {} -// TagFilterBuilder implementation -TagFilterBuilder::TagFilterBuilder(TableSchema* schema) - : table_schema_(schema) {} - -Filter* TagFilterBuilder::build(Expression::Ptr expression) { - // The legacy builder also returns an immediately evaluable Filter. - // Keep the named operand for readers that bind against a different schema. - std::unique_ptr bound; - if (bind_for_standalone_use_) { - if (TagFilter::bind(*expression, *table_schema_, bound) != common::E_OK) - return nullptr; - } else { - if (table_schema_->find_id_column_order( - expression->operand()->reference) < 0) - return nullptr; - bound.reset(new TagFilter(-1, "")); - } - bound->source_ = std::move(expression); - return bound.release(); -} - -Filter* TagFilterBuilder::eq(const std::string& columnName, - const std::string& value) { - return build(Expression::compare(columnName, Expression::CompareOp::EQ, - Expression::Literal::string(value))); -} - -Filter* TagFilterBuilder::neq(const std::string& columnName, - const std::string& value) { - return build(Expression::compare(columnName, Expression::CompareOp::NE, - Expression::Literal::string(value))); -} - -Filter* TagFilterBuilder::lt(const std::string& columnName, - const std::string& value) { - return build(Expression::compare(columnName, Expression::CompareOp::LT, - Expression::Literal::string(value))); -} - -Filter* TagFilterBuilder::lteq(const std::string& columnName, - const std::string& value) { - return build(Expression::compare(columnName, Expression::CompareOp::LE, - Expression::Literal::string(value))); -} - -Filter* TagFilterBuilder::gt(const std::string& columnName, - const std::string& value) { - return build(Expression::compare(columnName, Expression::CompareOp::GT, - Expression::Literal::string(value))); -} - -Filter* TagFilterBuilder::gteq(const std::string& columnName, - const std::string& value) { - return build(Expression::compare(columnName, Expression::CompareOp::GE, - Expression::Literal::string(value))); -} - -Filter* TagFilterBuilder::reg_exp(const std::string& columnName, - const std::string& value) { - return build(Expression::regexp(columnName, value, false)); -} - -Filter* TagFilterBuilder::not_reg_exp(const std::string& columnName, - const std::string& value) { - return build(Expression::regexp(columnName, value, true)); -} - -Filter* TagFilterBuilder::is_null(const std::string& columnName) { - return build(Expression::is_null(columnName)); -} - -Filter* TagFilterBuilder::is_not_null(const std::string& columnName) { - return build(Expression::is_not_null(columnName)); -} - -Filter* TagFilterBuilder::between_and(const std::string& columnName, - const std::string& lower, - const std::string& upper) { - return build( - Expression::between(columnName, Expression::Literal::string(lower), - Expression::Literal::string(upper), false)); -} - -Filter* TagFilterBuilder::not_between_and(const std::string& columnName, - const std::string& lower, - const std::string& upper) { - return build(Expression::between(columnName, - Expression::Literal::string(lower), - Expression::Literal::string(upper), true)); -} - -Filter* TagFilterBuilder::and_filter(Filter* left, Filter* right) { - auto* lhs = dynamic_cast(left); - auto* rhs = dynamic_cast(right); - if (!lhs || !rhs || lhs == rhs) return nullptr; - return new TagAnd(lhs, rhs); -} - -Filter* TagFilterBuilder::or_filter(Filter* left, Filter* right) { - auto* lhs = dynamic_cast(left); - auto* rhs = dynamic_cast(right); - if (!lhs || !rhs || lhs == rhs) return nullptr; - return new TagOr(lhs, rhs); -} - -Filter* TagFilterBuilder::not_filter(Filter* filter) { - auto* child = dynamic_cast(filter); - return child ? new TagNot(child) : nullptr; -} - -namespace { -class BorrowedTagChild : public TagFilter { - public: - explicit BorrowedTagChild(const TagFilter* child) - : TagFilter(-1, ""), child_(child) {} - bool satisfyRow(std::vector segments) const override { - return child_->satisfyRow(std::move(segments)); - } - - private: - const TagFilter* child_; -}; -} // namespace - -int TagFilter::bind_for_query(const Filter* filter, TableSchema& schema, - std::unique_ptr& bound) { - const auto* tag = dynamic_cast(filter); - if (!tag) return common::E_OK; - if (tag->source_) return bind(*tag->source_, schema, bound); - // Only rebuild built-in logical nodes. Custom and explicitly indexed - // leaves retain their original segment overload and borrowing contract. - if (typeid(*tag) != typeid(TagAnd) && typeid(*tag) != typeid(TagOr) && - typeid(*tag) != typeid(TagNot)) - return common::E_OK; - std::unique_ptr left, right; - int ret = bind_for_query(tag->left_tag(), schema, left); - if (ret != common::E_OK) return ret; - ret = bind_for_query(tag->right_tag(), schema, right); - if (ret != common::E_OK || (!left && !right)) return ret; - if (!left) left.reset(new BorrowedTagChild(tag->left_tag())); - if (!right && tag->right_tag()) - right.reset(new BorrowedTagChild(tag->right_tag())); - bound.reset(new TagFilter(tag->kind(), left.release(), right.release())); - return common::E_OK; -} - } // namespace storage \ No newline at end of file diff --git a/cpp/src/reader/filter/tag_filter.h b/cpp/src/reader/filter/tag_filter.h index 04023014c..da005833b 100644 --- a/cpp/src/reader/filter/tag_filter.h +++ b/cpp/src/reader/filter/tag_filter.h @@ -28,15 +28,12 @@ #include "common/schema.h" #include "reader/filter/bound_predicate.h" -struct table_schema; namespace storage { class TagFilter : public BoundPredicate { public: static int bind(const Expression& expr, TableSchema& schema, std::unique_ptr& out); - static int bind_for_query(const Filter* filter, TableSchema& schema, - std::unique_ptr& bound); TagFilter(int col_idx, std::string tag_value); ~TagFilter() override; @@ -54,8 +51,6 @@ class TagFilter : public BoundPredicate { TagFilter(Kind kind, TagFilter* left, TagFilter* right); private: - friend class TagFilterBuilder; - Expression::Ptr source_; const TagFilter* left_tag() const { return static_cast(left()); } @@ -164,44 +159,5 @@ class TagNot : public TagFilter { explicit TagNot(TagFilter* filter); }; -class TagFilterBuilder { - TableSchema* table_schema_; - bool bind_for_standalone_use_ = true; - - public: - explicit TagFilterBuilder(TableSchema* schema); - // Checked handles validate names immediately and bind indices in the - // reader. - static TagFilterBuilder for_query(TableSchema* schema) { - TagFilterBuilder builder(schema); - builder.bind_for_standalone_use_ = false; - return builder; - } - - Filter* eq(const std::string& columnName, const std::string& value); - Filter* neq(const std::string& columnName, const std::string& value); - Filter* lt(const std::string& columnName, const std::string& value); - Filter* lteq(const std::string& columnName, const std::string& value); - Filter* gt(const std::string& columnName, const std::string& value); - Filter* gteq(const std::string& columnName, const std::string& value); - Filter* reg_exp(const std::string& columnName, const std::string& value); - Filter* not_reg_exp(const std::string& columnName, - const std::string& value); - Filter* is_null(const std::string& columnName); - Filter* is_not_null(const std::string& columnName); - Filter* between_and(const std::string& columnName, const std::string& lower, - const std::string& upper); - Filter* not_between_and(const std::string& columnName, - const std::string& lower, const std::string& upper); - - // Logical operations - static Filter* and_filter(Filter* left, Filter* right); - static Filter* or_filter(Filter* left, Filter* right); - static Filter* not_filter(Filter* filter); - - private: - Filter* build(Expression::Ptr expression); -}; - } // namespace storage #endif // READER_FILTER_TAG_FILTER_H \ No newline at end of file diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index d83e7e76c..af1f4d011 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -89,11 +89,9 @@ int TableQueryExecutor::query_impl(const std::string& table_name, data_types.push_back(table_schema->get_data_types()[ind]); } std::unique_ptr bound_tag; - ret = tag_expression - ? TagFilter::bind(*tag_expression, *table_schema, bound_tag) - : TagFilter::bind_for_query(tag_filter, *table_schema, bound_tag); - if (ret != common::E_OK) { - return ret; + if (tag_expression) { + ret = TagFilter::bind(*tag_expression, *table_schema, bound_tag); + if (ret != common::E_OK) return ret; } if (field_expression) { AlignedFieldFilter::Ptr bound; diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index a7c1ff9dc..1dd0d920e 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -29,7 +29,6 @@ #include "device_meta_iterator.h" #include "file/local_random_access_read_file.h" #include "filter/time_operator.h" -#include "reader/filter/tag_filter.h" #include "tsfile_executor.h" using namespace common; @@ -344,12 +343,7 @@ int TsFileReader::prepare_table_series( common::PageArena pa; pa.init(512, common::MOD_TSFILE_READER); - std::unique_ptr bound_tag; - if (RET_FAIL( - TagFilter::bind_for_query(tag_filter, *table_schema, bound_tag))) - return ret; - DeviceMetaIterator device_iterator( - io_reader, table_root, bound_tag ? bound_tag.get() : tag_filter); + DeviceMetaIterator device_iterator(io_reader, table_root, tag_filter); bool has_next = false; if (RET_FAIL(device_iterator.has_next(has_next))) { return ret; diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 765a2fdfc..baa0279c4 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -483,6 +483,10 @@ TEST(CWrapperExtendedTest, TagFilterCombinations) { tsfile_tag_filter_eq(reader, kTableName, "TAG", "devB"); ASSERT_NE(nullptr, dev_a); ASSERT_NE(nullptr, dev_b); + EXPECT_EQ(nullptr, tsfile_tag_filter_and(dev_a, dev_a)); + EXPECT_EQ(nullptr, tsfile_tag_filter_or(dev_b, dev_b)); + EXPECT_EQ(nullptr, tsfile_tag_filter_and(dev_a, nullptr)); + EXPECT_EQ(nullptr, tsfile_tag_filter_or(nullptr, dev_b)); TagFilterHandle both = tsfile_tag_filter_and(dev_a, dev_b); ASSERT_NE(nullptr, both); ResultSet and_result = tsfile_query_table_with_tag_filter( @@ -505,9 +509,9 @@ TEST(CWrapperExtendedTest, TagFilterCombinations) { &err); ASSERT_EQ(RET_OK, err); ASSERT_NE(nullptr, or_result); + tsfile_tag_filter_free(either); EXPECT_EQ(10, count_result_rows(or_result, &err)); free_tsfile_result_set(&or_result); - tsfile_tag_filter_free(either); dev_a = tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); ASSERT_NE(nullptr, dev_a); diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index 67b85d78f..f5d8fc1de 100644 --- a/cpp/test/reader/filter/tag_filter_test.cc +++ b/cpp/test/reader/filter/tag_filter_test.cc @@ -42,12 +42,18 @@ class TagFilterTest : public ::testing::Test { common::ColumnCategory::TAG); schema_ = new TableSchema("test_table", column_schemas); - builder_ = new TagFilterBuilder(schema_); } - void TearDown() override { - delete builder_; - delete schema_; + void TearDown() override { delete schema_; } + + using E = Expression; + using Op = E::CompareOp; + using Literal = E::Literal; + + std::unique_ptr bind(const E::Ptr& expr) { + std::unique_ptr filter; + EXPECT_EQ(common::E_OK, TagFilter::bind(*expr, *schema_, filter)); + return filter; } // Helper method to create segments starting from index 1 @@ -73,12 +79,11 @@ class TagFilterTest : public ::testing::Test { } TableSchema* schema_ = nullptr; - TagFilterBuilder* builder_ = nullptr; }; // Equality filter TEST_F(TagFilterTest, TagEqFilter) { - auto filter = builder_->eq("name", "john"); + auto filter = bind(E::compare("name", Op::EQ, Literal::string("john"))); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "25", "engineering", "active", "95"); @@ -88,13 +93,11 @@ TEST_F(TagFilterTest, TagEqFilter) { segments = createSegments("alice", "25", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // Inequality filter TEST_F(TagFilterTest, TagNeqFilter) { - auto filter = builder_->neq("name", "john"); + auto filter = bind(E::compare("name", Op::NE, Literal::string("john"))); ASSERT_NE(filter, nullptr); auto segments = @@ -105,13 +108,11 @@ TEST_F(TagFilterTest, TagNeqFilter) { segments = createSegments("john", "25", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // Less than filter TEST_F(TagFilterTest, TagLtFilter) { - auto filter = builder_->lt("age", "30"); + auto filter = bind(E::compare("age", Op::LT, Literal::string("30"))); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "25", "engineering", "active", "95"); @@ -121,13 +122,11 @@ TEST_F(TagFilterTest, TagLtFilter) { segments = createSegments("john", "35", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // Less than or equal filter TEST_F(TagFilterTest, TagLteqFilter) { - auto filter = builder_->lteq("age", "30"); + auto filter = bind(E::compare("age", Op::LE, Literal::string("30"))); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "30", "engineering", "active", "95"); @@ -141,13 +140,11 @@ TEST_F(TagFilterTest, TagLteqFilter) { segments = createSegments("john", "35", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // Greater than filter TEST_F(TagFilterTest, TagGtFilter) { - auto filter = builder_->gt("age", "30"); + auto filter = bind(E::compare("age", Op::GT, Literal::string("30"))); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "35", "engineering", "active", "95"); @@ -157,13 +154,11 @@ TEST_F(TagFilterTest, TagGtFilter) { segments = createSegments("john", "25", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // Greater than or equal filter TEST_F(TagFilterTest, TagGteqFilter) { - auto filter = builder_->gteq("age", "30"); + auto filter = bind(E::compare("age", Op::GE, Literal::string("30"))); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "30", "engineering", "active", "95"); @@ -177,13 +172,12 @@ TEST_F(TagFilterTest, TagGteqFilter) { segments = createSegments("john", "25", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // Between filter TEST_F(TagFilterTest, TagBetweenFilter) { - auto filter = builder_->between_and("age", "25", "35"); + auto filter = + bind(E::between("age", Literal::string("25"), Literal::string("35"))); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "25", "engineering", "active", "95"); @@ -205,13 +199,12 @@ TEST_F(TagFilterTest, TagBetweenFilter) { segments = createSegments("john", "40", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // Not between filter TEST_F(TagFilterTest, TagNotBetweenFilter) { - auto filter = builder_->not_between_and("age", "25", "35"); + auto filter = bind( + E::between("age", Literal::string("25"), Literal::string("35"), true)); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "20", "engineering", "active", "95"); @@ -229,15 +222,15 @@ TEST_F(TagFilterTest, TagNotBetweenFilter) { segments = createSegments("john", "30", "engineering", "active", "95"); EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; } // AND filter TEST_F(TagFilterTest, TagAndFilter) { - auto left_filter = builder_->gteq("age", "25"); - auto right_filter = builder_->eq("department", "engineering"); - auto and_filter = builder_->and_filter(left_filter, right_filter); + auto left_filter = E::compare("age", Op::GE, Literal::string("25")); + auto right_filter = + E::compare("department", Op::EQ, Literal::string("engineering")); + auto and_filter = + bind(E::and_filter(std::move(left_filter), std::move(right_filter))); ASSERT_NE(and_filter, nullptr); auto segments = createSegments("john", "30", "engineering", "active", "95"); @@ -251,15 +244,15 @@ TEST_F(TagFilterTest, TagAndFilter) { segments = createSegments("john", "30", "sales", "active", "95"); EXPECT_FALSE(and_filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete and_filter; } // OR filter TEST_F(TagFilterTest, TagOrFilter) { - auto left_filter = builder_->lt("age", "25"); - auto right_filter = builder_->eq("department", "engineering"); - auto or_filter = builder_->or_filter(left_filter, right_filter); + auto left_filter = E::compare("age", Op::LT, Literal::string("25")); + auto right_filter = + E::compare("department", Op::EQ, Literal::string("engineering")); + auto or_filter = + bind(E::or_filter(std::move(left_filter), std::move(right_filter))); ASSERT_NE(or_filter, nullptr); auto segments = createSegments("john", "20", "engineering", "active", "95"); @@ -277,14 +270,12 @@ TEST_F(TagFilterTest, TagOrFilter) { segments = createSegments("john", "30", "sales", "active", "95"); EXPECT_FALSE(or_filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete or_filter; } // NOT filter TEST_F(TagFilterTest, TagNotFilter) { - auto base_filter = builder_->eq("status", "active"); - auto not_filter = builder_->not_filter(base_filter); + auto base_filter = E::compare("status", Op::EQ, Literal::string("active")); + auto not_filter = bind(E::not_filter(std::move(base_filter))); ASSERT_NE(not_filter, nullptr); auto segments = @@ -295,18 +286,19 @@ TEST_F(TagFilterTest, TagNotFilter) { segments = createSegments("john", "30", "engineering", "active", "95"); EXPECT_FALSE(not_filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete not_filter; } // Complex nested filters TEST_F(TagFilterTest, ComplexNestedFilters) { - auto age_filter = builder_->gteq("age", "25"); - auto dept_filter = builder_->eq("department", "engineering"); - auto score_filter = builder_->gt("score", "90"); - - auto and_filter = builder_->and_filter(age_filter, dept_filter); - auto complex_filter = builder_->or_filter(and_filter, score_filter); + auto age_filter = E::compare("age", Op::GE, Literal::string("25")); + auto dept_filter = + E::compare("department", Op::EQ, Literal::string("engineering")); + auto score_filter = E::compare("score", Op::GT, Literal::string("90")); + + auto and_filter = + E::and_filter(std::move(age_filter), std::move(dept_filter)); + auto complex_filter = + bind(E::or_filter(std::move(and_filter), std::move(score_filter))); ASSERT_NE(complex_filter, nullptr); auto segments = createSegments("john", "30", "engineering", "active", "85"); @@ -320,19 +312,20 @@ TEST_F(TagFilterTest, ComplexNestedFilters) { segments = createSegments("bob", "20", "sales", "active", "85"); EXPECT_FALSE(complex_filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete complex_filter; } // Invalid column name TEST_F(TagFilterTest, InvalidColumnName) { - auto filter = builder_->eq("invalid_column", "value"); + auto expr = E::compare("invalid_column", Op::EQ, Literal::string("value")); + std::unique_ptr filter; + EXPECT_EQ(common::E_COLUMN_NOT_EXIST, + TagFilter::bind(*expr, *schema_, filter)); EXPECT_EQ(filter, nullptr); } // Boundary conditions TEST_F(TagFilterTest, BoundaryConditions) { - auto filter = builder_->eq("name", "test"); + auto filter = bind(E::compare("name", Op::EQ, Literal::string("test"))); ASSERT_NE(filter, nullptr); std::vector empty_segments; @@ -345,13 +338,11 @@ TEST_F(TagFilterTest, BoundaryConditions) { new std::string("test")}; EXPECT_TRUE(filter->satisfyRow(0, minimal_segments)); delete minimal_segments[1]; - - delete filter; } // Basic regex match and not match TEST_F(TagFilterTest, TagRegExpBasic) { - auto filter = builder_->reg_exp("name", "^j.*"); + auto filter = bind(E::regexp("name", "^j.*")); ASSERT_NE(filter, nullptr); auto segments = createSegments("john", "25", "engineering", "active", "95"); @@ -362,24 +353,23 @@ TEST_F(TagFilterTest, TagRegExpBasic) { EXPECT_FALSE(filter->satisfyRow(0, segments)); cleanupSegments(segments); - auto not_filter = builder_->not_reg_exp("name", "^j.*"); + auto not_filter = bind(E::regexp("name", "^j.*", true)); segments = createSegments("alice", "25", "engineering", "active", "95"); EXPECT_TRUE(not_filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete filter; - delete not_filter; } // Complex regex pattern with logical operations TEST_F(TagFilterTest, TagRegExpComplexLogic) { // Match names starting with j OR age in 20s AND department contains "eng" - auto name_filter = builder_->reg_exp("name", "^j.*"); - auto age_filter = builder_->reg_exp("age", "^2[0-9]$"); - auto dept_filter = builder_->reg_exp("department", ".*eng.*"); + auto name_filter = E::regexp("name", "^j.*"); + auto age_filter = E::regexp("age", "^2[0-9]$"); + auto dept_filter = E::regexp("department", ".*eng.*"); - auto age_dept_and = builder_->and_filter(age_filter, dept_filter); - auto complex_or = builder_->or_filter(name_filter, age_dept_and); + auto age_dept_and = + E::and_filter(std::move(age_filter), std::move(dept_filter)); + auto complex_or = + bind(E::or_filter(std::move(name_filter), std::move(age_dept_and))); auto segments = createSegments("john", "35", "sales", "active", "95"); EXPECT_TRUE(complex_or->satisfyRow(0, segments)); // name matches @@ -392,14 +382,12 @@ TEST_F(TagFilterTest, TagRegExpComplexLogic) { segments = createSegments("bob", "35", "sales", "active", "95"); EXPECT_FALSE(complex_or->satisfyRow(0, segments)); // no match cleanupSegments(segments); - - delete complex_or; } // Edge cases: invalid regex and boundary values TEST_F(TagFilterTest, TagRegExpEdgeCases) { // Invalid regex should not crash - auto invalid_filter = builder_->reg_exp("name", "[invalid[pattern"); + auto invalid_filter = bind(E::regexp("name", "[invalid[pattern")); ASSERT_NE(invalid_filter, nullptr); auto segments = createSegments("test", "25", "engineering", "active", "95"); @@ -408,13 +396,10 @@ TEST_F(TagFilterTest, TagRegExpEdgeCases) { cleanupSegments(segments); // Empty pattern matches everything - auto empty_filter = builder_->reg_exp("name", ""); + auto empty_filter = bind(E::regexp("name", "")); segments = createSegments("any", "25", "engineering", "active", "95"); EXPECT_TRUE(empty_filter->satisfyRow(0, segments)); cleanupSegments(segments); - - delete invalid_filter; - delete empty_filter; } // A null tag segment must not crash comparison filters; a null value never @@ -425,12 +410,13 @@ TEST_F(TagFilterTest, ComparisonFiltersTreatNullSegmentAsNoMatch) { new std::string("25"), new std::string("engineering")}; - auto eq = builder_->eq("name", "john"); - auto neq = builder_->neq("name", "john"); - auto lt = builder_->lt("name", "z"); - auto gt = builder_->gt("name", "a"); - auto between = builder_->between_and("name", "a", "z"); - auto reg = builder_->reg_exp("name", ".*"); + auto eq = bind(E::compare("name", Op::EQ, Literal::string("john"))); + auto neq = bind(E::compare("name", Op::NE, Literal::string("john"))); + auto lt = bind(E::compare("name", Op::LT, Literal::string("z"))); + auto gt = bind(E::compare("name", Op::GT, Literal::string("a"))); + auto between = + bind(E::between("name", Literal::string("a"), Literal::string("z"))); + auto reg = bind(E::regexp("name", ".*")); EXPECT_FALSE(eq->satisfyRow(0, segments)); EXPECT_FALSE(neq->satisfyRow(0, segments)); @@ -439,19 +425,13 @@ TEST_F(TagFilterTest, ComparisonFiltersTreatNullSegmentAsNoMatch) { EXPECT_FALSE(between->satisfyRow(0, segments)); EXPECT_FALSE(reg->satisfyRow(0, segments)); - delete eq; - delete neq; - delete lt; - delete gt; - delete between; - delete reg; delete segments[2]; delete segments[3]; } // IS NULL filter TEST_F(TagFilterTest, TagIsNullFilter) { - auto filter = builder_->is_null("name"); + auto filter = bind(E::is_null("name")); ASSERT_NE(filter, nullptr); // "name" is an explicit null pointer. @@ -469,18 +449,15 @@ TEST_F(TagFilterTest, TagIsNullFilter) { // A trailing tag column omitted from the device id (segment count too // small) is also treated as null. - auto trailing = builder_->is_null("score"); // col_idx 5 + auto trailing = bind(E::is_null("score")); // col_idx 5 std::vector short_seg = {nullptr, new std::string("john")}; EXPECT_TRUE(trailing->satisfyRow(0, short_seg)); delete short_seg[1]; - - delete filter; - delete trailing; } // IS NOT NULL filter TEST_F(TagFilterTest, TagIsNotNullFilter) { - auto filter = builder_->is_not_null("name"); + auto filter = bind(E::is_not_null("name")); ASSERT_NE(filter, nullptr); auto present = createSegments("john", "25", "engineering"); @@ -491,13 +468,10 @@ TEST_F(TagFilterTest, TagIsNotNullFilter) { EXPECT_FALSE(filter->satisfyRow(0, null_seg)); // An omitted trailing tag is null, so IS NOT NULL is false. - auto trailing = builder_->is_not_null("score"); + auto trailing = bind(E::is_not_null("score")); std::vector short_seg = {nullptr, new std::string("john")}; EXPECT_FALSE(trailing->satisfyRow(0, short_seg)); delete short_seg[1]; - - delete filter; - delete trailing; } TEST_F(TagFilterTest, LogicalOperatorsUseSegmentOverloadForChildren) { class SegmentEquals : public TagEq { @@ -521,15 +495,16 @@ TEST_F(TagFilterTest, LogicalOperatorsUseSegmentOverloadForChildren) { TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { using Field = AlignedFieldFilter; using Kind = BoundPredicate::Kind; - std::unique_ptr tag( - builder_->not_filter(builder_->eq("name", "x"))); - auto field = Field::not_filter(Field::compare("name", Field::CompareOp::EQ, - Field::Literal::string("x"))); + auto predicate = + E::not_filter(E::compare("name", Op::EQ, Literal::string("x"))); + auto tag = bind(predicate); + ASSERT_NE(nullptr, tag); + Field::Ptr field; + ASSERT_EQ(common::E_OK, Field::from_expression(*predicate, field, true)); - const auto* tag_expr = dynamic_cast(tag.get()); - ASSERT_NE(nullptr, tag_expr); for (const BoundPredicate* expr : - {tag_expr, static_cast(field.get())}) { + {static_cast(tag.get()), + static_cast(field.get())}) { EXPECT_EQ(Kind::NOT, expr->kind()); ASSERT_NE(nullptr, expr->left()); EXPECT_EQ(Kind::COMPARISON, expr->left()->kind()); @@ -546,11 +521,9 @@ TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { EXPECT_FALSE(mask.test(0)); } -TEST_F(TagFilterTest, TagCombinatorsRejectFieldOperandsWithoutTakingOwnership) { - std::unique_ptr tag(builder_->eq("name", "x")); - auto field = AlignedFieldFilter::is_null("name"); - EXPECT_EQ(nullptr, builder_->and_filter(tag.get(), field.get())); - EXPECT_EQ(nullptr, builder_->or_filter(field.get(), tag.get())); - EXPECT_EQ(nullptr, builder_->not_filter(field.get())); - EXPECT_EQ(nullptr, builder_->and_filter(tag.get(), tag.get())); +TEST_F(TagFilterTest, RejectsNumericTagOperandDuringBinding) { + auto expr = E::not_filter(E::compare("name", Op::EQ, Literal::int32(1))); + std::unique_ptr bound; + EXPECT_EQ(common::E_NOT_SUPPORT, TagFilter::bind(*expr, *schema_, bound)); + EXPECT_EQ(nullptr, bound); } diff --git a/cpp/test/reader/table_field_filter_test.cc b/cpp/test/reader/table_field_filter_test.cc index 529ded3b7..ffe4acdd9 100644 --- a/cpp/test/reader/table_field_filter_test.cc +++ b/cpp/test/reader/table_field_filter_test.cc @@ -386,14 +386,16 @@ TEST_P(TableFieldFilterTest, PageAfterTimeRangeAndOptionalFilters) { TEST_P(TableFieldFilterTest, BindTagAgainstQuerySchemaAndRejectWrongCategory) { TsFileReader reader; ASSERT_EQ(E_OK, reader.open(filename_)); - // The compatibility builder can validate against a different TAG order. + auto tag = Expression::compare("id", Expression::CompareOp::EQ, + Expression::Literal::string("d1")); TableSchema schema("other", {{"unused", STRING, ColumnCategory::TAG}, {"id", STRING, ColumnCategory::TAG}}); - TagFilterBuilder builder(&schema); - std::unique_ptr tag(builder.eq("id", "d1")); - ASSERT_TRUE(tag); + std::unique_ptr bound; + ASSERT_EQ(E_OK, TagFilter::bind(*tag, schema, bound)); + EXPECT_EQ(2, bound->col_idx_); ResultSet* rows = nullptr; - ASSERT_EQ(E_OK, reader.queryByRow("t", {"v"}, 0, 1, rows, tag.get())); + ASSERT_EQ(E_OK, + reader.queryByRow("t", {"v"}, 0, 1, rows, tag.get(), nullptr)); tag.reset(); bool next; ASSERT_EQ(E_OK, rows->next(next)); diff --git a/cpp/test/reader/table_read_failure_test.cc b/cpp/test/reader/table_read_failure_test.cc index 99d02669b..ed4335bf5 100644 --- a/cpp/test/reader/table_read_failure_test.cc +++ b/cpp/test/reader/table_read_failure_test.cc @@ -855,17 +855,17 @@ TEST_P(TableReadFailureTest, NullTagOperatorsAcceptNullValues) { } ASSERT_EQ(ret, common::E_OK); ASSERT_NE(filter, nullptr); - storage::ResultSet* result = nullptr; - ret = reader.query("test", {"value"}, 0, INT64_MAX, result, - static_cast(filter)); + char value_column[] = "value"; + char* columns[] = {value_column}; + auto result = tsfile_query_table_with_tag_filter( + &reader, "test", columns, 1, 0, INT64_MAX, filter, 0, &ret); EXPECT_EQ(ret, common::E_OK); int rows = 0; - bool next = false; if (result != nullptr) { - while ((ret = result->next(next)) == common::E_OK && next) { + while (tsfile_result_set_next(result, &ret)) { ++rows; } - reader.destroy_query_data_set(result); + free_tsfile_result_set(&result); } tsfile_tag_filter_free(filter); EXPECT_EQ(ret, common::E_OK); diff --git a/cpp/test/reader/table_view/tsfile_reader_table_test.cc b/cpp/test/reader/table_view/tsfile_reader_table_test.cc index 9cc236cba..d6c18e4f0 100644 --- a/cpp/test/reader/table_view/tsfile_reader_table_test.cc +++ b/cpp/test/reader/table_view/tsfile_reader_table_test.cc @@ -29,7 +29,7 @@ #include "file/local_random_access_read_file.h" #include "file/tsfile_io_writer.h" #include "file/write_file.h" -#include "reader/filter/tag_filter.h" +#include "reader/expression.h" #include "reader/filter/time_operator.h" #include "reader/table_query_executor.h" #include "reader/table_result_set.h" @@ -167,11 +167,12 @@ class TsFileTableReaderTest : public ::testing::Test { ASSERT_EQ(ret, common::E_OK); ResultSet* tmp_result_set = nullptr; - Filter* tag_filter = - TagFilterBuilder(table_schema).eq("id0", "device_id"); + auto tag_filter = + Expression::compare("id0", Expression::CompareOp::EQ, + Expression::Literal::string("device_id")); ret = reader.query(table_schema->get_table_name(), table_schema->get_measurement_names(), 0, end_time, - tmp_result_set, tag_filter); + tmp_result_set, tag_filter.get(), nullptr); auto* table_result_set = (TableResultSet*)tmp_result_set; char* literal = new char[std::strlen("device_id") + 1]; std::strcpy(literal, "device_id"); @@ -240,7 +241,6 @@ class TsFileTableReaderTest : public ::testing::Test { delete[] literal; ASSERT_EQ(reader.close(), common::E_OK); delete table_schema; - delete tag_filter; } }; @@ -1554,10 +1554,11 @@ TEST_F(TsFileTableReaderTest, DirectLookupSingleTagColumn) { ASSERT_EQ(reader.open(file_name_), common::E_OK); ResultSet* tmp_result_set = nullptr; - Filter* tag_filter = TagFilterBuilder(table_schema).eq("tag", "dev2"); + auto tag_filter = Expression::compare("tag", Expression::CompareOp::EQ, + Expression::Literal::string("dev2")); std::vector cols = {"tag", "val"}; int ret = reader.query("single_tag_table", cols, 0, 1000000, tmp_result_set, - tag_filter); + tag_filter.get(), nullptr); ASSERT_EQ(ret, common::E_OK); auto* table_result_set = (TableResultSet*)tmp_result_set; @@ -1577,7 +1578,6 @@ TEST_F(TsFileTableReaderTest, DirectLookupSingleTagColumn) { reader.destroy_query_data_set(table_result_set); ASSERT_EQ(reader.close(), common::E_OK); delete table_schema; - delete tag_filter; } TEST_F(TsFileTableReaderTest, DirectLookupNonExistDevice) { @@ -1613,10 +1613,12 @@ TEST_F(TsFileTableReaderTest, DirectLookupNonExistDevice) { ASSERT_EQ(reader.open(file_name_), common::E_OK); ResultSet* tmp_result_set = nullptr; - Filter* tag_filter = TagFilterBuilder(table_schema).eq("tag", "non_exist"); + auto tag_filter = + Expression::compare("tag", Expression::CompareOp::EQ, + Expression::Literal::string("non_exist")); std::vector cols = {"tag", "val"}; int ret = reader.query("single_tag_table", cols, 0, 1000000, tmp_result_set, - tag_filter); + tag_filter.get(), nullptr); ASSERT_EQ(ret, common::E_OK); auto* table_result_set = (TableResultSet*)tmp_result_set; @@ -1630,7 +1632,6 @@ TEST_F(TsFileTableReaderTest, DirectLookupNonExistDevice) { reader.destroy_query_data_set(table_result_set); ASSERT_EQ(reader.close(), common::E_OK); delete table_schema; - delete tag_filter; } TEST_F(TsFileTableReaderTest, MultiTagColumnFilterOnSecondTag) { @@ -1689,10 +1690,11 @@ TEST_F(TsFileTableReaderTest, MultiTagColumnFilterOnSecondTag) { ASSERT_EQ(reader.open(file_name_), common::E_OK); ResultSet* tmp_result_set = nullptr; - Filter* tag_filter = TagFilterBuilder(table_schema).eq("device", "dev_c"); + auto tag_filter = Expression::compare("device", Expression::CompareOp::EQ, + Expression::Literal::string("dev_c")); std::vector cols = {"region", "device", "val"}; int ret = reader.query("multi_tag_table", cols, 0, 1000000, tmp_result_set, - tag_filter); + tag_filter.get(), nullptr); ASSERT_EQ(ret, common::E_OK); auto* table_result_set = (TableResultSet*)tmp_result_set; @@ -1706,5 +1708,4 @@ TEST_F(TsFileTableReaderTest, MultiTagColumnFilterOnSecondTag) { reader.destroy_query_data_set(table_result_set); ASSERT_EQ(reader.close(), common::E_OK); delete table_schema; - delete tag_filter; } diff --git a/cpp/test/tools/model_format_e2e_test.cc b/cpp/test/tools/model_format_e2e_test.cc index bbd2ba7c9..d12f5499a 100644 --- a/cpp/test/tools/model_format_e2e_test.cc +++ b/cpp/test/tools/model_format_e2e_test.cc @@ -609,6 +609,8 @@ TEST(IndependentFixtures, NullableTagsHaveExactPredicateResults) { expect_cli_exact(cat({"id1", "neq", "dev_a"}), 0, "time,id1,s1\n1,\"\",20\n4,dev_b,50\n2,null,30\n", ""); expect_cli_exact(cat({"id1", "regexp", "dev"}), 0, "time,id1,s1\n", ""); + expect_cli_exact(cat({"id1", "regexp", "dev|dev_b"}), 0, + "time,id1,s1\n4,dev_b,50\n", ""); expect_cli_exact(cat({"id1", "regexp", "dev_.*"}), 0, "time,id1,s1\n3,dev_a,40\n4,dev_b,50\n", ""); diff --git a/cpp/tools/commands/commands.h b/cpp/tools/commands/commands.h index d7cd018c0..fe44571d0 100644 --- a/cpp/tools/commands/commands.h +++ b/cpp/tools/commands/commands.h @@ -29,7 +29,6 @@ #include "format/output_format.h" namespace storage { -class Filter; class TableSchema; class TsFileReader; } // namespace storage @@ -50,10 +49,6 @@ std::vector> sorted_table_schemas( std::vector collect_tree_query_paths( const ParsedArgs& args, storage::TsFileReader& reader); -int build_table_tag_filter(const ParsedArgs& args, - storage::TsFileReader& reader, - const std::string& table_name, std::ostream& err, - std::unique_ptr& ret_filter); // Resolve the projected schema and reject name collisions without scanning // rows or preparing output files. Export calls this for every object first. diff --git a/cpp/tools/commands/row_query.cc b/cpp/tools/commands/row_query.cc index 04908a8df..f212468d8 100644 --- a/cpp/tools/commands/row_query.cc +++ b/cpp/tools/commands/row_query.cc @@ -33,27 +33,12 @@ #include "common/schema.h" #include "format/result_set_format.h" #include "format/staged_output.h" -#include "reader/filter/tag_filter.h" +#include "reader/expression.h" #include "reader/tsfile_reader.h" namespace tsfile_cli { namespace { -class CliFullMatchTagRegExp : public storage::TagFilter { - public: - CliFullMatchTagRegExp(int col_idx, const std::string& pattern) - : storage::TagFilter(col_idx, pattern), pattern_(pattern) {} - - bool satisfyRow(std::vector segments) const override { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) { - return false; - } - return std::regex_match(*segments[col_idx_], pattern_); - } - - private: - std::regex pattern_; -}; bool can_push_down_row_window(const ParsedArgs& args, long long offset, long long limit) { return !args.has_start && !args.has_end && offset == 0 && @@ -241,12 +226,10 @@ int resolve_row_query_selection(const ParsedArgs& args, return kExitOk; } -} // namespace - int build_table_tag_filter(const ParsedArgs& args, storage::TsFileReader& reader, const std::string& table_name, std::ostream& err, - std::unique_ptr& ret_filter) { + storage::Expression::Ptr& ret_filter) { if (!args.has_tag_filter) { return kExitOk; } @@ -262,16 +245,17 @@ int build_table_tag_filter(const ParsedArgs& args, return kExitFile; } - storage::TagFilterBuilder builder(schema.get()); - std::unique_ptr combined; - for (const ParsedArgs::TagFilterSpec& spec : args.tag_filters) { - storage::Filter* filter = nullptr; + using E = storage::Expression; + E::Ptr combined; + for (const auto& spec : args.tag_filters) { + E::Ptr filter; switch (spec.op) { case ParsedArgs::TagFilterOp::kEq: - filter = builder.eq(spec.column, spec.value); - break; case ParsedArgs::TagFilterOp::kNeq: - filter = builder.neq(spec.column, spec.value); + filter = E::compare(spec.column, + spec.op == ParsedArgs::TagFilterOp::kEq + ? E::CompareOp::EQ : E::CompareOp::NE, + E::Literal::string(spec.value)); break; case ParsedArgs::TagFilterOp::kRegexp: try { @@ -282,42 +266,37 @@ int build_table_tag_filter(const ParsedArgs& args, << spec.column << "'\n"; return kExitUsage; } - { - int tag_order = schema->find_id_column_order(spec.column); - if (tag_order >= 0) { - filter = new CliFullMatchTagRegExp(tag_order + 1, - spec.value); - } - } + // CLI patterns match the entire TAG value, including alternatives. + filter = E::regexp(spec.column, "^(?:" + spec.value + ")$"); break; case ParsedArgs::TagFilterOp::kIsNull: - filter = builder.is_null(spec.column); + filter = E::is_null(spec.column); break; case ParsedArgs::TagFilterOp::kNotNull: - filter = builder.is_not_null(spec.column); + filter = E::is_not_null(spec.column); break; case ParsedArgs::TagFilterOp::kNone: break; } - if (filter == nullptr) { + if (!filter || schema->find_id_column_order(spec.column) < 0) { err << "Error: invalid tag filter column '" << spec.column << "' for table " << table_name << "\n"; return kExitUsage; } if (!combined) { - combined.reset(filter); + combined = std::move(filter); } else if (args.tag_match == "any") { - combined.reset(storage::TagFilterBuilder::or_filter( - combined.release(), filter)); + combined = E::or_filter(std::move(combined), std::move(filter)); } else { - combined.reset(storage::TagFilterBuilder::and_filter( - combined.release(), filter)); + combined = E::and_filter(std::move(combined), std::move(filter)); } } ret_filter = std::move(combined); return kExitOk; } +} // namespace + std::vector collect_tree_query_paths( const ParsedArgs& args, storage::TsFileReader& reader) { std::vector paths; @@ -392,7 +371,7 @@ int run_row_query(const ParsedArgs& args, storage::TsFileReader& reader, const bool push_down = can_push_down_row_window(args, offset, limit); const std::string tree_device_prefix = selection.table_model ? "" : selection.object; - std::unique_ptr tag_filter; + storage::Expression::Ptr tag_filter; if (selection.table_model) { const int filter_ret = build_table_tag_filter( args, reader, selection.object, err, tag_filter); @@ -401,10 +380,10 @@ int run_row_query(const ParsedArgs& args, storage::TsFileReader& reader, qret = reader.queryByRow(selection.object, selection.columns, to_reader_row_bound(offset), to_reader_row_bound(limit), rs, - tag_filter.get()); + tag_filter.get(), nullptr); } else { qret = reader.query(selection.object, selection.columns, start, end, - rs, tag_filter.get()); + rs, tag_filter.get(), nullptr); } } else if (push_down) { qret = reader.queryByRow(selection.columns, to_reader_row_bound(offset), diff --git a/skills/tsfile/references/docs-map.yaml b/skills/tsfile/references/docs-map.yaml index 8b0ab4470..e2a3ecbe5 100644 --- a/skills/tsfile/references/docs-map.yaml +++ b/skills/tsfile/references/docs-map.yaml @@ -134,6 +134,7 @@ current_capabilities: - java/tsfile/src/main/java/org/apache/tsfile/read/filter/factory/TagFilterBuilder.java - java/tsfile/src/main/java/org/apache/tsfile/read/v4/ITsFileReader.java - java/tsfile/src/main/java/org/apache/tsfile/write/v4/ITsFileWriter.java + - cpp/src/reader/expression.h - cpp/src/reader/filter/tag_filter.h - cpp/src/reader/tsfile_reader.h - cpp/src/writer/tsfile_writer.h diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index e8c64d285..0893efcb2 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -46,9 +46,8 @@ the property manually does not enable it. ## Table TAG Filters -Build TAG predicates against a `TableSchema`, apply them only to Table-model -queries, and pass field/time restrictions through their separate query -arguments. TAG values are strings; do not apply a TAG builder to FIELD columns. +TAG filters apply to table-model device-ID columns and use string values. +Pass them to the table query alongside the time range or row window. - Java `TagFilterBuilder`: `eq`, `neq`, `lt`, `lteq`, `gt`, `gteq`, `betweenAnd`, `notBetweenAnd`, `regExp`, `notRegExp`, `like`, `notLike`, plus @@ -59,10 +58,10 @@ arguments. TAG values are strings; do not apply a TAG builder to FIELD columns. `tag_is_not_null`, `tag_between`, and `tag_not_between`. Compose with `&`, `|`, and `~`, then pass `tag_filter=` to `query_table` or `query_table_by_row`. -- C++ `TagFilterBuilder`: use `eq`/`neq`/comparison, regex, null, range, and - static logical builders from `cpp/src/reader/filter/tag_filter.h`; pass the - resulting `Filter*` to the matching `TsFileReader::query` or `queryByRow` - overload and follow the current ownership implementation. +- C++: construct a named `storage::Expression` and pass it to the TAG argument + of `TsFileReader::query` or `queryByRow`. The reader binds names to the + queried table. For standalone segment evaluation, use `TagFilter::bind` + with a schema to obtain an executable filter. - C wrapper: construct `TagFilterHandle` values with the declared factory and composition functions, pass them to the tag-filter query entry point, and release them with `tsfile_tag_filter_free`. From 38e70c0184426ebe613b553cb1d08f49a1ef6e2c Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 00:08:46 +0800 Subject: [PATCH 07/10] Bind TAG and FIELD operands on the shared query expression --- cpp/src/reader/aligned_chunk_reader.cc | 10 +- cpp/src/reader/column_mapping.h | 15 +- cpp/src/reader/device_meta_iterator.cc | 9 +- cpp/src/reader/expression.cc | 21 +- cpp/src/reader/expression.h | 36 +- cpp/src/reader/filter/aligned_field_filter.cc | 577 +++++++----------- cpp/src/reader/filter/aligned_field_filter.h | 77 +-- cpp/src/reader/filter/bind_expression.cc | 230 +++---- cpp/src/reader/filter/bind_expression.h | 32 +- cpp/src/reader/filter/bound_predicate.h | 77 --- cpp/src/reader/filter/tag_filter.cc | 221 ++++--- cpp/src/reader/filter/tag_filter.h | 37 +- cpp/src/reader/qds_without_timegenerator.cc | 23 +- cpp/src/reader/qds_without_timegenerator.h | 3 +- cpp/src/reader/table_query_executor.cc | 19 +- .../reader/aligned_chunk_reader_bulk_test.cc | 9 +- .../aligned_field_filter_regression_test.cc | 53 +- .../reader/block/masked_bulk_copy_test.cc | 5 +- cpp/test/reader/chunk_reader_resource_test.cc | 9 +- .../filter/aligned_field_filter_test.cc | 184 +++--- cpp/test/reader/filter/tag_filter_test.cc | 14 +- cpp/test/reader/table_field_filter_test.cc | 102 ++-- .../tsfile/references/properties-filters.md | 4 +- 23 files changed, 746 insertions(+), 1021 deletions(-) delete mode 100644 cpp/src/reader/filter/bound_predicate.h diff --git a/cpp/src/reader/aligned_chunk_reader.cc b/cpp/src/reader/aligned_chunk_reader.cc index c67c27ff1..a64847a6e 100644 --- a/cpp/src/reader/aligned_chunk_reader.cc +++ b/cpp/src/reader/aligned_chunk_reader.cc @@ -21,6 +21,7 @@ #include #include +#include #include #include "common/global.h" @@ -1525,7 +1526,7 @@ void AlignedChunkReader::build_filter_column_mask() { filter_column_mask_.assign(value_columns_.size(), false); if (field_filter_ == nullptr) return; std::set filter_columns; - for (const auto& name : field_filter_->referenced_columns()) { + for (const auto& name : field_filter_->expression().referenced_columns()) { filter_columns.insert(name); } for (uint32_t c = 0; c < value_columns_.size(); ++c) { @@ -1592,13 +1593,6 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { current_page_plan_index_ = 0; current_page_loaded_ = false; page_plan_built_ = false; - // A structurally broken predicate (e.g. an OR missing one operand) must - // fail here rather than be classified by page statistics: statistics-based - // FULL_PASS would otherwise return rows without ever running evaluation. - if (field_filter_ != nullptr && !field_filter_->is_valid()) { - return E_INVALID_ARG; - } - const uint32_t num_cols = value_columns_.size(); // For single-page chunks the times decoded while classifying the page are // exactly the ones the lazy decode path would decode again; keep them so diff --git a/cpp/src/reader/column_mapping.h b/cpp/src/reader/column_mapping.h index 621f8756c..a340a154b 100644 --- a/cpp/src/reader/column_mapping.h +++ b/cpp/src/reader/column_mapping.h @@ -46,18 +46,9 @@ class ColumnMapping { return common::E_OK; } - int add(const Expression& measurementFilter) { - // TODO: get measurements in the filter and add them to - // field_columns_ - return common::E_OK; - } - - int add_filter_columns(AlignedFieldFilter& filter, TableSchema& schema) { - const int ret = filter.bind(schema); - if (ret != common::E_OK) return ret; - for (const auto& column_name : filter.referenced_columns()) { - field_columns_.insert(column_name); - } + int add(const Expression& expr) { + for (const auto& name : expr.referenced_columns()) + field_columns_.insert(name); return common::E_OK; } diff --git a/cpp/src/reader/device_meta_iterator.cc b/cpp/src/reader/device_meta_iterator.cc index 32d6484b4..c6da20918 100644 --- a/cpp/src/reader/device_meta_iterator.cc +++ b/cpp/src/reader/device_meta_iterator.cc @@ -171,10 +171,9 @@ int DeviceMetaIterator::load_internal_node(MetaIndexNode* meta_index_node) { void DeviceMetaIterator::try_setup_direct_lookup(MetaIndexNode* root_node) { if (id_filter_ == nullptr || root_node == nullptr) return; - const auto* eq = dynamic_cast(id_filter_); - if (eq == nullptr || eq->kind() != BoundPredicate::Kind::COMPARISON || - eq->compare_op() != BoundPredicate::CompareOp::EQ || eq->col_idx_ != 1) - return; + const auto* tag = dynamic_cast(id_filter_); + const auto* segment = tag ? tag->exact_device_id_segment() : nullptr; + if (!segment) return; if (root_node->children_.empty()) return; @@ -192,7 +191,7 @@ void DeviceMetaIterator::try_setup_direct_lookup(MetaIndexNode* root_node) { for (int i = 1; i < actual_segment_count; i++) { segs[i] = ""; } - segs[eq->col_idx_] = eq->value_; + segs[1] = *segment; direct_device_id_ = std::make_shared(segs); direct_root_node_ = root_node; } diff --git a/cpp/src/reader/expression.cc b/cpp/src/reader/expression.cc index 2cb1ecbec..1efe781ed 100644 --- a/cpp/src/reader/expression.cc +++ b/cpp/src/reader/expression.cc @@ -19,6 +19,8 @@ #include "expression.h" +#include + #include "reader/filter/and_filter.h" #include "reader/filter/or_filter.h" @@ -72,8 +74,8 @@ Expression::Ptr named(ExpressionType type, std::string reference, Expression::Literal value = {}, Expression::Literal upper = {}) { Expression::Ptr node(new Expression(type)); - node->filter_ = new Expression::Operand(std::move(reference), op, - std::move(value), std::move(upper)); + node->operand_.reset(new Expression::Operand( + std::move(reference), op, std::move(value), std::move(upper))); return node; } Expression::Ptr logical(ExpressionType type, Expression::Ptr left, @@ -119,6 +121,21 @@ Expression::Ptr Expression::regexp(std::string reference, std::string pattern, Literal::string(std::move(pattern))); } +std::vector Expression::referenced_columns() const { + std::vector columns; + std::set seen; + std::vector pending{this}; + while (!pending.empty()) { + const auto* node = pending.back(); + pending.pop_back(); + if (node->operand_ && seen.insert(node->operand_->reference).second) + columns.push_back(node->operand_->reference); + if (node->right_) pending.push_back(node->right_); + if (node->left_) pending.push_back(node->left_); + } + return columns; +} + void QueryExpression::add_time_filter_to_series_filter( Filter* time_filter, Expression* single_series_expr) { Filter* filter = new AndFilter(single_series_expr->filter_, time_filter); diff --git a/cpp/src/reader/expression.h b/cpp/src/reader/expression.h index e78558cff..1d726fe7f 100644 --- a/cpp/src/reader/expression.h +++ b/cpp/src/reader/expression.h @@ -44,15 +44,31 @@ enum ExpressionType { BETWEEN, NOT_BETWEEN, REGEXP, - NOT_REGEXP, - CUSTOM, - AND = AND_EXPR, - OR = OR_EXPR + NOT_REGEXP }; struct Expression { using Ptr = std::unique_ptr; enum class CompareOp { EQ, NE, LT, LE, GT, GE }; + template + static bool compare_values(const T& value, const T& literal, CompareOp op) { + switch (op) { + case CompareOp::EQ: + return value == literal; + case CompareOp::NE: + return value != literal; + case CompareOp::LT: + return value < literal; + case CompareOp::LE: + return value <= literal; + case CompareOp::GT: + return value > literal; + case CompareOp::GE: + return value >= literal; + } + return false; + } + struct Literal { common::TSDataType type = common::INVALID_DATATYPE; bool bool_value = false; @@ -83,13 +99,13 @@ struct Expression { static Ptr regexp(std::string reference, std::string pattern, bool negated = false); - // A named leaf uses the existing owned leaf slot. It carries data only; - // readers replace it with a query-local executable filter when binding. - struct Operand final : Filter { + struct Operand { std::string reference; CompareOp comparison; Literal literal; Literal upper; + size_t index = + 0; // Device segment or series position resolved during binding. Operand(std::string name, CompareOp op, Literal value, Literal upper_bound) : reference(std::move(name)), @@ -97,9 +113,8 @@ struct Expression { literal(std::move(value)), upper(std::move(upper_bound)) {} }; - const Operand* operand() const { - return dynamic_cast(filter_); - } + std::unique_ptr operand_; + std::vector referenced_columns() const; ExpressionType type_; Expression* left_; @@ -128,6 +143,7 @@ struct Expression { filter_(f), series_path_(path) {} void destroy() { + operand_.reset(); if (filter_ != nullptr) { delete filter_; filter_ = nullptr; diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index 7ff0583ce..1c05be18e 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -29,9 +29,11 @@ namespace storage { namespace { -AlignedFieldFilter::CompareOp negate_comparison( - AlignedFieldFilter::CompareOp op) { - using Op = AlignedFieldFilter::CompareOp; +using Op = Expression::CompareOp; +using Literal = Expression::Literal; +using ColumnView = AlignedFieldFilter::ColumnView; + +Op negate_comparison(Op op) { switch (op) { case Op::EQ: return Op::NE; @@ -59,303 +61,113 @@ bool has_nan_statistics(const S& statistic) { std::isnan(statistic.min_value_) || std::isnan(statistic.max_value_); } -} // namespace - -bool AlignedFieldFilter::may_match( - const std::map& statistics, - int64_t row_count) const { - return page_matches(statistics, row_count, false, false); -} - -bool AlignedFieldFilter::all_match( - const std::map& statistics, - int64_t row_count) const { - if (row_count <= 0) return false; - return page_matches(statistics, row_count, true, false); +// NOT is applied only to non-null comparisons. A range uses both bounds +// directly, including for NaN values and reversed endpoints. +template +bool matches_comparison(const Expression& leaf, bool negated, Compare compare) { + const auto& operand = *leaf.operand_; + if (leaf.type_ == COMPARISON) + return compare(operand.comparison, operand.literal, negated); + const bool outside = (leaf.type_ == NOT_BETWEEN) != negated; + if (outside) + return compare(Op::GE, operand.literal, true) || + compare(Op::LE, operand.upper, true); + return compare(Op::GE, operand.literal, false) && + compare(Op::LE, operand.upper, false); } -bool AlignedFieldFilter::page_matches( - const std::map& statistics, int64_t row_count, - bool require_all, bool negated) const { - if (kind_ == Kind::NOT) { - return left_ ? left_field()->page_matches(statistics, row_count, - require_all, !negated) - : !require_all; - } - if (kind_ == Kind::AND || kind_ == Kind::OR) { - if (!left_ || !right_) return !require_all; - const bool lhs = left_field()->page_matches(statistics, row_count, - require_all, negated); - if ((kind_ == Kind::AND) != negated) { - return lhs && right_field()->page_matches(statistics, row_count, - require_all, negated); - } - return lhs || right_field()->page_matches(statistics, row_count, - require_all, negated); +template +bool range_matches(T min, T max, T literal, Op op, bool all, bool no_nulls) { + switch (op) { + case Op::EQ: + return all ? min == literal && max == literal + : min <= literal && literal <= max; + case Op::NE: + return all ? literal < min || literal > max + : !(min == literal && max == literal && no_nulls); + case Op::LT: + return (all ? max : min) < literal; + case Op::LE: + return (all ? max : min) <= literal; + case Op::GT: + return (all ? min : max) > literal; + case Op::GE: + return (all ? min : max) >= literal; } - return require_all ? leaf_all_match(statistics, row_count, negated) - : leaf_may_match(statistics, row_count, negated); + return !all; } -bool AlignedFieldFilter::leaf_may_match( - const std::map& statistics, int64_t row_count, - bool negated) const { - const auto found = statistics.find(column_); - if (found == statistics.end() || found->second == nullptr) return true; - Statistic* statistic = found->second; - if (kind_ == Kind::IS_NULL || kind_ == Kind::IS_NOT_NULL) { - const bool selects_null = (kind_ == Kind::IS_NULL) != negated; - return selects_null ? (row_count <= 0 || statistic->count_ < row_count) - : statistic->count_ > 0; - } - if (statistic->count_ <= 0) return false; - - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::INT32) return true; - switch (negated ? negate_comparison(compare_op_) : compare_op_) { - case CompareOp::EQ: - return typed->min_value_ <= literal_.int32_value && - literal_.int32_value <= typed->max_value_; - case CompareOp::NE: - return !(typed->min_value_ == typed->max_value_ && - typed->min_value_ == literal_.int32_value && - typed->count_ == row_count); - case CompareOp::LT: - return typed->min_value_ < literal_.int32_value; - case CompareOp::LE: - return typed->min_value_ <= literal_.int32_value; - case CompareOp::GT: - return typed->max_value_ > literal_.int32_value; - case CompareOp::GE: - return typed->max_value_ >= literal_.int32_value; - } - } - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::INT64) return true; - switch (negated ? negate_comparison(compare_op_) : compare_op_) { - case CompareOp::EQ: - return typed->min_value_ <= literal_.int64_value && - literal_.int64_value <= typed->max_value_; - case CompareOp::NE: - return !(typed->min_value_ == typed->max_value_ && - typed->min_value_ == literal_.int64_value && - typed->count_ == row_count); - case CompareOp::LT: - return typed->min_value_ < literal_.int64_value; - case CompareOp::LE: - return typed->min_value_ <= literal_.int64_value; - case CompareOp::GT: - return typed->max_value_ > literal_.int64_value; - case CompareOp::GE: - return typed->max_value_ >= literal_.int64_value; - } - } - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::FLOAT || has_nan_statistics(*typed) || - (negated && compare_op_ != CompareOp::EQ && - compare_op_ != CompareOp::NE && std::isnan(literal_.float_value))) - return true; - // Complementing an ordered operator is safe only when neither the - // page nor the literal can contain NaN. - const CompareOp op = - negated ? negate_comparison(compare_op_) : compare_op_; - switch (op) { - case CompareOp::EQ: - return typed->min_value_ <= literal_.float_value && - literal_.float_value <= typed->max_value_; - case CompareOp::NE: - return !(typed->min_value_ == typed->max_value_ && - typed->min_value_ == literal_.float_value && - typed->count_ == row_count); - case CompareOp::LT: - return typed->min_value_ < literal_.float_value; - case CompareOp::LE: - return typed->min_value_ <= literal_.float_value; - case CompareOp::GT: - return typed->max_value_ > literal_.float_value; - case CompareOp::GE: - return typed->max_value_ >= literal_.float_value; - } - } - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::DOUBLE || has_nan_statistics(*typed) || - (negated && compare_op_ != CompareOp::EQ && - compare_op_ != CompareOp::NE && std::isnan(literal_.double_value))) - return true; - const CompareOp op = - negated ? negate_comparison(compare_op_) : compare_op_; - switch (op) { - case CompareOp::EQ: - return typed->min_value_ <= literal_.double_value && - literal_.double_value <= typed->max_value_; - case CompareOp::NE: - return !(typed->min_value_ == typed->max_value_ && - typed->min_value_ == literal_.double_value && - typed->count_ == row_count); - case CompareOp::LT: - return typed->min_value_ < literal_.double_value; - case CompareOp::LE: - return typed->min_value_ <= literal_.double_value; - case CompareOp::GT: - return typed->max_value_ > literal_.double_value; - case CompareOp::GE: - return typed->max_value_ >= literal_.double_value; - } - } - return true; +template +bool page_comparison(const S& stat, const Expression& leaf, bool negated, + bool all, bool no_nulls, common::TSDataType type, + T Literal::*member) { + return matches_comparison( + leaf, negated, [&](Op op, const Literal& literal, bool invert) { + if (literal.type != type) return !all; + const T value = literal.*member; + if (invert && op != Op::EQ && op != Op::NE && std::isnan(value)) + return !all; + return range_matches(stat.min_value_, stat.max_value_, value, + invert ? negate_comparison(op) : op, all, + no_nulls); + }); } -bool AlignedFieldFilter::leaf_all_match( - const std::map& statistics, int64_t row_count, - bool negated) const { - const auto found = statistics.find(column_); - if (found == statistics.end() || found->second == nullptr) return false; - Statistic* statistic = found->second; - if (kind_ == Kind::IS_NULL || kind_ == Kind::IS_NOT_NULL) { - const bool selects_null = (kind_ == Kind::IS_NULL) != negated; - return selects_null ? statistic->count_ == 0 - : statistic->count_ == row_count; +bool page_matches(const Expression& expr, + const std::map& statistics, + int64_t rows, bool all, bool negated) { + if (expr.type_ == NOT) + return page_matches(*expr.left_, statistics, rows, all, !negated); + if (expr.type_ == AND_EXPR || expr.type_ == OR_EXPR) { + const bool lhs = + page_matches(*expr.left_, statistics, rows, all, negated); + if ((expr.type_ == AND_EXPR) != negated) + return lhs && + page_matches(*expr.right_, statistics, rows, all, negated); + return lhs || + page_matches(*expr.right_, statistics, rows, all, negated); } - // Ordinary comparisons do not match NULL. A page-wide match requires that - // every row has a non-NULL value and that the whole min/max range passes. - if (statistic->count_ != row_count) return false; - - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::INT32) return false; - switch (negated ? negate_comparison(compare_op_) : compare_op_) { - case CompareOp::EQ: - return typed->min_value_ == literal_.int32_value && - typed->max_value_ == literal_.int32_value; - case CompareOp::NE: - return literal_.int32_value < typed->min_value_ || - literal_.int32_value > typed->max_value_; - case CompareOp::LT: - return typed->max_value_ < literal_.int32_value; - case CompareOp::LE: - return typed->max_value_ <= literal_.int32_value; - case CompareOp::GT: - return typed->min_value_ > literal_.int32_value; - case CompareOp::GE: - return typed->min_value_ >= literal_.int32_value; - } + const auto it = statistics.find(expr.operand_->reference); + if (it == statistics.end() || !it->second) return !all; + const auto* stat = it->second; + const bool no_nulls = stat->count_ == rows; + if (expr.type_ == IS_NULL || expr.type_ == IS_NOT_NULL) { + const bool selects_null = (expr.type_ == IS_NULL) != negated; + if (all) return selects_null ? stat->count_ == 0 : no_nulls; + return selects_null ? rows <= 0 || stat->count_ < rows + : stat->count_ > 0; } - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::INT64) return false; - switch (negated ? negate_comparison(compare_op_) : compare_op_) { - case CompareOp::EQ: - return typed->min_value_ == literal_.int64_value && - typed->max_value_ == literal_.int64_value; - case CompareOp::NE: - return literal_.int64_value < typed->min_value_ || - literal_.int64_value > typed->max_value_; - case CompareOp::LT: - return typed->max_value_ < literal_.int64_value; - case CompareOp::LE: - return typed->max_value_ <= literal_.int64_value; - case CompareOp::GT: - return typed->min_value_ > literal_.int64_value; - case CompareOp::GE: - return typed->min_value_ >= literal_.int64_value; - } + if (stat->count_ == 0 || (all && !no_nulls)) return false; + if (auto* typed = dynamic_cast(stat)) + return page_comparison(*typed, expr, negated, all, no_nulls, + common::INT32, &Literal::int32_value); + if (auto* typed = dynamic_cast(stat)) + return page_comparison(*typed, expr, negated, all, no_nulls, + common::INT64, &Literal::int64_value); + if (auto* typed = dynamic_cast(stat)) { + if (has_nan_statistics(*typed)) return !all; + return page_comparison(*typed, expr, negated, all, no_nulls, + common::FLOAT, &Literal::float_value); } - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::FLOAT || has_nan_statistics(*typed) || - (negated && compare_op_ != CompareOp::EQ && - compare_op_ != CompareOp::NE && std::isnan(literal_.float_value))) - return false; - const CompareOp op = - negated ? negate_comparison(compare_op_) : compare_op_; - switch (op) { - case CompareOp::EQ: - return typed->min_value_ == literal_.float_value && - typed->max_value_ == literal_.float_value; - case CompareOp::NE: - return literal_.float_value < typed->min_value_ || - literal_.float_value > typed->max_value_; - case CompareOp::LT: - return typed->max_value_ < literal_.float_value; - case CompareOp::LE: - return typed->max_value_ <= literal_.float_value; - case CompareOp::GT: - return typed->min_value_ > literal_.float_value; - case CompareOp::GE: - return typed->min_value_ >= literal_.float_value; - } - } - if (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::DOUBLE || has_nan_statistics(*typed) || - (negated && compare_op_ != CompareOp::EQ && - compare_op_ != CompareOp::NE && std::isnan(literal_.double_value))) - return false; - const CompareOp op = - negated ? negate_comparison(compare_op_) : compare_op_; - switch (op) { - case CompareOp::EQ: - return typed->min_value_ == literal_.double_value && - typed->max_value_ == literal_.double_value; - case CompareOp::NE: - return literal_.double_value < typed->min_value_ || - literal_.double_value > typed->max_value_; - case CompareOp::LT: - return typed->max_value_ < literal_.double_value; - case CompareOp::LE: - return typed->max_value_ <= literal_.double_value; - case CompareOp::GT: - return typed->min_value_ > literal_.double_value; - case CompareOp::GE: - return typed->min_value_ >= literal_.double_value; - } + if (auto* typed = dynamic_cast(stat)) { + if (has_nan_statistics(*typed)) return !all; + return page_comparison(*typed, expr, negated, all, no_nulls, + common::DOUBLE, &Literal::double_value); } - return false; -} - -int AlignedFieldFilter::evaluate(common::TsBlock& block, - const std::vector& column_names, - SelectionMask& mask) const { - std::map column_index; - for (uint32_t i = 0; i < column_names.size(); ++i) { - column_index[column_names[i]] = i + 1; - } - - return evaluate_tree(block.get_row_count(), mask, - [&](const AlignedFieldFilter& leaf, bool negated, - SelectionMask& result) { - return leaf.evaluate_leaf(block, column_index, - negated, result); - }); -} - -int AlignedFieldFilter::evaluate_columns(const std::vector& columns, - uint32_t row_count, - SelectionMask& mask) const { - std::map column_index; - for (uint32_t i = 0; i < columns.size(); ++i) { - column_index[columns[i].name] = i; - } - - return evaluate_tree(row_count, mask, - [&](const AlignedFieldFilter& leaf, bool negated, - SelectionMask& result) -> int { - const auto found = column_index.find(leaf.column_); - if (found == column_index.end()) - return common::E_COLUMN_NOT_EXIST; - return leaf.evaluate_leaf(columns[found->second], - row_count, negated, - result); - }); + return !all; } // Carry NOT down to the comparison. Complementing a completed one-bit mask // would also select NULL rows; only non-null comparisons may be inverted. template -int AlignedFieldFilter::evaluate_tree(uint32_t row_count, SelectionMask& mask, - EvaluateLeaf evaluate_leaf) const { +int evaluate_tree(const Expression& expr, uint32_t row_count, + SelectionMask& mask, EvaluateLeaf evaluate_leaf) { struct Frame { - const AlignedFieldFilter* node; + const Expression* node; bool negated; bool combine; }; - std::vector pending{{this, false, false}}; + std::vector pending{{&expr, false, false}}; std::vector results; while (!pending.empty()) { const Frame frame = pending.back(); @@ -365,18 +177,18 @@ int AlignedFieldFilter::evaluate_tree(uint32_t row_count, SelectionMask& mask, if (frame.combine) { SelectionMask rhs = std::move(results.back()); results.pop_back(); - if ((node->kind_ == Kind::AND) != frame.negated) { + if ((node->type_ == AND_EXPR) != frame.negated) { results.back().and_with(rhs); } else { results.back().or_with(rhs); } - } else if (node->kind_ == Kind::NOT) { - pending.push_back({node->left_field(), !frame.negated, false}); - } else if (node->kind_ == Kind::AND || node->kind_ == Kind::OR) { + } else if (node->type_ == NOT) { + pending.push_back({node->left_, !frame.negated, false}); + } else if (node->type_ == AND_EXPR || node->type_ == OR_EXPR) { if (!node->left_ || !node->right_) return common::E_INVALID_ARG; pending.push_back({node, frame.negated, true}); - pending.push_back({node->right_field(), frame.negated, false}); - pending.push_back({node->left_field(), frame.negated, false}); + pending.push_back({node->right_, frame.negated, false}); + pending.push_back({node->left_, frame.negated, false}); } else { results.emplace_back(row_count); const int ret = evaluate_leaf(*node, frame.negated, results.back()); @@ -387,84 +199,84 @@ int AlignedFieldFilter::evaluate_tree(uint32_t row_count, SelectionMask& mask, return common::E_OK; } -int AlignedFieldFilter::evaluate_value(common::TSDataType column_type, - const char* data, uint32_t len, - bool is_null, bool negated, - bool& satisfied) const { - satisfied = false; - if (kind_ == Kind::IS_NULL) { - satisfied = is_null != negated; - } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = is_null == negated; - } else if (!is_null) { - if (column_type == common::BOOLEAN && - literal_.type == common::BOOLEAN) { - bool value; - std::memcpy(&value, data, sizeof(value)); - satisfied = compare_values(value, literal_.bool_value, compare_op_); - } else if ((column_type == common::INT32 || - column_type == common::DATE) && - literal_.type == common::INT32) { - int32_t value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.int32_value, compare_op_); - } else if ((column_type == common::INT64 || - column_type == common::TIMESTAMP) && - literal_.type == common::INT64) { - int64_t value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.int64_value, compare_op_); - } else if (column_type == common::FLOAT && - literal_.type == common::FLOAT) { - float value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.float_value, compare_op_); - } else if (column_type == common::DOUBLE && - literal_.type == common::DOUBLE) { - double value; - std::memcpy(&value, data, sizeof(value)); - satisfied = - compare_values(value, literal_.double_value, compare_op_); - } else if (common::is_string_type(column_type) && - common::is_string_type(literal_.type)) { - satisfied = compare_values(std::string(data ? data : "", len), - literal_.string_value, compare_op_); - } else { - return common::E_NOT_SUPPORT; - } - // NULL never satisfies a comparison, negated or not. - if (negated) satisfied = !satisfied; +template +bool matches_value(const Expression& expr, bool negated, const T& value, + T Literal::*member) { + return matches_comparison( + expr, negated, [&](Op op, const Literal& literal, bool invert) { + return Expression::compare_values(value, literal.*member, op) != + invert; + }); +} + +template +bool matches_fixed_value(const Expression& expr, bool negated, const char* data, + T Literal::*member) { + T value; + std::memcpy(&value, data, sizeof(value)); + return matches_value(expr, negated, value, member); +} + +int evaluate_value(const Expression& expr, common::TSDataType type, + const char* data, uint32_t len, bool is_null, bool negated, + bool& satisfied) { + if (expr.type_ == IS_NULL || expr.type_ == IS_NOT_NULL) { + satisfied = (expr.type_ == IS_NULL) == (is_null != negated); + return common::E_OK; } + satisfied = false; + if (is_null) return common::E_OK; + const auto literal_type = expr.operand_->literal.type; + if (type == common::BOOLEAN && literal_type == common::BOOLEAN) + satisfied = + matches_fixed_value(expr, negated, data, &Literal::bool_value); + else if ((type == common::INT32 || type == common::DATE) && + literal_type == common::INT32) + satisfied = + matches_fixed_value(expr, negated, data, &Literal::int32_value); + else if ((type == common::INT64 || type == common::TIMESTAMP) && + literal_type == common::INT64) + satisfied = + matches_fixed_value(expr, negated, data, &Literal::int64_value); + else if (type == common::FLOAT && literal_type == common::FLOAT) + satisfied = + matches_fixed_value(expr, negated, data, &Literal::float_value); + else if (type == common::DOUBLE && literal_type == common::DOUBLE) + satisfied = + matches_fixed_value(expr, negated, data, &Literal::double_value); + else if (common::is_string_type(type) && + common::is_string_type(literal_type)) + satisfied = + matches_value(expr, negated, std::string(data ? data : "", len), + &Literal::string_value); + else + return common::E_NOT_SUPPORT; return common::E_OK; } -int AlignedFieldFilter::evaluate_row(const std::vector& fields, - bool& accepted, bool negated) const { - if (kind_ == Kind::NOT) - return left_field()->evaluate_row(fields, accepted, !negated); - if (kind_ == Kind::AND || kind_ == Kind::OR) { - int ret = left_field()->evaluate_row(fields, accepted, negated); - const bool conjunction = (kind_ == Kind::AND) != negated; +int matches_row(const Expression& expr, const std::vector& fields, + bool& accepted, bool negated) { + if (expr.type_ == NOT) + return matches_row(*expr.left_, fields, accepted, !negated); + if (expr.type_ == AND_EXPR || expr.type_ == OR_EXPR) { + int ret = matches_row(*expr.left_, fields, accepted, negated); + const bool conjunction = (expr.type_ == AND_EXPR) != negated; if (ret != common::E_OK || accepted != conjunction) return ret; - return right_field()->evaluate_row(fields, accepted, negated); + return matches_row(*expr.right_, fields, accepted, negated); } - const auto& field = *fields[series_index_]; + const auto& field = *fields[expr.operand_->index]; const char* data = reinterpret_cast(&field.value_); uint32_t len = 0; if (common::is_string_type(field.type_)) { data = field.value_.strval_->buf_; len = field.value_.strval_->len_; } - return evaluate_value(field.type_, data, len, + return evaluate_value(expr, field.type_, data, len, field.type_ == common::NULL_TYPE, negated, accepted); } -int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, - uint32_t row_count, bool negated, - SelectionMask& mask) const { +int evaluate_leaf(const Expression& expr, const ColumnView& column, + uint32_t row_count, bool negated, SelectionMask& mask) { if (column.type == common::INVALID_DATATYPE) return common::E_INVALID_ARG; if ((column.notnull_bitmap != nullptr && static_cast(column.row_offset) + row_count > @@ -510,18 +322,18 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, } bool satisfied; - const int ret = - evaluate_value(column.type, data, len, is_null, negated, satisfied); + const int ret = evaluate_value(expr, column.type, data, len, is_null, + negated, satisfied); if (ret != common::E_OK) return ret; if (satisfied) mask.set_one(row); } return common::E_OK; } -int AlignedFieldFilter::evaluate_leaf( - common::TsBlock& block, const std::map& column_index, - bool negated, SelectionMask& mask) const { - const auto found = column_index.find(column_); +int evaluate_leaf(const Expression& expr, common::TsBlock& block, + const std::map& column_index, + bool negated, SelectionMask& mask) { + const auto found = column_index.find(expr.operand_->reference); if (found == column_index.end()) return common::E_COLUMN_NOT_EXIST; const uint32_t vector_index = found->second; @@ -537,8 +349,8 @@ int AlignedFieldFilter::evaluate_leaf( char* data = iter.read(&len, &is_null); bool satisfied; - const int ret = - evaluate_value(column_type, data, len, is_null, negated, satisfied); + const int ret = evaluate_value(expr, column_type, data, len, is_null, + negated, satisfied); if (ret != common::E_OK) return ret; if (satisfied) mask.set_one(row); iter.next(); @@ -546,4 +358,55 @@ int AlignedFieldFilter::evaluate_leaf( return common::E_OK; } +} // namespace + +bool AlignedFieldFilter::may_match( + const std::map& statistics, int64_t rows) const { + return page_matches(*expression_, statistics, rows, false, false); +} +bool AlignedFieldFilter::all_match( + const std::map& statistics, int64_t rows) const { + return rows > 0 && + page_matches(*expression_, statistics, rows, true, false); +} +int AlignedFieldFilter::evaluate_row(const std::vector& fields, + bool& accepted) const { + return matches_row(*expression_, fields, accepted, false); +} + +int AlignedFieldFilter::evaluate(common::TsBlock& block, + const std::vector& column_names, + SelectionMask& mask) const { + std::map column_index; + for (uint32_t i = 0; i < column_names.size(); ++i) { + column_index[column_names[i]] = i + 1; + } + + return evaluate_tree( + *expression_, block.get_row_count(), mask, + [&](const Expression& leaf, bool negated, SelectionMask& result) { + return evaluate_leaf(leaf, block, column_index, negated, result); + }); +} + +int AlignedFieldFilter::evaluate_columns(const std::vector& columns, + uint32_t row_count, + SelectionMask& mask) const { + std::map column_index; + for (uint32_t i = 0; i < columns.size(); ++i) { + column_index[columns[i].name] = i; + } + + return evaluate_tree(*expression_, row_count, mask, + [&](const Expression& leaf, bool negated, + SelectionMask& result) -> int { + const auto found = + column_index.find(leaf.operand_->reference); + if (found == column_index.end()) + return common::E_COLUMN_NOT_EXIST; + return evaluate_leaf(leaf, columns[found->second], + row_count, negated, result); + }); +} + } // namespace storage diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 484cb5514..31cbb1ef8 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -23,12 +23,11 @@ #include #include #include -#include #include #include #include "common/tsblock/tsblock.h" -#include "reader/filter/bound_predicate.h" +#include "reader/expression.h" #include "reader/filter/selection_mask.h" namespace storage { @@ -39,7 +38,7 @@ struct Field; // pruning when possible; non-aligned sources use the table reader's timestamp // merge and typed row evaluation. Mixed-device files may use both paths. // It deliberately does not implement TableFieldFilter::satisfy_row(). -class AlignedFieldFilter : public BoundPredicate { +class AlignedFieldFilter : public Filter { public: struct ColumnView { std::string name; @@ -54,35 +53,9 @@ class AlignedFieldFilter : public BoundPredicate { uint32_t value_count = 0; }; - using Literal = Expression::Literal; - using Ptr = std::unique_ptr; - - static int from_expression(const Expression& expr, Ptr& out, - bool table_columns); - ~AlignedFieldFilter() override = default; - - static Ptr compare(std::string column, CompareOp op, Literal literal); - static Ptr is_null(std::string column); - static Ptr is_not_null(std::string column); - // Logical operands must be non-null. A missing operand remains an invalid - // non-null tree, rejected with E_INVALID_ARG when bound or queried. - static Ptr and_filter(Ptr left, Ptr right); - static Ptr or_filter(Ptr left, Ptr right); - static Ptr not_filter(Ptr child); - - const std::string& column() const { return column_; } - const Literal& literal() const { return literal_; } - std::vector referenced_columns() const; - - // False when a composite node is missing one of its operands. Callers use - // this to reject a malformed tree before page statistics can classify it - // as a full-page match and skip evaluation. - bool is_valid() const; - - // Resolve FIELD references and normalize literals to the declared column - // types before row evaluation or page pruning. - int bind(TableSchema& schema); + const Expression& expression() const { return *expression_; } + static int bind(const Expression& expr, TableSchema& schema, Ptr& result); // Conservatively decides whether any row in a page can satisfy the filter. // Missing or unsupported statistics always return true. @@ -100,45 +73,15 @@ class AlignedFieldFilter : public BoundPredicate { uint32_t row_count, SelectionMask& mask) const; private: + explicit AlignedFieldFilter(Expression::Ptr expr) + : expression_(std::move(expr)) {} friend class QDSWithoutTimeGenerator; using SeriesBindings = std::map>; - int bind_series(const SeriesBindings& bindings); - int evaluate_row(const std::vector& fields, bool& accepted, - bool negated = false) const; - - AlignedFieldFilter(Kind kind, std::string column, CompareOp op, - Literal literal); - AlignedFieldFilter(Kind kind, Ptr left, Ptr right); - const AlignedFieldFilter* left_field() const { - return static_cast(left()); - } - const AlignedFieldFilter* right_field() const { - return static_cast(right()); - } - - bool page_matches(const std::map& statistics, - int64_t row_count, bool require_all, bool negated) const; - bool leaf_may_match(const std::map& statistics, - int64_t row_count, bool negated) const; - bool leaf_all_match(const std::map& statistics, - int64_t row_count, bool negated) const; - - template - int evaluate_tree(uint32_t row_count, SelectionMask& mask, - EvaluateLeaf evaluate_leaf) const; - - int evaluate_leaf(common::TsBlock& block, - const std::map& column_index, - bool negated, SelectionMask& mask) const; - int evaluate_leaf(const ColumnView& column, uint32_t row_count, - bool negated, SelectionMask& mask) const; - int evaluate_value(common::TSDataType column_type, const char* data, - uint32_t len, bool is_null, bool negated, - bool& satisfied) const; - size_t series_index_ = 0; - std::string column_; - Literal literal_; + static int bind(const Expression& expr, const SeriesBindings& bindings, + Ptr& result); + int evaluate_row(const std::vector& fields, bool& accepted) const; + Expression::Ptr expression_; }; } // namespace storage diff --git a/cpp/src/reader/filter/bind_expression.cc b/cpp/src/reader/filter/bind_expression.cc index c224ddd57..4f8572465 100644 --- a/cpp/src/reader/filter/bind_expression.cc +++ b/cpp/src/reader/filter/bind_expression.cc @@ -22,7 +22,6 @@ #include #include #include -#include #include #include "common/schema.h" @@ -148,170 +147,87 @@ int bind_literal(Expression::Literal& literal, common::TSDataType column_type) { return common::E_NOT_SUPPORT; } -AlignedFieldFilter::AlignedFieldFilter(Kind kind, std::string column, - CompareOp op, Literal literal) - : BoundPredicate(kind, op), - column_(std::move(column)), - literal_(std::move(literal)) {} - -AlignedFieldFilter::AlignedFieldFilter(Kind kind, Ptr left, Ptr right) - : BoundPredicate(kind, std::move(left), std::move(right)) {} - -AlignedFieldFilter::Ptr AlignedFieldFilter::compare(std::string column, - CompareOp op, - Literal literal) { - return Ptr(new AlignedFieldFilter(Kind::COMPARISON, to_lower(column), op, - std::move(literal))); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::is_null(std::string column) { - return Ptr(new AlignedFieldFilter(Kind::IS_NULL, to_lower(column), - CompareOp::EQ, Literal())); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::is_not_null(std::string column) { - return Ptr(new AlignedFieldFilter(Kind::IS_NOT_NULL, to_lower(column), - CompareOp::EQ, Literal())); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::and_filter(Ptr left, Ptr right) { - return Ptr( - new AlignedFieldFilter(Kind::AND, std::move(left), std::move(right))); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::or_filter(Ptr left, Ptr right) { - return Ptr( - new AlignedFieldFilter(Kind::OR, std::move(left), std::move(right))); -} - -AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { - if (child && child->kind() == Kind::NOT) { - // Keep NOT(NULL operand) invalid across repeated negations. - if (!child->left_) return child; - return Ptr(static_cast(child->left_.release())); - } - return Ptr(new AlignedFieldFilter(Kind::NOT, std::move(child), nullptr)); -} - -int AlignedFieldFilter::from_expression(const Expression& expr, Ptr& out, - bool table_columns) { - auto leaf = [&](ExpressionType type, const Expression::Operand& operand, - Ptr& result) -> int { - std::string name = - table_columns ? to_lower(operand.reference) : operand.reference; - switch (type) { - case Kind::IS_NULL: - case Kind::IS_NOT_NULL: - case Kind::COMPARISON: - break; - case ExpressionType::BETWEEN: - case ExpressionType::NOT_BETWEEN: { - Ptr lower(new AlignedFieldFilter( - Kind::COMPARISON, name, CompareOp::GE, operand.literal)); - Ptr upper(new AlignedFieldFilter(Kind::COMPARISON, name, - CompareOp::LE, operand.upper)); - result = and_filter(std::move(lower), std::move(upper)); - if (type == ExpressionType::NOT_BETWEEN) - result = not_filter(std::move(result)); - return common::E_OK; - } - default: - return common::E_NOT_SUPPORT; +int bind_expression(const Expression& source, Expression::Ptr& result, + const std::function& bind_leaf) { + Expression::Ptr node(new Expression(source.type_)); + if (source.type_ == AND_EXPR || source.type_ == OR_EXPR || + source.type_ == NOT) { + if (!source.left_ || + (source.type_ == NOT) != (source.right_ == nullptr) || + source.operand_ || source.filter_) + return common::E_INVALID_ARG; + Expression::Ptr child; + int ret = bind_expression(*source.left_, child, bind_leaf); + if (ret != common::E_OK) return ret; + node->left_ = child.release(); + if (source.right_) { + ret = bind_expression(*source.right_, child, bind_leaf); + if (ret != common::E_OK) return ret; + node->right_ = child.release(); } - result.reset(new AlignedFieldFilter( - type, std::move(name), operand.comparison, operand.literal)); - return common::E_OK; - }; - return bind_expression( - expr, out, leaf, [](ExpressionType type, Ptr left, Ptr right) { - if (type == ExpressionType::NOT) return not_filter(std::move(left)); - if (type == AND_EXPR) - return and_filter(std::move(left), std::move(right)); - return or_filter(std::move(left), std::move(right)); - }); -} - -int AlignedFieldFilter::bind_series(const SeriesBindings& bindings) { - if (left_) { - int ret = static_cast(left_.get()) - ->bind_series(bindings); - if (ret != common::E_OK || !right_) return ret; - return static_cast(right_.get()) - ->bind_series(bindings); + } else { + if (source.left_ || source.right_ || !source.operand_ || + source.operand_->reference.empty()) + return common::E_INVALID_ARG; + node->operand_.reset(new Expression::Operand(*source.operand_)); + int ret = bind_leaf(*node); + if (ret != common::E_OK) return ret; } - auto it = bindings.find(column_); - if (it == bindings.end()) return common::E_COLUMN_NOT_EXIST; - series_index_ = it->second.first; - return kind_ == Kind::COMPARISON ? bind_literal(literal_, it->second.second) - : common::E_OK; + result = std::move(node); + return common::E_OK; } -std::vector AlignedFieldFilter::referenced_columns() const { - std::vector columns; - std::set seen_columns; - std::set seen_nodes; - std::vector stack{this}; - while (!stack.empty()) { - const AlignedFieldFilter* node = stack.back(); - stack.pop_back(); - if (node == nullptr || !seen_nodes.insert(node).second) continue; - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - if (seen_columns.insert(node->column_).second) { - columns.push_back(node->column_); - } - continue; +namespace { +int bind_value_leaf(Expression& node, common::TSDataType type) { + auto& operand = *node.operand_; + switch (node.type_) { + case IS_NULL: + case IS_NOT_NULL: + return common::E_OK; + case BETWEEN: + case NOT_BETWEEN: { + const int ret = bind_literal(operand.upper, type); + if (ret != common::E_OK) return ret; + break; } - if (node->right_) stack.push_back(node->right_field()); - if (node->left_) stack.push_back(node->left_field()); - } - return columns; -} - -bool AlignedFieldFilter::is_valid() const { - switch (kind_) { - case Kind::COMPARISON: - case Kind::IS_NULL: - case Kind::IS_NOT_NULL: - return true; - case Kind::NOT: - return left_ && left_field()->is_valid(); - case Kind::BETWEEN: - case Kind::NOT_BETWEEN: - case Kind::REGEXP: - case Kind::NOT_REGEXP: - case Kind::CUSTOM: - case SERIES_EXPR: - case GLOBALTIME_EXPR: - case INVALID_EXPR: - return false; - case Kind::AND: - case Kind::OR: - return left_ != nullptr && right_ != nullptr && - left_field()->is_valid() && right_field()->is_valid(); + case COMPARISON: + break; + default: + return common::E_NOT_SUPPORT; } - return false; + return bind_literal(operand.literal, type); } +} // namespace -int AlignedFieldFilter::bind(TableSchema& schema) { - if (kind_ == Kind::NOT) { - return left_ - ? static_cast(left_.get())->bind(schema) - : common::E_INVALID_ARG; - } - if (kind_ == Kind::AND || kind_ == Kind::OR) { - if (!left_ || !right_) return common::E_INVALID_ARG; - const int ret = - static_cast(left_.get())->bind(schema); - if (ret != common::E_OK) return ret; - return static_cast(right_.get())->bind(schema); - } - const common::ColumnSchema column = schema.get_column_schema(column_); - if (!column.is_valid()) return common::E_COLUMN_NOT_EXIST; - if (column.column_category_ != common::ColumnCategory::FIELD) - return common::E_INVALID_ARG; - if (kind_ != Kind::COMPARISON) return common::E_OK; - return bind_literal(literal_, column.data_type_); +int AlignedFieldFilter::bind(const Expression& expr, TableSchema& schema, + Ptr& result) { + Expression::Ptr bound; + const int ret = bind_expression(expr, bound, [&](Expression& node) -> int { + auto& name = node.operand_->reference; + to_lowercase_inplace(name); + const auto column = schema.get_column_schema(name); + if (!column.is_valid()) return common::E_COLUMN_NOT_EXIST; + if (column.column_category_ != common::ColumnCategory::FIELD) + return common::E_INVALID_ARG; + return bind_value_leaf(node, column.data_type_); + }); + if (ret == common::E_OK) + result.reset(new AlignedFieldFilter(std::move(bound))); + return ret; +} + +int AlignedFieldFilter::bind(const Expression& expr, + const SeriesBindings& bindings, Ptr& result) { + Expression::Ptr bound; + const int ret = bind_expression(expr, bound, [&](Expression& node) -> int { + const auto found = bindings.find(node.operand_->reference); + if (found == bindings.end()) return common::E_COLUMN_NOT_EXIST; + node.operand_->index = found->second.first; + return bind_value_leaf(node, found->second.second); + }); + if (ret == common::E_OK) + result.reset(new AlignedFieldFilter(std::move(bound))); + return ret; } } // namespace storage diff --git a/cpp/src/reader/filter/bind_expression.h b/cpp/src/reader/filter/bind_expression.h index 4255a5119..c37307205 100644 --- a/cpp/src/reader/filter/bind_expression.h +++ b/cpp/src/reader/filter/bind_expression.h @@ -4,7 +4,7 @@ * 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 + * "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 @@ -19,6 +19,8 @@ #ifndef READER_FILTER_BIND_EXPRESSION_H #define READER_FILTER_BIND_EXPRESSION_H +#include + #include "reader/expression.h" #include "utils/errno_define.h" @@ -27,31 +29,9 @@ namespace storage { // Validate the literal and convert numeric values to the column's type. int bind_literal(Expression::Literal& literal, common::TSDataType column_type); -// Bind the same logical nodes for device IDs, table fields and tree series. -// The leaf binder resolves names and literals for the query's schema. -template -int bind_expression(const Expression& expr, std::unique_ptr& result, - const BindLeaf& bind_leaf, const Combine& combine) { - const auto type = expr.type_; - if (type != AND_EXPR && type != OR_EXPR && type != ExpressionType::NOT) { - const auto* operand = expr.operand(); - if (expr.left_ || expr.right_ || !operand || operand->reference.empty()) - return common::E_INVALID_ARG; - return bind_leaf(type, *operand, result); - } - if (!expr.left_ || - ((type == ExpressionType::NOT) != (expr.right_ == nullptr))) - return common::E_INVALID_ARG; - std::unique_ptr left, right; - int ret = bind_expression(*expr.left_, left, bind_leaf, combine); - if (ret != common::E_OK) return ret; - if (expr.right_) { - ret = bind_expression(*expr.right_, right, bind_leaf, combine); - if (ret != common::E_OK) return ret; - } - result = combine(type, std::move(left), std::move(right)); - return common::E_OK; -} +// Copy a named expression for a query and resolve each leaf in that copy. +int bind_expression(const Expression& source, Expression::Ptr& result, + const std::function& bind_leaf); } // namespace storage #endif // READER_FILTER_BIND_EXPRESSION_H diff --git a/cpp/src/reader/filter/bound_predicate.h b/cpp/src/reader/filter/bound_predicate.h deleted file mode 100644 index 0f7f004a8..000000000 --- a/cpp/src/reader/filter/bound_predicate.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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. - */ - -#ifndef READER_FILTER_BOUND_PREDICATE_H -#define READER_FILTER_BOUND_PREDICATE_H - -#include -#include - -#include "reader/expression.h" - -namespace storage { - -// Execution nodes use the same operators as the named source expression. -class BoundPredicate : public Filter { - public: - using Kind = ExpressionType; - using CompareOp = Expression::CompareOp; - - Kind kind() const { return kind_; } - CompareOp compare_op() const { return compare_op_; } - const BoundPredicate* left() const { return left_.get(); } - const BoundPredicate* right() const { return right_.get(); } - - protected: - explicit BoundPredicate(Kind kind, CompareOp op = CompareOp::EQ) - : kind_(kind), compare_op_(op) {} - BoundPredicate(Kind kind, std::unique_ptr left, - std::unique_ptr right) - : kind_(kind), - compare_op_(CompareOp::EQ), - left_(std::move(left)), - right_(std::move(right)) {} - - template - static bool compare_values(const T& value, const T& literal, CompareOp op) { - switch (op) { - case CompareOp::EQ: - return value == literal; - case CompareOp::NE: - return value != literal; - case CompareOp::LT: - return value < literal; - case CompareOp::LE: - return value <= literal; - case CompareOp::GT: - return value > literal; - case CompareOp::GE: - return value >= literal; - } - return false; - } - - Kind kind_; - CompareOp compare_op_; - std::unique_ptr left_; - std::unique_ptr right_; -}; - -} // namespace storage -#endif // READER_FILTER_BOUND_PREDICATE_H diff --git a/cpp/src/reader/filter/tag_filter.cc b/cpp/src/reader/filter/tag_filter.cc index b7e3c07c9..9e4319ed9 100644 --- a/cpp/src/reader/filter/tag_filter.cc +++ b/cpp/src/reader/filter/tag_filter.cc @@ -25,131 +25,148 @@ namespace storage { +namespace { +bool matches_segment(ExpressionType type, Expression::CompareOp op, + size_t index, const std::string& literal, + const std::string& upper, + const std::vector& segments) { + const auto* value = index < segments.size() ? segments[index] : nullptr; + if (type == IS_NULL) return value == nullptr; + if (type == IS_NOT_NULL) return value != nullptr; + if (!value) return false; + if (type == COMPARISON) + return Expression::compare_values(*value, literal, op); + if (type == BETWEEN || type == NOT_BETWEEN) + return (literal <= *value && *value <= upper) == (type == BETWEEN); + ASSERT(false); + return false; +} + +bool matches_device(const Expression& expr, + const std::vector& segments) { + switch (expr.type_) { + case AND_EXPR: + return matches_device(*expr.left_, segments) && + matches_device(*expr.right_, segments); + case OR_EXPR: + return matches_device(*expr.left_, segments) || + matches_device(*expr.right_, segments); + case NOT: + return !matches_device(*expr.left_, segments); + case REGEXP: + case NOT_REGEXP: + return expr.filter_->satisfyRow(0, segments); + default: { + const auto& leaf = *expr.operand_; + return matches_segment(expr.type_, leaf.comparison, leaf.index, + leaf.literal.string_value, + leaf.upper.string_value, segments); + } + } +} +} // namespace + int TagFilter::bind(const Expression& expr, TableSchema& schema, std::unique_ptr& out) { - using Ptr = std::unique_ptr; - auto leaf = [&](ExpressionType type, const Expression::Operand& operand, - Ptr& result) -> int { + Expression::Ptr bound; + const int ret = bind_expression(expr, bound, [&](Expression& node) -> int { + auto& operand = *node.operand_; const int order = schema.find_id_column_order(operand.reference); if (order < 0) return common::E_COLUMN_NOT_EXIST; - const int index = order + 1; - if (type == ExpressionType::IS_NULL || - type == ExpressionType::IS_NOT_NULL) { - result.reset(new TagFilter(type, index, "")); + operand.index = order + 1; + if (node.type_ == IS_NULL || node.type_ == IS_NOT_NULL) return common::E_OK; - } if (operand.literal.type != common::STRING) return common::E_NOT_SUPPORT; - const auto& value = operand.literal.string_value; - if ((type == Kind::BETWEEN || type == Kind::NOT_BETWEEN) && - operand.upper.type != common::STRING) - return common::E_NOT_SUPPORT; - switch (type) { - case ExpressionType::COMPARISON: - result.reset(new TagFilter(Kind::COMPARISON, index, value, - operand.comparison)); - break; - case ExpressionType::BETWEEN: - result.reset( - new TagBetween(index, value, operand.upper.string_value)); - break; - case ExpressionType::NOT_BETWEEN: - result.reset(new TagNotBetween(index, value, - operand.upper.string_value)); - break; - case ExpressionType::REGEXP: - result.reset(new TagRegExp(index, value)); - break; - case ExpressionType::NOT_REGEXP: - result.reset(new TagNotRegExp(index, value)); - break; + switch (node.type_) { + case COMPARISON: + return common::E_OK; + case BETWEEN: + case NOT_BETWEEN: + return operand.upper.type == common::STRING + ? common::E_OK + : common::E_NOT_SUPPORT; + case REGEXP: + node.filter_ = + new TagRegExp(order + 1, operand.literal.string_value); + return common::E_OK; + case NOT_REGEXP: + node.filter_ = + new TagNotRegExp(order + 1, operand.literal.string_value); + return common::E_OK; default: return common::E_NOT_SUPPORT; } - return common::E_OK; - }; - return bind_expression( - expr, out, leaf, [](ExpressionType type, Ptr left, Ptr right) { - return Ptr(new TagFilter(type, left.release(), right.release())); - }); + }); + if (ret == common::E_OK) out.reset(new TagFilter(std::move(bound))); + return ret; } -TagFilter::TagFilter(int col_idx, std::string value) - : TagFilter(Kind::CUSTOM, col_idx, std::move(value)) {} +TagFilter::TagFilter(Expression::Ptr expression) : TagFilter(-1, "") { + expression_ = std::move(expression); +} -TagFilter::TagFilter(Kind kind, int col_idx, std::string value, CompareOp op) - : BoundPredicate(kind, op), value_(std::move(value)), col_idx_(col_idx) {} +TagFilter::TagFilter(int col_idx, std::string value) + : TagFilter(INVALID_EXPR, col_idx, std::move(value)) {} -TagFilter::TagFilter(Kind kind, TagFilter* left, TagFilter* right) - : BoundPredicate(kind, std::unique_ptr(left), - std::unique_ptr(right)), - col_idx_(-1) {} +TagFilter::TagFilter(ExpressionType type, int col_idx, std::string value, + Expression::CompareOp op) + : value_(std::move(value)), + col_idx_(col_idx), + type_(type), + comparison_(op) {} TagFilter::~TagFilter() = default; +const std::string* TagFilter::exact_device_id_segment() const { + if (expression_) { + const auto* leaf = expression_->operand_.get(); + if (expression_->type_ == COMPARISON && + leaf->comparison == Expression::CompareOp::EQ && leaf->index == 1) + return &leaf->literal.string_value; + } else if (typeid(*this) == typeid(TagEq) && col_idx_ == 1) { + return &value_; + } + return nullptr; +} + bool TagFilter::satisfyRow(int time, std::vector segments) const { return satisfyRow(std::move(segments)); } bool TagFilter::satisfyRow(std::vector segments) const { - switch (kind_) { - case Kind::AND: - return left_tag()->satisfyRow(segments) && - right_tag()->satisfyRow(std::move(segments)); - case Kind::OR: - return left_tag()->satisfyRow(segments) || - right_tag()->satisfyRow(std::move(segments)); - case Kind::NOT: - return !left_tag()->satisfyRow(std::move(segments)); - case Kind::IS_NULL: - return col_idx_ >= segments.size() || !segments[col_idx_]; - case Kind::IS_NOT_NULL: - return col_idx_ < segments.size() && segments[col_idx_]; - case Kind::COMPARISON: - return col_idx_ < segments.size() && segments[col_idx_] && - compare_values(*segments[col_idx_], value_, compare_op_); - case Kind::BETWEEN: - case Kind::NOT_BETWEEN: { - if (col_idx_ >= segments.size() || !segments[col_idx_]) - return false; - const auto& value = *segments[col_idx_]; - const bool between = compare_values(value, value_, CompareOp::GE) && - compare_values(value, value2_, CompareOp::LE); - return kind_ == Kind::BETWEEN ? between : !between; - } - case Kind::REGEXP: - case Kind::NOT_REGEXP: - case Kind::CUSTOM: - case SERIES_EXPR: - case GLOBALTIME_EXPR: - case INVALID_EXPR: - ASSERT(false); - return false; - } - return false; + if (expression_) return matches_device(*expression_, segments); + return matches_segment(type_, comparison_, col_idx_, value_, value2_, + segments); } TagEq::TagEq(int col_idx, std::string value) - : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::EQ) {} + : TagFilter(ExpressionType::COMPARISON, col_idx, std::move(value), + Expression::CompareOp::EQ) {} TagNeq::TagNeq(int col_idx, std::string value) - : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::NE) {} + : TagFilter(ExpressionType::COMPARISON, col_idx, std::move(value), + Expression::CompareOp::NE) {} TagLt::TagLt(int col_idx, std::string value) - : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::LT) {} + : TagFilter(ExpressionType::COMPARISON, col_idx, std::move(value), + Expression::CompareOp::LT) {} TagLteq::TagLteq(int col_idx, std::string value) - : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::LE) {} + : TagFilter(ExpressionType::COMPARISON, col_idx, std::move(value), + Expression::CompareOp::LE) {} TagGt::TagGt(int col_idx, std::string value) - : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::GT) {} + : TagFilter(ExpressionType::COMPARISON, col_idx, std::move(value), + Expression::CompareOp::GT) {} TagGteq::TagGteq(int col_idx, std::string value) - : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::GE) {} + : TagFilter(ExpressionType::COMPARISON, col_idx, std::move(value), + Expression::CompareOp::GE) {} // TagRegExp implementation TagRegExp::TagRegExp(int col_idx, std::string tag_value) - : TagFilter(Kind::REGEXP, col_idx, std::move(tag_value)) { + : TagFilter(ExpressionType::REGEXP, col_idx, std::move(tag_value)) { try { pattern_ = std::regex(value_); is_valid_pattern_ = true; @@ -171,7 +188,7 @@ bool TagRegExp::satisfyRow(std::vector segments) const { // TagNotRegExp implementation TagNotRegExp::TagNotRegExp(int col_idx, std::string tag_value) - : TagFilter(Kind::NOT_REGEXP, col_idx, std::move(tag_value)) { + : TagFilter(ExpressionType::NOT_REGEXP, col_idx, std::move(tag_value)) { try { pattern_ = std::regex(value_); is_valid_pattern_ = true; @@ -191,28 +208,40 @@ bool TagNotRegExp::satisfyRow(std::vector segments) const { } } -TagIsNull::TagIsNull(int col_idx) : TagFilter(Kind::IS_NULL, col_idx, "") {} +TagIsNull::TagIsNull(int col_idx) + : TagFilter(ExpressionType::IS_NULL, col_idx, "") {} TagIsNotNull::TagIsNotNull(int col_idx) - : TagFilter(Kind::IS_NOT_NULL, col_idx, "") {} + : TagFilter(ExpressionType::IS_NOT_NULL, col_idx, "") {} // TagBetween implementation TagBetween::TagBetween(int col_idx, std::string lower_value, std::string upper_value) - : TagFilter(Kind::BETWEEN, col_idx, std::move(lower_value)) { + : TagFilter(ExpressionType::BETWEEN, col_idx, std::move(lower_value)) { value2_ = std::move(upper_value); } // TagNotBetween implementation TagNotBetween::TagNotBetween(int col_idx, std::string lower_value, std::string upper_value) - : TagFilter(Kind::NOT_BETWEEN, col_idx, std::move(lower_value)) { + : TagFilter(ExpressionType::NOT_BETWEEN, col_idx, std::move(lower_value)) { value2_ = std::move(upper_value); } TagAnd::TagAnd(TagFilter* left, TagFilter* right) - : TagFilter(Kind::AND, left, right) {} + : TagFilter(-1, ""), left_(left), right_(right) {} +bool TagAnd::satisfyRow(std::vector segments) const { + return left_->satisfyRow(segments) && + right_->satisfyRow(std::move(segments)); +} TagOr::TagOr(TagFilter* left, TagFilter* right) - : TagFilter(Kind::OR, left, right) {} -TagNot::TagNot(TagFilter* child) : TagFilter(Kind::NOT, child, nullptr) {} + : TagFilter(-1, ""), left_(left), right_(right) {} +bool TagOr::satisfyRow(std::vector segments) const { + return left_->satisfyRow(segments) || + right_->satisfyRow(std::move(segments)); +} +TagNot::TagNot(TagFilter* child) : TagFilter(-1, ""), left_(child) {} +bool TagNot::satisfyRow(std::vector segments) const { + return !left_->satisfyRow(std::move(segments)); +} -} // namespace storage \ No newline at end of file +} // namespace storage diff --git a/cpp/src/reader/filter/tag_filter.h b/cpp/src/reader/filter/tag_filter.h index da005833b..c66a50ac9 100644 --- a/cpp/src/reader/filter/tag_filter.h +++ b/cpp/src/reader/filter/tag_filter.h @@ -26,15 +26,16 @@ #include "common/allocator/my_string.h" #include "common/schema.h" -#include "reader/filter/bound_predicate.h" +#include "reader/expression.h" namespace storage { -class TagFilter : public BoundPredicate { +class TagFilter : public Filter { public: static int bind(const Expression& expr, TableSchema& schema, std::unique_ptr& out); TagFilter(int col_idx, std::string tag_value); + const std::string* exact_device_id_segment() const; ~TagFilter() override; bool satisfyRow(int time, @@ -46,17 +47,14 @@ class TagFilter : public BoundPredicate { int col_idx_; protected: - TagFilter(Kind kind, int col_idx, std::string value, - CompareOp op = CompareOp::EQ); - TagFilter(Kind kind, TagFilter* left, TagFilter* right); + TagFilter(ExpressionType type, int col_idx, std::string value, + Expression::CompareOp op = Expression::CompareOp::EQ); private: - const TagFilter* left_tag() const { - return static_cast(left()); - } - const TagFilter* right_tag() const { - return static_cast(right()); - } + explicit TagFilter(Expression::Ptr expression); + Expression::Ptr expression_; + ExpressionType type_; + Expression::CompareOp comparison_; }; // Equality comparison @@ -145,18 +143,35 @@ class TagNotBetween : public TagFilter { class TagAnd : public TagFilter { public: TagAnd(TagFilter* left, TagFilter* right); + bool satisfyRow(std::vector segments) const override; + using TagFilter::satisfyRow; + + private: + std::unique_ptr left_; + std::unique_ptr right_; }; // Logical OR operation (binary) class TagOr : public TagFilter { public: TagOr(TagFilter* left, TagFilter* right); + bool satisfyRow(std::vector segments) const override; + using TagFilter::satisfyRow; + + private: + std::unique_ptr left_; + std::unique_ptr right_; }; // Logical NOT operation class TagNot : public TagFilter { public: explicit TagNot(TagFilter* filter); + bool satisfyRow(std::vector segments) const override; + using TagFilter::satisfyRow; + + private: + std::unique_ptr left_; }; } // namespace storage diff --git a/cpp/src/reader/qds_without_timegenerator.cc b/cpp/src/reader/qds_without_timegenerator.cc index 25d698760..0e6dfae1e 100644 --- a/cpp/src/reader/qds_without_timegenerator.cc +++ b/cpp/src/reader/qds_without_timegenerator.cc @@ -97,11 +97,7 @@ int QDSWithoutTimeGenerator::init(TsFileIOReader* io_reader, int limit) { remaining_offset_ = offset; remaining_limit_ = limit; - qe_ = query; - int ret = - AlignedFieldFilter::from_expression(predicate, row_predicate_, false); - if (ret != E_OK) return ret; - return init_internal(io_reader, query); + return init_internal(io_reader, query, &predicate); } namespace { @@ -143,7 +139,8 @@ int resolve_series(const std::string& reference, } // namespace int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, - QueryExpression* qe) { + QueryExpression* qe, + const Expression* predicate) { int ret = E_OK; // cppcheck-suppress unreadVariable pa_.reset(); pa_.init(512, common::MOD_TSFILE_READER); @@ -154,12 +151,12 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, const size_t selected_count = paths.size(); size_t projected_count = 0; std::map filter_paths; - if (row_predicate_) { + if (predicate) { for (const auto& path : paths) { if (!path.device_id_ || path.measurement_.empty()) return E_INVALID_PATH; } - for (const auto& name : row_predicate_->referenced_columns()) { + for (const auto& name : predicate->referenced_columns()) { Path path; int status = resolve_series(name, qe_->selected_series_, path); if (status != E_OK) return status; @@ -184,7 +181,7 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, ssi_data_types.reserve(origin_path_count); Expression* global_time_expression = qe->expression_; Filter* global_time_filter = nullptr; - if (!row_predicate_ && global_time_expression != nullptr) { + if (!predicate && global_time_expression != nullptr) { global_time_filter = global_time_expression->filter_; } index_lookup_.insert({"time", 0}); @@ -223,7 +220,7 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, } size_t path_count = valid_paths.size(); - is_single_path_ = (path_count == 1 && !row_predicate_); + is_single_path_ = (path_count == 1 && !predicate); // Only push offset/limit to SSI for single-path; multi-path applies at // merge. for (size_t i = 0; i < path_count; i++) { @@ -237,7 +234,7 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, time_iters_.resize(path_count); value_iters_.resize(path_count); - if (row_predicate_) { + if (predicate) { predicate_row_arena_.init(512, common::MOD_TSFILE_READER); filter_only_row_.reset(new RowRecord(path_count - projected_count)); AlignedFieldFilter::SeriesBindings bindings; @@ -255,7 +252,9 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, size_t i = found->second; bindings.emplace(entry.first, std::make_pair(i, ssi_data_types[i])); } - if (RET_FAIL(row_predicate_->bind_series(bindings))) return ret; + if (RET_FAIL( + AlignedFieldFilter::bind(*predicate, bindings, row_predicate_))) + return ret; } for (size_t i = 0; i < path_count; i++) { diff --git a/cpp/src/reader/qds_without_timegenerator.h b/cpp/src/reader/qds_without_timegenerator.h index a3735ce30..399865f6c 100644 --- a/cpp/src/reader/qds_without_timegenerator.h +++ b/cpp/src/reader/qds_without_timegenerator.h @@ -65,7 +65,8 @@ class QDSWithoutTimeGenerator : public ResultSet { std::shared_ptr get_metadata(); private: - int init_internal(TsFileIOReader* io_reader, QueryExpression* qe); + int init_internal(TsFileIOReader* io_reader, QueryExpression* qe, + const Expression* predicate = nullptr); int load_next_tsblock(uint32_t index, bool alloc_mem); int load_next_tsblock_with_hint(uint32_t index, bool alloc_mem, int64_t min_time_hint); diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index af1f4d011..886dd6651 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -93,24 +93,15 @@ int TableQueryExecutor::query_impl(const std::string& table_name, ret = TagFilter::bind(*tag_expression, *table_schema, bound_tag); if (ret != common::E_OK) return ret; } + if (auto* filter = dynamic_cast(owned_field.get())) + field_expression = &filter->expression(); if (field_expression) { AlignedFieldFilter::Ptr bound; - ret = - AlignedFieldFilter::from_expression(*field_expression, bound, true); - if (ret != common::E_OK) { - return ret; - } + ret = AlignedFieldFilter::bind(*field_expression, *table_schema, bound); + if (ret != common::E_OK) return ret; + column_mapping->add(bound->expression()); owned_field = std::move(bound); } - if (auto* aligned_filter = - dynamic_cast(owned_field.get())) { - ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( - *aligned_filter, *table_schema) - : common::E_INVALID_ARG; - if (ret != common::E_OK) { - return ret; - } - } auto device_task_iterator = std::unique_ptr( new DeviceTaskIterator(lower_case_column_names, table_root, diff --git a/cpp/test/reader/aligned_chunk_reader_bulk_test.cc b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc index c5c5d2291..12be67b21 100644 --- a/cpp/test/reader/aligned_chunk_reader_bulk_test.cc +++ b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc @@ -410,9 +410,12 @@ TEST_F(AlignedBulkCopyTest, RowsSpanMultipleBlocks) { // partially matching page must stay on the row-by-row path. Page 1 (rows 8..15) // is only half retained; if it were bulk-copied, rows 8..11 would leak out. TEST_F(AlignedBulkCopyTest, FieldFilterKeepsPartialPageOnSlowPath) { - auto field_filter = - AlignedFieldFilter::compare("v", AlignedFieldFilter::CompareOp::GE, - AlignedFieldFilter::Literal::int64(12)); + AlignedFieldFilter::Ptr field_filter; + ASSERT_EQ(common::E_OK, + AlignedFieldFilter::bind( + *Expression::compare("v", Expression::CompareOp::GE, + Expression::Literal::int64(12)), + *schema_, field_filter)); ASSERT_NE(field_filter, nullptr); reader_->set_field_filter(field_filter.get()); const std::vector rows = read_all({"v", "w"}, nullptr, kRowCount); diff --git a/cpp/test/reader/aligned_field_filter_regression_test.cc b/cpp/test/reader/aligned_field_filter_regression_test.cc index 653c3a55e..2f471cf07 100644 --- a/cpp/test/reader/aligned_field_filter_regression_test.cc +++ b/cpp/test/reader/aligned_field_filter_regression_test.cc @@ -47,7 +47,7 @@ namespace { using namespace common; using namespace storage; -using A = AlignedFieldFilter; +using A = Expression; using Rows = std::vector>; const int64_t kNull = INT64_MIN; @@ -109,8 +109,8 @@ class AlignedFieldFilterRegressionTest EXPECT_EQ(file.open(filename_), E_OK); TableQueryExecutor executor(&file, std::get<1>(GetParam())); ResultSet* result = nullptr; - EXPECT_EQ(executor.query("t", columns, time_filter, nullptr, - filter.release(), offset, limit, result), + EXPECT_EQ(executor.query("t", columns, time_filter, offset, limit, + result, nullptr, filter.get()), E_OK); Rows rows; if (!result) return rows; @@ -483,6 +483,29 @@ TEST_P(AlignedFieldFilterRegressionTest, FloatingStatisticsKeepNaNRowsCorrect) { } } +TEST_P(AlignedFieldFilterRegressionTest, RangesBindBothBoundsAndExcludeNulls) { + write_floats(); + for (double upper : {2.0, -1.0, std::numeric_limits::quiet_NaN()}) { + for (bool outside : {false, true}) { + for (bool negate : {false, true}) { + auto expr = A::between("f", A::Literal::int32(1), + A::Literal::float64(upper), outside); + if (negate) expr = A::not_filter(std::move(expr)); + Rows expected; + for (int device = 0; device < 2; ++device) { + for (uint32_t r = 0; r < float_values_.size(); ++r) { + const auto value = float_values_[r]; + const bool inside = value >= 1.0 && value <= upper; + if (inside != (outside != negate)) + expected.push_back({r, device * 100 + r}); + } + } + EXPECT_EQ(scan({"v"}, std::move(expr)), expected); + } + } + } +} + TEST_P(AlignedFieldFilterRegressionTest, NotPreservesFloatingNaNRowSemantics) { write_floats(); // Control: d2 has no float data at all, so IS NULL must see all of its @@ -623,11 +646,11 @@ TEST_P(AlignedFieldFilterRegressionTest, TableQueryExecutor executor(&file, std::get<1>(GetParam())); ResultSet* result = nullptr; const int ret = - mode == 0 ? executor.query("t", {"v"}, nullptr, nullptr, - filter.release(), result) - : executor.query("t", {"v"}, nullptr, nullptr, - filter.release(), 0, - mode == 1 ? 0 : -1, result); + mode == 0 ? executor.query("t", {"v"}, nullptr, 0, -1, + result, nullptr, filter.get()) + : executor.query("t", {"v"}, nullptr, 0, + mode == 1 ? 0 : -1, result, + nullptr, filter.get()); EXPECT_EQ(ret, E_NOT_SUPPORT); EXPECT_EQ(result, nullptr); if (result != nullptr) executor.destroy_query_data_set(result); @@ -651,8 +674,8 @@ TEST_P(AlignedFieldFilterRegressionTest, IncompleteOrCannotBypassEvaluation) { ASSERT_EQ(file.open(filename_), E_OK); TableQueryExecutor executor(&file, std::get<1>(GetParam())); ResultSet* result = nullptr; - int ret = executor.query("t", {"v"}, nullptr, nullptr, filter.release(), 0, - -1, result); + int ret = executor.query("t", {"v"}, nullptr, 0, -1, result, nullptr, + filter.get()); if (ret == E_OK) { ASSERT_NE(result, nullptr); bool next = false; @@ -713,11 +736,11 @@ TEST_P(AlignedFieldFilterRegressionTest, ResultSet* result = nullptr; const int ret = mode == 0 - ? executor.query("t", {"v"}, nullptr, nullptr, - filter.release(), result) - : executor.query("t", {"v"}, nullptr, nullptr, - filter.release(), 0, - mode == 2 ? 0 : -1, result); + ? executor.query("t", {"v"}, nullptr, 0, -1, + result, nullptr, filter.get()) + : executor.query("t", {"v"}, nullptr, 0, + mode == 2 ? 0 : -1, result, + nullptr, filter.get()); EXPECT_EQ(ret, malformed ? E_INVALID_ARG : E_OK); if (malformed) EXPECT_EQ(result, nullptr); if (result != nullptr) { diff --git a/cpp/test/reader/block/masked_bulk_copy_test.cc b/cpp/test/reader/block/masked_bulk_copy_test.cc index d2a467a31..0357fd031 100644 --- a/cpp/test/reader/block/masked_bulk_copy_test.cc +++ b/cpp/test/reader/block/masked_bulk_copy_test.cc @@ -125,7 +125,10 @@ class MaskedBulkCopyTest : public ::testing::TestWithParam { auto device = std::make_shared( std::vector{"t"}); DeviceQueryTask task(device, names, mapping, nullptr, schema_); - auto source_filter = AlignedFieldFilter::is_not_null("v"); + AlignedFieldFilter::Ptr source_filter; + ASSERT_EQ(common::E_OK, + AlignedFieldFilter::bind(*Expression::is_not_null("v"), + *schema_, source_filter)); VectorMeasurementColumnContext context(&reader); std::vector> positions{{0, 4}, {1}, {2}, {}, {3}}; ASSERT_EQ(context.init(&task, names, nullptr, positions, arena, diff --git a/cpp/test/reader/chunk_reader_resource_test.cc b/cpp/test/reader/chunk_reader_resource_test.cc index 3da4d840d..dfd924356 100644 --- a/cpp/test/reader/chunk_reader_resource_test.cc +++ b/cpp/test/reader/chunk_reader_resource_test.cc @@ -277,9 +277,12 @@ class AlignedReaderFailureTest : public ::testing::Test { } const auto target_offset = payload_offset( file, target == "time" ? time : values.at(target), page_number); - auto filter = - AlignedFieldFilter::compare("v", AlignedFieldFilter::CompareOp::GE, - AlignedFieldFilter::Literal::int64(3)); + AlignedFieldFilter::Ptr filter; + ASSERT_EQ(common::E_OK, + AlignedFieldFilter::bind( + *Expression::compare("v", Expression::CompareOp::GE, + Expression::Literal::int64(3)), + *schema_, filter)); auto* reader = allocate_reader(&file); ASSERT_NE(reader, nullptr); // The production reader uses placement new and explicit destroy(). diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/aligned_field_filter_test.cc index ac1cd6dfa..4d88f9944 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/aligned_field_filter_test.cc @@ -28,14 +28,27 @@ #include "common/schema.h" #include "common/statistic.h" +#include "reader/filter/bind_expression.h" #include "reader/filter/selection_mask.h" namespace storage { namespace { +AlignedFieldFilter::Ptr bind_field(Expression::Ptr expr, + common::TSDataType type = common::INT64) { + std::vector columns; + for (const auto& name : expr->referenced_columns()) + columns.emplace_back(name, type, common::UNCOMPRESSED, common::PLAIN, + common::ColumnCategory::FIELD); + TableSchema schema("t", columns); + AlignedFieldFilter::Ptr filter; + EXPECT_EQ(common::E_OK, AlignedFieldFilter::bind(*expr, schema, filter)); + return filter; +} + TEST(AlignedFieldFilterTest, MissingNotOperandsStayInvalidAfterRewriting) { using namespace common; - using A = AlignedFieldFilter; + using A = Expression; TableSchema schema( "t", {{"v", INT64, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}}); for (int shape = 0; shape < 5; ++shape) { @@ -51,41 +64,41 @@ TEST(AlignedFieldFilterTest, MissingNotOperandsStayInvalidAfterRewriting) { SCOPED_TRACE(::testing::Message() << shape << ":" << depth); filter = A::not_filter(std::move(filter)); ASSERT_NE(filter, nullptr); - EXPECT_FALSE(filter->is_valid()); - EXPECT_EQ(filter->bind(schema), E_INVALID_ARG); - SelectionMask mask; - EXPECT_EQ(filter->evaluate_columns({}, 0, mask), E_INVALID_ARG); + AlignedFieldFilter::Ptr bound; + EXPECT_EQ(AlignedFieldFilter::bind(*filter, schema, bound), + E_INVALID_ARG); + EXPECT_EQ(bound, nullptr); } } } TEST(AlignedFieldFilterTest, AlternatingNotPreservesNullSemanticsAfterBinding) { - using A = AlignedFieldFilter; + using A = Expression; const int levels = 32; auto expr = A::is_null("v"); for (int height = 1; height < levels; ++height) { expr = A::not_filter(A::and_filter(std::move(expr), A::is_null("v"))); } - ASSERT_TRUE(expr->is_valid()); TableSchema schema("t", {{"v", common::INT64, common::UNCOMPRESSED, common::PLAIN, common::ColumnCategory::FIELD}}); - ASSERT_EQ(common::E_OK, expr->bind(schema)); - A::ColumnView v; + AlignedFieldFilter::Ptr bound; + ASSERT_EQ(common::E_OK, AlignedFieldFilter::bind(*expr, schema, bound)); + AlignedFieldFilter::ColumnView v; v.name = "v"; v.type = common::INT64; SelectionMask mask; - ASSERT_EQ(common::E_OK, expr->evaluate_columns({v}, 1, mask)); + ASSERT_EQ(common::E_OK, bound->evaluate_columns({v}, 1, mask)); EXPECT_EQ((levels % 2) == 1, mask.test(0)); } TEST(AlignedFieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { using namespace common; - using A = AlignedFieldFilter; + using A = Expression; const uint8_t bitmap = 0x90; // rows 0 and 3 have values const int64_t values[] = {4, 9}; const String strings[] = {String("a", 1), String("b", 1)}; for (bool text : {false, true}) { - A::ColumnView view; + AlignedFieldFilter::ColumnView view; view.name = "v"; view.type = text ? STRING : INT64; view.notnull_bitmap = &bitmap; @@ -93,7 +106,7 @@ TEST(AlignedFieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { view.fixed_values = reinterpret_cast(values); view.string_values = strings; view.value_count = 2; - auto filter = A::is_not_null("v"); + auto filter = bind_field(A::is_not_null("v"), view.type); SelectionMask mask; ASSERT_EQ(filter->evaluate_columns({view}, 4, mask), E_OK); EXPECT_EQ(mask.count_ones(), 2U); @@ -113,14 +126,16 @@ TEST(AlignedFieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { view.notnull_bitmap = nullptr; view.nonnull_start = 0; view.value_count = 0; - ASSERT_EQ(A::is_null("v")->evaluate_columns({view}, 4, mask), E_OK); + ASSERT_EQ(bind_field(A::is_null("v"), view.type) + ->evaluate_columns({view}, 4, mask), + E_OK); EXPECT_EQ(mask.count_ones(), 4U); } } TEST(AlignedFieldFilterTest, NumericBindingHandlesNarrowingAndRounding) { using namespace common; - using A = AlignedFieldFilter; + using A = Expression; using L = A::Literal; using Case = std::tuple; const double infinity = std::numeric_limits::infinity(); @@ -162,11 +177,8 @@ TEST(AlignedFieldFilterTest, NumericBindingHandlesNarrowingAndRounding) { const L& expected = std::get<2>(item); SCOPED_TRACE(::testing::Message() << int(type) << ":" << int(input.type)); - TableSchema schema( - "t", {{"v", type, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}}); - auto filter = A::compare("v", A::CompareOp::EQ, input); - ASSERT_EQ(filter->bind(schema), E_OK); - const L& actual = filter->literal(); + L actual = input; + ASSERT_EQ(bind_literal(actual, type), E_OK); ASSERT_EQ(actual.type, expected.type); if (actual.type == INT32) { EXPECT_EQ(actual.int32_value, expected.int32_value); @@ -291,37 +303,34 @@ TEST(AlignedFieldFilterTest, PageStatisticsAreConservative) { statistic.max_value_ = 20; const std::map stats{{"a", &statistic}}; - auto below = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::Literal::int64(5)); + auto below = bind_field(Expression::compare("a", Expression::CompareOp::LT, + Expression::Literal::int64(5))); EXPECT_FALSE(below->may_match(stats, 5)); - auto overlap = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::Literal::int64(10)); + auto overlap = bind_field(Expression::compare( + "a", Expression::CompareOp::LE, Expression::Literal::int64(10))); EXPECT_TRUE(overlap->may_match(stats, 5)); - auto is_null = AlignedFieldFilter::is_null("a"); + auto is_null = bind_field(Expression::is_null("a")); EXPECT_FALSE(is_null->may_match(stats, 5)); statistic.count_ = 4; EXPECT_TRUE(is_null->may_match(stats, 5)); - auto missing = AlignedFieldFilter::compare( - "missing", AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::Literal::int64(1)); + auto missing = bind_field(Expression::compare( + "missing", Expression::CompareOp::EQ, Expression::Literal::int64(1))); EXPECT_TRUE(missing->may_match(stats, 5)); } TEST(AlignedFieldFilterTest, UnknownRowCountCannotProveWholePageMatches) { - using Field = AlignedFieldFilter; + using Field = Expression; Int64Statistic empty, values; values.update(1, int64_t(5)); values.update(2, int64_t(15)); const std::map stats{{"a", &empty}, {"b", &values}}; - auto filter = Field::or_filter( + auto filter = bind_field(Field::or_filter( Field::is_not_null("a"), - Field::compare("b", Field::CompareOp::GT, Field::Literal::int64(10))); + Field::compare("b", Field::CompareOp::GT, Field::Literal::int64(10)))); EXPECT_TRUE(filter->may_match(stats, 0)); EXPECT_FALSE(filter->all_match(stats, 0)); @@ -334,65 +343,58 @@ TEST(AlignedFieldFilterTest, PageStatisticsAllMatchIsConservative) { statistic.max_value_ = 20; const std::map stats{{"a", &statistic}}; - auto ge = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::GE, - AlignedFieldFilter::Literal::int64(10)); + auto ge = bind_field(Expression::compare("a", Expression::CompareOp::GE, + Expression::Literal::int64(10))); EXPECT_TRUE(ge->all_match(stats, 5)); - auto lt = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::Literal::int64(21)); + auto lt = bind_field(Expression::compare("a", Expression::CompareOp::LT, + Expression::Literal::int64(21))); EXPECT_TRUE(lt->all_match(stats, 5)); - auto strict_lt = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::Literal::int64(20)); + auto strict_lt = bind_field(Expression::compare( + "a", Expression::CompareOp::LT, Expression::Literal::int64(20))); EXPECT_FALSE(strict_lt->all_match(stats, 5)); - auto not_null = AlignedFieldFilter::is_not_null("a"); + auto not_null = bind_field(Expression::is_not_null("a")); EXPECT_TRUE(not_null->all_match(stats, 5)); statistic.count_ = 4; EXPECT_FALSE(not_null->all_match(stats, 5)); - auto is_null = AlignedFieldFilter::is_null("a"); + auto is_null = bind_field(Expression::is_null("a")); statistic.count_ = 0; EXPECT_TRUE(is_null->all_match(stats, 5)); statistic.count_ = 5; - auto combined = AlignedFieldFilter::and_filter( - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::GE, - AlignedFieldFilter::Literal::int64(10)), - AlignedFieldFilter::is_not_null("a")); + auto combined = bind_field(Expression::and_filter( + Expression::compare("a", Expression::CompareOp::GE, + Expression::Literal::int64(10)), + Expression::is_not_null("a"))); EXPECT_TRUE(combined->all_match(stats, 5)); } TEST(AlignedFieldFilterTest, CollectsReferencedColumnsOnce) { - auto left = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::Literal::int32(1)); - auto right = AlignedFieldFilter::or_filter( - AlignedFieldFilter::is_null("b"), - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::GT, - AlignedFieldFilter::Literal::int32(3))); - auto root = - AlignedFieldFilter::and_filter(std::move(left), std::move(right)); + auto left = Expression::compare("a", Expression::CompareOp::EQ, + Expression::Literal::int32(1)); + auto right = Expression::or_filter( + Expression::is_null("b"), + Expression::compare("a", Expression::CompareOp::GT, + Expression::Literal::int32(3))); + auto root = Expression::and_filter(std::move(left), std::move(right)); EXPECT_EQ(root->referenced_columns(), (std::vector{"a", "b"})); } TEST(AlignedFieldFilterTest, NaNStatisticsCannotProvePageMatchesOrExclusion) { - const auto check = [](Statistic& stat, - const AlignedFieldFilter::Literal& literal) { + const auto check = [](Statistic& stat, const Expression::Literal& literal) { const std::map stats{{"v", &stat}}; - for (auto op : {AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::CompareOp::NE, - AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::CompareOp::GT, - AlignedFieldFilter::CompareOp::GE}) { - auto filter = AlignedFieldFilter::compare("v", op, literal); + for (auto op : {Expression::CompareOp::EQ, Expression::CompareOp::NE, + Expression::CompareOp::LT, Expression::CompareOp::LE, + Expression::CompareOp::GT, Expression::CompareOp::GE}) { + auto filter = + bind_field(Expression::compare("v", op, literal), literal.type); EXPECT_TRUE(filter->may_match(stats, 3)); EXPECT_FALSE(filter->all_match(stats, 3)); - auto negated = AlignedFieldFilter::not_filter( - AlignedFieldFilter::compare("v", op, literal)); + auto negated = bind_field( + Expression::not_filter(Expression::compare("v", op, literal)), + literal.type); EXPECT_TRUE(negated->may_match(stats, 3)); EXPECT_FALSE(negated->all_match(stats, 3)); } @@ -405,8 +407,8 @@ TEST(AlignedFieldFilterTest, NaNStatisticsCannotProvePageMatchesOrExclusion) { doubles.update(r, r == 1 ? std::numeric_limits::quiet_NaN() : 1.0); } - check(floats, AlignedFieldFilter::Literal::float32(1)); - check(doubles, AlignedFieldFilter::Literal::float64(1)); + check(floats, Expression::Literal::float32(1)); + check(doubles, Expression::Literal::float64(1)); } TEST(AlignedFieldFilterTest, FiniteFloatingStatisticsRetainFastPaths) { @@ -416,22 +418,23 @@ TEST(AlignedFieldFilterTest, FiniteFloatingStatisticsRetainFastPaths) { floats.update(r, 1.0f); doubles.update(r, 1.0); } - auto f = - AlignedFieldFilter::compare("v", AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::Literal::float32(1)); - auto d = - AlignedFieldFilter::compare("v", AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::Literal::float64(1)); + auto f = bind_field(Expression::compare("v", Expression::CompareOp::EQ, + Expression::Literal::float32(1)), + common::FLOAT); + auto d = bind_field(Expression::compare("v", Expression::CompareOp::EQ, + Expression::Literal::float64(1)), + common::DOUBLE); EXPECT_TRUE(f->all_match({{"v", &floats}}, 3)); EXPECT_TRUE(d->all_match({{"v", &doubles}}, 3)); auto below = - AlignedFieldFilter::compare("v", AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::Literal::float32(0)); + bind_field(Expression::compare("v", Expression::CompareOp::LT, + Expression::Literal::float32(0)), + common::FLOAT); EXPECT_FALSE(below->may_match({{"v", &floats}}, 3)); } TEST(AlignedFieldFilterTest, NegatedFloatingStatisticsPreserveSafeShortcuts) { - using A = AlignedFieldFilter; + using A = Expression; FloatStatistic floats; DoubleStatistic doubles; for (int value : {10, 15, 20}) { @@ -474,16 +477,21 @@ TEST(AlignedFieldFilterTest, NegatedFloatingStatisticsPreserveSafeShortcuts) { is_float ? A::Literal::float32(static_cast(threshold)) : A::Literal::float64(threshold); - auto filter = A::not_filter(A::compare("v", op, literal)); + auto filter = + bind_field(A::not_filter(A::compare("v", op, literal)), + (is_float ? common::FLOAT : common::DOUBLE)); EXPECT_EQ(filter->may_match(stats, 3), matches != 0); EXPECT_EQ(filter->all_match(stats, 3), matches == 3); // The same non-NULL statistics can describe a page with // another NULL row, which must never match a comparison. EXPECT_EQ(filter->may_match(stats, 4), matches != 0); EXPECT_FALSE(filter->all_match(stats, 4)); - auto original = A::compare("v", op, literal); - auto twice = - A::not_filter(A::not_filter(A::compare("v", op, literal))); + auto original = + bind_field(A::compare("v", op, literal), + (is_float ? common::FLOAT : common::DOUBLE)); + auto twice = bind_field( + A::not_filter(A::not_filter(A::compare("v", op, literal))), + (is_float ? common::FLOAT : common::DOUBLE)); EXPECT_EQ(twice->may_match(stats, 3), original->may_match(stats, 3)); EXPECT_EQ(twice->all_match(stats, 3), @@ -494,12 +502,16 @@ TEST(AlignedFieldFilterTest, NegatedFloatingStatisticsPreserveSafeShortcuts) { std::numeric_limits::quiet_NaN()) : A::Literal::float64( std::numeric_limits::quiet_NaN()); - auto filter = A::not_filter(A::compare("v", op, nan)); + auto filter = + bind_field(A::not_filter(A::compare("v", op, nan)), + (is_float ? common::FLOAT : common::DOUBLE)); EXPECT_TRUE(filter->may_match(stats, 3)); EXPECT_FALSE(filter->all_match(stats, 3)); } - auto mismatched = A::not_filter( - A::compare("v", A::CompareOp::LT, A::Literal::int32(15))); + auto mismatched = + bind_field(A::not_filter(A::compare("v", A::CompareOp::LT, + A::Literal::int32(15))), + common::INT32); EXPECT_TRUE(mismatched->may_match(stats, 3)); EXPECT_FALSE(mismatched->all_match(stats, 3)); } diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index f5d8fc1de..de930917f 100644 --- a/cpp/test/reader/filter/tag_filter_test.cc +++ b/cpp/test/reader/filter/tag_filter_test.cc @@ -494,22 +494,14 @@ TEST_F(TagFilterTest, LogicalOperatorsUseSegmentOverloadForChildren) { TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { using Field = AlignedFieldFilter; - using Kind = BoundPredicate::Kind; auto predicate = E::not_filter(E::compare("name", Op::EQ, Literal::string("x"))); auto tag = bind(predicate); ASSERT_NE(nullptr, tag); Field::Ptr field; - ASSERT_EQ(common::E_OK, Field::from_expression(*predicate, field, true)); - - for (const BoundPredicate* expr : - {static_cast(tag.get()), - static_cast(field.get())}) { - EXPECT_EQ(Kind::NOT, expr->kind()); - ASSERT_NE(nullptr, expr->left()); - EXPECT_EQ(Kind::COMPARISON, expr->left()->kind()); - EXPECT_EQ(BoundPredicate::CompareOp::EQ, expr->left()->compare_op()); - } + TableSchema fields("t", {{"name", common::STRING, common::UNCOMPRESSED, + common::PLAIN, common::ColumnCategory::FIELD}}); + ASSERT_EQ(common::E_OK, Field::bind(*predicate, fields, field)); EXPECT_TRUE(tag->satisfyRow(0, {})); EXPECT_TRUE(tag->satisfyRow(0, {nullptr, nullptr})); diff --git a/cpp/test/reader/table_field_filter_test.cc b/cpp/test/reader/table_field_filter_test.cc index ffe4acdd9..65b0915a2 100644 --- a/cpp/test/reader/table_field_filter_test.cc +++ b/cpp/test/reader/table_field_filter_test.cc @@ -266,11 +266,22 @@ class TableFieldFilterTest g_config_value_ = saved_; libtsfile_destroy(); } + std::vector scan_field(const std::vector& columns, + Expression::Ptr expr, int offset = 0, + int limit = -1, Filter* time = nullptr) { + LocalRandomAccessReadFile file; + EXPECT_EQ(file.open(filename_), E_OK); + TableQueryExecutor executor(&file, std::get<1>(GetParam())); + ResultSet* result = nullptr; + EXPECT_EQ(executor.query("t", columns, time, offset, limit, result, + nullptr, expr.get()), + E_OK); + return read_times(executor, result, E_OK); + } std::vector scan(const std::vector& columns, Filter* filter, int offset = 0, int limit = -1, Filter* time = nullptr, Filter* tag = nullptr, int expected_error = E_OK) { - std::vector times; LocalRandomAccessReadFile file; EXPECT_EQ(file.open(filename_), E_OK); TableQueryExecutor executor(&file, std::get<1>(GetParam())); @@ -278,6 +289,12 @@ class TableFieldFilterTest EXPECT_EQ(executor.query("t", columns, time, tag, filter, offset, limit, result), E_OK); + return read_times(executor, result, expected_error); + } + + std::vector read_times(TableQueryExecutor& executor, + ResultSet* result, int expected_error) { + std::vector times; if (!result) return times; bool next = false; int ret = E_OK; @@ -342,7 +359,7 @@ TEST_P(TableFieldFilterTest, ReuseNamedExpressionForTableAndTree) { path.measurement_ = "v"; path.full_path_ = path.device_id_->get_device_name() + ".v"; ASSERT_EQ(E_OK, reader.query({path}, *field, tree)); - EXPECT_EQ(common::DOUBLE, field->operand()->literal.type); + EXPECT_EQ(common::DOUBLE, field->operand_->literal.type); tag.reset(); field.reset(); for (auto* result : {table, tree}) { @@ -392,7 +409,9 @@ TEST_P(TableFieldFilterTest, BindTagAgainstQuerySchemaAndRejectWrongCategory) { {"id", STRING, ColumnCategory::TAG}}); std::unique_ptr bound; ASSERT_EQ(E_OK, TagFilter::bind(*tag, schema, bound)); - EXPECT_EQ(2, bound->col_idx_); + std::string d0 = "d0", d1 = "d1"; + EXPECT_TRUE(bound->satisfyRow(0, {nullptr, &d0, &d1})); + EXPECT_FALSE(bound->satisfyRow(0, {nullptr, &d1, &d0})); ResultSet* rows = nullptr; ASSERT_EQ(E_OK, reader.queryByRow("t", {"v"}, 0, 1, rows, tag.get(), nullptr)); @@ -413,17 +432,15 @@ TEST_P(TableFieldFilterTest, BindTagAgainstQuerySchemaAndRejectWrongCategory) { } TEST_P(TableFieldFilterTest, AlignedBatchFilterAndOrUsesFilterOnlyColumns) { - auto left = AlignedFieldFilter::and_filter( - AlignedFieldFilter::compare("i", AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::Literal::int32(-4)), - AlignedFieldFilter::compare( - "flag", AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::Literal::boolean(true))); - auto right = AlignedFieldFilter::is_not_null("tail_null"); - auto filter = - AlignedFieldFilter::or_filter(std::move(left), std::move(right)); - - EXPECT_EQ(scan({"v"}, filter.release()), expected([](int t) { + auto left = Expression::and_filter( + Expression::compare("i", Expression::CompareOp::LE, + Expression::Literal::int32(-4)), + Expression::compare("flag", Expression::CompareOp::EQ, + Expression::Literal::boolean(true))); + auto right = Expression::is_not_null("tail_null"); + auto filter = Expression::or_filter(std::move(left), std::move(right)); + + EXPECT_EQ(scan_field({"v"}, std::move(filter)), expected([](int t) { const bool and_branch = t % 3 != 0 && t >= 4 && (t % 2 == 1); const bool or_branch = t % 3 == 0; return and_branch || or_branch; @@ -431,77 +448,70 @@ TEST_P(TableFieldFilterTest, AlignedBatchFilterAndOrUsesFilterOnlyColumns) { } TEST_P(TableFieldFilterTest, AlignedBatchFilterSupportsNotAndChunkNulls) { - auto filter = AlignedFieldFilter::not_filter( - AlignedFieldFilter::is_null("chunk_null")); - EXPECT_EQ(scan({"v"}, filter.release()), + auto filter = Expression::not_filter(Expression::is_null("chunk_null")); + EXPECT_EQ(scan_field({"v"}, std::move(filter)), expected([](int t) { return t < 7; })); } TEST_P(TableFieldFilterTest, AlignedBatchFilterNotComparisonExcludesNulls) { // NOT over a nullable comparison must exclude NULL rows (SQL three-valued // logic): NOT(i <= -5) == i > -5, and NULL > -5 is still NULL, not TRUE. - auto filter = AlignedFieldFilter::not_filter( - AlignedFieldFilter::compare("i", AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::Literal::int32(-5))); - EXPECT_EQ(scan({"v"}, filter.release()), + auto filter = Expression::not_filter(Expression::compare( + "i", Expression::CompareOp::LE, Expression::Literal::int32(-5))); + EXPECT_EQ(scan_field({"v"}, std::move(filter)), expected([](int t) { return t % 3 != 0 && t < 5; })); } TEST_P(TableFieldFilterTest, AlignedBatchFilterAppliesOffsetAfterMask) { for (int offset : {0, 1, 3, 8}) { for (int limit : {0, 1, 4, -1}) { - auto filter = AlignedFieldFilter::compare( - "i", AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::Literal::int32(-5)); + auto filter = Expression::compare("i", Expression::CompareOp::LE, + Expression::Literal::int32(-5)); auto all = expected([](int t) { return t % 3 != 0 && t >= 5; }); auto begin = all.begin() + std::min(offset, all.size()); auto end = limit < 0 ? all.end() : begin + std::min(limit, all.end() - begin); std::vector wanted(begin, end); - EXPECT_EQ( - scan({"v"}, filter.release(), offset, limit, nullptr, nullptr), - wanted); + EXPECT_EQ(scan_field({"v"}, std::move(filter), offset, limit), + wanted); } } } TEST_P(TableFieldFilterTest, AlignedBatchFilterSharedProjectionColumn) { - auto filter = - AlignedFieldFilter::compare("i", AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::Literal::int32(-5)); - EXPECT_EQ(scan({"i"}, filter.release()), + auto filter = Expression::compare("i", Expression::CompareOp::LE, + Expression::Literal::int32(-5)); + EXPECT_EQ(scan_field({"i"}, std::move(filter)), expected([](int t) { return t % 3 != 0 && t >= 5; })); } TEST_P(TableFieldFilterTest, AlignedBatchFilterAllMatchFastPath) { - auto filter = - AlignedFieldFilter::compare("v", AlignedFieldFilter::CompareOp::GE, - AlignedFieldFilter::Literal::int64(0)); - EXPECT_EQ(scan({"v"}, filter.release()), + auto filter = Expression::compare("v", Expression::CompareOp::GE, + Expression::Literal::int64(0)); + EXPECT_EQ(scan_field({"v"}, std::move(filter)), expected([](int) { return true; })); } TEST_P(TableFieldFilterTest, AlignedBatchFilterAllNullFilterOnlyColumn) { - auto filter = AlignedFieldFilter::is_null("empty"); - EXPECT_EQ(scan({"v"}, filter.release()), + auto filter = Expression::is_null("empty"); + EXPECT_EQ(scan_field({"v"}, std::move(filter)), expected([](int) { return true; })); } TEST_P(TableFieldFilterTest, AlignedBatchFilterCombinesTimeAndFieldMask) { - auto filter = - AlignedFieldFilter::compare("i", AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::Literal::int32(-5)); - EXPECT_EQ(scan({"v"}, filter.release(), 0, -1, - TimeFilter::between(base_ + 7, base_ + 10, false)), + auto filter = Expression::compare("i", Expression::CompareOp::LE, + Expression::Literal::int32(-5)); + EXPECT_EQ(scan_field({"v"}, std::move(filter), 0, -1, + TimeFilter::between(base_ + 7, base_ + 10, false)), expected([](int t) { return t >= 7 && t <= 10 && t % 3 != 0; })); } TEST_P(TableFieldFilterTest, AlignedBatchFilterSupportsStringLiterals) { - auto filter = AlignedFieldFilter::compare( - "s", AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::Literal::string(std::string("a\0b", 3))); - EXPECT_EQ(scan({"v"}, filter.release()), + auto filter = Expression::compare( + "s", Expression::CompareOp::EQ, + Expression::Literal::string(std::string("a\0b", 3))); + EXPECT_EQ(scan_field({"v"}, std::move(filter)), expected([](int t) { return t % 2 == 1; })); } diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 0893efcb2..7ecafc829 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -72,7 +72,9 @@ exposes LIKE, while current C++/Python expose explicit null predicates. ## C++ table and tree predicates Build named conditions with `storage::Expression` from `reader/expression.h`. -A comparison retains its reference, operator and typed literal. Queries bind +Use the same factories for TAGs, FIELDs and tree measurements. For example, +use `Expression::compare` for a FIELD comparison. A comparison retains its +reference, operator and typed literal. Queries bind their own copy, so an expression can be used against multiple schemas and released once the query returns. From 4f1251b6dab8ff3a623c016e77b266bbdcf17f9f Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 10:03:47 +0800 Subject: [PATCH 08/10] Use the floating-point isnan overload for page pruning --- cpp/src/reader/filter/aligned_field_filter.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index 1c05be18e..b96009281 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -105,7 +105,8 @@ bool page_comparison(const S& stat, const Expression& leaf, bool negated, leaf, negated, [&](Op op, const Literal& literal, bool invert) { if (literal.type != type) return !all; const T value = literal.*member; - if (invert && op != Op::EQ && op != Op::NE && std::isnan(value)) + if (invert && op != Op::EQ && op != Op::NE && + std::isnan(static_cast(value))) return !all; return range_matches(stat.min_value_, stat.max_value_, value, invert ? negate_comparison(op) : op, all, From 35cffd62308926a72c246b996d7f2fe35995240a Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 10:49:56 +0800 Subject: [PATCH 09/10] Terminate on allocation failure when composing C TAG filters --- cpp/src/cwrapper/tsfile_cwrapper.cc | 12 +++--------- cpp/src/cwrapper/tsfile_cwrapper.h | 14 ++++++++------ skills/tsfile/references/properties-filters.md | 6 +++++- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 65db26edb..ece48bbc6 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -147,15 +147,9 @@ storage::Expression::Ptr tag_expression(const char* column, const char* value, TagFilterHandle combine_tag_filters(storage::ExpressionType op, TagFilterHandle left, - TagFilterHandle right) { - try { - // The C caller retains both operands if allocating the parent fails. - return new storage::Expression( - op, static_cast(left), - static_cast(right)); - } catch (...) { - return nullptr; - } + TagFilterHandle right) noexcept { + return new storage::Expression(op, static_cast(left), + static_cast(right)); } } // namespace diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index ae84338a3..a3eee1cb1 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -1338,22 +1338,24 @@ TagFilterHandle tsfile_tag_filter_gteq(TsFileReader reader, const char* value); /** - * @brief Logical AND of two tag filters. Takes ownership of left and right - * only on success. Returns NULL on failure; the caller still owns the inputs. + * @brief Logical AND of two tag filters. The result owns both inputs. + * Returns NULL for a NULL input or identical handles. In that case the caller + * retains ownership. Allocation failure terminates the process. */ TagFilterHandle tsfile_tag_filter_and(TagFilterHandle left, TagFilterHandle right); /** - * @brief Logical OR of two tag filters. Takes ownership of left and right - * only on success. Returns NULL on failure; the caller still owns the inputs. + * @brief Logical OR of two tag filters. The result owns both inputs. + * Returns NULL for a NULL input or identical handles. In that case the caller + * retains ownership. Allocation failure terminates the process. */ TagFilterHandle tsfile_tag_filter_or(TagFilterHandle left, TagFilterHandle right); /** - * @brief Logical NOT of a tag filter. Takes ownership of filter only on - * success. Returns NULL on failure; the caller still owns the input. + * @brief Logical NOT of a tag filter. The result owns the input. + * A NULL input returns NULL. Allocation failure terminates the process. */ TagFilterHandle tsfile_tag_filter_not(TagFilterHandle filter); diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 7ecafc829..600bf67ca 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -64,7 +64,11 @@ Pass them to the table query alongside the time range or row window. with a schema to obtain an executable filter. - C wrapper: construct `TagFilterHandle` values with the declared factory and composition functions, pass them to the tag-filter query entry point, and - release them with `tsfile_tag_filter_free`. + release them with `tsfile_tag_filter_free`. A successful AND, OR or NOT + owns its operands. Passing a null operand or passing the same handle twice + to a binary operator returns `NULL` and leaves ownership with the caller. + Memory exhaustion while constructing the compound filter terminates the + calling process, including when invoked through Python or Go. Do not translate operator names mechanically across bindings: Java additionally exposes LIKE, while current C++/Python expose explicit null predicates. From 13de553d87eaa13d3c8321a1a2801f4a7a3d560d Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 11:13:59 +0800 Subject: [PATCH 10/10] Pass a single device filter into table scans --- cpp/src/reader/table_query_executor.cc | 88 +++++++++++++------ cpp/src/reader/table_query_executor.h | 5 +- cpp/src/reader/task/device_task_iterator.h | 18 ++-- .../tsfile/references/properties-filters.md | 5 +- 4 files changed, 75 insertions(+), 41 deletions(-) diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 886dd6651..a3513a979 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -23,6 +23,47 @@ #include "utils/db_utils.h" namespace storage { +namespace { + +int bind_field(const Expression& expression, TableSchema& schema, + ColumnMapping& columns, std::unique_ptr& result) { + AlignedFieldFilter::Ptr bound; + const int ret = AlignedFieldFilter::bind(expression, schema, bound); + if (ret != common::E_OK) return ret; + columns.add(bound->expression()); + result = std::move(bound); + return common::E_OK; +} + +int prepare_filters(const Expression* tag, const Expression* field, + TableSchema& schema, ColumnMapping& columns, + std::shared_ptr& device_filter, + std::unique_ptr& value_filter) { + if (tag) { + std::unique_ptr filter; + const int ret = TagFilter::bind(*tag, schema, filter); + if (ret != common::E_OK) return ret; + device_filter = std::move(filter); + } + return field ? bind_field(*field, schema, columns, value_filter) + : common::E_OK; +} + +int prepare_filters(Filter* tag, std::unique_ptr field, + TableSchema& schema, ColumnMapping& columns, + std::shared_ptr& device_filter, + std::unique_ptr& value_filter) { + // The indexed API borrows the caller's TAG for the lifetime of the scan. + device_filter = + std::shared_ptr(std::shared_ptr(), tag); + if (auto* aligned = dynamic_cast(field.get())) + return bind_field(aligned->expression(), schema, columns, value_filter); + value_filter = std::move(field); + return common::E_OK; +} + +} // namespace + int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, Filter* time_filter, Filter* tag_filter, @@ -37,7 +78,8 @@ int TableQueryExecutor::query(const std::string& table_name, Filter* field_filter, int offset, int limit, ResultSet*& ret_qds) { return query_impl(table_name, columns, time_filter, tag_filter, - field_filter, nullptr, nullptr, offset, limit, ret_qds); + std::unique_ptr(field_filter), offset, limit, + ret_qds); } int TableQueryExecutor::query(const std::string& table_name, @@ -45,18 +87,17 @@ int TableQueryExecutor::query(const std::string& table_name, Filter* time_filter, int offset, int limit, ResultSet*& ret_qds, const Expression* tag_filter, const Expression* field_filter) { - return query_impl(table_name, columns, time_filter, nullptr, nullptr, - tag_filter, field_filter, offset, limit, ret_qds); + return query_impl(table_name, columns, time_filter, tag_filter, + field_filter, offset, limit, ret_qds); } +template int TableQueryExecutor::query_impl(const std::string& table_name, const std::vector& columns, - Filter* time_filter, Filter* tag_filter, - Filter* field_filter, - const Expression* tag_expression, - const Expression* field_expression, - int offset, int limit, ResultSet*& ret_qds) { - std::unique_ptr owned_time(time_filter), owned_field(field_filter); + Filter* time_filter, Tag tag_filter, + Field field_filter, int offset, int limit, + ResultSet*& ret_qds) { + std::unique_ptr owned_time(time_filter); int ret = common::E_OK; TsFileMeta* file_metadata = nullptr; ret_qds = nullptr; @@ -88,25 +129,16 @@ int TableQueryExecutor::query_impl(const std::string& table_name, } data_types.push_back(table_schema->get_data_types()[ind]); } - std::unique_ptr bound_tag; - if (tag_expression) { - ret = TagFilter::bind(*tag_expression, *table_schema, bound_tag); - if (ret != common::E_OK) return ret; - } - if (auto* filter = dynamic_cast(owned_field.get())) - field_expression = &filter->expression(); - if (field_expression) { - AlignedFieldFilter::Ptr bound; - ret = AlignedFieldFilter::bind(*field_expression, *table_schema, bound); - if (ret != common::E_OK) return ret; - column_mapping->add(bound->expression()); - owned_field = std::move(bound); - } + std::shared_ptr device_filter; + std::unique_ptr value_filter; + ret = prepare_filters(tag_filter, std::move(field_filter), *table_schema, + *column_mapping, device_filter, value_filter); + if (ret != common::E_OK) return ret; - auto device_task_iterator = std::unique_ptr( - new DeviceTaskIterator(lower_case_column_names, table_root, - column_mapping, meta_data_querier_, tag_filter, - table_schema, std::move(bound_tag))); + auto device_task_iterator = + std::unique_ptr(new DeviceTaskIterator( + lower_case_column_names, table_root, column_mapping, + meta_data_querier_, std::move(device_filter), table_schema)); std::unique_ptr tsblock_reader; switch (table_query_ordering_) { @@ -115,7 +147,7 @@ int TableQueryExecutor::query_impl(const std::string& table_name, new DeviceOrderedTsBlockReader( std::move(device_task_iterator), meta_data_querier_, block_size_, tsfile_io_reader_, owned_time.release(), - owned_field.release(), offset, limit)); + value_filter.release(), offset, limit)); break; case TableQueryOrdering::TIME: default: diff --git a/cpp/src/reader/table_query_executor.h b/cpp/src/reader/table_query_executor.h index fea6b1d3e..4b45fbf8d 100644 --- a/cpp/src/reader/table_query_executor.h +++ b/cpp/src/reader/table_query_executor.h @@ -95,11 +95,10 @@ class TableQueryExecutor { void destroy_query_data_set(ResultSet* qds); private: + template int query_impl(const std::string& table_name, const std::vector& columns, Filter* time_filter, - Filter* tag_filter, Filter* field_filter, - const Expression* tag_expression, - const Expression* field_expression, int offset, int limit, + Tag tag_filter, Field field_filter, int offset, int limit, ResultSet*& result); IMetadataQuerier* meta_data_querier_; TsFileIOReader* tsfile_io_reader_; diff --git a/cpp/src/reader/task/device_task_iterator.h b/cpp/src/reader/task/device_task_iterator.h index 4afc27393..cdefb09ef 100644 --- a/cpp/src/reader/task/device_task_iterator.h +++ b/cpp/src/reader/task/device_task_iterator.h @@ -34,14 +34,13 @@ class DeviceTaskIterator { MetaIndexNode* index_root, std::shared_ptr column_mapping, IMetadataQuerier* metadata_querier, - const Filter* id_filter, - std::shared_ptr table_schema, - std::unique_ptr bound_tag = nullptr) + std::shared_ptr id_filter, + std::shared_ptr table_schema) : column_names_(column_names), column_mapping_(column_mapping), - bound_tag_(std::move(bound_tag)), - device_meta_iterator_(metadata_querier->device_iterator( - index_root, bound_tag_ ? bound_tag_.get() : id_filter)), + id_filter_(std::move(id_filter)), + device_meta_iterator_( + metadata_querier->device_iterator(index_root, id_filter_.get())), table_schema_(table_schema) { pa_.init(512, common::MOD_DEVICE_TASK_ITER); } @@ -50,12 +49,13 @@ class DeviceTaskIterator { std::vector index_roots, std::shared_ptr column_mapping, IMetadataQuerier* metadata_querier, - const Filter* id_filter, + std::shared_ptr id_filter, std::shared_ptr table_schema) : column_names_(column_names), column_mapping_(column_mapping), + id_filter_(std::move(id_filter)), device_meta_iterator_( - metadata_querier->device_iterator(index_roots, id_filter)), + metadata_querier->device_iterator(index_roots, id_filter_.get())), table_schema_(table_schema) { pa_.init(512, common::MOD_DEVICE_TASK_ITER); } @@ -81,7 +81,7 @@ class DeviceTaskIterator { private: std::vector column_names_; std::shared_ptr column_mapping_; - std::unique_ptr bound_tag_; + std::shared_ptr id_filter_; std::unique_ptr device_meta_iterator_; std::shared_ptr table_schema_; common::PageArena pa_; diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 600bf67ca..ab445246f 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -92,7 +92,10 @@ int ret = reader.queryByRow("weather", {"temperature"}, 0, 100, // Consume rows and call reader.destroy_query_data_set(rows) after success. ``` -Pass `nullptr` for either `tag_filter` or `field_filter` to omit that condition. +The two-filter C++ overloads of `query` and `queryByRow` take +`const Expression*` for both `tag_filter` and `field_filter`. +Pass `nullptr` for either to omit that condition. The older TAG-only overloads +take a borrowed `Filter*`. The caller must keep it alive while reading the result. Time bounds restrict the timestamps scanned. Offset and limit count rows that pass the filters. TAG references bind to device-ID segments. FIELD references bind to column types and support page pruning. TAG regular expressions operate