From 1e3540624821e755b3a8f704749dd8dcf213d044 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 12:16:36 +0800 Subject: [PATCH 1/4] Bind named TAG and FIELD expressions when preparing table queries --- .github/workflows/native-packages.yml | 10 +- .github/workflows/unit-test-go.yml | 4 +- .github/workflows/wheels.yml | 2 +- cpp/CMakeLists.txt | 7 +- cpp/examples/cpp_examples/demo_read.cpp | 21 +- cpp/src/CMakeLists.txt | 17 +- cpp/src/common/db_common.h | 4 + cpp/src/cwrapper/tsfile_cwrapper.cc | 151 ++- cpp/src/reader/aligned_chunk_reader.cc | 25 +- cpp/src/reader/aligned_chunk_reader.h | 4 +- .../block/device_ordered_tsblock_reader.cc | 13 +- .../block/device_ordered_tsblock_reader.h | 7 +- .../block/single_device_tsblock_reader.cc | 97 +- .../block/single_device_tsblock_reader.h | 13 +- cpp/src/reader/column_mapping.h | 15 +- cpp/src/reader/device_meta_iterator.cc | 35 +- cpp/src/reader/device_meta_iterator.h | 12 +- cpp/src/reader/expression.cc | 112 ++ cpp/src/reader/expression.h | 80 +- cpp/src/reader/filter/aligned_field_filter.cc | 1076 ++++------------- cpp/src/reader/filter/aligned_field_filter.h | 104 +- cpp/src/reader/filter/bind_expression.cc | 203 ++++ cpp/src/reader/filter/bind_expression.h | 58 + cpp/src/reader/filter/table_field_filter.cc | 61 - cpp/src/reader/filter/table_field_filter.h | 90 -- cpp/src/reader/filter/tag_filter.cc | 394 ++---- cpp/src/reader/filter/tag_filter.h | 196 +-- cpp/src/reader/imeta_data_querier.h | 4 +- cpp/src/reader/meta_data_querier.cc | 4 +- cpp/src/reader/meta_data_querier.h | 4 +- cpp/src/reader/table_query_executor.cc | 132 +- cpp/src/reader/table_query_executor.h | 19 +- cpp/src/reader/task/device_task_iterator.h | 11 +- cpp/src/reader/tsfile_reader.cc | 106 +- cpp/src/reader/tsfile_reader.h | 37 +- cpp/src/reader/tsfile_series_scan_iterator.cc | 43 +- cpp/src/reader/tsfile_series_scan_iterator.h | 5 +- cpp/src/utils/util_define.h | 2 +- cpp/test/CMakeLists.txt | 4 +- cpp/test/cwrapper/cwrapper_extended_test.cc | 6 +- .../reader/aligned_chunk_reader_bulk_test.cc | 42 +- .../aligned_field_filter_regression_test.cc | 61 +- .../aligned_wide_table_small_block_test.cc | 3 +- .../reader/block/masked_bulk_copy_test.cc | 5 +- cpp/test/reader/chunk_reader_resource_test.cc | 9 +- .../filter/aligned_field_filter_test.cc | 266 ++-- cpp/test/reader/filter/tag_filter_test.cc | 330 ++--- cpp/test/reader/table_field_filter_test.cc | 585 +++------ cpp/test/reader/table_read_failure_test.cc | 21 +- .../table_view/tsfile_reader_table_test.cc | 95 +- cpp/test/tools/model_format_e2e_test.cc | 2 + cpp/tools/commands/commands.h | 6 - cpp/tools/commands/row_query.cc | 69 +- packaging/README.md | 4 +- packaging/scripts/check_python_wheel.py | 2 +- packaging/tests/go_installed_tests.py | 4 +- packaging/tests/test_python_wheel_contents.py | 7 +- packaging/tests/test_sdk_build_config.py | 10 +- python/_build_support.py | 9 +- python/pyproject.toml | 4 +- python/setup.py | 42 +- python/tsfile/__init__.py | 25 +- .../tsfile/references/properties-filters.md | 35 +- 63 files changed, 1916 insertions(+), 2908 deletions(-) create mode 100644 cpp/src/reader/filter/bind_expression.cc create mode 100644 cpp/src/reader/filter/bind_expression.h delete mode 100644 cpp/src/reader/filter/table_field_filter.cc delete mode 100644 cpp/src/reader/filter/table_field_filter.h diff --git a/.github/workflows/native-packages.yml b/.github/workflows/native-packages.yml index 127f943783..971d015cc5 100644 --- a/.github/workflows/native-packages.yml +++ b/.github/workflows/native-packages.yml @@ -1021,7 +1021,7 @@ jobs: cmake --install cpp/target/build --config Release --prefix $sdkRoot $requiredPaths = @( "$sdkRoot/bin/tsfile-cli.exe" - "$sdkRoot/bin/tsfile.dll" + "$sdkRoot/bin/tsfile-2.dll" "$sdkRoot/lib/tsfile.lib" "$sdkRoot/include/tsfile/cwrapper/tsfile_cwrapper.h" "$sdkRoot/lib/cmake/TsFile/TsFileConfig.cmake" @@ -1078,7 +1078,7 @@ jobs: }) $requiredSuffixes = @( 'bin/tsfile-cli.exe' - 'bin/tsfile.dll' + 'bin/tsfile-2.dll' 'lib/tsfile.lib' 'include/tsfile/cwrapper/tsfile_cwrapper.h' ) @@ -1194,7 +1194,7 @@ jobs: cmake --install cpp/target/build --config Release --prefix $sdkRoot $requiredPaths = @( "$sdkRoot/bin/tsfile-cli.exe" - "$sdkRoot/bin/tsfile.dll" + "$sdkRoot/bin/tsfile-2.dll" "$sdkRoot/lib/tsfile.lib" "$sdkRoot/include/tsfile/cwrapper/tsfile_cwrapper.h" "$sdkRoot/lib/cmake/TsFile/TsFileConfig.cmake" @@ -1245,7 +1245,7 @@ jobs: $entryPaths = @($archive.Entries | ForEach-Object { $_.FullName.Replace('\', '/') }) foreach ($suffix in @( 'bin/tsfile-cli.exe' - 'bin/tsfile.dll' + 'bin/tsfile-2.dll' 'lib/tsfile.lib' 'include/tsfile/cwrapper/tsfile_cwrapper.h' )) { @@ -1407,7 +1407,7 @@ jobs: # setup.py consumes libraries from lib/; the installed SDK stores DLLs in bin/. Copy-Item "$sdkRoot/bin/*.dll" "$sdkRoot/lib/" if (-not (Test-Path "$sdkRoot/lib/tsfile.lib")) { throw 'Missing MSVC import library' } - if (-not (Test-Path "$sdkRoot/lib/tsfile.dll")) { throw 'Missing TsFile DLL' } + if (-not (Test-Path "$sdkRoot/lib/tsfile-2.dll")) { throw 'Missing TsFile DLL' } "TSFILE_CPP_BUILD=$sdkRoot" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - name: Install wheel build tools diff --git a/.github/workflows/unit-test-go.yml b/.github/workflows/unit-test-go.yml index 0d5c10be0f..ad75a0e154 100644 --- a/.github/workflows/unit-test-go.yml +++ b/.github/workflows/unit-test-go.yml @@ -112,8 +112,8 @@ jobs: shell: pwsh run: | $nativeLib = Join-Path $env:GITHUB_WORKSPACE "cpp\target\build\lib" - $dll = Get-ChildItem -Path $nativeLib -Filter "tsfile.dll" -Recurse -ErrorAction SilentlyContinue + $dll = Get-ChildItem -Path $nativeLib -Filter "tsfile-2.dll" -Recurse -ErrorAction SilentlyContinue $importLib = Get-ChildItem -Path $nativeLib -Filter "tsfile.lib" -Recurse -ErrorAction SilentlyContinue - if (-not $dll) { throw "MSVC tsfile.dll was not produced under $nativeLib" } + if (-not $dll) { throw "MSVC tsfile-2.dll was not produced under $nativeLib" } if (-not $importLib) { throw "MSVC tsfile.lib import library was not produced under $nativeLib" } Write-Host "Verified MSVC outputs: $($dll.FullName) and $($importLib.FullName)" diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 124e9cb85e..c413799d82 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -113,7 +113,7 @@ jobs: # setup.py consumes DLLs and import libraries together under lib/. Copy-Item "$sdkRoot/bin/*.dll" "$sdkRoot/lib/" if (-not (Test-Path "$sdkRoot/lib/tsfile.lib")) { throw 'Missing MSVC import library' } - if (-not (Test-Path "$sdkRoot/lib/tsfile.dll")) { throw 'Missing TsFile DLL' } + if (-not (Test-Path "$sdkRoot/lib/tsfile-2.dll")) { throw 'Missing TsFile DLL' } - name: Install wheel build tools run: python -m pip install cibuildwheel==3.4.1 diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index dae05ae386..8ac0969716 100755 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -70,11 +70,8 @@ set(TSFILE_RPM_PACKAGE_VERSION "${TSFILE_PACKAGE_VERSION}" CACHE STRING "RPM Version value") set(TSFILE_RPM_PACKAGE_RELEASE "1" CACHE STRING "RPM Release value") -set(TSFILE_ABI_VERSION "1" CACHE STRING - "TsFile shared-library ABI epoch (changes only on ABI breaks)") -if (NOT TSFILE_ABI_VERSION MATCHES "^[0-9]+$") - message(FATAL_ERROR "TSFILE_ABI_VERSION must be a positive integer") -endif () +# Bump when installed C++ interfaces break binary compatibility. +set(TSFILE_ABI_VERSION 2) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/DependencySource.cmake) if (TSFILE_MSVC_STATIC_RUNTIME AND diff --git a/cpp/examples/cpp_examples/demo_read.cpp b/cpp/examples/cpp_examples/demo_read.cpp index 90e24c6762..b851d1b037 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/CMakeLists.txt b/cpp/src/CMakeLists.txt index b62cf7b58c..70a9bac7eb 100644 --- a/cpp/src/CMakeLists.txt +++ b/cpp/src/CMakeLists.txt @@ -172,12 +172,17 @@ set_property(DIRECTORY PROPERTY LINK_LIBRARIES unset(_TSFILE_SRC_LINK_LIBRARIES) if (TSFILE_BUILD_SHARED) - # Keep development suffixes out of the install name and SONAME. The ABI - # epoch changes only for incompatible binary interface changes. - set(LIBTSFILE_PROJECT_VERSION ${TSFILE_PACKAGE_VERSION}) - set(LIBTSFILE_SO_VERSION ${TSFILE_ABI_VERSION}) - set_target_properties(tsfile PROPERTIES VERSION ${LIBTSFILE_PROJECT_VERSION}) - set_target_properties(tsfile PROPERTIES SOVERSION ${LIBTSFILE_SO_VERSION}) + # Keep each ABI in its own real file even when two SDK builds share a + # project version. An existing SONAME must never point at a different ABI. + set_target_properties(tsfile PROPERTIES SOVERSION ${TSFILE_ABI_VERSION}) + if (APPLE) + set_target_properties(tsfile PROPERTIES MACHO_CURRENT_VERSION ${TSFILE_PACKAGE_VERSION}) + endif() + if (WIN32) + # PE imports identify the runtime by filename. Keep the import library + # name stable for consumers linking with -ltsfile or TsFile::tsfile. + set_target_properties(tsfile PROPERTIES RUNTIME_OUTPUT_NAME "tsfile-${TSFILE_ABI_VERSION}") + endif() endif() add_library(TsFile::tsfile ALIAS tsfile) diff --git a/cpp/src/common/db_common.h b/cpp/src/common/db_common.h index c2b394e00f..a705ba2279 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/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index c2e6f2a0d6..d93adef9ad 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -43,7 +43,6 @@ #include "common/statistic.h" #include "common/tablet.h" #include "common/tsfile_common.h" -#include "reader/filter/tag_filter.h" #include "reader/result_set.h" #include "reader/table_result_set.h" #include "reader/tsfile_reader.h" @@ -109,6 +108,50 @@ 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) noexcept { + return new (std::nothrow) + storage::Expression(op, static_cast(left), + static_cast(right)); +} + } // namespace #ifdef __cplusplus @@ -699,10 +742,10 @@ 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); + *err_code = r->prepare_table_series( + table_name, column_name, + static_cast(tag_filter), prepared); if (*err_code != common::E_OK) { return nullptr; } @@ -947,7 +990,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 +1023,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 +1048,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 +2882,11 @@ ERRNO tsfile_tag_filter_create_checked(TsFileReader reader, if (ret != common::E_OK) { return ret; } - storage::TagFilterBuilder builder(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 +2932,12 @@ ERRNO tsfile_tag_filter_between_checked(TsFileReader reader, if (ret != common::E_OK) { return ret; } - storage::TagFilterBuilder builder(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 +2965,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 +2996,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/aligned_chunk_reader.cc b/cpp/src/reader/aligned_chunk_reader.cc index c67c27ff19..a8fc540092 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" @@ -1241,7 +1242,8 @@ int AlignedChunkReader::get_next_page(TsBlock* ret_tsblock, // ══════════════════════════════════════════════════════════════════════════ int AlignedChunkReader::load_by_aligned_meta_multi( - ChunkMeta* time_chunk_meta, const std::vector& value_metas) { + ChunkMeta* time_chunk_meta, const std::vector& value_metas, + bool field_all_match) { int ret = E_OK; multi_value_mode_ = true; time_chunk_meta_ = time_chunk_meta; @@ -1253,6 +1255,8 @@ int AlignedChunkReader::load_by_aligned_meta_multi( page_time_count_ = 0; page_time_cursor_ = 0; + chunk_field_all_match_ = field_all_match; + // ── Load time chunk header ── file_data_time_buf_size_ = 1024; int32_t ret_read_len = 0; @@ -1592,13 +1596,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 @@ -1654,8 +1651,8 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { } bool field_page_skip = false; - bool field_all_match = false; - if (field_filter_ != nullptr) { + bool field_all_match = chunk_field_all_match_; + if (field_filter_ && !field_all_match) { std::map field_statistics; for (uint32_t c = 0; c < num_cols; ++c) { auto* col = value_columns_[c]; @@ -1667,11 +1664,11 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { cur_time_page_header_.statistic_ != nullptr ? cur_time_page_header_.statistic_->count_ : 0; + const auto match = + field_filter_->classify(field_statistics, row_count); field_page_skip = - !field_filter_->may_match(field_statistics, row_count); - field_all_match = - !field_page_skip && - field_filter_->all_match(field_statistics, row_count); + match == AlignedFieldFilter::StatisticsMatch::None; + field_all_match = match == AlignedFieldFilter::StatisticsMatch::All; } Statistic* stat = cur_time_page_header_.statistic_; diff --git a/cpp/src/reader/aligned_chunk_reader.h b/cpp/src/reader/aligned_chunk_reader.h index 310ee98ac4..74076af675 100644 --- a/cpp/src/reader/aligned_chunk_reader.h +++ b/cpp/src/reader/aligned_chunk_reader.h @@ -166,7 +166,8 @@ class AlignedChunkReader : public IChunkReader { // Multi-value: load one time chunk + N value chunks. int load_by_aligned_meta_multi(ChunkMeta* time_meta, - const std::vector& value_metas); + const std::vector& value_metas, + bool field_all_match = false); // In multi-value mode a hard read/decode error remains terminal until // reset(). E_OVERFLOW and end-of-stream do not poison the reader. @@ -346,6 +347,7 @@ class AlignedChunkReader : public IChunkReader { Compressor* value_compressor_; Filter* time_filter_; AlignedFieldFilter* field_filter_ = nullptr; + bool chunk_field_all_match_ = false; Decoder* time_decoder_; Decoder* value_decoder_; diff --git a/cpp/src/reader/block/device_ordered_tsblock_reader.cc b/cpp/src/reader/block/device_ordered_tsblock_reader.cc index 2c9b088415..316de25ccc 100644 --- a/cpp/src/reader/block/device_ordered_tsblock_reader.cc +++ b/cpp/src/reader/block/device_ordered_tsblock_reader.cc @@ -68,14 +68,14 @@ int DeviceOrderedTsBlockReader::has_next(bool& has_next) { } current_reader_ = new SingleDeviceTsBlockReader( task, block_size_, metadata_querier_, tsfile_io_reader_, - time_filter_, field_filter_); + time_filter_, field_filter_.get()); if (current_reader_ == nullptr) { return common::E_OOM; } current_reader_->set_reusable_block(&reusable_block_); - if (RET_FAIL(current_reader_->init(task, block_size_, time_filter_, - field_filter_, remaining_offset_, - remaining_limit_))) { + if (RET_FAIL(current_reader_->init( + task, block_size_, time_filter_, field_filter_.get(), + remaining_offset_, remaining_limit_))) { delete current_reader_; current_reader_ = nullptr; return ret; @@ -120,10 +120,7 @@ void DeviceOrderedTsBlockReader::close() { delete time_filter_; time_filter_ = nullptr; } - if (field_filter_ != nullptr) { - delete field_filter_; - field_filter_ = nullptr; - } + field_filter_.reset(); } } // namespace storage diff --git a/cpp/src/reader/block/device_ordered_tsblock_reader.h b/cpp/src/reader/block/device_ordered_tsblock_reader.h index 0190d11a8b..b166c120a1 100644 --- a/cpp/src/reader/block/device_ordered_tsblock_reader.h +++ b/cpp/src/reader/block/device_ordered_tsblock_reader.h @@ -33,13 +33,14 @@ class DeviceOrderedTsBlockReader : public TsBlockReader { std::unique_ptr device_task_iterator, IMetadataQuerier* metadata_querier, int32_t block_size, TsFileIOReader* tsfile_io_reader, Filter* time_filter, - Filter* field_filter, int row_offset = 0, int row_limit = -1) + AlignedFieldFilter::Ptr field_filter, int row_offset = 0, + int row_limit = -1) : device_task_iterator_(std::move(device_task_iterator)), metadata_querier_(metadata_querier), block_size_(block_size), tsfile_io_reader_(tsfile_io_reader), time_filter_(time_filter), - field_filter_(field_filter), + field_filter_(std::move(field_filter)), remaining_offset_(row_offset), remaining_limit_(row_limit) {} ~DeviceOrderedTsBlockReader() override { close(); } @@ -55,7 +56,7 @@ class DeviceOrderedTsBlockReader : public TsBlockReader { SingleDeviceTsBlockReader* current_reader_ = nullptr; TsFileIOReader* tsfile_io_reader_; Filter* time_filter_ = nullptr; - Filter* field_filter_ = nullptr; + AlignedFieldFilter::Ptr field_filter_ = nullptr; int remaining_offset_ = 0; int remaining_limit_ = -1; // Output block shared by the per-device readers this iterator creates. diff --git a/cpp/src/reader/block/single_device_tsblock_reader.cc b/cpp/src/reader/block/single_device_tsblock_reader.cc index 83e7768764..886580e7c0 100644 --- a/cpp/src/reader/block/single_device_tsblock_reader.cc +++ b/cpp/src/reader/block/single_device_tsblock_reader.cc @@ -24,7 +24,6 @@ #include #include "common/db_common.h" -#include "reader/filter/table_field_filter.h" namespace storage { @@ -41,18 +40,16 @@ common::TsBlock* reusable_block_factory(void* ctx, SingleDeviceTsBlockReader::SingleDeviceTsBlockReader( DeviceQueryTask* device_query_task, uint32_t block_size, IMetadataQuerier* metadata_querier, TsFileIOReader* tsfile_io_reader, - Filter* time_filter, Filter* field_filter) + Filter* time_filter, AlignedFieldFilter* field_filter) : device_query_task_(device_query_task), field_filter_(field_filter), block_size_(block_size), tuple_desc_(), - tsfile_io_reader_(tsfile_io_reader) { - aligned_field_filter_ = dynamic_cast(field_filter_); -} + tsfile_io_reader_(tsfile_io_reader) {} int SingleDeviceTsBlockReader::init(DeviceQueryTask* device_query_task, uint32_t block_size, Filter* time_filter, - Filter* field_filter) { + AlignedFieldFilter* field_filter) { remaining_offset_ = 0; remaining_limit_ = -1; dense_row_count_ = -1; @@ -63,8 +60,8 @@ int SingleDeviceTsBlockReader::init(DeviceQueryTask* device_query_task, int SingleDeviceTsBlockReader::init(DeviceQueryTask* device_query_task, uint32_t block_size, Filter* time_filter, - Filter* field_filter, int row_offset, - int row_limit) { + AlignedFieldFilter* field_filter, + int row_offset, int row_limit) { remaining_offset_ = row_offset; remaining_limit_ = row_limit; dense_row_count_ = -1; @@ -158,7 +155,7 @@ int32_t SingleDeviceTsBlockReader::compute_dense_row_count( int SingleDeviceTsBlockReader::init_internal(DeviceQueryTask* device_query_task, uint32_t block_size, Filter* time_filter, - Filter* field_filter) { + AlignedFieldFilter* field_filter) { int ret = common::E_OK; pa_.init(512, common::AllocModID::MOD_TSFILE_READER); tuple_desc_.reset(); @@ -248,8 +245,7 @@ int SingleDeviceTsBlockReader::init_internal(DeviceQueryTask* device_query_task, break; } } - if (can_multi && - (field_filter == nullptr || aligned_field_filter_ != nullptr)) { + if (can_multi) { std::vector meas_names(meas_cols.begin(), meas_cols.end()); // Stable order by first appearance in the result schema so the @@ -289,9 +285,9 @@ int SingleDeviceTsBlockReader::init_internal(DeviceQueryTask* device_query_task, dense_row_count_ >= 0) ? remaining_offset_ : 0; - int ctx_ret = ctx->init(device_query_task_, meas_names, time_filter, - pos_list, pa_, aligned_field_filter_, - ssi_offset, -1, reusable_block_); + int ctx_ret = + ctx->init(device_query_task_, meas_names, time_filter, pos_list, + pa_, field_filter_, ssi_offset, -1, reusable_block_); if (ctx_ret == common::E_OK) { if (ssi_offset > 0) { row_offset_pushed_to_ssi_ = true; @@ -310,7 +306,7 @@ int SingleDeviceTsBlockReader::init_internal(DeviceQueryTask* device_query_task, } else { delete ctx; if (ctx_ret == common::E_NO_MORE_DATA && - aligned_field_filter_ != nullptr) { + field_filter_ != nullptr) { // Page statistics can prove that no row in this device can // pass the structured FIELD filter. This is a valid empty // result, not a reason to fall back to the row path. @@ -359,8 +355,7 @@ int SingleDeviceTsBlockReader::init_internal(DeviceQueryTask* device_query_task, } } if (any_value_column_requested && - ((field_filter == nullptr && aligned_field_filter_ == nullptr) || - !all_value_columns_aligned)) { + (field_filter == nullptr || !all_value_columns_aligned)) { return common::E_OK; } @@ -388,10 +383,9 @@ int SingleDeviceTsBlockReader::init_internal(DeviceQueryTask* device_query_task, } // Detect aligned fast path: every field column comes from an aligned chunk. - if ((field_filter == nullptr || - (aligned_field_filter_ != nullptr && used_multi)) && + if ((field_filter == nullptr || used_multi) && !field_column_contexts_.empty() && - (dense_row_count_ >= 0 || aligned_field_filter_ != nullptr) && + (dense_row_count_ >= 0 || field_filter_ != nullptr) && aligned_col_count_ == field_column_contexts_.size()) { all_aligned_ = true; aligned_vec_.reserve(field_column_contexts_.size()); @@ -574,7 +568,7 @@ int SingleDeviceTsBlockReader::has_next_aligned_filtered( if (next_ret == common::E_NO_MORE_DATA) break; if (next_ret != common::E_OK) return next_ret; } - if (RET_FAIL(context->evaluate_filter(*aligned_field_filter_, + if (RET_FAIL(context->evaluate_filter(*field_filter_, aligned_filter_mask_))) { return ret; } @@ -617,7 +611,7 @@ int SingleDeviceTsBlockReader::has_next_aligned_filtered( } int SingleDeviceTsBlockReader::has_next_aligned(bool& result_has_next) { - if (aligned_field_filter_ != nullptr) { + if (field_filter_ != nullptr) { return has_next_aligned_filtered(result_has_next); } int ret = common::E_OK; @@ -788,10 +782,13 @@ int SingleDeviceTsBlockReader::fill_measurements( int SingleDeviceTsBlockReader::satisfy_field_filter(bool& satisfied) { int ret = common::E_OK; - std::vector fields; const auto& names = device_query_task_->get_column_mapping()->get_measurement_columns(); - fields.reserve(names.size()); + const uint8_t notnull = 0x80; + std::vector strings; + strings.reserve(names.size()); + std::vector views; + views.reserve(names.size()); for (const auto& name : names) { char* value = nullptr; uint32_t length = 0; @@ -806,43 +803,29 @@ int SingleDeviceTsBlockReader::satisfy_field_filter(bool& satisfied) { RET_FAIL(context->second->get_current_value(value, length))) return ret; } - auto schema = - device_query_task_->get_table_schema()->get_column_schema(name); - fields.push_back({name, schema.data_type_, value, length}); - } - if (aligned_field_filter_ != nullptr) { - // Non-aligned devices and aligned devices missing a measurement use - // the row merge instead of the shared multi-column SSI. Evaluate the - // merged row through the same typed evaluator, including explicit - // NULL views for missing measurements or timestamps. - const uint8_t notnull = 0x80; - std::vector strings(fields.size()); - std::vector views; - views.reserve(fields.size()); - for (size_t i = 0; i < fields.size(); ++i) { - const auto& field = fields[i]; - AlignedFieldFilter::ColumnView view; - view.name = field.name; - view.type = field.type; - view.notnull_bitmap = field.is_null() ? nullptr : ¬null; - view.notnull_bitmap_size = field.is_null() ? 0 : 1; - view.value_count = field.is_null() ? 0 : 1; - if (field.type == common::STRING || field.type == common::TEXT || - field.type == common::BLOB) { - strings[i] = common::String(field.data, field.size); - view.string_values = &strings[i]; + AlignedFieldFilter::ColumnView view; + view.name = name; + view.type = device_query_task_->get_table_schema() + ->get_column_schema(name) + .data_type_; + if (value != nullptr) { + view.notnull_bitmap = ¬null; + view.notnull_bitmap_size = 1; + view.value_count = 1; + if (view.type == common::STRING || view.type == common::TEXT || + view.type == common::BLOB) { + strings.emplace_back(value, length); + view.string_values = &strings.back(); } else { - view.fixed_values = field.data; + view.fixed_values = value; } - views.push_back(std::move(view)); } - SelectionMask mask; - ret = aligned_field_filter_->evaluate_columns(views, 1, mask); - satisfied = ret == common::E_OK && mask.test(0); - return ret; + views.push_back(std::move(view)); } - return evaluate_table_field_filter(*field_filter_, {next_time_, fields}, - satisfied); + SelectionMask mask; + ret = field_filter_->evaluate_columns(views, 1, mask); + satisfied = ret == common::E_OK && mask.test(0); + return ret; } int SingleDeviceTsBlockReader::advance_column( diff --git a/cpp/src/reader/block/single_device_tsblock_reader.h b/cpp/src/reader/block/single_device_tsblock_reader.h index 079943a873..2b001050b3 100644 --- a/cpp/src/reader/block/single_device_tsblock_reader.h +++ b/cpp/src/reader/block/single_device_tsblock_reader.h @@ -112,15 +112,15 @@ class SingleDeviceTsBlockReader : public TsBlockReader { IMetadataQuerier* metadata_querier, TsFileIOReader* tsfile_io_reader, Filter* time_filter, - Filter* field_filter); + AlignedFieldFilter* field_filter); ~SingleDeviceTsBlockReader() { close(); } int has_next(bool& has_next) override; int next(common::TsBlock*& ret_block) override; int init(DeviceQueryTask* device_query_task, uint32_t block_size, - Filter* time_filter, Filter* field_filter); + Filter* time_filter, AlignedFieldFilter* field_filter); int init(DeviceQueryTask* device_query_task, uint32_t block_size, - Filter* time_filter, Filter* field_filter, int row_offset, - int row_limit); + Filter* time_filter, AlignedFieldFilter* field_filter, + int row_offset, int row_limit); void close() override; // Borrow a block that can be reused across devices (see ReusableTsBlock). @@ -132,7 +132,7 @@ class SingleDeviceTsBlockReader : public TsBlockReader { private: int init_internal(DeviceQueryTask* device_query_task, uint32_t block_size, - Filter* time_filter, Filter* field_filter); + Filter* time_filter, AlignedFieldFilter* field_filter); int construct_column_context(const ITimeseriesIndex* time_series_index, Filter* time_filter, int ssi_offset, int ssi_limit); @@ -150,8 +150,7 @@ class SingleDeviceTsBlockReader : public TsBlockReader { int has_next_aligned_filtered(bool& has_next); DeviceQueryTask* device_query_task_; - Filter* field_filter_; - AlignedFieldFilter* aligned_field_filter_ = nullptr; + AlignedFieldFilter* field_filter_; uint32_t block_size_; common::TsBlock* current_block_ = nullptr; std::vector col_appenders_; diff --git a/cpp/src/reader/column_mapping.h b/cpp/src/reader/column_mapping.h index 621f8756c7..8280e8524a 100644 --- a/cpp/src/reader/column_mapping.h +++ b/cpp/src/reader/column_mapping.h @@ -46,19 +46,8 @@ 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); - } - return common::E_OK; + void add_filter_columns(const std::vector& names) { + field_columns_.insert(names.begin(), names.end()); } const std::vector& get_column_pos( diff --git a/cpp/src/reader/device_meta_iterator.cc b/cpp/src/reader/device_meta_iterator.cc index e57111e32b..d05c574ba8 100644 --- a/cpp/src/reader/device_meta_iterator.cc +++ b/cpp/src/reader/device_meta_iterator.cc @@ -121,11 +121,9 @@ int DeviceMetaIterator::load_leaf_device(MetaIndexNode* meta_index_node) { const auto& leaf_children = meta_index_node->children_; for (size_t i = 0; i < leaf_children.size(); i++) { std::shared_ptr child = leaf_children[i]; - if (id_filter_ != nullptr) { - if (!id_filter_->satisfyRow( - 0, child->get_device_id()->get_segments())) { - continue; - } + if (id_filter_ && + !id_filter_->matches(child->get_device_id()->get_segments())) { + continue; } int64_t start_offset = child->get_offset(); int64_t end_offset = i + 1 < leaf_children.size() @@ -168,33 +166,6 @@ int DeviceMetaIterator::load_internal_node(MetaIndexNode* meta_index_node) { return ret; } -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; - - if (root_node->children_.empty()) return; - - auto first_device = root_node->children_[0]->get_device_id(); - if (first_device == nullptr) return; - - auto first_segments = first_device->get_segments(); - int actual_segment_count = static_cast(first_segments.size()); - - if (actual_segment_count != 2) return; - - std::string table_name = first_device->get_table_name(); - std::vector segs(actual_segment_count); - segs[0] = table_name; - for (int i = 1; i < actual_segment_count; i++) { - segs[i] = ""; - } - segs[eq->col_idx_] = eq->value_; - direct_device_id_ = std::make_shared(segs); - direct_root_node_ = root_node; -} - int DeviceMetaIterator::load_results_direct() { int ret = common::E_OK; direct_lookup_done_ = true; diff --git a/cpp/src/reader/device_meta_iterator.h b/cpp/src/reader/device_meta_iterator.h index 00d5a8b860..4e00bf6139 100644 --- a/cpp/src/reader/device_meta_iterator.h +++ b/cpp/src/reader/device_meta_iterator.h @@ -25,7 +25,7 @@ #include #include "file/tsfile_io_reader.h" -#include "reader/expression.h" +#include "reader/filter/tag_filter.h" namespace storage { @@ -33,7 +33,7 @@ class DeviceMetaIterator { public: explicit DeviceMetaIterator(TsFileIOReader* io_reader, MetaIndexNode* meat_index_node, - const Filter* id_filter) + const TagFilter* id_filter) : io_reader_(io_reader), id_filter_(id_filter), should_split_device_name(false), @@ -42,14 +42,14 @@ class DeviceMetaIterator { // an empty iterator instead of dereferencing it during has_next(). if (meat_index_node != nullptr) { meta_index_nodes_.push({meat_index_node, false}); + if (id_filter_) direct_device_id_ = id_filter_->exact_device_id(); } pa_.init(512, common::MOD_DEVICE_META_ITER); - try_setup_direct_lookup(meat_index_node); } DeviceMetaIterator(TsFileIOReader* io_reader, const std::vector& meta_index_node_list, - const Filter* id_filter) + const TagFilter* id_filter) : io_reader_(io_reader), id_filter_(id_filter), direct_lookup_done_(false) { @@ -73,7 +73,6 @@ class DeviceMetaIterator { int load_leaf_device(MetaIndexNode* meta_index_node); int load_internal_node(MetaIndexNode* meta_index_node); - void try_setup_direct_lookup(MetaIndexNode* root_node); int load_results_direct(); TsFileIOReader* io_reader_; @@ -82,14 +81,13 @@ class DeviceMetaIterator { std::queue> meta_index_nodes_; std::queue, MetaIndexNode*>> result_cache_; - const Filter* id_filter_; + const TagFilter* id_filter_; common::PageArena pa_; bool should_split_device_name; int read_error_ = common::E_OK; bool direct_lookup_done_; std::shared_ptr direct_device_id_; - MetaIndexNode* direct_root_node_ = nullptr; }; } // end namespace storage diff --git a/cpp/src/reader/expression.cc b/cpp/src/reader/expression.cc index 3623b390e5..1efe781edf 100644 --- a/cpp/src/reader/expression.cc +++ b/cpp/src/reader/expression.cc @@ -19,11 +19,123 @@ #include "expression.h" +#include + #include "reader/filter/and_filter.h" #include "reader/filter/or_filter.h" 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->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, + 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))); +} + +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 1cf72b6d2a..9f97d5f202 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,15 +36,89 @@ 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 }; 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; + 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 TAG and FIELD column names against their schema. + 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); + + struct Operand { + 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)) {} + }; + std::vector referenced_columns() const; + ExpressionType type_; Expression* left_; Expression* right_; Filter* filter_; Path series_path_; + std::unique_ptr operand_; Expression(ExpressionType t) : type_(t), @@ -66,6 +141,7 @@ struct Expression { filter_(f), series_path_(path) {} void destroy() { + operand_.reset(); if (filter_ != nullptr) { delete filter_; filter_ = nullptr; @@ -79,6 +155,8 @@ struct Expression { right_ = nullptr; } } + Expression(const Expression&) = delete; + Expression& operator=(const Expression&) = delete; ~Expression() { destroy(); } }; diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index afa6bbb72a..91d9b089c3 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -19,41 +19,20 @@ #include "reader/filter/aligned_field_filter.h" -#include -#include #include #include -#include #include -#include "common/schema.h" #include "common/statistic.h" 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; -} +using Op = Expression::CompareOp; +using Literal = Expression::Literal; +using ColumnView = AlignedFieldFilter::ColumnView; -AlignedFieldFilter::CompareOp negate_comparison( - AlignedFieldFilter::CompareOp op) { - using Op = AlignedFieldFilter::CompareOp; +Op negate_comparison(Op op) { switch (op) { case Op::EQ: return Op::NE; @@ -71,26 +50,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 @@ -101,714 +60,202 @@ 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); +// 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); } 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::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, - bool negated) - : kind_(kind), - column_(std::move(column)), - compare_op_(op), - literal_(std::move(literal)), - negated_(negated) {} - -AlignedFieldFilter::AlignedFieldFilter(Kind kind, Ptr left, Ptr right) - : kind_(kind), left_(std::move(left)), right_(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) { - 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)); - } - 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; -} - -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_.get()); - if (node->left_) stack.push_back(node->left_.get()); - } - 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: - // Valid NOTs are pushed to leaves; only invalid markers remain. - return false; - case Kind::AND: - case Kind::OR: - return left_ != nullptr && right_ != nullptr && left_->is_valid() && - right_->is_valid(); - } - return false; -} - -int AlignedFieldFilter::bind(TableSchema& schema) { - if (kind_ == Kind::NOT) return 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); - if (ret != common::E_OK) return ret; - return right_->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; -} - -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)); - } - 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; - } - - 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 (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_ && 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_ && 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; -} - -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; - } - - 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; - } - // 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; - } - } - 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 (auto* typed = dynamic_cast(statistic)) { - if (literal_.type != common::FLOAT || has_nan_statistics(*typed) || - (negated_ && 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_ && 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; - } - } - 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; - } - +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 !all; +} + +template +bool statistics_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(static_cast(value))) + return !all; + return range_matches(stat.min_value_, stat.max_value_, value, + invert ? negate_comparison(op) : op, all, + no_nulls); + }); +} + +bool statistics_match(const Expression& expr, + const std::map& statistics, + int64_t rows, bool all, bool negated) { + if (expr.type_ == NOT) + return statistics_match(*expr.left_, statistics, rows, all, !negated); + if (expr.type_ == AND_EXPR || expr.type_ == OR_EXPR) { + const bool lhs = + statistics_match(*expr.left_, statistics, rows, all, negated); + if ((expr.type_ == AND_EXPR) != negated) + return lhs && statistics_match(*expr.right_, statistics, rows, all, + negated); + return lhs || + statistics_match(*expr.right_, statistics, rows, all, negated); + } + 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 (stat->count_ == 0 || (all && !no_nulls)) return false; + if (auto* typed = dynamic_cast(stat)) + return statistics_comparison(*typed, expr, negated, all, no_nulls, + common::INT32, &Literal::int32_value); + if (auto* typed = dynamic_cast(stat)) + return statistics_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 statistics_comparison(*typed, expr, negated, all, no_nulls, + common::FLOAT, &Literal::float_value); + } + if (auto* typed = dynamic_cast(stat)) { + if (has_nan_statistics(*typed)) return !all; + return statistics_comparison(*typed, expr, negated, all, no_nulls, + common::DOUBLE, &Literal::double_value); + } + 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 evaluate_tree(const Expression& expr, uint32_t row_count, + SelectionMask& mask, EvaluateLeaf evaluate_leaf) { struct Frame { - const AlignedFieldFilter* node; - uint8_t state; + const Expression* node; + bool negated; + bool combine; }; - 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}); + std::vector pending{{&expr, 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->type_ == AND_EXPR) != 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) { - 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 (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_, frame.negated, false}); + pending.push_back({node->left_, 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_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; - } - - struct Frame { - const AlignedFieldFilter* node; - uint8_t state; - }; - 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}); - } else { - postorder.push_back(node); - traversal.pop_back(); - } - } - } +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; + }); +} - 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 (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); - } - } +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; } - if (masks.size() != 1) return common::E_INVALID_ARG; - mask = std::move(masks.back()); + 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_leaf(const ColumnView& column, - uint32_t row_count, - 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 > @@ -853,63 +300,19 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, ++nonnull_index; } - bool satisfied = false; - if (kind_ == Kind::IS_NULL) { - satisfied = is_null; - } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = !is_null; - } 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_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(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, - 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; @@ -924,58 +327,61 @@ 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; - } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = !is_null; - } 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_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(expr, column_type, data, len, is_null, + negated, satisfied); + if (ret != common::E_OK) return ret; if (satisfied) mask.set_one(row); iter.next(); } return common::E_OK; } +} // namespace + +AlignedFieldFilter::StatisticsMatch AlignedFieldFilter::classify( + const std::map& statistics, int64_t rows) const { + if (!statistics_match(*expression_, statistics, rows, false, false)) + return StatisticsMatch::None; + if (rows > 0 && + statistics_match(*expression_, statistics, rows, true, false)) + return StatisticsMatch::All; + return StatisticsMatch::Possible; +} + +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 659d165b28..e0254843ca 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/filter.h" +#include "reader/expression.h" #include "reader/filter/selection_mask.h" namespace storage { @@ -37,13 +36,8 @@ class TableSchema; // 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 Filter { +class AlignedFieldFilter { 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; @@ -57,61 +51,18 @@ class AlignedFieldFilter : public Filter { 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 Ptr = std::unique_ptr; - - ~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); - - 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 - // this to reject a malformed tree before page statistics can classify it - // 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. - int bind(TableSchema& schema); - - // Conservatively decides whether any row in a page can satisfy the filter. - // Missing or unsupported statistics always return true. - bool may_match(const std::map& statistics, - int64_t row_count) const; - bool all_match(const std::map& statistics, - int64_t row_count) const; + const std::vector& referenced_columns() const { + return columns_; + } + static int bind(const Expression& expr, TableSchema& schema, Ptr& result); + + enum class StatisticsMatch { None, Possible, All }; + // Classify the rows in an aligned chunk or page using its shared time + // count. + StatisticsMatch classify( + const std::map& statistics, + int64_t row_count) const; // Evaluates against block.get_vector(0) as time and column_names[i] as // block.get_vector(i + 1). The mask is reset to block row count. @@ -122,30 +73,11 @@ class AlignedFieldFilter : public Filter { uint32_t row_count, SelectionMask& mask) const; private: - AlignedFieldFilter(Kind kind, std::string column, CompareOp op, - Literal literal, bool negated = false); - 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); - - int evaluate_leaf(common::TsBlock& block, - const std::map& column_index, - SelectionMask& mask) const; - int evaluate_leaf(const ColumnView& column, uint32_t row_count, - SelectionMask& mask) const; - Kind kind_; - 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_; + explicit AlignedFieldFilter(Expression::Ptr expr) + : expression_(std::move(expr)), + columns_(expression_->referenced_columns()) {} + Expression::Ptr expression_; + std::vector columns_; }; } // namespace storage diff --git a/cpp/src/reader/filter/bind_expression.cc b/cpp/src/reader/filter/bind_expression.cc new file mode 100644 index 0000000000..511f944b08 --- /dev/null +++ b/cpp/src/reader/filter/bind_expression.cc @@ -0,0 +1,203 @@ +/* + * 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 "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 detail::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; +} + +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 = detail::bind_literal(operand.upper, type); + if (ret != common::E_OK) return ret; + break; + } + case COMPARISON: + break; + default: + return common::E_NOT_SUPPORT; + } + return detail::bind_literal(operand.literal, type); +} +} // namespace + +int AlignedFieldFilter::bind(const Expression& expr, TableSchema& schema, + Ptr& result) { + result.reset(); + Expression::Ptr bound; + const int ret = detail::bind_expression( + expr, bound, + [&](const Expression& source, Expression::Ptr left, + Expression::Ptr right, Expression::Ptr& out) -> int { + Expression::Ptr node(new Expression(source.type_)); + if (source.operand_) { + node->operand_.reset(new Expression::Operand(*source.operand_)); + 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; + const int status = bind_value_leaf(*node, column.data_type_); + if (status != common::E_OK) return status; + } + node->left_ = left.release(); + node->right_ = right.release(); + out = std::move(node); + return common::E_OK; + }); + 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 new file mode 100644 index 0000000000..17273a9103 --- /dev/null +++ b/cpp/src/reader/filter/bind_expression.h @@ -0,0 +1,58 @@ +/* + * 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 { +namespace detail { + +int bind_literal(Expression::Literal& literal, common::TSDataType column_type); + +// Build query-owned nodes bottom-up. Both table filter inputs accept the same +// logical shapes; the leaf binder resolves names and validates column types. +template +int bind_expression(const Expression& source, std::unique_ptr& result, + const BindNode& bind_node) { + std::unique_ptr left, right; + if (source.filter_) return common::E_INVALID_ARG; + if (source.type_ == AND_EXPR || source.type_ == OR_EXPR || + source.type_ == NOT) { + if (!source.left_ || source.operand_ || + (source.type_ == NOT) != (source.right_ == nullptr)) + return common::E_INVALID_ARG; + int ret = bind_expression(*source.left_, left, bind_node); + if (ret != common::E_OK) return ret; + if (source.right_) { + ret = bind_expression(*source.right_, right, bind_node); + if (ret != common::E_OK) return ret; + } + } else if (source.left_ || source.right_ || !source.operand_ || + source.operand_->reference.empty()) { + return common::E_INVALID_ARG; + } + return bind_node(source, std::move(left), std::move(right), result); +} + +} // namespace detail +} // namespace storage +#endif // READER_FILTER_BIND_EXPRESSION_H diff --git a/cpp/src/reader/filter/table_field_filter.cc b/cpp/src/reader/filter/table_field_filter.cc deleted file mode 100644 index 5c385139d1..0000000000 --- a/cpp/src/reader/filter/table_field_filter.cc +++ /dev/null @@ -1,61 +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. - */ -#include "reader/filter/table_field_filter.h" - -namespace storage { -namespace { -template -int evaluate_integer(Filter& filter, const TableFieldRow& row, - bool& satisfied) { - T value; - if (!row.fields[0].get(value)) return common::E_DECODE_ERR; - satisfied = filter.satisfy(row.timestamp, static_cast(value)); - return common::E_OK; -} -} // namespace - -int evaluate_table_field_filter(Filter& filter, const TableFieldRow& row, - bool& satisfied) { - satisfied = false; - if (auto* row_filter = dynamic_cast(&filter)) { - return row_filter->satisfy_row(row, satisfied); - } - if (row.fields.size() != 1) return common::E_NOT_SUPPORT; - const auto& field = row.fields[0]; - if (field.is_null()) return common::E_OK; - switch (field.type) { - case common::BOOLEAN: - return evaluate_integer(filter, row, satisfied); - case common::DATE: - case common::INT32: - return evaluate_integer(filter, row, satisfied); - case common::TIMESTAMP: - case common::INT64: - return evaluate_integer(filter, row, satisfied); - case common::TEXT: - case common::STRING: - case common::BLOB: - satisfied = filter.satisfy(row.timestamp, - common::String(field.data, field.size)); - return common::E_OK; - default: - return common::E_NOT_SUPPORT; - } -} -} // namespace storage diff --git a/cpp/src/reader/filter/table_field_filter.h b/cpp/src/reader/filter/table_field_filter.h deleted file mode 100644 index 64ca4f17c1..0000000000 --- a/cpp/src/reader/filter/table_field_filter.h +++ /dev/null @@ -1,90 +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_TABLE_FIELD_FILTER_H -#define READER_TABLE_FIELD_FILTER_H - -#include -#include -#include -#include - -#include "reader/filter/filter.h" -#include "utils/errno_define.h" - -namespace storage { - -// Borrowed views: names and bytes are valid only during satisfy_row(). -// A null data pointer denotes NULL; size preserves embedded NUL bytes. -struct TableFieldValue { - const std::string& name; - common::TSDataType type; - const char* data; - uint32_t size; - - bool is_null() const { return data == nullptr; } - - // Exact native primitive types; string-like values use data and size. - template - bool get(T& value) const { - const bool matches = - (std::is_same::value && type == common::BOOLEAN) || - (std::is_same::value && - (type == common::INT32 || type == common::DATE)) || - (std::is_same::value && - (type == common::INT64 || type == common::TIMESTAMP)) || - (std::is_same::value && type == common::FLOAT) || - (std::is_same::value && type == common::DOUBLE); - if (is_null() || !matches || size != sizeof(T)) { - return false; - } - std::memcpy(&value, data, sizeof(T)); - return true; - } -}; - -struct TableFieldRow { - int64_t timestamp; - // Unique projected FIELDs with normalized names, in unspecified order. - const std::vector& fields; - - const TableFieldValue* find(const std::string& name) const { - for (const auto& field : fields) { - if (field.name == name) return &field; - } - return nullptr; - } -}; - -// Row predicates can inspect all projected FIELD columns, including NULLs. -// TAG predicates belong in query()'s tag_filter argument. Unprojected fields -// are not loaded automatically. An error is propagated through ResultSet. -class TableFieldFilter : public Filter { - public: - virtual int satisfy_row(const TableFieldRow& row, - bool& satisfied) const = 0; -}; - -// Legacy Filter callbacks support one selected integer/Boolean or string-like -// FIELD. NULL does not satisfy a legacy value predicate. Other legacy shapes -// return E_NOT_SUPPORT; use TableFieldFilter for floats or multiple fields. -int evaluate_table_field_filter(Filter& filter, const TableFieldRow& row, - bool& satisfied); - -} // namespace storage -#endif // READER_TABLE_FIELD_FILTER_H diff --git a/cpp/src/reader/filter/tag_filter.cc b/cpp/src/reader/filter/tag_filter.cc index 03b8ae7856..e8713bee44 100644 --- a/cpp/src/reader/filter/tag_filter.cc +++ b/cpp/src/reader/filter/tag_filter.cc @@ -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 @@ -17,319 +17,105 @@ * under the License. */ -#include "tag_filter.h" +#include "reader/filter/tag_filter.h" #include -#include -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() = default; - -bool TagFilter::satisfyRow(int time, std::vector segments) const { - return satisfyRow(segments); -} - -bool TagFilter::satisfyRow(std::vector segments) const { - ASSERT(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_; -} - -// TagNeq implementation -TagNeq::TagNeq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagNeq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] != value_; -} +#include "reader/filter/bind_expression.h" -// TagLt implementation -TagLt::TagLt(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagLt::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] < value_; -} - -// 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_; -} +namespace storage { -// TagRegExp implementation -TagRegExp::TagRegExp(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) { - try { - pattern_ = std::regex(value_); - is_valid_pattern_ = true; - } catch (const std::regex_error& e) { - is_valid_pattern_ = false; +int TagFilter::bind(const Expression& expression, TableSchema& schema, + Ptr& result) { + result.reset(); + int ret = detail::bind_expression( + expression, result, + [&](const Expression& source, Ptr left, Ptr right, Ptr& out) -> int { + Ptr node(new TagFilter(source.type_)); + if (source.operand_) { + const int status = node->bind_operand(*source.operand_, schema); + if (status != common::E_OK) return status; + } + node->left_ = std::move(left); + node->right_ = std::move(right); + out = std::move(node); + return common::E_OK; + }); + if (ret == common::E_OK && result->type_ == COMPARISON && + result->comparison_ == Expression::CompareOp::EQ) { + const auto categories = schema.get_column_categories(); + if (std::count(categories.begin(), categories.end(), + common::ColumnCategory::TAG) == 1) { + result->exact_device_id_ = + std::make_shared(std::vector{ + schema.get_table_name(), result->value_}); + } } -} - -bool TagRegExp::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr || - !is_valid_pattern_) - return false; - try { - return std::regex_search(*segments[col_idx_], pattern_); - } catch (const std::regex_error&) { - return false; + return ret; +} + +int TagFilter::bind_operand(const Expression::Operand& operand, + TableSchema& schema) { + const int order = schema.find_id_column_order(operand.reference); + if (order < 0) return common::E_COLUMN_NOT_EXIST; + if (schema.get_column_schema(operand.reference).data_type_ != + common::STRING) + return common::E_NOT_SUPPORT; + segment_ = static_cast(order) + 1; + if (type_ == IS_NULL || type_ == IS_NOT_NULL) return common::E_OK; + if (operand.literal.type != common::STRING) return common::E_NOT_SUPPORT; + value_ = operand.literal.string_value; + switch (type_) { + case COMPARISON: + comparison_ = operand.comparison; + break; + case BETWEEN: + case NOT_BETWEEN: + if (operand.upper.type != common::STRING) + return common::E_NOT_SUPPORT; + upper_ = operand.upper.string_value; + break; + case REGEXP: + case NOT_REGEXP: + try { + pattern_.reset(new std::regex(value_)); + } catch (const std::regex_error&) { + // An invalid pattern matches no device, including for + // NOT_REGEXP. + } + break; + default: + return common::E_NOT_SUPPORT; } -} - -// TagNotRegExp implementation -TagNotRegExp::TagNotRegExp(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) { - try { - pattern_ = std::regex(value_); - is_valid_pattern_ = true; - } catch (const std::regex_error& e) { - is_valid_pattern_ = false; + return common::E_OK; +} + +bool TagFilter::matches(const std::vector& segments) const { + switch (type_) { + case AND_EXPR: + return left_->matches(segments) && right_->matches(segments); + case OR_EXPR: + return left_->matches(segments) || right_->matches(segments); + case NOT: + return !left_->matches(segments); + default: + break; } -} - -bool TagNotRegExp::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr || - !is_valid_pattern_) - return false; + const auto* value = + segment_ < segments.size() ? segments[segment_] : 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, value_, comparison_); + if (type_ == BETWEEN || type_ == NOT_BETWEEN) + return (value_ <= *value && *value <= upper_) == (type_ == BETWEEN); + if (!pattern_) return false; try { - return !std::regex_search(*segments[col_idx_], pattern_); + return std::regex_search(*value, *pattern_) == (type_ == REGEXP); } catch (const std::regex_error&) { - return true; - } -} - -// 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; -} - -// TagBetween implementation -TagBetween::TagBetween(int col_idx, std::string lower_value, - std::string upper_value) - : TagFilter(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)) { - 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 -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); -} - -// TagFilterBuilder implementation -TagFilterBuilder::TagFilterBuilder(TableSchema* schema) - : table_schema_(schema) {} - -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); -} - -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); -} - -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); -} - -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); -} - -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); -} - -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); -} - -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); -} - -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); -} - -Filter* TagFilterBuilder::is_null(const std::string& columnName) { - auto idx = get_tag_column_index(columnName); - if (idx < 0) return nullptr; - return new TagIsNull(idx); -} - -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); -} - -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); -} - -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); -} - -Filter* TagFilterBuilder::and_filter(Filter* left, Filter* right) { - return new TagAnd(dynamic_cast(left), - dynamic_cast(right)); -} - -Filter* TagFilterBuilder::or_filter(Filter* left, Filter* right) { - return new TagOr(dynamic_cast(left), - dynamic_cast(right)); -} - -Filter* TagFilterBuilder::not_filter(Filter* filter) { - return new TagNot(dynamic_cast(filter)); -} - -int TagFilterBuilder::get_tag_column_index(const std::string& columnName) { - int idColumnOrder = table_schema_->find_id_column_order(columnName); - if (idColumnOrder == -1) { - return -1; + return type_ == NOT_REGEXP; } - return idColumnOrder + 1; } -} // 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 50c750d441..7f6a33b923 100644 --- a/cpp/src/reader/filter/tag_filter.h +++ b/cpp/src/reader/filter/tag_filter.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 @@ -20,187 +20,35 @@ #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/expression.h" -struct table_schema; namespace storage { -class TagFilter : public Filter { - public: - TagFilter(int col_idx, std::string tag_value); - ~TagFilter() override; - - bool satisfyRow(int time, - std::vector segments) const override; - virtual bool satisfyRow(std::vector segments) const; - - std::string value_; - std::string value2_; // For range queries - int col_idx_; -}; - -// 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 -class TagRegExp : public TagFilter { - std::regex pattern_; - bool is_valid_pattern_ = false; - - public: - TagRegExp(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; -}; - -// Regular expression not match -class TagNotRegExp : public TagFilter { - std::regex pattern_; - bool is_valid_pattern_ = false; - - public: - TagNotRegExp(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; -}; -// IS NULL: tag column has no value for this device. An absent trailing -// segment (col_idx_ beyond the device's segment count) is also treated as null. -class TagIsNull : public TagFilter { +class 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 -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; + using Ptr = std::unique_ptr; + static int bind(const Expression& expression, TableSchema& schema, + Ptr& result); + bool matches(const std::vector& segments) const; + std::shared_ptr exact_device_id() const { + return exact_device_id_; + } 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 { - TableSchema* table_schema_; - - public: - explicit TagFilterBuilder(TableSchema* schema); - - 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: - int get_tag_column_index(const std::string& columnName); + explicit TagFilter(ExpressionType type) : type_(type) {} + int bind_operand(const Expression::Operand& operand, TableSchema& schema); + ExpressionType type_; + Expression::CompareOp comparison_ = Expression::CompareOp::EQ; + size_t segment_ = 0; + std::string value_; + std::string upper_; + std::unique_ptr pattern_; + Ptr left_, right_; + std::shared_ptr exact_device_id_; }; } // namespace storage -#endif // READER_FILTER_TAG_FILTER_H \ No newline at end of file +#endif // READER_FILTER_TAG_FILTER_H diff --git a/cpp/src/reader/imeta_data_querier.h b/cpp/src/reader/imeta_data_querier.h index d7b5d7debe..b69befa325 100644 --- a/cpp/src/reader/imeta_data_querier.h +++ b/cpp/src/reader/imeta_data_querier.h @@ -56,11 +56,11 @@ class IMetadataQuerier { virtual void clear() = 0; virtual std::unique_ptr device_iterator( - MetaIndexNode* root, const Filter* id_filter) = 0; + MetaIndexNode* root, const TagFilter* id_filter) = 0; // FIXME(Colin): refine this. virtual std::unique_ptr device_iterator( - std::vector root, const Filter* id_filter) = 0; + std::vector root, const TagFilter* id_filter) = 0; }; } // end namespace storage #endif // READER_IMETA_DATA_QUERIER_H diff --git a/cpp/src/reader/meta_data_querier.cc b/cpp/src/reader/meta_data_querier.cc index df97901564..4b99cc808a 100644 --- a/cpp/src/reader/meta_data_querier.cc +++ b/cpp/src/reader/meta_data_querier.cc @@ -77,13 +77,13 @@ std::vector MetadataQuerier::convert_space_to_time_partition( void MetadataQuerier::clear() {} std::unique_ptr MetadataQuerier::device_iterator( - MetaIndexNode* root, const Filter* id_filter) { + MetaIndexNode* root, const TagFilter* id_filter) { return std::unique_ptr( new DeviceMetaIterator(io_reader_, root, id_filter)); } std::unique_ptr MetadataQuerier::device_iterator( - std::vector root, const Filter* id_filter) { + std::vector root, const TagFilter* id_filter) { return std::unique_ptr( new DeviceMetaIterator(io_reader_, root, id_filter)); } diff --git a/cpp/src/reader/meta_data_querier.h b/cpp/src/reader/meta_data_querier.h index b2346e6bf1..1f771ad4ed 100644 --- a/cpp/src/reader/meta_data_querier.h +++ b/cpp/src/reader/meta_data_querier.h @@ -56,10 +56,10 @@ class MetadataQuerier : public IMetadataQuerier { int64_t spacePartitionEndPos) const override; std::unique_ptr device_iterator( - MetaIndexNode* root, const Filter* id_filter) override; + MetaIndexNode* root, const TagFilter* id_filter) override; std::unique_ptr device_iterator( - std::vector root, const Filter* id_filter) override; + std::vector root, const TagFilter* id_filter) override; void clear() override; diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 8ecc1256de..d09b312e1c 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -19,35 +19,28 @@ #include "reader/table_query_executor.h" +#include "reader/filter/tag_filter.h" #include "utils/db_utils.h" namespace storage { int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, - Filter* time_filter, Filter* tag_filter, - Filter* field_filter, ResultSet*& ret_qds) { + Filter* time_filter, int offset, int limit, + ResultSet*& ret_qds, const Expression* tag_filter, + const Expression* field_filter) { + std::unique_ptr owned_time(time_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; - // 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; } + if (!table_schema) return common::E_TABLE_NOT_EXIST; file_metadata->get_table_metaindex_node(table_name, table_root); std::vector lower_case_column_names(columns); for (auto& column : lower_case_column_names) { @@ -64,28 +57,26 @@ 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]); } - 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; + std::unique_ptr device_filter; + if (tag_filter && + RET_FAIL(TagFilter::bind(*tag_filter, *table_schema, device_filter))) + return ret; + AlignedFieldFilter::Ptr value_filter; + if (field_filter) { + if (RET_FAIL(AlignedFieldFilter::bind(*field_filter, *table_schema, + value_filter))) return ret; - } + column_mapping->add_filter_columns(value_filter->referenced_columns()); } auto device_task_iterator = std::unique_ptr(new DeviceTaskIterator( lower_case_column_names, table_root, column_mapping, - meta_data_querier_, tag_filter, table_schema)); + meta_data_querier_, std::move(device_filter), table_schema)); std::unique_ptr tsblock_reader; switch (table_query_ordering_) { @@ -93,98 +84,11 @@ int TableQueryExecutor::query(const std::string& table_name, tsblock_reader = std::unique_ptr( new DeviceOrderedTsBlockReader( std::move(device_task_iterator), meta_data_querier_, - block_size_, tsfile_io_reader_, time_filter, field_filter)); + block_size_, tsfile_io_reader_, owned_time.release(), + std::move(value_filter), 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); - ret_qds = - new TableResultSet(std::move(tsblock_reader), lower_case_column_names, - data_types, return_mode_); - return ret; -} - -int TableQueryExecutor::query(const std::string& table_name, - const std::vector& columns, - Filter* time_filter, Filter* tag_filter, - Filter* field_filter, int offset, int limit, - 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; - 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, 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 e968c3601e..1f7687f6b6 100644 --- a/cpp/src/reader/table_query_executor.h +++ b/cpp/src/reader/table_query_executor.h @@ -72,18 +72,17 @@ class TableQueryExecutor { } } // FIELD filters apply to both aligned and non-aligned table devices. - // AlignedFieldFilter uses batch/page pruning where possible and otherwise - // evaluates merged rows. In the non-aligned path, candidate timestamps are - // the union of the projected and filter-referenced FIELD series; values - // absent at a candidate timestamp are NULL. OFFSET/LIMIT count accepted - // rows. A valid empty time range returns an empty result for either layout. + // AlignedFieldFilter uses chunk and page pruning where possible and + // otherwise evaluates merged rows. In the non-aligned path, candidate + // timestamps are the union of the projected and filter-referenced FIELD + // series; values absent at a candidate timestamp are NULL. OFFSET/LIMIT + // count accepted rows. A valid empty time range returns an empty result for + // either layout. int query(const std::string& table_name, const std::vector& columns, Filter* time_filter, - Filter* tag_filter, Filter* field_filter, ResultSet*& ret_qds); - int query(const std::string& table_name, - const std::vector& columns, Filter* time_filter, - Filter* tag_filter, Filter* field_filter, int offset, int limit, - ResultSet*& ret_qds); + int offset, int limit, ResultSet*& result, + const Expression* tag_filter = nullptr, + const Expression* field_filter = nullptr); int query_on_tree(const std::vector>& devices, const std::vector& tag_columns, const std::vector& field_columns, diff --git a/cpp/src/reader/task/device_task_iterator.h b/cpp/src/reader/task/device_task_iterator.h index ad86dbc1dd..5eeb91ce9a 100644 --- a/cpp/src/reader/task/device_task_iterator.h +++ b/cpp/src/reader/task/device_task_iterator.h @@ -34,12 +34,13 @@ class DeviceTaskIterator { MetaIndexNode* index_root, std::shared_ptr column_mapping, IMetadataQuerier* metadata_querier, - const Filter* id_filter, + std::unique_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_root, id_filter)), + metadata_querier->device_iterator(index_root, id_filter_.get())), table_schema_(table_schema) { pa_.init(512, common::MOD_DEVICE_TASK_ITER); } @@ -48,12 +49,13 @@ class DeviceTaskIterator { std::vector index_roots, std::shared_ptr column_mapping, IMetadataQuerier* metadata_querier, - const Filter* id_filter, + std::unique_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); } @@ -79,6 +81,7 @@ class DeviceTaskIterator { private: std::vector column_names_; std::shared_ptr column_mapping_; + std::unique_ptr id_filter_; std::unique_ptr device_meta_iterator_; std::shared_ptr table_schema_; common::PageArena pa_; diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index 4a39a9f232..26033a9340 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -232,49 +232,7 @@ int TsFileReader::query(const std::string& table_name, int64_t start_time, int64_t end_time, ResultSet*& result_set, int batch_size) { return this->query(table_name, columns_names, start_time, end_time, - result_set, nullptr, batch_size); -} - -int TsFileReader::query(const std::string& table_name, - const std::vector& columns_names, - int64_t start_time, int64_t end_time, - ResultSet*& result_set, Filter* tag_filter, - int batch_size) { - return query(table_name, columns_names, start_time, end_time, 0, -1, - result_set, tag_filter, batch_size); -} - -int TsFileReader::query(const std::string& table_name, - const std::vector& columns_names, - int64_t start_time, int64_t end_time, int offset, - int limit, ResultSet*& result_set, Filter* tag_filter, - int batch_size) { - if (tsfile_executor_ == nullptr) { - return E_INVALID_ARG; - } - int ret = E_OK; - TsFileMeta* tsfile_meta = nullptr; - if (RET_FAIL(tsfile_executor_->get_tsfile_meta(tsfile_meta))) { - return ret; - } - auto schema_it = tsfile_meta->table_schemas_.find(to_lower(table_name)); - if (schema_it == tsfile_meta->table_schemas_.end() || - schema_it->second == nullptr) { - return E_TABLE_NOT_EXIST; - } - if (offset < 0) { - return E_INVALID_ARG; - } - if (limit < 0) { - limit = -1; - } - - Filter* time_filter = new TimeBetween(start_time, end_time, false); - ensure_table_query_executor(batch_size); - ret = table_query_executor_->query(to_lower(table_name), columns_names, - time_filter, tag_filter, nullptr, offset, - limit, result_set); - return ret; + result_set, nullptr, nullptr, batch_size); } int TsFileReader::queryByRow(std::vector& path_list, int offset, @@ -316,7 +274,7 @@ int TsFileReader::prepare_series( int TsFileReader::prepare_table_series( const std::string& table_name, const std::string& column_name, - Filter* tag_filter, std::shared_ptr& prepared) { + const Expression* tag_filter, std::shared_ptr& prepared) { int ret = E_OK; prepared.reset(); if (read_file_ == nullptr || tsfile_executor_ == nullptr) { @@ -335,6 +293,12 @@ int TsFileReader::prepare_table_series( if (RET_FAIL(file_metadata->get_table_schema(table, table_schema))) { return ret; } + if (!table_schema) return E_TABLE_NOT_EXIST; + std::unique_ptr bound_tag; + if (tag_filter && + RET_FAIL(TagFilter::bind(*tag_filter, *table_schema, bound_tag))) + return ret; + MetaIndexNode* table_root = nullptr; file_metadata->get_table_metaindex_node(table, table_root); if (table_root == nullptr) { @@ -343,7 +307,7 @@ int TsFileReader::prepare_table_series( common::PageArena pa; pa.init(512, common::MOD_TSFILE_READER); - DeviceMetaIterator device_iterator(io_reader, table_root, tag_filter); + DeviceMetaIterator device_iterator(io_reader, table_root, bound_tag.get()); bool has_next = false; if (RET_FAIL(device_iterator.has_next(has_next))) { return ret; @@ -455,29 +419,41 @@ int TsFileReader::query_prepared_multi( prepared, start_time, end_time, offset, limit, result_set, block_rows); } +int TsFileReader::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) { + 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, 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), offset, limit, result_set, + tag_filter, field_filter); +} + int TsFileReader::queryByRow(const std::string& table_name, - const std::vector& column_names, + const std::vector& columns, int offset, int limit, ResultSet*& result_set, - Filter* tag_filter, int batch_size) { - if (tsfile_executor_ == nullptr) { - return E_INVALID_ARG; - } - int ret = E_OK; - TsFileMeta* tsfile_meta = nullptr; - if (RET_FAIL(tsfile_executor_->get_tsfile_meta(tsfile_meta))) { - return ret; - } - auto it = tsfile_meta->table_schemas_.find(to_lower(table_name)); - if (it == tsfile_meta->table_schemas_.end() || it->second == nullptr) { - return E_TABLE_NOT_EXIST; - } - + 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); - ret = table_query_executor_->query(to_lower(table_name), column_names, - /*time_filter=*/nullptr, tag_filter, - /*field_filter=*/nullptr, offset, limit, - result_set); - return ret; + return table_query_executor_->query(to_lower(table_name), columns, nullptr, + 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 6f2c7d3408..210af6c483 100644 --- a/cpp/src/reader/tsfile_reader.h +++ b/cpp/src/reader/tsfile_reader.h @@ -112,27 +112,19 @@ class TsFileReader { const std::vector& columns_names, int64_t start_time, int64_t end_time, ResultSet*& result_set, int batch_size = -1); - /** - * @brief query the tsfile by the table name, columns names, start time - * and end time, tag filter. this method is used to query the tsfile by the - * table model. - * - * @param [in] table_name the table name - * @param [in] columns_names the columns names - * @param [in] start_time the start time - * @param [in] end_time the end time - * @param [in] tag_filter the tag filter - * @param [out] result_set the result set - */ + // Each expression may be null. The result owns its query-time bindings. + // The caller owns both expressions. Each query binds the referenced TAG + // and FIELD names to this table and owns the resulting filters. int query(const std::string& table_name, - const std::vector& columns_names, int64_t start_time, - int64_t end_time, ResultSet*& result_set, Filter* tag_filter, - int batch_size = 0); - + const std::vector& columns, int64_t start_time, + int64_t end_time, ResultSet*& result_set, + const Expression* tag_filter, + const Expression* field_filter = nullptr, int batch_size = 0); int query(const std::string& table_name, - const std::vector& columns_names, int64_t start_time, + const std::vector& columns, int64_t start_time, int64_t end_time, int offset, int limit, ResultSet*& result_set, - Filter* tag_filter = nullptr, int batch_size = 0); + const Expression* tag_filter = nullptr, + const Expression* field_filter = nullptr, int batch_size = 0); /** * @brief Query tree-model time series by row with offset and limit. @@ -168,7 +160,8 @@ class TsFileReader { * @param [out] prepared the prepared series */ int prepare_table_series(const std::string& table_name, - const std::string& column_name, Filter* tag_filter, + const std::string& column_name, + const Expression* tag_filter, std::shared_ptr& prepared); int query_prepared(const std::shared_ptr& prepared, int64_t start_time, int64_t end_time, int offset, @@ -197,9 +190,11 @@ class TsFileReader { * @return Returns 0 on success, or a non-zero error code on failure. */ int queryByRow(const std::string& table_name, - const std::vector& column_names, int offset, + const std::vector& columns, int offset, int limit, ResultSet*& result_set, - Filter* tag_filter = nullptr, int batch_size = 0); + const Expression* tag_filter = nullptr, + const Expression* field_filter = nullptr, + int batch_size = 0); int query_table_on_tree(const std::vector& measurement_names, int64_t star_time, int64_t end_time, diff --git a/cpp/src/reader/tsfile_series_scan_iterator.cc b/cpp/src/reader/tsfile_series_scan_iterator.cc index ba7834e0be..2d914f45f6 100644 --- a/cpp/src/reader/tsfile_series_scan_iterator.cc +++ b/cpp/src/reader/tsfile_series_scan_iterator.cc @@ -269,6 +269,29 @@ bool TsFileSeriesScanIterator::should_skip_multi_aligned_chunk_by_offset( return false; } +AlignedFieldFilter::StatisticsMatch +TsFileSeriesScanIterator::classify_multi_chunk( + ChunkMeta* time, const std::vector& values) const { + if (!field_filter_) return AlignedFieldFilter::StatisticsMatch::All; + const auto* index = + static_cast(itimeseries_index_); + // A series with a single chunk stores its statistics in the series index. + const bool single_chunk = index->get_time_chunk_meta_list()->size() == 1; + auto statistics = [single_chunk](const ChunkMeta* chunk, + const TimeseriesIndex* series) { + return single_chunk && !chunk->statistic_ ? series->get_statistic() + : chunk->statistic_; + }; + const auto* time_stats = statistics(time, index->time_ts_idx_); + std::map field_stats; + for (size_t i = 0; i < values.size(); ++i) { + field_stats.emplace(values[i]->measurement_name_.to_std_string(), + statistics(values[i], index->value_ts_idxs_[i])); + } + return field_filter_->classify(field_stats, + time_stats ? time_stats->count_ : 0); +} + int TsFileSeriesScanIterator::get_next(TsBlock*& ret_tsblock, bool alloc, Filter* oneshoot_filter, int64_t min_time_hint) { @@ -304,7 +327,12 @@ int TsFileSeriesScanIterator::get_next(TsBlock*& ret_tsblock, bool alloc, if (should_skip_chunk_by_time(time_cm, min_time_hint)) { continue; } - if (field_filter_ == nullptr && + const auto match = classify_multi_chunk(time_cm, value_cms); + if (match == AlignedFieldFilter::StatisticsMatch::None) + continue; + const bool field_all_match = + match == AlignedFieldFilter::StatisticsMatch::All; + if (field_all_match && chunk_fully_satisfies_filter(time_cm, filter) && should_skip_multi_aligned_chunk_by_offset(time_cm, value_cms)) { @@ -312,9 +340,8 @@ int TsFileSeriesScanIterator::get_next(TsBlock*& ret_tsblock, bool alloc, } chunk_reader_->reset(); auto* acr = static_cast(chunk_reader_); - if (RET_FAIL(acr->load_by_aligned_meta_multi(time_cm, - value_cms))) { - } + ret = acr->load_by_aligned_meta_multi(time_cm, value_cms, + field_all_match); break; } else if (!is_aligned_) { ChunkMeta* cm = get_current_chunk_meta(); @@ -523,9 +550,9 @@ int TsFileSeriesScanIterator::init_chunk_reader_multi() { } acr->set_field_filter(field_filter_); - // No chunks → nothing to load; iteration short-circuits via - // has_next_chunk() returning false. - if (time_chunk_count == 0) { + // Filtered scans classify every chunk in get_next() before reading its + // headers. + if (time_chunk_count == 0 || field_filter_) { return ret; } @@ -545,7 +572,7 @@ int TsFileSeriesScanIterator::init_chunk_reader_multi() { time_chunk_meta_cursor_++; for (auto& cur : value_chunk_meta_cursors_) cur++; - return ret; + return E_OK; } TsBlock* TsFileSeriesScanIterator::alloc_or_reuse_tsblock() { diff --git a/cpp/src/reader/tsfile_series_scan_iterator.h b/cpp/src/reader/tsfile_series_scan_iterator.h index 44cca99b53..d55db75d88 100644 --- a/cpp/src/reader/tsfile_series_scan_iterator.h +++ b/cpp/src/reader/tsfile_series_scan_iterator.h @@ -142,8 +142,7 @@ class TsFileSeriesScanIterator { // Multi-value: number of value columns in the TsBlock uint32_t get_value_column_count() const { if (is_multi_value_ && chunk_reader_) { - auto* acr = static_cast(chunk_reader_); - return acr->get_value_column_count(); + return itimeseries_index_->get_value_column_count(); } return 1; } @@ -221,6 +220,8 @@ class TsFileSeriesScanIterator { FORCE_INLINE ChunkMeta* get_current_chunk_meta() { return chunk_meta_cursor_.get(); } + AlignedFieldFilter::StatisticsMatch classify_multi_chunk( + ChunkMeta* time, const std::vector& values) const; bool should_skip_chunk_by_time(ChunkMeta* cm, int64_t min_time_hint); bool should_skip_chunk_by_offset(ChunkMeta* cm); bool should_skip_aligned_chunk_by_offset(ChunkMeta* time_cm, diff --git a/cpp/src/utils/util_define.h b/cpp/src/utils/util_define.h index 33784e1528..9c6f126ce3 100644 --- a/cpp/src/utils/util_define.h +++ b/cpp/src/utils/util_define.h @@ -66,7 +66,7 @@ typedef int mode_t; /* ======== library symbol visibility ======== * - * Functions are exported from tsfile.dll automatically via + * Functions are exported from the TsFile DLL automatically via * CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS, but global DATA symbols (plain variables, * static class members) are not reliably auto-exported, and a consumer must * see __declspec(dllimport) to reference them across the DLL boundary. Mark diff --git a/cpp/test/CMakeLists.txt b/cpp/test/CMakeLists.txt index e640a08806..920c0fc70a 100644 --- a/cpp/test/CMakeLists.txt +++ b/cpp/test/CMakeLists.txt @@ -370,14 +370,14 @@ if (WIN32 AND TSFILE_BUILD_SHARED) COMMAND ${CMAKE_COMMAND} -E copy_if_different $ "$" - COMMENT "Copying libtsfile.dll to test executable directory" + COMMENT "Copying the TsFile DLL to the test executable directory" VERBATIM ) endif () include(GoogleTest) # On Windows, delay test discovery until ctest runs (PRE_TEST) so the test exe -# runs with the correct env (e.g. PATH has MinGW, libtsfile.dll is present). +# runs with the correct env (e.g. PATH has MinGW, the TsFile DLL is present). # Avoids 0xc0000139 when discovery runs at build time. # # DISCOVERY_TIMEOUT is raised well above the 5s default: the first execution of diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 765a2fdfc9..baa0279c49 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/aligned_chunk_reader_bulk_test.cc b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc index c5c5d22917..db6cf1e29b 100644 --- a/cpp/test/reader/aligned_chunk_reader_bulk_test.cc +++ b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc @@ -45,6 +45,7 @@ #include "reader/aligned_chunk_reader.h" #include "reader/filter/aligned_field_filter.h" #include "reader/filter/time_operator.h" +#include "reader/table_query_executor.h" #include "writer/tsfile_table_writer.h" #ifdef ENABLE_THREADS #include "common/thread_pool.h" @@ -321,6 +322,38 @@ class AlignedBulkCopyTest : public ::testing::Test { AlignedChunkReader* reader_ = nullptr; }; +TEST_F(AlignedBulkCopyTest, FieldStatisticsRejectChunkBeforeReadingHeaders) { + class RejectChunkRead : public LocalRandomAccessReadFile { + public: + explicit RejectChunkRead(int64_t offset) : blocked_(offset) {} + int read(int64_t offset, char* buf, int32_t len, + int32_t& read_len) override { + if (offset == blocked_) { + read_len = 0; + return E_FILE_READ_ERR; + } + return LocalRandomAccessReadFile::read(offset, buf, len, read_len); + } + + private: + int64_t blocked_; + }; + RejectChunkRead file(time_meta_->offset_of_chunk_header_); + ASSERT_EQ(E_OK, file.open(path_)); + TableQueryExecutor executor(&file); + for (auto op : {Expression::CompareOp::LT, Expression::CompareOp::GE}) { + auto expr = Expression::compare("v", op, Expression::Literal::int64(0)); + ResultSet* result = nullptr; + ASSERT_EQ(E_OK, executor.query("t", {"w"}, nullptr, 0, -1, result, + nullptr, expr.get())); + std::unique_ptr owned(result); + bool next = false; + EXPECT_EQ(op == Expression::CompareOp::LT ? E_OK : E_FILE_READ_ERR, + result->next(next)); + EXPECT_FALSE(next); + } +} + // A window whose endpoints fall inside pages leaves whole pages in the middle. // Those are BOUNDARY pages restricted to [0, data_num), and a contiguous time // filter proves every row in that range matches, so they are bulk-copied. @@ -410,9 +443,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 4abce065a4..100b2d92c7 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 @@ -521,7 +544,7 @@ TEST_P(AlignedFieldFilterRegressionTest, NotPreservesFloatingNaNRowSemantics) { } TEST_P(AlignedFieldFilterRegressionTest, - JavaNumericLiteralsUseTheDeclaredColumnType) { + NumericLiteralsUseTheDeclaredColumnType) { write_floats(); for (const std::string column : {"v", "f", "d"}) { for (const auto& literal : @@ -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) { @@ -1022,8 +1045,7 @@ TEST_P(AlignedFieldFilterRegressionTest, UnusableTsBlockCapacityReportsError) { ASSERT_EQ(file.open(filename_), E_OK); TableQueryExecutor executor(&file, std::get<1>(GetParam())); ResultSet* result = nullptr; - int ret = executor.query("t", {"v", "ghost"}, nullptr, nullptr, nullptr, 0, - -1, result); + int ret = executor.query("t", {"v", "ghost"}, nullptr, 0, -1, result); if (ret == E_OK) { ASSERT_NE(result, nullptr); bool next = false; @@ -1097,8 +1119,7 @@ TEST_P(AlignedFieldFilterRegressionTest, TableQueryExecutor executor(&rfile, std::get<1>(GetParam())); Filter* tf = new TimeBetween(kBase + 10, kBase + 80, false); ResultSet* result = nullptr; - int ret = - executor.query("t", query_columns, tf, nullptr, nullptr, 0, -1, result); + int ret = executor.query("t", query_columns, tf, 0, -1, result); if (ret == E_OK) { ASSERT_NE(result, nullptr); bool next = false; diff --git a/cpp/test/reader/aligned_wide_table_small_block_test.cc b/cpp/test/reader/aligned_wide_table_small_block_test.cc index a78873be85..1618cb62bb 100644 --- a/cpp/test/reader/aligned_wide_table_small_block_test.cc +++ b/cpp/test/reader/aligned_wide_table_small_block_test.cc @@ -139,8 +139,7 @@ TEST_F(AlignedWideTableSmallBlockTest, UnusableCapacityReportsError) { ASSERT_EQ(file.open(filename_), E_OK); TableQueryExecutor executor(&file, /*batch_size=*/16); ResultSet* result = nullptr; - int ret = executor.query("t", wide_columns(), nullptr, nullptr, nullptr, 0, - -1, result); + int ret = executor.query("t", wide_columns(), nullptr, 0, -1, result); if (ret == E_OK) { ASSERT_NE(result, nullptr); bool next = false; diff --git a/cpp/test/reader/block/masked_bulk_copy_test.cc b/cpp/test/reader/block/masked_bulk_copy_test.cc index d2a467a314..0357fd031a 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 3da4d840da..dfd924356f 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 cb5a200405..8177a03000 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,22 +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 = 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"))); + } + TableSchema schema("t", {{"v", common::INT64, common::UNCOMPRESSED, + common::PLAIN, common::ColumnCategory::FIELD}}); + 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, 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; @@ -74,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); @@ -94,22 +126,22 @@ 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, NumericBindingMatchesJavaNumberConversions) { +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(); 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)}, @@ -145,11 +177,8 @@ TEST(AlignedFieldFilterTest, NumericBindingMatchesJavaNumberConversions) { 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(detail::bind_literal(actual, type), E_OK); ASSERT_EQ(actual.type, expected.type); if (actual.type == INT32) { EXPECT_EQ(actual.int32_value, expected.int32_value); @@ -267,6 +296,8 @@ TEST(SelectionMaskTest, SelectedRunsMatchScalarOracle) { } } +using Match = AlignedFieldFilter::StatisticsMatch; + TEST(AlignedFieldFilterTest, PageStatisticsAreConservative) { Int64Statistic statistic; statistic.count_ = 5; @@ -274,25 +305,36 @@ 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)); - EXPECT_FALSE(below->may_match(stats, 5)); + auto below = bind_field(Expression::compare("a", Expression::CompareOp::LT, + Expression::Literal::int64(5))); + EXPECT_EQ(Match::None, below->classify(stats, 5)); - auto overlap = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::LE, - AlignedFieldFilter::Literal::int64(10)); - EXPECT_TRUE(overlap->may_match(stats, 5)); + auto overlap = bind_field(Expression::compare( + "a", Expression::CompareOp::LE, Expression::Literal::int64(10))); + EXPECT_NE(Match::None, overlap->classify(stats, 5)); - auto is_null = AlignedFieldFilter::is_null("a"); - EXPECT_FALSE(is_null->may_match(stats, 5)); + auto is_null = bind_field(Expression::is_null("a")); + EXPECT_EQ(Match::None, is_null->classify(stats, 5)); statistic.count_ = 4; - EXPECT_TRUE(is_null->may_match(stats, 5)); + EXPECT_NE(Match::None, is_null->classify(stats, 5)); + + auto missing = bind_field(Expression::compare( + "missing", Expression::CompareOp::EQ, Expression::Literal::int64(1))); + EXPECT_NE(Match::None, missing->classify(stats, 5)); +} + +TEST(AlignedFieldFilterTest, UnknownRowCountCannotProveWholePageMatches) { + 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 = bind_field(Field::or_filter( + Field::is_not_null("a"), + Field::compare("b", Field::CompareOp::GT, Field::Literal::int64(10)))); - auto missing = AlignedFieldFilter::compare( - "missing", AlignedFieldFilter::CompareOp::EQ, - AlignedFieldFilter::Literal::int64(1)); - EXPECT_TRUE(missing->may_match(stats, 5)); + EXPECT_EQ(Match::Possible, filter->classify(stats, 0)); } TEST(AlignedFieldFilterTest, PageStatisticsAllMatchIsConservative) { @@ -302,67 +344,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)); - EXPECT_TRUE(ge->all_match(stats, 5)); + auto ge = bind_field(Expression::compare("a", Expression::CompareOp::GE, + Expression::Literal::int64(10))); + EXPECT_EQ(Match::All, ge->classify(stats, 5)); - auto lt = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::Literal::int64(21)); - EXPECT_TRUE(lt->all_match(stats, 5)); + auto lt = bind_field(Expression::compare("a", Expression::CompareOp::LT, + Expression::Literal::int64(21))); + EXPECT_EQ(Match::All, lt->classify(stats, 5)); - auto strict_lt = - AlignedFieldFilter::compare("a", AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::Literal::int64(20)); - EXPECT_FALSE(strict_lt->all_match(stats, 5)); + auto strict_lt = bind_field(Expression::compare( + "a", Expression::CompareOp::LT, Expression::Literal::int64(20))); + EXPECT_NE(Match::All, strict_lt->classify(stats, 5)); - auto not_null = AlignedFieldFilter::is_not_null("a"); - EXPECT_TRUE(not_null->all_match(stats, 5)); + auto not_null = bind_field(Expression::is_not_null("a")); + EXPECT_EQ(Match::All, not_null->classify(stats, 5)); statistic.count_ = 4; - EXPECT_FALSE(not_null->all_match(stats, 5)); - auto is_null = AlignedFieldFilter::is_null("a"); + EXPECT_NE(Match::All, not_null->classify(stats, 5)); + auto is_null = bind_field(Expression::is_null("a")); statistic.count_ = 0; - EXPECT_TRUE(is_null->all_match(stats, 5)); + EXPECT_EQ(Match::All, is_null->classify(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")); - EXPECT_TRUE(combined->all_match(stats, 5)); + auto combined = bind_field(Expression::and_filter( + Expression::compare("a", Expression::CompareOp::GE, + Expression::Literal::int64(10)), + Expression::is_not_null("a"))); + EXPECT_EQ(Match::All, combined->classify(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); - EXPECT_TRUE(filter->may_match(stats, 3)); - EXPECT_FALSE(filter->all_match(stats, 3)); - auto negated = AlignedFieldFilter::not_filter( - AlignedFieldFilter::compare("v", op, literal)); - EXPECT_TRUE(negated->may_match(stats, 3)); - EXPECT_FALSE(negated->all_match(stats, 3)); + 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_EQ(Match::Possible, filter->classify(stats, 3)); + auto negated = bind_field( + Expression::not_filter(Expression::compare("v", op, literal)), + literal.type); + EXPECT_EQ(Match::Possible, negated->classify(stats, 3)); } }; FloatStatistic floats; @@ -373,8 +406,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) { @@ -384,22 +417,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)); - EXPECT_TRUE(f->all_match({{"v", &floats}}, 3)); - EXPECT_TRUE(d->all_match({{"v", &doubles}}, 3)); + 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_EQ(Match::All, f->classify({{"v", &floats}}, 3)); + EXPECT_EQ(Match::All, d->classify({{"v", &doubles}}, 3)); auto below = - AlignedFieldFilter::compare("v", AlignedFieldFilter::CompareOp::LT, - AlignedFieldFilter::Literal::float32(0)); - EXPECT_FALSE(below->may_match({{"v", &floats}}, 3)); + bind_field(Expression::compare("v", Expression::CompareOp::LT, + Expression::Literal::float32(0)), + common::FLOAT); + EXPECT_EQ(Match::None, below->classify({{"v", &floats}}, 3)); } TEST(AlignedFieldFilterTest, NegatedFloatingStatisticsPreserveSafeShortcuts) { - using A = AlignedFieldFilter; + using A = Expression; FloatStatistic floats; DoubleStatistic doubles; for (int value : {10, 15, 20}) { @@ -442,34 +476,42 @@ 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)); - EXPECT_EQ(filter->may_match(stats, 3), matches != 0); - EXPECT_EQ(filter->all_match(stats, 3), matches == 3); + auto filter = + bind_field(A::not_filter(A::compare("v", op, literal)), + (is_float ? common::FLOAT : common::DOUBLE)); + EXPECT_EQ(filter->classify(stats, 3) != Match::None, + matches != 0); + EXPECT_EQ(filter->classify(stats, 3) == Match::All, + 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))); - EXPECT_EQ(twice->may_match(stats, 3), - original->may_match(stats, 3)); - EXPECT_EQ(twice->all_match(stats, 3), - original->all_match(stats, 3)); + EXPECT_EQ(filter->classify(stats, 4) != Match::None, + matches != 0); + EXPECT_NE(Match::All, filter->classify(stats, 4)); + 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->classify(stats, 3), + original->classify(stats, 3)); } const auto nan = is_float ? A::Literal::float32( std::numeric_limits::quiet_NaN()) : A::Literal::float64( std::numeric_limits::quiet_NaN()); - auto filter = A::not_filter(A::compare("v", op, nan)); - EXPECT_TRUE(filter->may_match(stats, 3)); - EXPECT_FALSE(filter->all_match(stats, 3)); + auto filter = + bind_field(A::not_filter(A::compare("v", op, nan)), + (is_float ? common::FLOAT : common::DOUBLE)); + EXPECT_EQ(Match::Possible, filter->classify(stats, 3)); } - auto mismatched = A::not_filter( - A::compare("v", A::CompareOp::LT, A::Literal::int32(15))); - EXPECT_TRUE(mismatched->may_match(stats, 3)); - EXPECT_FALSE(mismatched->all_match(stats, 3)); + auto mismatched = + bind_field(A::not_filter(A::compare("v", A::CompareOp::LT, + A::Literal::int32(15))), + common::INT32); + EXPECT_EQ(Match::Possible, mismatched->classify(stats, 3)); } } diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index 923bb920a4..4d672f16a3 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; @@ -29,24 +30,30 @@ class TagFilterTest : public ::testing::Test { protected: void SetUp() override { std::vector column_schemas; - column_schemas.emplace_back("name", common::TSDataType::TEXT, + column_schemas.emplace_back("name", common::TSDataType::STRING, common::ColumnCategory::TAG); - column_schemas.emplace_back("age", common::TSDataType::TEXT, + column_schemas.emplace_back("age", common::TSDataType::STRING, common::ColumnCategory::TAG); - column_schemas.emplace_back("department", common::TSDataType::TEXT, + column_schemas.emplace_back("department", common::TSDataType::STRING, common::ColumnCategory::TAG); - column_schemas.emplace_back("status", common::TSDataType::TEXT, + column_schemas.emplace_back("status", common::TSDataType::STRING, common::ColumnCategory::TAG); - column_schemas.emplace_back("score", common::TSDataType::TEXT, + column_schemas.emplace_back("score", common::TSDataType::STRING, 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 @@ -72,348 +79,326 @@ 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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("alice", "25", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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 = createSegments("alice", "25", "engineering", "active", "95"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "25", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "35", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "25", "engineering", "active", "95"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "35", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "25", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "35", "engineering", "active", "95"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "25", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "30", "engineering", "active", "95"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "35", "engineering", "active", "95"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "20", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "40", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "40", "engineering", "active", "95"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "25", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "30", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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"); - EXPECT_TRUE(and_filter->satisfyRow(0, segments)); + EXPECT_TRUE(and_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "20", "engineering", "active", "95"); - EXPECT_FALSE(and_filter->satisfyRow(0, segments)); + EXPECT_FALSE(and_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "30", "sales", "active", "95"); - EXPECT_FALSE(and_filter->satisfyRow(0, segments)); + EXPECT_FALSE(and_filter->matches(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"); - EXPECT_TRUE(or_filter->satisfyRow(0, segments)); + EXPECT_TRUE(or_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "20", "sales", "active", "95"); - EXPECT_TRUE(or_filter->satisfyRow(0, segments)); + EXPECT_TRUE(or_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "30", "engineering", "active", "95"); - EXPECT_TRUE(or_filter->satisfyRow(0, segments)); + EXPECT_TRUE(or_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "30", "sales", "active", "95"); - EXPECT_FALSE(or_filter->satisfyRow(0, segments)); + EXPECT_FALSE(or_filter->matches(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 = createSegments("john", "30", "engineering", "inactive", "95"); - EXPECT_TRUE(not_filter->satisfyRow(0, segments)); + EXPECT_TRUE(not_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("john", "30", "engineering", "active", "95"); - EXPECT_FALSE(not_filter->satisfyRow(0, segments)); + EXPECT_FALSE(not_filter->matches(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"); - EXPECT_TRUE(complex_filter->satisfyRow(0, segments)); + EXPECT_TRUE(complex_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("alice", "20", "sales", "active", "95"); - EXPECT_TRUE(complex_filter->satisfyRow(0, segments)); + EXPECT_TRUE(complex_filter->matches(segments)); cleanupSegments(segments); segments = createSegments("bob", "20", "sales", "active", "85"); - EXPECT_FALSE(complex_filter->satisfyRow(0, segments)); + EXPECT_FALSE(complex_filter->matches(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; - EXPECT_FALSE(filter->satisfyRow(0, empty_segments)); + EXPECT_FALSE(filter->matches(empty_segments)); std::vector small_segments = {nullptr}; - EXPECT_FALSE(filter->satisfyRow(0, small_segments)); + EXPECT_FALSE(filter->matches(small_segments)); std::vector minimal_segments = {nullptr, new std::string("test")}; - EXPECT_TRUE(filter->satisfyRow(0, minimal_segments)); + EXPECT_TRUE(filter->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, segments)); + EXPECT_TRUE(filter->matches(segments)); cleanupSegments(segments); segments = createSegments("alice", "25", "engineering", "active", "95"); - EXPECT_FALSE(filter->satisfyRow(0, segments)); + EXPECT_FALSE(filter->matches(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)); + EXPECT_TRUE(not_filter->matches(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 + EXPECT_TRUE(complex_or->matches(segments)); // name matches cleanupSegments(segments); segments = createSegments("alice", "25", "engineering", "active", "95"); - EXPECT_TRUE(complex_or->satisfyRow(0, segments)); // age and dept match + EXPECT_TRUE(complex_or->matches(segments)); // age and dept match cleanupSegments(segments); segments = createSegments("bob", "35", "sales", "active", "95"); - EXPECT_FALSE(complex_or->satisfyRow(0, segments)); // no match + EXPECT_FALSE(complex_or->matches(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"); - EXPECT_FALSE( - invalid_filter->satisfyRow(0, segments)); // handles gracefully + EXPECT_FALSE(invalid_filter->matches(segments)); // handles gracefully 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)); + EXPECT_TRUE(empty_filter->matches(segments)); cleanupSegments(segments); - - delete invalid_filter; - delete empty_filter; } // A null tag segment must not crash comparison filters; a null value never @@ -424,77 +409,102 @@ 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", ".*"); - - EXPECT_FALSE(eq->satisfyRow(0, segments)); - EXPECT_FALSE(neq->satisfyRow(0, segments)); - EXPECT_FALSE(lt->satisfyRow(0, segments)); - EXPECT_FALSE(gt->satisfyRow(0, segments)); - EXPECT_FALSE(between->satisfyRow(0, segments)); - EXPECT_FALSE(reg->satisfyRow(0, segments)); - - delete eq; - delete neq; - delete lt; - delete gt; - delete between; - delete reg; + 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->matches(segments)); + EXPECT_FALSE(neq->matches(segments)); + EXPECT_FALSE(lt->matches(segments)); + EXPECT_FALSE(gt->matches(segments)); + EXPECT_FALSE(between->matches(segments)); + EXPECT_FALSE(reg->matches(segments)); + 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. std::vector null_seg = {nullptr, nullptr, new std::string("25"), new std::string("engineering")}; - EXPECT_TRUE(filter->satisfyRow(0, null_seg)); + EXPECT_TRUE(filter->matches(null_seg)); delete null_seg[2]; delete null_seg[3]; // "name" has a concrete value. auto present = createSegments("john", "25", "engineering"); - EXPECT_FALSE(filter->satisfyRow(0, present)); + EXPECT_FALSE(filter->matches(present)); cleanupSegments(present); // 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)); + EXPECT_TRUE(trailing->matches(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"); - EXPECT_TRUE(filter->satisfyRow(0, present)); + EXPECT_TRUE(filter->matches(present)); cleanupSegments(present); std::vector null_seg = {nullptr, nullptr}; - EXPECT_FALSE(filter->satisfyRow(0, null_seg)); + EXPECT_FALSE(filter->matches(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)); + EXPECT_FALSE(trailing->matches(short_seg)); delete short_seg[1]; +} +TEST_F(TagFilterTest, RejectsNonStringTagColumnAtBinding) { + TableSchema schema("t", + {{"id", common::INT64, common::ColumnCategory::TAG}}); + std::unique_ptr bound; + EXPECT_EQ(common::E_NOT_SUPPORT, + TagFilter::bind(*E::is_null("id"), schema, bound)); + EXPECT_EQ(nullptr, bound); +} - delete filter; - delete trailing; -} \ No newline at end of file +TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { + using Field = AlignedFieldFilter; + auto predicate = + E::not_filter(E::compare("name", Op::EQ, Literal::string("x"))); + auto tag = bind(predicate); + ASSERT_NE(nullptr, tag); + Field::Ptr field; + 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->matches({})); + EXPECT_TRUE(tag->matches({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, 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 a7c9aebc07..ef7f13e3a5 100644 --- a/cpp/test/reader/table_field_filter_test.cc +++ b/cpp/test/reader/table_field_filter_test.cc @@ -16,8 +16,6 @@ * specific language governing permissions and limitations * under the License. */ -#include "reader/filter/table_field_filter.h" - #include #include @@ -35,6 +33,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 @@ -46,123 +45,6 @@ namespace { using namespace common; using namespace storage; -using Predicate = std::function; - -class RowPredicate : public TableFieldFilter { - public: - explicit RowPredicate(Predicate predicate) : predicate_(predicate) {} - int satisfy_row(const TableFieldRow& row, bool& accepted) const override { - return predicate_(row, accepted); - } - - private: - Predicate predicate_; -}; - -class LegacyPredicate : public Filter { - public: - int calls = 0; - int64_t time = 0; - int64_t number = 0; - std::string bytes; - bool accept = true; - bool satisfy(int64_t timestamp, int64_t value) override { - ++calls; - time = timestamp; - number = value; - return accept; - } - bool satisfy(int64_t timestamp, String value) override { - ++calls; - time = timestamp; - bytes.assign(value.buf_, value.len_); - return accept; - } -}; - -TEST(TableFieldFilterValueTest, LegacyDispatchPreservesTypesAndBytes) { - LegacyPredicate filter; - bool accepted = false; - const int64_t timestamp = INT64_C(1099511627776); - const std::string name = "v"; - const bool flag = true; - const int32_t small = -123; - const int64_t large = INT64_MIN; - for (TSDataType type : {BOOLEAN, INT32, DATE, INT64, TIMESTAMP}) { - const char* value = type == BOOLEAN - ? reinterpret_cast(&flag) - : type == INT32 || type == DATE - ? reinterpret_cast(&small) - : reinterpret_cast(&large); - const uint32_t size = type == BOOLEAN ? sizeof(flag) - : type == INT32 || type == DATE ? sizeof(small) - : sizeof(large); - std::vector fields{{name, type, value, size}}; - EXPECT_EQ( - evaluate_table_field_filter(filter, {timestamp, fields}, accepted), - E_OK); - EXPECT_TRUE(accepted); - EXPECT_EQ(filter.time, timestamp); - EXPECT_EQ(filter.number, type == BOOLEAN ? 1 - : type == INT32 || type == DATE ? small - : large); - fields[0].size = 0; - EXPECT_EQ( - evaluate_table_field_filter(filter, {timestamp, fields}, accepted), - E_DECODE_ERR); - EXPECT_FALSE(accepted); - } - for (TSDataType type : {STRING, TEXT, BLOB}) { - const std::string bytes("a\0b", 3); - std::vector fields{{name, type, bytes.data(), 3}}; - EXPECT_EQ( - evaluate_table_field_filter(filter, {timestamp, fields}, accepted), - E_OK); - EXPECT_EQ(filter.bytes, bytes); - fields[0].size = 0; - EXPECT_EQ( - evaluate_table_field_filter(filter, {timestamp, fields}, accepted), - E_OK); - EXPECT_TRUE(filter.bytes.empty()); - } -} - -TEST(TableFieldFilterValueTest, InvalidLegacyShapesAndSafeGetters) { - LegacyPredicate filter; - bool accepted = true; - const std::string name = "v"; - int64_t number = 42; - std::vector fields{{name, INT64, nullptr, 8}}; - EXPECT_EQ(evaluate_table_field_filter(filter, {0, fields}, accepted), E_OK); - EXPECT_FALSE(accepted); - EXPECT_EQ(filter.calls, 0); - int64_t output = 7; - EXPECT_FALSE(fields[0].get(output)); - fields[0].data = reinterpret_cast(&number); - EXPECT_TRUE(fields[0].get(output)); - EXPECT_EQ(output, 42); - float wrong_type = 0; - EXPECT_FALSE(fields[0].get(wrong_type)); - fields[0].size = sizeof(int32_t); - int32_t truncated = 0; - EXPECT_FALSE(fields[0].get(truncated)); - fields[0].type = DOUBLE; - EXPECT_FALSE(fields[0].get(wrong_type)); - fields[0].type = FLOAT; - EXPECT_EQ(evaluate_table_field_filter(filter, {0, fields}, accepted), - E_NOT_SUPPORT); - fields.clear(); - EXPECT_EQ(evaluate_table_field_filter(filter, {0, fields}, accepted), - E_NOT_SUPPORT); - fields.push_back({name, INT64, nullptr, 0}); - fields.push_back({name, INT64, nullptr, 0}); - EXPECT_EQ(evaluate_table_field_filter(filter, {0, fields}, accepted), - E_NOT_SUPPORT); - EXPECT_EQ((TableFieldRow{0, fields}).find("absent"), nullptr); -} - -// A small page and explicit flush force rejection/acceptance at page and -// chunk boundaries. Both devices contain sparse NULLs and binary values. class TableFieldFilterTest : public ::testing::TestWithParam> { protected: @@ -265,18 +147,22 @@ class TableFieldFilterTest g_config_value_ = saved_; libtsfile_destroy(); } - 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; + std::vector scan_field(const std::vector& columns, + Expression::Ptr expr, int offset = 0, + int limit = -1, Filter* time = nullptr, + const Expression* tag = 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, tag, filter, offset, limit, - result), + EXPECT_EQ(executor.query("t", columns, time, offset, limit, result, tag, + expr.get()), E_OK); + return read_times(executor, result, E_OK); + } + 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; @@ -323,18 +209,95 @@ class TableFieldFilterTest const int64_t base_ = INT64_C(1099511627776); }; -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)); +TEST_P(TableFieldFilterTest, ResultOwnsTagAndFieldBindings) { + 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; + ASSERT_EQ(E_OK, reader.queryByRow("t", {"i"}, 0, -1, table, tag.get(), + field.get())); + tag.reset(); + field.reset(); + bool next = false; + ASSERT_EQ(E_OK, table->next(next)); + ASSERT_TRUE(next); + EXPECT_EQ(base_ + 5, table->get_value(1)); + ASSERT_EQ(E_OK, table->next(next)); + EXPECT_FALSE(next); + reader.destroy_query_data_set(table); +} - EXPECT_EQ(scan({"v"}, filter.release()), expected([](int t) { +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_)); + auto tag = Expression::compare("id", Expression::CompareOp::EQ, + Expression::Literal::string("d1")); + TableSchema schema("other", {{"unused", STRING, ColumnCategory::TAG}, + {"id", STRING, ColumnCategory::TAG}}); + std::unique_ptr bound; + ASSERT_EQ(E_OK, TagFilter::bind(*tag, schema, bound)); + std::string d0 = "d0", d1 = "d1"; + EXPECT_TRUE(bound->matches({nullptr, &d0, &d1})); + EXPECT_FALSE(bound->matches({nullptr, &d1, &d0})); + ResultSet* rows = nullptr; + 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)); + 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, rows, wrong.get(), nullptr)); + EXPECT_EQ(nullptr, rows); + wrong = Expression::is_null("id"); + EXPECT_EQ(E_INVALID_ARG, + reader.query("t", {"v"}, 0, 0, rows, nullptr, wrong.get())); + EXPECT_EQ(nullptr, rows); +} + +TEST_P(TableFieldFilterTest, AlignedBatchFilterAndOrUsesFilterOnlyColumns) { + 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; @@ -342,351 +305,121 @@ 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; })); } -TEST_P(TableFieldFilterTest, NullTrueFalseAndRejectWholePages) { - EXPECT_EQ(scan({"v"}, nullptr), expected([](int) { return true; })); - for (bool accept : {false, true}) { - int calls = 0; - auto* filter = new RowPredicate([&](const TableFieldRow&, bool& ok) { - ++calls; - ok = accept; - return E_OK; - }); - EXPECT_EQ(scan({"v"}, filter), - expected([accept](int) { return accept; })); - EXPECT_EQ(calls, 28); - } - int calls = 0; - EXPECT_EQ( - scan({"v"}, new RowPredicate([&](const TableFieldRow& row, bool& ok) { - ++calls; - ok = row.timestamp >= base_ + 10; - return E_OK; - })), - expected([](int t) { return t >= 10; })); - EXPECT_EQ(calls, 28); - // Preserve the original ordinary Filter callback as well. - auto* reject = new LegacyPredicate(); - reject->accept = false; - EXPECT_TRUE(scan({"v"}, reject).empty()); - EXPECT_EQ(scan({"v"}, new LegacyPredicate()), - expected([](int) { return true; })); -} - -TEST_P(TableFieldFilterTest, TypedRowsPreserveNullsFloatsBinaryAndTimestamp) { - int calls = 0; - const std::vector columns{"id", "v", "i", "flag", - "f", "d", "s", "text", - "blob", "date", "stamp", "v"}; - auto* filter = new RowPredicate([&](const TableFieldRow& row, bool& ok) { - ++calls; - const int t = int(row.timestamp - base_); - EXPECT_EQ(row.fields.size(), - 10u); // Duplicate projections are one FIELD. - EXPECT_EQ(row.find("id"), nullptr); - int64_t v = 0, stamp = 0; - EXPECT_TRUE(row.find("v")->get(v)); - EXPECT_TRUE(v == t || v == 100 + t); - EXPECT_TRUE(row.find("stamp")->get(stamp)); - EXPECT_EQ(stamp, -row.timestamp); - const auto* i = row.find("i"); - EXPECT_EQ(i->is_null(), t % 3 == 0); - int32_t integer = 0; - EXPECT_EQ(i->get(integer), t % 3 != 0); - if (!i->is_null()) EXPECT_EQ(integer, -t); - float f = 0; - double d = 0; - bool flag = false; - int32_t date = 0; - EXPECT_TRUE(row.find("f")->get(f)); - EXPECT_EQ(f, float(t) + 0.25f); - EXPECT_TRUE(row.find("d")->get(d)); - EXPECT_EQ(d, -double(t) - 0.5); - EXPECT_TRUE(row.find("flag")->get(flag)); - EXPECT_EQ(flag, bool(t % 2)); - EXPECT_TRUE(row.find("date")->get(date)); - EXPECT_EQ(date, 20260101 + t); - for (const std::string& name : {"s", "text", "blob"}) { - const auto* value = row.find(name); - EXPECT_FALSE(value->is_null()); - EXPECT_EQ(std::string(value->data, value->size), - t % 2 ? std::string("a\0b", 3) : std::string()); - } - ok = i->is_null() || (v % 2 == 0 && f > 4); - return E_OK; - }); - EXPECT_EQ(scan(columns, filter), expected([](int t) { - return t % 3 == 0 || (t % 2 == 0 && t >= 4); - })); - EXPECT_EQ(calls, 28); -} - -TEST_P(TableFieldFilterTest, OffsetLimitApplyAfterFilterAcrossDevices) { - auto all = expected([](int t) { return t % 2 == 1; }); - for (int offset : {0, 3, 8, 20}) { - for (int limit : {0, 1, 5, -1}) { - 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"}, - new RowPredicate([](const TableFieldRow& row, bool& ok) { - int64_t v = 0; - row.find("v")->get(v); - ok = v % 2 == 1; - return E_OK; - }), - offset, limit), - wanted); - } - } -} - TEST_P(TableFieldFilterTest, TimeAndTagFiltersComposeWithFieldFilter) { - auto* time = TimeFilter::gt_eq(base_ + 5); - TagEq tag(1, "d1"); - EXPECT_EQ(scan({"id", "v"}, - new RowPredicate([](const TableFieldRow& row, bool& ok) { - int64_t v = 0; - row.find("v")->get(v); - ok = v >= 100 && v % 2 == 0; - return E_OK; - }), - 1, 3, time, &tag), + auto tag = Expression::compare("id", Expression::CompareOp::EQ, + Expression::Literal::string("d1")); + auto field = Expression::compare("flag", Expression::CompareOp::EQ, + Expression::Literal::boolean(false)); + EXPECT_EQ(scan_field({"id", "v"}, std::move(field), 1, 3, + TimeFilter::gt_eq(base_ + 5), tag.get()), std::vector({base_ + 8, base_ + 10, base_ + 12})); } -TEST_P(TableFieldFilterTest, CallbackErrorsAreTerminal) { - int calls = 0; - auto* filter = new RowPredicate([&](const TableFieldRow&, bool& ok) { - ok = true; - return ++calls == 5 ? E_DECODE_ERR : E_OK; - }); - scan({"v"}, filter, 0, -1, nullptr, nullptr, E_DECODE_ERR); - EXPECT_EQ(calls, 5); - scan({"f"}, new LegacyPredicate(), 0, -1, nullptr, nullptr, E_NOT_SUPPORT); - scan({"v", "i"}, new LegacyPredicate(), 0, -1, nullptr, nullptr, - E_NOT_SUPPORT); -} - -TEST_P(TableFieldFilterTest, LegacyNullAndAllIntegerStringTypes) { - EXPECT_EQ(scan({"i"}, new LegacyPredicate()), - expected([](int t) { return t % 3 != 0; })); - for (const std::string& name : - {"flag", "date", "stamp", "s", "text", "blob"}) - EXPECT_EQ(scan({name}, new LegacyPredicate()), - expected([](int) { return true; })); -} - -TEST_P(TableFieldFilterTest, AllNullFieldDoesNotSuppressOtherFields) { - int calls = 0; - EXPECT_EQ(scan({"v", "empty"}, - new RowPredicate([&](const TableFieldRow& row, bool& ok) { - ++calls; - const auto* empty = row.find("empty"); - EXPECT_NE(empty, nullptr); - if (!empty) return E_DECODE_ERR; - EXPECT_EQ(empty->type, INT64); - EXPECT_TRUE(empty->is_null()); - int64_t v = 0; - EXPECT_TRUE(row.find("v")->get(v)); - ok = v % 2 == 0; - return E_OK; - })), - expected([](int t) { return t % 2 == 0; })); - EXPECT_EQ(calls, 28); -} - -TEST_P(TableFieldFilterTest, TimeOnlyRowsDoNotInventFieldValues) { - int calls = 0; - EXPECT_EQ( - scan({"id"}, new RowPredicate([&](const TableFieldRow& row, bool& ok) { - ++calls; - EXPECT_TRUE(row.fields.empty()); - EXPECT_EQ(row.find("v"), nullptr); - ok = row.timestamp >= base_ + 10; - return E_OK; - })), - expected([](int t) { return t >= 10; })); - EXPECT_EQ(calls, 28); -} - TEST_P(TableFieldFilterTest, NullRowsOutsideValueStatisticsReachPredicate) { - int calls = 0; - auto* filter = new RowPredicate([&](const TableFieldRow& row, bool& ok) { - ++calls; - const auto* field = row.find("tail_null"); - EXPECT_NE(field, nullptr); - ok = field != nullptr && field->is_null(); - return E_OK; - }); - // Each page starts with one non-NULL value followed by NULLs. The first - // value page has range [base, base], but its time page includes base+1/2. - EXPECT_EQ(scan({"tail_null"}, filter, 0, -1, - TimeFilter::between(base_ + 1, base_ + 2, false)), + EXPECT_EQ(scan_field({"tail_null"}, Expression::is_null("tail_null"), 0, -1, + TimeFilter::between(base_ + 1, base_ + 2, false)), expected([](int t) { return t == 1 || t == 2; })); - EXPECT_EQ(calls, 4); } -TEST_P(TableFieldFilterTest, NullBooleanRowsRespectTimeBeforeFieldAndOffset) { - for (int offset : {0, 1}) { - int calls = 0; - auto* filter = - new RowPredicate([&](const TableFieldRow& row, bool& ok) { - ++calls; - EXPECT_GE(row.timestamp, base_ + 1); - EXPECT_LE(row.timestamp, base_ + 2); - bool value = false; - const auto* field = row.find("nullable_flag"); - EXPECT_NE(field, nullptr); - EXPECT_TRUE(field != nullptr && field->get(value)); - ok = true; - return E_OK; - }); - std::vector wanted = - offset == 0 ? expected([](int t) { return t == 1 || t == 2; }) - : std::vector{base_ + 2, base_ + 1}; - EXPECT_EQ(scan({"nullable_flag"}, filter, offset, offset == 0 ? -1 : 2, - TimeFilter::between(base_ + 1, base_ + 2, false)), - wanted); - EXPECT_GE(calls, int(wanted.size())); +TEST_P(TableFieldFilterTest, + TypedFieldsSupportFilterOnlyAndDuplicateProjection) { + using Op = Expression::CompareOp; + using Literal = Expression::Literal; + for (const auto& name : {"s", "text", "blob"}) { + auto predicate = Expression::and_filter( + Expression::compare(name, Op::EQ, + Literal::string(std::string("a\0b", 3))), + Expression::and_filter( + Expression::compare("d", Op::LE, Literal::float64(-4.5)), + Expression::compare("f", Op::LT, Literal::float32(10.25f)))); + EXPECT_EQ(scan_field({"v", "v"}, std::move(predicate)), + expected([](int t) { return t % 2 && t >= 4 && t < 10; })); } + auto date = Expression::compare("date", Op::GE, Literal::int32(20260105)); + auto stamp = + Expression::compare("stamp", Op::GE, Literal::int64(-base_ - 9)); + EXPECT_EQ(scan_field({"id"}, Expression::and_filter(std::move(date), + std::move(stamp))), + expected([](int t) { return t >= 4 && t <= 9; })); } -TEST_P(TableFieldFilterTest, OnlyAllNullFieldStillSuppliesTimestampRows) { - for (bool accept : {true, false}) { - int calls = 0; - auto* filter = - new RowPredicate([&](const TableFieldRow& row, bool& ok) { - ++calls; - EXPECT_EQ(row.fields.size(), 1u); - const auto* empty = row.find("empty"); - EXPECT_NE(empty, nullptr); - if (!empty) return E_DECODE_ERR; - EXPECT_EQ(empty->type, INT64); - EXPECT_TRUE(empty->is_null()); - ok = accept && empty->is_null(); - return E_OK; - }); - EXPECT_EQ(scan({"empty"}, filter), - expected([accept](int) { return accept; })); - EXPECT_EQ(calls, 28); - } - // Legacy value predicates reject NULL instead of receiving a made-up 0. - EXPECT_TRUE(scan({"empty"}, new LegacyPredicate()).empty()); -} - -TEST_P(TableFieldFilterTest, NullOnlyChunkInTimeRangeReachesPredicate) { - int calls = 0; - auto predicate = [&calls]() -> Filter* { - return new RowPredicate([&calls](const TableFieldRow& row, bool& ok) { - ++calls; - const auto* field = row.find("chunk_null"); - ok = field != nullptr && field->is_null(); - return E_OK; - }); - }; - EXPECT_EQ(scan({"chunk_null"}, predicate()), - expected([](int t) { return t >= 7; })); - EXPECT_EQ(calls, 28); - calls = 0; - EXPECT_EQ(scan({"chunk_null"}, predicate(), 0, -1, - TimeFilter::between(base_ + 7, base_ + 13, false)), +TEST_P(TableFieldFilterTest, NullOnlyChunksAndAcceptedRowPagination) { + EXPECT_EQ(scan_field({"chunk_null"}, Expression::is_null("chunk_null")), expected([](int t) { return t >= 7; })); - EXPECT_EQ(calls, 14); -} - -TEST_P(TableFieldFilterTest, AllNullProjectionAppliesTimeOffsetLimit) { - auto predicate = []() -> Filter* { - return new RowPredicate([](const TableFieldRow& row, bool& ok) { - const auto* field = row.find("empty"); - ok = field != nullptr && field->is_null(); - return E_OK; - }); - }; - EXPECT_EQ(scan({"empty"}, predicate(), 15, 2), + EXPECT_EQ(scan_field({"empty"}, Expression::is_null("empty"), 15, 2), std::vector({base_ + 1, base_ + 2})); - EXPECT_EQ(scan({"empty"}, predicate(), 1, 2, - TimeFilter::between(base_ + 1, base_ + 2, false)), + EXPECT_EQ(scan_field({"empty"}, Expression::is_null("empty"), 1, 2, + TimeFilter::between(base_ + 1, base_ + 2, false)), std::vector({base_ + 2, base_ + 1})); - EXPECT_TRUE(scan({"empty"}, predicate(), 0, -1, - TimeFilter::between(base_ + 20, base_ + 21, false)) - .empty()); + EXPECT_TRUE( + scan_field({"empty"}, Expression::is_not_null("empty")).empty()); } INSTANTIATE_TEST_SUITE_P(RowAndBatchParallelModes, TableFieldFilterTest, diff --git a/cpp/test/reader/table_read_failure_test.cc b/cpp/test/reader/table_read_failure_test.cc index 99d02669be..18f0f2a15e 100644 --- a/cpp/test/reader/table_read_failure_test.cc +++ b/cpp/test/reader/table_read_failure_test.cc @@ -195,10 +195,13 @@ class TableReadFailureTest reader.open(std::unique_ptr(source)), common::E_OK); out.open_reads = source->reads; - storage::TagEq eq(1, "d0"); + using storage::Expression; + auto eq = Expression::compare("id0", Expression::CompareOp::EQ, + Expression::Literal::string("d0")); storage::ResultSet* result = nullptr; - out.ret = reader.query("test", {"id0", "value"}, 0, INT64_MAX, result, - filter ? &eq : nullptr, batch_size); + out.ret = + reader.query("test", {"id0", "value"}, 0, INT64_MAX, result, + filter ? eq.get() : nullptr, nullptr, batch_size); if (out.ret == common::E_OK) { ASSERT_NE(result, nullptr); bool next = false; @@ -855,17 +858,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 9cc236cba9..47bfe58e6e 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; } }; @@ -359,8 +359,8 @@ TEST_P(TsFileTableReaderTimeFilterTest, QueryContinuesAfterEmptyPageInChunk) { // The second filter also checks exhaustion after two empty pages. ResultSet* raw_result = nullptr; ASSERT_EQ(executor.query(table_schema->get_table_name(), columns, - new TimeIn(selected_times, false), nullptr, - nullptr, raw_result), + new TimeIn(selected_times, false), 0, -1, + raw_result), common::E_OK); std::unique_ptr result(raw_result); ASSERT_NE(result, nullptr); @@ -508,8 +508,8 @@ TEST_P(TsFileTableReaderTimeFilterTest, NotBetweenFullRangeReturnsNoRows) { ASSERT_EQ(executor.query( table_schema->get_table_name(), std::vector{"s0", "s1"}, - new TimeBetween(min_time, max_time, /*not_between=*/true), - nullptr, nullptr, 0, -1, result), + new TimeBetween(min_time, max_time, /*not_between=*/true), 0, + -1, result), common::E_OK); ASSERT_NE(nullptr, result); bool has_next = false; @@ -587,9 +587,9 @@ TEST_P(TsFileTableReaderTimeFilterTest, const std::vector query_columns{"v", "ghost", "w", "v"}; auto collect_times = [&](Filter* time_filter, std::vector& times) { ResultSet* result = nullptr; - ASSERT_EQ(executor.query("t", query_columns, time_filter, nullptr, - nullptr, 0, -1, result), - common::E_OK); + ASSERT_EQ( + executor.query("t", query_columns, time_filter, 0, -1, result), + common::E_OK); bool has_next = false; int ret = common::E_OK; while ((ret = result->next(has_next)) == common::E_OK && has_next) { @@ -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,56 @@ 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; +} + +TEST_F(TsFileTableReaderTest, + TagEqualityIncludesDevicesWithAndWithoutTrailingTag) { + TableSchema schema("t", {{"site", STRING, ColumnCategory::TAG}, + {"line", STRING, ColumnCategory::TAG}, + {"v", INT64, ColumnCategory::FIELD}}); + { + TsFileTableWriter writer(&write_file_, &schema); + Tablet partial("t", {"site", "v"}, {STRING, INT64}, + {ColumnCategory::TAG, ColumnCategory::FIELD}, 1); + ASSERT_EQ(E_OK, partial.add_timestamp(0, 1)); + ASSERT_EQ(E_OK, partial.add_value(0, "site", "A")); + ASSERT_EQ(E_OK, partial.add_value(0, "v", int64_t(101))); + ASSERT_EQ(E_OK, writer.write_table(partial)); + + Tablet full("t", schema.get_measurement_names(), + schema.get_data_types(), schema.get_column_categories(), 2); + for (int i = 0; i < 2; ++i) { + ASSERT_EQ(E_OK, full.add_timestamp(i, i + 2)); + ASSERT_EQ(E_OK, full.add_value(i, "site", i == 0 ? "A" : "C")); + ASSERT_EQ(E_OK, full.add_value(i, "line", "B")); + ASSERT_EQ(E_OK, full.add_value(i, "v", int64_t(102 + i))); + } + ASSERT_EQ(E_OK, writer.write_table(full)); + ASSERT_EQ(E_OK, writer.close()); + } + + TsFileReader reader; + ASSERT_EQ(E_OK, reader.open(file_name_)); + auto site = Expression::compare("site", Expression::CompareOp::EQ, + Expression::Literal::string("A")); + auto line = Expression::compare("line", Expression::CompareOp::EQ, + Expression::Literal::string("B")); + std::shared_ptr prepared; + EXPECT_EQ(E_NOT_SUPPORT, + reader.prepare_table_series("t", "v", site.get(), prepared)); + EXPECT_FALSE(prepared); + ResultSet* rows = nullptr; + ASSERT_EQ(E_OK, reader.queryByRow("t", {"v"}, 0, -1, rows, site.get())); + std::vector values; + bool more = false; + int ret; + while ((ret = rows->next(more)) == E_OK && more) + values.push_back(rows->get_value(2)); + EXPECT_EQ(E_OK, ret); + EXPECT_EQ((std::vector{101, 102}), values); + reader.destroy_query_data_set(rows); + auto complete = Expression::and_filter(std::move(site), std::move(line)); + EXPECT_EQ(E_OK, + reader.prepare_table_series("t", "v", complete.get(), prepared)); + EXPECT_TRUE(prepared); } diff --git a/cpp/test/tools/model_format_e2e_test.cc b/cpp/test/tools/model_format_e2e_test.cc index bbd2ba7c90..d12f5499a5 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 d7cd018c06..52a3d20b99 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,11 +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. int validate_row_query_names(const ParsedArgs& args, diff --git a/cpp/tools/commands/row_query.cc b/cpp/tools/commands/row_query.cc index 04908a8dfc..f1708fa209 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,18 @@ 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 +267,38 @@ 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 +373,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 +382,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/packaging/README.md b/packaging/README.md index 449a1ee1c7..a84531f2d7 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -237,7 +237,7 @@ plus an external CMake SDK consumer before producing `tsfile--windows-arm64.zip`. Each archive is one combined ZIP rather than one archive per CPack component, and contains the runtime, development files, and tools under a relocatable prefix. The MSVC outputs are -installed as `bin/tsfile.dll`, `lib/tsfile.lib`, and `bin/tsfile-cli.exe`. +installed as `bin/tsfile-2.dll`, `lib/tsfile.lib`, and `bin/tsfile-cli.exe`. The portable ZIP targets Windows 10 / Windows Server 2022 or newer and uses the static MSVC runtime (`/MT`) in Release. `TSFILE_MSVC_STATIC_RUNTIME=ON` @@ -256,7 +256,7 @@ compiler used to build that architecture and `/MT` NEW before `project()`). Keep allocation and release paired through the public APIs; CRT-owned objects such as `FILE*` must not cross DLL boundaries. The installed-consumer fixture demonstrates a public setting/getter round trip -that requires real symbols from `tsfile.dll`. +that requires real symbols from `tsfile-2.dll`. The workflow uploads the ZIPs as `native-windows-msvc-x86_64` and `native-windows-msvc-arm64` for 14 days. Like the Linux jobs, it validates the diff --git a/packaging/scripts/check_python_wheel.py b/packaging/scripts/check_python_wheel.py index 1ff57ec1bd..d018199913 100644 --- a/packaging/scripts/check_python_wheel.py +++ b/packaging/scripts/check_python_wheel.py @@ -96,7 +96,7 @@ def check_wheel(path, expected_version=None): name for name in names if Path(name).name.startswith("libtsfile") - or Path(name).name == "tsfile.dll" + or Path(name).match("tsfile-*.dll") ] if len(native) != 1: raise ValueError(f"Expected one TsFile runtime library in {path}: {native}") diff --git a/packaging/tests/go_installed_tests.py b/packaging/tests/go_installed_tests.py index 05667d9fb0..5535282239 100644 --- a/packaging/tests/go_installed_tests.py +++ b/packaging/tests/go_installed_tests.py @@ -91,8 +91,8 @@ def main(): triple = {"amd64": "x86_64", "arm64": "aarch64"}[goarch] + "-w64-mingw32" environment["CC"] = (tools / f"{triple}-clang.exe").as_posix() environment["CXX"] = (tools / f"{triple}-clang++.exe").as_posix() - dlls = [prefix / "bin" / name for name in ("tsfile.dll", "libtsfile.dll")] - dlls = [dll for dll in dlls if dll.is_file()] + bin_dir = prefix / "bin" + dlls = [*bin_dir.glob("tsfile-*.dll"), *bin_dir.glob("libtsfile-*.dll")] if len(dlls) != 1: raise ValueError(f"Expected one installed TsFile DLL: {dlls}") dll = dlls[0] diff --git a/packaging/tests/test_python_wheel_contents.py b/packaging/tests/test_python_wheel_contents.py index 16898491ce..41d17ccb1f 100644 --- a/packaging/tests/test_python_wheel_contents.py +++ b/packaging/tests/test_python_wheel_contents.py @@ -51,6 +51,11 @@ def test_runtime_only_wheel_is_accepted(self): } ) + def test_windows_abi_versioned_runtime_is_accepted(self): + for runtime in ("tsfile-2.dll", "libtsfile-2.dll"): + with self.subTest(runtime=runtime): + self.check({f"tsfile/{runtime}": b"native", "tsfile/reader.pyd": b"binding"}) + def test_development_wheel_filename_and_metadata_must_match_requested_version(self): for expected in ("2.5.1.dev0", "2.5.1.dev2"): for filename_version, directory_version, metadata_version in ( @@ -96,7 +101,7 @@ def test_sdk_headers_and_import_libraries_are_rejected(self): with self.subTest(name=name), self.assertRaisesRegex( ValueError, "Build-only" ): - self.check({"tsfile/tsfile.dll": b"native", name: b"build-input"}) + self.check({"tsfile/tsfile-2.dll": b"native", name: b"build-input"}) def test_library_alias_copies_are_rejected(self): with self.assertRaisesRegex(ValueError, "one TsFile runtime library"): diff --git a/packaging/tests/test_sdk_build_config.py b/packaging/tests/test_sdk_build_config.py index af889450f7..eac23ef069 100644 --- a/packaging/tests/test_sdk_build_config.py +++ b/packaging/tests/test_sdk_build_config.py @@ -141,15 +141,15 @@ def test_staging_one_soname_removes_stale_alias_copies(self): root = Path(temporary) package = root / "tsfile" package.mkdir() - source = root / "libtsfile.so.2.5.0" - source.write_bytes(b"native-library") + (root / "libtsfile.so.1").write_bytes(b"old-abi") + (root / "libtsfile.so.2").write_bytes(b"current-abi") for name in ("libtsfile.so", "libtsfile.so.1", "libtsfile.so.2.5.0"): (package / name).write_bytes(b"old-copy") target = support.copy_runtime_library( - package, source, {"runtime_library": "libtsfile.so.1"} + package, root, {"runtime_library": "libtsfile.so.2"} ) - self.assertEqual([p.name for p in package.iterdir()], ["libtsfile.so.1"]) - self.assertEqual(target.read_bytes(), source.read_bytes()) + self.assertEqual([p.name for p in package.iterdir()], ["libtsfile.so.2"]) + self.assertEqual(target.read_bytes(), b"current-abi") def test_runtime_filename_cannot_escape_package(self): with tempfile.TemporaryDirectory() as temporary: diff --git a/python/_build_support.py b/python/_build_support.py index e2a22395fb..b53e807d15 100644 --- a/python/_build_support.py +++ b/python/_build_support.py @@ -73,14 +73,14 @@ def msvc_runtime_flag(config): return MSVC_RUNTIME_FLAGS[runtime] -def copy_runtime_library(package, library, config): +def copy_runtime_library(package, library_dir, config): package = Path(package) # Repeated ABI builds must not retain aliases from an earlier SDK view. - for pattern in ("libtsfile.so*", "libtsfile*.dylib", "tsfile.dll", "libtsfile.dll"): + for pattern in ("libtsfile.so*", "libtsfile*.dylib", "tsfile*.dll", "libtsfile*.dll"): for stale in package.glob(pattern): stale.unlink() target = package / config["runtime_library"] - shutil.copy2(library, target) + shutil.copy2(Path(library_dir) / config["runtime_library"], target) return target @@ -107,7 +107,8 @@ def strip_wheel_binaries(build_lib, platform): def is_runtime_library(path): - return Path(path).name.startswith(("libtsfile", "tsfile.dll")) + name = Path(path).name + return name.startswith("libtsfile") or (name.startswith("tsfile") and name.endswith(".dll")) def native_binaries(root): diff --git a/python/pyproject.toml b/python/pyproject.toml index eda59bd65e..3717e29512 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -69,8 +69,8 @@ namespaces = false tsfile = [ "libtsfile.so*", "libtsfile*.dylib", - "tsfile.dll", - "libtsfile.dll", + "tsfile-*.dll", + "libtsfile-*.dll", "libstdc++-6.dll", "libgcc_s_seh-1.dll", "libwinpthread-1.dll", diff --git a/python/setup.py b/python/setup.py index ecda8a3312..0aa4204fc4 100644 --- a/python/setup.py +++ b/python/setup.py @@ -118,30 +118,23 @@ def _find_lib(root, patterns): runtime_lib_dst = None if sys.platform.startswith("linux"): - candidates = sorted( - CPP_LIB.rglob("libtsfile.so*"), key=lambda p: len(p.name), reverse=True - ) - if not candidates: - raise FileNotFoundError("missing libtsfile.so* in build output") - src = candidates[0] + src = _find_lib(CPP_LIB, ["libtsfile.so"]) + if src is None: + raise FileNotFoundError("missing libtsfile.so in build output") sdk_config = read_sdk_config(CPP_OUT, src) - runtime_lib_dst = copy_runtime_library(PKG, src, sdk_config) native_link_dir = src.parent + runtime_lib_dst = copy_runtime_library(PKG, native_link_dir, sdk_config) elif sys.platform == "darwin": - candidates = sorted(CPP_LIB.rglob("libtsfile.*.dylib")) or list( - CPP_LIB.rglob("libtsfile.dylib") - ) - if not candidates: - raise FileNotFoundError("missing libtsfile*.dylib in build output") - src = candidates[0] + src = _find_lib(CPP_LIB, ["libtsfile.dylib"]) + if src is None: + raise FileNotFoundError("missing libtsfile.dylib in build output") sdk_config = read_sdk_config(CPP_OUT, src) - runtime_lib_dst = copy_runtime_library(PKG, src, sdk_config) native_link_dir = src.parent + runtime_lib_dst = copy_runtime_library(PKG, native_link_dir, sdk_config) elif sys.platform == "win32": - # The shared library is named tsfile.dll (MSVC) or libtsfile.dll (MinGW). - dll_src = _find_lib(CPP_LIB, ["tsfile*.dll", "libtsfile*.dll"]) + dll_src = _find_lib(CPP_LIB, ["tsfile-*.dll", "libtsfile-*.dll"]) if dll_src is None: raise FileNotFoundError(f"missing tsfile DLL in build output: {CPP_LIB}") @@ -159,16 +152,13 @@ def _find_lib(root, patterns): f"missing tsfile import library (*.lib or *.dll.a) in {CPP_LIB}" ) - # For MSVC the DLL is already named tsfile.dll. For MinGW, keep the original - # name (libtsfile.dll): the import library (libtsfile.dll.a) has that name - # baked in, so Cython .pyd files record "libtsfile.dll" in their PE import - # table and Windows must find it by that exact name at runtime. + # Preserve the ABI-specific DLL name recorded in each PE import table. sdk_config = read_sdk_config(CPP_OUT, dll_src) - dll_dst = copy_runtime_library(PKG, dll_src, sdk_config) + dll_dst = copy_runtime_library(PKG, dll_src.parent, sdk_config) runtime_lib_dst = dll_dst native_link_dir = PKG - # Copy import library with a name matching the DLL. + # The extension links with the unversioned import library name. if win_toolchain == "mingw": imp_dst = PKG / "tsfile.dll.a" else: @@ -180,13 +170,13 @@ def _find_lib(root, patterns): ) if win_toolchain == "mingw": - # Copy MinGW runtime DLLs next to tsfile.dll so Python can find them. + # Copy MinGW runtime DLLs next to the TsFile DLL so Python can find them. # Python 3.8+ does not search PATH for DLLs; they must sit in the # same directory as the .pyd extensions (os.add_dll_directory). # Prefer runtime DLLs captured from the same MSYS2 environment that - # built libtsfile.dll. Mixing MinGW runtime DLLs from a different + # built the TsFile DLL. Mixing MinGW runtime DLLs from a different # install can load successfully but fail later with WinError 127 when - # libtsfile.dll imports a newer runtime symbol. + # the TsFile DLL imports a newer runtime symbol. _mingw_search_dirs = [CPP_LIB] for _dir in os.environ.get("PATH", "").split(os.pathsep): if _dir: @@ -322,7 +312,7 @@ def finalize_options(self): elif sys.platform == "win32": if win_toolchain == "mingw": # Resolve EH/runtime symbols from MinGW runtimes before libtsfile.dll.a. - # Otherwise _Unwind_Resume is recorded against libtsfile.dll and loading + # Otherwise _Unwind_Resume is recorded against the TsFile DLL and loading # the .pyd fails with WinError 127 on Windows. libraries = ["gcc_s", "stdc++", "tsfile"] extra_compile_args += [ diff --git a/python/tsfile/__init__.py b/python/tsfile/__init__.py index b15634ddc0..da5772cbae 100644 --- a/python/tsfile/__init__.py +++ b/python/tsfile/__init__.py @@ -37,7 +37,7 @@ def _preload_dll(path): # counting frees the object immediately if not stored, which calls # RemoveDllDirectory and undoes the registration before any .pyd is loaded. _dll_dir = os.add_dll_directory(_pkg_dir) - # Preload MinGW runtime DLLs before libtsfile.dll. Python 3.8+ does not + # Preload MinGW runtime DLLs before the TsFile DLL. Python 3.8+ does not # search PATH for DLL dependencies; they must live next to the extensions. for _mingw_dll in ( "libwinpthread-1.dll", @@ -45,19 +45,18 @@ def _preload_dll(path): "libstdc++-6.dll", ): _preload_dll(os.path.join(_pkg_dir, _mingw_dll)) - # Preload the tsfile DLL so Windows finds it when loading Cython extensions. - # MSVC builds produce "tsfile.dll"; MinGW builds produce "libtsfile.dll". - _tsfile_cdll = None - for _dll_name in ("tsfile.dll", "libtsfile.dll"): - _tsfile_dll = os.path.join(_pkg_dir, _dll_name) - if os.path.isfile(_tsfile_dll): - _tsfile_cdll = ctypes.CDLL(_tsfile_dll) - break - else: - raise FileNotFoundError( - f"tsfile DLL (tsfile.dll or libtsfile.dll) not found in {_pkg_dir}. " - "Re-build the C++ module and reinstall the Python package." + # The import library records the ABI-specific name in each extension. + from pathlib import Path as _Path + + _native_dlls = [ + *_Path(_pkg_dir).glob("tsfile-*.dll"), + *_Path(_pkg_dir).glob("libtsfile-*.dll"), + ] + if len(_native_dlls) != 1: + raise ImportError( + f"Expected one TsFile runtime DLL in {_pkg_dir}, found {_native_dlls}" ) + _tsfile_cdll = ctypes.CDLL(str(_native_dlls[0])) elif sys.platform == "darwin": _tsfile_dylib = os.path.join(_pkg_dir, "libtsfile.dylib") if os.path.isfile(_tsfile_dylib): diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 4bd8d43788..01ac140a45 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -59,10 +59,8 @@ 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++ table queries accept a named `storage::Expression` in each of the + `tag_filter` and `field_filter` arguments. Omit either with `nullptr`. - 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`. @@ -70,6 +68,33 @@ 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 queries + +Build an expression before opening a file or fetching its schema. Both +`query` and `queryByRow` bind the names and literal types when called. A +result owns its bound filters, so the caller can reuse or release the inputs. + +```cpp +using E = storage::Expression; +auto site = E::compare("site", E::CompareOp::EQ, E::Literal::string("west")); +auto hot = E::compare("temperature", E::CompareOp::GT, E::Literal::float64(22.5)); +storage::ResultSet* rows = nullptr; +int ret = reader.queryByRow("weather", {"temperature"}, 0, 100, rows, + site.get(), hot.get()); +// On success, consume rows and call reader.destroy_query_data_set(rows). +``` + +TAG expressions match STRING columns in device IDs. A missing trailing TAG +satisfies `is_null` and `NOT(tag = x)`. FIELD expressions evaluate typed +values. A NULL value is excluded by both a comparison and its negation. +Aligned chunks and pages use the same statistics to classify the match before +decoding values. Offset and limit apply to matching rows. A TAG expression +passed to `prepare_table_series` must select a single device. + +The C++ shared-library ABI epoch is 2. Rebuild C++ applications and use headers +and binaries from the same SDK when migrating from epoch 1. Replace indexed +TAG constructors and FIELD filter builders with the named factories above. + ## Source Anchors - Java: `java/tsfile/src/main/java/org/apache/tsfile/read/filter/factory/TagFilterBuilder.java`, @@ -77,7 +102,7 @@ exposes LIKE, while current C++/Python expose explicit null predicates. `java/examples/src/main/java/org/apache/tsfile/v4/TagFilterExample.java` - Python: `python/tsfile/tag_filter.py`, `python/tsfile/tsfile_reader.pyx`, and `python/tests/test_tag_filter*.py` -- C/C++: `cpp/src/reader/filter/tag_filter.h`, +- C/C++: `cpp/src/reader/expression.h`, `cpp/src/reader/tsfile_reader.h`, and `cpp/src/cwrapper/tsfile_cwrapper.h` - Properties: the current writer/reader interfaces plus `python/tests/test_tsfile_properties.py` and From 39a0c8cd975f54720836cbe409b189a6cef5c483 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 14:14:54 +0800 Subject: [PATCH 2/4] Keep existing SDK library names and ABI version --- .github/workflows/native-packages.yml | 10 ++--- .github/workflows/unit-test-go.yml | 4 +- .github/workflows/wheels.yml | 2 +- cpp/CMakeLists.txt | 7 +++- cpp/src/CMakeLists.txt | 17 +++----- cpp/src/utils/util_define.h | 2 +- cpp/test/CMakeLists.txt | 4 +- packaging/README.md | 4 +- packaging/scripts/check_python_wheel.py | 2 +- packaging/tests/go_installed_tests.py | 4 +- packaging/tests/test_python_wheel_contents.py | 7 +--- packaging/tests/test_sdk_build_config.py | 10 ++--- python/_build_support.py | 9 ++-- python/pyproject.toml | 4 +- python/setup.py | 42 ++++++++++++------- python/tsfile/__init__.py | 25 +++++------ .../tsfile/references/properties-filters.md | 6 +-- 17 files changed, 81 insertions(+), 78 deletions(-) diff --git a/.github/workflows/native-packages.yml b/.github/workflows/native-packages.yml index 971d015cc5..127f943783 100644 --- a/.github/workflows/native-packages.yml +++ b/.github/workflows/native-packages.yml @@ -1021,7 +1021,7 @@ jobs: cmake --install cpp/target/build --config Release --prefix $sdkRoot $requiredPaths = @( "$sdkRoot/bin/tsfile-cli.exe" - "$sdkRoot/bin/tsfile-2.dll" + "$sdkRoot/bin/tsfile.dll" "$sdkRoot/lib/tsfile.lib" "$sdkRoot/include/tsfile/cwrapper/tsfile_cwrapper.h" "$sdkRoot/lib/cmake/TsFile/TsFileConfig.cmake" @@ -1078,7 +1078,7 @@ jobs: }) $requiredSuffixes = @( 'bin/tsfile-cli.exe' - 'bin/tsfile-2.dll' + 'bin/tsfile.dll' 'lib/tsfile.lib' 'include/tsfile/cwrapper/tsfile_cwrapper.h' ) @@ -1194,7 +1194,7 @@ jobs: cmake --install cpp/target/build --config Release --prefix $sdkRoot $requiredPaths = @( "$sdkRoot/bin/tsfile-cli.exe" - "$sdkRoot/bin/tsfile-2.dll" + "$sdkRoot/bin/tsfile.dll" "$sdkRoot/lib/tsfile.lib" "$sdkRoot/include/tsfile/cwrapper/tsfile_cwrapper.h" "$sdkRoot/lib/cmake/TsFile/TsFileConfig.cmake" @@ -1245,7 +1245,7 @@ jobs: $entryPaths = @($archive.Entries | ForEach-Object { $_.FullName.Replace('\', '/') }) foreach ($suffix in @( 'bin/tsfile-cli.exe' - 'bin/tsfile-2.dll' + 'bin/tsfile.dll' 'lib/tsfile.lib' 'include/tsfile/cwrapper/tsfile_cwrapper.h' )) { @@ -1407,7 +1407,7 @@ jobs: # setup.py consumes libraries from lib/; the installed SDK stores DLLs in bin/. Copy-Item "$sdkRoot/bin/*.dll" "$sdkRoot/lib/" if (-not (Test-Path "$sdkRoot/lib/tsfile.lib")) { throw 'Missing MSVC import library' } - if (-not (Test-Path "$sdkRoot/lib/tsfile-2.dll")) { throw 'Missing TsFile DLL' } + if (-not (Test-Path "$sdkRoot/lib/tsfile.dll")) { throw 'Missing TsFile DLL' } "TSFILE_CPP_BUILD=$sdkRoot" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - name: Install wheel build tools diff --git a/.github/workflows/unit-test-go.yml b/.github/workflows/unit-test-go.yml index ad75a0e154..0d5c10be0f 100644 --- a/.github/workflows/unit-test-go.yml +++ b/.github/workflows/unit-test-go.yml @@ -112,8 +112,8 @@ jobs: shell: pwsh run: | $nativeLib = Join-Path $env:GITHUB_WORKSPACE "cpp\target\build\lib" - $dll = Get-ChildItem -Path $nativeLib -Filter "tsfile-2.dll" -Recurse -ErrorAction SilentlyContinue + $dll = Get-ChildItem -Path $nativeLib -Filter "tsfile.dll" -Recurse -ErrorAction SilentlyContinue $importLib = Get-ChildItem -Path $nativeLib -Filter "tsfile.lib" -Recurse -ErrorAction SilentlyContinue - if (-not $dll) { throw "MSVC tsfile-2.dll was not produced under $nativeLib" } + if (-not $dll) { throw "MSVC tsfile.dll was not produced under $nativeLib" } if (-not $importLib) { throw "MSVC tsfile.lib import library was not produced under $nativeLib" } Write-Host "Verified MSVC outputs: $($dll.FullName) and $($importLib.FullName)" diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index c413799d82..124e9cb85e 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -113,7 +113,7 @@ jobs: # setup.py consumes DLLs and import libraries together under lib/. Copy-Item "$sdkRoot/bin/*.dll" "$sdkRoot/lib/" if (-not (Test-Path "$sdkRoot/lib/tsfile.lib")) { throw 'Missing MSVC import library' } - if (-not (Test-Path "$sdkRoot/lib/tsfile-2.dll")) { throw 'Missing TsFile DLL' } + if (-not (Test-Path "$sdkRoot/lib/tsfile.dll")) { throw 'Missing TsFile DLL' } - name: Install wheel build tools run: python -m pip install cibuildwheel==3.4.1 diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 8ac0969716..dae05ae386 100755 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -70,8 +70,11 @@ set(TSFILE_RPM_PACKAGE_VERSION "${TSFILE_PACKAGE_VERSION}" CACHE STRING "RPM Version value") set(TSFILE_RPM_PACKAGE_RELEASE "1" CACHE STRING "RPM Release value") -# Bump when installed C++ interfaces break binary compatibility. -set(TSFILE_ABI_VERSION 2) +set(TSFILE_ABI_VERSION "1" CACHE STRING + "TsFile shared-library ABI epoch (changes only on ABI breaks)") +if (NOT TSFILE_ABI_VERSION MATCHES "^[0-9]+$") + message(FATAL_ERROR "TSFILE_ABI_VERSION must be a positive integer") +endif () include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/DependencySource.cmake) if (TSFILE_MSVC_STATIC_RUNTIME AND diff --git a/cpp/src/CMakeLists.txt b/cpp/src/CMakeLists.txt index 70a9bac7eb..b62cf7b58c 100644 --- a/cpp/src/CMakeLists.txt +++ b/cpp/src/CMakeLists.txt @@ -172,17 +172,12 @@ set_property(DIRECTORY PROPERTY LINK_LIBRARIES unset(_TSFILE_SRC_LINK_LIBRARIES) if (TSFILE_BUILD_SHARED) - # Keep each ABI in its own real file even when two SDK builds share a - # project version. An existing SONAME must never point at a different ABI. - set_target_properties(tsfile PROPERTIES SOVERSION ${TSFILE_ABI_VERSION}) - if (APPLE) - set_target_properties(tsfile PROPERTIES MACHO_CURRENT_VERSION ${TSFILE_PACKAGE_VERSION}) - endif() - if (WIN32) - # PE imports identify the runtime by filename. Keep the import library - # name stable for consumers linking with -ltsfile or TsFile::tsfile. - set_target_properties(tsfile PROPERTIES RUNTIME_OUTPUT_NAME "tsfile-${TSFILE_ABI_VERSION}") - endif() + # Keep development suffixes out of the install name and SONAME. The ABI + # epoch changes only for incompatible binary interface changes. + set(LIBTSFILE_PROJECT_VERSION ${TSFILE_PACKAGE_VERSION}) + set(LIBTSFILE_SO_VERSION ${TSFILE_ABI_VERSION}) + set_target_properties(tsfile PROPERTIES VERSION ${LIBTSFILE_PROJECT_VERSION}) + set_target_properties(tsfile PROPERTIES SOVERSION ${LIBTSFILE_SO_VERSION}) endif() add_library(TsFile::tsfile ALIAS tsfile) diff --git a/cpp/src/utils/util_define.h b/cpp/src/utils/util_define.h index 9c6f126ce3..33784e1528 100644 --- a/cpp/src/utils/util_define.h +++ b/cpp/src/utils/util_define.h @@ -66,7 +66,7 @@ typedef int mode_t; /* ======== library symbol visibility ======== * - * Functions are exported from the TsFile DLL automatically via + * Functions are exported from tsfile.dll automatically via * CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS, but global DATA symbols (plain variables, * static class members) are not reliably auto-exported, and a consumer must * see __declspec(dllimport) to reference them across the DLL boundary. Mark diff --git a/cpp/test/CMakeLists.txt b/cpp/test/CMakeLists.txt index 920c0fc70a..e640a08806 100644 --- a/cpp/test/CMakeLists.txt +++ b/cpp/test/CMakeLists.txt @@ -370,14 +370,14 @@ if (WIN32 AND TSFILE_BUILD_SHARED) COMMAND ${CMAKE_COMMAND} -E copy_if_different $ "$" - COMMENT "Copying the TsFile DLL to the test executable directory" + COMMENT "Copying libtsfile.dll to test executable directory" VERBATIM ) endif () include(GoogleTest) # On Windows, delay test discovery until ctest runs (PRE_TEST) so the test exe -# runs with the correct env (e.g. PATH has MinGW, the TsFile DLL is present). +# runs with the correct env (e.g. PATH has MinGW, libtsfile.dll is present). # Avoids 0xc0000139 when discovery runs at build time. # # DISCOVERY_TIMEOUT is raised well above the 5s default: the first execution of diff --git a/packaging/README.md b/packaging/README.md index a84531f2d7..449a1ee1c7 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -237,7 +237,7 @@ plus an external CMake SDK consumer before producing `tsfile--windows-arm64.zip`. Each archive is one combined ZIP rather than one archive per CPack component, and contains the runtime, development files, and tools under a relocatable prefix. The MSVC outputs are -installed as `bin/tsfile-2.dll`, `lib/tsfile.lib`, and `bin/tsfile-cli.exe`. +installed as `bin/tsfile.dll`, `lib/tsfile.lib`, and `bin/tsfile-cli.exe`. The portable ZIP targets Windows 10 / Windows Server 2022 or newer and uses the static MSVC runtime (`/MT`) in Release. `TSFILE_MSVC_STATIC_RUNTIME=ON` @@ -256,7 +256,7 @@ compiler used to build that architecture and `/MT` NEW before `project()`). Keep allocation and release paired through the public APIs; CRT-owned objects such as `FILE*` must not cross DLL boundaries. The installed-consumer fixture demonstrates a public setting/getter round trip -that requires real symbols from `tsfile-2.dll`. +that requires real symbols from `tsfile.dll`. The workflow uploads the ZIPs as `native-windows-msvc-x86_64` and `native-windows-msvc-arm64` for 14 days. Like the Linux jobs, it validates the diff --git a/packaging/scripts/check_python_wheel.py b/packaging/scripts/check_python_wheel.py index d018199913..1ff57ec1bd 100644 --- a/packaging/scripts/check_python_wheel.py +++ b/packaging/scripts/check_python_wheel.py @@ -96,7 +96,7 @@ def check_wheel(path, expected_version=None): name for name in names if Path(name).name.startswith("libtsfile") - or Path(name).match("tsfile-*.dll") + or Path(name).name == "tsfile.dll" ] if len(native) != 1: raise ValueError(f"Expected one TsFile runtime library in {path}: {native}") diff --git a/packaging/tests/go_installed_tests.py b/packaging/tests/go_installed_tests.py index 5535282239..05667d9fb0 100644 --- a/packaging/tests/go_installed_tests.py +++ b/packaging/tests/go_installed_tests.py @@ -91,8 +91,8 @@ def main(): triple = {"amd64": "x86_64", "arm64": "aarch64"}[goarch] + "-w64-mingw32" environment["CC"] = (tools / f"{triple}-clang.exe").as_posix() environment["CXX"] = (tools / f"{triple}-clang++.exe").as_posix() - bin_dir = prefix / "bin" - dlls = [*bin_dir.glob("tsfile-*.dll"), *bin_dir.glob("libtsfile-*.dll")] + dlls = [prefix / "bin" / name for name in ("tsfile.dll", "libtsfile.dll")] + dlls = [dll for dll in dlls if dll.is_file()] if len(dlls) != 1: raise ValueError(f"Expected one installed TsFile DLL: {dlls}") dll = dlls[0] diff --git a/packaging/tests/test_python_wheel_contents.py b/packaging/tests/test_python_wheel_contents.py index 41d17ccb1f..16898491ce 100644 --- a/packaging/tests/test_python_wheel_contents.py +++ b/packaging/tests/test_python_wheel_contents.py @@ -51,11 +51,6 @@ def test_runtime_only_wheel_is_accepted(self): } ) - def test_windows_abi_versioned_runtime_is_accepted(self): - for runtime in ("tsfile-2.dll", "libtsfile-2.dll"): - with self.subTest(runtime=runtime): - self.check({f"tsfile/{runtime}": b"native", "tsfile/reader.pyd": b"binding"}) - def test_development_wheel_filename_and_metadata_must_match_requested_version(self): for expected in ("2.5.1.dev0", "2.5.1.dev2"): for filename_version, directory_version, metadata_version in ( @@ -101,7 +96,7 @@ def test_sdk_headers_and_import_libraries_are_rejected(self): with self.subTest(name=name), self.assertRaisesRegex( ValueError, "Build-only" ): - self.check({"tsfile/tsfile-2.dll": b"native", name: b"build-input"}) + self.check({"tsfile/tsfile.dll": b"native", name: b"build-input"}) def test_library_alias_copies_are_rejected(self): with self.assertRaisesRegex(ValueError, "one TsFile runtime library"): diff --git a/packaging/tests/test_sdk_build_config.py b/packaging/tests/test_sdk_build_config.py index eac23ef069..af889450f7 100644 --- a/packaging/tests/test_sdk_build_config.py +++ b/packaging/tests/test_sdk_build_config.py @@ -141,15 +141,15 @@ def test_staging_one_soname_removes_stale_alias_copies(self): root = Path(temporary) package = root / "tsfile" package.mkdir() - (root / "libtsfile.so.1").write_bytes(b"old-abi") - (root / "libtsfile.so.2").write_bytes(b"current-abi") + source = root / "libtsfile.so.2.5.0" + source.write_bytes(b"native-library") for name in ("libtsfile.so", "libtsfile.so.1", "libtsfile.so.2.5.0"): (package / name).write_bytes(b"old-copy") target = support.copy_runtime_library( - package, root, {"runtime_library": "libtsfile.so.2"} + package, source, {"runtime_library": "libtsfile.so.1"} ) - self.assertEqual([p.name for p in package.iterdir()], ["libtsfile.so.2"]) - self.assertEqual(target.read_bytes(), b"current-abi") + self.assertEqual([p.name for p in package.iterdir()], ["libtsfile.so.1"]) + self.assertEqual(target.read_bytes(), source.read_bytes()) def test_runtime_filename_cannot_escape_package(self): with tempfile.TemporaryDirectory() as temporary: diff --git a/python/_build_support.py b/python/_build_support.py index b53e807d15..e2a22395fb 100644 --- a/python/_build_support.py +++ b/python/_build_support.py @@ -73,14 +73,14 @@ def msvc_runtime_flag(config): return MSVC_RUNTIME_FLAGS[runtime] -def copy_runtime_library(package, library_dir, config): +def copy_runtime_library(package, library, config): package = Path(package) # Repeated ABI builds must not retain aliases from an earlier SDK view. - for pattern in ("libtsfile.so*", "libtsfile*.dylib", "tsfile*.dll", "libtsfile*.dll"): + for pattern in ("libtsfile.so*", "libtsfile*.dylib", "tsfile.dll", "libtsfile.dll"): for stale in package.glob(pattern): stale.unlink() target = package / config["runtime_library"] - shutil.copy2(Path(library_dir) / config["runtime_library"], target) + shutil.copy2(library, target) return target @@ -107,8 +107,7 @@ def strip_wheel_binaries(build_lib, platform): def is_runtime_library(path): - name = Path(path).name - return name.startswith("libtsfile") or (name.startswith("tsfile") and name.endswith(".dll")) + return Path(path).name.startswith(("libtsfile", "tsfile.dll")) def native_binaries(root): diff --git a/python/pyproject.toml b/python/pyproject.toml index 3717e29512..eda59bd65e 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -69,8 +69,8 @@ namespaces = false tsfile = [ "libtsfile.so*", "libtsfile*.dylib", - "tsfile-*.dll", - "libtsfile-*.dll", + "tsfile.dll", + "libtsfile.dll", "libstdc++-6.dll", "libgcc_s_seh-1.dll", "libwinpthread-1.dll", diff --git a/python/setup.py b/python/setup.py index 0aa4204fc4..ecda8a3312 100644 --- a/python/setup.py +++ b/python/setup.py @@ -118,23 +118,30 @@ def _find_lib(root, patterns): runtime_lib_dst = None if sys.platform.startswith("linux"): - src = _find_lib(CPP_LIB, ["libtsfile.so"]) - if src is None: - raise FileNotFoundError("missing libtsfile.so in build output") + candidates = sorted( + CPP_LIB.rglob("libtsfile.so*"), key=lambda p: len(p.name), reverse=True + ) + if not candidates: + raise FileNotFoundError("missing libtsfile.so* in build output") + src = candidates[0] sdk_config = read_sdk_config(CPP_OUT, src) + runtime_lib_dst = copy_runtime_library(PKG, src, sdk_config) native_link_dir = src.parent - runtime_lib_dst = copy_runtime_library(PKG, native_link_dir, sdk_config) elif sys.platform == "darwin": - src = _find_lib(CPP_LIB, ["libtsfile.dylib"]) - if src is None: - raise FileNotFoundError("missing libtsfile.dylib in build output") + candidates = sorted(CPP_LIB.rglob("libtsfile.*.dylib")) or list( + CPP_LIB.rglob("libtsfile.dylib") + ) + if not candidates: + raise FileNotFoundError("missing libtsfile*.dylib in build output") + src = candidates[0] sdk_config = read_sdk_config(CPP_OUT, src) + runtime_lib_dst = copy_runtime_library(PKG, src, sdk_config) native_link_dir = src.parent - runtime_lib_dst = copy_runtime_library(PKG, native_link_dir, sdk_config) elif sys.platform == "win32": - dll_src = _find_lib(CPP_LIB, ["tsfile-*.dll", "libtsfile-*.dll"]) + # The shared library is named tsfile.dll (MSVC) or libtsfile.dll (MinGW). + dll_src = _find_lib(CPP_LIB, ["tsfile*.dll", "libtsfile*.dll"]) if dll_src is None: raise FileNotFoundError(f"missing tsfile DLL in build output: {CPP_LIB}") @@ -152,13 +159,16 @@ def _find_lib(root, patterns): f"missing tsfile import library (*.lib or *.dll.a) in {CPP_LIB}" ) - # Preserve the ABI-specific DLL name recorded in each PE import table. + # For MSVC the DLL is already named tsfile.dll. For MinGW, keep the original + # name (libtsfile.dll): the import library (libtsfile.dll.a) has that name + # baked in, so Cython .pyd files record "libtsfile.dll" in their PE import + # table and Windows must find it by that exact name at runtime. sdk_config = read_sdk_config(CPP_OUT, dll_src) - dll_dst = copy_runtime_library(PKG, dll_src.parent, sdk_config) + dll_dst = copy_runtime_library(PKG, dll_src, sdk_config) runtime_lib_dst = dll_dst native_link_dir = PKG - # The extension links with the unversioned import library name. + # Copy import library with a name matching the DLL. if win_toolchain == "mingw": imp_dst = PKG / "tsfile.dll.a" else: @@ -170,13 +180,13 @@ def _find_lib(root, patterns): ) if win_toolchain == "mingw": - # Copy MinGW runtime DLLs next to the TsFile DLL so Python can find them. + # Copy MinGW runtime DLLs next to tsfile.dll so Python can find them. # Python 3.8+ does not search PATH for DLLs; they must sit in the # same directory as the .pyd extensions (os.add_dll_directory). # Prefer runtime DLLs captured from the same MSYS2 environment that - # built the TsFile DLL. Mixing MinGW runtime DLLs from a different + # built libtsfile.dll. Mixing MinGW runtime DLLs from a different # install can load successfully but fail later with WinError 127 when - # the TsFile DLL imports a newer runtime symbol. + # libtsfile.dll imports a newer runtime symbol. _mingw_search_dirs = [CPP_LIB] for _dir in os.environ.get("PATH", "").split(os.pathsep): if _dir: @@ -312,7 +322,7 @@ def finalize_options(self): elif sys.platform == "win32": if win_toolchain == "mingw": # Resolve EH/runtime symbols from MinGW runtimes before libtsfile.dll.a. - # Otherwise _Unwind_Resume is recorded against the TsFile DLL and loading + # Otherwise _Unwind_Resume is recorded against libtsfile.dll and loading # the .pyd fails with WinError 127 on Windows. libraries = ["gcc_s", "stdc++", "tsfile"] extra_compile_args += [ diff --git a/python/tsfile/__init__.py b/python/tsfile/__init__.py index da5772cbae..b15634ddc0 100644 --- a/python/tsfile/__init__.py +++ b/python/tsfile/__init__.py @@ -37,7 +37,7 @@ def _preload_dll(path): # counting frees the object immediately if not stored, which calls # RemoveDllDirectory and undoes the registration before any .pyd is loaded. _dll_dir = os.add_dll_directory(_pkg_dir) - # Preload MinGW runtime DLLs before the TsFile DLL. Python 3.8+ does not + # Preload MinGW runtime DLLs before libtsfile.dll. Python 3.8+ does not # search PATH for DLL dependencies; they must live next to the extensions. for _mingw_dll in ( "libwinpthread-1.dll", @@ -45,18 +45,19 @@ def _preload_dll(path): "libstdc++-6.dll", ): _preload_dll(os.path.join(_pkg_dir, _mingw_dll)) - # The import library records the ABI-specific name in each extension. - from pathlib import Path as _Path - - _native_dlls = [ - *_Path(_pkg_dir).glob("tsfile-*.dll"), - *_Path(_pkg_dir).glob("libtsfile-*.dll"), - ] - if len(_native_dlls) != 1: - raise ImportError( - f"Expected one TsFile runtime DLL in {_pkg_dir}, found {_native_dlls}" + # Preload the tsfile DLL so Windows finds it when loading Cython extensions. + # MSVC builds produce "tsfile.dll"; MinGW builds produce "libtsfile.dll". + _tsfile_cdll = None + for _dll_name in ("tsfile.dll", "libtsfile.dll"): + _tsfile_dll = os.path.join(_pkg_dir, _dll_name) + if os.path.isfile(_tsfile_dll): + _tsfile_cdll = ctypes.CDLL(_tsfile_dll) + break + else: + raise FileNotFoundError( + f"tsfile DLL (tsfile.dll or libtsfile.dll) not found in {_pkg_dir}. " + "Re-build the C++ module and reinstall the Python package." ) - _tsfile_cdll = ctypes.CDLL(str(_native_dlls[0])) elif sys.platform == "darwin": _tsfile_dylib = os.path.join(_pkg_dir, "libtsfile.dylib") if os.path.isfile(_tsfile_dylib): diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 01ac140a45..6a1d747ba9 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -91,9 +91,9 @@ Aligned chunks and pages use the same statistics to classify the match before decoding values. Offset and limit apply to matching rows. A TAG expression passed to `prepare_table_series` must select a single device. -The C++ shared-library ABI epoch is 2. Rebuild C++ applications and use headers -and binaries from the same SDK when migrating from epoch 1. Replace indexed -TAG constructors and FIELD filter builders with the named factories above. +When upgrading, replace indexed TAG constructors and FIELD filter builders +with the named factories above. Recompile and relink C++ applications against +the headers and library shipped in the new SDK. ## Source Anchors From 3d3e3495b9b3dbc3ea3bd20cfef6a7ccaedb49e9 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 15:26:42 +0800 Subject: [PATCH 3/4] Clarify ownership of bound table filters --- cpp/src/file/tsfile_io_reader.cc | 2 +- cpp/src/file/tsfile_io_reader.h | 2 +- cpp/src/reader/aligned_chunk_reader.cc | 9 +-- cpp/src/reader/aligned_chunk_reader.h | 6 +- .../block/device_ordered_tsblock_reader.cc | 11 +-- .../block/device_ordered_tsblock_reader.h | 16 ++-- .../block/prepared_series_tsblock_reader.cc | 17 +++-- .../block/prepared_series_tsblock_reader.h | 8 +- .../block/single_device_tsblock_reader.cc | 57 ++++---------- .../block/single_device_tsblock_reader.h | 30 +++----- cpp/src/reader/column_mapping.h | 5 +- cpp/src/reader/filter/bind_expression.cc | 9 +-- ...ligned_field_filter.cc => field_filter.cc} | 18 ++--- ...{aligned_field_filter.h => field_filter.h} | 12 +-- cpp/src/reader/filter/filter.h | 5 -- cpp/src/reader/table_query_executor.cc | 28 ++++--- cpp/src/reader/table_query_executor.h | 14 ++-- cpp/src/reader/tsfile_executor.cc | 10 ++- cpp/src/reader/tsfile_reader.cc | 9 ++- cpp/src/reader/tsfile_series_scan_iterator.cc | 10 +-- cpp/src/reader/tsfile_series_scan_iterator.h | 8 +- .../reader/aligned_chunk_reader_bulk_test.cc | 14 ++-- .../reader/block/masked_bulk_copy_test.cc | 7 +- cpp/test/reader/chunk_reader_resource_test.cc | 7 +- ...est.cc => field_filter_regression_test.cc} | 75 +++++++++---------- ...ld_filter_test.cc => field_filter_test.cc} | 47 ++++++------ cpp/test/reader/filter/tag_filter_test.cc | 4 +- cpp/test/reader/table_field_filter_test.cc | 60 +++++++++++++-- .../table_view/tsfile_reader_table_test.cc | 29 +++---- .../tsfile/references/properties-filters.md | 4 +- 30 files changed, 262 insertions(+), 271 deletions(-) rename cpp/src/reader/filter/{aligned_field_filter.cc => field_filter.cc} (96%) rename cpp/src/reader/filter/{aligned_field_filter.h => field_filter.h} (91%) rename cpp/test/reader/{aligned_field_filter_regression_test.cc => field_filter_regression_test.cc} (95%) rename cpp/test/reader/filter/{aligned_field_filter_test.cc => field_filter_test.cc} (93%) diff --git a/cpp/src/file/tsfile_io_reader.cc b/cpp/src/file/tsfile_io_reader.cc index 6de4ed20da..cbabebfc1f 100644 --- a/cpp/src/file/tsfile_io_reader.cc +++ b/cpp/src/file/tsfile_io_reader.cc @@ -342,7 +342,7 @@ int TsFileIOReader::alloc_multi_ssi( std::shared_ptr device_id, const std::vector& measurement_names, TsFileSeriesScanIterator*& ssi, common::PageArena& pa, Filter* time_filter, - AlignedFieldFilter* field_filter) { + const FieldFilter* field_filter) { int ret = E_OK; if (RET_FAIL(load_tsfile_meta_if_necessary())) return ret; diff --git a/cpp/src/file/tsfile_io_reader.h b/cpp/src/file/tsfile_io_reader.h index f996991cd8..49776df25a 100644 --- a/cpp/src/file/tsfile_io_reader.h +++ b/cpp/src/file/tsfile_io_reader.h @@ -101,7 +101,7 @@ class TsFileIOReader { const std::vector& measurement_names, TsFileSeriesScanIterator*& ssi, common::PageArena& pa, Filter* time_filter = nullptr, - AlignedFieldFilter* field_filter = nullptr); + const FieldFilter* field_filter = nullptr); int prepare_series(const FileGeneration& generation, const PreparedLocator& locator, diff --git a/cpp/src/reader/aligned_chunk_reader.cc b/cpp/src/reader/aligned_chunk_reader.cc index a8fc540092..b7deb7185e 100644 --- a/cpp/src/reader/aligned_chunk_reader.cc +++ b/cpp/src/reader/aligned_chunk_reader.cc @@ -1543,12 +1543,12 @@ void AlignedChunkReader::build_filter_column_mask() { int AlignedChunkReader::evaluate_page_field_mask(size_t page_idx) { if (field_filter_ == nullptr) return E_OK; const ChunkPageInfo& page_info = chunk_pages_[page_idx]; - std::vector views; + std::vector views; for (uint32_t c = 0; c < value_columns_.size(); ++c) { if (!filter_column_mask_[c]) continue; auto* col = value_columns_[c]; auto& pps = col->per_page_state[page_idx]; - AlignedFieldFilter::ColumnView view; + FieldFilter::ColumnView view; view.name = col->chunk_meta->measurement_name_.to_std_string(); view.type = col->chunk_header.data_type_; view.notnull_bitmap = @@ -1666,9 +1666,8 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { : 0; const auto match = field_filter_->classify(field_statistics, row_count); - field_page_skip = - match == AlignedFieldFilter::StatisticsMatch::None; - field_all_match = match == AlignedFieldFilter::StatisticsMatch::All; + field_page_skip = match == FieldFilter::StatisticsMatch::None; + field_all_match = match == FieldFilter::StatisticsMatch::All; } Statistic* stat = cur_time_page_header_.statistic_; diff --git a/cpp/src/reader/aligned_chunk_reader.h b/cpp/src/reader/aligned_chunk_reader.h index 74076af675..d12bf2dc3e 100644 --- a/cpp/src/reader/aligned_chunk_reader.h +++ b/cpp/src/reader/aligned_chunk_reader.h @@ -25,7 +25,7 @@ #include "compress/compressor.h" #include "encoding/decoder.h" #include "file/random_access_read_file.h" -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include "reader/filter/filter.h" #include "reader/ichunk_reader.h" @@ -138,7 +138,7 @@ class AlignedChunkReader : public IChunkReader { cur_value_index(-1) {} int init(RandomAccessReadFile* read_file, common::String m_name, common::TSDataType data_type, Filter* time_filter) override; - void set_field_filter(AlignedFieldFilter* field_filter) { + void set_field_filter(const FieldFilter* field_filter) { field_filter_ = field_filter; } bool field_filter_applied() const { @@ -346,7 +346,7 @@ class AlignedChunkReader : public IChunkReader { Compressor* time_compressor_; Compressor* value_compressor_; Filter* time_filter_; - AlignedFieldFilter* field_filter_ = nullptr; + const FieldFilter* field_filter_ = nullptr; bool chunk_field_all_match_ = false; Decoder* time_decoder_; diff --git a/cpp/src/reader/block/device_ordered_tsblock_reader.cc b/cpp/src/reader/block/device_ordered_tsblock_reader.cc index 316de25ccc..680275d3ea 100644 --- a/cpp/src/reader/block/device_ordered_tsblock_reader.cc +++ b/cpp/src/reader/block/device_ordered_tsblock_reader.cc @@ -66,15 +66,13 @@ int DeviceOrderedTsBlockReader::has_next(bool& has_next) { delete current_reader_; current_reader_ = nullptr; } - current_reader_ = new SingleDeviceTsBlockReader( - task, block_size_, metadata_querier_, tsfile_io_reader_, - time_filter_, field_filter_.get()); + current_reader_ = new SingleDeviceTsBlockReader(tsfile_io_reader_); if (current_reader_ == nullptr) { return common::E_OOM; } current_reader_->set_reusable_block(&reusable_block_); if (RET_FAIL(current_reader_->init( - task, block_size_, time_filter_, field_filter_.get(), + task, block_size_, time_filter_.get(), field_filter_.get(), remaining_offset_, remaining_limit_))) { delete current_reader_; current_reader_ = nullptr; @@ -116,10 +114,7 @@ void DeviceOrderedTsBlockReader::close() { if (device_task_iterator_) { device_task_iterator_->flush_remaining_device_meta_cache(); } - if (time_filter_ != nullptr) { - delete time_filter_; - time_filter_ = nullptr; - } + time_filter_.reset(); field_filter_.reset(); } diff --git a/cpp/src/reader/block/device_ordered_tsblock_reader.h b/cpp/src/reader/block/device_ordered_tsblock_reader.h index b166c120a1..34c274a368 100644 --- a/cpp/src/reader/block/device_ordered_tsblock_reader.h +++ b/cpp/src/reader/block/device_ordered_tsblock_reader.h @@ -20,7 +20,6 @@ #define READER_DEVICE_ORDERED_TSBLOCK_READER_H #include "reader/block/single_device_tsblock_reader.h" #include "reader/block/tsblock_reader.h" -#include "reader/meta_data_querier.h" #include "reader/task/device_task_iterator.h" namespace storage { @@ -31,15 +30,13 @@ class DeviceOrderedTsBlockReader : public TsBlockReader { public: explicit DeviceOrderedTsBlockReader( std::unique_ptr device_task_iterator, - IMetadataQuerier* metadata_querier, int32_t block_size, - TsFileIOReader* tsfile_io_reader, Filter* time_filter, - AlignedFieldFilter::Ptr field_filter, int row_offset = 0, - int row_limit = -1) + int32_t block_size, TsFileIOReader* tsfile_io_reader, + std::unique_ptr time_filter, FieldFilter::Ptr field_filter, + int row_offset = 0, int row_limit = -1) : device_task_iterator_(std::move(device_task_iterator)), - metadata_querier_(metadata_querier), block_size_(block_size), tsfile_io_reader_(tsfile_io_reader), - time_filter_(time_filter), + time_filter_(std::move(time_filter)), field_filter_(std::move(field_filter)), remaining_offset_(row_offset), remaining_limit_(row_limit) {} @@ -51,12 +48,11 @@ class DeviceOrderedTsBlockReader : public TsBlockReader { private: std::unique_ptr device_task_iterator_; - IMetadataQuerier* metadata_querier_; int32_t block_size_; SingleDeviceTsBlockReader* current_reader_ = nullptr; TsFileIOReader* tsfile_io_reader_; - Filter* time_filter_ = nullptr; - AlignedFieldFilter::Ptr field_filter_ = nullptr; + std::unique_ptr time_filter_; + FieldFilter::Ptr field_filter_; int remaining_offset_ = 0; int remaining_limit_ = -1; // Output block shared by the per-device readers this iterator creates. diff --git a/cpp/src/reader/block/prepared_series_tsblock_reader.cc b/cpp/src/reader/block/prepared_series_tsblock_reader.cc index df91463f91..fdc8ce409a 100644 --- a/cpp/src/reader/block/prepared_series_tsblock_reader.cc +++ b/cpp/src/reader/block/prepared_series_tsblock_reader.cc @@ -50,14 +50,15 @@ common::TSDataType prepared_value_data_type(ITimeseriesIndex* index) { int PreparedSeriesTsBlockReader::init( TsFileIOReader* io_reader, const std::shared_ptr& prepared, - Filter* owned_time_filter, int offset, int limit, uint32_t block_rows) { - owned_time_filter_ = owned_time_filter; + std::unique_ptr time_filter, int offset, int limit, + uint32_t block_rows) { block_rows_ = block_rows == 0 ? PREPARED_BATCH_ROWS : block_rows; if (io_reader == nullptr || prepared == nullptr || prepared->index() == nullptr || offset < 0 || closed_) { return common::E_INVALID_ARG; } + time_filter_ = std::move(time_filter); io_reader_ = io_reader; prepared_ = prepared; remaining_limit_ = limit; @@ -75,7 +76,7 @@ int PreparedSeriesTsBlockReader::init( } int ret = io_reader_->alloc_prepared_ssi(prepared_, ssi_, pa_, - owned_time_filter_); + time_filter_.get()); if (ret == common::E_NO_MORE_DATA) { exhausted_ = true; return common::E_OK; @@ -93,13 +94,14 @@ int PreparedSeriesTsBlockReader::init( int PreparedSeriesTsBlockReader::init_multi( TsFileIOReader* io_reader, const std::vector>& prepared, - Filter* owned_time_filter, int offset, int limit, uint32_t block_rows) { - owned_time_filter_ = owned_time_filter; + std::unique_ptr time_filter, int offset, int limit, + uint32_t block_rows) { block_rows_ = block_rows == 0 ? PREPARED_BATCH_ROWS : block_rows; if (io_reader == nullptr || prepared.empty() || offset < 0 || closed_) { return common::E_INVALID_ARG; } + time_filter_ = std::move(time_filter); io_reader_ = io_reader; remaining_limit_ = limit; value_data_types_.reserve(prepared.size()); @@ -122,7 +124,7 @@ int PreparedSeriesTsBlockReader::init_multi( } int ret = io_reader_->alloc_prepared_multi_ssi(prepared, ssi_, pa_, - owned_time_filter_); + time_filter_.get()); if (ret == common::E_NO_MORE_DATA) { exhausted_ = true; return common::E_OK; @@ -237,8 +239,7 @@ void PreparedSeriesTsBlockReader::close() { io_reader_->revert_ssi(ssi_); ssi_ = nullptr; } - delete owned_time_filter_; - owned_time_filter_ = nullptr; + time_filter_.reset(); pa_.destroy(); prepared_.reset(); std::vector().swap(value_data_types_); diff --git a/cpp/src/reader/block/prepared_series_tsblock_reader.h b/cpp/src/reader/block/prepared_series_tsblock_reader.h index 3e1930f006..c80b3813b8 100644 --- a/cpp/src/reader/block/prepared_series_tsblock_reader.h +++ b/cpp/src/reader/block/prepared_series_tsblock_reader.h @@ -23,10 +23,10 @@ #include "common/allocator/page_arena.h" #include "reader/block/tsblock_reader.h" +#include "reader/filter/filter.h" namespace storage { -class Filter; class PreparedSeries; class TsFileIOReader; class TsFileSeriesScanIterator; @@ -41,11 +41,11 @@ class PreparedSeriesTsBlockReader final : public TsBlockReader { int init(TsFileIOReader* io_reader, const std::shared_ptr& prepared, - Filter* owned_time_filter, int offset, int limit, + std::unique_ptr time_filter, int offset, int limit, uint32_t block_rows = 0); int init_multi(TsFileIOReader* io_reader, const std::vector>& prepared, - Filter* owned_time_filter, int offset, int limit, + std::unique_ptr time_filter, int offset, int limit, uint32_t block_rows = 0); int has_next(bool& has_next) override; @@ -60,7 +60,7 @@ class PreparedSeriesTsBlockReader final : public TsBlockReader { private: TsFileIOReader* io_reader_ = nullptr; std::shared_ptr prepared_; - Filter* owned_time_filter_ = nullptr; + std::unique_ptr time_filter_; TsFileSeriesScanIterator* ssi_ = nullptr; common::PageArena pa_; common::TsBlock* block_ = nullptr; diff --git a/cpp/src/reader/block/single_device_tsblock_reader.cc b/cpp/src/reader/block/single_device_tsblock_reader.cc index 886580e7c0..d954312ac5 100644 --- a/cpp/src/reader/block/single_device_tsblock_reader.cc +++ b/cpp/src/reader/block/single_device_tsblock_reader.cc @@ -37,39 +37,6 @@ common::TsBlock* reusable_block_factory(void* ctx, } } // namespace -SingleDeviceTsBlockReader::SingleDeviceTsBlockReader( - DeviceQueryTask* device_query_task, uint32_t block_size, - IMetadataQuerier* metadata_querier, TsFileIOReader* tsfile_io_reader, - Filter* time_filter, AlignedFieldFilter* field_filter) - : device_query_task_(device_query_task), - field_filter_(field_filter), - block_size_(block_size), - tuple_desc_(), - tsfile_io_reader_(tsfile_io_reader) {} - -int SingleDeviceTsBlockReader::init(DeviceQueryTask* device_query_task, - uint32_t block_size, Filter* time_filter, - AlignedFieldFilter* field_filter) { - remaining_offset_ = 0; - remaining_limit_ = -1; - dense_row_count_ = -1; - row_offset_pushed_to_ssi_ = false; - return init_internal(device_query_task, block_size, time_filter, - field_filter); -} - -int SingleDeviceTsBlockReader::init(DeviceQueryTask* device_query_task, - uint32_t block_size, Filter* time_filter, - AlignedFieldFilter* field_filter, - int row_offset, int row_limit) { - remaining_offset_ = row_offset; - remaining_limit_ = row_limit; - dense_row_count_ = -1; - row_offset_pushed_to_ssi_ = false; - return init_internal(device_query_task, block_size, time_filter, - field_filter); -} - int32_t SingleDeviceTsBlockReader::compute_dense_row_count( const std::vector& ts_indexes) { int64_t reference_time_count = -1; @@ -152,10 +119,16 @@ int32_t SingleDeviceTsBlockReader::compute_dense_row_count( return static_cast(reference_time_count); } -int SingleDeviceTsBlockReader::init_internal(DeviceQueryTask* device_query_task, - uint32_t block_size, - Filter* time_filter, - AlignedFieldFilter* field_filter) { +int SingleDeviceTsBlockReader::init(DeviceQueryTask* device_query_task, + uint32_t block_size, Filter* time_filter, + const FieldFilter* field_filter, + int row_offset, int row_limit) { + device_query_task_ = device_query_task; + block_size_ = block_size; + field_filter_ = field_filter; + remaining_offset_ = row_offset; + remaining_limit_ = row_limit; + row_offset_pushed_to_ssi_ = false; int ret = common::E_OK; pa_.init(512, common::AllocModID::MOD_TSFILE_READER); tuple_desc_.reset(); @@ -787,7 +760,7 @@ int SingleDeviceTsBlockReader::satisfy_field_filter(bool& satisfied) { const uint8_t notnull = 0x80; std::vector strings; strings.reserve(names.size()); - std::vector views; + std::vector views; views.reserve(names.size()); for (const auto& name : names) { char* value = nullptr; @@ -803,7 +776,7 @@ int SingleDeviceTsBlockReader::satisfy_field_filter(bool& satisfied) { RET_FAIL(context->second->get_current_value(value, length))) return ret; } - AlignedFieldFilter::ColumnView view; + FieldFilter::ColumnView view; view.name = name; view.type = device_query_task_->get_table_schema() ->get_column_schema(name) @@ -1198,7 +1171,7 @@ int VectorMeasurementColumnContext::init( DeviceQueryTask* device_query_task, const std::vector& measurement_names, Filter* time_filter, std::vector>& pos_in_result, common::PageArena& pa, - AlignedFieldFilter* field_filter, int ssi_offset, int ssi_limit, + const FieldFilter* field_filter, int ssi_offset, int ssi_limit, ReusableTsBlock* reusable_block) { int ret = common::E_OK; pos_in_result_ = pos_in_result; @@ -1326,8 +1299,8 @@ uint32_t VectorMeasurementColumnContext::available_rows() const { return time_iter_->remaining(); } -int VectorMeasurementColumnContext::evaluate_filter( - const AlignedFieldFilter& filter, SelectionMask& mask) { +int VectorMeasurementColumnContext::evaluate_filter(const FieldFilter& filter, + SelectionMask& mask) { if (tsblock_ == nullptr) return common::E_NO_MORE_DATA; if (ssi_ != nullptr && ssi_->field_filter_applied_in_chunk()) { mask.reset(tsblock_->get_row_count()); diff --git a/cpp/src/reader/block/single_device_tsblock_reader.h b/cpp/src/reader/block/single_device_tsblock_reader.h index 2b001050b3..16845caa87 100644 --- a/cpp/src/reader/block/single_device_tsblock_reader.h +++ b/cpp/src/reader/block/single_device_tsblock_reader.h @@ -20,11 +20,11 @@ #define READER_SINGLE_DEVICE_TSBLOCK_READER_H #include "common/tsblock/tsblock.h" +#include "file/tsfile_io_reader.h" #include "reader/block/tsblock_reader.h" -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include "reader/filter/filter.h" #include "reader/filter/selection_mask.h" -#include "reader/imeta_data_querier.h" #include "reader/task/device_query_task.h" namespace storage { @@ -107,20 +107,14 @@ class ReusableTsBlock { class SingleDeviceTsBlockReader : public TsBlockReader { public: - explicit SingleDeviceTsBlockReader(DeviceQueryTask* device_query_task, - uint32_t block_size, - IMetadataQuerier* metadata_querier, - TsFileIOReader* tsfile_io_reader, - Filter* time_filter, - AlignedFieldFilter* field_filter); + explicit SingleDeviceTsBlockReader(TsFileIOReader* tsfile_io_reader) + : tsfile_io_reader_(tsfile_io_reader) {} ~SingleDeviceTsBlockReader() { close(); } int has_next(bool& has_next) override; int next(common::TsBlock*& ret_block) override; int init(DeviceQueryTask* device_query_task, uint32_t block_size, - Filter* time_filter, AlignedFieldFilter* field_filter); - int init(DeviceQueryTask* device_query_task, uint32_t block_size, - Filter* time_filter, AlignedFieldFilter* field_filter, - int row_offset, int row_limit); + Filter* time_filter, const FieldFilter* field_filter, + int row_offset = 0, int row_limit = -1); void close() override; // Borrow a block that can be reused across devices (see ReusableTsBlock). @@ -131,8 +125,6 @@ class SingleDeviceTsBlockReader : public TsBlockReader { int32_t get_dense_row_count() const { return dense_row_count_; } private: - int init_internal(DeviceQueryTask* device_query_task, uint32_t block_size, - Filter* time_filter, AlignedFieldFilter* field_filter); int construct_column_context(const ITimeseriesIndex* time_series_index, Filter* time_filter, int ssi_offset, int ssi_limit); @@ -149,9 +141,9 @@ class SingleDeviceTsBlockReader : public TsBlockReader { int has_next_aligned(bool& has_next); int has_next_aligned_filtered(bool& has_next); - DeviceQueryTask* device_query_task_; - AlignedFieldFilter* field_filter_; - uint32_t block_size_; + DeviceQueryTask* device_query_task_ = nullptr; + const FieldFilter* field_filter_ = nullptr; + uint32_t block_size_ = 0; common::TsBlock* current_block_ = nullptr; std::vector col_appenders_; common::RowAppender* row_appender_ = nullptr; @@ -282,7 +274,7 @@ class VectorMeasurementColumnContext final : public MeasurementColumnContext { const std::vector& measurement_names, Filter* time_filter, std::vector>& pos_in_result, - common::PageArena& pa, AlignedFieldFilter* field_filter = nullptr, + common::PageArena& pa, const FieldFilter* field_filter = nullptr, int ssi_offset = 0, int ssi_limit = -1, ReusableTsBlock* reusable_block = nullptr); int get_next_tsblock(bool alloc_mem) override; @@ -295,7 +287,7 @@ class VectorMeasurementColumnContext final : public MeasurementColumnContext { common::RowAppender* row_appender, uint32_t count) override; int skip_rows(uint32_t count) override; - int evaluate_filter(const AlignedFieldFilter& filter, SelectionMask& mask); + int evaluate_filter(const FieldFilter& filter, SelectionMask& mask); int filtered_bulk_copy_into( std::vector& col_appenders, common::ColAppender* time_appender, diff --git a/cpp/src/reader/column_mapping.h b/cpp/src/reader/column_mapping.h index 8280e8524a..339c635442 100644 --- a/cpp/src/reader/column_mapping.h +++ b/cpp/src/reader/column_mapping.h @@ -19,9 +19,10 @@ #ifndef READER_COLUMN_MAPPING_H #define READER_COLUMN_MAPPING_H +#include + #include "common/schema.h" -#include "expression.h" -#include "reader/filter/aligned_field_filter.h" + namespace storage { class ColumnMapping { public: diff --git a/cpp/src/reader/filter/bind_expression.cc b/cpp/src/reader/filter/bind_expression.cc index 511f944b08..8b43b40c1b 100644 --- a/cpp/src/reader/filter/bind_expression.cc +++ b/cpp/src/reader/filter/bind_expression.cc @@ -25,7 +25,7 @@ #include #include "common/schema.h" -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include "utils/storage_utils.h" namespace storage { @@ -170,8 +170,8 @@ int bind_value_leaf(Expression& node, common::TSDataType type) { } } // namespace -int AlignedFieldFilter::bind(const Expression& expr, TableSchema& schema, - Ptr& result) { +int FieldFilter::bind(const Expression& expr, TableSchema& schema, + Ptr& result) { result.reset(); Expression::Ptr bound; const int ret = detail::bind_expression( @@ -195,8 +195,7 @@ int AlignedFieldFilter::bind(const Expression& expr, TableSchema& schema, out = std::move(node); return common::E_OK; }); - if (ret == common::E_OK) - result.reset(new AlignedFieldFilter(std::move(bound))); + if (ret == common::E_OK) result.reset(new FieldFilter(std::move(bound))); return ret; } diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/field_filter.cc similarity index 96% rename from cpp/src/reader/filter/aligned_field_filter.cc rename to cpp/src/reader/filter/field_filter.cc index 91d9b089c3..75bac12a30 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/field_filter.cc @@ -17,7 +17,7 @@ * under the License. */ -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include #include @@ -30,7 +30,7 @@ namespace { using Op = Expression::CompareOp; using Literal = Expression::Literal; -using ColumnView = AlignedFieldFilter::ColumnView; +using ColumnView = FieldFilter::ColumnView; Op negate_comparison(Op op) { switch (op) { @@ -339,7 +339,7 @@ int evaluate_leaf(const Expression& expr, common::TsBlock& block, } // namespace -AlignedFieldFilter::StatisticsMatch AlignedFieldFilter::classify( +FieldFilter::StatisticsMatch FieldFilter::classify( const std::map& statistics, int64_t rows) const { if (!statistics_match(*expression_, statistics, rows, false, false)) return StatisticsMatch::None; @@ -349,9 +349,9 @@ AlignedFieldFilter::StatisticsMatch AlignedFieldFilter::classify( return StatisticsMatch::Possible; } -int AlignedFieldFilter::evaluate(common::TsBlock& block, - const std::vector& column_names, - SelectionMask& mask) const { +int FieldFilter::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; @@ -364,9 +364,9 @@ int AlignedFieldFilter::evaluate(common::TsBlock& block, }); } -int AlignedFieldFilter::evaluate_columns(const std::vector& columns, - uint32_t row_count, - SelectionMask& mask) const { +int FieldFilter::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; diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/field_filter.h similarity index 91% rename from cpp/src/reader/filter/aligned_field_filter.h rename to cpp/src/reader/filter/field_filter.h index e0254843ca..b1c4cc3f31 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/field_filter.h @@ -17,8 +17,8 @@ * under the License. */ -#ifndef READER_FILTER_ALIGNED_FIELD_FILTER_H -#define READER_FILTER_ALIGNED_FIELD_FILTER_H +#ifndef READER_FILTER_FIELD_FILTER_H +#define READER_FILTER_FIELD_FILTER_H #include #include @@ -36,7 +36,7 @@ class TableSchema; // 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. -class AlignedFieldFilter { +class FieldFilter { public: struct ColumnView { std::string name; @@ -51,7 +51,7 @@ class AlignedFieldFilter { uint32_t value_count = 0; }; - using Ptr = std::unique_ptr; + using Ptr = std::unique_ptr; const std::vector& referenced_columns() const { return columns_; } @@ -73,7 +73,7 @@ class AlignedFieldFilter { uint32_t row_count, SelectionMask& mask) const; private: - explicit AlignedFieldFilter(Expression::Ptr expr) + explicit FieldFilter(Expression::Ptr expr) : expression_(std::move(expr)), columns_(expression_->referenced_columns()) {} Expression::Ptr expression_; @@ -82,4 +82,4 @@ class AlignedFieldFilter { } // namespace storage -#endif // READER_FILTER_ALIGNED_FIELD_FILTER_H +#endif // READER_FILTER_FIELD_FILTER_H diff --git a/cpp/src/reader/filter/filter.h b/cpp/src/reader/filter/filter.h index fc2494fac5..b74df9bea3 100644 --- a/cpp/src/reader/filter/filter.h +++ b/cpp/src/reader/filter/filter.h @@ -54,11 +54,6 @@ class Filter { ASSERT(false); return false; } - virtual bool satisfyRow(int time, - std::vector segments) const { - ASSERT(false); - return false; - } virtual std::vector* get_time_ranges() { ASSERT(false); return nullptr; diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index d09b312e1c..76c7e9508e 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -25,10 +25,10 @@ namespace storage { int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, - Filter* time_filter, int offset, int limit, - ResultSet*& ret_qds, const Expression* tag_filter, + std::unique_ptr time_filter, int offset, + int limit, ResultSet*& ret_qds, + const Expression* tag_filter, const Expression* field_filter) { - std::unique_ptr owned_time(time_filter); int ret = common::E_OK; TsFileMeta* file_metadata = nullptr; ret_qds = nullptr; @@ -65,10 +65,10 @@ int TableQueryExecutor::query(const std::string& table_name, if (tag_filter && RET_FAIL(TagFilter::bind(*tag_filter, *table_schema, device_filter))) return ret; - AlignedFieldFilter::Ptr value_filter; + FieldFilter::Ptr value_filter; if (field_filter) { - if (RET_FAIL(AlignedFieldFilter::bind(*field_filter, *table_schema, - value_filter))) + if (RET_FAIL( + FieldFilter::bind(*field_filter, *table_schema, value_filter))) return ret; column_mapping->add_filter_columns(value_filter->referenced_columns()); } @@ -83,8 +83,8 @@ int TableQueryExecutor::query(const std::string& table_name, case TableQueryOrdering::DEVICE: tsblock_reader = std::unique_ptr( new DeviceOrderedTsBlockReader( - std::move(device_task_iterator), meta_data_querier_, - block_size_, tsfile_io_reader_, owned_time.release(), + std::move(device_task_iterator), block_size_, + tsfile_io_reader_, std::move(time_filter), std::move(value_filter), offset, limit)); break; case TableQueryOrdering::TIME: @@ -101,15 +101,14 @@ int TableQueryExecutor::query(const std::string& table_name, int TableQueryExecutor::query_on_tree( const std::vector>& devices, const std::vector& tag_columns, - const std::vector& field_columns, Filter* time_filter, - ResultSet*& ret_qds) { + const std::vector& field_columns, + std::unique_ptr time_filter, ResultSet*& ret_qds) { common::PageArena pa; pa.init(512, common::MOD_TSFILE_READER); int ret = common::E_OK; ret_qds = nullptr; TsFileMeta* file_meta = nullptr; if (RET_FAIL(tsfile_io_reader_->get_tsfile_meta(file_meta))) { - delete time_filter; return ret; } std::unordered_set table_inodes; @@ -117,7 +116,6 @@ int TableQueryExecutor::query_on_tree( MetaIndexNode* table_inode = nullptr; if (RET_FAIL(file_meta->get_table_metaindex_node( device->get_table_name(), table_inode))) { - delete time_filter; return ret; } table_inodes.insert(table_inode); @@ -198,12 +196,12 @@ int TableQueryExecutor::query_on_tree( 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, nullptr)); + std::move(device_task_iterator), block_size_, + tsfile_io_reader_, std::move(time_filter), nullptr)); break; case TableQueryOrdering::TIME: default: - ret = common::E_UNSUPPORTED_ORDER; + return common::E_UNSUPPORTED_ORDER; } assert(tsblock_reader != nullptr); ret_qds = new TableResultSet(std::move(tsblock_reader), diff --git a/cpp/src/reader/table_query_executor.h b/cpp/src/reader/table_query_executor.h index 1f7687f6b6..d0e7d6bf84 100644 --- a/cpp/src/reader/table_query_executor.h +++ b/cpp/src/reader/table_query_executor.h @@ -19,13 +19,15 @@ #ifndef READER_TABLE_QUERY_EXECUTOR_H #define READER_TABLE_QUERY_EXECUTOR_H +#include + #include "common/schema.h" #include "expression.h" #include "file/random_access_read_file.h" -#include "imeta_data_querier.h" #include "reader/block/device_ordered_tsblock_reader.h" #include "reader/block/tsblock_reader.h" #include "reader/column_mapping.h" +#include "reader/meta_data_querier.h" #include "reader/task/device_task_iterator.h" #include "result_set.h" #include "table_result_set.h" @@ -72,21 +74,21 @@ class TableQueryExecutor { } } // FIELD filters apply to both aligned and non-aligned table devices. - // AlignedFieldFilter uses chunk and page pruning where possible and + // FieldFilter uses chunk and page pruning where possible and // otherwise evaluates merged rows. In the non-aligned path, candidate // timestamps are the union of the projected and filter-referenced FIELD // series; values absent at a candidate timestamp are NULL. OFFSET/LIMIT // count accepted rows. A valid empty time range returns an empty result for // either layout. int query(const std::string& table_name, - const std::vector& columns, Filter* time_filter, - int offset, int limit, ResultSet*& result, - const Expression* tag_filter = nullptr, + const std::vector& columns, + std::unique_ptr time_filter, int offset, int limit, + ResultSet*& result, const Expression* tag_filter = nullptr, const Expression* field_filter = nullptr); int query_on_tree(const std::vector>& devices, const std::vector& tag_columns, const std::vector& field_columns, - Filter* time_filter, ResultSet*& ret_qds); + std::unique_ptr time_filter, ResultSet*& ret_qds); void destroy_query_data_set(ResultSet* qds); private: diff --git a/cpp/src/reader/tsfile_executor.cc b/cpp/src/reader/tsfile_executor.cc index c2aa8d8cd6..03e38117d3 100644 --- a/cpp/src/reader/tsfile_executor.cc +++ b/cpp/src/reader/tsfile_executor.cc @@ -133,9 +133,10 @@ int TsFileExecutor::execute_prepared( } auto tsblock_reader = std::unique_ptr( new PreparedSeriesTsBlockReader()); - int ret = tsblock_reader->init(&io_reader_, prepared, - new TimeBetween(start_time, end_time, false), - offset, limit, block_rows); + int ret = tsblock_reader->init( + &io_reader_, prepared, + std::unique_ptr(new TimeBetween(start_time, end_time, false)), + offset, limit, block_rows); if (ret != E_OK) { return ret; } @@ -160,7 +161,8 @@ int TsFileExecutor::execute_prepared_multi( auto tsblock_reader = std::unique_ptr( new PreparedSeriesTsBlockReader()); int ret = tsblock_reader->init_multi( - &io_reader_, prepared, new TimeBetween(start_time, end_time, false), + &io_reader_, prepared, + std::unique_ptr(new TimeBetween(start_time, end_time, false)), offset, limit, block_rows); if (ret != E_OK) { return ret; diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index 26033a9340..af92be27d7 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -439,8 +439,8 @@ int TsFileReader::query(const std::string& table_name, ensure_table_query_executor(batch_size); return table_query_executor_->query( to_lower(table_name), columns, - new TimeBetween(start_time, end_time, false), offset, limit, result_set, - tag_filter, field_filter); + std::unique_ptr(new TimeBetween(start_time, end_time, false)), + offset, limit, result_set, tag_filter, field_filter); } int TsFileReader::queryByRow(const std::string& table_name, @@ -536,11 +536,12 @@ int TsFileReader::query_table_on_tree( for (int i = 0; i < device_max_len; i++) { columns_names[i] = "col_" + std::to_string(i); } - Filter* time_filter = new TimeBetween(star_time, end_time, false); + std::unique_ptr time_filter( + new TimeBetween(star_time, end_time, false)); ensure_table_query_executor(-1); ret = table_query_executor_->query_on_tree( satisfied_device_ids, columns_names, measurement_names_to_query, - time_filter, result_set); + std::move(time_filter), result_set); return ret; } diff --git a/cpp/src/reader/tsfile_series_scan_iterator.cc b/cpp/src/reader/tsfile_series_scan_iterator.cc index 2d914f45f6..44e79af260 100644 --- a/cpp/src/reader/tsfile_series_scan_iterator.cc +++ b/cpp/src/reader/tsfile_series_scan_iterator.cc @@ -269,10 +269,9 @@ bool TsFileSeriesScanIterator::should_skip_multi_aligned_chunk_by_offset( return false; } -AlignedFieldFilter::StatisticsMatch -TsFileSeriesScanIterator::classify_multi_chunk( +FieldFilter::StatisticsMatch TsFileSeriesScanIterator::classify_multi_chunk( ChunkMeta* time, const std::vector& values) const { - if (!field_filter_) return AlignedFieldFilter::StatisticsMatch::All; + if (!field_filter_) return FieldFilter::StatisticsMatch::All; const auto* index = static_cast(itimeseries_index_); // A series with a single chunk stores its statistics in the series index. @@ -328,10 +327,9 @@ int TsFileSeriesScanIterator::get_next(TsBlock*& ret_tsblock, bool alloc, continue; } const auto match = classify_multi_chunk(time_cm, value_cms); - if (match == AlignedFieldFilter::StatisticsMatch::None) - continue; + if (match == FieldFilter::StatisticsMatch::None) continue; const bool field_all_match = - match == AlignedFieldFilter::StatisticsMatch::All; + match == FieldFilter::StatisticsMatch::All; if (field_all_match && chunk_fully_satisfies_filter(time_cm, filter) && should_skip_multi_aligned_chunk_by_offset(time_cm, diff --git a/cpp/src/reader/tsfile_series_scan_iterator.h b/cpp/src/reader/tsfile_series_scan_iterator.h index d55db75d88..68f31e518e 100644 --- a/cpp/src/reader/tsfile_series_scan_iterator.h +++ b/cpp/src/reader/tsfile_series_scan_iterator.h @@ -29,7 +29,7 @@ #include "file/random_access_read_file.h" #include "file/tsfile_io_reader.h" #include "reader/chunk_reader.h" -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include "reader/filter/filter.h" #include "utils/util_define.h" @@ -64,7 +64,7 @@ class TsFileSeriesScanIterator { const std::string& measurement_name, RandomAccessReadFile* read_file, Filter* time_filter, common::PageArena& data_pa, - AlignedFieldFilter* field_filter = nullptr) { + const FieldFilter* field_filter = nullptr) { ASSERT(read_file != nullptr); device_id_ = device_id; measurement_name_ = measurement_name; @@ -220,7 +220,7 @@ class TsFileSeriesScanIterator { FORCE_INLINE ChunkMeta* get_current_chunk_meta() { return chunk_meta_cursor_.get(); } - AlignedFieldFilter::StatisticsMatch classify_multi_chunk( + FieldFilter::StatisticsMatch classify_multi_chunk( ChunkMeta* time, const std::vector& values) const; bool should_skip_chunk_by_time(ChunkMeta* cm, int64_t min_time_hint); bool should_skip_chunk_by_offset(ChunkMeta* cm); @@ -252,7 +252,7 @@ class TsFileSeriesScanIterator { common::TupleDesc tuple_desc_; common::TsBlock* tsblock_; Filter* time_filter_; - AlignedFieldFilter* field_filter_; + const FieldFilter* field_filter_; // Keeps the arena-backed index alive until the chunk reader has released // every pointer into it. Empty for the legacy path-owned metadata arena. std::shared_ptr prepared_; diff --git a/cpp/test/reader/aligned_chunk_reader_bulk_test.cc b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc index db6cf1e29b..7788df82c8 100644 --- a/cpp/test/reader/aligned_chunk_reader_bulk_test.cc +++ b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc @@ -43,7 +43,7 @@ #include "file/tsfile_io_reader.h" #include "file/write_file.h" #include "reader/aligned_chunk_reader.h" -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include "reader/filter/time_operator.h" #include "reader/table_query_executor.h" #include "writer/tsfile_table_writer.h" @@ -443,12 +443,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) { - AlignedFieldFilter::Ptr field_filter; - ASSERT_EQ(common::E_OK, - AlignedFieldFilter::bind( - *Expression::compare("v", Expression::CompareOp::GE, - Expression::Literal::int64(12)), - *schema_, field_filter)); + FieldFilter::Ptr field_filter; + ASSERT_EQ( + common::E_OK, + FieldFilter::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/block/masked_bulk_copy_test.cc b/cpp/test/reader/block/masked_bulk_copy_test.cc index 0357fd031a..0eda410b5e 100644 --- a/cpp/test/reader/block/masked_bulk_copy_test.cc +++ b/cpp/test/reader/block/masked_bulk_copy_test.cc @@ -125,10 +125,9 @@ class MaskedBulkCopyTest : public ::testing::TestWithParam { auto device = std::make_shared( std::vector{"t"}); DeviceQueryTask task(device, names, mapping, nullptr, schema_); - AlignedFieldFilter::Ptr source_filter; - ASSERT_EQ(common::E_OK, - AlignedFieldFilter::bind(*Expression::is_not_null("v"), - *schema_, source_filter)); + FieldFilter::Ptr source_filter; + ASSERT_EQ(common::E_OK, FieldFilter::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 dfd924356f..ad98e88522 100644 --- a/cpp/test/reader/chunk_reader_resource_test.cc +++ b/cpp/test/reader/chunk_reader_resource_test.cc @@ -277,9 +277,9 @@ class AlignedReaderFailureTest : public ::testing::Test { } const auto target_offset = payload_offset( file, target == "time" ? time : values.at(target), page_number); - AlignedFieldFilter::Ptr filter; + FieldFilter::Ptr filter; ASSERT_EQ(common::E_OK, - AlignedFieldFilter::bind( + FieldFilter::bind( *Expression::compare("v", Expression::CompareOp::GE, Expression::Literal::int64(3)), *schema_, filter)); @@ -428,8 +428,7 @@ TEST_F(AlignedReaderFailureTest, CloseIsSafeBeforeAndAfterExhaustion) { auto device = std::make_shared( std::vector{"t"}); DeviceQueryTask task(device, names, mapping, nullptr, schema_); - SingleDeviceTsBlockReader reader(&task, 7, nullptr, &io, nullptr, - nullptr); + SingleDeviceTsBlockReader reader(&io); ASSERT_EQ(reader.init(&task, 7, nullptr, nullptr), E_OK); if (exhaust) { int rows = 0; diff --git a/cpp/test/reader/aligned_field_filter_regression_test.cc b/cpp/test/reader/field_filter_regression_test.cc similarity index 95% rename from cpp/test/reader/aligned_field_filter_regression_test.cc rename to cpp/test/reader/field_filter_regression_test.cc index 100b2d92c7..a1e688b241 100644 --- a/cpp/test/reader/aligned_field_filter_regression_test.cc +++ b/cpp/test/reader/field_filter_regression_test.cc @@ -32,7 +32,7 @@ #include "common/tablet.h" #include "file/local_random_access_read_file.h" #include "file/write_file.h" -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include "reader/filter/time_filter.h" #include "reader/filter/time_operator.h" #include "reader/table_query_executor.h" @@ -69,7 +69,7 @@ bool compare(double value, double literal, A::CompareOp op) { return false; } -class AlignedFieldFilterRegressionTest +class FieldFilterRegressionTest : public ::testing::TestWithParam> { protected: void SetUp() override { @@ -85,7 +85,7 @@ class AlignedFieldFilterRegressionTest #endif static std::atomic filename_counter{0}; filename_ = - "aligned_field_filter_regression_" + + "field_filter_regression_" + std::to_string( std::chrono::steady_clock::now().time_since_epoch().count()) + "_" + std::to_string(process_id) + "_" + @@ -104,13 +104,14 @@ class AlignedFieldFilterRegressionTest ASSERT_EQ(file.create(filename_, flags, 0666), E_OK); } Rows scan(const std::vector& columns, A::Ptr filter, - int offset = 0, int limit = -1, Filter* time_filter = nullptr) { + int offset = 0, int limit = -1, + std::unique_ptr time_filter = 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_filter, offset, limit, - result, nullptr, filter.get()), + EXPECT_EQ(executor.query("t", columns, std::move(time_filter), offset, + limit, result, nullptr, filter.get()), E_OK); Rows rows; if (!result) return rows; @@ -328,8 +329,7 @@ class AlignedFieldFilterRegressionTest std::numeric_limits::quiet_NaN()}; }; -TEST_P(AlignedFieldFilterRegressionTest, - NonAlignedAndMixedSourcesUseTheRowEvaluator) { +TEST_P(FieldFilterRegressionTest, NonAlignedAndMixedSourcesUseTheRowEvaluator) { auto make_filter = [](int predicate) -> A::Ptr { switch (predicate) { case 0: @@ -448,7 +448,8 @@ TEST_P(AlignedFieldFilterRegressionTest, offset, offset == 0 ? -1 : 4, window == 0 ? nullptr - : TimeFilter::between(start, end, false)), + : std::unique_ptr( + TimeFilter::between(start, end, false))), Rows(expected.begin() + begin, expected.begin() + end_row)); } @@ -457,7 +458,7 @@ TEST_P(AlignedFieldFilterRegressionTest, } } -TEST_P(AlignedFieldFilterRegressionTest, FloatingStatisticsKeepNaNRowsCorrect) { +TEST_P(FieldFilterRegressionTest, FloatingStatisticsKeepNaNRowsCorrect) { write_floats(); for (bool is_float : {true, false}) { for (auto op : {A::CompareOp::EQ, A::CompareOp::NE, A::CompareOp::LT, @@ -483,7 +484,7 @@ TEST_P(AlignedFieldFilterRegressionTest, FloatingStatisticsKeepNaNRowsCorrect) { } } -TEST_P(AlignedFieldFilterRegressionTest, RangesBindBothBoundsAndExcludeNulls) { +TEST_P(FieldFilterRegressionTest, RangesBindBothBoundsAndExcludeNulls) { write_floats(); for (double upper : {2.0, -1.0, std::numeric_limits::quiet_NaN()}) { for (bool outside : {false, true}) { @@ -506,7 +507,7 @@ TEST_P(AlignedFieldFilterRegressionTest, RangesBindBothBoundsAndExcludeNulls) { } } -TEST_P(AlignedFieldFilterRegressionTest, NotPreservesFloatingNaNRowSemantics) { +TEST_P(FieldFilterRegressionTest, NotPreservesFloatingNaNRowSemantics) { write_floats(); // Control: d2 has no float data at all, so IS NULL must see all of its // rows. This proves the NULL device is actually part of the result stream @@ -543,8 +544,7 @@ TEST_P(AlignedFieldFilterRegressionTest, NotPreservesFloatingNaNRowSemantics) { } } -TEST_P(AlignedFieldFilterRegressionTest, - NumericLiteralsUseTheDeclaredColumnType) { +TEST_P(FieldFilterRegressionTest, NumericLiteralsUseTheDeclaredColumnType) { write_floats(); for (const std::string column : {"v", "f", "d"}) { for (const auto& literal : @@ -577,8 +577,7 @@ TEST_P(AlignedFieldFilterRegressionTest, } } -TEST_P(AlignedFieldFilterRegressionTest, - InvalidLiteralTypesFailBeforeReadingAnyData) { +TEST_P(FieldFilterRegressionTest, InvalidLiteralTypesFailBeforeReadingAnyData) { for (int contents : {0, 1, 2}) { { TableSchema schema( @@ -663,7 +662,7 @@ TEST_P(AlignedFieldFilterRegressionTest, } } -TEST_P(AlignedFieldFilterRegressionTest, IncompleteOrCannotBypassEvaluation) { +TEST_P(FieldFilterRegressionTest, IncompleteOrCannotBypassEvaluation) { write_floats(); // Every row of every page satisfies the left operand, so page statistics // classify the page as a full match. The missing right operand must still @@ -691,7 +690,7 @@ TEST_P(AlignedFieldFilterRegressionTest, IncompleteOrCannotBypassEvaluation) { EXPECT_EQ(ret, E_INVALID_ARG); } -TEST_P(AlignedFieldFilterRegressionTest, +TEST_P(FieldFilterRegressionTest, InvalidTreesCannotBypassEmptyTableOrZeroLimit) { for (bool populated : {false, true}) { { @@ -761,7 +760,7 @@ TEST_P(AlignedFieldFilterRegressionTest, } } -TEST_P(AlignedFieldFilterRegressionTest, +TEST_P(FieldFilterRegressionTest, MissingFieldNamedLikeInternalContextRemainsNull) { write_missing_columns(); const std::string internal_name = "__time_only_aligned_context__"; @@ -787,7 +786,7 @@ TEST_P(AlignedFieldFilterRegressionTest, } } -TEST_P(AlignedFieldFilterRegressionTest, +TEST_P(FieldFilterRegressionTest, RealFieldNamedLikeInternalContextRetainsValues) { const std::string internal_name = "__time_only_aligned_context__"; TableSchema schema( @@ -821,7 +820,7 @@ TEST_P(AlignedFieldFilterRegressionTest, EXPECT_EQ(scan(columns, A::is_not_null(internal_name)), nonnulls); } -TEST_P(AlignedFieldFilterRegressionTest, PagePlanResumesAcrossSmallTsBlocks) { +TEST_P(FieldFilterRegressionTest, PagePlanResumesAcrossSmallTsBlocks) { g_config_value_.page_writer_max_point_num_ = 32; g_config_value_.tsblock_max_memory_ = 128; const std::vector columns{ @@ -856,7 +855,7 @@ TEST_P(AlignedFieldFilterRegressionTest, PagePlanResumesAcrossSmallTsBlocks) { Rows(all.begin() + 29, all.begin() + 67)); } -TEST_P(AlignedFieldFilterRegressionTest, +TEST_P(FieldFilterRegressionTest, EmptyFieldMaskResumesIntoPartialAndFullPages) { g_config_value_.page_writer_max_point_num_ = 8; g_config_value_.tsblock_max_memory_ = 64; @@ -891,13 +890,12 @@ TEST_P(AlignedFieldFilterRegressionTest, EXPECT_EQ(scan({"w"}, make_filter()), expected); EXPECT_EQ(scan({"w"}, make_filter(), 3, 6), Rows(expected.begin() + 3, expected.begin() + 9)); - EXPECT_EQ( - scan({"w"}, make_filter(), 1, 4, TimeFilter::between(14, 20, false)), - Rows(expected.begin() + 3, expected.begin() + 7)); + EXPECT_EQ(scan({"w"}, make_filter(), 1, 4, + std::unique_ptr(TimeFilter::between(14, 20, false))), + Rows(expected.begin() + 3, expected.begin() + 7)); } -TEST_P(AlignedFieldFilterRegressionTest, - MissingFilterAndProjectionColumnsAreNull) { +TEST_P(FieldFilterRegressionTest, MissingFilterAndProjectionColumnsAreNull) { write_missing_columns(); Rows null_filter, missing_projection; for (int d = 0; d < 2; ++d) @@ -930,8 +928,7 @@ TEST_P(AlignedFieldFilterRegressionTest, {5, 105}})); } -TEST_P(AlignedFieldFilterRegressionTest, - MissingStringFilterPreservesBinaryValues) { +TEST_P(FieldFilterRegressionTest, MissingStringFilterPreservesBinaryValues) { write_missing_columns(); Rows expected; for (int d = 1; d < 3; ++d) @@ -943,7 +940,7 @@ TEST_P(AlignedFieldFilterRegressionTest, expected); } -TEST_P(AlignedFieldFilterRegressionTest, AllMissingColumnsUseSharedTimestamps) { +TEST_P(FieldFilterRegressionTest, AllMissingColumnsUseSharedTimestamps) { write_missing_columns(); Rows expected; for (int d = 0; d < 3; ++d) @@ -951,11 +948,11 @@ TEST_P(AlignedFieldFilterRegressionTest, AllMissingColumnsUseSharedTimestamps) { EXPECT_EQ(scan({"ghost"}, A::is_null("ghost")), expected); EXPECT_TRUE(scan({"ghost"}, A::is_not_null("ghost")).empty()); EXPECT_EQ(scan({"ghost"}, A::is_null("ghost"), 3, 4, - TimeFilter::between(1, 4, false)), + std::unique_ptr(TimeFilter::between(1, 4, false))), (Rows{{4, kNull}, {1, kNull}, {2, kNull}, {3, kNull}})); } -TEST_P(AlignedFieldFilterRegressionTest, +TEST_P(FieldFilterRegressionTest, MissingColumnsApplyOffsetAfterFilterAcrossDevices) { write_missing_columns(); for (int offset : {0, 3, 5, 6, 8, 20}) { @@ -976,8 +973,7 @@ TEST_P(AlignedFieldFilterRegressionTest, // stall the first ResultSet::next() forever: the single-column aligned decode // demanded a full batch before consuming input, so no block could ever be // filled and the caller retried without progress. -TEST_P(AlignedFieldFilterRegressionTest, - SmallTsBlockCapacityResumesAlignedReads) { +TEST_P(FieldFilterRegressionTest, SmallTsBlockCapacityResumesAlignedReads) { g_config_value_.page_writer_max_point_num_ = 5; g_config_value_.tsblock_max_memory_ = 128; TableSchema schema( @@ -1038,7 +1034,7 @@ TEST_P(AlignedFieldFilterRegressionTest, // A block that cannot hold even one row has no supported capacity; the read // must surface an error instead of reporting empty successful blocks forever. -TEST_P(AlignedFieldFilterRegressionTest, UnusableTsBlockCapacityReportsError) { +TEST_P(FieldFilterRegressionTest, UnusableTsBlockCapacityReportsError) { g_config_value_.tsblock_max_memory_ = 8; write_missing_columns(); LocalRandomAccessReadFile file; @@ -1060,7 +1056,7 @@ TEST_P(AlignedFieldFilterRegressionTest, UnusableTsBlockCapacityReportsError) { // tsblock_max_memory_ was smaller than one result row: the SSI's 0-row retry // branch saw has_more_data() stay true without any progress. The read must // surface E_INVALID_ARG instead of looping. -TEST_P(AlignedFieldFilterRegressionTest, +TEST_P(FieldFilterRegressionTest, TimeBetweenFilterUnusableCapacityReportsError) { g_config_value_.tsblock_max_memory_ = 8; const int kTags = 10; @@ -1117,9 +1113,9 @@ TEST_P(AlignedFieldFilterRegressionTest, LocalRandomAccessReadFile rfile; ASSERT_EQ(rfile.open(filename_), E_OK); TableQueryExecutor executor(&rfile, std::get<1>(GetParam())); - Filter* tf = new TimeBetween(kBase + 10, kBase + 80, false); + std::unique_ptr tf(new TimeBetween(kBase + 10, kBase + 80, false)); ResultSet* result = nullptr; - int ret = executor.query("t", query_columns, tf, 0, -1, result); + int ret = executor.query("t", query_columns, std::move(tf), 0, -1, result); if (ret == E_OK) { ASSERT_NE(result, nullptr); bool next = false; @@ -1130,8 +1126,7 @@ TEST_P(AlignedFieldFilterRegressionTest, EXPECT_EQ(ret, E_INVALID_ARG); } -INSTANTIATE_TEST_SUITE_P(RowAndBatchParallelModes, - AlignedFieldFilterRegressionTest, +INSTANTIATE_TEST_SUITE_P(RowAndBatchParallelModes, FieldFilterRegressionTest, ::testing::Combine(::testing::Bool(), ::testing::Values(-1, 1, 4))); } // namespace diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/field_filter_test.cc similarity index 93% rename from cpp/test/reader/filter/aligned_field_filter_test.cc rename to cpp/test/reader/filter/field_filter_test.cc index 8177a03000..e38bf3369d 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/field_filter_test.cc @@ -17,7 +17,7 @@ * under the License. */ -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" #include @@ -34,19 +34,19 @@ namespace storage { namespace { -AlignedFieldFilter::Ptr bind_field(Expression::Ptr expr, - common::TSDataType type = common::INT64) { +FieldFilter::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)); + FieldFilter::Ptr filter; + EXPECT_EQ(common::E_OK, FieldFilter::bind(*expr, schema, filter)); return filter; } -TEST(AlignedFieldFilterTest, MissingNotOperandsStayInvalidAfterRewriting) { +TEST(FieldFilterTest, MissingNotOperandsStayInvalidAfterRewriting) { using namespace common; using A = Expression; TableSchema schema( @@ -64,15 +64,14 @@ TEST(AlignedFieldFilterTest, MissingNotOperandsStayInvalidAfterRewriting) { SCOPED_TRACE(::testing::Message() << shape << ":" << depth); filter = A::not_filter(std::move(filter)); ASSERT_NE(filter, nullptr); - AlignedFieldFilter::Ptr bound; - EXPECT_EQ(AlignedFieldFilter::bind(*filter, schema, bound), - E_INVALID_ARG); + FieldFilter::Ptr bound; + EXPECT_EQ(FieldFilter::bind(*filter, schema, bound), E_INVALID_ARG); EXPECT_EQ(bound, nullptr); } } } -TEST(AlignedFieldFilterTest, AlternatingNotPreservesNullSemanticsAfterBinding) { +TEST(FieldFilterTest, AlternatingNotPreservesNullSemanticsAfterBinding) { using A = Expression; const int levels = 32; auto expr = A::is_null("v"); @@ -81,9 +80,9 @@ TEST(AlignedFieldFilterTest, AlternatingNotPreservesNullSemanticsAfterBinding) { } TableSchema schema("t", {{"v", common::INT64, common::UNCOMPRESSED, common::PLAIN, common::ColumnCategory::FIELD}}); - AlignedFieldFilter::Ptr bound; - ASSERT_EQ(common::E_OK, AlignedFieldFilter::bind(*expr, schema, bound)); - AlignedFieldFilter::ColumnView v; + FieldFilter::Ptr bound; + ASSERT_EQ(common::E_OK, FieldFilter::bind(*expr, schema, bound)); + FieldFilter::ColumnView v; v.name = "v"; v.type = common::INT64; SelectionMask mask; @@ -91,14 +90,14 @@ TEST(AlignedFieldFilterTest, AlternatingNotPreservesNullSemanticsAfterBinding) { EXPECT_EQ((levels % 2) == 1, mask.test(0)); } -TEST(AlignedFieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { +TEST(FieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { using namespace common; 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}) { - AlignedFieldFilter::ColumnView view; + FieldFilter::ColumnView view; view.name = "v"; view.type = text ? STRING : INT64; view.notnull_bitmap = &bitmap; @@ -133,7 +132,7 @@ TEST(AlignedFieldFilterTest, ColumnViewsRejectTruncatedBuffersAndOffsets) { } } -TEST(AlignedFieldFilterTest, NumericBindingHandlesNarrowingAndRounding) { +TEST(FieldFilterTest, NumericBindingHandlesNarrowingAndRounding) { using namespace common; using A = Expression; using L = A::Literal; @@ -296,9 +295,9 @@ TEST(SelectionMaskTest, SelectedRunsMatchScalarOracle) { } } -using Match = AlignedFieldFilter::StatisticsMatch; +using Match = FieldFilter::StatisticsMatch; -TEST(AlignedFieldFilterTest, PageStatisticsAreConservative) { +TEST(FieldFilterTest, PageStatisticsAreConservative) { Int64Statistic statistic; statistic.count_ = 5; statistic.min_value_ = 10; @@ -323,7 +322,7 @@ TEST(AlignedFieldFilterTest, PageStatisticsAreConservative) { EXPECT_NE(Match::None, missing->classify(stats, 5)); } -TEST(AlignedFieldFilterTest, UnknownRowCountCannotProveWholePageMatches) { +TEST(FieldFilterTest, UnknownRowCountCannotProveWholePageMatches) { using Field = Expression; Int64Statistic empty, values; values.update(1, int64_t(5)); @@ -337,7 +336,7 @@ TEST(AlignedFieldFilterTest, UnknownRowCountCannotProveWholePageMatches) { EXPECT_EQ(Match::Possible, filter->classify(stats, 0)); } -TEST(AlignedFieldFilterTest, PageStatisticsAllMatchIsConservative) { +TEST(FieldFilterTest, PageStatisticsAllMatchIsConservative) { Int64Statistic statistic; statistic.count_ = 5; statistic.min_value_ = 10; @@ -372,7 +371,7 @@ TEST(AlignedFieldFilterTest, PageStatisticsAllMatchIsConservative) { EXPECT_EQ(Match::All, combined->classify(stats, 5)); } -TEST(AlignedFieldFilterTest, CollectsReferencedColumnsOnce) { +TEST(FieldFilterTest, CollectsReferencedColumnsOnce) { auto left = Expression::compare("a", Expression::CompareOp::EQ, Expression::Literal::int32(1)); auto right = Expression::or_filter( @@ -383,7 +382,7 @@ TEST(AlignedFieldFilterTest, CollectsReferencedColumnsOnce) { EXPECT_EQ(root->referenced_columns(), (std::vector{"a", "b"})); } -TEST(AlignedFieldFilterTest, NaNStatisticsCannotProvePageMatchesOrExclusion) { +TEST(FieldFilterTest, NaNStatisticsCannotProvePageMatchesOrExclusion) { const auto check = [](Statistic& stat, const Expression::Literal& literal) { const std::map stats{{"v", &stat}}; for (auto op : {Expression::CompareOp::EQ, Expression::CompareOp::NE, @@ -410,7 +409,7 @@ TEST(AlignedFieldFilterTest, NaNStatisticsCannotProvePageMatchesOrExclusion) { check(doubles, Expression::Literal::float64(1)); } -TEST(AlignedFieldFilterTest, FiniteFloatingStatisticsRetainFastPaths) { +TEST(FieldFilterTest, FiniteFloatingStatisticsRetainFastPaths) { FloatStatistic floats; DoubleStatistic doubles; for (int r = 0; r < 3; ++r) { @@ -432,7 +431,7 @@ TEST(AlignedFieldFilterTest, FiniteFloatingStatisticsRetainFastPaths) { EXPECT_EQ(Match::None, below->classify({{"v", &floats}}, 3)); } -TEST(AlignedFieldFilterTest, NegatedFloatingStatisticsPreserveSafeShortcuts) { +TEST(FieldFilterTest, NegatedFloatingStatisticsPreserveSafeShortcuts) { using A = Expression; FloatStatistic floats; DoubleStatistic doubles; diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index 4d672f16a3..2af8759a01 100644 --- a/cpp/test/reader/filter/tag_filter_test.cc +++ b/cpp/test/reader/filter/tag_filter_test.cc @@ -22,7 +22,7 @@ #include #include "common/schema.h" -#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/field_filter.h" using namespace storage; @@ -482,7 +482,7 @@ TEST_F(TagFilterTest, RejectsNonStringTagColumnAtBinding) { } TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { - using Field = AlignedFieldFilter; + using Field = FieldFilter; auto predicate = E::not_filter(E::compare("name", Op::EQ, Literal::string("x"))); auto tag = bind(predicate); diff --git a/cpp/test/reader/table_field_filter_test.cc b/cpp/test/reader/table_field_filter_test.cc index ef7f13e3a5..d69447ee3e 100644 --- a/cpp/test/reader/table_field_filter_test.cc +++ b/cpp/test/reader/table_field_filter_test.cc @@ -28,7 +28,6 @@ #include "common/tablet.h" #include "file/local_random_access_read_file.h" #include "file/write_file.h" -#include "reader/filter/aligned_field_filter.h" #include "reader/filter/tag_filter.h" #include "reader/filter/time_filter.h" #include "reader/filter/time_operator.h" @@ -149,14 +148,15 @@ class TableFieldFilterTest } std::vector scan_field(const std::vector& columns, Expression::Ptr expr, int offset = 0, - int limit = -1, Filter* time = nullptr, + int limit = -1, + std::unique_ptr time = nullptr, const Expression* tag = 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, tag, - expr.get()), + EXPECT_EQ(executor.query("t", columns, std::move(time), offset, limit, + result, tag, expr.get()), E_OK); return read_times(executor, result, E_OK); } @@ -230,6 +230,46 @@ TEST_P(TableFieldFilterTest, ResultOwnsTagAndFieldBindings) { reader.destroy_query_data_set(table); } +TEST_P(TableFieldFilterTest, TimeFilterLifetimeOnBindFailureAndResultClose) { + class CountedTimeFilter : public TimeBetween { + public: + CountedTimeFilter(int64_t time, int& destructions) + : TimeBetween(time, time, false), destructions_(destructions) {} + ~CountedTimeFilter() override { ++destructions_; } + + private: + int& destructions_; + }; + + LocalRandomAccessReadFile file; + ASSERT_EQ(E_OK, file.open(filename_)); + TableQueryExecutor executor(&file, std::get<1>(GetParam())); + int destructions = 0; + auto time_filter = [&]() { + return std::unique_ptr( + new CountedTimeFilter(base_ + 5, destructions)); + }; + ResultSet* result = nullptr; + auto wrong_field = Expression::is_null("id"); + EXPECT_EQ(E_INVALID_ARG, + executor.query("t", {"v"}, time_filter(), 0, -1, result, nullptr, + wrong_field.get())); + EXPECT_EQ(nullptr, result); + EXPECT_EQ(1, destructions); + + ASSERT_EQ(E_OK, executor.query("t", {"v"}, time_filter(), 0, -1, result)); + std::unique_ptr rows(result); + ASSERT_NE(nullptr, rows); + bool has_next = false; + ASSERT_EQ(E_OK, rows->next(has_next)); + ASSERT_TRUE(has_next); + EXPECT_EQ(1, destructions); + rows->close(); + EXPECT_EQ(2, destructions); + rows.reset(); + EXPECT_EQ(2, destructions); +} + TEST_P(TableFieldFilterTest, PageAfterTimeRangeAndOptionalFilters) { TsFileReader reader; ASSERT_EQ(E_OK, reader.open(filename_)); @@ -360,7 +400,8 @@ TEST_P(TableFieldFilterTest, AlignedBatchFilterCombinesTimeAndFieldMask) { 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)), + std::unique_ptr(TimeFilter::between( + base_ + 7, base_ + 10, false))), expected([](int t) { return t >= 7 && t <= 10 && t % 3 != 0; })); } @@ -378,13 +419,15 @@ TEST_P(TableFieldFilterTest, TimeAndTagFiltersComposeWithFieldFilter) { auto field = Expression::compare("flag", Expression::CompareOp::EQ, Expression::Literal::boolean(false)); EXPECT_EQ(scan_field({"id", "v"}, std::move(field), 1, 3, - TimeFilter::gt_eq(base_ + 5), tag.get()), + std::unique_ptr(TimeFilter::gt_eq(base_ + 5)), + tag.get()), std::vector({base_ + 8, base_ + 10, base_ + 12})); } TEST_P(TableFieldFilterTest, NullRowsOutsideValueStatisticsReachPredicate) { EXPECT_EQ(scan_field({"tail_null"}, Expression::is_null("tail_null"), 0, -1, - TimeFilter::between(base_ + 1, base_ + 2, false)), + std::unique_ptr( + TimeFilter::between(base_ + 1, base_ + 2, false))), expected([](int t) { return t == 1 || t == 2; })); } @@ -416,7 +459,8 @@ TEST_P(TableFieldFilterTest, NullOnlyChunksAndAcceptedRowPagination) { EXPECT_EQ(scan_field({"empty"}, Expression::is_null("empty"), 15, 2), std::vector({base_ + 1, base_ + 2})); EXPECT_EQ(scan_field({"empty"}, Expression::is_null("empty"), 1, 2, - TimeFilter::between(base_ + 1, base_ + 2, false)), + std::unique_ptr( + TimeFilter::between(base_ + 1, base_ + 2, false))), std::vector({base_ + 2, base_ + 1})); EXPECT_TRUE( scan_field({"empty"}, Expression::is_not_null("empty")).empty()); 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 47bfe58e6e..5277dcdd60 100644 --- a/cpp/test/reader/table_view/tsfile_reader_table_test.cc +++ b/cpp/test/reader/table_view/tsfile_reader_table_test.cc @@ -359,8 +359,9 @@ TEST_P(TsFileTableReaderTimeFilterTest, QueryContinuesAfterEmptyPageInChunk) { // The second filter also checks exhaustion after two empty pages. ResultSet* raw_result = nullptr; ASSERT_EQ(executor.query(table_schema->get_table_name(), columns, - new TimeIn(selected_times, false), 0, -1, - raw_result), + std::unique_ptr( + new TimeIn(selected_times, false)), + 0, -1, raw_result), common::E_OK); std::unique_ptr result(raw_result); ASSERT_NE(result, nullptr); @@ -505,11 +506,11 @@ TEST_P(TsFileTableReaderTimeFilterTest, NotBetweenFullRangeReturnsNoRows) { const int64_t min_time = std::numeric_limits::min(); const int64_t max_time = std::numeric_limits::max(); ResultSet* result = nullptr; - ASSERT_EQ(executor.query( - table_schema->get_table_name(), - std::vector{"s0", "s1"}, - new TimeBetween(min_time, max_time, /*not_between=*/true), 0, - -1, result), + ASSERT_EQ(executor.query(table_schema->get_table_name(), + std::vector{"s0", "s1"}, + std::unique_ptr(new TimeBetween( + min_time, max_time, /*not_between=*/true)), + 0, -1, result), common::E_OK); ASSERT_NE(nullptr, result); bool has_next = false; @@ -585,11 +586,12 @@ TEST_P(TsFileTableReaderTimeFilterTest, // A 4096-byte budget holds the decoder's 129-row batch for these blocks. TableQueryExecutor executor(&read_file); const std::vector query_columns{"v", "ghost", "w", "v"}; - auto collect_times = [&](Filter* time_filter, std::vector& times) { + auto collect_times = [&](std::unique_ptr time_filter, + std::vector& times) { ResultSet* result = nullptr; - ASSERT_EQ( - executor.query("t", query_columns, time_filter, 0, -1, result), - common::E_OK); + ASSERT_EQ(executor.query("t", query_columns, std::move(time_filter), 0, + -1, result), + common::E_OK); bool has_next = false; int ret = common::E_OK; while ((ret = result->next(has_next)) == common::E_OK && has_next) { @@ -612,7 +614,8 @@ TEST_P(TsFileTableReaderTimeFilterTest, << "parallel=" << GetParam() << ", selected_times=" << ::testing::PrintToString(selected_times)); std::vector times; - collect_times(new TimeIn(selected_times, false), times); + collect_times( + std::unique_ptr(new TimeIn(selected_times, false)), times); std::vector expected; for (int device = 0; device < 3; ++device) { expected.insert(expected.end(), selected_times.begin(), @@ -628,7 +631,7 @@ TEST_P(TsFileTableReaderTimeFilterTest, // No-matching control: the series is empty and still terminates. times.clear(); - collect_times(new TimeIn({100}, false), times); + collect_times(std::unique_ptr(new TimeIn({100}, false)), times); EXPECT_TRUE(times.empty()); } diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 6a1d747ba9..8e0f0407b0 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -85,8 +85,8 @@ int ret = reader.queryByRow("weather", {"temperature"}, 0, 100, rows, ``` TAG expressions match STRING columns in device IDs. A missing trailing TAG -satisfies `is_null` and `NOT(tag = x)`. FIELD expressions evaluate typed -values. A NULL value is excluded by both a comparison and its negation. +satisfies `is_null` and `NOT(tag = x)`. FIELD expressions bind to the same `FieldFilter` for aligned and non-aligned +series. It evaluates typed values at each candidate timestamp. A NULL value is excluded by both a comparison and its negation. Aligned chunks and pages use the same statistics to classify the match before decoding values. Offset and limit apply to matching rows. A TAG expression passed to `prepare_table_series` must select a single device. From 63924c07a02d3ec38b4eb1cbf29976bf81dc1924 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Thu, 3 Dec 2026 17:05:24 +0800 Subject: [PATCH 4/4] Reuse FIELD statistics on time-boundary pages --- cpp/src/reader/aligned_chunk_reader.cc | 127 ++++++------------ cpp/src/reader/aligned_chunk_reader.h | 8 +- .../reader/aligned_chunk_reader_bulk_test.cc | 40 +++++- skills/tsfile/references/advanced-apis.md | 7 +- .../tsfile/references/properties-filters.md | 27 +++- 5 files changed, 108 insertions(+), 101 deletions(-) diff --git a/cpp/src/reader/aligned_chunk_reader.cc b/cpp/src/reader/aligned_chunk_reader.cc index b7deb7185e..215fb4908b 100644 --- a/cpp/src/reader/aligned_chunk_reader.cc +++ b/cpp/src/reader/aligned_chunk_reader.cc @@ -53,7 +53,6 @@ int AlignedChunkReader::init(RandomAccessReadFile* read_file, String m_name, void AlignedChunkReader::reset() { multi_page_error_ = E_OK; - current_page_field_mask_valid_ = false; time_chunk_meta_ = nullptr; value_chunk_meta_ = nullptr; time_chunk_header_.reset(); @@ -133,6 +132,7 @@ void AlignedChunkReader::reset() { per_page_times_.clear(); #ifdef ENABLE_TEST bulk_page_count_ = 0; + field_mask_evaluations_ = 0; #endif } @@ -1541,7 +1541,9 @@ void AlignedChunkReader::build_filter_column_mask() { } int AlignedChunkReader::evaluate_page_field_mask(size_t page_idx) { - if (field_filter_ == nullptr) return E_OK; +#ifdef ENABLE_TEST + ++field_mask_evaluations_; +#endif const ChunkPageInfo& page_info = chunk_pages_[page_idx]; std::vector views; for (uint32_t c = 0; c < value_columns_.size(); ++c) { @@ -1572,12 +1574,8 @@ int AlignedChunkReader::evaluate_page_field_mask(size_t page_idx) { const uint32_t row_count = static_cast(page_info.row_end - page_info.row_begin); - current_page_field_mask_.reset(row_count); - int ret = field_filter_->evaluate_columns(views, row_count, - current_page_field_mask_); - if (ret != E_OK) return ret; - current_page_field_mask_valid_ = true; - return E_OK; + return field_filter_->evaluate_columns(views, row_count, + current_page_field_mask_); } int AlignedChunkReader::decode_output_columns_for_page(size_t page_idx) { @@ -1651,8 +1649,8 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { } bool field_page_skip = false; - bool field_all_match = chunk_field_all_match_; - if (field_filter_ && !field_all_match) { + page_info.needs_field_mask = field_filter_ && !chunk_field_all_match_; + if (page_info.needs_field_mask) { std::map field_statistics; for (uint32_t c = 0; c < num_cols; ++c) { auto* col = value_columns_[c]; @@ -1667,7 +1665,8 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { const auto match = field_filter_->classify(field_statistics, row_count); field_page_skip = match == FieldFilter::StatisticsMatch::None; - field_all_match = match == FieldFilter::StatisticsMatch::All; + page_info.needs_field_mask = + match == FieldFilter::StatisticsMatch::Possible; } Statistic* stat = cur_time_page_header_.statistic_; @@ -1678,8 +1677,7 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { if (field_page_skip || (stat != nullptr && filter != nullptr && !filter->satisfy(stat))) { page_info.pass_type = PagePassType::SKIP; - } else if (time_full_match && - (field_filter_ == nullptr || field_all_match)) { + } else if (time_full_match && !page_info.needs_field_mask) { page_info.pass_type = PagePassType::FULL_PASS; page_info.row_begin = 0; page_info.row_end = stat != nullptr ? stat->count_ : 0; @@ -1700,17 +1698,10 @@ int AlignedChunkReader::build_page_plan(Filter* filter, int& row_offset) { const int32_t n = static_cast(decoded_page_times.size()); if (filter->is_unbounded_time_filter()) { - // Every timestamp matches, so the per-row predicate can - // be skipped. Without a FIELD filter the whole page is - // passed and takes the bulk-copy path; the shared - // FULL_PASS handling below consumes OFFSET. With a FIELD - // filter the exact rows depend on statistics that are not - // available here, so the page stays a boundary page and - // the mask decides (OFFSET is applied after the mask). if (n > 0) { first = 0; last = n - 1; - if (field_filter_ == nullptr) { + if (!page_info.needs_field_mask) { page_info.pass_type = PagePassType::FULL_PASS; } } @@ -2282,38 +2273,11 @@ int AlignedChunkReader::decode_page_lazy(size_t page_idx) { per_page_times_[page_idx]))) { return ret; } - if (field_filter_ != nullptr && - filter_column_mask_.size() != value_columns_.size()) { - build_filter_column_mask(); - } - if (field_filter_ == nullptr) { - for (uint32_t c = 0; c < value_columns_.size(); ++c) { - if (RET_FAIL(decode_value_page_for_slot(c, page_idx))) return ret; - } - return E_OK; - } - if (chunk_pages_[page_idx].pass_type == PagePassType::FULL_PASS) { - // Every row matches; no mask evaluation is needed, so decode all - // columns once instead of first decoding the filter columns. - for (uint32_t c = 0; c < value_columns_.size(); ++c) { - if (RET_FAIL(decode_value_page_for_slot(c, page_idx))) return ret; - } - current_page_field_mask_.reset(static_cast( - chunk_pages_[page_idx].row_end - chunk_pages_[page_idx].row_begin)); - current_page_field_mask_.set_all(); - current_page_field_mask_valid_ = true; - return E_OK; - } - - // BOUNDARY page: decode only the filter columns, evaluate the mask, then - // decode output columns only when at least one row survives. for (uint32_t c = 0; c < value_columns_.size(); ++c) { - if (!filter_column_mask_[c]) continue; + if (field_filter_ && !filter_column_mask_[c]) continue; if (RET_FAIL(decode_value_page_for_slot(c, page_idx))) return ret; } - if (RET_FAIL(evaluate_page_field_mask(page_idx))) return ret; - if (current_page_field_mask_.empty()) return E_OK; - return decode_output_columns_for_page(page_idx); + return E_OK; } // Release the decoded buffers of one page slot so they can be reused by the @@ -2333,15 +2297,14 @@ void AlignedChunkReader::release_page_slot(size_t page_idx) { } } -int AlignedChunkReader::validate_page_slot(size_t page_idx) const { +int AlignedChunkReader::validate_page_slot(size_t page_idx, + bool outputs_skipped) const { const auto& page = chunk_pages_[page_idx]; const auto& times = per_page_times_[page_idx]; if (page.row_begin < 0 || page.row_end < page.row_begin || static_cast(page.row_end) > times.size()) { return E_TSFILE_CORRUPTED; } - const bool outputs_skipped = - field_filter_ != nullptr && current_page_field_mask_.empty(); for (size_t c = 0; c < value_columns_.size(); ++c) { // An empty FIELD mask deliberately leaves output-only columns unread. if (outputs_skipped && !filter_column_mask_[c]) continue; @@ -2420,42 +2383,33 @@ int AlignedChunkReader::get_next_page_multi_impl(TsBlock* ret_tsblock, const ChunkPageInfo& page_info = chunk_pages_[current_page_plan_index_]; if (!current_page_loaded_) { - current_page_field_mask_valid_ = false; - if (single_thread_lazy) { - if (RET_FAIL(decode_page_lazy(current_page_plan_index_))) { - return ret; - } + if (single_thread_lazy && + RET_FAIL(decode_page_lazy(current_page_plan_index_))) { + return ret; } - page_time_cursor_ = page_info.row_begin; - page_time_count_ = page_info.row_end; - current_page_loaded_ = true; - } - - if (field_filter_ != nullptr && !current_page_field_mask_valid_) { - if (page_info.pass_type == PagePassType::FULL_PASS) { - current_page_field_mask_.reset(static_cast( - page_info.row_end - page_info.row_begin)); - current_page_field_mask_.set_all(); - current_page_field_mask_valid_ = true; - } else if (RET_FAIL(evaluate_page_field_mask( - current_page_plan_index_))) { + if (page_info.needs_field_mask && + RET_FAIL(evaluate_page_field_mask(current_page_plan_index_))) { return ret; } - if (!single_thread_lazy && !current_page_field_mask_.empty() && - RET_FAIL( - decode_output_columns_for_page(current_page_plan_index_))) { + const bool skip_outputs = + page_info.needs_field_mask && current_page_field_mask_.empty(); + if (!skip_outputs && RET_FAIL(decode_output_columns_for_page( + current_page_plan_index_))) { return ret; } - } - if (RET_FAIL(validate_page_slot(current_page_plan_index_))) return ret; - // Lazy decoding may already have produced the mask, including an - // empty one that deliberately left output columns undecoded. - if (field_filter_ != nullptr && current_page_field_mask_.empty()) { - if (single_thread_lazy) release_page_slot(current_page_plan_index_); - current_page_plan_index_++; - current_page_loaded_ = false; - current_page_field_mask_valid_ = false; - continue; + if (RET_FAIL(validate_page_slot(current_page_plan_index_, + skip_outputs))) { + return ret; + } + if (skip_outputs) { + if (single_thread_lazy) + release_page_slot(current_page_plan_index_); + ++current_page_plan_index_; + continue; + } + page_time_cursor_ = page_info.row_begin; + page_time_count_ = page_info.row_end; + current_page_loaded_ = true; } const std::vector& times = @@ -2479,7 +2433,7 @@ int AlignedChunkReader::get_next_page_multi_impl(TsBlock* ret_tsblock, // range, so those pages must stay on the row-by-row path. const bool boundary_contiguous = page_info.pass_type == PagePassType::BOUNDARY && - field_filter_ == nullptr && + !page_info.needs_field_mask && (filter == nullptr || filter->is_contiguous_time_filter()); bool can_bulk = (page_info.pass_type == PagePassType::FULL_PASS || boundary_contiguous) && @@ -2588,7 +2542,7 @@ int AlignedChunkReader::get_next_page_multi_impl(TsBlock* ret_tsblock, int64_t ts = times[page_time_cursor_]; const uint32_t field_row = page_time_cursor_ - page_info.row_begin; const bool field_rejected = - field_filter_ != nullptr && + page_info.needs_field_mask && !current_page_field_mask_.test(field_row); if (field_rejected || (boundary_filter && !filter->satisfy_start_end_time(ts, ts))) { @@ -2666,7 +2620,6 @@ int AlignedChunkReader::get_next_page_multi_impl(TsBlock* ret_tsblock, } current_page_plan_index_++; current_page_loaded_ = false; - current_page_field_mask_valid_ = false; } return E_NO_MORE_DATA; } diff --git a/cpp/src/reader/aligned_chunk_reader.h b/cpp/src/reader/aligned_chunk_reader.h index d12bf2dc3e..bcc5e01e53 100644 --- a/cpp/src/reader/aligned_chunk_reader.h +++ b/cpp/src/reader/aligned_chunk_reader.h @@ -43,6 +43,7 @@ enum class PagePassType { SKIP, FULL_PASS, BOUNDARY }; // Metadata collected per page during the chunk scan phase. struct ChunkPageInfo { PagePassType pass_type = PagePassType::SKIP; + bool needs_field_mask = false; // File offsets of compressed data for time and each value column. int64_t time_file_offset = 0; uint32_t time_compressed_size = 0; @@ -196,6 +197,9 @@ class AlignedChunkReader : public IChunkReader { // Pages scattered by the bulk-copy path so far (FULL_PASS pages and // BOUNDARY pages a contiguous time filter proves fully matched). size_t TEST_bulk_page_count() const { return bulk_page_count_; } + size_t TEST_field_mask_evaluations() const { + return field_mask_evaluations_; + } // Leading pages of the current plan that decode straight into the // destination block's column buffers (see prepare_direct_decode()). size_t TEST_direct_page_end() const { return direct_page_end_; } @@ -287,7 +291,7 @@ class AlignedChunkReader : public IChunkReader { int get_next_page_multi_impl(common::TsBlock* ret_tsblock, Filter* oneshoot_filter, common::PageArena& pa, int& row_offset); - int validate_page_slot(size_t page_idx) const; + int validate_page_slot(size_t page_idx, bool outputs_skipped) const; int get_next_page_multi_serial(common::TsBlock* ret_tsblock, Filter* filter, common::PageArena& pa, int& row_offset); int skip_cur_page_multi(); @@ -379,7 +383,6 @@ class AlignedChunkReader : public IChunkReader { size_t current_page_plan_index_ = 0; std::vector filter_column_mask_; SelectionMask current_page_field_mask_; - bool current_page_field_mask_valid_ = false; // Direct decode: pages [0, direct_page_end_) are decoded straight into the // destination Vector memory instead of a per-page staging buffer. See @@ -395,6 +398,7 @@ class AlignedChunkReader : public IChunkReader { #ifdef ENABLE_TEST size_t bulk_page_count_ = 0; + size_t field_mask_evaluations_ = 0; #endif #ifdef ENABLE_THREADS diff --git a/cpp/test/reader/aligned_chunk_reader_bulk_test.cc b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc index 7788df82c8..ea8bfeb902 100644 --- a/cpp/test/reader/aligned_chunk_reader_bulk_test.cc +++ b/cpp/test/reader/aligned_chunk_reader_bulk_test.cc @@ -208,15 +208,16 @@ class AlignedBulkCopyTest : public ::testing::Test { std::vector read_all(const std::vector& columns, Filter* time_filter, uint32_t block_rows, size_t* max_direct_pages = nullptr, - size_t* bulk_pages = nullptr) { + size_t* bulk_pages = nullptr, + bool chunk_field_all_match = false) { if (max_direct_pages != nullptr) *max_direct_pages = 0; if (bulk_pages != nullptr) *bulk_pages = 0; std::vector value_metas; for (const auto& name : columns) { value_metas.push_back(value_metas_[name]); } - if (reader_->load_by_aligned_meta_multi(time_meta_, value_metas) != - E_OK) { + if (reader_->load_by_aligned_meta_multi( + time_meta_, value_metas, chunk_field_all_match) != E_OK) { ADD_FAILURE() << "load_by_aligned_meta_multi failed"; return {}; } @@ -439,6 +440,38 @@ TEST_F(AlignedBulkCopyTest, RowsSpanMultipleBlocks) { } } +TEST_F(AlignedBulkCopyTest, TimeBoundariesReuseFieldStatistics) { + using E = Expression; + TimeIn times({kBaseTime + 9, kBaseTime + 12, kBaseTime + 17}, false); + // One column uses lazy decode. Two columns also exercise the worker pool. + for (const auto& columns : + {std::vector{"v"}, std::vector{"v", "w"}}) { + for (bool chunk_all_match : {false, true}) { + SCOPED_TRACE(::testing::Message() + << "columns=" << columns.size() + << ", chunk_all_match=" << chunk_all_match); + reader_->reset(); + // v contains the row index. The whole chunk satisfies v >= 0. + // For v >= 8 only the retained pages prove a full FIELD match. + auto expr = E::compare("v", E::CompareOp::GE, + E::Literal::int64(chunk_all_match ? 0 : 8)); + FieldFilter::Ptr filter; + ASSERT_EQ(E_OK, FieldFilter::bind(*expr, *schema_, filter)); + reader_->set_field_filter(filter.get()); + const auto rows = + read_all(columns, ×, 1, nullptr, nullptr, chunk_all_match); + ASSERT_EQ(3u, rows.size()); + const int indices[] = {9, 12, 17}; + for (size_t i = 0; i < rows.size(); ++i) { + EXPECT_EQ(kBaseTime + indices[i], rows[i].time); + EXPECT_EQ(indices[i], rows[i].v); + if (columns.size() == 2) EXPECT_EQ(2 * indices[i], rows[i].w); + } + EXPECT_EQ(0u, reader_->TEST_field_mask_evaluations()); + } + } +} + // A field predicate can still reject rows inside a page's retained range, so a // 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. @@ -452,6 +485,7 @@ TEST_F(AlignedBulkCopyTest, FieldFilterKeepsPartialPageOnSlowPath) { ASSERT_NE(field_filter, nullptr); reader_->set_field_filter(field_filter.get()); const std::vector rows = read_all({"v", "w"}, nullptr, kRowCount); + EXPECT_GT(reader_->TEST_field_mask_evaluations(), 0u); ASSERT_EQ(rows.size(), static_cast(kRowCount - 12)); for (int r = 12; r < kRowCount; r++) { EXPECT_EQ(rows[r - 12].time, kBaseTime + r); diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 23005997fd..71757cbc6e 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -25,14 +25,17 @@ the listed current source. ## Row-window Queries - C++ exposes `TsFileReader::queryByRow` for Tree paths and for Table columns, - with `offset`, `limit`, optional Table TAG filter, and optional batch size. + with `offset` and `limit`. The Table overload also accepts optional + `tag_filter` and `field_filter` expressions followed by `batch_size`. `TsFileTreeReader::queryByRow` accepts device and measurement lists. - Python exposes `query_tree_by_row` and `query_table_by_row`; Table queries accept `tag_filter` and `batch_size`. - Treat `limit < 0` as unlimited and reject negative offsets. Close or destroy every result set through the binding that created it. - Table `TsFileReader::query` also has an overload combining start/end times, - offset/limit, a TAG filter, and batch size; `queryByRow` has no time bounds. + offset/limit, TAG and FIELD expressions, and batch size. Use `queryByRow` + for a row window without time bounds. See the + [C++ table query examples](properties-filters.md#c-table-queries). ## Timestamp Ordering diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 8e0f0407b0..f5c3fedd6b 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -85,15 +85,28 @@ int ret = reader.queryByRow("weather", {"temperature"}, 0, 100, rows, ``` TAG expressions match STRING columns in device IDs. A missing trailing TAG -satisfies `is_null` and `NOT(tag = x)`. FIELD expressions bind to the same `FieldFilter` for aligned and non-aligned -series. It evaluates typed values at each candidate timestamp. A NULL value is excluded by both a comparison and its negation. -Aligned chunks and pages use the same statistics to classify the match before -decoding values. Offset and limit apply to matching rows. A TAG expression -passed to `prepare_table_series` must select a single device. +satisfies `is_null` and `NOT(tag = x)`. FIELD expressions bind to the same +`FieldFilter` for aligned and non-aligned series. It evaluates typed values +at each candidate timestamp. A NULL value is excluded by both a comparison +and its negation. Aligned chunks and pages use the same statistics to classify +the match. When every row satisfies the FIELD predicate, the reader can still +apply the time range without evaluating the FIELD predicate again. Offset and +limit apply to matching rows. A TAG expression passed to `prepare_table_series` +must select a single device. When upgrading, replace indexed TAG constructors and FIELD filter builders -with the named factories above. Recompile and relink C++ applications against -the headers and library shipped in the new SDK. +with the named factories above. In both `query` and `queryByRow`, the FIELD +expression now comes immediately before the batch size. For a TAG-only query +with an explicit batch size, pass `nullptr` in that position. + +```cpp +int batch_size = 1024; +int ret = reader.query("weather", {"temperature"}, start_time, end_time, + rows, site.get(), nullptr, batch_size); +``` + +Recompile and relink C++ applications against the headers and library shipped +in the new SDK. ## Source Anchors