You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by yi...@apache.org on 2024/01/23 02:13:10 UTC
(doris) branch branch-2.1 updated (09d46dc6e4c -> fb2145fe961)
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a change to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
from 09d46dc6e4c 2.1.0-rc05
new f66f6b2a822 [refactor](close) refactor ispendingfinish logic and close logic to do close more quickly (#30021)
new 8a75da0fec3 [enhance-wip](multi-catalog) Speed up consume rate of hms events. (#27666)
new 21db1ecff20 [fix](tablet meta) stale rowset is not loaded while BE start (#30077)
new caf7790797c [pipelineX](filescan) Support parallel executing for external table scanning (#30121)
new 7cc85f893c8 [ci](perf) add required (#30155)
new 7180ca707c4 [doc](ranger) update ranger doc #30101
new c8be73934d1 [fix](ci) remove required of performance (#30185)
new ec898f26770 Revert "[ci](perf) add required (#30155)" (#30165)
new ead3b4ac1db [feature](function) support ip function is_ipv4_compat, is_ipv4_mapped (#29954)
new a9ab0946141 [Bug](fix) try to fix the coredump of streambyte decode of sse (#30190)
new 1bb1d35f709 [fix](group commit) Fix some group commit case (#30132)
new 332b9cb6199 [opt](nereids) do not change RuntimeFilter Type from IN-OR_BLOOM to BLOOM on broadcast join (#30148)
new 9dd368f8dcf [config](load) set default memtable_flush_running_count_limit to 2 (#30146)
new e5f1d8d7ec5 [fix](phrase_prefix) fix match_phrase_prefix query incorrect result (#29946)
new 4480f751e62 [Improve](Variant) support implicit cast to numeric and string type (#30029)
new dfde10d4c8a [improvement](function) switch inet(6)_aton alias origin function (#30196)
new 06f8266ca21 [regression test](schema change) add boolean type check for agg (#30186)
new ad1c19bd656 [refactor](Nereids): Eager Aggregation unify pushdown agg function (#30142)
new 9a58cacf0f5 [Improvement](nereids) Make sure to catch and record exception for every materialization context (#29953)
new d0dd0904586 [fix](routine-load) optimize error msg when meet out of range (#30118)
new 3e73933857d [fix](routineload) check offset when schedule tasks (#30136)
new 62a46876b62 [improvement](statistics) Optimize drop stats operation (#30144)
new 5a7ce5cbf55 [temporary](log) Add temporary log for debug insert into lost result (#30140)
new cd0ca2b3af0 [docs](ip function) add ipv4/v6 datatype and some ip functions' docs (#30194)
new e5dea910bf3 [feature](bitwise function) bit_count/bit_shift_left/bit_shift_right implementation (#30046)
new 24c0900b419 [fix](planner) should return outputTupleDesc's id instead of tupleIds if outputTupleDesc is set in Plan Node (#30150)
new 5c43708d920 [Fix](Job)Incorrect task query result of insert type (#30024)
new 8061597f2a0 [fix](Nereids) nullable not adjust in output exprs in result sink node (#30206)
new 1b1e088e832 [fix](exec_node) crashing caused by cancelled query in ExecNode (#30192)
new 9b100207d23 [docker](container)create data path after rm residual data avoiding docker start fail (#30141)
new 45f6cba837d [fix](Nereids) Fixed a bug where the execution plan was incorrect after ddl (#30107)
new 68e67470c0a [Improvement](doc) add table-buckets doc for flink connector (#29672)
new d5d0e5e6118 [feature](function) support ip functions named to_ipv4[or_default, or_null](string) and to_ipv6[or_default, or_null](string) (#29838)
new 60ce22f15e8 [fix](auto-partition) Fix a concurrent bug (#30086)
new ce47354d598 [fix](Nereids) result nullable of sum distinct in scalar agg is wrong (#30221)
new 24ed3e41030 [Fix](Expr&code-style) check prepare&open before every VExpr execute (#26673)
new b3296a2a16c [fix](Nereids) user identify syntax is wrong (#30226)
new 9e0c518aaf4 [Feature](executor)Workload Group support Non-Pipeline Execution (#30164)
new 9c742d46a23 [fix](group commit) abort txn should use label if replay wal failed (#30219)
new 32c5153999d [fix](routine-load) pause job when json path is invalid #30197
new bb6fff3455f [fix](move-memtable) make sure index descriptor is set when creating delta writer (#30157)
new 510d88f3150 [fix](mtmv)return MTMV with at least one available partition #30156
new fb2145fe961 [fix](fe) Upgrade mariadb client version from 3.0.4 to 3.0.9 (#30242)
The 43 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
be/src/agent/workload_group_listener.cpp | 6 +-
be/src/common/config.cpp | 4 +-
be/src/common/status.h | 2 +
be/src/exec/data_sink.h | 2 +-
be/src/exec/exec_node.cpp | 72 ++--
be/src/exec/exec_node.h | 19 +-
.../inverted_index/query/phrase_prefix_query.cpp | 5 +-
be/src/olap/tablet_meta.cpp | 7 +
be/src/olap/wal/wal_manager.cpp | 10 +-
be/src/olap/wal/wal_table.cpp | 29 +-
be/src/olap/wal/wal_table.h | 2 +-
be/src/pipeline/exec/jdbc_table_sink_operator.h | 1 +
.../exec/multi_cast_data_stream_source.cpp | 8 +-
be/src/pipeline/exec/olap_table_sink_operator.h | 1 +
be/src/pipeline/exec/olap_table_sink_v2_operator.h | 1 +
be/src/pipeline/exec/operator.h | 20 +-
.../pipeline/exec/partition_sort_sink_operator.cpp | 2 -
be/src/pipeline/exec/result_file_sink_operator.cpp | 6 +-
be/src/pipeline/exec/result_file_sink_operator.h | 1 +
be/src/pipeline/exec/set_sink_operator.cpp | 16 +-
be/src/pipeline/exec/sort_sink_operator.cpp | 1 -
be/src/pipeline/exec/table_function_operator.cpp | 1 -
be/src/pipeline/pipeline_fragment_context.cpp | 33 +-
be/src/pipeline/pipeline_fragment_context.h | 4 +-
be/src/pipeline/pipeline_x/operator.cpp | 14 +-
be/src/pipeline/pipeline_x/operator.h | 5 +
.../pipeline_x/pipeline_x_fragment_context.cpp | 5 +-
be/src/runtime/fragment_mgr.cpp | 61 ++--
be/src/runtime/group_commit_mgr.cpp | 12 +-
be/src/runtime/query_context.cpp | 25 ++
be/src/runtime/query_context.h | 13 +-
be/src/runtime/result_writer.h | 2 +
be/src/runtime/runtime_state.cpp | 18 -
be/src/runtime/runtime_state.h | 5 -
be/src/runtime/tablets_channel.cpp | 2 +-
be/src/runtime/task_group/task_group_manager.cpp | 57 +++-
be/src/runtime/task_group/task_group_manager.h | 9 +-
.../workload_sched_policy_mgr.cpp | 1 -
be/src/service/point_query_executor.cpp | 10 +-
be/src/vec/columns/column_nullable.cpp | 6 +-
be/src/vec/columns/column_nullable.h | 4 +-
be/src/vec/common/unaligned.h | 33 +-
be/src/vec/core/block.cpp | 3 +-
be/src/vec/data_types/data_type_decimal.cpp | 2 -
be/src/vec/exec/format/json/new_json_reader.cpp | 6 +-
be/src/vec/exec/join/vjoin_node_base.h | 19 +-
be/src/vec/exec/scan/scanner_context.h | 2 +-
be/src/vec/exec/vpartition_sort_node.cpp | 3 -
be/src/vec/exec/vset_operation_node.cpp | 7 +-
be/src/vec/exec/vset_operation_node.h | 7 +-
be/src/vec/exec/vsort_node.cpp | 2 -
be/src/vec/exec/vtable_function_node.cpp | 1 -
be/src/vec/exec/vunion_node.cpp | 25 +-
be/src/vec/exprs/vbitmap_predicate.cpp | 4 +
be/src/vec/exprs/vbloom_predicate.cpp | 4 +
be/src/vec/exprs/vcase_expr.cpp | 9 +-
be/src/vec/exprs/vcast_expr.cpp | 4 +
be/src/vec/exprs/vcolumn_ref.h | 10 +
be/src/vec/exprs/vdirect_in_predicate.h | 19 +-
be/src/vec/exprs/vectorized_fn_call.cpp | 19 +-
be/src/vec/exprs/vexpr.cpp | 62 ++--
be/src/vec/exprs/vexpr.h | 63 ++--
be/src/vec/exprs/vexpr_context.cpp | 28 +-
be/src/vec/exprs/vexpr_context.h | 15 +-
be/src/vec/exprs/vin_predicate.cpp | 4 +
be/src/vec/exprs/vlambda_function_call_expr.h | 12 +-
be/src/vec/exprs/vlambda_function_expr.h | 15 +
be/src/vec/exprs/vliteral.cpp | 19 +-
be/src/vec/exprs/vliteral.h | 5 +
be/src/vec/exprs/vmatch_predicate.cpp | 5 +-
be/src/vec/exprs/vruntimefilter_wrapper.cpp | 15 +-
be/src/vec/exprs/vslot_ref.cpp | 11 +
be/src/vec/exprs/vslot_ref.h | 5 +-
be/src/vec/exprs/vtuple_is_null_predicate.cpp | 9 +
be/src/vec/exprs/vtuple_is_null_predicate.h | 4 +-
be/src/vec/functions/function_bit_count.cpp | 61 ++++
be/src/vec/functions/function_bit_shift.cpp | 90 +++++
be/src/vec/functions/function_ip.cpp | 26 +-
be/src/vec/functions/function_ip.h | 349 ++++++++++++++-----
be/src/vec/functions/simple_function_factory.h | 4 +
be/src/vec/runtime/vdata_stream_recvr.h | 8 +-
be/src/vec/sink/async_writer_sink.h | 23 +-
be/src/vec/sink/vresult_file_sink.cpp | 19 +-
be/src/vec/sink/writer/async_result_writer.cpp | 23 +-
be/src/vec/sink/writer/async_result_writer.h | 7 -
be/src/vec/sink/writer/vjdbc_table_writer.h | 6 +-
be/src/vec/sink/writer/vodbc_table_writer.h | 6 +-
be/src/vec/sink/writer/vtablet_writer.cpp | 83 +++--
be/src/vec/sink/writer/vtablet_writer.h | 12 +-
be/src/vec/sink/writer/vtablet_writer_v2.cpp | 12 +
docker/thirdparties/run-thirdparties-docker.sh | 10 +-
docs/en/docs/ecosystem/flink-doris-connector.md | 4 +-
docs/en/docs/lakehouse/multi-catalog/hive.md | 13 +
.../inet-aton.md => bitwise-functions/bitcount.md} | 43 +--
.../bitwise-functions/bitshfitleft.md | 71 ++++
.../bitwise-functions/bitshfitright.md | 79 +++++
.../sql-functions/ip-functions/inet-aton.md | 20 +-
.../sql-functions/ip-functions/inet6-aton.md | 30 +-
.../ip-functions/ipv4-cidr-to-range.md | 72 ++++
.../ip-functions/ipv6-cidr-to-range.md | 72 ++++
.../ip-functions/is-ip-address-in-range.md | 65 ++++
.../{inet-aton.md => is-ipv4-compat.md} | 44 +--
.../sql-functions/ip-functions/is-ipv4-mapped.md | 69 ++++
.../sql-functions/ip-functions/is-ipv4-string.md | 80 +++++
.../sql-functions/ip-functions/is-ipv6-string.md | 80 +++++
.../{inet-aton.md => to-ipv4-or-default.md} | 38 ++-
.../{inet-aton.md => to-ipv4-or-null.md} | 38 ++-
.../ip-functions/{inet-aton.md => to-ipv4.md} | 33 +-
.../{inet-aton.md => to-ipv6-or-default.md} | 38 ++-
.../{inet-aton.md => to-ipv6-or-null.md} | 38 ++-
.../ip-functions/{inet-aton.md => to-ipv6.md} | 33 +-
.../sql-manual/sql-reference/Data-Types/IPV4.md | 85 +++++
.../sql-manual/sql-reference/Data-Types/IPV6.md | 83 +++++
.../sql-manual/sql-reference/Data-Types/STRUCT.md | 2 +-
docs/sidebars.json | 22 +-
docs/zh-CN/docs/ecosystem/flink-doris-connector.md | 2 +-
docs/zh-CN/docs/lakehouse/multi-catalog/hive.md | 13 +
.../inet-aton.md => bitwise-functions/bitcount.md} | 45 +--
.../bitwise-functions/bitshiftleft.md | 71 ++++
.../bitwise-functions/bitshiftright.md | 78 +++++
.../sql-functions/ip-functions/inet-aton.md | 19 +-
.../sql-functions/ip-functions/inet6-aton.md | 29 +-
.../ip-functions/ipv4-cidr-to-range.md | 72 ++++
.../ip-functions/ipv6-cidr-to-range.md | 72 ++++
.../ip-functions/is-ip-address-in-range.md | 65 ++++
.../{inet-aton.md => is-ipv4-compat.md} | 44 +--
.../sql-functions/ip-functions/is-ipv4-mapped.md | 68 ++++
.../sql-functions/ip-functions/is-ipv4-string.md | 80 +++++
.../sql-functions/ip-functions/is-ipv6-string.md | 80 +++++
.../{inet-aton.md => to-ipv4-or-default.md} | 38 ++-
.../{inet-aton.md => to-ipv4-or-null.md} | 38 ++-
.../ip-functions/{inet-aton.md => to-ipv4.md} | 33 +-
.../{inet-aton.md => to-ipv6-or-default.md} | 38 ++-
.../{inet-aton.md => to-ipv6-or-null.md} | 38 ++-
.../ip-functions/{inet-aton.md => to-ipv6.md} | 33 +-
.../sql-manual/sql-reference/Data-Types/IPV4.md | 85 +++++
.../sql-manual/sql-reference/Data-Types/IPV6.md | 83 +++++
.../antlr4/org/apache/doris/nereids/DorisParser.g4 | 2 +-
.../org/apache/doris/alter/SchemaChangeJobV2.java | 15 +-
.../java/org/apache/doris/alter/SystemHandler.java | 11 +-
.../org/apache/doris/analysis/BinaryPredicate.java | 8 +
.../org/apache/doris/analysis/DropStatsStmt.java | 19 ++
.../org/apache/doris/analysis/MatchPredicate.java | 10 +-
.../apache/doris/analysis/NativeInsertStmt.java | 2 +-
.../doris/catalog/BuiltinScalarFunctions.java | 30 +-
.../main/java/org/apache/doris/catalog/Env.java | 17 +-
.../doris/catalog/external/ExternalDatabase.java | 20 +-
.../catalog/external/HMSExternalDatabase.java | 13 +-
.../catalog/external/IcebergExternalDatabase.java | 4 +-
.../catalog/external/PaimonExternalDatabase.java | 4 +-
.../org/apache/doris/datasource/CatalogMgr.java | 257 ++------------
.../apache/doris/datasource/ExternalCatalog.java | 14 +-
.../apache/doris/datasource/ExternalMetaIdMgr.java | 263 +++++++++++++++
.../doris/datasource/HMSExternalCatalog.java | 107 ++----
.../org/apache/doris/datasource/InitTableLog.java | 67 ----
.../apache/doris/datasource/MetaIdMappingsLog.java | 274 +++++++++++++++
.../datasource/hive/event/AddPartitionEvent.java | 16 +
.../datasource/hive/event/AlterTableEvent.java | 6 +-
.../datasource/hive/event/CreateDatabaseEvent.java | 12 +
.../datasource/hive/event/CreateTableEvent.java | 14 +-
.../datasource/hive/event/DropDatabaseEvent.java | 11 +
.../datasource/hive/event/DropPartitionEvent.java | 17 +-
.../datasource/hive/event/DropTableEvent.java | 15 +-
.../datasource/hive/event/MetastoreEvent.java | 9 +
.../hive/event/MetastoreEventFactory.java | 26 +-
.../hive/event/MetastoreEventsProcessor.java | 225 +++++++++++--
.../doris/httpv2/rest/CheckWalSizeAction.java | 3 +-
.../org/apache/doris/httpv2/rest/LoadAction.java | 23 +-
.../org/apache/doris/job/base/AbstractJob.java | 15 +-
.../doris/job/extensions/insert/InsertJob.java | 46 ++-
.../doris/job/extensions/insert/InsertTask.java | 30 +-
.../org/apache/doris/job/manager/JobManager.java | 23 +-
.../apache/doris/job/scheduler/JobScheduler.java | 6 +-
.../org/apache/doris/journal/JournalEntity.java | 20 +-
.../org/apache/doris/load/GroupCommitManager.java | 25 +-
.../load/routineload/KafkaRoutineLoadJob.java | 23 +-
.../doris/load/routineload/KafkaTaskInfo.java | 2 +-
.../doris/load/routineload/RoutineLoadJob.java | 25 +-
.../load/routineload/RoutineLoadTaskInfo.java | 2 +-
.../load/routineload/RoutineLoadTaskScheduler.java | 16 +-
.../main/java/org/apache/doris/mtmv/MTMVCache.java | 4 +-
.../org/apache/doris/mtmv/MTMVRelationManager.java | 21 +-
.../doris/nereids/analyzer/UnboundResultSink.java | 5 +
.../doris/nereids/analyzer/UnboundTableSink.java | 6 +
.../glue/translator/RuntimeFilterTranslator.java | 6 -
.../processor/post/RuntimeFilterGenerator.java | 2 +-
.../AdjustAggregateNullableForEmptySet.java | 3 +-
.../mv/AbstractMaterializedViewAggregateRule.java | 114 +++----
.../mv/AbstractMaterializedViewJoinRule.java | 17 +-
.../mv/AbstractMaterializedViewRule.java | 372 ++++++++++++---------
.../mv/InitMaterializationContextHook.java | 2 +-
.../mv/MaterializedViewAggregateRule.java | 2 +-
.../nereids/rules/exploration/mv/Predicates.java | 28 +-
.../nereids/rules/exploration/mv/StructInfo.java | 147 +++++---
.../rules/implementation/AggregateStrategies.java | 44 +--
.../LogicalOlapScanToPhysicalOlapScan.java | 10 +-
.../nereids/rules/rewrite/AdjustNullable.java | 8 +
.../nereids/rules/rewrite/NormalizeToSlot.java | 23 +-
.../rules/rewrite/PushDownMinMaxThroughJoin.java | 17 +-
.../rules/rewrite/PushDownSumThroughJoin.java | 4 +-
.../rewrite/PushDownSumThroughJoinOneSide.java | 117 +------
.../org/apache/doris/nereids/trees/TreeNode.java | 17 -
.../trees/expressions/functions/agg/Sum.java | 6 +
.../expressions/functions/scalar/BitCount.java | 67 ++++
.../expressions/functions/scalar/BitShiftLeft.java | 61 ++++
.../functions/scalar/BitShiftRight.java | 63 ++++
.../expressions/functions/scalar/IsIpv4Compat.java | 67 ++++
.../expressions/functions/scalar/IsIpv4Mapped.java | 67 ++++
.../trees/expressions/functions/scalar/ToIpv4.java | 67 ++++
.../functions/scalar/ToIpv4OrDefault.java | 67 ++++
.../expressions/functions/scalar/ToIpv4OrNull.java | 67 ++++
.../trees/expressions/functions/scalar/ToIpv6.java | 67 ++++
.../functions/scalar/ToIpv6OrDefault.java | 67 ++++
.../expressions/functions/scalar/ToIpv6OrNull.java | 67 ++++
.../expressions/visitor/ScalarFunctionVisitor.java | 55 +++
.../logical/LogicalDeferMaterializeResultSink.java | 7 +
.../trees/plans/logical/LogicalFileSink.java | 2 +-
.../trees/plans/logical/LogicalOlapTableSink.java | 5 +
.../trees/plans/logical/LogicalProject.java | 4 +
.../trees/plans/logical/LogicalResultSink.java | 5 +
.../nereids/trees/plans/logical/LogicalSink.java | 2 +
.../trees/plans/physical/AbstractPhysicalJoin.java | 15 +
.../trees/plans/physical/AbstractPhysicalPlan.java | 21 +-
.../trees/plans/physical/RuntimeFilter.java | 4 +
.../apache/doris/nereids/util/ExpressionUtils.java | 4 +-
.../java/org/apache/doris/persist/EditLog.java | 29 +-
.../org/apache/doris/persist/OperationType.java | 9 +
.../apache/doris/planner/GroupCommitPlanner.java | 3 -
.../org/apache/doris/planner/OlapScanNode.java | 5 +
.../java/org/apache/doris/planner/PlanNode.java | 3 +
.../java/org/apache/doris/planner/ScanNode.java | 7 +-
.../doris/planner/external/FileQueryScanNode.java | 12 +
.../main/java/org/apache/doris/qe/Coordinator.java | 3 +
.../java/org/apache/doris/qe/StmtExecutor.java | 2 +-
.../org/apache/doris/rewrite/FunctionAlias.java | 4 +-
.../apache/doris/service/FrontendServiceImpl.java | 36 +-
.../apache/doris/statistics/AnalysisManager.java | 70 +++-
.../doris/statistics/InvalidateStatsTarget.java | 44 ++-
.../apache/doris/statistics/StatisticsCache.java | 17 +-
.../apache/doris/transaction/TransactionState.java | 3 +-
.../doris/datasource/ExternalMetaIdMgrTest.java | 76 +++++
.../doris/datasource/MetaIdMappingsLogTest.java | 97 ++++++
.../external/hms/MetastoreEventFactoryTest.java | 2 +-
fe/pom.xml | 2 +-
gensrc/proto/internal_service.proto | 6 +-
gensrc/script/doris_builtins_functions.py | 43 ++-
gensrc/thrift/FrontendService.thrift | 2 +
gensrc/thrift/PaloInternalService.thrift | 19 +-
gensrc/thrift/Status.thrift | 1 +
.../data/correctness_p0/test_bit_function.out | 132 ++++++++
.../data/correctness_p0/test_bit_shift_lagency.out | 345 +++++++++++++++++++
.../data/correctness_p0/test_bit_shift_nereids.out | 345 +++++++++++++++++++
.../correctness_p0/test_nested_lateral_view.out | 15 +
.../test_index_match_phrase_prefix_1.out} | 13 +-
.../data/nereids_function_p0/ip_functions.out | 68 +++-
.../mv/agg_with_roll_up/aggregate_with_roll_up.out | 6 +
.../data/nereids_syntax_p0/agg_with_empty_set.out | 3 +
.../rf_prune/query64.out | 16 +-
.../nereids_tpcds_shape_sf100_p0/shape/query64.out | 28 +-
.../ip_functions/test_ip_functions.out | 68 +++-
.../ip_functions/test_to_ip_functions.out | 21 ++
.../data/variant_p0/sql/implicit_cast.out | 80 +++++
.../suites/correctness_p0/test_bit_function.groovy | 63 ++++
.../correctness_p0/test_bit_shift_lagency.groovy | 105 ++++++
.../correctness_p0/test_bit_shift_nereids.groovy | 105 ++++++
.../correctness_p0/test_nested_lateral_view.groovy | 55 +++
.../test_index_match_phrase_prefix_1.groovy | 62 ++++
.../suites/job_p0/test_base_insert_job.groovy | 24 +-
.../routine_load/data/invalid_json_path.json | 0
.../routine_load/test_routine_load_error.groovy | 157 +++++++++
.../suites/nereids_function_p0/ip_functions.groovy | 24 ++
.../agg_with_roll_up/aggregate_with_roll_up.groovy | 131 +++++---
.../nereids_syntax_p0/agg_with_empty_set.groovy | 1 +
.../auto_partition/ddl/stress_destination.sql | 20 ++
.../auto_partition/ddl/stress_source.sql | 19 ++
.../doris_dbgen_conf/stress_test_insert_into.yaml} | 8 +-
.../auto_partition/sql/multi_thread_load.groovy | 3 +-
.../sql/stress_test_insert_into.groovy | 118 +++++++
.../ip_functions/test_ip_functions.groovy | 24 ++
.../ip_functions/test_to_ip_functions.groovy | 49 +++
.../schema_change_p0/test_schema_change_agg.groovy | 28 ++
.../suites/variant_p0/sql/implicit_cast.sql | 15 +
282 files changed, 7978 insertions(+), 2209 deletions(-)
create mode 100644 be/src/vec/functions/function_bit_count.cpp
create mode 100644 be/src/vec/functions/function_bit_shift.cpp
copy docs/en/docs/sql-manual/sql-functions/{ip-functions/inet-aton.md => bitwise-functions/bitcount.md} (52%)
create mode 100644 docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitleft.md
create mode 100644 docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitright.md
create mode 100644 docs/en/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md
create mode 100644 docs/en/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md
create mode 100644 docs/en/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md
copy docs/en/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => is-ipv4-compat.md} (53%)
create mode 100644 docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md
create mode 100644 docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md
create mode 100644 docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md
copy docs/en/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv4-or-default.md} (54%)
copy docs/en/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv4-or-null.md} (54%)
copy docs/en/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv4.md} (54%)
copy docs/en/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv6-or-default.md} (54%)
copy docs/en/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv6-or-null.md} (54%)
copy docs/en/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv6.md} (54%)
create mode 100644 docs/en/docs/sql-manual/sql-reference/Data-Types/IPV4.md
create mode 100644 docs/en/docs/sql-manual/sql-reference/Data-Types/IPV6.md
copy docs/zh-CN/docs/sql-manual/sql-functions/{ip-functions/inet-aton.md => bitwise-functions/bitcount.md} (52%)
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftleft.md
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftright.md
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md
copy docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => is-ipv4-compat.md} (53%)
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md
create mode 100644 docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md
copy docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv4-or-default.md} (56%)
copy docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv4-or-null.md} (56%)
copy docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv4.md} (56%)
copy docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv6-or-default.md} (56%)
copy docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv6-or-null.md} (56%)
copy docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/{inet-aton.md => to-ipv6.md} (56%)
create mode 100644 docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV4.md
create mode 100644 docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV6.md
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalMetaIdMgr.java
delete mode 100644 fe/fe-core/src/main/java/org/apache/doris/datasource/InitTableLog.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/datasource/MetaIdMappingsLog.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitCount.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftLeft.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftRight.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Compat.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Mapped.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrDefault.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrNull.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrDefault.java
create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrNull.java
copy be/src/vec/exprs/vlambda_function_expr.h => fe/fe-core/src/main/java/org/apache/doris/statistics/InvalidateStatsTarget.java (52%)
create mode 100644 fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalMetaIdMgrTest.java
create mode 100644 fe/fe-core/src/test/java/org/apache/doris/datasource/MetaIdMappingsLogTest.java
create mode 100644 regression-test/data/correctness_p0/test_bit_shift_lagency.out
create mode 100644 regression-test/data/correctness_p0/test_bit_shift_nereids.out
create mode 100644 regression-test/data/correctness_p0/test_nested_lateral_view.out
copy regression-test/data/{correctness_p0/test_bit_function.out => inverted_index_p0/test_index_match_phrase_prefix_1.out} (63%)
create mode 100644 regression-test/data/query_p0/sql_functions/ip_functions/test_to_ip_functions.out
create mode 100644 regression-test/data/variant_p0/sql/implicit_cast.out
create mode 100644 regression-test/suites/correctness_p0/test_bit_shift_lagency.groovy
create mode 100644 regression-test/suites/correctness_p0/test_bit_shift_nereids.groovy
create mode 100644 regression-test/suites/correctness_p0/test_nested_lateral_view.groovy
create mode 100644 regression-test/suites/inverted_index_p0/test_index_match_phrase_prefix_1.groovy
copy docker/thirdparties/docker-compose/kafka/scripts/basic_data_json_by_line.json => regression-test/suites/load_p0/routine_load/data/invalid_json_path.json (100%)
create mode 100644 regression-test/suites/partition_p1/auto_partition/ddl/stress_destination.sql
create mode 100644 regression-test/suites/partition_p1/auto_partition/ddl/stress_source.sql
copy regression-test/suites/{correctness_p0/test_bit_function.groovy => partition_p1/auto_partition/doris_dbgen_conf/stress_test_insert_into.yaml} (81%)
create mode 100644 regression-test/suites/partition_p1/auto_partition/sql/stress_test_insert_into.groovy
create mode 100644 regression-test/suites/query_p0/sql_functions/ip_functions/test_to_ip_functions.groovy
create mode 100644 regression-test/suites/variant_p0/sql/implicit_cast.sql
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 21/43: [fix](routineload) check offset when schedule tasks (#30136)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 3e73933857d1173a11c4bc0114bf495afb3cb537
Author: HHoflittlefish777 <77...@users.noreply.github.com>
AuthorDate: Mon Jan 22 13:16:03 2024 +0800
[fix](routineload) check offset when schedule tasks (#30136)
---
.../load/routineload/KafkaRoutineLoadJob.java | 23 ++++++++---
.../doris/load/routineload/KafkaTaskInfo.java | 2 +-
.../load/routineload/RoutineLoadTaskInfo.java | 2 +-
.../load/routineload/RoutineLoadTaskScheduler.java | 16 ++++----
.../routine_load/test_routine_load_error.groovy | 47 ++++++++++++++++++++++
5 files changed, 74 insertions(+), 16 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java
index d7a090c23e5..faad0a0248a 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java
@@ -704,7 +704,7 @@ public class KafkaRoutineLoadJob extends RoutineLoadJob {
// check if given partitions has more data to consume.
// 'partitionIdToOffset' to the offset to be consumed.
- public boolean hasMoreDataToConsume(UUID taskId, Map<Integer, Long> partitionIdToOffset) {
+ public boolean hasMoreDataToConsume(UUID taskId, Map<Integer, Long> partitionIdToOffset) throws UserException {
for (Map.Entry<Integer, Long> entry : partitionIdToOffset.entrySet()) {
if (cachedPartitionWithLatestOffsets.containsKey(entry.getKey())
&& entry.getValue() < cachedPartitionWithLatestOffsets.get(entry.getKey())) {
@@ -734,11 +734,22 @@ public class KafkaRoutineLoadJob extends RoutineLoadJob {
// check again
for (Map.Entry<Integer, Long> entry : partitionIdToOffset.entrySet()) {
- if (cachedPartitionWithLatestOffsets.containsKey(entry.getKey())
- && entry.getValue() < cachedPartitionWithLatestOffsets.get(entry.getKey())) {
- LOG.debug("has more data to consume. offsets to be consumed: {}, latest offsets: {}, task {}, job {}",
- partitionIdToOffset, cachedPartitionWithLatestOffsets, taskId, id);
- return true;
+ Integer partitionId = entry.getKey();
+ if (cachedPartitionWithLatestOffsets.containsKey(partitionId)) {
+ long partitionLatestOffset = cachedPartitionWithLatestOffsets.get(partitionId);
+ long recordPartitionOffset = entry.getValue();
+ if (recordPartitionOffset < partitionLatestOffset) {
+ LOG.debug("has more data to consume. offsets to be consumed: {},"
+ + " latest offsets: {}, task {}, job {}",
+ partitionIdToOffset, cachedPartitionWithLatestOffsets, taskId, id);
+ return true;
+ } else if (recordPartitionOffset > partitionLatestOffset) {
+ String msg = "offset set in job: " + recordPartitionOffset
+ + " is greater than kafka latest offset: "
+ + partitionLatestOffset + " partition id: "
+ + partitionId;
+ throw new UserException(msg);
+ }
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java
index 2075e5548e5..a8d387a2f6d 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java
@@ -119,7 +119,7 @@ public class KafkaTaskInfo extends RoutineLoadTaskInfo {
}
@Override
- boolean hasMoreDataToConsume() {
+ boolean hasMoreDataToConsume() throws UserException {
KafkaRoutineLoadJob routineLoadJob = (KafkaRoutineLoadJob) routineLoadManager.getJob(jobId);
return routineLoadJob.hasMoreDataToConsume(id, partitionIdToOffset);
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java
index fd8e8182321..9c28dbfc6a8 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java
@@ -209,7 +209,7 @@ public abstract class RoutineLoadTaskInfo {
abstract String getTaskDataSourceProperties();
- abstract boolean hasMoreDataToConsume();
+ abstract boolean hasMoreDataToConsume() throws UserException;
@Override
public boolean equals(Object obj) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java
index 0f594a2d508..a6cc796027a 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java
@@ -128,15 +128,15 @@ public class RoutineLoadTaskScheduler extends MasterDaemon {
return;
}
- // check if topic has more data to consume
- if (!routineLoadTaskInfo.hasMoreDataToConsume()) {
- needScheduleTasksQueue.put(routineLoadTaskInfo);
- return;
- }
-
- // allocate BE slot for this task.
- // this should be done before txn begin, or the txn may be begun successfully but failed to be allocated.
try {
+ // check if topic has more data to consume
+ if (!routineLoadTaskInfo.hasMoreDataToConsume()) {
+ needScheduleTasksQueue.put(routineLoadTaskInfo);
+ return;
+ }
+
+ // allocate BE slot for this task.
+ // this should be done before txn begin, or the txn may be begun successfully but failed to be allocated.
if (!allocateTaskToBe(routineLoadTaskInfo)) {
// allocate failed, push it back to the queue to wait next scheduling
needScheduleTasksQueue.put(routineLoadTaskInfo);
diff --git a/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy b/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy
index b04610740d9..c4180e35f4d 100644
--- a/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy
+++ b/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy
@@ -91,4 +91,51 @@ suite("test_routine_load_error","p0") {
sql "stop routine load for testTableNoExist"
}
}
+
+ // test out of range
+ if (enabled != null && enabled.equalsIgnoreCase("true")) {
+ def jobName = "testOutOfRange"
+ try {
+ sql """
+ CREATE ROUTINE LOAD ${jobName}
+ COLUMNS TERMINATED BY "|"
+ PROPERTIES
+ (
+ "max_batch_interval" = "5",
+ "max_batch_rows" = "300000",
+ "max_batch_size" = "209715200"
+ )
+ FROM KAFKA
+ (
+ "kafka_broker_list" = "${externalEnvIp}:${kafka_port}",
+ "kafka_partitions" = "0",
+ "kafka_topic" = "multi_table_load_invalid_table",
+ "kafka_offsets" = "100"
+ );
+ """
+ sql "sync"
+
+ def count = 0
+ while (true) {
+ sleep(1000)
+ def res = sql "show routine load for ${jobName}"
+ def state = res[0][8].toString()
+ log.info("routine load state: ${res[0][8].toString()}".toString())
+ log.info("routine load statistic: ${res[0][14].toString()}".toString())
+ log.info("reason of state changed: ${res[0][17].toString()}".toString())
+ if (state != "PAUSED") {
+ count++
+ if (count > 60) {
+ assertEquals(1, 2)
+ }
+ continue;
+ }
+ log.info("reason of state changed: ${res[0][17].toString()}".toString())
+ assertTrue(res[0][17].toString().contains("is greater than kafka latest offset"))
+ break;
+ }
+ } finally {
+ sql "stop routine load for ${jobName}"
+ }
+ }
}
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 25/43: [feature](bitwise function) bit_count/bit_shift_left/bit_shift_right implementation (#30046)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit e5dea910bf3e25dc1461bb8f325e72a3adc09ba6
Author: zhiqiang <se...@163.com>
AuthorDate: Mon Jan 22 13:27:46 2024 +0800
[feature](bitwise function) bit_count/bit_shift_left/bit_shift_right implementation (#30046)
---
be/src/vec/functions/function_bit_count.cpp | 61 ++++
be/src/vec/functions/function_bit_shift.cpp | 90 ++++++
be/src/vec/functions/simple_function_factory.h | 4 +
.../sql-functions/bitwise-functions/bitcount.md | 52 ++++
.../bitwise-functions/bitshfitleft.md | 71 +++++
.../bitwise-functions/bitshfitright.md | 79 +++++
.../sql-functions/bitwise-functions/bitcount.md | 52 ++++
.../bitwise-functions/bitshiftleft.md | 71 +++++
.../bitwise-functions/bitshiftright.md | 78 +++++
.../doris/catalog/BuiltinScalarFunctions.java | 6 +
.../expressions/functions/scalar/BitCount.java | 67 ++++
.../expressions/functions/scalar/BitShiftLeft.java | 61 ++++
.../functions/scalar/BitShiftRight.java | 63 ++++
.../expressions/visitor/ScalarFunctionVisitor.java | 15 +
gensrc/script/doris_builtins_functions.py | 11 +-
.../data/correctness_p0/test_bit_function.out | 132 ++++++++
.../data/correctness_p0/test_bit_shift_lagency.out | 345 +++++++++++++++++++++
.../data/correctness_p0/test_bit_shift_nereids.out | 345 +++++++++++++++++++++
.../suites/correctness_p0/test_bit_function.groovy | 63 ++++
.../correctness_p0/test_bit_shift_lagency.groovy | 105 +++++++
.../correctness_p0/test_bit_shift_nereids.groovy | 105 +++++++
21 files changed, 1875 insertions(+), 1 deletion(-)
diff --git a/be/src/vec/functions/function_bit_count.cpp b/be/src/vec/functions/function_bit_count.cpp
new file mode 100644
index 00000000000..66ef9d4c4f7
--- /dev/null
+++ b/be/src/vec/functions/function_bit_count.cpp
@@ -0,0 +1,61 @@
+// 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 <bit>
+#include <bitset>
+#include <cstdint>
+#include <type_traits>
+
+#include "common/exception.h"
+#include "common/status.h"
+#include "gutil/integral_types.h"
+#include "util/radix_sort.h"
+#include "vec/core/types.h"
+#include "vec/functions/function_unary_arithmetic.h"
+#include "vec/functions/simple_function_factory.h"
+
+namespace doris::vectorized {
+
+struct NameBitCount {
+ static constexpr auto name = "bit_count";
+};
+
+template <typename T>
+struct BitCountImpl {
+ // No unsigned type in Java. So we need signed number as return type
+ // Int8_MAX = 127
+ using ResultType = std::conditional_t<sizeof(T) * 8 >= 128, Int16, Int8>;
+
+ static inline ResultType apply(T a) {
+ if constexpr (std::is_same_v<T, Int128> || std::is_same_v<T, Int64> ||
+ std::is_same_v<T, Int32> || std::is_same_v<T, Int16> ||
+ std::is_same_v<T, Int8>) {
+ return std::popcount(static_cast<std::make_unsigned_t<T>>(a));
+ } else {
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "bit_count only support using INTEGER as operator");
+ }
+ }
+};
+
+using FunctionBitCount = FunctionUnaryArithmetic<BitCountImpl, NameBitCount, false>;
+
+void register_function_bit_count(SimpleFunctionFactory& factory) {
+ factory.register_function<FunctionBitCount>();
+}
+
+} // namespace doris::vectorized
diff --git a/be/src/vec/functions/function_bit_shift.cpp b/be/src/vec/functions/function_bit_shift.cpp
new file mode 100644
index 00000000000..36a5c59e3cb
--- /dev/null
+++ b/be/src/vec/functions/function_bit_shift.cpp
@@ -0,0 +1,90 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <bit>
+#include <bitset>
+#include <cstdint>
+#include <exception>
+#include <stdexcept>
+#include <type_traits>
+
+#include "common/exception.h"
+#include "common/logging.h"
+#include "common/status.h"
+#include "gutil/integral_types.h"
+#include "util/radix_sort.h"
+#include "vec/core/types.h"
+#include "vec/functions/function_binary_arithmetic.h"
+#include "vec/functions/simple_function_factory.h"
+
+namespace doris::vectorized {
+
+struct NameBitShiftLeft {
+ static constexpr auto name = "bit_shift_left";
+};
+
+struct NameBitShiftRight {
+ static constexpr auto name = "bit_shift_right";
+};
+
+template <typename A, typename B>
+struct BitShiftLeftImpl {
+ using ResultType = typename NumberTraits::ResultOfBit<A, B>::Type;
+
+ template <typename Result = ResultType>
+ static inline Result apply(A a, B b) {
+ if constexpr (!std::is_same_v<A, Int64> || !std::is_same_v<B, Int8>) {
+ throw Exception(ErrorCode::NOT_FOUND,
+ "bit_shift_left only supports [BIGINT, TINYINT] as operator");
+ } else {
+ // return zero if b < 0, keep consistent with mysql
+ // cast to unsigned so that we can do logical shift by default, keep consistent with mysql
+ return b < 0 ? 0
+ : static_cast<typename std::make_unsigned<A>::type>(a)
+ << static_cast<Result>(b);
+ }
+ }
+};
+
+template <typename A, typename B>
+struct BitShiftRightImpl {
+ using ResultType = typename NumberTraits::ResultOfBit<A, B>::Type;
+
+ template <typename Result = ResultType>
+ static inline Result apply(A a, B b) {
+ if constexpr (!std::is_same_v<A, Int64> || !std::is_same_v<B, Int8>) {
+ throw Exception(ErrorCode::NOT_FOUND,
+ "bit_shift_right only supports [BIGINT, TINYINT] as operator");
+ } else {
+ // return zero if b < 0, keep consistent with mysql
+ // cast to unsigned so that we can do logical shift by default, keep consistent with mysql
+ return b < 0 ? 0
+ : static_cast<typename std::make_unsigned<A>::type>(a) >>
+ static_cast<Result>(b);
+ }
+ }
+};
+
+using FunctionBitShiftLeft = FunctionBinaryArithmetic<BitShiftLeftImpl, NameBitShiftLeft, false>;
+using FunctionBitShiftRight = FunctionBinaryArithmetic<BitShiftRightImpl, NameBitShiftRight, false>;
+
+void register_function_bit_shift(SimpleFunctionFactory& factory) {
+ factory.register_function<FunctionBitShiftLeft>();
+ factory.register_function<FunctionBitShiftRight>();
+}
+
+} // namespace doris::vectorized
diff --git a/be/src/vec/functions/simple_function_factory.h b/be/src/vec/functions/simple_function_factory.h
index 0992239e99b..5c47198fd6b 100644
--- a/be/src/vec/functions/simple_function_factory.h
+++ b/be/src/vec/functions/simple_function_factory.h
@@ -48,6 +48,8 @@ void register_function_multiply(SimpleFunctionFactory& factory);
void register_function_divide(SimpleFunctionFactory& factory);
void register_function_int_div(SimpleFunctionFactory& factory);
void register_function_bit(SimpleFunctionFactory& factory);
+void register_function_bit_count(SimpleFunctionFactory& factory);
+void register_function_bit_shift(SimpleFunctionFactory& factory);
void register_function_math(SimpleFunctionFactory& factory);
void register_function_modulo(SimpleFunctionFactory& factory);
void register_function_bitmap(SimpleFunctionFactory& factory);
@@ -229,6 +231,8 @@ public:
register_function_int_div(instance);
register_function_modulo(instance);
register_function_bit(instance);
+ register_function_bit_count(instance);
+ register_function_bit_shift(instance);
register_function_is_null(instance);
register_function_is_not_null(instance);
register_function_nullables(instance);
diff --git a/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitcount.md b/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitcount.md
new file mode 100644
index 00000000000..2518e35f2f1
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitcount.md
@@ -0,0 +1,52 @@
+---
+{
+"title": "BIT_COUNT",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## bit_count
+### description
+#### Syntax
+
+`BIT_COUNT(Integer-type x)`
+
+Returns the exist count of one in 2's complement represent of integer x.
+
+Integer-type could be: TINYINT、SMALLINT、INT、BIGINT、LARGEINT
+
+### example
+
+```
+select "0b11111111", bit_count(-1)
+--------------
+
++--------------+---------------+
+| '0b11111111' | bit_count(-1) |
++--------------+---------------+
+| 0b11111111 | 8 |
++--------------+---------------+
+```
+
+### keywords
+
+ BITCOUNT, BIT_COUNT
diff --git a/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitleft.md b/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitleft.md
new file mode 100644
index 00000000000..b48313c242b
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitleft.md
@@ -0,0 +1,71 @@
+---
+{
+"title": "BIT_SHIFT_LEFT",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## bit_shift_left
+### description
+#### syntax
+
+`BIT_SHIFT_LEFT(BIGINT x, TINYINT c)`
+
+Do logical left shift to `BIGINT` type x by c bits, and return result as a `BIGINT`.
+Return zero if `c` is less than 0.
+
+### example
+Normal case
+```sql
+select 8 as x, number as c, bit_shift_left(8, number) as bit_shift_left from numbers("number"="5")
+--------------
+
++------+------+----------------+
+| x | c | bit_shift_left |
++------+------+----------------+
+| 8 | 0 | 8 |
+| 8 | 1 | 16 |
+| 8 | 2 | 32 |
+| 8 | 3 | 64 |
+| 8 | 4 | 128 |
++------+------+----------------+
+5 rows in set (0.04 sec)
+```
+Left shift result of `9223372036854775807` which is `BIGINT_MAX` by 1 bit will get -2.
+```sql
+WITH tbl AS (
+ SELECT 9223372036854775807 AS BIGINT_MAX
+)
+SELECT BIGINT_MAX, bit_shift_left(BIGINT_MAX, 1)
+FROM tbl
+--------------
+
++---------------------+-------------------------------+
+| BIGINT_MAX | bit_shift_left(BIGINT_MAX, 1) |
++---------------------+-------------------------------+
+| 9223372036854775807 | -2 |
++---------------------+-------------------------------+
+1 row in set (0.05 sec)
+```
+### keywords
+
+ BITSHIFT, BITSHIFTLEFT
diff --git a/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitright.md b/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitright.md
new file mode 100644
index 00000000000..8d44c3421be
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/bitwise-functions/bitshfitright.md
@@ -0,0 +1,79 @@
+---
+{
+"title": "BIT_SHIFT_RIGHT",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## bit_shift_right
+### description
+#### syntax
+
+`BIT_SHIFT_RIGHT(BIGINT x, TINYINT c)`
+
+Return result of logical right shift of `BIGINT` type x by c bits.
+
+### example
+Normal case
+```sql
+select 1024 as x, number as c, bit_shift_right(1024, number) as bit_shift_right from numbers("number"="5")
+--------------
+
++------+------+-----------------+
+| x | c | bit_shift_right |
++------+------+-----------------+
+| 1024 | 0 | 1024 |
+| 1024 | 1 | 512 |
+| 1024 | 2 | 256 |
+| 1024 | 3 | 128 |
+| 1024 | 4 | 64 |
++------+------+-----------------+
+5 rows in set (0.03 sec)
+```
+Logical right shift `BIGINT` -1 by 1 bits gets `BIGINT_MAX`
+```sql
+select bit_shift_right(-1, 1)
+--------------
+
++------------------------+
+| bit_shift_right(-1, 1) |
++------------------------+
+| 9223372036854775807 |
++------------------------+
+```
+Return zero if `c` is less than 0
+```sql
+select bit_shift_right(100, -1)
+--------------
+
++--------------------------+
+| bit_shift_right(100, -1) |
++--------------------------+
+| 0 |
++--------------------------+
+1 row in set (0.04 sec)
+```
+
+
+### keywords
+
+ BITSHIFT, BITSHIFTRIGHT
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitcount.md b/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitcount.md
new file mode 100644
index 00000000000..9dfdd7e9d49
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitcount.md
@@ -0,0 +1,52 @@
+---
+{
+"title": "BIT_COUNT",
+"language": "zh-CH"
+}
+---
+
+<!--
+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.
+-->
+
+## bit_count
+### description
+#### Syntax
+
+`BIT_COUNT(Integer-type x)`
+
+统计整型 x 的二的补码表示中 1 的个数。
+
+整型可以是:TINYINT、SMALLINT、INT、BIGINT、LARGEINT
+
+### example
+
+```
+select "0b11111111", bit_count(-1)
+--------------
+
++--------------+---------------+
+| '0b11111111' | bit_count(-1) |
++--------------+---------------+
+| 0b11111111 | 8 |
++--------------+---------------+
+```
+
+### keywords
+
+ BITCOUNT, BIT_COUNT
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftleft.md b/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftleft.md
new file mode 100644
index 00000000000..1729b7ac75a
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftleft.md
@@ -0,0 +1,71 @@
+---
+{
+"title": "BIT_SHIFT_LEFT",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## bit_shift_left
+### description
+#### syntax
+
+`BIT_SHIFT_LEFT(BIGINT x, TINYINT c)`
+
+将 BIGINT 类型的 x 向左移动 c 位,并将结果作为 BIGINT 返回。
+如果 c 小于 0,则返回零。
+
+### example
+```sql
+select 8 as x, number as c, bit_shift_left(8, number) as bit_shift_left from numbers("number"="5")
+--------------
+
++------+------+----------------+
+| x | c | bit_shift_left |
++------+------+----------------+
+| 8 | 0 | 8 |
+| 8 | 1 | 16 |
+| 8 | 2 | 32 |
+| 8 | 3 | 64 |
+| 8 | 4 | 128 |
++------+------+----------------+
+5 rows in set (0.04 sec)
+```
+对于 BIGINT 类型的最大值 9223372036854775807(即 BIGINT_MAX),进行一位左移的结果将得到 -2。
+```sql
+WITH tbl AS (
+ SELECT 9223372036854775807 AS BIGINT_MAX
+)
+SELECT BIGINT_MAX, bit_shift_left(BIGINT_MAX, 1)
+FROM tbl
+--------------
+
++---------------------+-------------------------------+
+| BIGINT_MAX | bit_shift_left(BIGINT_MAX, 1) |
++---------------------+-------------------------------+
+| 9223372036854775807 | -2 |
++---------------------+-------------------------------+
+1 row in set (0.05 sec)
+```
+
+### keywords
+
+ BITSHIFT, BITSHIFTLEFT
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftright.md b/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftright.md
new file mode 100644
index 00000000000..4308bff470a
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/bitwise-functions/bitshiftright.md
@@ -0,0 +1,78 @@
+---
+{
+"title": "BIT_SHIFT_RIGHT",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+## bit_shift_right
+### description
+#### syntax
+
+`BIT_SHIFT_RIGHT(BIGINT x, TINYINT c)`
+
+返回对 BIGINT 类型 x 进行逻辑右移 c 位的结果。
+
+### example
+Normal case
+```sql
+select 1024 as x, number as c, bit_shift_right(1024, number) as bit_shift_right from numbers("number"="5")
+--------------
+
++------+------+-----------------+
+| x | c | bit_shift_right |
++------+------+-----------------+
+| 1024 | 0 | 1024 |
+| 1024 | 1 | 512 |
+| 1024 | 2 | 256 |
+| 1024 | 3 | 128 |
+| 1024 | 4 | 64 |
++------+------+-----------------+
+5 rows in set (0.03 sec)
+```
+BIGINT -1 逻辑右移一位得到的结果是 BIGINT_MAX
+
+```sql
+select bit_shift_right(-1, 1)
+--------------
+
++------------------------+
+| bit_shift_right(-1, 1) |
++------------------------+
+| 9223372036854775807 |
++------------------------+
+```
+如果 c 小于 0 得到的结果始终为 0
+```sql
+select bit_shift_right(100, -1)
+--------------
+
++--------------------------+
+| bit_shift_right(100, -1) |
++--------------------------+
+| 0 |
++--------------------------+
+1 row in set (0.04 sec)
+```
+
+### keywords
+
+ BITSHIFT, BITSHIFTRIGHT
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
index fcc2a351bf0..492c561f0a1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
@@ -73,7 +73,10 @@ import org.apache.doris.nereids.trees.expressions.functions.scalar.Ascii;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Asin;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Atan;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Bin;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.BitCount;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitLength;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.BitShiftLeft;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.BitShiftRight;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapAnd;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapAndCount;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapAndNot;
@@ -486,6 +489,7 @@ public class BuiltinScalarFunctions implements FunctionHelper {
scalar(Asin.class, "asin"),
scalar(Atan.class, "atan"),
scalar(Bin.class, "bin"),
+ scalar(BitCount.class, "bit_count"),
scalar(BitLength.class, "bit_length"),
scalar(BitmapAnd.class, "bitmap_and"),
scalar(BitmapAndCount.class, "bitmap_and_count"),
@@ -516,6 +520,8 @@ public class BuiltinScalarFunctions implements FunctionHelper {
scalar(BitmapToString.class, "bitmap_to_string"),
scalar(BitmapXor.class, "bitmap_xor"),
scalar(BitmapXorCount.class, "bitmap_xor_count"),
+ scalar(BitShiftLeft.class, "bit_shift_left"),
+ scalar(BitShiftRight.class, "bit_shift_right"),
scalar(Cardinality.class, "array_size", "cardinality", "size"),
scalar(Cbrt.class, "cbrt"),
scalar(Ceil.class, "ceil", "ceiling"),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitCount.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitCount.java
new file mode 100644
index 00000000000..5cbbf24df96
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitCount.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
+import org.apache.doris.nereids.trees.expressions.shape.UnaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.BigIntType;
+import org.apache.doris.nereids.types.IntegerType;
+import org.apache.doris.nereids.types.LargeIntType;
+import org.apache.doris.nereids.types.SmallIntType;
+import org.apache.doris.nereids.types.TinyIntType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/** BitCount function */
+
+public class BitCount extends ScalarFunction
+ implements UnaryExpression, ExplicitlyCastableSignature, PropagateNullable {
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(TinyIntType.INSTANCE).args(TinyIntType.INSTANCE),
+ FunctionSignature.ret(TinyIntType.INSTANCE).args(SmallIntType.INSTANCE),
+ FunctionSignature.ret(TinyIntType.INSTANCE).args(IntegerType.INSTANCE),
+ FunctionSignature.ret(TinyIntType.INSTANCE).args(BigIntType.INSTANCE),
+ FunctionSignature.ret(SmallIntType.INSTANCE).args(LargeIntType.INSTANCE));
+
+ public BitCount(Expression arg) {
+ super("bit_count", arg);
+ }
+
+ @Override
+ public BitCount withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1);
+ return new BitCount(children.get(0));
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitBitCount(this, context);
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftLeft.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftLeft.java
new file mode 100644
index 00000000000..aa78d01e320
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftLeft.java
@@ -0,0 +1,61 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.BigIntType;
+import org.apache.doris.nereids.types.TinyIntType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/** BitShiftLeft function */
+
+public class BitShiftLeft extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, PropagateNullable {
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(BigIntType.INSTANCE).args(BigIntType.INSTANCE, TinyIntType.INSTANCE));
+
+ public BitShiftLeft(Expression arg1, Expression arg2) {
+ super("bit_shift_left", arg1, arg2);
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitBitShiftLeft(this, context);
+ }
+
+ @Override
+ public BitShiftLeft withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 2);
+ return new BitShiftLeft(children.get(0), children.get(1));
+ }
+}
+
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftRight.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftRight.java
new file mode 100644
index 00000000000..ab2bce00a04
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitShiftRight.java
@@ -0,0 +1,63 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.BigIntType;
+import org.apache.doris.nereids.types.TinyIntType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/** BitShiftRight
+ * Do logical right shift to a BigInt value x by c bits.
+ */
+
+public class BitShiftRight extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, PropagateNullable {
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(BigIntType.INSTANCE).args(BigIntType.INSTANCE, TinyIntType.INSTANCE));
+
+ public BitShiftRight(Expression arg1, Expression arg2) {
+ super("bit_shift_right", arg1, arg2);
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitBitShiftRight(this, context);
+ }
+
+ @Override
+ public BitShiftRight withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 2);
+ return new BitShiftRight(children.get(0), children.get(1));
+ }
+}
+
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
index 01823f78199..8629d15b2bc 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
@@ -73,7 +73,10 @@ import org.apache.doris.nereids.trees.expressions.functions.scalar.Ascii;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Asin;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Atan;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Bin;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.BitCount;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitLength;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.BitShiftLeft;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.BitShiftRight;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapAnd;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapAndCount;
import org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapAndNot;
@@ -625,6 +628,10 @@ public interface ScalarFunctionVisitor<R, C> {
return visitScalarFunction(bin, context);
}
+ default R visitBitCount(BitCount bitCount, C context) {
+ return visitScalarFunction(bitCount, context);
+ }
+
default R visitBitLength(BitLength bitLength, C context) {
return visitScalarFunction(bitLength, context);
}
@@ -745,6 +752,14 @@ public interface ScalarFunctionVisitor<R, C> {
return visitScalarFunction(bitmapXorCount, context);
}
+ default R visitBitShiftLeft(BitShiftLeft bitShiftLeft, C context) {
+ return visitScalarFunction(bitShiftLeft, context);
+ }
+
+ default R visitBitShiftRight(BitShiftRight bitShiftRight, C context) {
+ return visitScalarFunction(bitShiftRight, context);
+ }
+
default R visitCardinality(Cardinality cardinality, C context) {
return visitScalarFunction(cardinality, context);
}
diff --git a/gensrc/script/doris_builtins_functions.py b/gensrc/script/doris_builtins_functions.py
index 183b38bdfda..a9d2fe26dc2 100644
--- a/gensrc/script/doris_builtins_functions.py
+++ b/gensrc/script/doris_builtins_functions.py
@@ -51,6 +51,12 @@ visible_functions = {
[['bitand'], 'INT', ['INT', 'INT'], ''],
[['bitand'], 'BIGINT', ['BIGINT', 'BIGINT'], ''],
[['bitand'], 'LARGEINT', ['LARGEINT', 'LARGEINT'], ''],
+
+ [['bit_count'], 'TINYINT', ['TINYINT'], ''],
+ [['bit_count'], 'TINYINT', ['SMALLINT'], ''],
+ [['bit_count'], 'TINYINT', ['INT'], ''],
+ [['bit_count'], 'TINYINT', ['BIGINT'], ''],
+ [['bit_count'], 'SMALLINT', ['LARGEINT'], ''],
[['bitor'], 'TINYINT', ['TINYINT', 'TINYINT'], ''],
[['bitor'], 'SMALLINT', ['SMALLINT', 'SMALLINT'], ''],
@@ -68,7 +74,10 @@ visible_functions = {
[['bitnot'], 'SMALLINT', ['SMALLINT'], ''],
[['bitnot'], 'INT', ['INT'], ''],
[['bitnot'], 'BIGINT', ['BIGINT'], ''],
- [['bitnot'], 'LARGEINT', ['LARGEINT'], '']
+ [['bitnot'], 'LARGEINT', ['LARGEINT'], ''],
+
+ [['bit_shift_left'], 'BIGINT', ['BIGINT', 'TINYINT'], ''],
+ [['bit_shift_right'], 'BIGINT', ['BIGINT', 'TINYINT'], '']
],
# map functions
diff --git a/regression-test/data/correctness_p0/test_bit_function.out b/regression-test/data/correctness_p0/test_bit_function.out
index 0fe60dde32c..02334fcab28 100644
--- a/regression-test/data/correctness_p0/test_bit_function.out
+++ b/regression-test/data/correctness_p0/test_bit_function.out
@@ -2,3 +2,135 @@
-- !select --
64 123713 123649 -322
+-- !bit_count --
+0
+1
+1
+2
+1
+2
+2
+3
+1
+2
+
+-- !bit_count --
+0
+
+-- !bit_count --
+8
+
+-- !bit_count --
+8
+
+-- !bit_count --
+16
+
+-- !bit_count --
+32
+
+-- !bit_count --
+64
+
+-- !bit_count --
+128
+
+-- !bit_count_TINYINT_MAX --
+7
+
+-- !bit_count_TINYINT_MIN --
+1
+
+-- !bit_count_SMALLINT_MAX --
+15
+
+-- !bit_count_SMALLINT_MIN --
+1
+
+-- !bit_count_INT_MAX --
+31
+
+-- !bit_count_INT_IN --
+1
+
+-- !bit_count_INT64_MAX --
+63
+
+-- !bit_count_INT64_MIN --
+1
+
+-- !bit_count_INT128_MAX --
+127 127
+
+-- !bit_count_INT128_MIN --
+1 1
+
+-- !select --
+1 1
+
+-- !bit_count --
+0
+1
+1
+2
+1
+2
+2
+3
+1
+2
+
+-- !bit_count --
+0
+
+-- !bit_count --
+8
+
+-- !bit_count --
+8
+
+-- !bit_count --
+16
+
+-- !bit_count --
+32
+
+-- !bit_count --
+64
+
+-- !bit_count --
+128
+
+-- !bit_count_TINYINT_MAX --
+7
+
+-- !bit_count_TINYINT_MIN --
+1
+
+-- !bit_count_SMALLINT_MAX --
+15
+
+-- !bit_count_SMALLINT_MIN --
+1
+
+-- !bit_count_INT_MAX --
+31
+
+-- !bit_count_INT_IN --
+1
+
+-- !bit_count_INT64_MAX --
+63
+
+-- !bit_count_INT64_MIN --
+1
+
+-- !bit_count_INT128_MAX --
+127 127
+
+-- !bit_count_INT128_MIN --
+1 1
+
+-- !select --
+1 1
+
diff --git a/regression-test/data/correctness_p0/test_bit_shift_lagency.out b/regression-test/data/correctness_p0/test_bit_shift_lagency.out
new file mode 100644
index 00000000000..1c956fe3c74
--- /dev/null
+++ b/regression-test/data/correctness_p0/test_bit_shift_lagency.out
@@ -0,0 +1,345 @@
+-- This file is automatically generated. You should know what you did if you want to edit this
+-- !comment --
+testing big_shift_left
+
+-- !numbers --
+0
+16
+32
+48
+64
+80
+96
+112
+128
+144
+
+-- !0 --
+0
+
+-- !1 --
+1024
+
+-- !2 --
+-9223372036854775808
+
+-- !3 --
+1
+
+-- !select --
+254
+
+-- !select --
+254
+
+-- !int64_max --
+9223372036854775807 -2
+
+-- !int64_min --
+-9223372036854775808 0
+
+-- !select --
+127 -9223372036854775808
+
+-- !select --
+-128 0
+
+-- !select --
+0 254 65534 4294967294 -2
+1 -256 -65536 -4294967296 -2
+
+-- !comment --
+testing big_shift_right
+
+-- !select --
+0
+
+-- !select --
+0
+
+-- !select --
+1
+
+-- !select --
+0
+
+-- !select --
+9223372036854775807
+
+-- !select --
+2
+
+-- !select --
+1
+
+-- !select --
+-9223372036854775808
+
+-- !select --
+0
+
+-- !select --
+0
+
+-- !select --
+1
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+
+-- !select --
+1
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+
diff --git a/regression-test/data/correctness_p0/test_bit_shift_nereids.out b/regression-test/data/correctness_p0/test_bit_shift_nereids.out
new file mode 100644
index 00000000000..1c956fe3c74
--- /dev/null
+++ b/regression-test/data/correctness_p0/test_bit_shift_nereids.out
@@ -0,0 +1,345 @@
+-- This file is automatically generated. You should know what you did if you want to edit this
+-- !comment --
+testing big_shift_left
+
+-- !numbers --
+0
+16
+32
+48
+64
+80
+96
+112
+128
+144
+
+-- !0 --
+0
+
+-- !1 --
+1024
+
+-- !2 --
+-9223372036854775808
+
+-- !3 --
+1
+
+-- !select --
+254
+
+-- !select --
+254
+
+-- !int64_max --
+9223372036854775807 -2
+
+-- !int64_min --
+-9223372036854775808 0
+
+-- !select --
+127 -9223372036854775808
+
+-- !select --
+-128 0
+
+-- !select --
+0 254 65534 4294967294 -2
+1 -256 -65536 -4294967296 -2
+
+-- !comment --
+testing big_shift_right
+
+-- !select --
+0
+
+-- !select --
+0
+
+-- !select --
+1
+
+-- !select --
+0
+
+-- !select --
+9223372036854775807
+
+-- !select --
+2
+
+-- !select --
+1
+
+-- !select --
+-9223372036854775808
+
+-- !select --
+0
+
+-- !select --
+0
+
+-- !select --
+1
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+
+-- !select --
+1
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+
diff --git a/regression-test/suites/correctness_p0/test_bit_function.groovy b/regression-test/suites/correctness_p0/test_bit_function.groovy
index 10b6e52de15..fc7b2c454b5 100644
--- a/regression-test/suites/correctness_p0/test_bit_function.groovy
+++ b/regression-test/suites/correctness_p0/test_bit_function.groovy
@@ -18,4 +18,67 @@
suite("test_bit_functions") {
sql "SET enable_nereids_planner=false"
qt_select 'select bitand(123456, 321.0), bitor(123456, 321.0), bitxor(123456, 321.0), bitnot(321.0);'
+
+ sql "SET enable_nereids_planner=false;"
+ qt_bit_count 'select bit_count(number) from numbers("number"="10");'
+ qt_bit_count 'select bit_count(0);'
+ qt_bit_count 'select bit_count(-1);'
+ qt_bit_count 'select bit_count(cast (-1 as tinyint));' // 8
+ qt_bit_count 'select bit_count(cast (-1 as smallint));' // 16
+ qt_bit_count 'select bit_count(cast (-1 as int));' // 32
+ qt_bit_count 'select bit_count(cast (-1 as bigint));' // 64
+ qt_bit_count 'select bit_count(cast (-1 as largeint));' // 128
+ qt_bit_count_TINYINT_MAX 'select bit_count(cast (127 as tinyint));' // TINYINT_MAX
+ qt_bit_count_TINYINT_MIN 'select bit_count(cast (-128 as tinyint));' // TINYINT_MIN
+ qt_bit_count_SMALLINT_MAX 'select bit_count(cast (32767 as smallint));' // SMALLINT_MAX
+ qt_bit_count_SMALLINT_MIN 'select bit_count(cast (-32768 as smallint));' // SMALLINT_MIN
+ qt_bit_count_INT_MAX 'select bit_count(cast (2147483647 as int));' // INT_MAX
+ qt_bit_count_INT_IN 'select bit_count(cast (-2147483648 as int));' // INT_MIN
+ qt_bit_count_INT64_MAX 'select bit_count(cast (9223372036854775807 as bigint));' // INT64_MAX
+ qt_bit_count_INT64_MIN 'select bit_count(cast (-9223372036854775808 as bigint));' // INT64_MIN
+ // INT128_MAX
+ qt_bit_count_INT128_MAX """
+ select bit_count(170141183460469231731687303715884105727),
+ bit_count(cast (170141183460469231731687303715884105727 as largeint));
+ """
+ // INT128_MIN
+ qt_bit_count_INT128_MIN """
+ select bit_count(-170141183460469231731687303715884105728),
+ bit_count(cast (-170141183460469231731687303715884105728 as largeint));
+ """
+
+ qt_select "select bit_count(bit_shift_right(-1, 63)), bit_count(bit_shift_right(-1, 63));"
+
+ sql "SET enable_nereids_planner=true;"
+ sql "SET enable_fallback_to_original_planner=false;"
+
+ qt_bit_count 'select bit_count(number) from numbers("number"="10");'
+ qt_bit_count 'select bit_count(0);'
+ qt_bit_count 'select bit_count(-1);'
+ qt_bit_count 'select bit_count(cast (-1 as tinyint));' // 8
+ qt_bit_count 'select bit_count(cast (-1 as smallint));' // 16
+ qt_bit_count 'select bit_count(cast (-1 as int));' // 32
+ qt_bit_count 'select bit_count(cast (-1 as bigint));' // 64
+ qt_bit_count 'select bit_count(cast (-1 as largeint));' // 128
+ qt_bit_count_TINYINT_MAX 'select bit_count(cast (127 as tinyint));' // TINYINT_MAX
+ qt_bit_count_TINYINT_MIN 'select bit_count(cast (-128 as tinyint));' // TINYINT_MIN
+ qt_bit_count_SMALLINT_MAX 'select bit_count(cast (32767 as smallint));' // SMALLINT_MAX
+ qt_bit_count_SMALLINT_MIN 'select bit_count(cast (-32768 as smallint));' // SMALLINT_MIN
+ qt_bit_count_INT_MAX 'select bit_count(cast (2147483647 as int));' // INT_MAX
+ qt_bit_count_INT_IN 'select bit_count(cast (-2147483648 as int));' // INT_MIN
+ qt_bit_count_INT64_MAX 'select bit_count(cast (9223372036854775807 as bigint));' // INT64_MAX
+ qt_bit_count_INT64_MIN 'select bit_count(cast (-9223372036854775808 as bigint));' // INT64_MIN
+ // INT128_MAX
+ qt_bit_count_INT128_MAX """
+ select bit_count(170141183460469231731687303715884105727),
+ bit_count(cast (170141183460469231731687303715884105727 as largeint));
+ """
+ // INT128_MIN
+ qt_bit_count_INT128_MIN """
+ select bit_count(-170141183460469231731687303715884105728),
+ bit_count(cast (-170141183460469231731687303715884105728 as largeint));
+ """
+
+ qt_select "select bit_count(bit_shift_right(-1, 63)), bit_count(bit_shift_right(-1, 63));"
+
}
diff --git a/regression-test/suites/correctness_p0/test_bit_shift_lagency.groovy b/regression-test/suites/correctness_p0/test_bit_shift_lagency.groovy
new file mode 100644
index 00000000000..2db6ab0e901
--- /dev/null
+++ b/regression-test/suites/correctness_p0/test_bit_shift_lagency.groovy
@@ -0,0 +1,105 @@
+// 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.
+
+suite("test_bit_shift_lagency") {
+ sql "SET enable_nereids_planner=false;"
+
+ qt_comment """
+ select "testing big_shift_left";
+ """
+ def INT64_MAX=9223372036854775807;
+ def INT64_MIN=-9223372036854775808;
+ def INT8_MAX=127
+ def INT8_MIN=-128
+
+ // bit_shift_left
+
+ qt_numbers 'select bit_shift_left(number, 4) from numbers("number"="10");'
+ qt_0 "select bit_shift_left(0, 0);"
+ qt_1 "select bit_shift_left(1, 10);"
+ qt_2 "select bit_shift_left(1, 63);"
+ qt_3 "select bit_shift_left(1, 64);"
+ qt_select "select bit_shift_left(127, 1);"
+ qt_select "select bit_shift_left(cast (127 as TINYINT), 1);"
+ qt_int64_max """
+ WITH tbl AS (
+ SELECT ${INT64_MAX} AS BIGINT_MAX)
+ SELECT BIGINT_MAX, bit_shift_left(BIGINT_MAX, 1)
+ FROM tbl
+ """
+ qt_int64_min """
+ WITH tbl AS (
+ SELECT ${INT64_MIN} AS BIGINT_MIN)
+ SELECT BIGINT_MIN, bit_shift_left(BIGINT_MIN, 1)
+ FROM tbl
+ """
+ qt_select """
+ WITH tbl AS (
+ SELECT ${INT8_MAX} AS TINYINT_MAX)
+ SELECT TINYINT_MAX, bit_shift_left(1, TINYINT_MAX)
+ FROM tbl
+ """
+ qt_select """
+ WITH tbl AS (
+ SELECT ${INT8_MIN} AS TINYINT_MIN)
+ SELECT TINYINT_MIN, bit_shift_left(1, TINYINT_MIN)
+ FROM tbl
+ """
+
+ sql """ drop table if exists test_bit_shift_nereids; """
+ sql """
+ create table test_bit_shift_nereids (
+ rid tinyint,
+ ti tinyint,
+ si smallint,
+ i int,
+ bi bigint
+ ) distributed by HASH(rid)
+ properties("replication_num"="1");
+ """
+ sql """ insert into test_bit_shift_nereids values
+ (0, 127, 32767, 2147483647, ${INT64_MAX}),
+ (1, -128, -32768, -2147483648, ${INT64_MAX})"""
+
+ qt_select """
+ select rid,
+ bit_shift_left(ti, 1), bit_shift_left(si, 1),
+ bit_shift_left(i, 1), bit_shift_left(bi, 1)
+ from test_bit_shift_nereids order by rid; """
+
+ // bit_shift_right
+
+ qt_comment """
+ select "testing big_shift_right";
+ """
+
+ qt_select "SELECT bit_shift_right(0, 0);"
+ qt_select "SELECT bit_shift_right(0, 127);"
+ qt_select "SELECT bit_shift_right(${INT64_MAX}, 62);"
+ qt_select "SELECT bit_shift_right(${INT64_MAX}, 63);"
+ qt_select "SELECT bit_shift_right(${INT64_MAX}, 64);"
+ qt_select "SELECT bit_shift_right(${INT64_MIN}, 62);"
+ qt_select "SELECT bit_shift_right(${INT64_MIN}, 63);"
+ qt_select "SELECT bit_shift_right(${INT64_MIN}, 64);"
+ qt_select "SELECT bit_shift_right(1, ${INT8_MAX});"
+ qt_select "SELECT bit_shift_right(1, ${INT8_MIN});"
+
+ // nagitave shift count
+
+ qt_select """SELECT bit_shift_right(1, -number) from numbers("number"="129") order by number;"""
+ qt_select """SELECT bit_shift_right(1, -number) from numbers("number"="129") order by number;"""
+}
diff --git a/regression-test/suites/correctness_p0/test_bit_shift_nereids.groovy b/regression-test/suites/correctness_p0/test_bit_shift_nereids.groovy
new file mode 100644
index 00000000000..65f86877374
--- /dev/null
+++ b/regression-test/suites/correctness_p0/test_bit_shift_nereids.groovy
@@ -0,0 +1,105 @@
+// 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.
+
+suite("test_bit_shift_nereids") {
+ sql "SET enable_nereids_planner=true;"
+ sql "SET enable_fallback_to_original_planner=false;"
+
+ qt_comment """
+ select "testing big_shift_left";
+ """
+ def INT64_MAX=9223372036854775807;
+ def INT64_MIN=-9223372036854775808;
+ def INT8_MAX=127
+ def INT8_MIN=-128
+
+ // bit_shift_left
+
+ qt_numbers 'select bit_shift_left(number, 4) from numbers("number"="10");'
+ qt_0 "select bit_shift_left(0, 0);"
+ qt_1 "select bit_shift_left(1, 10);"
+ qt_2 "select bit_shift_left(1, 63);"
+ qt_3 "select bit_shift_left(1, 64);"
+ qt_select "select bit_shift_left(127, 1);"
+ qt_select "select bit_shift_left(cast (127 as TINYINT), 1);"
+ qt_int64_max """
+ WITH tbl AS (
+ SELECT ${INT64_MAX} AS BIGINT_MAX)
+ SELECT BIGINT_MAX, bit_shift_left(BIGINT_MAX, 1)
+ FROM tbl
+ """
+ qt_int64_min """
+ WITH tbl AS (
+ SELECT ${INT64_MIN} AS BIGINT_MIN)
+ SELECT BIGINT_MIN, bit_shift_left(BIGINT_MIN, 1)
+ FROM tbl
+ """
+ qt_select """
+ WITH tbl AS (
+ SELECT ${INT8_MAX} AS TINYINT_MAX)
+ SELECT TINYINT_MAX, bit_shift_left(1, TINYINT_MAX)
+ FROM tbl
+ """
+ qt_select """
+ WITH tbl AS (
+ SELECT ${INT8_MIN} AS TINYINT_MIN)
+ SELECT TINYINT_MIN, bit_shift_left(1, TINYINT_MIN)
+ FROM tbl
+ """
+
+ sql """ drop table if exists test_bit_shift_nereids; """
+ sql """
+ create table test_bit_shift_nereids (
+ rid tinyint,
+ ti tinyint,
+ si smallint,
+ i int,
+ bi bigint
+ ) distributed by HASH(rid)
+ properties("replication_num"="1");
+ """
+ sql """ insert into test_bit_shift_nereids values
+ (0, 127, 32767, 2147483647, ${INT64_MAX}),
+ (1, -128, -32768, -2147483648, ${INT64_MAX})"""
+
+ qt_select """
+ select rid,
+ bit_shift_left(ti, 1), bit_shift_left(si, 1),
+ bit_shift_left(i, 1), bit_shift_left(bi, 1)
+ from test_bit_shift_nereids order by rid; """
+ // bit_shift_right
+
+ qt_comment """
+ select "testing big_shift_right";
+ """
+
+ qt_select "SELECT bit_shift_right(0, 0);"
+ qt_select "SELECT bit_shift_right(0, 127);"
+ qt_select "SELECT bit_shift_right(${INT64_MAX}, 62);"
+ qt_select "SELECT bit_shift_right(${INT64_MAX}, 63);"
+ qt_select "SELECT bit_shift_right(${INT64_MAX}, 64);"
+ qt_select "SELECT bit_shift_right(${INT64_MIN}, 62);"
+ qt_select "SELECT bit_shift_right(${INT64_MIN}, 63);"
+ qt_select "SELECT bit_shift_right(${INT64_MIN}, 64);"
+ qt_select "SELECT bit_shift_right(1, ${INT8_MAX});"
+ qt_select "SELECT bit_shift_right(1, ${INT8_MIN});"
+
+ // nagitave shift count
+
+ qt_select """SELECT bit_shift_right(1, -number) from numbers("number"="129") order by number;"""
+ qt_select """SELECT bit_shift_right(1, -number) from numbers("number"="129") order by number;"""
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 34/43: [fix](auto-partition) Fix a concurrent bug (#30086)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 60ce22f15e869d8d1a8ed5a9a0048f67d6a79422
Author: zclllyybb <zh...@selectdb.com>
AuthorDate: Mon Jan 22 17:46:26 2024 +0800
[fix](auto-partition) Fix a concurrent bug (#30086)
when incremental opening, it may be a mistake to send new packet from sender to reciever cuz' re-constructed send closure.
now fixed it.
---
be/src/runtime/tablets_channel.cpp | 2 +-
be/src/vec/sink/writer/vtablet_writer.cpp | 51 +++++----
be/src/vec/sink/writer/vtablet_writer.h | 4 +-
.../auto_partition/ddl/stress_destination.sql | 20 ++++
.../auto_partition/ddl/stress_source.sql | 19 ++++
.../doris_dbgen_conf/stress_test_insert_into.yaml | 21 ++++
.../auto_partition/sql/multi_thread_load.groovy | 3 +-
.../sql/stress_test_insert_into.groovy | 118 +++++++++++++++++++++
8 files changed, 215 insertions(+), 23 deletions(-)
diff --git a/be/src/runtime/tablets_channel.cpp b/be/src/runtime/tablets_channel.cpp
index 7ead68d916f..d248ad09d7a 100644
--- a/be/src/runtime/tablets_channel.cpp
+++ b/be/src/runtime/tablets_channel.cpp
@@ -152,7 +152,7 @@ Status BaseTabletsChannel::open(const PTabletWriterOpenRequest& request) {
Status BaseTabletsChannel::incremental_open(const PTabletWriterOpenRequest& params) {
SCOPED_TIMER(_incremental_open_timer);
if (_state == kInitialized) { // haven't opened
- return open(params);
+ RETURN_IF_ERROR(open(params));
}
std::lock_guard<std::mutex> l(_lock);
std::vector<SlotDescriptor*>* index_slots = nullptr;
diff --git a/be/src/vec/sink/writer/vtablet_writer.cpp b/be/src/vec/sink/writer/vtablet_writer.cpp
index 0ca2f7d8ffb..8eb1c4d743a 100644
--- a/be/src/vec/sink/writer/vtablet_writer.cpp
+++ b/be/src/vec/sink/writer/vtablet_writer.cpp
@@ -310,6 +310,10 @@ void VNodeChannel::clear_all_blocks() {
// no need to set _cancel_msg because the error will be
// returned directly via "TabletSink::prepare()" method.
Status VNodeChannel::init(RuntimeState* state) {
+ if (_inited) {
+ return Status::OK();
+ }
+
SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
_task_exec_ctx = state->get_task_execution_context();
_tuple_desc = _parent->_output_tuple_desc;
@@ -348,6 +352,25 @@ Status VNodeChannel::init(RuntimeState* state) {
_cur_add_block_request->set_backend_id(_node_id);
_cur_add_block_request->set_eos(false);
+ // add block closure
+ _send_block_callback = WriteBlockCallback<PTabletWriterAddBlockResult>::create_shared();
+ _send_block_callback->addFailedHandler([this](bool is_last_rpc) {
+ auto ctx_lock = _task_exec_ctx.lock();
+ if (ctx_lock == nullptr) {
+ return;
+ }
+ _add_block_failed_callback(is_last_rpc);
+ });
+
+ _send_block_callback->addSuccessHandler(
+ [this](const PTabletWriterAddBlockResult& result, bool is_last_rpc) {
+ auto ctx_lock = _task_exec_ctx.lock();
+ if (ctx_lock == nullptr) {
+ return;
+ }
+ _add_block_success_callback(result, is_last_rpc);
+ });
+
_name = fmt::format("VNodeChannel[{}-{}]", _index_channel->_index_id, _node_id);
// The node channel will send _batch_size rows of data each rpc. When the
// number of tablets is large, the number of data rows received by each
@@ -356,18 +379,23 @@ Status VNodeChannel::init(RuntimeState* state) {
// a relatively large value to improve the import performance.
_batch_size = std::max(_batch_size, 8192);
+ _inited = true;
return Status::OK();
}
void VNodeChannel::_open_internal(bool is_incremental) {
+ if (_tablets_wait_open.empty()) {
+ return;
+ }
SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
auto request = std::make_shared<PTabletWriterOpenRequest>();
request->set_allocated_id(&_parent->_load_id);
request->set_index_id(_index_channel->_index_id);
request->set_txn_id(_parent->_txn_id);
request->set_allocated_schema(_parent->_schema->to_protobuf());
+
std::set<int64_t> deduper;
- for (auto& tablet : _all_tablets) {
+ for (auto& tablet : _tablets_wait_open) {
if (deduper.contains(tablet.tablet_id)) {
continue;
}
@@ -375,7 +403,10 @@ void VNodeChannel::_open_internal(bool is_incremental) {
ptablet->set_partition_id(tablet.partition_id);
ptablet->set_tablet_id(tablet.tablet_id);
deduper.insert(tablet.tablet_id);
+ _all_tablets.push_back(std::move(tablet));
}
+ _tablets_wait_open.clear();
+
request->set_num_senders(_parent->_num_senders);
request->set_need_gen_rollup(false); // Useless but it is a required field in pb
request->set_load_mem_limit(_parent->_load_mem_limit);
@@ -444,24 +475,6 @@ Status VNodeChannel::open_wait() {
}
}
- // add block closure
- _send_block_callback = WriteBlockCallback<PTabletWriterAddBlockResult>::create_shared();
- _send_block_callback->addFailedHandler([this](bool is_last_rpc) {
- auto ctx_lock = _task_exec_ctx.lock();
- if (ctx_lock == nullptr) {
- return;
- }
- _add_block_failed_callback(is_last_rpc);
- });
-
- _send_block_callback->addSuccessHandler(
- [this](const PTabletWriterAddBlockResult& result, bool is_last_rpc) {
- auto ctx_lock = _task_exec_ctx.lock();
- if (ctx_lock == nullptr) {
- return;
- }
- _add_block_success_callback(result, is_last_rpc);
- });
return status;
}
diff --git a/be/src/vec/sink/writer/vtablet_writer.h b/be/src/vec/sink/writer/vtablet_writer.h
index cd2eafb1f24..68534cd3a16 100644
--- a/be/src/vec/sink/writer/vtablet_writer.h
+++ b/be/src/vec/sink/writer/vtablet_writer.h
@@ -219,7 +219,7 @@ public:
~VNodeChannel();
// called before open, used to add tablet located in this backend. called by IndexChannel::init
- void add_tablet(const TTabletWithPartition& tablet) { _all_tablets.emplace_back(tablet); }
+ void add_tablet(const TTabletWithPartition& tablet) { _tablets_wait_open.emplace_back(tablet); }
std::string debug_tablets() const {
std::stringstream ss;
for (const auto& tab : _all_tablets) {
@@ -368,6 +368,7 @@ protected:
std::vector<std::shared_ptr<DummyBrpcCallback<PTabletWriterOpenResult>>> _open_callbacks;
std::vector<TTabletWithPartition> _all_tablets;
+ std::vector<TTabletWithPartition> _tablets_wait_open;
// map from tablet_id to node_id where slave replicas locate in
std::unordered_map<int64_t, std::vector<int64_t>> _slave_tablet_nodes;
std::vector<TTabletCommitInfo> _tablet_commit_infos;
@@ -388,6 +389,7 @@ protected:
// The IndexChannel is definitely accessible until the NodeChannel is closed.
std::mutex _closed_lock;
bool _is_closed = false;
+ bool _inited = false;
RuntimeState* _state = nullptr;
// A context lock for callbacks, the callback has to lock the ctx, to avoid
diff --git a/regression-test/suites/partition_p1/auto_partition/ddl/stress_destination.sql b/regression-test/suites/partition_p1/auto_partition/ddl/stress_destination.sql
new file mode 100644
index 00000000000..f1dbb790987
--- /dev/null
+++ b/regression-test/suites/partition_p1/auto_partition/ddl/stress_destination.sql
@@ -0,0 +1,20 @@
+CREATE TABLE `stress_destination` (
+ `create_date` DATE NOT NULL,
+ `parent_org_id` VARCHAR(96) NULL,
+ `org_id` VARCHAR(100) NULL,
+ `org_name` VARCHAR(192) NULL,
+ `create_month` VARCHAR(11) NOT NULL,
+ `org_type` VARCHAR(192) NULL,
+ `sms_total` INT NULL,
+ `success_sms_total` INT NULL,
+ `sms_price_total` DOUBLE NULL,
+ `sms_total_sum` INT NULL,
+ `has_sub` INT NULL,
+ `order_num` INT NULL
+) ENGINE=OLAP
+UNIQUE KEY(`create_date`, `parent_org_id`, `org_id`)
+AUTO PARTITION BY RANGE date_trunc(`create_date`,'day')()
+DISTRIBUTED BY HASH(`create_date`, `org_id`) BUCKETS AUTO
+PROPERTIES (
+"replication_allocation" = "tag.location.default: 1"
+);
diff --git a/regression-test/suites/partition_p1/auto_partition/ddl/stress_source.sql b/regression-test/suites/partition_p1/auto_partition/ddl/stress_source.sql
new file mode 100644
index 00000000000..d095e4119c7
--- /dev/null
+++ b/regression-test/suites/partition_p1/auto_partition/ddl/stress_source.sql
@@ -0,0 +1,19 @@
+CREATE TABLE `stress_source` (
+ `create_date` DATE NOT NULL,
+ `parent_org_id` VARCHAR(96) NULL,
+ `org_id` VARCHAR(100) NULL,
+ `org_name` VARCHAR(192) NULL,
+ `create_month` VARCHAR(11) NOT NULL,
+ `org_type` VARCHAR(192) NULL,
+ `sms_total` INT NULL,
+ `success_sms_total` INT NULL,
+ `sms_price_total` DOUBLE NULL,
+ `sms_total_sum` INT NULL,
+ `has_sub` INT NULL,
+ `order_num` INT NULL
+) ENGINE=OLAP
+UNIQUE KEY(`create_date`, `parent_org_id`, `org_id`)
+DISTRIBUTED BY HASH(`create_date`, `org_id`) BUCKETS AUTO
+PROPERTIES (
+"replication_allocation" = "tag.location.default: 1"
+);
diff --git a/regression-test/suites/partition_p1/auto_partition/doris_dbgen_conf/stress_test_insert_into.yaml b/regression-test/suites/partition_p1/auto_partition/doris_dbgen_conf/stress_test_insert_into.yaml
new file mode 100644
index 00000000000..a45fb01c316
--- /dev/null
+++ b/regression-test/suites/partition_p1/auto_partition/doris_dbgen_conf/stress_test_insert_into.yaml
@@ -0,0 +1,21 @@
+// 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.
+
+tables:
+ stress_source:
+ create_date:
+ range: {min: "2023-07-01", max: "2024-01-10"}
\ No newline at end of file
diff --git a/regression-test/suites/partition_p1/auto_partition/sql/multi_thread_load.groovy b/regression-test/suites/partition_p1/auto_partition/sql/multi_thread_load.groovy
index 25a9a49305d..aebc022feeb 100644
--- a/regression-test/suites/partition_p1/auto_partition/sql/multi_thread_load.groovy
+++ b/regression-test/suites/partition_p1/auto_partition/sql/multi_thread_load.groovy
@@ -20,9 +20,8 @@ import java.nio.file.Files
import java.nio.file.Paths
import java.net.URL
import java.io.File
-import java.util.concurrent.locks.ReentrantLock
-suite("multi_thread_load") {
+suite("multi_thread_load", "nonConcurrent") { // stress case should use resource fully
// get doris-db from s3
def dirPath = context.file.parent
def fatherPath = context.file.parentFile.parentFile.getPath()
diff --git a/regression-test/suites/partition_p1/auto_partition/sql/stress_test_insert_into.groovy b/regression-test/suites/partition_p1/auto_partition/sql/stress_test_insert_into.groovy
new file mode 100644
index 00000000000..d2ce87248e0
--- /dev/null
+++ b/regression-test/suites/partition_p1/auto_partition/sql/stress_test_insert_into.groovy
@@ -0,0 +1,118 @@
+// 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.
+
+import groovy.io.FileType
+import java.nio.file.Files
+import java.nio.file.Paths
+import java.net.URL
+import java.io.File
+
+suite("stress_test_insert_into") {
+ // get doris-db from s3
+ def dirPath = context.file.parent
+ def fatherPath = context.file.parentFile.parentFile.getPath()
+ def fileName = "doris-dbgen"
+ def fileUrl = "${getS3Url()}/regression/doris-dbgen-23-10-18/doris-dbgen-23-10-20/doris-dbgen"
+ def filePath = Paths.get(dirPath, fileName)
+ if (!Files.exists(filePath)) {
+ new URL(fileUrl).withInputStream { inputStream ->
+ Files.copy(inputStream, filePath)
+ }
+ def file = new File(dirPath + "/" + fileName)
+ file.setExecutable(true)
+ }
+
+ def rows = 100000
+
+ // load data via doris-dbgen
+ def doris_dbgen_create_data = { db_name, tb_name ->
+ def tableName = tb_name
+
+ def jdbcUrl = context.config.jdbcUrl
+ def urlWithoutSchema = jdbcUrl.substring(jdbcUrl.indexOf("://") + 3)
+ def sql_ip = urlWithoutSchema.substring(0, urlWithoutSchema.indexOf(":"))
+ def sql_port
+ if (urlWithoutSchema.indexOf("/") >= 0) {
+ // e.g: jdbc:mysql://locahost:8080/?a=b
+ sql_port = urlWithoutSchema.substring(urlWithoutSchema.indexOf(":") + 1, urlWithoutSchema.indexOf("/"))
+ } else {
+ // e.g: jdbc:mysql://locahost:8080
+ sql_port = urlWithoutSchema.substring(urlWithoutSchema.indexOf(":") + 1)
+ }
+ String feHttpAddress = context.config.feHttpAddress
+ def http_port = feHttpAddress.substring(feHttpAddress.indexOf(":") + 1)
+
+ String realDb = db_name
+ String user = context.config.jdbcUser
+ String password = context.config.jdbcPassword
+
+ def cm
+ if (password) {
+ cm = """
+ ${dirPath}/doris-dbgen gen
+ --host ${sql_ip}
+ --sql-port ${sql_port}
+ --user ${user}
+ --password ${password}
+ --database ${realDb}
+ --table ${tableName}
+ --rows ${rows}
+ --http-port ${http_port}
+ --config ${fatherPath}/doris_dbgen_conf/stress_test_insert_into.yaml
+ """
+ } else {
+ cm = """
+ ${dirPath}/doris-dbgen gen
+ --host ${sql_ip}
+ --sql-port ${sql_port}
+ --user ${user}
+ --database ${realDb}
+ --table ${tableName}
+ --rows ${rows}
+ --http-port ${http_port}
+ --config ${fatherPath}/doris_dbgen_conf/stress_test_insert_into.yaml
+ """
+ }
+
+ logger.info("datagen: " + cm)
+ def proc = cm.execute()
+ def sout = new StringBuilder(), serr = new StringBuilder()
+ proc.consumeProcessOutput(sout, serr)
+ proc.waitForOrKill(1800000)
+ }
+
+ def database_name = "regression_test_auto_partition_concurrent"
+ def table_src = "stress_source"
+ def table_dest = "stress_destination"
+
+ sql """create database if not exists ${database_name};"""
+ sql """use ${database_name};"""
+ sql """drop table if exists ${table_src};"""
+ sql """drop table if exists ${table_dest};"""
+ sql new File("""${fatherPath}/ddl/stress_source.sql""").text
+ sql new File("""${fatherPath}/ddl/stress_destination.sql""").text
+ doris_dbgen_create_data(database_name, table_src)
+
+ // TEST-BODY
+ def count_src = sql " select count() from ${table_src}; "
+ sql " insert into ${table_dest} select * from ${table_src} "
+ def count_dest = sql " select count() from ${table_dest}; "
+ // check data count
+ assertTrue(count_src[0][0] > 0)
+ assertEquals(count_src[0][0], count_dest[0][0])
+ logger.info("got rows: ${count_src[0][0]}")
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 14/43: [fix](phrase_prefix) fix match_phrase_prefix query incorrect result (#29946)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit e5f1d8d7ec5486ce7d9a69a50990bffe610fe417
Author: zzzxl <33...@users.noreply.github.com>
AuthorDate: Mon Jan 22 10:34:25 2024 +0800
[fix](phrase_prefix) fix match_phrase_prefix query incorrect result (#29946)
---
.../inverted_index/query/phrase_prefix_query.cpp | 5 +-
.../test_index_match_phrase_prefix_1.out | 13 +++++
.../test_index_match_phrase_prefix_1.groovy | 62 ++++++++++++++++++++++
3 files changed, 79 insertions(+), 1 deletion(-)
diff --git a/be/src/olap/rowset/segment_v2/inverted_index/query/phrase_prefix_query.cpp b/be/src/olap/rowset/segment_v2/inverted_index/query/phrase_prefix_query.cpp
index 7920336c752..407e515dc92 100644
--- a/be/src/olap/rowset/segment_v2/inverted_index/query/phrase_prefix_query.cpp
+++ b/be/src/olap/rowset/segment_v2/inverted_index/query/phrase_prefix_query.cpp
@@ -17,6 +17,7 @@
#include "phrase_prefix_query.h"
+#include "CLucene/util/stringUtil.h"
#include "olap/rowset//segment_v2/inverted_index/query/prefix_query.h"
namespace doris::segment_v2 {
@@ -43,7 +44,9 @@ void PhrasePrefixQuery::add(const std::wstring& field_name, const std::vector<st
PrefixQuery::get_prefix_terms(_searcher->getReader(), field_name, terms[i],
prefix_terms, _max_expansions);
if (prefix_terms.empty()) {
- continue;
+ std::wstring ws_term = StringUtil::string_to_wstring(terms[i]);
+ Term* t = _CLNEW Term(field_name.c_str(), ws_term.c_str());
+ prefix_terms.push_back(t);
}
_query->add(prefix_terms);
for (auto& t : prefix_terms) {
diff --git a/regression-test/data/inverted_index_p0/test_index_match_phrase_prefix_1.out b/regression-test/data/inverted_index_p0/test_index_match_phrase_prefix_1.out
new file mode 100644
index 00000000000..e7e934f394e
--- /dev/null
+++ b/regression-test/data/inverted_index_p0/test_index_match_phrase_prefix_1.out
@@ -0,0 +1,13 @@
+-- This file is automatically generated. You should know what you did if you want to edit this
+-- !sql --
+7
+
+-- !sql --
+7
+
+-- !sql --
+6
+
+-- !sql --
+6
+
diff --git a/regression-test/suites/inverted_index_p0/test_index_match_phrase_prefix_1.groovy b/regression-test/suites/inverted_index_p0/test_index_match_phrase_prefix_1.groovy
new file mode 100644
index 00000000000..1e2ac0d7900
--- /dev/null
+++ b/regression-test/suites/inverted_index_p0/test_index_match_phrase_prefix_1.groovy
@@ -0,0 +1,62 @@
+// 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.
+
+
+suite("test_index_match_phrase_prefix_1", "p0"){
+ def indexTbName1 = "test_index_match_phrase_prefix_1"
+
+ sql "DROP TABLE IF EXISTS ${indexTbName1}"
+
+ sql """
+ CREATE TABLE ${indexTbName1} (
+ `a` int(11) NULL COMMENT "",
+ `b` string NULL COMMENT "",
+ `c` string NULL COMMENT "",
+ `d` string NULL COMMENT "",
+ INDEX b_idx (`b`) USING INVERTED COMMENT '',
+ INDEX c_idx (`c`) USING INVERTED PROPERTIES("parser" = "unicode", "support_phrase" = "true") COMMENT '',
+ INDEX d_idx (`d`) USING INVERTED PROPERTIES("parser" = "english", "support_phrase" = "true") COMMENT ''
+ ) ENGINE=OLAP
+ DUPLICATE KEY(`a`)
+ COMMENT "OLAP"
+ DISTRIBUTED BY RANDOM BUCKETS 1
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1"
+ );
+ """
+
+ sql """ INSERT INTO ${indexTbName1} VALUES (1, "O1704361998540E2Cemx9S", "O1704361998540E2Cemx9S", "O1704361998540E2Cemx9S"); """
+ sql """ INSERT INTO ${indexTbName1} VALUES (2, "O1704361998540E2Cemx9S)123456789", "O1704361998540E2Cemx9S)123456789", "O1704361998540E2Cemx9S)123456789"); """
+ sql """ INSERT INTO ${indexTbName1} VALUES (3, "O1704361998540E2Cemx9S=123456789", "O1704361998540E2Cemx9S=123456789", "O1704361998540E2Cemx9S=123456789"); """
+ sql """ INSERT INTO ${indexTbName1} VALUES (4, "O1704361998540E2Cemx9S+123456789", "O1704361998540E2Cemx9S+123456789", "O1704361998540E2Cemx9S+123456789"); """
+ sql """ INSERT INTO ${indexTbName1} VALUES (5, "O1704361998540E2Cemx9S!123456789", "O1704361998540E2Cemx9S!123456789", "O1704361998540E2Cemx9S!123456789"); """
+ sql """ INSERT INTO ${indexTbName1} VALUES (6, "O1704361998540E2Cemx9S 123456789", "O1704361998540E2Cemx9S 123456789", "O1704361998540E2Cemx9S 123456789"); """
+ sql """ INSERT INTO ${indexTbName1} VALUES (7, "O1704361998540E2Cemx9S*123456789", "O1704361998540E2Cemx9S*123456789", "O1704361998540E2Cemx9S*123456789"); """
+
+ try {
+ sql "sync"
+
+ qt_sql """ select count() from ${indexTbName1} where c match_phrase_prefix 'O1704361998540E2Cemx9S'; """
+ qt_sql """ select count() from ${indexTbName1} where d match_phrase_prefix 'O1704361998540E2Cemx9S'; """
+
+ qt_sql """ select count() from ${indexTbName1} where c match_phrase_prefix 'O1704361998540E2Cemx9S=123456789'; """
+ qt_sql """ select count() from ${indexTbName1} where d match_phrase_prefix 'O1704361998540E2Cemx9S=123456789'; """
+
+ } finally {
+ //try_sql("DROP TABLE IF EXISTS ${testTable}")
+ }
+}
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 19/43: [Improvement](nereids) Make sure to catch and record exception for every materialization context (#29953)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 9a58cacf0f5062cc2c0b535a794519fecb52ce73
Author: seawinde <14...@users.noreply.github.com>
AuthorDate: Mon Jan 22 13:04:04 2024 +0800
[Improvement](nereids) Make sure to catch and record exception for every materialization context (#29953)
1. Make sure instance when change params of StructInfo,Predicates.
2. Catch and record exception for every materialization context, this make sure that if throw exception when one materialization context rewrite, it will not influence others.
3. Support to mv rewrite when hava count function when aggregate without group by
---
.../main/java/org/apache/doris/mtmv/MTMVCache.java | 4 +-
.../mv/AbstractMaterializedViewAggregateRule.java | 114 +++----
.../mv/AbstractMaterializedViewJoinRule.java | 17 +-
.../mv/AbstractMaterializedViewRule.java | 372 ++++++++++++---------
.../mv/MaterializedViewAggregateRule.java | 2 +-
.../nereids/rules/exploration/mv/Predicates.java | 28 +-
.../nereids/rules/exploration/mv/StructInfo.java | 147 +++++---
.../nereids/rules/rewrite/NormalizeToSlot.java | 23 +-
.../org/apache/doris/nereids/trees/TreeNode.java | 17 -
.../trees/plans/logical/LogicalProject.java | 4 +
.../apache/doris/nereids/util/ExpressionUtils.java | 4 +-
.../mv/agg_with_roll_up/aggregate_with_roll_up.out | 6 +
.../agg_with_roll_up/aggregate_with_roll_up.groovy | 131 +++++---
13 files changed, 483 insertions(+), 386 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVCache.java b/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVCache.java
index 3d776d9a7a4..a7ddeeb170c 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVCache.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVCache.java
@@ -63,7 +63,9 @@ public class MTMVCache {
StatementContext mvSqlStatementContext = new StatementContext(connectContext,
new OriginStatement(mtmv.getQuerySql(), 0));
NereidsPlanner planner = new NereidsPlanner(mvSqlStatementContext);
-
+ if (mvSqlStatementContext.getConnectContext().getStatementContext() == null) {
+ mvSqlStatementContext.getConnectContext().setStatementContext(mvSqlStatementContext);
+ }
Plan mvRewrittenPlan =
planner.plan(unboundMvPlan, PhysicalProperties.ANY, ExplainLevel.REWRITTEN_PLAN);
Plan mvPlan = mvRewrittenPlan instanceof LogicalResultSink
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewAggregateRule.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewAggregateRule.java
index e47e15dd56b..48b900ca745 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewAggregateRule.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewAggregateRule.java
@@ -23,8 +23,8 @@ import org.apache.doris.nereids.jobs.joinorder.hypergraph.edge.JoinEdge;
import org.apache.doris.nereids.jobs.joinorder.hypergraph.node.AbstractNode;
import org.apache.doris.nereids.jobs.joinorder.hypergraph.node.StructInfoNode;
import org.apache.doris.nereids.rules.exploration.mv.StructInfo.PlanSplitContext;
-import org.apache.doris.nereids.rules.exploration.mv.mapping.ExpressionMapping;
import org.apache.doris.nereids.rules.exploration.mv.mapping.SlotMapping;
+import org.apache.doris.nereids.trees.expressions.Alias;
import org.apache.doris.nereids.trees.expressions.Any;
import org.apache.doris.nereids.trees.expressions.Cast;
import org.apache.doris.nereids.trees.expressions.ExprId;
@@ -45,7 +45,6 @@ import org.apache.doris.nereids.types.BigIntType;
import org.apache.doris.nereids.util.ExpressionUtils;
import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
@@ -64,7 +63,7 @@ import java.util.stream.Collectors;
*/
public abstract class AbstractMaterializedViewAggregateRule extends AbstractMaterializedViewRule {
- protected static final Multimap<Expression, Expression>
+ protected static final Multimap<Function, Expression>
AGGREGATE_ROLL_UP_EQUIVALENT_FUNCTION_MAP = ArrayListMultimap.create();
static {
@@ -95,7 +94,7 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
protected Plan rewriteQueryByView(MatchMode matchMode,
StructInfo queryStructInfo,
StructInfo viewStructInfo,
- SlotMapping queryToViewSlotMapping,
+ SlotMapping viewToQuerySlotMapping,
Plan tempRewritedPlan,
MaterializationContext materializationContext) {
// get view and query aggregate and top plan correspondingly
@@ -115,12 +114,11 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
}
// Firstly,if group by expression between query and view is equals, try to rewrite expression directly
Plan queryTopPlan = queryTopPlanAndAggPair.key();
- SlotMapping viewToQurySlotMapping = queryToViewSlotMapping.inverse();
- if (isGroupByEquals(queryTopPlanAndAggPair, viewTopPlanAndAggPair, viewToQurySlotMapping)) {
+ if (isGroupByEquals(queryTopPlanAndAggPair, viewTopPlanAndAggPair, viewToQuerySlotMapping)) {
List<Expression> rewrittenQueryExpressions = rewriteExpression(queryTopPlan.getExpressions(),
queryTopPlan,
materializationContext.getMvExprToMvScanExprMapping(),
- queryToViewSlotMapping,
+ viewToQuerySlotMapping,
true);
if (!rewrittenQueryExpressions.isEmpty()) {
return new LogicalProject<>(
@@ -133,15 +131,17 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
Pair.of("Can not rewrite expression when no roll up",
String.format("expressionToWrite = %s,\n mvExprToMvScanExprMapping = %s,\n"
- + "queryToViewSlotMapping = %s",
+ + "viewToQuerySlotMapping = %s",
queryTopPlan.getExpressions(),
materializationContext.getMvExprToMvScanExprMapping(),
- queryToViewSlotMapping)));
+ viewToQuerySlotMapping)));
}
// if view is scalar aggregate but query is not. Or if query is scalar aggregate but view is not
// Should not rewrite
- if (queryTopPlanAndAggPair.value().getGroupByExpressions().isEmpty()
- || viewTopPlanAndAggPair.value().getGroupByExpressions().isEmpty()) {
+ List<Expression> queryGroupByExpressions = queryTopPlanAndAggPair.value().getGroupByExpressions();
+ List<Expression> viewGroupByExpressions = viewTopPlanAndAggPair.value().getGroupByExpressions();
+ if ((queryGroupByExpressions.isEmpty() && !viewGroupByExpressions.isEmpty())
+ || (!queryGroupByExpressions.isEmpty() && viewGroupByExpressions.isEmpty())) {
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
Pair.of("only one the of query or view is scalar aggregate and "
+ "can not rewrite expression meanwhile",
@@ -154,53 +154,42 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
// split the query top plan expressions to group expressions and functions, if can not, bail out.
Pair<Set<? extends Expression>, Set<? extends Expression>> queryGroupAndFunctionPair
= topPlanSplitToGroupAndFunction(queryTopPlanAndAggPair);
- // this map will be used to rewrite expression
- Multimap<Expression, Expression> needRollupExprMap = HashMultimap.create();
- Multimap<Expression, Expression> groupRewrittenExprMap = HashMultimap.create();
- // permute the mv expr mapping to query based
- Map<Expression, Expression> mvExprToMvScanExprQueryBased =
- materializationContext.getMvExprToMvScanExprMapping().keyPermute(viewToQurySlotMapping)
- .flattenMap().get(0);
Set<? extends Expression> queryTopPlanFunctionSet = queryGroupAndFunctionPair.value();
// try to rewrite, contains both roll up aggregate functions and aggregate group expression
List<NamedExpression> finalAggregateExpressions = new ArrayList<>();
List<Expression> finalGroupExpressions = new ArrayList<>();
- for (Expression topExpression : queryTopPlan.getExpressions()) {
+ List<? extends Expression> queryExpressions = queryTopPlan.getExpressions();
+ // permute the mv expr mapping to query based
+ Map<Expression, Expression> mvExprToMvScanExprQueryBased =
+ materializationContext.getMvExprToMvScanExprMapping().keyPermute(viewToQuerySlotMapping)
+ .flattenMap().get(0);
+ for (Expression topExpression : queryExpressions) {
// if agg function, try to roll up and rewrite
if (queryTopPlanFunctionSet.contains(topExpression)) {
Expression queryFunctionShuttled = ExpressionUtils.shuttleExpressionWithLineage(
topExpression,
queryTopPlan);
// try to roll up
- AggregateFunction queryFunction = (AggregateFunction) queryFunctionShuttled.firstMatch(
- expr -> expr instanceof AggregateFunction);
- Function rollupAggregateFunction = rollup(queryFunction, queryFunctionShuttled,
- mvExprToMvScanExprQueryBased);
+ List<Object> queryFunctions =
+ queryFunctionShuttled.collectFirst(expr -> expr instanceof AggregateFunction);
+ if (queryFunctions.isEmpty()) {
+ materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("Can not found query function",
+ String.format("queryFunctionShuttled = %s", queryFunctionShuttled)));
+ return null;
+ }
+ Function rollupAggregateFunction = rollup((AggregateFunction) queryFunctions.get(0),
+ queryFunctionShuttled, mvExprToMvScanExprQueryBased);
if (rollupAggregateFunction == null) {
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
Pair.of("Query function roll up fail",
String.format("queryFunction = %s,\n queryFunctionShuttled = %s,\n"
+ "mvExprToMvScanExprQueryBased = %s",
- queryFunction, queryFunctionShuttled, mvExprToMvScanExprQueryBased)));
- return null;
- }
- // key is query need roll up expr, value is mv scan based roll up expr
- needRollupExprMap.put(queryFunctionShuttled, rollupAggregateFunction);
- // rewrite query function expression by mv expression
- ExpressionMapping needRollupExprMapping = new ExpressionMapping(needRollupExprMap);
- Expression rewrittenFunctionExpression = rewriteExpression(topExpression,
- queryTopPlan,
- needRollupExprMapping,
- queryToViewSlotMapping,
- false);
- if (rewrittenFunctionExpression == null) {
- materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Roll up expression can not rewrite by view", String.format(
- "topExpression = %s,\n needRollupExprMapping = %s,\n queryToViewSlotMapping = %s",
- topExpression, needRollupExprMapping, queryToViewSlotMapping)));
+ queryFunctions.get(0), queryFunctionShuttled,
+ mvExprToMvScanExprQueryBased)));
return null;
}
- finalAggregateExpressions.add((NamedExpression) rewrittenFunctionExpression);
+ finalAggregateExpressions.add(new Alias(rollupAggregateFunction));
} else {
// if group by expression, try to rewrite group by expression
Expression queryGroupShuttledExpr =
@@ -213,26 +202,9 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
mvExprToMvScanExprQueryBased, queryGroupShuttledExpr)));
return null;
}
- groupRewrittenExprMap.put(queryGroupShuttledExpr,
- mvExprToMvScanExprQueryBased.get(queryGroupShuttledExpr));
- // rewrite query group expression by mv expression
- ExpressionMapping groupRewrittenExprMapping = new ExpressionMapping(groupRewrittenExprMap);
- Expression rewrittenGroupExpression = rewriteExpression(
- topExpression,
- queryTopPlan,
- groupRewrittenExprMapping,
- queryToViewSlotMapping,
- true);
- if (rewrittenGroupExpression == null) {
- materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Query dimensions can not be rewritten by view",
- String.format("topExpression is %s,\n groupRewrittenExprMapping is %s,\n"
- + "queryToViewSlotMapping = %s",
- topExpression, groupRewrittenExprMapping, queryToViewSlotMapping)));
- return null;
- }
- finalAggregateExpressions.add((NamedExpression) rewrittenGroupExpression);
- finalGroupExpressions.add(rewrittenGroupExpression);
+ Expression expression = mvExprToMvScanExprQueryBased.get(queryGroupShuttledExpr);
+ finalAggregateExpressions.add((NamedExpression) expression);
+ finalGroupExpressions.add(expression);
}
}
// add project to guarantee group by column ref is slot reference,
@@ -271,7 +243,7 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
private boolean isGroupByEquals(Pair<Plan, LogicalAggregate<Plan>> queryTopPlanAndAggPair,
Pair<Plan, LogicalAggregate<Plan>> viewTopPlanAndAggPair,
- SlotMapping viewToQurySlotMapping) {
+ SlotMapping viewToQuerySlotMapping) {
Plan queryTopPlan = queryTopPlanAndAggPair.key();
Plan viewTopPlan = viewTopPlanAndAggPair.key();
LogicalAggregate<Plan> queryAggregate = queryTopPlanAndAggPair.value();
@@ -282,7 +254,7 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
Set<? extends Expression> viewGroupShuttledExpressionQueryBased = ExpressionUtils.shuttleExpressionWithLineage(
viewAggregate.getGroupByExpressions(), viewTopPlan)
.stream()
- .map(expr -> ExpressionUtils.replace(expr, viewToQurySlotMapping.toSlotReferenceMap()))
+ .map(expr -> ExpressionUtils.replace(expr, viewToQuerySlotMapping.toSlotReferenceMap()))
.collect(Collectors.toSet());
return queryGroupShuttledExpression.equals(viewGroupShuttledExpressionQueryBased);
}
@@ -309,19 +281,20 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
}
Expression rollupParam = null;
Expression viewRollupFunction = null;
- if (mvExprToMvScanExprQueryBased.containsKey(queryAggregateFunctionShuttled)) {
- // function can rewrite by view
+ // handle simple aggregate function roll up which is not in the AGGREGATE_ROLL_UP_EQUIVALENT_FUNCTION_MAP
+ if (mvExprToMvScanExprQueryBased.containsKey(queryAggregateFunctionShuttled)
+ && AGGREGATE_ROLL_UP_EQUIVALENT_FUNCTION_MAP.keySet().stream()
+ .noneMatch(aggFunction -> aggFunction.equals(queryAggregateFunction))) {
rollupParam = mvExprToMvScanExprQueryBased.get(queryAggregateFunctionShuttled);
viewRollupFunction = queryAggregateFunctionShuttled;
} else {
- // function can not rewrite by view, try to use complex roll up param
+ // handle complex functions roll up
// eg: query is count(distinct param), mv sql is bitmap_union(to_bitmap(param))
for (Expression mvExprShuttled : mvExprToMvScanExprQueryBased.keySet()) {
if (!(mvExprShuttled instanceof Function)) {
continue;
}
- if (isAggregateFunctionEquivalent(queryAggregateFunction, queryAggregateFunctionShuttled,
- (Function) mvExprShuttled)) {
+ if (isAggregateFunctionEquivalent(queryAggregateFunction, (Function) mvExprShuttled)) {
rollupParam = mvExprToMvScanExprQueryBased.get(mvExprShuttled);
viewRollupFunction = mvExprShuttled;
}
@@ -429,13 +402,12 @@ public abstract class AbstractMaterializedViewAggregateRule extends AbstractMate
* This will check the count(distinct a) in query is equivalent to bitmap_union(to_bitmap(a)) in mv,
* and then check their arguments is equivalent.
*/
- private boolean isAggregateFunctionEquivalent(Function queryFunction, Expression queryFunctionShuttled,
- Function viewFunction) {
+ private boolean isAggregateFunctionEquivalent(Function queryFunction, Function viewFunction) {
if (queryFunction.equals(viewFunction)) {
return true;
}
// check the argument of rollup function is equivalent to view function or not
- for (Map.Entry<Expression, Collection<Expression>> equivalentFunctionEntry :
+ for (Map.Entry<Function, Collection<Expression>> equivalentFunctionEntry :
AGGREGATE_ROLL_UP_EQUIVALENT_FUNCTION_MAP.asMap().entrySet()) {
if (equivalentFunctionEntry.getKey().equals(queryFunction)) {
// check is have equivalent function or not
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewJoinRule.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewJoinRule.java
index a482b13b5e7..57894ac17ca 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewJoinRule.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewJoinRule.java
@@ -23,6 +23,7 @@ import org.apache.doris.nereids.jobs.joinorder.hypergraph.edge.JoinEdge;
import org.apache.doris.nereids.jobs.joinorder.hypergraph.node.AbstractNode;
import org.apache.doris.nereids.jobs.joinorder.hypergraph.node.StructInfoNode;
import org.apache.doris.nereids.rules.exploration.mv.mapping.SlotMapping;
+import org.apache.doris.nereids.trees.expressions.Alias;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.NamedExpression;
import org.apache.doris.nereids.trees.plans.Plan;
@@ -47,7 +48,7 @@ public abstract class AbstractMaterializedViewJoinRule extends AbstractMateriali
protected Plan rewriteQueryByView(MatchMode matchMode,
StructInfo queryStructInfo,
StructInfo viewStructInfo,
- SlotMapping queryToViewSlotMapping,
+ SlotMapping targetToSourceMapping,
Plan tempRewritedPlan,
MaterializationContext materializationContext) {
// Rewrite top projects, represent the query projects by view
@@ -55,19 +56,18 @@ public abstract class AbstractMaterializedViewJoinRule extends AbstractMateriali
queryStructInfo.getExpressions(),
queryStructInfo.getOriginalPlan(),
materializationContext.getMvExprToMvScanExprMapping(),
- queryToViewSlotMapping,
+ targetToSourceMapping,
true
);
// Can not rewrite, bail out
- if (expressionsRewritten.isEmpty()
- || expressionsRewritten.stream().anyMatch(expr -> !(expr instanceof NamedExpression))) {
+ if (expressionsRewritten.isEmpty()) {
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
Pair.of("Rewrite expressions by view in join fail",
String.format("expressionToRewritten is %s,\n mvExprToMvScanExprMapping is %s,\n"
- + "queryToViewSlotMapping = %s",
+ + "targetToSourceMapping = %s",
queryStructInfo.getExpressions(),
materializationContext.getMvExprToMvScanExprMapping(),
- queryToViewSlotMapping)));
+ targetToSourceMapping)));
return null;
}
// record the group id in materializationContext, and when rewrite again in
@@ -77,7 +77,10 @@ public abstract class AbstractMaterializedViewJoinRule extends AbstractMateriali
queryStructInfo.getOriginalPlan().getGroupExpression().get().getOwnerGroup().getGroupId());
}
return new LogicalProject<>(
- expressionsRewritten.stream().map(NamedExpression.class::cast).collect(Collectors.toList()),
+ expressionsRewritten.stream()
+ .map(expression -> expression instanceof NamedExpression ? expression : new Alias(expression))
+ .map(NamedExpression.class::cast)
+ .collect(Collectors.toList()),
tempRewritedPlan);
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java
index 352bccc019b..ea035769b60 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java
@@ -48,6 +48,7 @@ import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.algebra.CatalogRelation;
import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
import org.apache.doris.nereids.util.ExpressionUtils;
import org.apache.doris.nereids.util.TypeUtils;
@@ -72,163 +73,222 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
JoinType.LEFT_OUTER_JOIN);
/**
- * The abstract template method for query rewrite, it contains the main logic and different query
- * pattern should override the sub logic.
+ * The abstract template method for query rewrite, it contains the main logic, try to rewrite query by
+ * multi materialization every time. if exception it will catch the exception and record it to
+ * materialization context.
*/
- protected List<Plan> rewrite(Plan queryPlan, CascadesContext cascadesContext) {
+ public List<Plan> rewrite(Plan queryPlan, CascadesContext cascadesContext) {
+ List<Plan> rewrittenPlans = new ArrayList<>();
+ // already rewrite or query is invalid, bail out
+ List<StructInfo> queryStructInfos = checkQuery(queryPlan, cascadesContext);
+ if (queryStructInfos.isEmpty()) {
+ return rewrittenPlans;
+ }
+ for (MaterializationContext context : cascadesContext.getMaterializationContexts()) {
+ if (checkIfRewritten(queryPlan, context)) {
+ continue;
+ }
+ // TODO Just support only one query struct info, support multi later.
+ StructInfo queryStructInfo = queryStructInfos.get(0);
+ try {
+ rewrittenPlans.addAll(doRewrite(queryStructInfo, cascadesContext, context));
+ } catch (Exception exception) {
+ context.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("Materialized view rule exec fail", exception.toString()));
+ }
+ }
+ return rewrittenPlans;
+ }
+
+ /**
+ * Check query is valid or not, if valid return the query struct infos, if invalid return empty list.
+ */
+ protected List<StructInfo> checkQuery(Plan queryPlan, CascadesContext cascadesContext) {
+ List<StructInfo> validQueryStructInfos = new ArrayList<>();
List<MaterializationContext> materializationContexts = cascadesContext.getMaterializationContexts();
- List<Plan> rewriteResults = new ArrayList<>();
if (materializationContexts.isEmpty()) {
- return rewriteResults;
+ return validQueryStructInfos;
}
List<StructInfo> queryStructInfos = MaterializedViewUtils.extractStructInfo(queryPlan, cascadesContext);
// TODO Just Check query queryPlan firstly, support multi later.
StructInfo queryStructInfo = queryStructInfos.get(0);
if (!checkPattern(queryStructInfo)) {
- materializationContexts.forEach(ctx -> ctx.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Query struct info is invalid",
- String.format("queryPlan is %s", queryPlan.treeString()))));
+ cascadesContext.getMaterializationContexts().forEach(ctx ->
+ ctx.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("Query struct info is invalid",
+ String.format("queryPlan is %s", queryPlan.treeString())))
+ );
+ return validQueryStructInfos;
+ }
+ validQueryStructInfos.add(queryStructInfo);
+ return validQueryStructInfos;
+ }
+
+ /**
+ * The abstract template method for query rewrite, it contains the main logic, try to rewrite query by
+ * only one materialization every time. Different query pattern should override the sub logic.
+ */
+ protected List<Plan> doRewrite(StructInfo queryStructInfo, CascadesContext cascadesContext,
+ MaterializationContext materializationContext) {
+ List<Plan> rewriteResults = new ArrayList<>();
+ List<StructInfo> viewStructInfos = MaterializedViewUtils.extractStructInfo(
+ materializationContext.getMvPlan(), cascadesContext);
+ if (viewStructInfos.size() > 1) {
+ // view struct info should only have one
+ materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("The num of view struct info is more then one",
+ String.format("mv plan is %s", materializationContext.getMvPlan().treeString())));
return rewriteResults;
}
- for (MaterializationContext materializationContext : materializationContexts) {
- // already rewrite, bail out
- if (checkIfRewritten(queryPlan, materializationContext)) {
- continue;
- }
- List<StructInfo> viewStructInfos = MaterializedViewUtils.extractStructInfo(
- materializationContext.getMvPlan(), cascadesContext);
- if (viewStructInfos.size() > 1) {
- // view struct info should only have one
- materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("The num of view struct info is more then one",
- String.format("mv plan is %s", materializationContext.getMvPlan().treeString())));
- return rewriteResults;
- }
- StructInfo viewStructInfo = viewStructInfos.get(0);
- if (!checkPattern(viewStructInfo)) {
+ StructInfo viewStructInfo = viewStructInfos.get(0);
+ if (!checkPattern(viewStructInfo)) {
+ materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("View struct info is invalid",
+ String.format(", view plan is %s", viewStructInfo.getOriginalPlan().treeString())));
+ return rewriteResults;
+ }
+ MatchMode matchMode = decideMatchMode(queryStructInfo.getRelations(), viewStructInfo.getRelations());
+ if (MatchMode.COMPLETE != matchMode) {
+ materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("Match mode is invalid", String.format("matchMode is %s", matchMode)));
+ return rewriteResults;
+ }
+ List<RelationMapping> queryToViewTableMappings = RelationMapping.generate(queryStructInfo.getRelations(),
+ viewStructInfo.getRelations());
+ // if any relation in query and view can not map, bail out.
+ if (queryToViewTableMappings == null) {
+ materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("Query to view table mapping is null", ""));
+ return rewriteResults;
+ }
+ for (RelationMapping queryToViewTableMapping : queryToViewTableMappings) {
+ SlotMapping queryToViewSlotMapping = SlotMapping.generate(queryToViewTableMapping);
+ if (queryToViewSlotMapping == null) {
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("View struct info is invalid",
- String.format(", view plan is %s", viewStructInfo.getOriginalPlan().treeString())));
+ Pair.of("Query to view slot mapping is null", ""));
continue;
}
- MatchMode matchMode = decideMatchMode(queryStructInfo.getRelations(), viewStructInfo.getRelations());
- if (MatchMode.COMPLETE != matchMode) {
+ SlotMapping viewToQuerySlotMapping = queryToViewSlotMapping.inverse();
+ LogicalCompatibilityContext compatibilityContext = LogicalCompatibilityContext.from(
+ queryToViewTableMapping, queryToViewSlotMapping, queryStructInfo, viewStructInfo);
+ ComparisonResult comparisonResult = StructInfo.isGraphLogicalEquals(queryStructInfo, viewStructInfo,
+ compatibilityContext);
+ if (comparisonResult.isInvalid()) {
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Match mode is invalid", String.format("matchMode is %s", matchMode)));
+ Pair.of("The graph logic between query and view is not consistent",
+ comparisonResult.getErrorMessage()));
continue;
}
- List<RelationMapping> queryToViewTableMappings = RelationMapping.generate(queryStructInfo.getRelations(),
- viewStructInfo.getRelations());
- // if any relation in query and view can not map, bail out.
- if (queryToViewTableMappings == null) {
+ SplitPredicate compensatePredicates = predicatesCompensate(queryStructInfo, viewStructInfo,
+ viewToQuerySlotMapping, comparisonResult, cascadesContext);
+ // Can not compensate, bail out
+ if (compensatePredicates.isInvalid()) {
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Query to view table mapping is null", ""));
- return rewriteResults;
+ Pair.of("Predicate compensate fail",
+ String.format("query predicates = %s,\n query equivalenceClass = %s, \n"
+ + "view predicates = %s,\n query equivalenceClass = %s\n",
+ queryStructInfo.getPredicates(),
+ queryStructInfo.getEquivalenceClass(),
+ viewStructInfo.getPredicates(),
+ viewStructInfo.getEquivalenceClass())));
+ continue;
}
- for (RelationMapping queryToViewTableMapping : queryToViewTableMappings) {
- SlotMapping queryToViewSlotMapping = SlotMapping.generate(queryToViewTableMapping);
- if (queryToViewSlotMapping == null) {
+ Plan rewrittenPlan;
+ Plan mvScan = materializationContext.getMvScanPlan();
+ Plan originalPlan = queryStructInfo.getOriginalPlan();
+ if (compensatePredicates.isAlwaysTrue()) {
+ rewrittenPlan = mvScan;
+ } else {
+ // Try to rewrite compensate predicates by using mv scan
+ List<Expression> rewriteCompensatePredicates = rewriteExpression(compensatePredicates.toList(),
+ originalPlan, materializationContext.getMvExprToMvScanExprMapping(),
+ viewToQuerySlotMapping, true);
+ if (rewriteCompensatePredicates.isEmpty()) {
materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Query to view slot mapping is null", ""));
+ Pair.of("Rewrite compensate predicate by view fail", String.format(
+ "compensatePredicates = %s,\n mvExprToMvScanExprMapping = %s,\n"
+ + "viewToQuerySlotMapping = %s",
+ compensatePredicates,
+ materializationContext.getMvExprToMvScanExprMapping(),
+ viewToQuerySlotMapping)));
continue;
}
- LogicalCompatibilityContext compatibilityContext = LogicalCompatibilityContext.from(
- queryToViewTableMapping, queryToViewSlotMapping, queryStructInfo, viewStructInfo);
- ComparisonResult comparisonResult = StructInfo.isGraphLogicalEquals(queryStructInfo, viewStructInfo,
- compatibilityContext);
- if (comparisonResult.isInvalid()) {
- materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("The graph logic between query and view is not consistent",
- comparisonResult.getErrorMessage()));
- continue;
- }
- SplitPredicate compensatePredicates = predicatesCompensate(queryStructInfo, viewStructInfo,
- queryToViewSlotMapping, comparisonResult, cascadesContext);
- // Can not compensate, bail out
- if (compensatePredicates.isInvalid()) {
- materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Predicate compensate fail",
- String.format("query predicates = %s,\n query equivalenceClass = %s, \n"
- + "view predicates = %s,\n query equivalenceClass = %s\n",
- queryStructInfo.getPredicates(),
- queryStructInfo.getEquivalenceClass(),
- viewStructInfo.getPredicates(),
- viewStructInfo.getEquivalenceClass())));
- continue;
- }
- Plan rewrittenPlan;
- Plan mvScan = materializationContext.getMvScanPlan();
- if (compensatePredicates.isAlwaysTrue()) {
- rewrittenPlan = mvScan;
- } else {
- // Try to rewrite compensate predicates by using mv scan
- List<Expression> rewriteCompensatePredicates = rewriteExpression(compensatePredicates.toList(),
- queryPlan, materializationContext.getMvExprToMvScanExprMapping(), queryToViewSlotMapping,
- true);
- if (rewriteCompensatePredicates.isEmpty()) {
- materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Rewrite compensate predicate by view fail", String.format(
- "compensatePredicates = %s,\n mvExprToMvScanExprMapping = %s,\n"
- + "queryToViewSlotMapping = %s",
- compensatePredicates,
- materializationContext.getMvExprToMvScanExprMapping(),
- queryToViewSlotMapping)));
- continue;
- }
- rewrittenPlan = new LogicalFilter<>(Sets.newHashSet(rewriteCompensatePredicates), mvScan);
- }
- // Rewrite query by view
- rewrittenPlan = rewriteQueryByView(matchMode, queryStructInfo, viewStructInfo, queryToViewSlotMapping,
- rewrittenPlan, materializationContext);
- if (rewrittenPlan == null) {
- continue;
- }
- // run rbo job on mv rewritten plan
- CascadesContext rewrittenPlanContext = CascadesContext.initContext(
- cascadesContext.getStatementContext(), rewrittenPlan,
- cascadesContext.getCurrentJobContext().getRequiredProperties());
- Rewriter.getWholeTreeRewriter(rewrittenPlanContext).execute();
- rewrittenPlan = rewrittenPlanContext.getRewritePlan();
- if (!checkOutput(queryPlan, rewrittenPlan, materializationContext)) {
- continue;
- }
- // check the partitions used by rewritten plan is valid or not
- Set<Long> invalidPartitionsQueryUsed =
- calcInvalidPartitions(rewrittenPlan, materializationContext, cascadesContext);
- if (!invalidPartitionsQueryUsed.isEmpty()) {
- materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
- Pair.of("Check partition query used validation fail",
- String.format("the partition used by query is invalid by materialized view,"
- + "invalid partition info query used is %s",
- materializationContext.getMTMV().getPartitions().stream()
- .filter(partition ->
- invalidPartitionsQueryUsed.contains(partition.getId()))
- .collect(Collectors.toSet()))));
- continue;
- }
- recordIfRewritten(queryPlan, materializationContext);
- rewriteResults.add(rewrittenPlan);
+ rewrittenPlan = new LogicalFilter<>(Sets.newHashSet(rewriteCompensatePredicates), mvScan);
+ }
+ // Rewrite query by view
+ rewrittenPlan = rewriteQueryByView(matchMode, queryStructInfo, viewStructInfo, viewToQuerySlotMapping,
+ rewrittenPlan, materializationContext);
+ if (rewrittenPlan == null) {
+ continue;
}
+ rewrittenPlan = rewriteByRules(cascadesContext, rewrittenPlan, originalPlan);
+ if (!isOutputValid(originalPlan, rewrittenPlan)) {
+ ObjectId planObjId = originalPlan.getGroupExpression().map(GroupExpression::getId)
+ .orElseGet(() -> new ObjectId(-1));
+ materializationContext.recordFailReason(planObjId, Pair.of(
+ "RewrittenPlan output logical properties is different with target group",
+ String.format("planOutput logical properties = %s,\n"
+ + "groupOutput logical properties = %s", rewrittenPlan.getLogicalProperties(),
+ originalPlan.getLogicalProperties())));
+ continue;
+ }
+ // check the partitions used by rewritten plan is valid or not
+ Set<Long> invalidPartitionsQueryUsed =
+ calcInvalidPartitions(rewrittenPlan, materializationContext, cascadesContext);
+ if (!invalidPartitionsQueryUsed.isEmpty()) {
+ materializationContext.recordFailReason(queryStructInfo.getOriginalPlanId(),
+ Pair.of("Check partition query used validation fail",
+ String.format("the partition used by query is invalid by materialized view,"
+ + "invalid partition info query used is %s",
+ materializationContext.getMTMV().getPartitions().stream()
+ .filter(partition ->
+ invalidPartitionsQueryUsed.contains(partition.getId()))
+ .collect(Collectors.toSet()))));
+ continue;
+ }
+ recordIfRewritten(originalPlan, materializationContext);
+ rewriteResults.add(rewrittenPlan);
}
return rewriteResults;
}
+ /**
+ * Rewrite by rules and try to make output is the same after optimize by rules
+ */
+ protected Plan rewriteByRules(CascadesContext cascadesContext, Plan rewrittenPlan, Plan originPlan) {
+ // run rbo job on mv rewritten plan
+ CascadesContext rewrittenPlanContext = CascadesContext.initContext(
+ cascadesContext.getStatementContext(), rewrittenPlan,
+ cascadesContext.getCurrentJobContext().getRequiredProperties());
+ Rewriter.getWholeTreeRewriter(rewrittenPlanContext).execute();
+ rewrittenPlan = rewrittenPlanContext.getRewritePlan();
+ List<Slot> originPlanOutput = originPlan.getOutput();
+ List<Slot> rewrittenPlanOutput = rewrittenPlan.getOutput();
+ if (originPlanOutput.size() != rewrittenPlanOutput.size()) {
+ return null;
+ }
+ List<NamedExpression> expressions = new ArrayList<>();
+ // should add project above rewritten plan if top plan is not project, if aggregate above will nu
+ if (!isOutputValid(originPlan, rewrittenPlan)) {
+ for (int i = 0; i < originPlanOutput.size(); i++) {
+ expressions.add(((NamedExpression) normalizeExpression(originPlanOutput.get(i),
+ rewrittenPlanOutput.get(i))));
+ }
+ return new LogicalProject<>(expressions, rewrittenPlan, false);
+ }
+ return rewrittenPlan;
+ }
+
/**
* Check the logical properties of rewritten plan by mv is the same with source plan
+ * if same return true, if different return false
*/
- protected boolean checkOutput(Plan sourcePlan, Plan rewrittenPlan, MaterializationContext materializationContext) {
+ protected boolean isOutputValid(Plan sourcePlan, Plan rewrittenPlan) {
if (sourcePlan.getGroupExpression().isPresent() && !rewrittenPlan.getLogicalProperties()
.equals(sourcePlan.getGroupExpression().get().getOwnerGroup().getLogicalProperties())) {
- ObjectId planObjId = sourcePlan.getGroupExpression().map(GroupExpression::getId)
- .orElseGet(() -> new ObjectId(-1));
- materializationContext.recordFailReason(planObjId, Pair.of(
- "RewrittenPlan output logical properties is different with target group",
- String.format("planOutput logical properties = %s,\n"
- + "groupOutput logical properties = %s", rewrittenPlan.getLogicalProperties(),
- sourcePlan.getGroupExpression().get().getOwnerGroup().getLogicalProperties())));
return false;
}
- return true;
+ return sourcePlan.getLogicalProperties().equals(rewrittenPlan.getLogicalProperties());
}
/**
@@ -271,7 +331,7 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
* Rewrite query by view, for aggregate or join rewriting should be different inherit class implementation
*/
protected Plan rewriteQueryByView(MatchMode matchMode, StructInfo queryStructInfo, StructInfo viewStructInfo,
- SlotMapping queryToViewSlotMapping, Plan tempRewritedPlan, MaterializationContext materializationContext) {
+ SlotMapping viewToQuerySlotMapping, Plan tempRewritedPlan, MaterializationContext materializationContext) {
return tempRewritedPlan;
}
@@ -298,7 +358,7 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
* target
*/
protected List<Expression> rewriteExpression(List<? extends Expression> sourceExpressionsToWrite, Plan sourcePlan,
- ExpressionMapping targetExpressionMapping, SlotMapping sourceToTargetMapping,
+ ExpressionMapping targetExpressionMapping, SlotMapping targetToSourceMapping,
boolean targetExpressionNeedSourceBased) {
// Firstly, rewrite the target expression using source with inverse mapping
// then try to use the target expression to represent the query. if any of source expressions
@@ -307,14 +367,13 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
List<? extends Expression> sourceShuttledExpressions = ExpressionUtils.shuttleExpressionWithLineage(
sourceExpressionsToWrite, sourcePlan);
ExpressionMapping expressionMappingKeySourceBased = targetExpressionNeedSourceBased
- ? targetExpressionMapping.keyPermute(sourceToTargetMapping.inverse()) : targetExpressionMapping;
+ ? targetExpressionMapping.keyPermute(targetToSourceMapping) : targetExpressionMapping;
// target to target replacement expression mapping, because mv is 1:1 so get first element
List<Map<Expression, Expression>> flattenExpressionMap = expressionMappingKeySourceBased.flattenMap();
Map<? extends Expression, ? extends Expression> targetToTargetReplacementMapping = flattenExpressionMap.get(0);
List<Expression> rewrittenExpressions = new ArrayList<>();
- for (int index = 0; index < sourceShuttledExpressions.size(); index++) {
- Expression expressionShuttledToRewrite = sourceShuttledExpressions.get(index);
+ for (Expression expressionShuttledToRewrite : sourceShuttledExpressions) {
if (expressionShuttledToRewrite instanceof Literal) {
rewrittenExpressions.add(expressionShuttledToRewrite);
continue;
@@ -327,39 +386,31 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
// if contains any slot to rewrite, which means can not be rewritten by target, bail out
return ImmutableList.of();
}
- Expression sourceExpression = sourceExpressionsToWrite.get(index);
- if (sourceExpression instanceof NamedExpression
- && replacedExpression.nullable() != sourceExpression.nullable()) {
- // if enable join eliminate, query maybe inner join and mv maybe outer join.
- // If the slot is at null generate side, the nullable maybe different between query and view
- // So need to force to consistent.
- replacedExpression = sourceExpression.nullable()
- ? new Nullable(replacedExpression) : new NonNullable(replacedExpression);
- }
- if (sourceExpression instanceof NamedExpression) {
- NamedExpression sourceNamedExpression = (NamedExpression) sourceExpression;
- replacedExpression = new Alias(sourceNamedExpression.getExprId(), replacedExpression,
- sourceNamedExpression.getName());
- }
rewrittenExpressions.add(replacedExpression);
}
return rewrittenExpressions;
}
/**
- * Rewrite single expression, the logic is the same with above
+ * Normalize expression with query, keep the consistency of exprId and nullable props with
+ * query
*/
- protected Expression rewriteExpression(Expression sourceExpressionsToWrite, Plan sourcePlan,
- ExpressionMapping targetExpressionMapping, SlotMapping sourceToTargetMapping,
- boolean targetExpressionNeedSourceBased) {
- List<Expression> expressionToRewrite = new ArrayList<>();
- expressionToRewrite.add(sourceExpressionsToWrite);
- List<Expression> rewrittenExpressions = rewriteExpression(expressionToRewrite, sourcePlan,
- targetExpressionMapping, sourceToTargetMapping, targetExpressionNeedSourceBased);
- if (rewrittenExpressions.isEmpty()) {
- return null;
+ protected Expression normalizeExpression(Expression sourceExpression, Expression replacedExpression) {
+ if (sourceExpression instanceof NamedExpression
+ && replacedExpression.nullable() != sourceExpression.nullable()) {
+ // if enable join eliminate, query maybe inner join and mv maybe outer join.
+ // If the slot is at null generate side, the nullable maybe different between query and view
+ // So need to force to consistent.
+ replacedExpression = sourceExpression.nullable()
+ ? new Nullable(replacedExpression) : new NonNullable(replacedExpression);
+ }
+ if (sourceExpression instanceof NamedExpression
+ && !sourceExpression.equals(replacedExpression)) {
+ NamedExpression sourceNamedExpression = (NamedExpression) sourceExpression;
+ replacedExpression = new Alias(sourceNamedExpression.getExprId(), replacedExpression,
+ sourceNamedExpression.getName());
}
- return rewrittenExpressions.get(0);
+ return replacedExpression;
}
/**
@@ -371,7 +422,7 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
protected SplitPredicate predicatesCompensate(
StructInfo queryStructInfo,
StructInfo viewStructInfo,
- SlotMapping queryToViewSlotMapping,
+ SlotMapping viewToQuerySlotMapping,
ComparisonResult comparisonResult,
CascadesContext cascadesContext
) {
@@ -379,15 +430,16 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
List<Expression> queryPulledUpExpressions = ImmutableList.copyOf(comparisonResult.getQueryExpressions());
// set pulled up expression to queryStructInfo predicates and update related predicates
if (!queryPulledUpExpressions.isEmpty()) {
- queryStructInfo.addPredicates(queryPulledUpExpressions);
+ queryStructInfo = queryStructInfo.withPredicates(
+ queryStructInfo.getPredicates().merge(queryPulledUpExpressions));
}
List<Expression> viewPulledUpExpressions = ImmutableList.copyOf(comparisonResult.getViewExpressions());
// set pulled up expression to viewStructInfo predicates and update related predicates
if (!viewPulledUpExpressions.isEmpty()) {
- viewStructInfo.addPredicates(viewPulledUpExpressions);
+ viewStructInfo = viewStructInfo.withPredicates(
+ viewStructInfo.getPredicates().merge(viewPulledUpExpressions));
}
// viewEquivalenceClass to query based
- SlotMapping viewToQuerySlotMapping = queryToViewSlotMapping.inverse();
// equal predicate compensate
final Set<Expression> equalCompensateConjunctions = Predicates.compensateEquivalence(
queryStructInfo,
@@ -422,11 +474,11 @@ public abstract class AbstractMaterializedViewRule implements ExplorationRuleFac
// query has not null reject predicates, so return
return SplitPredicate.INVALID_INSTANCE;
}
+ SlotMapping queryToViewMapping = viewToQuerySlotMapping.inverse();
Set<Expression> queryUsedNeedRejectNullSlotsViewBased = nullRejectPredicates.stream()
.map(expression -> TypeUtils.isNotNull(expression).orElse(null))
.filter(Objects::nonNull)
- .map(expr -> ExpressionUtils.replace((Expression) expr,
- queryToViewSlotMapping.toSlotReferenceMap()))
+ .map(expr -> ExpressionUtils.replace((Expression) expr, queryToViewMapping.toSlotReferenceMap()))
.collect(Collectors.toSet());
if (requireNoNullableViewSlot.stream().anyMatch(
set -> Sets.intersection(set, queryUsedNeedRejectNullSlotsViewBased).isEmpty())) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/MaterializedViewAggregateRule.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/MaterializedViewAggregateRule.java
index 9059499d381..8e0f8d6f717 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/MaterializedViewAggregateRule.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/MaterializedViewAggregateRule.java
@@ -28,7 +28,7 @@ import java.util.List;
/**
* This is responsible for aggregate rewriting according to different pattern
- * */
+ */
public class MaterializedViewAggregateRule extends AbstractMaterializedViewAggregateRule {
public static final MaterializedViewAggregateRule INSTANCE = new MaterializedViewAggregateRule();
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/Predicates.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/Predicates.java
index 93bd1d314b1..472e49d3b43 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/Predicates.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/Predicates.java
@@ -29,6 +29,7 @@ import org.apache.doris.nereids.util.Utils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
+import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@@ -39,32 +40,30 @@ import java.util.Set;
import java.util.stream.Collectors;
/**
- * This record the predicates which can be pulled up or some other type predicates
+ * This record the predicates which can be pulled up or some other type predicates.
+ * Also contains the necessary method for predicates process
*/
public class Predicates {
// Predicates that can be pulled up
- private final Set<Expression> pulledUpPredicates = new HashSet<>();
+ private final Set<Expression> pulledUpPredicates;
- private Predicates() {
+ public Predicates(Set<Expression> pulledUpPredicates) {
+ this.pulledUpPredicates = pulledUpPredicates;
}
- public static Predicates of() {
- return new Predicates();
- }
-
- public static Predicates of(List<? extends Expression> pulledUpPredicates) {
- Predicates predicates = new Predicates();
- pulledUpPredicates.forEach(predicates::addPredicate);
- return predicates;
+ public static Predicates of(Set<Expression> pulledUpPredicates) {
+ return new Predicates(pulledUpPredicates);
}
public Set<Expression> getPulledUpPredicates() {
return pulledUpPredicates;
}
- public void addPredicate(Expression expression) {
- this.pulledUpPredicates.add(expression);
+ public Predicates merge(Collection<Expression> predicates) {
+ Set<Expression> mergedPredicates = new HashSet<>(predicates);
+ mergedPredicates.addAll(this.pulledUpPredicates);
+ return new Predicates(mergedPredicates);
}
public Expression composedExpression() {
@@ -98,8 +97,7 @@ public class Predicates {
if (queryEquivalenceClass.isEmpty() && viewEquivalenceClass.isEmpty()) {
equalCompensateConjunctions.add(BooleanLiteral.TRUE);
}
- if (queryEquivalenceClass.isEmpty()
- && !viewEquivalenceClass.isEmpty()) {
+ if (queryEquivalenceClass.isEmpty() && !viewEquivalenceClass.isEmpty()) {
return null;
}
EquivalenceClassSetMapping queryToViewEquivalenceMapping =
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/StructInfo.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/StructInfo.java
index d79153bdc8e..3451d8e7c44 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/StructInfo.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/StructInfo.java
@@ -17,7 +17,9 @@
package org.apache.doris.nereids.rules.exploration.mv;
+import org.apache.doris.common.Pair;
import org.apache.doris.nereids.jobs.joinorder.hypergraph.HyperGraph;
+import org.apache.doris.nereids.jobs.joinorder.hypergraph.edge.JoinEdge;
import org.apache.doris.nereids.jobs.joinorder.hypergraph.node.StructInfoNode;
import org.apache.doris.nereids.memo.Group;
import org.apache.doris.nereids.memo.GroupExpression;
@@ -44,6 +46,7 @@ import org.apache.doris.nereids.trees.plans.visitor.DefaultPlanVisitor;
import org.apache.doris.nereids.trees.plans.visitor.ExpressionLineageReplacer;
import org.apache.doris.nereids.util.ExpressionUtils;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
@@ -60,6 +63,8 @@ import javax.annotation.Nullable;
/**
* StructInfo for plan, this contains necessary info for query rewrite by materialized view
+ * the struct info is used by all materialization, so it's struct info should only get, should not
+ * modify, if wanting to modify, should copy and then modify
*/
public class StructInfo {
public static final JoinPatternChecker JOIN_PATTERN_CHECKER = new JoinPatternChecker();
@@ -70,58 +75,76 @@ public class StructInfo {
private static final PredicateCollector PREDICATE_COLLECTOR = new PredicateCollector();
// source data
private final Plan originalPlan;
- private ObjectId originalPlanId;
+ private final ObjectId originalPlanId;
private final HyperGraph hyperGraph;
- private boolean valid = true;
+ private final boolean valid;
// derived data following
// top plan which may include project or filter, except for join and scan
- private Plan topPlan;
+ private final Plan topPlan;
// bottom plan which top plan only contain join or scan. this is needed by hyper graph
- private Plan bottomPlan;
- private final List<CatalogRelation> relations = new ArrayList<>();
+ private final Plan bottomPlan;
+ private final List<CatalogRelation> relations;
// this is for LogicalCompatibilityContext later
- private final Map<RelationId, StructInfoNode> relationIdStructInfoNodeMap = new HashMap<>();
+ private final Map<RelationId, StructInfoNode> relationIdStructInfoNodeMap;
// this recorde the predicates which can pull up, not shuttled
private Predicates predicates;
// split predicates is shuttled
- private SplitPredicate splitPredicate;
- private EquivalenceClass equivalenceClass;
+ private final SplitPredicate splitPredicate;
+ private final EquivalenceClass equivalenceClass;
// Key is the expression shuttled and the value is the origin expression
// this is for building LogicalCompatibilityContext later.
- private final Map<Expression, Expression> shuttledHashConjunctsToConjunctsMap = new HashMap<>();
+ private final Map<Expression, Expression> shuttledHashConjunctsToConjunctsMap;
// Record the exprId and the corresponding expr map, this is used by expression shuttled
- private final Map<ExprId, Expression> namedExprIdAndExprMapping = new HashMap<>();
+ private final Map<ExprId, Expression> namedExprIdAndExprMapping;
- private StructInfo(Plan originalPlan, @Nullable Plan topPlan, @Nullable Plan bottomPlan, HyperGraph hyperGraph) {
+ /**
+ * The construct method for StructInfo
+ */
+ public StructInfo(Plan originalPlan, ObjectId originalPlanId, HyperGraph hyperGraph, boolean valid, Plan topPlan,
+ Plan bottomPlan, List<CatalogRelation> relations,
+ Map<RelationId, StructInfoNode> relationIdStructInfoNodeMap,
+ @Nullable Predicates predicates,
+ Map<Expression, Expression> shuttledHashConjunctsToConjunctsMap,
+ Map<ExprId, Expression> namedExprIdAndExprMapping) {
this.originalPlan = originalPlan;
- this.originalPlanId = originalPlan.getGroupExpression()
- .map(GroupExpression::getId).orElseGet(() -> new ObjectId(-1));
+ this.originalPlanId = originalPlanId;
this.hyperGraph = hyperGraph;
+ this.valid = valid;
this.topPlan = topPlan;
this.bottomPlan = bottomPlan;
- init();
- }
-
- private void init() {
- // split the top plan to two parts by join node
- if (topPlan == null || bottomPlan == null) {
- PlanSplitContext planSplitContext = new PlanSplitContext(Sets.newHashSet(LogicalJoin.class));
- originalPlan.accept(PLAN_SPLITTER, planSplitContext);
- this.bottomPlan = planSplitContext.getBottomPlan();
- this.topPlan = planSplitContext.getTopPlan();
+ this.relations = relations;
+ this.relationIdStructInfoNodeMap = relationIdStructInfoNodeMap;
+ this.predicates = predicates;
+ if (predicates == null) {
+ // collect predicate from top plan which not in hyper graph
+ Set<Expression> topPlanPredicates = new HashSet<>();
+ topPlan.accept(PREDICATE_COLLECTOR, topPlanPredicates);
+ this.predicates = Predicates.of(topPlanPredicates);
}
- collectStructInfoFromGraph();
- initPredicates();
+ Pair<SplitPredicate, EquivalenceClass> derivedPredicates = predicatesDerive(this.predicates, originalPlan);
+ this.splitPredicate = derivedPredicates.key();
+ this.equivalenceClass = derivedPredicates.value();
+ this.shuttledHashConjunctsToConjunctsMap = shuttledHashConjunctsToConjunctsMap;
+ this.namedExprIdAndExprMapping = namedExprIdAndExprMapping;
}
- public void addPredicates(List<Expression> canPulledUpExpressions) {
- canPulledUpExpressions.forEach(this.predicates::addPredicate);
- predicatesDerive();
+ /**
+ * Construct StructInfo with new predicates
+ */
+ public StructInfo withPredicates(Predicates predicates) {
+ return new StructInfo(this.originalPlan, this.originalPlanId, this.hyperGraph, this.valid, this.topPlan,
+ this.bottomPlan, this.relations, this.relationIdStructInfoNodeMap, predicates,
+ this.shuttledHashConjunctsToConjunctsMap, this.namedExprIdAndExprMapping);
}
- private void collectStructInfoFromGraph() {
+ private static boolean collectStructInfoFromGraph(HyperGraph hyperGraph,
+ Plan topPlan,
+ Map<Expression, Expression> shuttledHashConjunctsToConjunctsMap,
+ Map<ExprId, Expression> namedExprIdAndExprMapping,
+ ImmutableList.Builder<CatalogRelation> relationBuilder,
+ Map<RelationId, StructInfoNode> relationIdStructInfoNodeMap) {
// Collect expression from join condition in hyper graph
- this.hyperGraph.getJoinEdges().forEach(edge -> {
+ for (JoinEdge edge : hyperGraph.getJoinEdges()) {
List<Expression> hashJoinConjuncts = edge.getHashJoinConjuncts();
// shuttle expression in edge for the build of LogicalCompatibilityContext later.
// Record the exprId to expr map in the processing to strut info
@@ -132,34 +155,31 @@ public class StructInfo {
Lists.newArrayList(conjunctExpr),
ImmutableSet.of(),
ImmutableSet.of());
- this.topPlan.accept(ExpressionLineageReplacer.INSTANCE, replaceContext);
+ topPlan.accept(ExpressionLineageReplacer.INSTANCE, replaceContext);
// Replace expressions by expression map
List<Expression> replacedExpressions = replaceContext.getReplacedExpressions();
shuttledHashConjunctsToConjunctsMap.put(replacedExpressions.get(0), conjunctExpr);
// Record this, will be used in top level expression shuttle later, see the method
// ExpressionLineageReplacer#visitGroupPlan
- this.namedExprIdAndExprMapping.putAll(replaceContext.getExprIdExpressionMap());
+ namedExprIdAndExprMapping.putAll(replaceContext.getExprIdExpressionMap());
});
List<Expression> otherJoinConjuncts = edge.getOtherJoinConjuncts();
if (!otherJoinConjuncts.isEmpty()) {
- this.valid = false;
+ return false;
}
- });
- if (!this.isValid()) {
- return;
}
// Collect relations from hyper graph which in the bottom plan
- this.hyperGraph.getNodes().forEach(node -> {
+ hyperGraph.getNodes().forEach(node -> {
// plan relation collector and set to map
Plan nodePlan = node.getPlan();
List<CatalogRelation> nodeRelations = new ArrayList<>();
nodePlan.accept(RELATION_COLLECTOR, nodeRelations);
- this.relations.addAll(nodeRelations);
+ relationBuilder.addAll(nodeRelations);
// every node should only have one relation, this is for LogicalCompatibilityContext
relationIdStructInfoNodeMap.put(nodeRelations.get(0).getRelationId(), (StructInfoNode) node);
});
// Collect expression from where in hyper graph
- this.hyperGraph.getFilterEdges().forEach(filterEdge -> {
+ hyperGraph.getFilterEdges().forEach(filterEdge -> {
List<? extends Expression> filterExpressions = filterEdge.getExpressions();
filterExpressions.forEach(predicate -> {
// this is used for LogicalCompatibilityContext
@@ -168,28 +188,18 @@ public class StructInfo {
ExpressionUtils.shuttleExpressionWithLineage(predicate, topPlan), predicate));
});
});
- }
-
- private void initPredicates() {
- // Collect predicate from top plan which not in hyper graph
- this.predicates = Predicates.of();
- Set<Expression> topPlanPredicates = new HashSet<>();
- topPlan.accept(PREDICATE_COLLECTOR, topPlanPredicates);
- topPlanPredicates.forEach(this.predicates::addPredicate);
- predicatesDerive();
+ return true;
}
// derive some useful predicate by predicates
- private void predicatesDerive() {
+ private Pair<SplitPredicate, EquivalenceClass> predicatesDerive(Predicates predicates, Plan originalPlan) {
// construct equivalenceClass according to equals predicates
List<Expression> shuttledExpression = ExpressionUtils.shuttleExpressionWithLineage(
- new ArrayList<>(this.predicates.getPulledUpPredicates()), originalPlan).stream()
+ new ArrayList<>(predicates.getPulledUpPredicates()), originalPlan).stream()
.map(Expression.class::cast)
.collect(Collectors.toList());
SplitPredicate splitPredicate = Predicates.splitPredicates(ExpressionUtils.and(shuttledExpression));
- this.splitPredicate = splitPredicate;
-
- this.equivalenceClass = new EquivalenceClass();
+ EquivalenceClass equivalenceClass = new EquivalenceClass();
for (Expression expression : ExpressionUtils.extractConjunction(splitPredicate.getEqualPredicate())) {
if (expression instanceof Literal) {
continue;
@@ -201,6 +211,7 @@ public class StructInfo {
(SlotReference) equalTo.getArguments().get(1));
}
}
+ return Pair.of(splitPredicate, equivalenceClass);
}
/**
@@ -216,11 +227,39 @@ public class StructInfo {
List<HyperGraph> structInfos = HyperGraph.toStructInfo(planSplitContext.getBottomPlan());
return structInfos.stream()
- .map(hyperGraph -> new StructInfo(originalPlan, planSplitContext.getTopPlan(),
+ .map(hyperGraph -> StructInfo.of(originalPlan, planSplitContext.getTopPlan(),
planSplitContext.getBottomPlan(), hyperGraph))
.collect(Collectors.toList());
}
+ /**
+ * The construct method for init StructInfo
+ */
+ public static StructInfo of(Plan originalPlan, @Nullable Plan topPlan, @Nullable Plan bottomPlan,
+ HyperGraph hyperGraph) {
+ ObjectId originalPlanId = originalPlan.getGroupExpression()
+ .map(GroupExpression::getId).orElseGet(() -> new ObjectId(-1));
+ // if any of topPlan or bottomPlan is null, split the top plan to two parts by join node
+ if (topPlan == null || bottomPlan == null) {
+ PlanSplitContext planSplitContext = new PlanSplitContext(Sets.newHashSet(LogicalJoin.class));
+ originalPlan.accept(PLAN_SPLITTER, planSplitContext);
+ bottomPlan = planSplitContext.getBottomPlan();
+ topPlan = planSplitContext.getTopPlan();
+ }
+ // collect struct info fromGraph
+ ImmutableList.Builder<CatalogRelation> relationBuilder = ImmutableList.builder();
+ Map<RelationId, StructInfoNode> relationIdStructInfoNodeMap = new HashMap<>();
+ Map<Expression, Expression> shuttledHashConjunctsToConjunctsMap = new HashMap<>();
+ Map<ExprId, Expression> namedExprIdAndExprMapping = new HashMap<>();
+ boolean valid = collectStructInfoFromGraph(hyperGraph, topPlan, shuttledHashConjunctsToConjunctsMap,
+ namedExprIdAndExprMapping,
+ relationBuilder,
+ relationIdStructInfoNodeMap);
+ return new StructInfo(originalPlan, originalPlanId, hyperGraph, valid, topPlan, bottomPlan,
+ relationBuilder.build(), relationIdStructInfoNodeMap, null, shuttledHashConjunctsToConjunctsMap,
+ namedExprIdAndExprMapping);
+ }
+
/**
* Build Struct info from group.
* Maybe return multi structInfo when original plan already be rewritten by mv
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeToSlot.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeToSlot.java
index 41f384ac776..1cd56ad1298 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeToSlot.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeToSlot.java
@@ -38,10 +38,14 @@ import java.util.function.BiFunction;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
-/** NormalizeToSlot */
+/**
+ * NormalizeToSlot
+ */
public interface NormalizeToSlot {
- /** NormalizeSlotContext */
+ /**
+ * NormalizeSlotContext
+ */
class NormalizeToSlotContext {
private final Map<Expression, NormalizeToSlotTriplet> normalizeToSlotMap;
@@ -51,11 +55,11 @@ public interface NormalizeToSlot {
/**
* build normalization context by follow step.
- * 1. collect all exists alias by input parameters existsAliases build a reverted map: expr -> alias
- * 2. for all input source expressions, use existsAliasMap to construct triple:
- * origin expr, pushed expr and alias to replace origin expr,
- * see more detail in {@link NormalizeToSlotTriplet}
- * 3. construct a map: original expr -> triple constructed by step 2
+ * 1. collect all exists alias by input parameters existsAliases build a reverted map: expr -> alias
+ * 2. for all input source expressions, use existsAliasMap to construct triple:
+ * origin expr, pushed expr and alias to replace origin expr,
+ * see more detail in {@link NormalizeToSlotTriplet}
+ * 3. construct a map: original expr -> triple constructed by step 2
*/
public static NormalizeToSlotContext buildContext(
Set<Alias> existsAliases, Collection<? extends Expression> sourceExpressions) {
@@ -65,7 +69,6 @@ public interface NormalizeToSlot {
for (Alias existsAlias : existsAliases) {
existsAliasMap.put(existsAlias.child(), existsAlias);
}
-
for (Expression expression : sourceExpressions) {
if (normalizeToSlotMap.containsKey(expression)) {
continue;
@@ -186,7 +189,9 @@ public interface NormalizeToSlot {
}
}
- /** NormalizeToSlotTriplet */
+ /**
+ * NormalizeToSlotTriplet
+ */
class NormalizeToSlotTriplet {
// which expression need to normalized to slot?
// e.g. `a + 1`
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/TreeNode.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/TreeNode.java
index 00ac71eaf24..3519a983fd1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/TreeNode.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/TreeNode.java
@@ -199,23 +199,6 @@ public interface TreeNode<NODE_TYPE extends TreeNode<NODE_TYPE>> {
return false;
}
- /**
- * iterate top down and test predicate if any matched. Top-down traverse implicitly.
- * @param predicate predicate
- * @return the first node which match the predicate
- */
- default TreeNode<NODE_TYPE> firstMatch(Predicate<TreeNode<NODE_TYPE>> predicate) {
- if (predicate.test(this)) {
- return this;
- }
- for (NODE_TYPE child : children()) {
- if (child.anyMatch(predicate)) {
- return child;
- }
- }
- return this;
- }
-
/**
* Collect the nodes that satisfied the predicate.
*/
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalProject.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalProject.java
index 5e7ffc1e815..cdacfe95b66 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalProject.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalProject.java
@@ -61,6 +61,10 @@ public class LogicalProject<CHILD_TYPE extends Plan> extends LogicalUnary<CHILD_
this(projects, ImmutableList.of(), false, true, ImmutableList.of(child));
}
+ public LogicalProject(List<NamedExpression> projects, CHILD_TYPE child, boolean canEliminate) {
+ this(projects, ImmutableList.of(), false, canEliminate, ImmutableList.of(child));
+ }
+
public LogicalProject(List<NamedExpression> projects, List<NamedExpression> excepts,
boolean isDistinct, List<Plan> child) {
this(projects, excepts, isDistinct, true, Optional.empty(), Optional.empty(), child);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java
index 7a2d9fc27d5..fd96ceecb93 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java
@@ -231,7 +231,9 @@ public class ExpressionUtils {
Plan plan,
Set<TableType> targetTypes,
Set<String> tableIdentifiers) {
-
+ if (expressions.isEmpty()) {
+ return ImmutableList.of();
+ }
ExpressionLineageReplacer.ExpressionReplaceContext replaceContext =
new ExpressionLineageReplacer.ExpressionReplaceContext(
expressions.stream().map(Expression.class::cast).collect(Collectors.toList()),
diff --git a/regression-test/data/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.out b/regression-test/data/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.out
index 10c593bd5f0..17104fbd732 100644
--- a/regression-test/data/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.out
+++ b/regression-test/data/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.out
@@ -255,3 +255,9 @@
-- !query29_0_after --
8
+-- !query29_1_before --
+0 178.10 1.20 8
+
+-- !query29_1_after --
+0 178.10 1.20 8
+
diff --git a/regression-test/suites/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.groovy b/regression-test/suites/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.groovy
index cffb031cb17..4d001af4128 100644
--- a/regression-test/suites/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.groovy
+++ b/regression-test/suites/nereids_rules_p0/mv/agg_with_roll_up/aggregate_with_roll_up.groovy
@@ -171,7 +171,7 @@ suite("aggregate_with_roll_up") {
}
}
- def check_rewrite_with_force_analyze = { mv_sql, query_sql, mv_name ->
+ def check_rewrite_but_not_chose = { mv_sql, query_sql, mv_name ->
sql """DROP MATERIALIZED VIEW IF EXISTS ${mv_name}"""
sql"""
@@ -182,16 +182,14 @@ suite("aggregate_with_roll_up") {
AS ${mv_sql}
"""
- sql "analyze table ${mv_name} with sync;"
- sql "analyze table lineitem with sync;"
- sql "analyze table orders with sync;"
- sql "analyze table partsupp with sync;"
-
def job_name = getJobName(db, mv_name);
waitingMTMVTaskFinished(job_name)
explain {
sql("${query_sql}")
- contains("${mv_name}(${mv_name})")
+ check {result ->
+ def splitResult = result.split("MaterializedViewRewriteSuccessButNotChose")
+ splitResult.length == 2 ? splitResult[1].contains(mv_name) : false
+ }
}
}
@@ -436,19 +434,21 @@ suite("aggregate_with_roll_up") {
"o_orderdate, " +
"l_partkey, " +
"l_suppkey"
- def query17_0 = "select t1.l_partkey, t1.l_suppkey, l_shipdate, " +
- "sum(o_totalprice), " +
- "max(o_totalprice), " +
- "min(o_totalprice), " +
- "count(*), " +
- "count(distinct case when o_shippriority > 1 and o_orderkey IN (1, 3) then o_custkey else null end) " +
- "from lineitem t1 " +
- "left join orders on t1.l_orderkey = orders.o_orderkey and t1.l_shipdate = o_orderdate " +
- "where o_orderdate = '2023-12-11' " +
- "group by " +
- "l_shipdate, " +
- "l_partkey, " +
- "l_suppkey"
+ def query17_0 = """
+ select t1.l_partkey, t1.l_suppkey, l_shipdate,
+ sum(o_totalprice),
+ max(o_totalprice),
+ min(o_totalprice),
+ count(*),
+ count(distinct case when o_shippriority > 1 and o_orderkey IN (1, 3) then o_custkey else null end)
+ from lineitem t1
+ left join orders on t1.l_orderkey = orders.o_orderkey and t1.l_shipdate = o_orderdate
+ where o_orderdate = '2023-12-11'
+ group by
+ l_shipdate,
+ l_partkey,
+ l_suppkey;
+ """
order_qt_query17_0_before "${query17_0}"
check_rewrite(mv17_0, query17_0, "mv17_0")
order_qt_query17_0_after "${query17_0}"
@@ -888,34 +888,38 @@ suite("aggregate_with_roll_up") {
// single table
// filter + use roll up dimension
- def mv1_1 = "select o_orderdate, o_shippriority, o_comment, " +
- "sum(o_totalprice) as sum_total, " +
- "max(o_totalprice) as max_total, " +
- "min(o_totalprice) as min_total, " +
- "count(*) as count_all, " +
- "bitmap_union(to_bitmap(case when o_shippriority > 1 and o_orderkey IN (1, 3) then o_custkey else null end)) cnt_1, " +
- "bitmap_union(to_bitmap(case when o_shippriority > 2 and o_orderkey IN (2) then o_custkey else null end)) as cnt_2 " +
- "from orders " +
- "group by " +
- "o_orderdate, " +
- "o_shippriority, " +
- "o_comment "
- def query1_1 = "select o_shippriority, o_comment, " +
- "count(distinct case when o_shippriority > 1 and o_orderkey IN (1, 3) then o_custkey else null end) as cnt_1, " +
- "count(distinct case when O_SHIPPRIORITY > 2 and o_orderkey IN (2) then o_custkey else null end) as cnt_2, " +
- "sum(o_totalprice), " +
- "max(o_totalprice), " +
- "min(o_totalprice), " +
- "count(*) " +
- "from orders " +
- "where o_orderdate = '2023-12-09' " +
- "group by " +
- "o_shippriority, " +
- "o_comment "
+ def mv1_1 = """
+ select o_orderdate, o_shippriority, o_comment,
+ sum(o_totalprice) as sum_total,
+ max(o_totalprice) as max_total,
+ min(o_totalprice) as min_total,
+ count(*) as count_all,
+ bitmap_union(to_bitmap(case when o_shippriority > 1 and o_orderkey IN (1, 3) then o_custkey else null end)) cnt_1,
+ bitmap_union(to_bitmap(case when o_shippriority > 2 and o_orderkey IN (2) then o_custkey else null end)) as cnt_2
+ from orders
+ group by
+ o_orderdate,
+ o_shippriority,
+ o_comment;
+ """
+ def query1_1 = """
+ select o_shippriority, o_comment,
+ count(distinct case when o_shippriority > 1 and o_orderkey IN (1, 3) then o_custkey else null end) as cnt_1,
+ count(distinct case when O_SHIPPRIORITY > 2 and o_orderkey IN (2) then o_custkey else null end) as cnt_2,
+ sum(o_totalprice),
+ max(o_totalprice),
+ min(o_totalprice),
+ count(*)
+ from orders
+ where o_orderdate = '2023-12-09'
+ group by
+ o_shippriority,
+ o_comment;
+ """
order_qt_query1_1_before "${query1_1}"
- // rewrite success, for cbo chose, should force analyze
+ // rewrite success, but not chose
// because data volume is small and mv plan is almost same to query plan
- check_rewrite_with_force_analyze(mv1_1, query1_1, "mv1_1")
+ check_rewrite_but_not_chose(mv1_1, query1_1, "mv1_1")
order_qt_query1_1_after "${query1_1}"
sql """ DROP MATERIALIZED VIEW IF EXISTS mv1_1"""
@@ -947,9 +951,9 @@ suite("aggregate_with_roll_up") {
"o_comment "
order_qt_query2_0_before "${query2_0}"
- // rewrite success, for cbo chose, should force analyze
+ // rewrite success, but not chose
// because data volume is small and mv plan is almost same to query plan
- check_rewrite_with_force_analyze(mv2_0, query2_0, "mv2_0")
+ check_rewrite_but_not_chose(mv2_0, query2_0, "mv2_0")
order_qt_query2_0_after "${query2_0}"
sql """ DROP MATERIALIZED VIEW IF EXISTS mv2_0"""
@@ -1078,8 +1082,8 @@ suite("aggregate_with_roll_up") {
ifnull(o_totalprice, 0) as price_with_no_null
from lineitem
left join orders on l_orderkey = o_orderkey and l_shipdate = o_orderdate
- )
- select
+ )
+ select
count(1) count_all
from
cte_view_1 cte_view
@@ -1090,4 +1094,31 @@ suite("aggregate_with_roll_up") {
check_rewrite(mv29_0, query29_0, "mv29_0")
order_qt_query29_0_after "${query29_0}"
sql """ DROP MATERIALIZED VIEW IF EXISTS mv29_0"""
+
+ // mv and query both are scalar aggregate
+ def mv29_1 = """
+ select
+ sum(o_totalprice) as sum_total,
+ max(o_totalprice) as max_total,
+ min(o_totalprice) as min_total,
+ count(*) as count_all,
+ bitmap_union(to_bitmap(case when o_shippriority > 1 and o_orderkey IN (1, 3) then o_custkey else null end)) cnt_1,
+ bitmap_union(to_bitmap(case when o_shippriority > 2 and o_orderkey IN (2) then o_custkey else null end)) as cnt_2
+ from lineitem
+ left join orders on l_orderkey = o_orderkey and l_shipdate = o_orderdate;
+ """
+ def query29_1 = """
+ select
+ count(distinct case when O_SHIPPRIORITY > 2 and o_orderkey IN (2) then o_custkey else null end) as cnt_2,
+ sum(o_totalprice),
+ min(o_totalprice),
+ count(*)
+ from lineitem
+ left join orders on l_orderkey = o_orderkey and l_shipdate = o_orderdate;
+ """
+
+ order_qt_query29_1_before "${query29_1}"
+ check_rewrite(mv29_1, query29_1, "mv29_1")
+ order_qt_query29_1_after "${query29_1}"
+ sql """ DROP MATERIALIZED VIEW IF EXISTS mv29_1"""
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 01/43: [refactor](close) refactor ispendingfinish logic and close logic to do close more quickly (#30021)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit f66f6b2a82253e256aa78141f0ee74a48295f842
Author: yiguolei <67...@qq.com>
AuthorDate: Fri Jan 19 15:23:27 2024 +0800
[refactor](close) refactor ispendingfinish logic and close logic to do close more quickly (#30021)
---
be/src/exec/data_sink.h | 2 +-
be/src/pipeline/exec/jdbc_table_sink_operator.h | 1 +
be/src/pipeline/exec/olap_table_sink_operator.h | 1 +
be/src/pipeline/exec/olap_table_sink_v2_operator.h | 1 +
be/src/pipeline/exec/operator.h | 2 +-
.../pipeline/exec/partition_sort_sink_operator.cpp | 2 --
be/src/pipeline/exec/result_file_sink_operator.cpp | 6 ++---
be/src/pipeline/exec/result_file_sink_operator.h | 1 +
be/src/pipeline/exec/sort_sink_operator.cpp | 1 -
be/src/pipeline/exec/table_function_operator.cpp | 1 -
be/src/pipeline/pipeline_x/operator.cpp | 14 +++++------
be/src/pipeline/pipeline_x/operator.h | 5 ++++
be/src/runtime/result_writer.h | 2 ++
be/src/runtime/runtime_state.cpp | 18 --------------
be/src/runtime/runtime_state.h | 5 ----
be/src/vec/exec/vpartition_sort_node.cpp | 3 ---
be/src/vec/exec/vsort_node.cpp | 2 --
be/src/vec/exec/vtable_function_node.cpp | 1 -
be/src/vec/sink/async_writer_sink.h | 23 +++++++++++-------
be/src/vec/sink/vresult_file_sink.cpp | 19 ++++++++++-----
be/src/vec/sink/writer/async_result_writer.cpp | 23 +++++++++++-------
be/src/vec/sink/writer/async_result_writer.h | 7 ------
be/src/vec/sink/writer/vjdbc_table_writer.h | 6 ++---
be/src/vec/sink/writer/vodbc_table_writer.h | 6 ++---
be/src/vec/sink/writer/vtablet_writer.cpp | 28 ++++------------------
be/src/vec/sink/writer/vtablet_writer.h | 8 ++-----
26 files changed, 75 insertions(+), 113 deletions(-)
diff --git a/be/src/exec/data_sink.h b/be/src/exec/data_sink.h
index 3bf72ae5450..be6cfe236b7 100644
--- a/be/src/exec/data_sink.h
+++ b/be/src/exec/data_sink.h
@@ -74,7 +74,7 @@ public:
return Status::OK();
}
- virtual bool is_close_done() { return true; }
+ [[nodiscard]] virtual bool is_pending_finish() const { return false; }
// Releases all resources that were allocated in prepare()/send().
// Further send() calls are illegal after calling close().
diff --git a/be/src/pipeline/exec/jdbc_table_sink_operator.h b/be/src/pipeline/exec/jdbc_table_sink_operator.h
index 41348ccaccf..33018f69da5 100644
--- a/be/src/pipeline/exec/jdbc_table_sink_operator.h
+++ b/be/src/pipeline/exec/jdbc_table_sink_operator.h
@@ -58,6 +58,7 @@ public:
private:
friend class JdbcTableSinkLocalState;
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
friend class AsyncWriterSink;
const RowDescriptor& _row_desc;
diff --git a/be/src/pipeline/exec/olap_table_sink_operator.h b/be/src/pipeline/exec/olap_table_sink_operator.h
index 6aa80776a3a..6707ddd86e6 100644
--- a/be/src/pipeline/exec/olap_table_sink_operator.h
+++ b/be/src/pipeline/exec/olap_table_sink_operator.h
@@ -102,6 +102,7 @@ public:
private:
friend class OlapTableSinkLocalState;
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
friend class AsyncWriterSink;
const RowDescriptor& _row_desc;
vectorized::VExprContextSPtrs _output_vexpr_ctxs;
diff --git a/be/src/pipeline/exec/olap_table_sink_v2_operator.h b/be/src/pipeline/exec/olap_table_sink_v2_operator.h
index 1e68f9e98d3..f1b5d6e9061 100644
--- a/be/src/pipeline/exec/olap_table_sink_v2_operator.h
+++ b/be/src/pipeline/exec/olap_table_sink_v2_operator.h
@@ -104,6 +104,7 @@ public:
private:
friend class OlapTableSinkV2LocalState;
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
friend class AsyncWriterSink;
const RowDescriptor& _row_desc;
vectorized::VExprContextSPtrs _output_vexpr_ctxs;
diff --git a/be/src/pipeline/exec/operator.h b/be/src/pipeline/exec/operator.h
index 80184374b77..cd5fba5fee3 100644
--- a/be/src/pipeline/exec/operator.h
+++ b/be/src/pipeline/exec/operator.h
@@ -297,7 +297,7 @@ public:
return _sink->try_close(state, state->query_status());
}
- [[nodiscard]] bool is_pending_finish() const override { return !_sink->is_close_done(); }
+ [[nodiscard]] bool is_pending_finish() const override { return _sink->is_pending_finish(); }
Status close(RuntimeState* state) override {
if (is_closed()) {
diff --git a/be/src/pipeline/exec/partition_sort_sink_operator.cpp b/be/src/pipeline/exec/partition_sort_sink_operator.cpp
index 14d917d62e3..c09a6a90b95 100644
--- a/be/src/pipeline/exec/partition_sort_sink_operator.cpp
+++ b/be/src/pipeline/exec/partition_sort_sink_operator.cpp
@@ -120,8 +120,6 @@ Status PartitionSortSinkOperatorX::sink(RuntimeState* state, vectorized::Block*
RETURN_IF_ERROR(
_split_block_by_partition(input_block, state->batch_size(), local_state));
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(
- state->check_query_state("VPartitionSortNode, while split input block."));
input_block->clear_column_data();
}
}
diff --git a/be/src/pipeline/exec/result_file_sink_operator.cpp b/be/src/pipeline/exec/result_file_sink_operator.cpp
index 2b095748b15..71a2d539c95 100644
--- a/be/src/pipeline/exec/result_file_sink_operator.cpp
+++ b/be/src/pipeline/exec/result_file_sink_operator.cpp
@@ -173,9 +173,9 @@ Status ResultFileSinkLocalState::close(RuntimeState* state, Status exec_status)
}
Status final_status = exec_status;
- // close the writer
- if (_writer && _writer->need_normal_close()) {
- Status st = _writer->close();
+ // For pipelinex engine, the writer is closed in async thread process_block
+ if (_writer) {
+ Status st = _writer->get_writer_status();
if (!st.ok() && exec_status.ok()) {
// close file writer failed, should return this error to client
final_status = st;
diff --git a/be/src/pipeline/exec/result_file_sink_operator.h b/be/src/pipeline/exec/result_file_sink_operator.h
index 57e1e8c9147..e196401991a 100644
--- a/be/src/pipeline/exec/result_file_sink_operator.h
+++ b/be/src/pipeline/exec/result_file_sink_operator.h
@@ -106,6 +106,7 @@ public:
private:
friend class ResultFileSinkLocalState;
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
friend class AsyncWriterSink;
const RowDescriptor& _row_desc;
diff --git a/be/src/pipeline/exec/sort_sink_operator.cpp b/be/src/pipeline/exec/sort_sink_operator.cpp
index e2c851f758f..56a81422484 100644
--- a/be/src/pipeline/exec/sort_sink_operator.cpp
+++ b/be/src/pipeline/exec/sort_sink_operator.cpp
@@ -150,7 +150,6 @@ Status SortSinkOperatorX::sink(doris::RuntimeState* state, vectorized::Block* in
if (in_block->rows() > 0) {
RETURN_IF_ERROR(local_state._shared_state->sorter->append_block(in_block));
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(state->check_query_state("vsort, while sorting input."));
// update runtime predicate
if (_use_topn_opt) {
diff --git a/be/src/pipeline/exec/table_function_operator.cpp b/be/src/pipeline/exec/table_function_operator.cpp
index cf14b3ec5e3..960fccff2b4 100644
--- a/be/src/pipeline/exec/table_function_operator.cpp
+++ b/be/src/pipeline/exec/table_function_operator.cpp
@@ -159,7 +159,6 @@ Status TableFunctionLocalState::get_expanded_block(RuntimeState* state,
while (columns[p._child_slots.size()]->size() < state->batch_size()) {
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(state->check_query_state("VTableFunctionNode, while getting next batch."));
if (_child_block->rows() == 0) {
break;
diff --git a/be/src/pipeline/pipeline_x/operator.cpp b/be/src/pipeline/pipeline_x/operator.cpp
index e38e7b39d95..bbb7473f868 100644
--- a/be/src/pipeline/pipeline_x/operator.cpp
+++ b/be/src/pipeline/pipeline_x/operator.cpp
@@ -497,6 +497,7 @@ Status StatefulOperatorX<LocalStateType>::get_block(RuntimeState* state, vectori
}
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
Status AsyncWriterSink<Writer, Parent>::init(RuntimeState* state, LocalSinkStateInfo& info) {
RETURN_IF_ERROR(Base::init(state, info));
_output_vexpr_ctxs.resize(_parent->cast<Parent>()._output_vexpr_ctxs.size());
@@ -516,6 +517,7 @@ Status AsyncWriterSink<Writer, Parent>::init(RuntimeState* state, LocalSinkState
}
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
Status AsyncWriterSink<Writer, Parent>::open(RuntimeState* state) {
RETURN_IF_ERROR(Base::open(state));
_writer->start_writer(state, _profile);
@@ -523,12 +525,14 @@ Status AsyncWriterSink<Writer, Parent>::open(RuntimeState* state) {
}
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
Status AsyncWriterSink<Writer, Parent>::sink(RuntimeState* state, vectorized::Block* block,
SourceState source_state) {
return _writer->sink(block, source_state == SourceState::FINISHED);
}
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
Status AsyncWriterSink<Writer, Parent>::close(RuntimeState* state, Status exec_status) {
if (_closed) {
return Status::OK();
@@ -537,19 +541,13 @@ Status AsyncWriterSink<Writer, Parent>::close(RuntimeState* state, Status exec_s
COUNTER_SET(_wait_for_finish_dependency_timer, _finish_dependency->watcher_elapse_time());
// if the init failed, the _writer may be nullptr. so here need check
if (_writer) {
- if (_writer->need_normal_close()) {
- if (exec_status.ok() && !state->is_cancelled()) {
- RETURN_IF_ERROR(_writer->commit_trans());
- }
- RETURN_IF_ERROR(_writer->close(exec_status));
- } else {
- RETURN_IF_ERROR(_writer->get_writer_status());
- }
+ RETURN_IF_ERROR(_writer->get_writer_status());
}
return Base::close(state, exec_status);
}
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
Status AsyncWriterSink<Writer, Parent>::try_close(RuntimeState* state, Status exec_status) {
if (state->is_cancelled() || !exec_status.ok()) {
_writer->force_close(!exec_status.ok() ? exec_status : Status::Cancelled("Cancelled"));
diff --git a/be/src/pipeline/pipeline_x/operator.h b/be/src/pipeline/pipeline_x/operator.h
index d46dc859b0c..ca1b224c5c5 100644
--- a/be/src/pipeline/pipeline_x/operator.h
+++ b/be/src/pipeline/pipeline_x/operator.h
@@ -22,6 +22,9 @@
#include "pipeline/pipeline_x/dependency.h"
#include "pipeline/pipeline_x/local_exchange/local_exchanger.h"
+namespace doris::vectorized {
+class AsyncResultWriter;
+}
namespace doris::pipeline {
struct LocalExchangeSinkDependency;
@@ -569,6 +572,7 @@ public:
protected:
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
friend class AsyncWriterSink;
// _operator_id : the current Operator's ID, which is not visible to the user.
// _node_id : the plan node ID corresponding to the Operator, which is visible on the profile.
@@ -680,6 +684,7 @@ public:
};
template <typename Writer, typename Parent>
+ requires(std::is_base_of_v<vectorized::AsyncResultWriter, Writer>)
class AsyncWriterSink : public PipelineXSinkLocalState<FakeDependency> {
public:
using Base = PipelineXSinkLocalState<FakeDependency>;
diff --git a/be/src/runtime/result_writer.h b/be/src/runtime/result_writer.h
index f65f06399b8..5c49954ef2f 100644
--- a/be/src/runtime/result_writer.h
+++ b/be/src/runtime/result_writer.h
@@ -38,6 +38,8 @@ public:
virtual Status init(RuntimeState* state) = 0;
+ virtual Status finish(RuntimeState* state) { return Status::OK(); }
+
virtual Status close(Status s = Status::OK()) = 0;
[[nodiscard]] virtual int64_t get_written_rows() const { return _written_rows; }
diff --git a/be/src/runtime/runtime_state.cpp b/be/src/runtime/runtime_state.cpp
index 1a6f8a2661f..d84b86f2290 100644
--- a/be/src/runtime/runtime_state.cpp
+++ b/be/src/runtime/runtime_state.cpp
@@ -365,24 +365,6 @@ Status RuntimeState::set_mem_limit_exceeded(const std::string& msg) {
return _process_status;
}
-Status RuntimeState::check_query_state(const std::string& msg) {
- // TODO: it would be nice if this also checked for cancellation, but doing so breaks
- // cases where we use Status::Cancelled("Cancelled") to indicate that the limit was reached.
- //
- // If the thread MemTrackerLimiter exceeds the limit, an error status is returned.
- // Usually used after SCOPED_ATTACH_TASK, during query execution.
- if (is_thread_context_init() && thread_context()->thread_mem_tracker()->limit_exceeded() &&
- !config::enable_query_memory_overcommit) {
- auto failed_msg =
- fmt::format("{}, {}", msg,
- thread_context()->thread_mem_tracker()->tracker_limit_exceeded_str());
- thread_context()->thread_mem_tracker()->print_log_usage(failed_msg);
- log_error(failed_msg);
- return Status::MemoryLimitExceeded(failed_msg);
- }
- return query_status();
-}
-
const int64_t MAX_ERROR_NUM = 50;
Status RuntimeState::create_error_log_file() {
diff --git a/be/src/runtime/runtime_state.h b/be/src/runtime/runtime_state.h
index ede451cd92a..91443ef9492 100644
--- a/be/src/runtime/runtime_state.h
+++ b/be/src/runtime/runtime_state.h
@@ -236,11 +236,6 @@ public:
// generic "Memory limit exceeded" error.
Status set_mem_limit_exceeded(const std::string& msg = "Memory limit exceeded");
- // Returns a non-OK status if query execution should stop (e.g., the query was cancelled
- // or a mem limit was exceeded). Exec nodes should check this periodically so execution
- // doesn't continue if the query terminates abnormally.
- Status check_query_state(const std::string& msg);
-
std::vector<std::string>& output_files() { return _output_files; }
void set_import_label(const std::string& import_label) { _import_label = import_label; }
diff --git a/be/src/vec/exec/vpartition_sort_node.cpp b/be/src/vec/exec/vpartition_sort_node.cpp
index 6a7ebcffd1e..95c0abd72a8 100644
--- a/be/src/vec/exec/vpartition_sort_node.cpp
+++ b/be/src/vec/exec/vpartition_sort_node.cpp
@@ -168,8 +168,6 @@ Status VPartitionSortNode::sink(RuntimeState* state, vectorized::Block* input_bl
} else {
RETURN_IF_ERROR(_split_block_by_partition(input_block, state->batch_size()));
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(
- state->check_query_state("VPartitionSortNode, while split input block."));
input_block->clear_column_data();
}
}
@@ -237,7 +235,6 @@ Status VPartitionSortNode::alloc_resource(RuntimeState* state) {
RETURN_IF_ERROR(VExpr::open(_partition_expr_ctxs, state));
RETURN_IF_ERROR(_vsort_exec_exprs.open(state));
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(state->check_query_state("VPartitionSortNode, while open."));
return Status::OK();
}
diff --git a/be/src/vec/exec/vsort_node.cpp b/be/src/vec/exec/vsort_node.cpp
index 189c628ef0b..e313e3f74ac 100644
--- a/be/src/vec/exec/vsort_node.cpp
+++ b/be/src/vec/exec/vsort_node.cpp
@@ -130,7 +130,6 @@ Status VSortNode::alloc_resource(doris::RuntimeState* state) {
RETURN_IF_ERROR(ExecNode::alloc_resource(state));
RETURN_IF_ERROR(_vsort_exec_exprs.open(state));
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(state->check_query_state("vsort, while open."));
return Status::OK();
}
@@ -140,7 +139,6 @@ Status VSortNode::sink(RuntimeState* state, vectorized::Block* input_block, bool
if (input_block->rows() > 0) {
RETURN_IF_ERROR(_sorter->append_block(input_block));
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(state->check_query_state("vsort, while sorting input."));
// update runtime predicate
if (_use_topn_opt) {
diff --git a/be/src/vec/exec/vtable_function_node.cpp b/be/src/vec/exec/vtable_function_node.cpp
index 8affd4cbe7e..0c35fae806e 100644
--- a/be/src/vec/exec/vtable_function_node.cpp
+++ b/be/src/vec/exec/vtable_function_node.cpp
@@ -170,7 +170,6 @@ Status VTableFunctionNode::_get_expanded_block(RuntimeState* state, Block* outpu
while (columns[_child_slots.size()]->size() < state->batch_size()) {
RETURN_IF_CANCELLED(state);
- RETURN_IF_ERROR(state->check_query_state("VTableFunctionNode, while getting next batch."));
if (_child_block->rows() == 0) {
break;
diff --git a/be/src/vec/sink/async_writer_sink.h b/be/src/vec/sink/async_writer_sink.h
index 600eb609281..1260382d6fa 100644
--- a/be/src/vec/sink/async_writer_sink.h
+++ b/be/src/vec/sink/async_writer_sink.h
@@ -42,6 +42,7 @@ namespace vectorized {
class Block;
template <typename Writer, const char* Name>
+ requires(std::is_base_of_v<AsyncResultWriter, Writer>)
class AsyncWriterSink : public DataSink {
public:
AsyncWriterSink(const RowDescriptor& row_desc, const std::vector<TExpr>& t_exprs)
@@ -78,13 +79,21 @@ public:
return Status::OK();
}
+ // Non-pipeline engine will call this api to send data to sink destination
Status send(RuntimeState* state, vectorized::Block* block, bool eos = false) override {
SCOPED_TIMER(_exec_timer);
COUNTER_UPDATE(_blocks_sent_counter, 1);
COUNTER_UPDATE(_output_rows_counter, block->rows());
- return _writer->write(*block);
+ Status st = _writer->write(*block);
+ // Should also check !state->is_cancelled()???, do not know which scenario?
+ if (st.ok() && eos) {
+ // If this is the last block, then call finish to flush the buffer or commit transctions.
+ st = _writer->finish(state);
+ }
+ return st;
}
+ // Pipeline engine will call this api to send data to destination. This is an async API.
Status sink(RuntimeState* state, vectorized::Block* block, bool eos = false) override {
return _writer->sink(block, eos);
}
@@ -94,13 +103,11 @@ public:
Status close(RuntimeState* state, Status exec_status) override {
// if the init failed, the _writer may be nullptr. so here need check
if (_writer) {
- if (_writer->need_normal_close()) {
- if (exec_status.ok() && !state->is_cancelled()) {
- RETURN_IF_ERROR(_writer->commit_trans());
- }
- RETURN_IF_ERROR(_writer->close(exec_status));
- } else {
+ // For pipeline engine, the writer is always closed in async thread process_block
+ if (state->enable_pipeline_exec()) {
RETURN_IF_ERROR(_writer->get_writer_status());
+ } else {
+ RETURN_IF_ERROR(_writer->close(exec_status));
}
}
return DataSink::close(state, exec_status);
@@ -113,7 +120,7 @@ public:
return Status::OK();
}
- bool is_close_done() override { return !_writer->is_pending_finish(); }
+ [[nodiscard]] bool is_pending_finish() const override { return _writer->is_pending_finish(); }
protected:
const std::vector<TExpr>& _t_output_expr;
diff --git a/be/src/vec/sink/vresult_file_sink.cpp b/be/src/vec/sink/vresult_file_sink.cpp
index 02d77fa6d42..08dd881bf4b 100644
--- a/be/src/vec/sink/vresult_file_sink.cpp
+++ b/be/src/vec/sink/vresult_file_sink.cpp
@@ -113,14 +113,21 @@ Status VResultFileSink::close(RuntimeState* state, Status exec_status) {
}
Status final_status = exec_status;
- // close the writer
- if (_writer && _writer->need_normal_close()) {
- Status st = _writer->close();
- if (!st.ok() && exec_status.ok()) {
- // close file writer failed, should return this error to client
- final_status = st;
+ Status writer_st = Status::OK();
+ if (_writer) {
+ // For pipeline engine, the writer is always closed in async thread process_block
+ if (state->enable_pipeline_exec()) {
+ writer_st = _writer->get_writer_status();
+ } else {
+ writer_st = _writer->close(exec_status);
}
}
+
+ if (!writer_st.ok() && exec_status.ok()) {
+ // close file writer failed, should return this error to client
+ final_status = writer_st;
+ }
+
if (_is_top_sink) {
// close sender, this is normal path end
if (_sender) {
diff --git a/be/src/vec/sink/writer/async_result_writer.cpp b/be/src/vec/sink/writer/async_result_writer.cpp
index 0ce3196e3a3..35d94fe3c47 100644
--- a/be/src/vec/sink/writer/async_result_writer.cpp
+++ b/be/src/vec/sink/writer/async_result_writer.cpp
@@ -125,15 +125,22 @@ void AsyncResultWriter::process_block(RuntimeState* state, RuntimeProfile* profi
}
}
- // if not in transaction or status is in error or force close we can do close in
- // async IO thread
- if (!_writer_status.ok() || !in_transaction()) {
- std::lock_guard l(_m);
- // Using lock to make sure the writer status is not modified
- // There is a unique ptr err_msg in Status, if it is modified, the unique ptr
- // maybe released. And it will core because use after free.
+ // If the last block is sent successfuly, then call finish to clear the buffer or commit
+ // transactions.
+ // Using lock to make sure the writer status is not modified
+ // There is a unique ptr err_msg in Status, if it is modified, the unique ptr
+ // maybe released. And it will core because use after free.
+ std::lock_guard l(_m);
+ if (_writer_status.ok() && _eos) {
+ _writer_status = finish(state);
+ }
+
+ if (_writer_status.ok()) {
_writer_status = close(_writer_status);
- _need_normal_close = false;
+ } else {
+ // If it is already failed before, then not update the write status so that we could get
+ // the real reason.
+ static_cast<void>(close(_writer_status));
}
_writer_thread_closed = true;
if (_finish_dependency) {
diff --git a/be/src/vec/sink/writer/async_result_writer.h b/be/src/vec/sink/writer/async_result_writer.h
index ced123267c5..5fbcca98af3 100644
--- a/be/src/vec/sink/writer/async_result_writer.h
+++ b/be/src/vec/sink/writer/async_result_writer.h
@@ -61,12 +61,6 @@ public:
void force_close(Status s);
- virtual bool in_transaction() { return false; }
-
- virtual Status commit_trans() { return Status::OK(); }
-
- bool need_normal_close() const { return _need_normal_close; }
-
Status init(RuntimeState* state) override { return Status::OK(); }
virtual Status open(RuntimeState* state, RuntimeProfile* profile) = 0;
@@ -110,7 +104,6 @@ private:
std::deque<std::unique_ptr<Block>> _data_queue;
Status _writer_status = Status::OK();
bool _eos = false;
- bool _need_normal_close = true;
bool _writer_thread_closed = false;
// Used by pipelineX
diff --git a/be/src/vec/sink/writer/vjdbc_table_writer.h b/be/src/vec/sink/writer/vjdbc_table_writer.h
index 735c023fce5..a683259c992 100644
--- a/be/src/vec/sink/writer/vjdbc_table_writer.h
+++ b/be/src/vec/sink/writer/vjdbc_table_writer.h
@@ -46,11 +46,9 @@ public:
Status write(vectorized::Block& block) override;
- Status close(Status s) override { return JdbcConnector::close(s); }
-
- bool in_transaction() override { return TableConnector::_is_in_transaction; }
+ Status finish(RuntimeState* state) override { return JdbcConnector::finish_trans(); }
- Status commit_trans() override { return JdbcConnector::finish_trans(); }
+ Status close(Status s) override { return JdbcConnector::close(s); }
private:
JdbcConnectorParam _param;
diff --git a/be/src/vec/sink/writer/vodbc_table_writer.h b/be/src/vec/sink/writer/vodbc_table_writer.h
index a28947355e7..687b5106a8b 100644
--- a/be/src/vec/sink/writer/vodbc_table_writer.h
+++ b/be/src/vec/sink/writer/vodbc_table_writer.h
@@ -46,11 +46,9 @@ public:
Status write(vectorized::Block& block) override;
- Status close(Status s) override { return ODBCConnector::close(s); }
-
- bool in_transaction() override { return TableConnector::_is_in_transaction; }
+ Status finish(RuntimeState* state) override { return ODBCConnector::finish_trans(); }
- Status commit_trans() override { return ODBCConnector::finish_trans(); }
+ Status close(Status s) override { return ODBCConnector::close(s); }
};
} // namespace vectorized
} // namespace doris
\ No newline at end of file
diff --git a/be/src/vec/sink/writer/vtablet_writer.cpp b/be/src/vec/sink/writer/vtablet_writer.cpp
index 7c51b80a015..7af7b115c43 100644
--- a/be/src/vec/sink/writer/vtablet_writer.cpp
+++ b/be/src/vec/sink/writer/vtablet_writer.cpp
@@ -865,10 +865,6 @@ void VNodeChannel::cancel(const std::string& cancel_msg) {
static_cast<void>(request->release_id());
}
-bool VNodeChannel::is_send_data_rpc_done() const {
- return _add_batches_finished || _cancelled;
-}
-
Status VNodeChannel::close_wait(RuntimeState* state) {
DBUG_EXECUTE_IF("VNodeChannel.close_wait_full_gc", { MemInfo::process_full_gc(); });
SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
@@ -891,7 +887,8 @@ Status VNodeChannel::close_wait(RuntimeState* state) {
}
// waiting for finished, it may take a long time, so we couldn't set a timeout
- // In pipeline, is_close_done() is false at this time, will not block.
+ // For pipeline engine, the close is called in async writer's process block method,
+ // so that it will not block pipeline thread.
while (!_add_batches_finished && !_cancelled && !state->is_cancelled()) {
bthread_usleep(1000);
}
@@ -1358,7 +1355,7 @@ Status VTabletWriter::_send_new_partition_batch() {
return Status::OK();
}
-Status VTabletWriter::try_close(RuntimeState* state, Status exec_status) {
+void VTabletWriter::_do_try_close(RuntimeState* state, const Status& exec_status) {
SCOPED_TIMER(_close_timer);
Status status = exec_status;
@@ -1400,23 +1397,6 @@ Status VTabletWriter::try_close(RuntimeState* state, Status exec_status) {
_close_status = status;
_close_wait = true;
}
-
- return Status::OK();
-}
-
-bool VTabletWriter::is_close_done() {
- // Only after try_close, need to wait rpc end.
- if (!_close_wait) {
- return true;
- }
- bool close_done = true;
- for (const auto& index_channel : _channels) {
- index_channel->for_each_node_channel(
- [&close_done](const std::shared_ptr<VNodeChannel>& ch) {
- close_done &= ch->is_send_data_rpc_done();
- });
- }
- return close_done;
}
Status VTabletWriter::close(Status exec_status) {
@@ -1431,7 +1411,7 @@ Status VTabletWriter::close(Status exec_status) {
SCOPED_TIMER(_profile->total_time_counter());
// will make the last batch of request-> close_wait will wait this finished.
- static_cast<void>(try_close(_state, exec_status));
+ _do_try_close(_state, exec_status);
// If _close_status is not ok, all nodes have been canceled in try_close.
if (_close_status.ok()) {
diff --git a/be/src/vec/sink/writer/vtablet_writer.h b/be/src/vec/sink/writer/vtablet_writer.h
index 58ddbfd8869..cd2eafb1f24 100644
--- a/be/src/vec/sink/writer/vtablet_writer.h
+++ b/be/src/vec/sink/writer/vtablet_writer.h
@@ -259,8 +259,6 @@ public:
// 2. just cancel()
void mark_close();
- bool is_send_data_rpc_done() const;
-
bool is_closed() const { return _is_closed; }
bool is_cancelled() const { return _cancelled; }
std::string get_cancel_msg() {
@@ -527,15 +525,11 @@ public:
Status open(RuntimeState* state, RuntimeProfile* profile) override;
- Status try_close(RuntimeState* state, Status exec_status);
-
// the consumer func of sending pending batches in every NodeChannel.
// use polling & NodeChannel::try_send_and_fetch_status() to achieve nonblocking sending.
// only focus on pending batches and channel status, the internal errors of NodeChannels will be handled by the producer
void _send_batch_process();
- bool is_close_done();
-
Status on_partitions_created(TCreatePartitionResult* result);
Status _send_new_partition_batch();
@@ -562,6 +556,8 @@ private:
Status _incremental_open_node_channel(const std::vector<TOlapTablePartition>& partitions);
+ void _do_try_close(RuntimeState* state, const Status& exec_status);
+
TDataSink _t_sink;
std::shared_ptr<MemTracker> _mem_tracker;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 38/43: [Feature](executor)Workload Group support Non-Pipeline Execution (#30164)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 9e0c518aaf4f61453b1bf51ec1344f51d76cc0ce
Author: wangbo <wa...@apache.org>
AuthorDate: Mon Jan 22 20:25:28 2024 +0800
[Feature](executor)Workload Group support Non-Pipeline Execution (#30164)
---
be/src/agent/workload_group_listener.cpp | 6 ++-
be/src/common/config.cpp | 2 +-
be/src/pipeline/pipeline_fragment_context.cpp | 7 +--
.../pipeline_x/pipeline_x_fragment_context.cpp | 5 +-
be/src/runtime/fragment_mgr.cpp | 61 +++++++++-------------
be/src/runtime/query_context.cpp | 25 +++++++++
be/src/runtime/query_context.h | 13 +++--
be/src/runtime/task_group/task_group_manager.cpp | 57 ++++++++++++++++----
be/src/runtime/task_group/task_group_manager.h | 9 ++--
.../workload_sched_policy_mgr.cpp | 1 -
be/src/vec/exec/scan/scanner_context.h | 2 +-
.../main/java/org/apache/doris/qe/Coordinator.java | 3 ++
.../java/org/apache/doris/qe/StmtExecutor.java | 2 +-
gensrc/thrift/PaloInternalService.thrift | 19 ++++---
14 files changed, 135 insertions(+), 77 deletions(-)
diff --git a/be/src/agent/workload_group_listener.cpp b/be/src/agent/workload_group_listener.cpp
index 6ea7c28669c..237d6c77274 100644
--- a/be/src/agent/workload_group_listener.cpp
+++ b/be/src/agent/workload_group_listener.cpp
@@ -26,6 +26,7 @@ namespace doris {
void WorkloadGroupListener::handle_topic_info(const std::vector<TopicInfo>& topic_info_list) {
std::set<uint64_t> current_wg_ids;
+ bool is_set_cgroup_path = config::doris_cgroup_cpu_path != "";
for (const TopicInfo& topic_info : topic_info_list) {
if (!topic_info.__isset.workload_group_info) {
continue;
@@ -52,7 +53,7 @@ void WorkloadGroupListener::handle_topic_info(const std::vector<TopicInfo>& topi
// 4 create and update task scheduler
Status ret2 = _exec_env->task_group_manager()->upsert_cg_task_scheduler(&task_group_info,
_exec_env);
- if (!ret2.ok()) {
+ if (is_set_cgroup_path && !ret2.ok()) {
LOG(INFO) << "upsert task sche failed, tg_id=" << task_group_info.id
<< ", reason=" << ret2.to_string();
}
@@ -63,7 +64,8 @@ void WorkloadGroupListener::handle_topic_info(const std::vector<TopicInfo>& topi
<< ", cgroup cpu_shares=" << task_group_info.cgroup_cpu_shares
<< ", cgroup cpu_hard_limit=" << task_group_info.cgroup_cpu_hard_limit
<< ", enable_cgroup_cpu_soft_limit="
- << (config::enable_cgroup_cpu_soft_limit ? "true" : "false");
+ << (config::enable_cgroup_cpu_soft_limit ? "true" : "false")
+ << ", is set cgroup path=" << (is_set_cgroup_path ? "true" : "flase");
}
_exec_env->task_group_manager()->delete_task_group_by_ids(current_wg_ids);
diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index 174572c5c66..894ea80d6d1 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -1137,7 +1137,7 @@ DEFINE_Bool(enable_flush_file_cache_async, "true");
// cgroup
DEFINE_mString(doris_cgroup_cpu_path, "");
-DEFINE_mBool(enable_cgroup_cpu_soft_limit, "false");
+DEFINE_mBool(enable_cgroup_cpu_soft_limit, "true");
DEFINE_Bool(ignore_always_true_predicate_for_segment, "true");
diff --git a/be/src/pipeline/pipeline_fragment_context.cpp b/be/src/pipeline/pipeline_fragment_context.cpp
index 538a2ce1bdb..909039b23fb 100644
--- a/be/src/pipeline/pipeline_fragment_context.cpp
+++ b/be/src/pipeline/pipeline_fragment_context.cpp
@@ -718,12 +718,7 @@ Status PipelineFragmentContext::submit() {
int submit_tasks = 0;
Status st;
- auto* scheduler = _exec_env->pipeline_task_scheduler();
- if (_query_ctx->get_task_scheduler()) {
- scheduler = _query_ctx->get_task_scheduler();
- } else if (_task_group_entity && _query_ctx->use_task_group_for_cpu_limit.load()) {
- scheduler = _exec_env->pipeline_task_group_scheduler();
- }
+ auto* scheduler = _query_ctx->get_pipe_exec_scheduler();
for (auto& task : _tasks) {
st = scheduler->schedule_task(task.get());
if (!st) {
diff --git a/be/src/pipeline/pipeline_x/pipeline_x_fragment_context.cpp b/be/src/pipeline/pipeline_x/pipeline_x_fragment_context.cpp
index a44db667450..4a16b97b2f3 100644
--- a/be/src/pipeline/pipeline_x/pipeline_x_fragment_context.cpp
+++ b/be/src/pipeline/pipeline_x/pipeline_x_fragment_context.cpp
@@ -1219,10 +1219,7 @@ Status PipelineXFragmentContext::submit() {
int submit_tasks = 0;
Status st;
- auto* scheduler = _exec_env->pipeline_task_scheduler();
- if (_task_group_entity) {
- scheduler = _exec_env->pipeline_task_group_scheduler();
- }
+ auto* scheduler = _query_ctx->get_pipe_exec_scheduler();
for (auto& task : _tasks) {
for (auto& t : task) {
st = scheduler->schedule_task(t.get());
diff --git a/be/src/runtime/fragment_mgr.cpp b/be/src/runtime/fragment_mgr.cpp
index 0fbaacb4fa2..a76c7687f02 100644
--- a/be/src/runtime/fragment_mgr.cpp
+++ b/be/src/runtime/fragment_mgr.cpp
@@ -677,41 +677,27 @@ Status FragmentMgr::_get_query_ctx(const Params& params, TUniqueId query_id, boo
query_ctx->register_memory_statistics();
query_ctx->register_cpu_statistics();
+ bool is_pipeline = false;
if constexpr (std::is_same_v<TPipelineFragmentParams, Params>) {
- if (params.__isset.workload_groups && !params.workload_groups.empty()) {
- uint64_t tg_id = params.workload_groups[0].id;
- auto* tg_mgr = _exec_env->task_group_manager();
- if (auto task_group_ptr = tg_mgr->get_task_group_by_id(tg_id)) {
- task_group_ptr->add_mem_tracker_limiter(query_ctx->query_mem_tracker);
- // set task group to queryctx for memory tracker can be removed, see QueryContext's destructor
- query_ctx->set_task_group(task_group_ptr);
- stringstream ss;
- ss << "Query/load id: " << print_id(query_ctx->query_id())
- << ", use task group:" << task_group_ptr->debug_string()
- << ", enable cpu hard limit:"
- << (tg_mgr->enable_cpu_hard_limit() ? "true" : "false");
- bool ret = false;
- if (tg_mgr->enable_cgroup()) {
- ret = tg_mgr->set_cg_task_sche_for_query_ctx(tg_id, query_ctx.get());
- if (ret) {
- ss << ", use cgroup for cpu limit.";
- } else {
- ss << ", not found cgroup sche, no limit for cpu.";
- }
- } else {
- ss << ", use doris sche for cpu limit.";
- query_ctx->use_task_group_for_cpu_limit.store(true);
- }
- LOG(INFO) << ss.str();
- _exec_env->runtime_query_statistics_mgr()->set_workload_group_id(
- print_id(query_id), tg_id);
- } else {
- VLOG_DEBUG << "Query/load id: " << print_id(query_ctx->query_id())
- << " no task group found, does not use task group.";
- }
- } else {
- VLOG_DEBUG << "Query/load id: " << print_id(query_ctx->query_id())
- << " does not use task group.";
+ is_pipeline = true;
+ }
+
+ if (params.__isset.workload_groups && !params.workload_groups.empty()) {
+ uint64_t tg_id = params.workload_groups[0].id;
+ auto* tg_mgr = _exec_env->task_group_manager();
+ if (auto task_group_ptr = tg_mgr->get_task_group_by_id(tg_id)) {
+ task_group_ptr->add_mem_tracker_limiter(query_ctx->query_mem_tracker);
+ // set task group to queryctx for memory tracker can be removed, see QueryContext's destructor
+ query_ctx->set_task_group(task_group_ptr);
+ _exec_env->runtime_query_statistics_mgr()->set_workload_group_id(print_id(query_id),
+ tg_id);
+ query_ctx->set_query_scheduler(tg_id);
+
+ LOG(INFO) << "Query/load id: " << print_id(query_ctx->query_id())
+ << ", use task group: " << task_group_ptr->debug_string()
+ << ", is pipeline: " << ((int)is_pipeline)
+ << ", enable cgroup soft limit: "
+ << ((int)config::enable_cgroup_cpu_soft_limit);
}
}
@@ -795,7 +781,12 @@ Status FragmentMgr::exec_plan_fragment(const TExecPlanFragmentParams& params,
std::make_pair(params.params.fragment_instance_id, fragment_executor));
_cv.notify_all();
}
- auto st = _thread_pool->submit_func(
+
+ auto* current_thread_pool = query_ctx->get_non_pipe_exec_thread_pool();
+ if (!current_thread_pool) {
+ current_thread_pool = _thread_pool.get();
+ }
+ auto st = current_thread_pool->submit_func(
[this, fragment_executor, cb] { _exec_actual(fragment_executor, cb); });
if (!st.ok()) {
{
diff --git a/be/src/runtime/query_context.cpp b/be/src/runtime/query_context.cpp
index fffb5ad57a9..a70bf6695ac 100644
--- a/be/src/runtime/query_context.cpp
+++ b/be/src/runtime/query_context.cpp
@@ -20,6 +20,7 @@
#include "pipeline/pipeline_fragment_context.h"
#include "pipeline/pipeline_x/dependency.h"
#include "runtime/runtime_query_statistics_mgr.h"
+#include "runtime/task_group/task_group_manager.h"
namespace doris {
@@ -152,4 +153,28 @@ void QueryContext::register_cpu_statistics() {
}
}
+void QueryContext::set_query_scheduler(uint64_t tg_id) {
+ auto* tg_mgr = _exec_env->task_group_manager();
+ tg_mgr->get_query_scheduler(tg_id, &_task_scheduler, &_scan_task_scheduler,
+ &_non_pipe_thread_pool);
+}
+
+doris::pipeline::TaskScheduler* QueryContext::get_pipe_exec_scheduler() {
+ if (!config::enable_cgroup_cpu_soft_limit) {
+ return _exec_env->pipeline_task_group_scheduler();
+ } else if (_task_scheduler) {
+ return _task_scheduler;
+ } else {
+ return _exec_env->pipeline_task_scheduler();
+ }
+}
+
+ThreadPool* QueryContext::get_non_pipe_exec_thread_pool() {
+ if (_task_group) {
+ return _non_pipe_thread_pool;
+ } else {
+ return nullptr;
+ }
+}
+
} // namespace doris
diff --git a/be/src/runtime/query_context.h b/be/src/runtime/query_context.h
index dd24206c415..d5a8f12cee1 100644
--- a/be/src/runtime/query_context.h
+++ b/be/src/runtime/query_context.h
@@ -218,6 +218,12 @@ public:
std::shared_ptr<QueryStatistics> get_cpu_statistics() { return _cpu_statistics; }
+ void set_query_scheduler(uint64_t wg_id);
+
+ doris::pipeline::TaskScheduler* get_pipe_exec_scheduler();
+
+ ThreadPool* get_non_pipe_exec_thread_pool();
+
public:
DescriptorTbl* desc_tbl = nullptr;
bool set_rsc_info = false;
@@ -247,8 +253,6 @@ public:
// only for file scan node
std::map<int, TFileScanRangeParams> file_scan_range_params_map;
- std::atomic<bool> use_task_group_for_cpu_limit = false;
-
private:
TUniqueId _query_id;
ExecEnv* _exec_env = nullptr;
@@ -272,7 +276,7 @@ private:
std::shared_ptr<vectorized::SharedScannerController> _shared_scanner_controller;
vectorized::RuntimePredicate _runtime_predicate;
- taskgroup::TaskGroupPtr _task_group;
+ taskgroup::TaskGroupPtr _task_group = nullptr;
std::unique_ptr<RuntimeFilterMgr> _runtime_filter_mgr;
const TQueryOptions _query_options;
@@ -281,8 +285,9 @@ private:
// to report the real message if failed.
Status _exec_status = Status::OK();
- pipeline::TaskScheduler* _task_scheduler = nullptr;
+ doris::pipeline::TaskScheduler* _task_scheduler = nullptr;
vectorized::SimplifiedScanScheduler* _scan_task_scheduler = nullptr;
+ ThreadPool* _non_pipe_thread_pool = nullptr;
std::unique_ptr<pipeline::Dependency> _execution_dependency;
std::shared_ptr<QueryStatistics> _cpu_statistics = nullptr;
diff --git a/be/src/runtime/task_group/task_group_manager.cpp b/be/src/runtime/task_group/task_group_manager.cpp
index cbd7b5f73f6..74694baa9fc 100644
--- a/be/src/runtime/task_group/task_group_manager.cpp
+++ b/be/src/runtime/task_group/task_group_manager.cpp
@@ -67,18 +67,25 @@ TaskGroupPtr TaskGroupManager::get_task_group_by_id(uint64_t tg_id) {
return nullptr;
}
-bool TaskGroupManager::set_cg_task_sche_for_query_ctx(uint64_t tg_id, QueryContext* query_ctx_ptr) {
- std::lock_guard<std::shared_mutex> write_lock(_task_scheduler_lock);
+void TaskGroupManager::get_query_scheduler(uint64_t tg_id,
+ doris::pipeline::TaskScheduler** exec_sched,
+ vectorized::SimplifiedScanScheduler** scan_sched,
+ ThreadPool** non_pipe_thread_pool) {
+ std::shared_lock<std::shared_mutex> r_lock(_task_scheduler_lock);
auto tg_sche_it = _tg_sche_map.find(tg_id);
if (tg_sche_it != _tg_sche_map.end()) {
- query_ctx_ptr->set_task_scheduler(tg_sche_it->second.get());
- auto _tg_scan_sche_it = _tg_scan_sche_map.find(tg_id);
- if (_tg_scan_sche_it != _tg_scan_sche_map.end()) {
- query_ctx_ptr->set_scan_task_scheduler(_tg_scan_sche_it->second.get());
- return true;
- }
+ *exec_sched = tg_sche_it->second.get();
+ }
+
+ auto tg_scan_sche_it = _tg_scan_sche_map.find(tg_id);
+ if (tg_scan_sche_it != _tg_scan_sche_map.end()) {
+ *scan_sched = tg_scan_sche_it->second.get();
+ }
+
+ auto non_pipe_thread_pool_iter = _non_pipe_thread_pool_map.find(tg_id);
+ if (non_pipe_thread_pool_iter != _non_pipe_thread_pool_map.end()) {
+ *non_pipe_thread_pool = non_pipe_thread_pool_iter->second.get();
}
- return false;
}
Status TaskGroupManager::upsert_cg_task_scheduler(taskgroup::TaskGroupInfo* tg_info,
@@ -135,7 +142,23 @@ Status TaskGroupManager::upsert_cg_task_scheduler(taskgroup::TaskGroupInfo* tg_i
}
}
- // step 4 update cgroup cpu if needed
+ // step 4: init non-pipe scheduler
+ if (_non_pipe_thread_pool_map.find(tg_id) == _non_pipe_thread_pool_map.end()) {
+ std::unique_ptr<ThreadPool> thread_pool = nullptr;
+ auto ret = ThreadPoolBuilder("nonPip_" + tg_name)
+ .set_min_threads(1)
+ .set_max_threads(config::fragment_pool_thread_num_max)
+ .set_max_queue_size(config::fragment_pool_queue_size)
+ .set_cgroup_cpu_ctl(cg_cu_ctl_ptr)
+ .build(&thread_pool);
+ if (!ret.ok()) {
+ LOG(INFO) << "create non-pipline thread pool failed";
+ } else {
+ _non_pipe_thread_pool_map.emplace(tg_id, std::move(thread_pool));
+ }
+ }
+
+ // step 5: update cgroup cpu if needed
if (enable_cpu_hard_limit) {
if (cpu_hard_limit > 0) {
_cgroup_ctl_map.at(tg_id)->update_cpu_hard_limit(cpu_hard_limit);
@@ -160,6 +183,7 @@ void TaskGroupManager::delete_task_group_by_ids(std::set<uint64_t> used_wg_id) {
// stop task sche may cost some time, so it should not be locked
std::set<doris::pipeline::TaskScheduler*> task_sche_to_del;
std::set<vectorized::SimplifiedScanScheduler*> scan_task_sche_to_del;
+ std::set<ThreadPool*> non_pip_thread_pool_to_del;
std::set<uint64_t> deleted_tg_ids;
{
std::shared_lock<std::shared_mutex> read_lock(_task_scheduler_lock);
@@ -177,6 +201,13 @@ void TaskGroupManager::delete_task_group_by_ids(std::set<uint64_t> used_wg_id) {
scan_task_sche_to_del.insert(_tg_scan_sche_map[tg_id].get());
}
}
+ for (auto iter = _non_pipe_thread_pool_map.begin(); iter != _non_pipe_thread_pool_map.end();
+ iter++) {
+ uint64_t tg_id = iter->first;
+ if (used_wg_id.find(tg_id) == used_wg_id.end()) {
+ non_pip_thread_pool_to_del.insert(_non_pipe_thread_pool_map[tg_id].get());
+ }
+ }
}
// 1 stop all threads
for (auto* ptr1 : task_sche_to_del) {
@@ -185,6 +216,9 @@ void TaskGroupManager::delete_task_group_by_ids(std::set<uint64_t> used_wg_id) {
for (auto* ptr2 : scan_task_sche_to_del) {
ptr2->stop();
}
+ for (auto& ptr3 : non_pip_thread_pool_to_del) {
+ ptr3->shutdown();
+ }
// 2 release resource in memory
{
std::lock_guard<std::shared_mutex> write_lock(_task_scheduler_lock);
@@ -242,6 +276,9 @@ void TaskGroupManager::stop() {
for (auto& task_sche : _tg_scan_sche_map) {
task_sche.second->stop();
}
+ for (auto& no_pip_sche : _non_pipe_thread_pool_map) {
+ no_pip_sche.second->shutdown();
+ }
}
} // namespace doris::taskgroup
diff --git a/be/src/runtime/task_group/task_group_manager.h b/be/src/runtime/task_group/task_group_manager.h
index 08968b6fe99..a7ccb52f00e 100644
--- a/be/src/runtime/task_group/task_group_manager.h
+++ b/be/src/runtime/task_group/task_group_manager.h
@@ -65,11 +65,9 @@ public:
bool enable_cpu_hard_limit() { return _enable_cpu_hard_limit.load(); }
- bool set_cg_task_sche_for_query_ctx(uint64_t tg_id, QueryContext* query_ctx_ptr);
-
- // currently cgroup both support cpu soft limit and cpu hard limit
- // doris task group only support cpu soft limit
- bool enable_cgroup() { return enable_cpu_hard_limit() || config::enable_cgroup_cpu_soft_limit; }
+ void get_query_scheduler(uint64_t tg_id, doris::pipeline::TaskScheduler** exec_sched,
+ vectorized::SimplifiedScanScheduler** scan_sched,
+ ThreadPool** non_pipe_thread_pool);
private:
std::shared_mutex _group_mutex;
@@ -81,6 +79,7 @@ private:
std::map<uint64_t, std::unique_ptr<doris::pipeline::TaskScheduler>> _tg_sche_map;
std::map<uint64_t, std::unique_ptr<vectorized::SimplifiedScanScheduler>> _tg_scan_sche_map;
std::map<uint64_t, std::unique_ptr<CgroupCpuCtl>> _cgroup_ctl_map;
+ std::map<uint64_t, std::unique_ptr<ThreadPool>> _non_pipe_thread_pool_map;
std::shared_mutex _init_cg_ctl_lock;
std::unique_ptr<CgroupCpuCtl> _cg_cpu_ctl;
diff --git a/be/src/runtime/workload_management/workload_sched_policy_mgr.cpp b/be/src/runtime/workload_management/workload_sched_policy_mgr.cpp
index 2398bff465c..731dd0c8661 100644
--- a/be/src/runtime/workload_management/workload_sched_policy_mgr.cpp
+++ b/be/src/runtime/workload_management/workload_sched_policy_mgr.cpp
@@ -81,7 +81,6 @@ void WorkloadSchedPolicyMgr::_schedule_workload() {
if (list.size() == 0) {
continue;
}
- LOG(INFO) << "[workload_schedule] get query list size=" << list.size();
for (int i = 0; i < list.size(); i++) {
WorkloadQueryInfo* query_info_ptr = &(list[i]);
diff --git a/be/src/vec/exec/scan/scanner_context.h b/be/src/vec/exec/scan/scanner_context.h
index 1dd9966b162..28aec83d6a2 100644
--- a/be/src/vec/exec/scan/scanner_context.h
+++ b/be/src/vec/exec/scan/scanner_context.h
@@ -253,7 +253,7 @@ protected:
const int64_t _max_bytes_in_queue;
doris::vectorized::ScannerScheduler* _scanner_scheduler;
- SimplifiedScanScheduler* _simple_scan_scheduler = nullptr; // used for cpu hard limit
+ SimplifiedScanScheduler* _simple_scan_scheduler = nullptr;
// List "scanners" saves all "unfinished" scanners.
// The scanner scheduler will pop scanners from this list, run scanner,
// and then if the scanner is not finished, will be pushed back to this list.
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java b/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java
index 586a27ee103..8581980da2f 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/Coordinator.java
@@ -3639,6 +3639,9 @@ public class Coordinator implements CoordInterface {
params.params.setPerNodeScanRanges(scanRanges);
params.params.setPerExchNumSenders(perExchNumSenders);
+ if (tWorkloadGroups != null) {
+ params.setWorkloadGroups(tWorkloadGroups);
+ }
params.params.setDestinations(destinations);
params.params.setSenderId(i);
params.params.setNumSenders(instanceExecParams.size());
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java b/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
index 767d03f43d7..8b72ce3eb2e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
@@ -1519,7 +1519,7 @@ public class StmtExecutor {
coordBase = new PointQueryExec(planner, analyzer);
} else {
coord = new Coordinator(context, analyzer, planner, context.getStatsErrorEstimator());
- if (Config.enable_workload_group && context.sessionVariable.getEnablePipelineEngine()) {
+ if (Config.enable_workload_group) {
coord.setTWorkloadGroups(context.getEnv().getWorkloadGroupMgr().getWorkloadGroup(context));
} else {
context.setWorkloadGroupName("");
diff --git a/gensrc/thrift/PaloInternalService.thrift b/gensrc/thrift/PaloInternalService.thrift
index e4f5156d042..7d3525f5c28 100644
--- a/gensrc/thrift/PaloInternalService.thrift
+++ b/gensrc/thrift/PaloInternalService.thrift
@@ -397,6 +397,13 @@ struct TGlobalDict {
2: optional map<i32, i32> slot_dicts // map from slot id to column dict id, because 2 or more column may share the dict
}
+struct TPipelineWorkloadGroup {
+ 1: optional i64 id
+ 2: optional string name
+ 3: optional map<string, string> properties
+ 4: optional i64 version
+}
+
// ExecPlanFragment
struct TExecPlanFragmentParams {
1: required PaloInternalServiceVersion protocol_version
@@ -479,6 +486,11 @@ struct TExecPlanFragmentParams {
28: optional i32 num_local_sink
29: optional i64 content_length
+
+ 30: optional list<TPipelineWorkloadGroup> workload_groups
+
+ // For cloud
+ 1000: optional bool is_mow_table;
}
struct TExecPlanFragmentParamsList {
@@ -653,13 +665,6 @@ struct TPipelineInstanceParams {
7: optional map<Types.TPlanNodeId, bool> per_node_shared_scans
}
-struct TPipelineWorkloadGroup {
- 1: optional i64 id
- 2: optional string name
- 3: optional map<string, string> properties
- 4: optional i64 version
-}
-
// ExecPlanFragment
struct TPipelineFragmentParams {
1: required PaloInternalServiceVersion protocol_version
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 41/43: [fix](move-memtable) make sure index descriptor is set when creating delta writer (#30157)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit bb6fff3455f59ba61642bbd21562f96bf2f47f55
Author: Kaijie Chen <ck...@apache.org>
AuthorDate: Mon Jan 22 20:35:18 2024 +0800
[fix](move-memtable) make sure index descriptor is set when creating delta writer (#30157)
---------
Co-authored-by: Yongqiang YANG <98...@users.noreply.github.com>
Co-authored-by: Xin Liao <li...@126.com>
---
be/src/vec/sink/writer/vtablet_writer_v2.cpp | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/be/src/vec/sink/writer/vtablet_writer_v2.cpp b/be/src/vec/sink/writer/vtablet_writer_v2.cpp
index e23fe761ecf..cfeeb782bed 100644
--- a/be/src/vec/sink/writer/vtablet_writer_v2.cpp
+++ b/be/src/vec/sink/writer/vtablet_writer_v2.cpp
@@ -431,15 +431,27 @@ Status VTabletWriterV2::_write_memtable(std::shared_ptr<vectorized::Block> block
.is_high_priority = _is_high_priority,
.write_file_cache = _write_file_cache,
};
+ bool index_not_found = true;
for (const auto& index : _schema->indexes()) {
if (index->index_id == rows.index_id) {
req.slots = &index->slots;
req.schema_hash = index->schema_hash;
+ index_not_found = false;
break;
}
}
+ if (index_not_found) {
+ LOG(WARNING) << "index " << rows.index_id
+ << " not found in schema, load_id=" << print_id(_load_id);
+ return std::unique_ptr<DeltaWriterV2>(nullptr);
+ }
return DeltaWriterV2::open(&req, streams, _state);
});
+ if (delta_writer == nullptr) {
+ LOG(WARNING) << "failed to open DeltaWriter for tablet " << tablet_id
+ << ", load_id=" << print_id(_load_id);
+ return Status::InternalError("failed to open DeltaWriter for tablet {}", tablet_id);
+ }
{
SCOPED_TIMER(_wait_mem_limit_timer);
ExecEnv::GetInstance()->memtable_memory_limiter()->handle_memtable_flush();
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 37/43: [fix](Nereids) user identify syntax is wrong (#30226)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit b3296a2a16c718d8d38756b87e3818880683969a
Author: morrySnow <10...@users.noreply.github.com>
AuthorDate: Mon Jan 22 18:36:15 2024 +0800
[fix](Nereids) user identify syntax is wrong (#30226)
---
fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4 | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4 b/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
index 709ee61f54a..1f3e1167538 100644
--- a/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
+++ b/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
@@ -176,7 +176,7 @@ identifierOrText
;
userIdentify
- : user=identifierOrText (AT (host=identifierOrText | LEFT_PAREN host=identifierOrText RIGHT_PAREN))?
+ : user=identifierOrText (ATSIGN (host=identifierOrText | LEFT_PAREN host=identifierOrText RIGHT_PAREN))?
;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 36/43: [Fix](Expr&code-style) check prepare&open before every VExpr execute (#26673)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 24ed3e4103027cef1a465f5b7ba58702214831ec
Author: zclllyybb <zh...@selectdb.com>
AuthorDate: Mon Jan 22 18:04:22 2024 +0800
[Fix](Expr&code-style) check prepare&open before every VExpr execute (#26673)
---
be/src/exec/exec_node.cpp | 52 +++++++++---------
be/src/exec/exec_node.h | 19 ++-----
.../exec/multi_cast_data_stream_source.cpp | 8 ++-
be/src/pipeline/exec/operator.h | 18 ++-----
be/src/pipeline/exec/set_sink_operator.cpp | 16 +++---
be/src/pipeline/pipeline_fragment_context.cpp | 26 ++++-----
be/src/pipeline/pipeline_fragment_context.h | 4 +-
be/src/service/point_query_executor.cpp | 10 ++--
be/src/vec/columns/column_nullable.cpp | 6 +--
be/src/vec/columns/column_nullable.h | 4 +-
be/src/vec/exec/join/vjoin_node_base.h | 19 +++----
be/src/vec/exec/vset_operation_node.cpp | 7 +--
be/src/vec/exec/vset_operation_node.h | 7 +--
be/src/vec/exec/vunion_node.cpp | 21 +++-----
be/src/vec/exprs/vbitmap_predicate.cpp | 4 ++
be/src/vec/exprs/vbloom_predicate.cpp | 4 ++
be/src/vec/exprs/vcase_expr.cpp | 9 +++-
be/src/vec/exprs/vcast_expr.cpp | 4 ++
be/src/vec/exprs/vcolumn_ref.h | 10 ++++
be/src/vec/exprs/vdirect_in_predicate.h | 19 ++++++-
be/src/vec/exprs/vectorized_fn_call.cpp | 19 +++----
be/src/vec/exprs/vexpr.cpp | 62 ++++++++++-----------
be/src/vec/exprs/vexpr.h | 63 +++++++++++++---------
be/src/vec/exprs/vexpr_context.cpp | 28 ++++------
be/src/vec/exprs/vexpr_context.h | 15 +++---
be/src/vec/exprs/vin_predicate.cpp | 4 ++
be/src/vec/exprs/vlambda_function_call_expr.h | 12 ++++-
be/src/vec/exprs/vlambda_function_expr.h | 15 ++++++
be/src/vec/exprs/vliteral.cpp | 19 +++++--
be/src/vec/exprs/vliteral.h | 5 ++
be/src/vec/exprs/vmatch_predicate.cpp | 5 +-
be/src/vec/exprs/vruntimefilter_wrapper.cpp | 15 +++++-
be/src/vec/exprs/vslot_ref.cpp | 11 ++++
be/src/vec/exprs/vslot_ref.h | 5 +-
be/src/vec/exprs/vtuple_is_null_predicate.cpp | 9 ++++
be/src/vec/exprs/vtuple_is_null_predicate.h | 4 +-
be/src/vec/runtime/vdata_stream_recvr.h | 8 +--
37 files changed, 329 insertions(+), 237 deletions(-)
diff --git a/be/src/exec/exec_node.cpp b/be/src/exec/exec_node.cpp
index d65e8f96bd2..ac6e7eae9a0 100644
--- a/be/src/exec/exec_node.cpp
+++ b/be/src/exec/exec_node.cpp
@@ -25,8 +25,8 @@
#include <thrift/protocol/TDebugProtocol.h>
#include <map>
+#include <memory>
#include <sstream>
-#include <typeinfo>
#include <utility>
#include "common/compiler_util.h" // IWYU pragma: keep
@@ -84,16 +84,10 @@ ExecNode::ExecNode(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl
_tuple_ids(tnode.row_tuples),
_row_descriptor(descs, tnode.row_tuples, tnode.nullable_tuples),
_resource_profile(tnode.resource_profile),
- _limit(tnode.limit),
- _num_rows_returned(0),
- _rows_returned_counter(nullptr),
- _rows_returned_rate(nullptr),
- _memory_used_counter(nullptr),
- _peak_memory_usage_counter(nullptr),
- _is_closed(false),
- _ref(0) {
+ _limit(tnode.limit) {
if (tnode.__isset.output_tuple_id) {
- _output_row_descriptor.reset(new RowDescriptor(descs, {tnode.output_tuple_id}, {true}));
+ _output_row_descriptor = std::make_unique<RowDescriptor>(
+ descs, std::vector {tnode.output_tuple_id}, std::vector {true});
}
_query_statistics = std::make_shared<QueryStatistics>();
}
@@ -108,7 +102,7 @@ Status ExecNode::init(const TPlanNode& tnode, RuntimeState* state) {
RETURN_IF_ERROR(vectorized::VExpr::create_expr_tree(tnode.vconjunct, context));
_conjuncts.emplace_back(context);
} else if (tnode.__isset.conjuncts) {
- for (auto& conjunct : tnode.conjuncts) {
+ for (const auto& conjunct : tnode.conjuncts) {
vectorized::VExprContextSPtr context;
RETURN_IF_ERROR(vectorized::VExpr::create_expr_tree(conjunct, context));
_conjuncts.emplace_back(context);
@@ -136,8 +130,9 @@ Status ExecNode::prepare(RuntimeState* state) {
_projection_timer = ADD_TIMER(_runtime_profile, "ProjectionTime");
_rows_returned_rate = runtime_profile()->add_derived_counter(
ROW_THROUGHPUT_COUNTER, TUnit::UNIT_PER_SECOND,
- std::bind<int64_t>(&RuntimeProfile::units_per_second, _rows_returned_counter,
- runtime_profile()->total_time_counter()),
+ [this, capture0 = runtime_profile()->total_time_counter()] {
+ return RuntimeProfile::units_per_second(_rows_returned_counter, capture0);
+ },
"");
_memory_used_counter = ADD_LABEL_COUNTER(runtime_profile(), "MemoryUsage");
_peak_memory_usage_counter = _runtime_profile->AddHighWaterMarkCounter(
@@ -150,13 +145,13 @@ Status ExecNode::prepare(RuntimeState* state) {
RETURN_IF_ERROR(vectorized::VExpr::prepare(_projections, state, intermediate_row_desc()));
- for (int i = 0; i < _children.size(); ++i) {
- RETURN_IF_ERROR(_children[i]->prepare(state));
+ for (auto& i : _children) {
+ RETURN_IF_ERROR(i->prepare(state));
}
return Status::OK();
}
-Status ExecNode::alloc_resource(doris::RuntimeState* state) {
+Status ExecNode::alloc_resource(RuntimeState* state) {
for (auto& conjunct : _conjuncts) {
RETURN_IF_ERROR(conjunct->open(state));
}
@@ -170,8 +165,8 @@ Status ExecNode::open(RuntimeState* state) {
Status ExecNode::reset(RuntimeState* state) {
_num_rows_returned = 0;
- for (int i = 0; i < _children.size(); ++i) {
- RETURN_IF_ERROR(_children[i]->reset(state));
+ for (auto& i : _children) {
+ RETURN_IF_ERROR(i->reset(state));
}
return Status::OK();
}
@@ -199,8 +194,8 @@ Status ExecNode::close(RuntimeState* state) {
_is_closed = true;
Status result;
- for (int i = 0; i < _children.size(); ++i) {
- auto st = _children[i]->close(state);
+ for (auto& i : _children) {
+ auto st = i->close(state);
if (result.ok() && !st.ok()) {
result = st;
}
@@ -227,7 +222,7 @@ void ExecNode::add_runtime_exec_option(const std::string& str) {
Status ExecNode::create_tree(RuntimeState* state, ObjectPool* pool, const TPlan& plan,
const DescriptorTbl& descs, ExecNode** root) {
- if (plan.nodes.size() == 0) {
+ if (plan.nodes.empty()) {
*root = nullptr;
return Status::OK();
}
@@ -305,6 +300,7 @@ Status ExecNode::create_tree_helper(RuntimeState* state, ObjectPool* pool,
return Status::OK();
}
+// NOLINTBEGIN(readability-function-size)
Status ExecNode::create_node(RuntimeState* state, ObjectPool* pool, const TPlanNode& tnode,
const DescriptorTbl& descs, ExecNode** node) {
VLOG_CRITICAL << "tnode:\n" << apache::thrift::ThriftDebugString(tnode);
@@ -428,8 +424,7 @@ Status ExecNode::create_node(RuntimeState* state, ObjectPool* pool, const TPlanN
return Status::OK();
default:
- std::map<int, const char*>::const_iterator i =
- _TPlanNodeType_VALUES_TO_NAMES.find(tnode.node_type);
+ auto i = _TPlanNodeType_VALUES_TO_NAMES.find(tnode.node_type);
const char* str = "unknown node type";
if (i != _TPlanNodeType_VALUES_TO_NAMES.end()) {
@@ -443,6 +438,7 @@ Status ExecNode::create_node(RuntimeState* state, ObjectPool* pool, const TPlanN
return Status::OK();
}
+// NOLINTEND(readability-function-size)
std::string ExecNode::debug_string() const {
std::stringstream out;
@@ -459,9 +455,9 @@ void ExecNode::debug_string(int indentation_level, std::stringstream* out) const
}
*out << "]";
- for (int i = 0; i < _children.size(); ++i) {
+ for (auto* i : _children) {
*out << "\n";
- _children[i]->debug_string(indentation_level + 1, out);
+ i->debug_string(indentation_level + 1, out);
}
}
@@ -470,8 +466,8 @@ void ExecNode::collect_nodes(TPlanNodeType::type node_type, std::vector<ExecNode
nodes->push_back(this);
}
- for (int i = 0; i < _children.size(); ++i) {
- _children[i]->collect_nodes(node_type, nodes);
+ for (auto& i : _children) {
+ i->collect_nodes(node_type, nodes);
}
}
@@ -488,7 +484,7 @@ void ExecNode::collect_scan_nodes(vector<ExecNode*>* nodes) {
void ExecNode::init_runtime_profile(const std::string& name) {
std::stringstream ss;
ss << name << " (id=" << _id << ")";
- _runtime_profile.reset(new RuntimeProfile(ss.str()));
+ _runtime_profile = std::make_unique<RuntimeProfile>(ss.str());
_runtime_profile->set_metadata(_id);
}
diff --git a/be/src/exec/exec_node.h b/be/src/exec/exec_node.h
index f4b49cba6f5..903122ecded 100644
--- a/be/src/exec/exec_node.h
+++ b/be/src/exec/exec_node.h
@@ -21,10 +21,10 @@
#pragma once
#include <gen_cpp/PlanNodes_types.h>
-#include <stddef.h>
-#include <stdint.h>
#include <atomic>
+#include <cstddef>
+#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
@@ -267,7 +267,7 @@ protected:
const TBackendResourceProfile _resource_profile;
int64_t _limit; // -1: no limit
- int64_t _num_rows_returned;
+ int64_t _num_rows_returned = 0;
std::unique_ptr<RuntimeProfile> _runtime_profile;
@@ -303,15 +303,6 @@ protected:
bool is_closed() const { return _is_closed; }
- // TODO(zc)
- /// Pointer to the containing SubplanNode or nullptr if not inside a subplan.
- /// Set by SubplanNode::Init(). Not owned.
- // SubplanNode* containing_subplan_;
-
- /// Returns true if this node is inside the right-hand side plan tree of a SubplanNode.
- /// Valid to call in or after Prepare().
- bool is_in_subplan() const { return false; }
-
// Create a single exec node derived from thrift node; place exec node in 'pool'.
static Status create_node(RuntimeState* state, ObjectPool* pool, const TPlanNode& tnode,
const DescriptorTbl& descs, ExecNode** node);
@@ -334,9 +325,9 @@ private:
ExecNode** root);
friend class pipeline::OperatorBase;
- bool _is_closed;
+ bool _is_closed = false;
bool _is_resource_released = false;
- std::atomic_int _ref; // used by pipeline operator to release resource.
+ std::atomic_int _ref = 0; // used by pipeline operator to release resource.
};
} // namespace doris
diff --git a/be/src/pipeline/exec/multi_cast_data_stream_source.cpp b/be/src/pipeline/exec/multi_cast_data_stream_source.cpp
index a4f3ff55a5c..6ac06ee5f10 100644
--- a/be/src/pipeline/exec/multi_cast_data_stream_source.cpp
+++ b/be/src/pipeline/exec/multi_cast_data_stream_source.cpp
@@ -17,13 +17,11 @@
#include "multi_cast_data_stream_source.h"
-#include <functional>
-
#include "common/status.h"
#include "pipeline/exec/multi_cast_data_streamer.h"
#include "pipeline/exec/operator.h"
-#include "runtime/query_statistics.h"
#include "vec/core/block.h"
+#include "vec/core/materialize_block.h"
namespace doris::pipeline {
@@ -108,7 +106,7 @@ Status MultiCastDataStreamerSourceOperator::get_block(RuntimeState* state, vecto
if (!_output_expr_contexts.empty() && output_block->rows() > 0) {
RETURN_IF_ERROR(vectorized::VExprContext::get_output_block_after_execute_exprs(
_output_expr_contexts, *output_block, block, true));
- materialize_block_inplace(*block);
+ vectorized::materialize_block_inplace(*block);
}
if (eos) {
source_state = SourceState::FINISHED;
@@ -176,7 +174,7 @@ Status MultiCastDataStreamerSourceOperatorX::get_block(RuntimeState* state,
if (!local_state._output_expr_contexts.empty() && output_block->rows() > 0) {
RETURN_IF_ERROR(vectorized::VExprContext::get_output_block_after_execute_exprs(
local_state._output_expr_contexts, *output_block, block, true));
- materialize_block_inplace(*block);
+ vectorized::materialize_block_inplace(*block);
}
COUNTER_UPDATE(local_state._rows_returned_counter, block->rows());
if (eos) {
diff --git a/be/src/pipeline/exec/operator.h b/be/src/pipeline/exec/operator.h
index cd5fba5fee3..bf41c670e0c 100644
--- a/be/src/pipeline/exec/operator.h
+++ b/be/src/pipeline/exec/operator.h
@@ -19,20 +19,16 @@
#include <fmt/format.h>
#include <glog/logging.h>
-#include <stdint.h>
+#include <cstdint>
#include <functional>
#include <memory>
-#include <ostream>
#include <string>
-#include <type_traits>
#include <utility>
#include <vector>
#include "common/status.h"
#include "exec/exec_node.h"
-#include "pipeline/pipeline_x/dependency.h"
-#include "runtime/memory/mem_tracker.h"
#include "runtime/runtime_state.h"
#include "util/runtime_profile.h"
#include "vec/core/block.h"
@@ -105,7 +101,7 @@ using OperatorBuilders = std::vector<OperatorBuilderPtr>;
class OperatorBuilderBase {
public:
- OperatorBuilderBase(int32_t id, const std::string& name) : _id(id), _name(name) {}
+ OperatorBuilderBase(int32_t id, std::string name) : _id(id), _name(std::move(name)) {}
virtual ~OperatorBuilderBase() = default;
@@ -333,10 +329,7 @@ public:
return Status::OK();
}
- Status open(RuntimeState* state) override {
- RETURN_IF_ERROR(_node->alloc_resource(state));
- return Status::OK();
- }
+ Status open(RuntimeState* state) override { return _node->alloc_resource(state); }
Status sink(RuntimeState* state, vectorized::Block* in_block,
SourceState source_state) override {
@@ -413,8 +406,7 @@ class StatefulOperator : public StreamingOperator<StatefulNodeType> {
public:
StatefulOperator(OperatorBuilderBase* builder, ExecNode* node)
: StreamingOperator<StatefulNodeType>(builder, node),
- _child_block(vectorized::Block::create_shared()),
- _child_source_state(SourceState::DEPEND_ON_SOURCE) {}
+ _child_block(vectorized::Block::create_shared()) {}
virtual ~StatefulOperator() = default;
@@ -454,7 +446,7 @@ public:
protected:
std::shared_ptr<vectorized::Block> _child_block;
- SourceState _child_source_state;
+ SourceState _child_source_state {SourceState::DEPEND_ON_SOURCE};
};
} // namespace doris::pipeline
diff --git a/be/src/pipeline/exec/set_sink_operator.cpp b/be/src/pipeline/exec/set_sink_operator.cpp
index 6c18cab03f6..cb106d76edb 100644
--- a/be/src/pipeline/exec/set_sink_operator.cpp
+++ b/be/src/pipeline/exec/set_sink_operator.cpp
@@ -21,6 +21,7 @@
#include "pipeline/exec/operator.h"
#include "vec/common/hash_table/hash_table_set_build.h"
+#include "vec/core/materialize_block.h"
#include "vec/exec/vset_operation_node.h"
namespace doris {
@@ -139,10 +140,10 @@ Status SetSinkOperatorX<is_intersect>::_extract_build_column(
block.get_by_position(result_col_id).column =
block.get_by_position(result_col_id).column->convert_to_full_column_if_const();
- auto column = block.get_by_position(result_col_id).column.get();
+ const auto* column = block.get_by_position(result_col_id).column.get();
- if (auto* nullable = check_and_get_column<vectorized::ColumnNullable>(*column)) {
- auto& col_nested = nullable->get_nested_column();
+ if (const auto* nullable = check_and_get_column<vectorized::ColumnNullable>(*column)) {
+ const auto& col_nested = nullable->get_nested_column();
if (local_state._shared_state->build_not_ignore_null[i]) {
raw_ptrs[i] = nullable;
} else {
@@ -165,7 +166,7 @@ Status SetSinkLocalState<is_intersect>::init(RuntimeState* state, LocalSinkState
SCOPED_TIMER(_open_timer);
_build_timer = ADD_TIMER(_profile, "BuildTime");
- Parent& parent = _parent->cast<Parent>();
+ auto& parent = _parent->cast<Parent>();
_dependency->set_cur_child_id(parent._cur_child_id);
_child_exprs.resize(parent._child_exprs.size());
for (size_t i = 0; i < _child_exprs.size(); i++) {
@@ -175,16 +176,15 @@ Status SetSinkLocalState<is_intersect>::init(RuntimeState* state, LocalSinkState
_shared_state->child_quantity = parent._child_quantity;
auto& child_exprs_lists = _shared_state->child_exprs_lists;
- DCHECK(child_exprs_lists.size() == 0 || child_exprs_lists.size() == parent._child_quantity);
- if (child_exprs_lists.size() == 0) {
+ DCHECK(child_exprs_lists.empty() || child_exprs_lists.size() == parent._child_quantity);
+ if (child_exprs_lists.empty()) {
child_exprs_lists.resize(parent._child_quantity);
}
child_exprs_lists[parent._cur_child_id] = _child_exprs;
_shared_state->hash_table_variants = std::make_unique<vectorized::SetHashTableVariants>();
- for (int i = 0; i < child_exprs_lists[0].size(); ++i) {
- const auto& ctx = child_exprs_lists[0][i];
+ for (const auto& ctx : child_exprs_lists[0]) {
_shared_state->build_not_ignore_null.push_back(ctx->root()->is_nullable());
}
_shared_state->hash_table_init();
diff --git a/be/src/pipeline/pipeline_fragment_context.cpp b/be/src/pipeline/pipeline_fragment_context.cpp
index b9c2382ce86..538a2ce1bdb 100644
--- a/be/src/pipeline/pipeline_fragment_context.cpp
+++ b/be/src/pipeline/pipeline_fragment_context.cpp
@@ -22,13 +22,15 @@
#include <gen_cpp/PlanNodes_types.h>
#include <gen_cpp/Planner_types.h>
#include <pthread.h>
-#include <stdlib.h>
+
+#include <cstdlib>
// IWYU pragma: no_include <bits/chrono.h>
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <chrono> // IWYU pragma: keep
#include <map>
+#include <memory>
#include <ostream>
#include <typeinfo>
#include <utility>
@@ -212,8 +214,7 @@ PipelinePtr PipelineFragmentContext::add_pipeline(PipelinePtr parent, int idx) {
return pipeline;
}
-Status PipelineFragmentContext::prepare(const doris::TPipelineFragmentParams& request,
- const size_t idx) {
+Status PipelineFragmentContext::prepare(const doris::TPipelineFragmentParams& request, size_t idx) {
if (_prepared) {
return Status::InternalError("Already prepared");
}
@@ -299,16 +300,16 @@ Status PipelineFragmentContext::prepare(const doris::TPipelineFragmentParams& re
<< local_params.per_node_scan_ranges.size();
// set scan range in ScanNode
- for (int i = 0; i < scan_nodes.size(); ++i) {
+ for (auto& i : scan_nodes) {
// TODO(cmy): this "if...else" should be removed once all ScanNode are derived from VScanNode.
- ExecNode* node = scan_nodes[i];
+ ExecNode* node = i;
if (typeid(*node) == typeid(vectorized::NewOlapScanNode) ||
typeid(*node) == typeid(vectorized::NewFileScanNode) ||
typeid(*node) == typeid(vectorized::NewOdbcScanNode) ||
typeid(*node) == typeid(vectorized::NewEsScanNode) ||
typeid(*node) == typeid(vectorized::VMetaScanNode) ||
typeid(*node) == typeid(vectorized::NewJdbcScanNode)) {
- auto* scan_node = static_cast<vectorized::VScanNode*>(scan_nodes[i]);
+ auto* scan_node = static_cast<vectorized::VScanNode*>(i);
auto scan_ranges = find_with_default(local_params.per_node_scan_ranges, scan_node->id(),
no_scan_ranges);
const bool shared_scan =
@@ -316,7 +317,7 @@ Status PipelineFragmentContext::prepare(const doris::TPipelineFragmentParams& re
scan_node->set_scan_ranges(_runtime_state.get(), scan_ranges);
scan_node->set_shared_scan(_runtime_state.get(), shared_scan);
} else {
- ScanNode* scan_node = static_cast<ScanNode*>(node);
+ auto* scan_node = static_cast<ScanNode*>(node);
auto scan_ranges = find_with_default(local_params.per_node_scan_ranges, scan_node->id(),
no_scan_ranges);
static_cast<void>(scan_node->set_scan_ranges(_runtime_state.get(), scan_ranges));
@@ -850,10 +851,10 @@ Status PipelineFragmentContext::_create_sink(int sender_id, const TDataSink& thr
{false})
: sink_->row_desc();
// 1. create the data stream sender sink
- _multi_cast_stream_sink_senders[i].reset(new vectorized::VDataStreamSender(
+ _multi_cast_stream_sink_senders[i] = std::make_unique<vectorized::VDataStreamSender>(
_runtime_state.get(), _runtime_state->obj_pool(), sender_id, row_desc,
thrift_sink.multi_cast_stream_sink.sinks[i],
- thrift_sink.multi_cast_stream_sink.destinations[i]));
+ thrift_sink.multi_cast_stream_sink.destinations[i]);
// 2. create and set the source operator of multi_cast_data_stream_source for new pipeline
OperatorBuilderPtr source_op =
@@ -941,9 +942,10 @@ Status PipelineFragmentContext::send_report(bool done) {
_fragment_instance_id,
_backend_num,
_runtime_state.get(),
- std::bind(&PipelineFragmentContext::update_status, this, std::placeholders::_1),
- std::bind(&PipelineFragmentContext::cancel, this, std::placeholders::_1,
- std::placeholders::_2),
+ [this](auto&& PH1) { return update_status(std::forward<decltype(PH1)>(PH1)); },
+ [this](auto&& PH1, auto&& PH2) {
+ cancel(std::forward<decltype(PH1)>(PH1), std::forward<decltype(PH2)>(PH2));
+ },
_query_ctx->get_query_statistics()},
std::dynamic_pointer_cast<PipelineFragmentContext>(shared_from_this()));
}
diff --git a/be/src/pipeline/pipeline_fragment_context.h b/be/src/pipeline/pipeline_fragment_context.h
index 353e7a06586..a7a45d8f07f 100644
--- a/be/src/pipeline/pipeline_fragment_context.h
+++ b/be/src/pipeline/pipeline_fragment_context.h
@@ -67,7 +67,7 @@ public:
const std::function<void(RuntimeState*, Status*)>& call_back,
const report_status_callback& report_status_cb);
- virtual ~PipelineFragmentContext();
+ ~PipelineFragmentContext() override;
PipelinePtr add_pipeline();
@@ -89,7 +89,7 @@ public:
int32_t next_operator_builder_id() { return _next_operator_builder_id++; }
- Status prepare(const doris::TPipelineFragmentParams& request, const size_t idx);
+ Status prepare(const doris::TPipelineFragmentParams& request, size_t idx);
virtual Status prepare(const doris::TPipelineFragmentParams& request) {
return Status::InternalError("Pipeline fragment context do not implement prepare");
diff --git a/be/src/service/point_query_executor.cpp b/be/src/service/point_query_executor.cpp
index a86d5ed90b8..83d059ba206 100644
--- a/be/src/service/point_query_executor.cpp
+++ b/be/src/service/point_query_executor.cpp
@@ -26,6 +26,7 @@
#include <unordered_map>
#include <vector>
+#include "common/status.h"
#include "gutil/integral_types.h"
#include "olap/lru_cache.h"
#include "olap/olap_tuple.h"
@@ -56,21 +57,22 @@ Status Reusable::init(const TDescriptorTable& t_desc_tbl, const std::vector<TExp
RETURN_IF_ERROR(DescriptorTbl::create(_runtime_state->obj_pool(), t_desc_tbl, &_desc_tbl));
_runtime_state->set_desc_tbl(_desc_tbl);
_block_pool.resize(block_size);
- for (int i = 0; i < _block_pool.size(); ++i) {
- _block_pool[i] = vectorized::Block::create_unique(tuple_desc()->slots(), 2);
+ for (auto& i : _block_pool) {
+ i = vectorized::Block::create_unique(tuple_desc()->slots(), 2);
// Name is useless but cost space
- _block_pool[i]->clear_names();
+ i->clear_names();
}
RETURN_IF_ERROR(vectorized::VExpr::create_expr_trees(output_exprs, _output_exprs_ctxs));
RowDescriptor row_desc(tuple_desc(), false);
// Prepare the exprs to run.
RETURN_IF_ERROR(vectorized::VExpr::prepare(_output_exprs_ctxs, _runtime_state.get(), row_desc));
+ RETURN_IF_ERROR(vectorized::VExpr::open(_output_exprs_ctxs, _runtime_state.get()));
_create_timestamp = butil::gettimeofday_ms();
_data_type_serdes = vectorized::create_data_type_serdes(tuple_desc()->slots());
_col_default_values.resize(tuple_desc()->slots().size());
for (int i = 0; i < tuple_desc()->slots().size(); ++i) {
- auto slot = tuple_desc()->slots()[i];
+ auto* slot = tuple_desc()->slots()[i];
_col_uid_to_idx[slot->col_unique_id()] = i;
_col_default_values[i] = slot->col_default_value();
}
diff --git a/be/src/vec/columns/column_nullable.cpp b/be/src/vec/columns/column_nullable.cpp
index 426de2d4f70..8b0008d6e2e 100644
--- a/be/src/vec/columns/column_nullable.cpp
+++ b/be/src/vec/columns/column_nullable.cpp
@@ -23,9 +23,7 @@
#include "vec/columns/column_const.h"
#include "vec/common/arena.h"
#include "vec/common/assert_cast.h"
-#include "vec/common/nan_utils.h"
#include "vec/common/sip_hash.h"
-#include "vec/common/typeid_cast.h"
#include "vec/core/sort_block.h"
#include "vec/data_types/data_type.h"
#include "vec/utils/util.hpp"
@@ -571,7 +569,9 @@ bool ColumnNullable::has_null(size_t size) const {
}
ColumnPtr make_nullable(const ColumnPtr& column, bool is_nullable) {
- if (is_column_nullable(*column)) return column;
+ if (is_column_nullable(*column)) {
+ return column;
+ }
if (is_column_const(*column)) {
return ColumnConst::create(
diff --git a/be/src/vec/columns/column_nullable.h b/be/src/vec/columns/column_nullable.h
index 83cbe82e328..91128fb69a8 100644
--- a/be/src/vec/columns/column_nullable.h
+++ b/be/src/vec/columns/column_nullable.h
@@ -32,7 +32,6 @@
#include "olap/olap_common.h"
#include "runtime/define_primitive_type.h"
#include "vec/columns/column.h"
-#include "vec/columns/column_impl.h"
#include "vec/columns/column_vector.h"
#include "vec/columns/columns_number.h"
#include "vec/common/assert_cast.h"
@@ -77,8 +76,7 @@ public:
null_map_->assume_mutable());
}
- template <typename... Args,
- typename = typename std::enable_if<IsMutableColumns<Args...>::value>::type>
+ template <typename... Args, typename = std::enable_if_t<IsMutableColumns<Args...>::value>>
static MutablePtr create(Args&&... args) {
return Base::create(std::forward<Args>(args)...);
}
diff --git a/be/src/vec/exec/join/vjoin_node_base.h b/be/src/vec/exec/join/vjoin_node_base.h
index a44bc5513a9..c918e26e6fe 100644
--- a/be/src/vec/exec/join/vjoin_node_base.h
+++ b/be/src/vec/exec/join/vjoin_node_base.h
@@ -23,7 +23,6 @@
#include <memory>
#include <type_traits>
#include <variant>
-#include <vector>
#include "common/status.h"
#include "exec/exec_node.h"
@@ -57,22 +56,20 @@ class VJoinNodeBase : public ExecNode {
public:
VJoinNodeBase(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs);
- virtual Status prepare(RuntimeState* state) override;
+ Status prepare(RuntimeState* state) override;
- virtual Status close(RuntimeState* state) override;
+ Status close(RuntimeState* state) override;
- virtual Status open(RuntimeState* state) override;
+ Status open(RuntimeState* state) override;
- virtual const RowDescriptor& row_desc() const override { return *_output_row_desc; }
+ const RowDescriptor& row_desc() const override { return *_output_row_desc; }
- virtual const RowDescriptor& intermediate_row_desc() const override {
- return *_intermediate_row_desc;
- }
+ const RowDescriptor& intermediate_row_desc() const override { return *_intermediate_row_desc; }
- virtual Status alloc_resource(RuntimeState* state) override;
- virtual void release_resource(RuntimeState* state) override;
+ Status alloc_resource(RuntimeState* state) override;
+ void release_resource(RuntimeState* state) override;
- virtual Status init(const TPlanNode& tnode, RuntimeState* state = nullptr) override;
+ Status init(const TPlanNode& tnode, RuntimeState* state = nullptr) override;
[[nodiscard]] bool can_terminate_early() override { return _short_circuit_for_probe; }
diff --git a/be/src/vec/exec/vset_operation_node.cpp b/be/src/vec/exec/vset_operation_node.cpp
index 4f4634fbd64..3c47638ef42 100644
--- a/be/src/vec/exec/vset_operation_node.cpp
+++ b/be/src/vec/exec/vset_operation_node.cpp
@@ -22,8 +22,6 @@
#include <gen_cpp/PlanNodes_types.h>
#include <glog/logging.h>
-#include <array>
-#include <atomic>
#include <ostream>
#include <string>
#include <type_traits>
@@ -31,12 +29,9 @@
#include "runtime/define_primitive_type.h"
#include "runtime/runtime_state.h"
-#include "util/defer_op.h"
#include "vec/columns/column_nullable.h"
-#include "vec/common/columns_hashing.h"
#include "vec/common/hash_table/hash_table_set_build.h"
#include "vec/common/hash_table/hash_table_set_probe.h"
-#include "vec/common/uint128.h"
#include "vec/core/column_with_type_and_name.h"
#include "vec/core/materialize_block.h"
#include "vec/core/types.h"
@@ -100,6 +95,8 @@ Status VSetOperationNode<is_intersect>::init(const TPlanNode& tnode, RuntimeStat
template <bool is_intersect>
Status VSetOperationNode<is_intersect>::alloc_resource(RuntimeState* state) {
SCOPED_TIMER(_exec_timer);
+ // will open projections
+ RETURN_IF_ERROR(ExecNode::alloc_resource(state));
// open result expr lists.
for (const VExprContextSPtrs& exprs : _child_expr_lists) {
RETURN_IF_ERROR(VExpr::open(exprs, state));
diff --git a/be/src/vec/exec/vset_operation_node.h b/be/src/vec/exec/vset_operation_node.h
index ae600c6490d..b1ab9c47650 100644
--- a/be/src/vec/exec/vset_operation_node.h
+++ b/be/src/vec/exec/vset_operation_node.h
@@ -17,10 +17,7 @@
#pragma once
-#include <stddef.h>
-#include <stdint.h>
-
-#include <functional>
+#include <cstdint>
#include <iosfwd>
#include <memory>
#include <unordered_map>
@@ -33,8 +30,6 @@
#include "vec/aggregate_functions/aggregate_function.h"
#include "vec/columns/column.h"
#include "vec/common/arena.h"
-#include "vec/common/hash_table/hash_map.h"
-#include "vec/common/string_ref.h"
#include "vec/core/block.h"
#include "vec/exec/join/process_hash_table_probe.h"
#include "vec/exec/join/vhash_join_node.h"
diff --git a/be/src/vec/exec/vunion_node.cpp b/be/src/vec/exec/vunion_node.cpp
index e77fd9fee90..eac8aa1b167 100644
--- a/be/src/vec/exec/vunion_node.cpp
+++ b/be/src/vec/exec/vunion_node.cpp
@@ -20,7 +20,6 @@
#include <gen_cpp/Exprs_types.h>
#include <gen_cpp/PlanNodes_types.h>
-#include <algorithm>
#include <boost/iterator/iterator_facade.hpp>
#include <functional>
#include <memory>
@@ -66,8 +65,8 @@ Status VUnionNode::init(const TPlanNode& tnode, RuntimeState* state) {
_const_expr_lists.push_back(ctxs);
}
// Create result_expr_ctx_lists_ from thrift exprs.
- auto& result_texpr_lists = tnode.union_node.result_expr_lists;
- for (auto& texprs : result_texpr_lists) {
+ const auto& result_texpr_lists = tnode.union_node.result_expr_lists;
+ for (const auto& texprs : result_texpr_lists) {
VExprContextSPtrs ctxs;
RETURN_IF_ERROR(VExpr::create_expr_trees(texprs, ctxs));
_child_expr_lists.push_back(ctxs);
@@ -127,7 +126,6 @@ Status VUnionNode::alloc_resource(RuntimeState* state) {
Status VUnionNode::get_next_pass_through(RuntimeState* state, Block* block) {
DCHECK(!reached_limit());
- DCHECK(!is_in_subplan());
DCHECK_LT(_child_idx, _children.size());
DCHECK(is_child_passthrough(_child_idx));
if (_child_eos) {
@@ -196,12 +194,6 @@ Status VUnionNode::get_next_materialized(RuntimeState* state, Block* block) {
// incremented '_num_rows_returned' yet.
DCHECK(!reached_limit());
if (_child_eos) {
- // Unless we are inside a subplan expecting to call open()/get_next() on the child
- // again, the child can be closed at this point.
- // TODO: Recheck whether is_in_subplan() is right
- // if (!is_in_subplan()) {
- // child(_child_idx)->close(state);
- // }
++_child_idx;
}
}
@@ -275,7 +267,6 @@ Status VUnionNode::get_next(RuntimeState* state, Block* block, bool* eos) {
// The previous child needs to be closed if passthrough was enabled for it. In the non
// passthrough case, the child was already closed in the previous call to get_next().
DCHECK(is_child_passthrough(_to_close_child_idx));
- DCHECK(!is_in_subplan());
static_cast<void>(child(_to_close_child_idx)->close(state));
_to_close_child_idx = -1;
}
@@ -317,8 +308,8 @@ void VUnionNode::debug_string(int indentation_level, std::stringstream* out) con
*out << string(indentation_level * 2, ' ');
*out << "_union(_first_materialized_child_idx=" << _first_materialized_child_idx
<< " _child_expr_lists=[";
- for (int i = 0; i < _child_expr_lists.size(); ++i) {
- *out << VExpr::debug_string(_child_expr_lists[i]) << ", ";
+ for (const auto& _child_expr_list : _child_expr_lists) {
+ *out << VExpr::debug_string(_child_expr_list) << ", ";
}
*out << "] \n";
ExecNode::debug_string(indentation_level, out);
@@ -329,9 +320,9 @@ Status VUnionNode::materialize_block(Block* src_block, int child_idx, Block* res
SCOPED_TIMER(_exec_timer);
const auto& child_exprs = _child_expr_lists[child_idx];
ColumnsWithTypeAndName colunms;
- for (size_t i = 0; i < child_exprs.size(); ++i) {
+ for (const auto& child_expr : child_exprs) {
int result_column_id = -1;
- RETURN_IF_ERROR(child_exprs[i]->execute(src_block, &result_column_id));
+ RETURN_IF_ERROR(child_expr->execute(src_block, &result_column_id));
colunms.emplace_back(src_block->get_by_position(result_column_id));
}
_child_row_idx += src_block->rows();
diff --git a/be/src/vec/exprs/vbitmap_predicate.cpp b/be/src/vec/exprs/vbitmap_predicate.cpp
index 0e158298d85..8116311247b 100644
--- a/be/src/vec/exprs/vbitmap_predicate.cpp
+++ b/be/src/vec/exprs/vbitmap_predicate.cpp
@@ -66,19 +66,23 @@ doris::Status vectorized::VBitmapPredicate::prepare(doris::RuntimeState* state,
auto column = child->data_type()->create_column();
argument_template.emplace_back(std::move(column), child->data_type(), child->expr_name());
}
+ _prepare_finished = true;
return Status::OK();
}
doris::Status vectorized::VBitmapPredicate::open(doris::RuntimeState* state,
vectorized::VExprContext* context,
FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
return Status::OK();
}
doris::Status vectorized::VBitmapPredicate::execute(vectorized::VExprContext* context,
doris::vectorized::Block* block,
int* result_column_id) {
+ DCHECK(_open_finished || _getting_const_col);
doris::vectorized::ColumnNumbers arguments(_children.size());
for (int i = 0; i < _children.size(); ++i) {
int column_id = -1;
diff --git a/be/src/vec/exprs/vbloom_predicate.cpp b/be/src/vec/exprs/vbloom_predicate.cpp
index f72657c528a..08f891b0e56 100644
--- a/be/src/vec/exprs/vbloom_predicate.cpp
+++ b/be/src/vec/exprs/vbloom_predicate.cpp
@@ -60,12 +60,15 @@ Status VBloomPredicate::prepare(RuntimeState* state, const RowDescriptor& desc,
}
_be_exec_version = state->be_exec_version();
+ _prepare_finished = true;
return Status::OK();
}
Status VBloomPredicate::open(RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
return Status::OK();
}
@@ -74,6 +77,7 @@ void VBloomPredicate::close(VExprContext* context, FunctionContext::FunctionStat
}
Status VBloomPredicate::execute(VExprContext* context, Block* block, int* result_column_id) {
+ DCHECK(_open_finished || _getting_const_col);
doris::vectorized::ColumnNumbers arguments(_children.size());
for (int i = 0; i < _children.size(); ++i) {
int column_id = -1;
diff --git a/be/src/vec/exprs/vcase_expr.cpp b/be/src/vec/exprs/vcase_expr.cpp
index e09d62bfb23..dee60b5a6f1 100644
--- a/be/src/vec/exprs/vcase_expr.cpp
+++ b/be/src/vec/exprs/vcase_expr.cpp
@@ -74,22 +74,26 @@ Status VCaseExpr::prepare(RuntimeState* state, const RowDescriptor& desc, VExprC
}
VExpr::register_function_context(state, context);
+ _prepare_finished = true;
return Status::OK();
}
Status VCaseExpr::open(RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope) {
- for (int i = 0; i < _children.size(); ++i) {
- RETURN_IF_ERROR(_children[i]->open(state, context, scope));
+ DCHECK(_prepare_finished);
+ for (auto& i : _children) {
+ RETURN_IF_ERROR(i->open(state, context, scope));
}
RETURN_IF_ERROR(VExpr::init_function_context(context, scope, _function));
if (scope == FunctionContext::FRAGMENT_LOCAL) {
RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
}
+ _open_finished = true;
return Status::OK();
}
void VCaseExpr::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
VExpr::close_function_context(context, scope, _function);
VExpr::close(context, scope);
}
@@ -98,6 +102,7 @@ Status VCaseExpr::execute(VExprContext* context, Block* block, int* result_colum
if (is_const_and_have_executed()) { // const have execute in open function
return get_result_from_const(block, _expr_name, result_column_id);
}
+ DCHECK(_open_finished || _getting_const_col);
ColumnNumbers arguments(_children.size());
for (int i = 0; i < _children.size(); i++) {
int column_id = -1;
diff --git a/be/src/vec/exprs/vcast_expr.cpp b/be/src/vec/exprs/vcast_expr.cpp
index 3207ba5b541..f322c1d2fae 100644
--- a/be/src/vec/exprs/vcast_expr.cpp
+++ b/be/src/vec/exprs/vcast_expr.cpp
@@ -76,6 +76,7 @@ doris::Status VCastExpr::prepare(doris::RuntimeState* state, const doris::RowDes
VExpr::register_function_context(state, context);
_expr_name = fmt::format("(CAST {}({}) TO {})", child_name, child->data_type()->get_name(),
_target_data_type_name);
+ _prepare_finished = true;
return Status::OK();
}
@@ -85,6 +86,7 @@ const DataTypePtr& VCastExpr::get_target_type() const {
doris::Status VCastExpr::open(doris::RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
for (int i = 0; i < _children.size(); ++i) {
RETURN_IF_ERROR(_children[i]->open(state, context, scope));
}
@@ -92,6 +94,7 @@ doris::Status VCastExpr::open(doris::RuntimeState* state, VExprContext* context,
if (scope == FunctionContext::FRAGMENT_LOCAL) {
RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
}
+ _open_finished = true;
return Status::OK();
}
@@ -102,6 +105,7 @@ void VCastExpr::close(VExprContext* context, FunctionContext::FunctionStateScope
doris::Status VCastExpr::execute(VExprContext* context, doris::vectorized::Block* block,
int* result_column_id) {
+ DCHECK(_open_finished || _getting_const_col);
// for each child call execute
int column_id = 0;
RETURN_IF_ERROR(_children[0]->execute(context, block, &column_id));
diff --git a/be/src/vec/exprs/vcolumn_ref.h b/be/src/vec/exprs/vcolumn_ref.h
index 25e35dec4a5..a763797880e 100644
--- a/be/src/vec/exprs/vcolumn_ref.h
+++ b/be/src/vec/exprs/vcolumn_ref.h
@@ -43,10 +43,20 @@ public:
"VColumnRef have invalid slot id: {}, _column_name: {}, desc: {}", _column_id,
_column_name, desc.debug_string());
}
+ _prepare_finished = true;
+ return Status::OK();
+ }
+
+ Status open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) override {
+ DCHECK(_prepare_finished);
+ RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
return Status::OK();
}
Status execute(VExprContext* context, Block* block, int* result_column_id) override {
+ DCHECK(_open_finished || _getting_const_col);
*result_column_id = _column_id;
return Status::OK();
}
diff --git a/be/src/vec/exprs/vdirect_in_predicate.h b/be/src/vec/exprs/vdirect_in_predicate.h
index 5211e013466..a68a6c3121a 100644
--- a/be/src/vec/exprs/vdirect_in_predicate.h
+++ b/be/src/vec/exprs/vdirect_in_predicate.h
@@ -18,6 +18,7 @@
#pragma once
#include "common/status.h"
+#include "exprs/hybrid_set.h"
#include "vec/exprs/vexpr.h"
namespace doris::vectorized {
@@ -29,7 +30,23 @@ public:
: VExpr(node), _filter(nullptr), _expr_name("direct_in_predicate") {}
~VDirectInPredicate() override = default;
+ Status prepare(RuntimeState* state, const RowDescriptor& row_desc,
+ VExprContext* context) override {
+ RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, row_desc, context));
+ _prepare_finished = true;
+ return Status::OK();
+ }
+
+ Status open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) override {
+ DCHECK(_prepare_finished);
+ RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
+ return Status::OK();
+ }
+
Status execute(VExprContext* context, Block* block, int* result_column_id) override {
+ DCHECK(_open_finished || _getting_const_col);
ColumnNumbers arguments(_children.size());
for (int i = 0; i < _children.size(); ++i) {
int column_id = -1;
@@ -47,7 +64,7 @@ public:
if (argument_column->is_nullable()) {
auto column_nested = static_cast<const ColumnNullable*>(argument_column.get())
->get_nested_column_ptr();
- auto& null_map =
+ const auto& null_map =
static_cast<const ColumnNullable*>(argument_column.get())->get_null_map_data();
_filter->find_batch_nullable(*column_nested, sz, null_map, res_data_column->get_data());
} else {
diff --git a/be/src/vec/exprs/vectorized_fn_call.cpp b/be/src/vec/exprs/vectorized_fn_call.cpp
index 48522b35500..bf38185f7df 100644
--- a/be/src/vec/exprs/vectorized_fn_call.cpp
+++ b/be/src/vec/exprs/vectorized_fn_call.cpp
@@ -21,8 +21,6 @@
#include <fmt/ranges.h> // IWYU pragma: keep
#include <gen_cpp/Types_types.h>
-#include <algorithm>
-#include <memory>
#include <ostream>
#include <string_view>
#include <utility>
@@ -115,19 +113,21 @@ Status VectorizedFnCall::prepare(RuntimeState* state, const RowDescriptor& desc,
VExpr::register_function_context(state, context);
_function_name = _fn.name.function_name;
_can_fast_execute = _function->can_fast_execute();
-
+ _prepare_finished = true;
return Status::OK();
}
Status VectorizedFnCall::open(RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope) {
- for (int i = 0; i < _children.size(); ++i) {
- RETURN_IF_ERROR(_children[i]->open(state, context, scope));
+ DCHECK(_prepare_finished);
+ for (auto& i : _children) {
+ RETURN_IF_ERROR(i->open(state, context, scope));
}
RETURN_IF_ERROR(VExpr::init_function_context(context, scope, _function));
if (scope == FunctionContext::FRAGMENT_LOCAL) {
RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
}
+ _open_finished = true;
return Status::OK();
}
@@ -142,6 +142,7 @@ Status VectorizedFnCall::execute(VExprContext* context, vectorized::Block* block
return get_result_from_const(block, _expr_name, result_column_id);
}
+ DCHECK(_open_finished || _getting_const_col) << debug_string();
// TODO: not execute const expr again, but use the const column in function context
vectorized::ColumnNumbers arguments(_children.size());
for (int i = 0; i < _children.size(); ++i) {
@@ -188,9 +189,9 @@ bool VectorizedFnCall::fast_execute(FunctionContext* context, Block& block,
block.get_by_name(result_column_name).column->convert_to_full_column_if_const();
auto& result_info = block.get_by_position(result);
if (result_info.type->is_nullable()) {
- block.replace_by_position(result,
- ColumnNullable::create(std::move(result_column),
- ColumnUInt8::create(input_rows_count, 0)));
+ block.replace_by_position(
+ result,
+ ColumnNullable::create(result_column, ColumnUInt8::create(input_rows_count, 0)));
} else {
block.replace_by_position(result, std::move(result_column));
}
@@ -208,7 +209,7 @@ std::string VectorizedFnCall::debug_string() const {
out << _expr_name;
out << "]{";
bool first = true;
- for (auto& input_expr : children()) {
+ for (const auto& input_expr : children()) {
if (first) {
first = false;
} else {
diff --git a/be/src/vec/exprs/vexpr.cpp b/be/src/vec/exprs/vexpr.cpp
index 7270126e563..4f6b984e8fc 100644
--- a/be/src/vec/exprs/vexpr.cpp
+++ b/be/src/vec/exprs/vexpr.cpp
@@ -17,6 +17,7 @@
#include "vec/exprs/vexpr.h"
+#include <fmt/format.h>
#include <gen_cpp/Exprs_types.h>
#include <thrift/protocol/TDebugProtocol.h>
@@ -27,7 +28,6 @@
#include "common/config.h"
#include "common/exception.h"
-#include "common/object_pool.h"
#include "common/status.h"
#include "vec/columns/column_vector.h"
#include "vec/columns/columns_number.h"
@@ -40,6 +40,7 @@
#include "vec/exprs/vcompound_pred.h"
#include "vec/exprs/vectorized_fn_call.h"
#include "vec/exprs/vexpr_context.h"
+#include "vec/exprs/vexpr_fwd.h"
#include "vec/exprs/vin_predicate.h"
#include "vec/exprs/vinfo_func.h"
#include "vec/exprs/vlambda_function_call_expr.h"
@@ -55,6 +56,9 @@
namespace doris {
class RowDescriptor;
class RuntimeState;
+
+// NOLINTBEGIN(readability-function-cognitive-complexity)
+// NOLINTBEGIN(readability-function-size)
TExprNode create_texpr_node_from(const void* data, const PrimitiveType& type, int precision,
int scale) {
TExprNode node;
@@ -146,6 +150,8 @@ TExprNode create_texpr_node_from(const void* data, const PrimitiveType& type, in
}
return node;
}
+// NOLINTEND(readability-function-size)
+// NOLINTEND(readability-function-cognitive-complexity)
} // namespace doris
namespace doris::vectorized {
@@ -162,9 +168,7 @@ bool VExpr::is_acting_on_a_slot(const VExpr& expr) {
VExpr::VExpr(const TExprNode& node)
: _node_type(node.node_type),
_opcode(node.__isset.opcode ? node.opcode : TExprOpcode::INVALID_OPCODE),
- _type(TypeDescriptor::from_thrift(node.type)),
- _fn_context_index(-1),
- _prepared(false) {
+ _type(TypeDescriptor::from_thrift(node.type)) {
if (node.__isset.fn) {
_fn = node.fn;
}
@@ -183,10 +187,7 @@ VExpr::VExpr(const TExprNode& node)
VExpr::VExpr(const VExpr& vexpr) = default;
VExpr::VExpr(TypeDescriptor type, bool is_slotref, bool is_nullable)
- : _opcode(TExprOpcode::INVALID_OPCODE),
- _type(std::move(type)),
- _fn_context_index(-1),
- _prepared(false) {
+ : _opcode(TExprOpcode::INVALID_OPCODE), _type(std::move(type)) {
if (is_slotref) {
_node_type = TExprNodeType::SLOT_REF;
}
@@ -221,11 +222,12 @@ Status VExpr::open(RuntimeState* state, VExprContext* context,
}
void VExpr::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
- for (int i = 0; i < _children.size(); ++i) {
- _children[i]->close(context, scope);
+ for (auto& i : _children) {
+ i->close(context, scope);
}
}
+// NOLINTBEGIN(readability-function-size)
Status VExpr::create_expr(const TExprNode& expr_node, VExprSPtr& expr) {
try {
switch (expr_node.node_type) {
@@ -326,6 +328,7 @@ Status VExpr::create_expr(const TExprNode& expr_node, VExprSPtr& expr) {
}
return Status::OK();
}
+// NOLINTEND(readability-function-size)
Status VExpr::create_tree_from_thrift(const std::vector<TExprNode>& nodes, int* node_idx,
VExprSPtr& root_expr, VExprContextSPtr& ctx) {
@@ -348,7 +351,7 @@ Status VExpr::create_tree_from_thrift(const std::vector<TExprNode>& nodes, int*
// non-recursive traversal
std::stack<std::pair<VExprSPtr, int>> s;
- s.push({root, root_children});
+ s.emplace(root, root_children);
while (!s.empty()) {
auto& parent = s.top();
if (parent.second > 1) {
@@ -366,14 +369,14 @@ Status VExpr::create_tree_from_thrift(const std::vector<TExprNode>& nodes, int*
parent.first->add_child(expr);
int num_children = nodes[*node_idx].num_children;
if (num_children > 0) {
- s.push({expr, num_children});
+ s.emplace(expr, num_children);
}
}
return Status::OK();
}
Status VExpr::create_expr_tree(const TExpr& texpr, VExprContextSPtr& ctx) {
- if (texpr.nodes.size() == 0) {
+ if (texpr.nodes.empty()) {
ctx = nullptr;
return Status::OK();
}
@@ -395,9 +398,9 @@ Status VExpr::create_expr_tree(const TExpr& texpr, VExprContextSPtr& ctx) {
Status VExpr::create_expr_trees(const std::vector<TExpr>& texprs, VExprContextSPtrs& ctxs) {
ctxs.clear();
- for (int i = 0; i < texprs.size(); ++i) {
+ for (const auto& texpr : texprs) {
VExprContextSPtr ctx;
- RETURN_IF_ERROR(create_expr_tree(texprs[i], ctx));
+ RETURN_IF_ERROR(create_expr_tree(texpr, ctx));
ctxs.push_back(ctx);
}
return Status::OK();
@@ -412,8 +415,8 @@ Status VExpr::prepare(const VExprContextSPtrs& ctxs, RuntimeState* state,
}
Status VExpr::open(const VExprContextSPtrs& ctxs, RuntimeState* state) {
- for (int i = 0; i < ctxs.size(); ++i) {
- RETURN_IF_ERROR(ctxs[i]->open(state));
+ for (const auto& ctx : ctxs) {
+ RETURN_IF_ERROR(ctx->open(state));
}
return Status::OK();
}
@@ -423,8 +426,8 @@ Status VExpr::clone_if_not_exists(const VExprContextSPtrs& ctxs, RuntimeState* s
if (!new_ctxs.empty()) {
// 'ctxs' was already cloned into '*new_ctxs', nothing to do.
DCHECK_EQ(new_ctxs.size(), ctxs.size());
- for (int i = 0; i < new_ctxs.size(); ++i) {
- DCHECK(new_ctxs[i]->_is_clone);
+ for (auto& new_ctx : new_ctxs) {
+ DCHECK(new_ctx->_is_clone);
}
return Status::OK();
}
@@ -461,20 +464,15 @@ std::string VExpr::debug_string(const VExprSPtrs& exprs) {
std::string VExpr::debug_string(const VExprContextSPtrs& ctxs) {
VExprSPtrs exprs;
- for (int i = 0; i < ctxs.size(); ++i) {
- exprs.push_back(ctxs[i]->root());
+ for (const auto& ctx : ctxs) {
+ exprs.push_back(ctx->root());
}
return debug_string(exprs);
}
bool VExpr::is_constant() const {
- for (int i = 0; i < _children.size(); ++i) {
- if (!_children[i]->is_constant()) {
- return false;
- }
- }
-
- return true;
+ return std::all_of(_children.begin(), _children.end(),
+ [](const VExprSPtr& expr) { return expr->is_constant(); });
}
Status VExpr::get_const_col(VExprContext* context,
@@ -494,7 +492,11 @@ Status VExpr::get_const_col(VExprContext* context,
// If block is empty, some functions will produce no result. So we insert a column with
// single value here.
block.insert({ColumnUInt8::create(1), std::make_shared<DataTypeUInt8>(), ""});
+
+ _getting_const_col = true;
RETURN_IF_ERROR(execute(context, &block, &result));
+ _getting_const_col = false;
+
DCHECK(result != -1);
const auto& column = block.get_by_position(result).column;
_constant_col = std::make_shared<ColumnPtrWrapper>(column);
@@ -507,8 +509,8 @@ Status VExpr::get_const_col(VExprContext* context,
void VExpr::register_function_context(RuntimeState* state, VExprContext* context) {
std::vector<TypeDescriptor> arg_types;
- for (int i = 0; i < _children.size(); ++i) {
- arg_types.push_back(_children[i]->type());
+ for (auto& i : _children) {
+ arg_types.push_back(i->type());
}
_fn_context_index = context->register_function_context(state, _type, arg_types);
diff --git a/be/src/vec/exprs/vexpr.h b/be/src/vec/exprs/vexpr.h
index b6a2b4ac6bd..a852afeb2d2 100644
--- a/be/src/vec/exprs/vexpr.h
+++ b/be/src/vec/exprs/vexpr.h
@@ -21,15 +21,14 @@
#include <gen_cpp/Opcodes_types.h>
#include <gen_cpp/Types_types.h>
#include <glog/logging.h>
-#include <stddef.h>
+#include <cstddef>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
-#include "common/factory_creator.h"
#include "common/status.h"
#include "runtime/define_primitive_type.h"
#include "runtime/large_int_value.h"
@@ -57,10 +56,9 @@ namespace vectorized {
#define RETURN_IF_ERROR_OR_PREPARED(stmt) \
if (_prepared) { \
return Status::OK(); \
- } else { \
- _prepared = true; \
- RETURN_IF_ERROR(stmt); \
- }
+ } \
+ _prepared = true; \
+ RETURN_IF_ERROR(stmt);
// VExpr should be used as shared pointer because it will be passed between classes
// like runtime filter to scan node, or from scannode to scanner. We could not make sure
@@ -106,6 +104,14 @@ public:
virtual Status open(RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope);
+ // before execute, check if expr has been parepared+opened.
+ [[maybe_unused]] Status ready_status() const {
+ if (_prepare_finished && _open_finished) {
+ return Status::OK();
+ }
+ return Status::InternalError(expr_name() + " is not ready when execute");
+ }
+
virtual Status execute(VExprContext* context, Block* block, int* result_column_id) = 0;
/// Subclasses overriding this function should call VExpr::Close().
@@ -156,6 +162,8 @@ public:
static std::string debug_string(const VExprSPtrs& exprs);
static std::string debug_string(const VExprContextSPtrs& ctxs);
+ void set_getting_const_col(bool val = true) { _getting_const_col = val; }
+
bool is_and_expr() const { return _fn.name.function_name == "and"; }
virtual bool is_compound_predicate() const { return false; }
@@ -254,63 +262,69 @@ protected:
/// Index to pass to ExprContext::fn_context() to retrieve this expr's FunctionContext.
/// Set in RegisterFunctionContext(). -1 if this expr does not need a FunctionContext and
/// doesn't call RegisterFunctionContext().
- int _fn_context_index;
+ int _fn_context_index = -1;
// If this expr is constant, this will store and cache the value generated by
// get_const_col()
std::shared_ptr<ColumnPtrWrapper> _constant_col;
- bool _prepared;
+ bool _prepared = false; // for base class VExpr
+ bool _getting_const_col =
+ false; // if true, current execute() is in prepare() (that is, can't check _prepared)
+ // for concrete classes
+ bool _prepare_finished = false;
+ bool _open_finished = false;
};
} // namespace vectorized
+// NOLINTBEGIN(readability-function-size)
template <PrimitiveType T>
Status create_texpr_literal_node(const void* data, TExprNode* node, int precision = 0,
int scale = 0) {
if constexpr (T == TYPE_BOOLEAN) {
- auto origin_value = reinterpret_cast<const bool*>(data);
+ const auto* origin_value = reinterpret_cast<const bool*>(data);
TBoolLiteral boolLiteral;
(*node).__set_node_type(TExprNodeType::BOOL_LITERAL);
boolLiteral.__set_value(*origin_value);
(*node).__set_bool_literal(boolLiteral);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
} else if constexpr (T == TYPE_TINYINT) {
- auto origin_value = reinterpret_cast<const int8_t*>(data);
+ const auto* origin_value = reinterpret_cast<const int8_t*>(data);
(*node).__set_node_type(TExprNodeType::INT_LITERAL);
TIntLiteral intLiteral;
intLiteral.__set_value(*origin_value);
(*node).__set_int_literal(intLiteral);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_TINYINT));
} else if constexpr (T == TYPE_SMALLINT) {
- auto origin_value = reinterpret_cast<const int16_t*>(data);
+ const auto* origin_value = reinterpret_cast<const int16_t*>(data);
(*node).__set_node_type(TExprNodeType::INT_LITERAL);
TIntLiteral intLiteral;
intLiteral.__set_value(*origin_value);
(*node).__set_int_literal(intLiteral);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_SMALLINT));
} else if constexpr (T == TYPE_INT) {
- auto origin_value = reinterpret_cast<const int32_t*>(data);
+ const auto* origin_value = reinterpret_cast<const int32_t*>(data);
(*node).__set_node_type(TExprNodeType::INT_LITERAL);
TIntLiteral intLiteral;
intLiteral.__set_value(*origin_value);
(*node).__set_int_literal(intLiteral);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_INT));
} else if constexpr (T == TYPE_BIGINT) {
- auto origin_value = reinterpret_cast<const int64_t*>(data);
+ const auto* origin_value = reinterpret_cast<const int64_t*>(data);
(*node).__set_node_type(TExprNodeType::INT_LITERAL);
TIntLiteral intLiteral;
intLiteral.__set_value(*origin_value);
(*node).__set_int_literal(intLiteral);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_BIGINT));
} else if constexpr (T == TYPE_LARGEINT) {
- auto origin_value = reinterpret_cast<const int128_t*>(data);
+ const auto* origin_value = reinterpret_cast<const int128_t*>(data);
(*node).__set_node_type(TExprNodeType::LARGE_INT_LITERAL);
TLargeIntLiteral large_int_literal;
large_int_literal.__set_value(LargeIntValue::to_string(*origin_value));
(*node).__set_large_int_literal(large_int_literal);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_LARGEINT));
} else if constexpr ((T == TYPE_DATE) || (T == TYPE_DATETIME) || (T == TYPE_TIME)) {
- auto origin_value = reinterpret_cast<const VecDateTimeValue*>(data);
+ const auto* origin_value = reinterpret_cast<const VecDateTimeValue*>(data);
TDateLiteral date_literal;
char convert_buffer[30];
origin_value->to_string(convert_buffer);
@@ -325,7 +339,7 @@ Status create_texpr_literal_node(const void* data, TExprNode* node, int precisio
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_TIME));
}
} else if constexpr (T == TYPE_DATEV2) {
- auto origin_value = reinterpret_cast<const DateV2Value<DateV2ValueType>*>(data);
+ const auto* origin_value = reinterpret_cast<const DateV2Value<DateV2ValueType>*>(data);
TDateLiteral date_literal;
char convert_buffer[30];
origin_value->to_string(convert_buffer);
@@ -334,7 +348,7 @@ Status create_texpr_literal_node(const void* data, TExprNode* node, int precisio
(*node).__set_node_type(TExprNodeType::DATE_LITERAL);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_DATEV2));
} else if constexpr (T == TYPE_DATETIMEV2) {
- auto origin_value = reinterpret_cast<const DateV2Value<DateTimeV2ValueType>*>(data);
+ const auto* origin_value = reinterpret_cast<const DateV2Value<DateTimeV2ValueType>*>(data);
TDateLiteral date_literal;
char convert_buffer[30];
origin_value->to_string(convert_buffer);
@@ -343,28 +357,28 @@ Status create_texpr_literal_node(const void* data, TExprNode* node, int precisio
(*node).__set_node_type(TExprNodeType::DATE_LITERAL);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_DATETIMEV2));
} else if constexpr (T == TYPE_DECIMALV2) {
- auto origin_value = reinterpret_cast<const DecimalV2Value*>(data);
+ const auto* origin_value = reinterpret_cast<const DecimalV2Value*>(data);
(*node).__set_node_type(TExprNodeType::DECIMAL_LITERAL);
TDecimalLiteral decimal_literal;
decimal_literal.__set_value(origin_value->to_string());
(*node).__set_decimal_literal(decimal_literal);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_DECIMALV2, precision, scale));
} else if constexpr (T == TYPE_DECIMAL32) {
- auto origin_value = reinterpret_cast<const vectorized::Decimal<int32_t>*>(data);
+ const auto* origin_value = reinterpret_cast<const vectorized::Decimal<int32_t>*>(data);
(*node).__set_node_type(TExprNodeType::DECIMAL_LITERAL);
TDecimalLiteral decimal_literal;
decimal_literal.__set_value(origin_value->to_string(scale));
(*node).__set_decimal_literal(decimal_literal);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_DECIMAL32, precision, scale));
} else if constexpr (T == TYPE_DECIMAL64) {
- auto origin_value = reinterpret_cast<const vectorized::Decimal<int64_t>*>(data);
+ const auto* origin_value = reinterpret_cast<const vectorized::Decimal<int64_t>*>(data);
(*node).__set_node_type(TExprNodeType::DECIMAL_LITERAL);
TDecimalLiteral decimal_literal;
decimal_literal.__set_value(origin_value->to_string(scale));
(*node).__set_decimal_literal(decimal_literal);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_DECIMAL64, precision, scale));
} else if constexpr (T == TYPE_DECIMAL128I) {
- auto origin_value = reinterpret_cast<const vectorized::Decimal<int128_t>*>(data);
+ const auto* origin_value = reinterpret_cast<const vectorized::Decimal<int128_t>*>(data);
(*node).__set_node_type(TExprNodeType::DECIMAL_LITERAL);
TDecimalLiteral decimal_literal;
decimal_literal.__set_value(origin_value->to_string(scale));
@@ -378,21 +392,21 @@ Status create_texpr_literal_node(const void* data, TExprNode* node, int precisio
(*node).__set_decimal_literal(decimal_literal);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_DECIMAL256, precision, scale));
} else if constexpr (T == TYPE_FLOAT) {
- auto origin_value = reinterpret_cast<const float*>(data);
+ const auto* origin_value = reinterpret_cast<const float*>(data);
(*node).__set_node_type(TExprNodeType::FLOAT_LITERAL);
TFloatLiteral float_literal;
float_literal.__set_value(*origin_value);
(*node).__set_float_literal(float_literal);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_FLOAT));
} else if constexpr (T == TYPE_DOUBLE) {
- auto origin_value = reinterpret_cast<const double*>(data);
+ const auto* origin_value = reinterpret_cast<const double*>(data);
(*node).__set_node_type(TExprNodeType::FLOAT_LITERAL);
TFloatLiteral float_literal;
float_literal.__set_value(*origin_value);
(*node).__set_float_literal(float_literal);
(*node).__set_type(create_type_desc(PrimitiveType::TYPE_DOUBLE));
} else if constexpr ((T == TYPE_STRING) || (T == TYPE_CHAR) || (T == TYPE_VARCHAR)) {
- auto origin_value = reinterpret_cast<const StringRef*>(data);
+ const auto* origin_value = reinterpret_cast<const StringRef*>(data);
(*node).__set_node_type(TExprNodeType::STRING_LITERAL);
TStringLiteral string_literal;
string_literal.__set_value(origin_value->to_string());
@@ -403,6 +417,7 @@ Status create_texpr_literal_node(const void* data, TExprNode* node, int precisio
}
return Status::OK();
}
+// NOLINTEND(readability-function-size)
TExprNode create_texpr_node_from(const void* data, const PrimitiveType& type, int precision = 0,
int scale = 0);
diff --git a/be/src/vec/exprs/vexpr_context.cpp b/be/src/vec/exprs/vexpr_context.cpp
index 35eaae5c607..cebb7dd2e53 100644
--- a/be/src/vec/exprs/vexpr_context.cpp
+++ b/be/src/vec/exprs/vexpr_context.cpp
@@ -17,17 +17,14 @@
#include "vec/exprs/vexpr_context.h"
-#include <algorithm>
#include <ostream>
#include <string>
#include "common/compiler_util.h" // IWYU pragma: keep
#include "common/exception.h"
-#include "common/object_pool.h"
#include "runtime/runtime_state.h"
#include "runtime/thread_context.h"
#include "udf/udf.h"
-#include "util/stack_util.h"
#include "vec/columns/column_const.h"
#include "vec/core/column_with_type_and_name.h"
#include "vec/core/columns_with_type_and_name.h"
@@ -38,13 +35,6 @@ class RowDescriptor;
} // namespace doris
namespace doris::vectorized {
-VExprContext::VExprContext(const VExprSPtr& expr)
- : _root(expr),
- _is_clone(false),
- _prepared(false),
- _opened(false),
- _last_result_column_id(-1) {}
-
VExprContext::~VExprContext() {
// In runtime filter, only create expr context to get expr root, will not call
// prepare or open, so that it is not need to call close. And call close may core
@@ -154,19 +144,19 @@ Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
return execute_conjuncts(ctxs, filters, false, block, result_filter, can_filter_all);
}
-// TODO Performance Optimization
+// TODO: Performance Optimization
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
const std::vector<IColumn::Filter*>* filters,
- const bool accept_null, Block* block,
+ bool accept_null, Block* block,
IColumn::Filter* result_filter, bool* can_filter_all) {
DCHECK(result_filter->size() == block->rows());
*can_filter_all = false;
auto* __restrict result_filter_data = result_filter->data();
- for (auto& ctx : ctxs) {
+ for (const auto& ctx : ctxs) {
int result_column_id = -1;
RETURN_IF_ERROR(ctx->execute(block, &result_column_id));
ColumnPtr& filter_column = block->get_by_position(result_column_id).column;
- if (auto* nullable_column = check_and_get_column<ColumnNullable>(*filter_column)) {
+ if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*filter_column)) {
size_t column_size = nullable_column->size();
if (column_size == 0) {
*can_filter_all = true;
@@ -175,9 +165,9 @@ Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
const ColumnPtr& nested_column = nullable_column->get_nested_column_ptr();
const IColumn::Filter& filter =
assert_cast<const ColumnUInt8&>(*nested_column).get_data();
- auto* __restrict filter_data = filter.data();
+ const auto* __restrict filter_data = filter.data();
const size_t size = filter.size();
- auto* __restrict null_map_data = nullable_column->get_null_map_data().data();
+ const auto* __restrict null_map_data = nullable_column->get_null_map_data().data();
if (accept_null) {
for (size_t i = 0; i < size; ++i) {
@@ -194,7 +184,7 @@ Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
return Status::OK();
}
}
- } else if (auto* const_column = check_and_get_column<ColumnConst>(*filter_column)) {
+ } else if (const auto* const_column = check_and_get_column<ColumnConst>(*filter_column)) {
// filter all
if (!const_column->get_bool(0)) {
*can_filter_all = true;
@@ -204,7 +194,7 @@ Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
} else {
const IColumn::Filter& filter =
assert_cast<const ColumnUInt8&>(*filter_column).get_data();
- auto* __restrict filter_data = filter.data();
+ const auto* __restrict filter_data = filter.data();
const size_t size = filter.size();
for (size_t i = 0; i < size; ++i) {
@@ -297,7 +287,7 @@ Status VExprContext::get_output_block_after_execute_exprs(
auto rows = input_block.rows();
vectorized::Block tmp_block(input_block.get_columns_with_type_and_name());
vectorized::ColumnsWithTypeAndName result_columns;
- for (auto& vexpr_ctx : output_vexpr_ctxs) {
+ for (const auto& vexpr_ctx : output_vexpr_ctxs) {
int result_column_id = -1;
RETURN_IF_ERROR(vexpr_ctx->execute(&tmp_block, &result_column_id));
DCHECK(result_column_id != -1);
diff --git a/be/src/vec/exprs/vexpr_context.h b/be/src/vec/exprs/vexpr_context.h
index db5c4c87d8d..70bd37b1878 100644
--- a/be/src/vec/exprs/vexpr_context.h
+++ b/be/src/vec/exprs/vexpr_context.h
@@ -20,6 +20,7 @@
#include <glog/logging.h>
#include <memory>
+#include <utility>
#include <vector>
#include "common/factory_creator.h"
@@ -40,7 +41,7 @@ class VExprContext {
ENABLE_FACTORY_CREATOR(VExprContext);
public:
- VExprContext(const VExprSPtr& expr);
+ VExprContext(VExprSPtr expr) : _root(std::move(expr)) {}
~VExprContext();
[[nodiscard]] Status prepare(RuntimeState* state, const RowDescriptor& row_desc);
[[nodiscard]] Status open(RuntimeState* state);
@@ -76,7 +77,7 @@ public:
[[nodiscard]] static Status execute_conjuncts(const VExprContextSPtrs& ctxs,
const std::vector<IColumn::Filter*>* filters,
- const bool accept_null, Block* block,
+ bool accept_null, Block* block,
IColumn::Filter* result_filter,
bool* can_filter_all);
@@ -121,7 +122,7 @@ public:
_prepared = other._prepared;
_opened = other._opened;
- for (auto& fn : other._fn_contexts) {
+ for (const auto& fn : other._fn_contexts) {
_fn_contexts.emplace_back(fn->clone());
}
@@ -152,17 +153,17 @@ private:
VExprSPtr _root;
/// True if this context came from a Clone() call. Used to manage FunctionStateScope.
- bool _is_clone;
+ bool _is_clone = false;
/// Variables keeping track of current state.
- bool _prepared;
- bool _opened;
+ bool _prepared = false;
+ bool _opened = false;
/// FunctionContexts for each registered expression. The FunctionContexts are created
/// and owned by this VExprContext.
std::vector<std::unique_ptr<FunctionContext>> _fn_contexts;
- int _last_result_column_id;
+ int _last_result_column_id = -1;
/// The depth of expression-tree.
int _depth_num = 0;
diff --git a/be/src/vec/exprs/vin_predicate.cpp b/be/src/vec/exprs/vin_predicate.cpp
index 9a25d3a2230..896b2a903d3 100644
--- a/be/src/vec/exprs/vin_predicate.cpp
+++ b/be/src/vec/exprs/vin_predicate.cpp
@@ -73,11 +73,13 @@ Status VInPredicate::prepare(RuntimeState* state, const RowDescriptor& desc,
}
VExpr::register_function_context(state, context);
+ _prepare_finished = true;
return Status::OK();
}
Status VInPredicate::open(RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
for (int i = 0; i < _children.size(); ++i) {
RETURN_IF_ERROR(_children[i]->open(state, context, scope));
}
@@ -85,6 +87,7 @@ Status VInPredicate::open(RuntimeState* state, VExprContext* context,
if (scope == FunctionContext::FRAGMENT_LOCAL) {
RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
}
+ _open_finished = true;
return Status::OK();
}
@@ -97,6 +100,7 @@ Status VInPredicate::execute(VExprContext* context, Block* block, int* result_co
if (is_const_and_have_executed()) { // const have execute in open function
return get_result_from_const(block, _expr_name, result_column_id);
}
+ DCHECK(_open_finished || _getting_const_col);
// TODO: not execute const expr again, but use the const column in function context
doris::vectorized::ColumnNumbers arguments(_children.size());
for (int i = 0; i < _children.size(); ++i) {
diff --git a/be/src/vec/exprs/vlambda_function_call_expr.h b/be/src/vec/exprs/vlambda_function_call_expr.h
index 44678498027..44d22b1f9eb 100644
--- a/be/src/vec/exprs/vlambda_function_call_expr.h
+++ b/be/src/vec/exprs/vlambda_function_call_expr.h
@@ -34,6 +34,8 @@ public:
VLambdaFunctionCallExpr(const TExprNode& node) : VExpr(node) {}
~VLambdaFunctionCallExpr() override = default;
+ const std::string& expr_name() const override { return _expr_name; }
+
Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override {
RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
@@ -48,12 +50,20 @@ public:
return Status::InternalError("Lambda Function {} is not implemented.",
_fn.name.function_name);
}
+ _prepare_finished = true;
return Status::OK();
}
- const std::string& expr_name() const override { return _expr_name; }
+ Status open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) override {
+ DCHECK(_prepare_finished);
+ RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
+ return Status::OK();
+ }
Status execute(VExprContext* context, Block* block, int* result_column_id) override {
+ DCHECK(_open_finished || _getting_const_col);
return _lambda_function->execute(context, block, result_column_id, _data_type, _children);
}
diff --git a/be/src/vec/exprs/vlambda_function_expr.h b/be/src/vec/exprs/vlambda_function_expr.h
index 6d84abb937f..94571712e40 100644
--- a/be/src/vec/exprs/vlambda_function_expr.h
+++ b/be/src/vec/exprs/vlambda_function_expr.h
@@ -28,7 +28,22 @@ public:
VLambdaFunctionExpr(const TExprNode& node) : VExpr(node) {}
~VLambdaFunctionExpr() override = default;
+ Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override {
+ RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
+ _prepare_finished = true;
+ return Status::OK();
+ }
+
+ Status open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) override {
+ DCHECK(_prepare_finished);
+ RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
+ return Status::OK();
+ }
+
Status execute(VExprContext* context, Block* block, int* result_column_id) override {
+ DCHECK(_open_finished || _getting_const_col);
return get_child(0)->execute(context, block, result_column_id);
}
diff --git a/be/src/vec/exprs/vliteral.cpp b/be/src/vec/exprs/vliteral.cpp
index 03d1659eee6..c7fbb081675 100644
--- a/be/src/vec/exprs/vliteral.cpp
+++ b/be/src/vec/exprs/vliteral.cpp
@@ -47,9 +47,7 @@
#include "vec/data_types/data_type_decimal.h"
#include "vec/runtime/vdatetime_value.h"
-namespace doris {
-
-namespace vectorized {
+namespace doris::vectorized {
class VExprContext;
void VLiteral::init(const TExprNode& node) {
@@ -58,8 +56,20 @@ void VLiteral::init(const TExprNode& node) {
_column_ptr = _data_type->create_column_const(1, field);
}
+Status VLiteral::prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) {
+ RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
+ return Status::OK();
+}
+
+Status VLiteral::open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) {
+ RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ return Status::OK();
+}
+
Status VLiteral::execute(VExprContext* context, vectorized::Block* block, int* result_column_id) {
// Literal expr should return least one row.
+ // sometimes we just use a VLiteral without open or prepare. so can't check it at this moment
size_t row_size = std::max(block->rows(), _column_ptr->size());
*result_column_id = VExpr::insert_param(block, {_column_ptr, _data_type, _expr_name}, row_size);
return Status::OK();
@@ -86,5 +96,4 @@ std::string VLiteral::debug_string() const {
return out.str();
}
-} // namespace vectorized
-} // namespace doris
+} // namespace doris::vectorized
diff --git a/be/src/vec/exprs/vliteral.h b/be/src/vec/exprs/vliteral.h
index 78879c00d04..d443478ada5 100644
--- a/be/src/vec/exprs/vliteral.h
+++ b/be/src/vec/exprs/vliteral.h
@@ -42,7 +42,12 @@ public:
init(node);
}
}
+
+ Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override;
+ Status open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) override;
Status execute(VExprContext* context, Block* block, int* result_column_id) override;
+
const std::string& expr_name() const override { return _expr_name; }
std::string debug_string() const override;
diff --git a/be/src/vec/exprs/vmatch_predicate.cpp b/be/src/vec/exprs/vmatch_predicate.cpp
index 23a34aae5ac..17326b5b23b 100644
--- a/be/src/vec/exprs/vmatch_predicate.cpp
+++ b/be/src/vec/exprs/vmatch_predicate.cpp
@@ -91,12 +91,13 @@ Status VMatchPredicate::prepare(RuntimeState* state, const RowDescriptor& desc,
VExpr::register_function_context(state, context);
_expr_name = fmt::format("{}({})", _fn.name.function_name, child_expr_name);
_function_name = _fn.name.function_name;
-
+ _prepare_finished = true;
return Status::OK();
}
Status VMatchPredicate::open(RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
for (int i = 0; i < _children.size(); ++i) {
RETURN_IF_ERROR(_children[i]->open(state, context, scope));
}
@@ -107,6 +108,7 @@ Status VMatchPredicate::open(RuntimeState* state, VExprContext* context,
if (scope == FunctionContext::FRAGMENT_LOCAL) {
RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
}
+ _open_finished = true;
return Status::OK();
}
@@ -116,6 +118,7 @@ void VMatchPredicate::close(VExprContext* context, FunctionContext::FunctionStat
}
Status VMatchPredicate::execute(VExprContext* context, Block* block, int* result_column_id) {
+ DCHECK(_open_finished || _getting_const_col);
// TODO: not execute const expr again, but use the const column in function context
doris::vectorized::ColumnNumbers arguments(_children.size());
for (int i = 0; i < _children.size(); ++i) {
diff --git a/be/src/vec/exprs/vruntimefilter_wrapper.cpp b/be/src/vec/exprs/vruntimefilter_wrapper.cpp
index 62ef2bbdb64..c623355d673 100644
--- a/be/src/vec/exprs/vruntimefilter_wrapper.cpp
+++ b/be/src/vec/exprs/vruntimefilter_wrapper.cpp
@@ -52,12 +52,16 @@ Status VRuntimeFilterWrapper::prepare(RuntimeState* state, const RowDescriptor&
VExprContext* context) {
RETURN_IF_ERROR_OR_PREPARED(_impl->prepare(state, desc, context));
_expr_name = fmt::format("VRuntimeFilterWrapper({})", _impl->expr_name());
+ _prepare_finished = true;
return Status::OK();
}
Status VRuntimeFilterWrapper::open(RuntimeState* state, VExprContext* context,
FunctionContext::FunctionStateScope scope) {
- return _impl->open(state, context, scope);
+ DCHECK(_prepare_finished);
+ RETURN_IF_ERROR(_impl->open(state, context, scope));
+ _open_finished = true;
+ return Status::OK();
}
void VRuntimeFilterWrapper::close(VExprContext* context,
@@ -66,6 +70,7 @@ void VRuntimeFilterWrapper::close(VExprContext* context,
}
Status VRuntimeFilterWrapper::execute(VExprContext* context, Block* block, int* result_column_id) {
+ DCHECK(_open_finished || _getting_const_col);
if (_always_true) {
auto res_data_column = ColumnVector<UInt8>::create(block->rows(), 1);
size_t num_columns_without_result = block->columns();
@@ -80,7 +85,15 @@ Status VRuntimeFilterWrapper::execute(VExprContext* context, Block* block, int*
return Status::OK();
} else {
_scan_rows += block->rows();
+
+ if (_getting_const_col) {
+ _impl->set_getting_const_col(true);
+ }
RETURN_IF_ERROR(_impl->execute(context, block, result_column_id));
+ if (_getting_const_col) {
+ _impl->set_getting_const_col(false);
+ }
+
uint8_t* data = nullptr;
const ColumnWithTypeAndName& result_column = block->get_by_position(*result_column_id);
if (is_column_const(*result_column.column)) {
diff --git a/be/src/vec/exprs/vslot_ref.cpp b/be/src/vec/exprs/vslot_ref.cpp
index 5a34999accb..b683a1fb156 100644
--- a/be/src/vec/exprs/vslot_ref.cpp
+++ b/be/src/vec/exprs/vslot_ref.cpp
@@ -51,6 +51,7 @@ Status VSlotRef::prepare(doris::RuntimeState* state, const doris::RowDescriptor&
RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
DCHECK_EQ(_children.size(), 0);
if (_slot_id == -1) {
+ _prepare_finished = true;
return Status::OK();
}
const SlotDescriptor* slot_desc = state->desc_tbl().get_slot_descriptor(_slot_id);
@@ -63,6 +64,7 @@ Status VSlotRef::prepare(doris::RuntimeState* state, const doris::RowDescriptor&
if (!context->force_materialize_slot() && !slot_desc->need_materialize()) {
// slot should be ignored manually
_column_id = -1;
+ _prepare_finished = true;
return Status::OK();
}
_column_id = desc.get_column_id(_slot_id, context->force_materialize_slot());
@@ -72,6 +74,15 @@ Status VSlotRef::prepare(doris::RuntimeState* state, const doris::RowDescriptor&
*_column_name, _slot_id, desc.debug_string(), slot_desc->debug_string(),
state->desc_tbl().debug_string());
}
+ _prepare_finished = true;
+ return Status::OK();
+}
+
+Status VSlotRef::open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
+ RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
return Status::OK();
}
diff --git a/be/src/vec/exprs/vslot_ref.h b/be/src/vec/exprs/vslot_ref.h
index 2084ae18715..c30ac64041f 100644
--- a/be/src/vec/exprs/vslot_ref.h
+++ b/be/src/vec/exprs/vslot_ref.h
@@ -38,8 +38,11 @@ class VSlotRef final : public VExpr {
public:
VSlotRef(const TExprNode& node);
VSlotRef(const SlotDescriptor* desc);
- Status execute(VExprContext* context, Block* block, int* result_column_id) override;
Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override;
+ Status open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) override;
+ Status execute(VExprContext* context, Block* block, int* result_column_id) override;
+
const std::string& expr_name() const override;
std::string debug_string() const override;
bool is_constant() const override { return false; }
diff --git a/be/src/vec/exprs/vtuple_is_null_predicate.cpp b/be/src/vec/exprs/vtuple_is_null_predicate.cpp
index b17428bfc00..641e34590a4 100644
--- a/be/src/vec/exprs/vtuple_is_null_predicate.cpp
+++ b/be/src/vec/exprs/vtuple_is_null_predicate.cpp
@@ -48,11 +48,20 @@ Status VTupleIsNullPredicate::prepare(RuntimeState* state, const RowDescriptor&
DCHECK_EQ(0, _children.size());
_column_to_check =
_is_left_null_side ? desc.num_materialized_slots() : desc.num_materialized_slots() + 1;
+ _prepare_finished = true;
+ return Status::OK();
+}
+Status VTupleIsNullPredicate::open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) {
+ DCHECK(_prepare_finished);
+ RETURN_IF_ERROR(VExpr::open(state, context, scope));
+ _open_finished = true;
return Status::OK();
}
Status VTupleIsNullPredicate::execute(VExprContext* context, Block* block, int* result_column_id) {
+ DCHECK(_open_finished || _getting_const_col);
*result_column_id = _column_to_check;
return Status::OK();
}
diff --git a/be/src/vec/exprs/vtuple_is_null_predicate.h b/be/src/vec/exprs/vtuple_is_null_predicate.h
index 9d3b794fb8b..c42e7300d1d 100644
--- a/be/src/vec/exprs/vtuple_is_null_predicate.h
+++ b/be/src/vec/exprs/vtuple_is_null_predicate.h
@@ -42,8 +42,10 @@ class VTupleIsNullPredicate final : public VExpr {
public:
explicit VTupleIsNullPredicate(const TExprNode& node);
~VTupleIsNullPredicate() override = default;
- Status execute(VExprContext* context, Block* block, int* result_column_id) override;
Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override;
+ Status open(RuntimeState* state, VExprContext* context,
+ FunctionContext::FunctionStateScope scope) override;
+ Status execute(VExprContext* context, Block* block, int* result_column_id) override;
[[nodiscard]] bool is_constant() const override { return false; }
diff --git a/be/src/vec/runtime/vdata_stream_recvr.h b/be/src/vec/runtime/vdata_stream_recvr.h
index 141a5c54b64..2da6f9f920b 100644
--- a/be/src/vec/runtime/vdata_stream_recvr.h
+++ b/be/src/vec/runtime/vdata_stream_recvr.h
@@ -20,11 +20,11 @@
#include <gen_cpp/Types_types.h>
#include <glog/logging.h>
#include <google/protobuf/stubs/callback.h>
-#include <stddef.h>
-#include <stdint.h>
#include <atomic>
#include <condition_variable>
+#include <cstddef>
+#include <cstdint>
#include <deque>
#include <list>
#include <memory>
@@ -42,14 +42,10 @@
#include "common/object_pool.h"
#include "common/status.h"
#include "runtime/descriptors.h"
-#include "runtime/query_statistics.h"
#include "runtime/task_execution_context.h"
#include "util/runtime_profile.h"
#include "util/stopwatch.hpp"
-#include "vec/columns/column.h"
#include "vec/core/block.h"
-#include "vec/core/column_with_type_and_name.h"
-#include "vec/core/materialize_block.h"
#include "vec/exprs/vexpr_fwd.h"
namespace doris {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 28/43: [fix](Nereids) nullable not adjust in output exprs in result sink node (#30206)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 8061597f2a09959fc1cbf5a71051dbfc8e9467b0
Author: morrySnow <10...@users.noreply.github.com>
AuthorDate: Mon Jan 22 14:47:18 2024 +0800
[fix](Nereids) nullable not adjust in output exprs in result sink node (#30206)
---
.../java/org/apache/doris/nereids/analyzer/UnboundResultSink.java | 5 +++++
.../java/org/apache/doris/nereids/analyzer/UnboundTableSink.java | 6 ++++++
.../org/apache/doris/nereids/rules/rewrite/AdjustNullable.java | 8 ++++++++
.../trees/plans/logical/LogicalDeferMaterializeResultSink.java | 7 +++++++
.../apache/doris/nereids/trees/plans/logical/LogicalFileSink.java | 2 +-
.../doris/nereids/trees/plans/logical/LogicalOlapTableSink.java | 5 +++++
.../doris/nereids/trees/plans/logical/LogicalResultSink.java | 5 +++++
.../org/apache/doris/nereids/trees/plans/logical/LogicalSink.java | 2 ++
8 files changed, 39 insertions(+), 1 deletion(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundResultSink.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundResultSink.java
index 6f378e99112..10a6b0121e3 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundResultSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundResultSink.java
@@ -21,6 +21,7 @@ import org.apache.doris.nereids.exceptions.UnboundException;
import org.apache.doris.nereids.memo.GroupExpression;
import org.apache.doris.nereids.properties.LogicalProperties;
import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.plans.BlockFuncDepsPropagation;
import org.apache.doris.nereids.trees.plans.Plan;
@@ -77,7 +78,11 @@ public class UnboundResultSink<CHILD_TYPE extends Plan> extends LogicalSink<CHIL
Optional<LogicalProperties> logicalProperties, List<Plan> children) {
Preconditions.checkArgument(children.size() == 1, "UnboundResultSink only accepts one child");
return new UnboundResultSink<>(groupExpression, logicalProperties, children.get(0));
+ }
+ @Override
+ public UnboundResultSink<CHILD_TYPE> withOutputExprs(List<NamedExpression> outputExprs) {
+ throw new UnboundException("could not call withOutputExprs on UnboundResultSink");
}
@Override
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundTableSink.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundTableSink.java
index 1bd4e994ac5..89d67dc3766 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundTableSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/analyzer/UnboundTableSink.java
@@ -22,6 +22,7 @@ import org.apache.doris.nereids.memo.GroupExpression;
import org.apache.doris.nereids.properties.LogicalProperties;
import org.apache.doris.nereids.properties.UnboundLogicalProperties;
import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.plans.BlockFuncDepsPropagation;
import org.apache.doris.nereids.trees.plans.Plan;
@@ -137,6 +138,11 @@ public class UnboundTableSink<CHILD_TYPE extends Plan> extends LogicalSink<CHILD
dmlCommandType, groupExpression, Optional.empty(), children.get(0));
}
+ @Override
+ public UnboundTableSink<CHILD_TYPE> withOutputExprs(List<NamedExpression> outputExprs) {
+ throw new UnboundException("could not call withOutputExprs on UnboundTableSink");
+ }
+
@Override
public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
return visitor.visitUnboundTableSink(this, context);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AdjustNullable.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AdjustNullable.java
index 2aa095875ee..8f70b86e4bd 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AdjustNullable.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AdjustNullable.java
@@ -40,6 +40,7 @@ import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
import org.apache.doris.nereids.trees.plans.logical.LogicalRepeat;
import org.apache.doris.nereids.trees.plans.logical.LogicalSetOperation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSink;
import org.apache.doris.nereids.trees.plans.logical.LogicalSort;
import org.apache.doris.nereids.trees.plans.logical.LogicalTopN;
import org.apache.doris.nereids.trees.plans.logical.LogicalUnion;
@@ -78,6 +79,13 @@ public class AdjustNullable extends DefaultPlanRewriter<Map<ExprId, Slot>> imple
return logicalPlan;
}
+ @Override
+ public Plan visitLogicalSink(LogicalSink<? extends Plan> logicalSink, Map<ExprId, Slot> replaceMap) {
+ logicalSink = (LogicalSink<? extends Plan>) super.visit(logicalSink, replaceMap);
+ List<NamedExpression> newOutputExprs = updateExpressions(logicalSink.getOutputExprs(), replaceMap);
+ return logicalSink.withOutputExprs(newOutputExprs);
+ }
+
@Override
public Plan visitLogicalAggregate(LogicalAggregate<? extends Plan> aggregate, Map<ExprId, Slot> replaceMap) {
aggregate = (LogicalAggregate<? extends Plan>) super.visit(aggregate, replaceMap);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalDeferMaterializeResultSink.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalDeferMaterializeResultSink.java
index ab6efb8977a..dab393cb007 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalDeferMaterializeResultSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalDeferMaterializeResultSink.java
@@ -21,6 +21,7 @@ import org.apache.doris.catalog.OlapTable;
import org.apache.doris.nereids.memo.GroupExpression;
import org.apache.doris.nereids.properties.LogicalProperties;
import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.PropagateFuncDeps;
import org.apache.doris.nereids.trees.plans.algebra.Sink;
@@ -82,6 +83,12 @@ public class LogicalDeferMaterializeResultSink<CHILD_TYPE extends Plan>
olapTable, selectedIndexId, Optional.empty(), Optional.empty(), children.get(0));
}
+ @Override
+ public LogicalDeferMaterializeResultSink<CHILD_TYPE> withOutputExprs(List<NamedExpression> outputExprs) {
+ return new LogicalDeferMaterializeResultSink<>(logicalResultSink, olapTable, selectedIndexId,
+ Optional.empty(), Optional.empty(), child());
+ }
+
@Override
public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
return visitor.visitLogicalDeferMaterializeResultSink(this, context);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalFileSink.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalFileSink.java
index 3ca559c5197..43e490c00c7 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalFileSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalFileSink.java
@@ -59,7 +59,7 @@ public class LogicalFileSink<CHILD_TYPE extends Plan> extends LogicalSink<CHILD_
this.properties = ImmutableMap.copyOf(Objects.requireNonNull(properties));
}
- public Plan withOutputExprs(List<NamedExpression> outputExprs) {
+ public LogicalFileSink<CHILD_TYPE> withOutputExprs(List<NamedExpression> outputExprs) {
return new LogicalFileSink<>(filePath, format, properties, outputExprs, child());
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalOlapTableSink.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalOlapTableSink.java
index a1147a96170..1a298ea8c40 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalOlapTableSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalOlapTableSink.java
@@ -113,6 +113,11 @@ public class LogicalOlapTableSink<CHILD_TYPE extends Plan> extends LogicalSink<C
return dmlCommandType;
}
+ public LogicalOlapTableSink<CHILD_TYPE> withOutputExprs(List<NamedExpression> outputExprs) {
+ return new LogicalOlapTableSink<>(database, targetTable, cols, partitionIds, outputExprs, isPartialUpdate,
+ dmlCommandType, Optional.empty(), Optional.empty(), child());
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalResultSink.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalResultSink.java
index 564938dd8b1..6312aee6235 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalResultSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalResultSink.java
@@ -72,6 +72,11 @@ public class LogicalResultSink<CHILD_TYPE extends Plan> extends LogicalSink<CHIL
return new LogicalResultSink<>(outputExprs, groupExpression, logicalProperties, children.get(0));
}
+ @Override
+ public LogicalResultSink<CHILD_TYPE> withOutputExprs(List<NamedExpression> outputExprs) {
+ return new LogicalResultSink<>(outputExprs, Optional.empty(), Optional.empty(), child());
+ }
+
@Override
public String toString() {
return Utils.toSqlString("LogicalResultSink[" + id.asInt() + "]",
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSink.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSink.java
index 028c0e93e0a..ea2fa49e466 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSink.java
@@ -52,6 +52,8 @@ public abstract class LogicalSink<CHILD_TYPE extends Plan> extends LogicalUnary<
return outputExprs;
}
+ public abstract LogicalSink<CHILD_TYPE> withOutputExprs(List<NamedExpression> outputExprs);
+
@Override
public List<? extends Expression> getExpressions() {
return outputExprs;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 15/43: [Improve](Variant) support implicit cast to numeric and string type (#30029)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 4480f751e62aa2f3679ca833f972425e225683bf
Author: lihangyu <15...@163.com>
AuthorDate: Mon Jan 22 11:02:55 2024 +0800
[Improve](Variant) support implicit cast to numeric and string type (#30029)
---
.../org/apache/doris/analysis/BinaryPredicate.java | 8 +++
.../org/apache/doris/analysis/MatchPredicate.java | 10 ++-
.../data/variant_p0/sql/implicit_cast.out | 80 ++++++++++++++++++++++
.../suites/variant_p0/sql/implicit_cast.sql | 15 ++++
4 files changed, 111 insertions(+), 2 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/analysis/BinaryPredicate.java b/fe/fe-core/src/main/java/org/apache/doris/analysis/BinaryPredicate.java
index bb30a46b3e9..1ce647a473c 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/analysis/BinaryPredicate.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/analysis/BinaryPredicate.java
@@ -496,6 +496,14 @@ public class BinaryPredicate extends Predicate implements Writable {
SessionVariable.getEnableDecimal256());
}
+ // Variant can be implicit cast to numeric type and string type at present
+ if (t1.isVariantType() && (t2.isNumericType() || t2.isStringType())) {
+ return Type.fromPrimitiveType(t2);
+ }
+ if (t2.isVariantType() && (t1.isNumericType() || t1.isStringType())) {
+ return Type.fromPrimitiveType(t1);
+ }
+
return Type.DOUBLE;
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/analysis/MatchPredicate.java b/fe/fe-core/src/main/java/org/apache/doris/analysis/MatchPredicate.java
index f106aec956c..e284d86e2bb 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/analysis/MatchPredicate.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/analysis/MatchPredicate.java
@@ -271,9 +271,10 @@ public class MatchPredicate extends Predicate {
throw new AnalysisException("right operand of " + op.toString() + " must be of type STRING: " + toSql());
}
- if (!getChild(0).getType().isStringType() && !getChild(0).getType().isArrayType()) {
+ if (!getChild(0).getType().isStringType() && !getChild(0).getType().isArrayType()
+ && !getChild(0).getType().isVariantType()) {
throw new AnalysisException(
- "left operand of " + op.toString() + " must be of type STRING or ARRAY: " + toSql());
+ "left operand of " + op.toString() + " must be of type STRING, ARRAY or VARIANT: " + toSql());
}
fn = getBuiltinFunction(op.toString(),
@@ -295,6 +296,11 @@ public class MatchPredicate extends Predicate {
}
}
+ // CAST variant to right expr type
+ if (e1.type.isVariantType()) {
+ setChild(0, e1.castTo(e2.getType()));
+ }
+
if (e1 instanceof SlotRef) {
SlotRef slotRef = (SlotRef) e1;
SlotDescriptor slotDesc = slotRef.getDesc();
diff --git a/regression-test/data/variant_p0/sql/implicit_cast.out b/regression-test/data/variant_p0/sql/implicit_cast.out
new file mode 100644
index 00000000000..b0f5d96087b
--- /dev/null
+++ b/regression-test/data/variant_p0/sql/implicit_cast.out
@@ -0,0 +1,80 @@
+-- This file is automatically generated. You should know what you did if you want to edit this
+-- !implicit_cast --
+0
+
+-- !implicit_cast_2 --
+0
+
+-- !implicit_cast_3 --
+0
+
+-- !implicit_cast_4 --
+5000
+
+-- !implicit_cast_5 --
+leonardomso/33-js-concepts 3
+ytdl-org/youtube-dl 3
+Bogdanp/neko 2
+bminossi/AllVideoPocsFromHackerOne 2
+disclose/diodata 2
+
+-- !implicit_cast_6 --
+282
+
+-- !implicit_cast_7 --
+14690758274
+
+-- !implicit_cast_8 --
+0
+
+-- !implicit_cast_9 --
+19829
+
+-- !implicit_cast_10 --
+49390617
+64890096
+10696700
+33066637
+32271952
+2051941
+32271952
+57325392
+42386044
+73801003
+
+-- !implicit_cast_11 --
+27 {"id":147350463,"name":"leonardomso/33-js-concepts","url":"https://api.github.com/repos/leonardomso/33-js-concepts"}
+36 {"id":26109545,"name":"odeke-em/drive","url":"https://api.github.com/repos/odeke-em/drive"}
+46 {"id":141905736,"name":"GO-LiFE/GoFIT_SDK_Android","url":"https://api.github.com/repos/GO-LiFE/GoFIT_SDK_Android"}
+56 {"id":289417971,"name":"MrXujiang/h5-Dooring","url":"https://api.github.com/repos/MrXujiang/h5-Dooring"}
+86 {"id":106453399,"name":"redsaph/cleartext","url":"https://api.github.com/repos/redsaph/cleartext"}
+98 {"id":162998479,"name":"sherlock-project/sherlock","url":"https://api.github.com/repos/sherlock-project/sherlock"}
+101 {"id":326215605,"name":"okandavut/react-spotify-nowplaying","url":"https://api.github.com/repos/okandavut/react-spotify-nowplaying"}
+112 {"id":178435468,"name":"sentriz/gonic","url":"https://api.github.com/repos/sentriz/gonic"}
+122 {"id":182606378,"name":"netlify-labs/react-netlify-identity-widget","url":"https://api.github.com/repos/netlify-labs/react-netlify-identity-widget"}
+169 {"id":68730444,"name":"microsoft/BotBuilder-Samples","url":"https://api.github.com/repos/microsoft/BotBuilder-Samples"}
+
+-- !implicit_cast_12 --
+27 14690746717 WatchEvent leonardomso/33-js-concepts
+36 14690746732 WatchEvent odeke-em/drive
+46 14690746749 WatchEvent GO-LiFE/GoFIT_SDK_Android
+56 14690746773 WatchEvent MrXujiang/h5-Dooring
+86 14690746843 WatchEvent redsaph/cleartext
+98 14690746866 WatchEvent sherlock-project/sherlock
+101 14690746870 WatchEvent okandavut/react-spotify-nowplaying
+112 14690746899 WatchEvent sentriz/gonic
+122 14690746914 WatchEvent netlify-labs/react-netlify-identity-widget
+169 14690747028 WatchEvent microsoft/BotBuilder-Samples
+
+-- !implicit_cast_13 --
+user
+user
+user
+user
+user
+user
+user
+user
+user
+user
+
diff --git a/regression-test/suites/variant_p0/sql/implicit_cast.sql b/regression-test/suites/variant_p0/sql/implicit_cast.sql
new file mode 100644
index 00000000000..0653a52eed7
--- /dev/null
+++ b/regression-test/suites/variant_p0/sql/implicit_cast.sql
@@ -0,0 +1,15 @@
+set exec_mem_limit=8G;
+set enable_two_phase_read_opt = true;
+set topn_opt_limit_threshold = 1024;
+SELECT count() from ghdata;
+SELECT cast(v["repo"]["name"] as string) as repo_name, count() AS stars FROM ghdata WHERE v["type"] = 'WatchEvent' GROUP BY repo_name ORDER BY stars DESC, repo_name LIMIT 5;
+SELECT COUNT() FROM ghdata WHERE v["type"] match 'WatchEvent';
+SELECT max(cast(v["id"] as bigint)) FROM ghdata;
+SELECT sum(cast(v["payload"]["pull_request"]["milestone"]["creator"]["site_admin"] as int)) FROM ghdata;
+SELECT sum(length(v["payload"]["pull_request"]["base"]["repo"]["html_url"])) FROM ghdata;
+SELECT v["payload"]["member"]["id"] FROM ghdata where v["payload"]["member"]["id"] is not null ORDER BY k LIMIT 10;
+-- select k, v:payload.commits.author.name AS name, e FROM ghdata as t lateral view explode(cast(v:payload.commits.author.name as array<string>)) tm1 as e order by k limit 5;
+select k, json_extract(v, '$.repo') from ghdata WHERE v["type"] = 'WatchEvent' order by k limit 10;
+-- SELECT v["payload"]["member"]["id"], count() FROM ghdata where v["payload"]["member"]["id"] is not null group by v["payload"]["member"]["id"] order by 1, 2 desc LIMIT 10;
+select k, v["id"], v["type"], v["repo"]["name"] from ghdata WHERE v["type"] = 'WatchEvent' order by k limit 10;
+SELECT v["payload"]["pusher_type"] FROM ghdata where v["payload"]["pusher_type"] is not null ORDER BY k LIMIT 10;
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 31/43: [fix](Nereids) Fixed a bug where the execution plan was incorrect after ddl (#30107)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 45f6cba837d1e6222c15d231e65a3f07c7d7de4a
Author: xy <wh...@163.com>
AuthorDate: Mon Jan 22 15:10:46 2024 +0800
[fix](Nereids) Fixed a bug where the execution plan was incorrect after ddl (#30107)
should only compare column name when generate data dist info of PhysicalOlapScan
Co-authored-by: xingying01 <xi...@corp.netease.com>
---
.../implementation/LogicalOlapScanToPhysicalOlapScan.java | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/LogicalOlapScanToPhysicalOlapScan.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/LogicalOlapScanToPhysicalOlapScan.java
index 6bcf22a9adc..43436355ae1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/LogicalOlapScanToPhysicalOlapScan.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/LogicalOlapScanToPhysicalOlapScan.java
@@ -94,7 +94,10 @@ public class LogicalOlapScanToPhysicalOlapScan extends OneImplementationRuleFact
if (hashColumns.size() != hashDistributionInfo.getDistributionColumns().size()) {
for (Slot slot : baseOutput) {
for (Column column : hashDistributionInfo.getDistributionColumns()) {
- if (((SlotReference) slot).getColumn().get().equals(column)) {
+ // If the length of the column in the bucket key changes after DDL, the length cannot be
+ // determined. As a result, some bucket fields are lost in the query execution plan.
+ // So here we use the column name to avoid this problem
+ if (((SlotReference) slot).getColumn().get().getName().equalsIgnoreCase(column.getName())) {
hashColumns.add(slot.getExprId());
}
}
@@ -108,7 +111,10 @@ public class LogicalOlapScanToPhysicalOlapScan extends OneImplementationRuleFact
List<ExprId> hashColumns = Lists.newArrayList();
for (Slot slot : output) {
for (Column column : hashDistributionInfo.getDistributionColumns()) {
- if (((SlotReference) slot).getColumn().get().equals(column)) {
+ // If the length of the column in the bucket key changes after DDL, the length cannot be
+ // determined. As a result, some bucket fields are lost in the query execution plan.
+ // So here we use the column name to avoid this problem
+ if (((SlotReference) slot).getColumn().get().getName().equalsIgnoreCase(column.getName())) {
hashColumns.add(slot.getExprId());
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 07/43: [fix](ci) remove required of performance (#30185)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit c8be73934d1a63f33ed4e79fd4c9d436da21af26
Author: Dongyang Li <he...@qq.com>
AuthorDate: Sat Jan 20 23:07:15 2024 +0800
[fix](ci) remove required of performance (#30185)
encounter this issue: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/troubleshooting-required-status-checks#required-status-checks-from-unexpected-sources
---
.asf.yaml | 2 --
1 file changed, 2 deletions(-)
diff --git a/.asf.yaml b/.asf.yaml
index 3633289db79..cc730103843 100644
--- a/.asf.yaml
+++ b/.asf.yaml
@@ -57,7 +57,6 @@ github:
- External Regression (Doris External Regression)
- FE UT (Doris FE UT)
- BE UT (Doris BE UT)
- - performance (Performance New)
- Build Broker
- Build Documents
- ShellCheck
@@ -93,7 +92,6 @@ github:
- External Regression (Doris External Regression)
- FE UT (Doris FE UT)
- BE UT (Doris BE UT)
- - performance (Performance New)
- Build Broker
- ShellCheck
- Build Documents
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 13/43: [config](load) set default memtable_flush_running_count_limit to 2 (#30146)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 9dd368f8dcf0533e29edff3f946582d69a2d3dd1
Author: Kaijie Chen <ck...@apache.org>
AuthorDate: Mon Jan 22 09:58:49 2024 +0800
[config](load) set default memtable_flush_running_count_limit to 2 (#30146)
---
be/src/common/config.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index d919d7f5719..174572c5c66 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -592,7 +592,7 @@ DEFINE_mInt64(write_buffer_size, "104857600");
// max buffer size used in memtable for the aggregated table, default 400MB
DEFINE_mInt64(write_buffer_size_for_agg, "419430400");
// max parallel flush task per memtable writer
-DEFINE_mInt32(memtable_flush_running_count_limit, "5");
+DEFINE_mInt32(memtable_flush_running_count_limit, "2");
DEFINE_Int32(load_process_max_memory_limit_percent, "50"); // 50%
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 05/43: [ci](perf) add required (#30155)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 7cc85f893c8b41b12d7e3e67c88eda2feea6650c
Author: Dongyang Li <he...@qq.com>
AuthorDate: Fri Jan 19 23:53:06 2024 +0800
[ci](perf) add required (#30155)
Co-authored-by: stephen <he...@qq.com>
---
.asf.yaml | 2 +
.github/workflows/comment-to-trigger-teamcity.yml | 21 +---
regression-test/pipeline/common/doris-utils.sh | 12 +-
regression-test/pipeline/common/github-utils.sh | 25 ----
regression-test/pipeline/performance/run-tpcds.sh | 1 +
regression-test/pipeline/performance/run-tpch.sh | 1 +
regression-test/pipeline/tpch/tpch-sf100/clean.sh | 40 -------
.../pipeline/tpch/tpch-sf100/conf/be.conf | 85 -------------
.../pipeline/tpch/tpch-sf100/conf/external.json | 26 ----
.../pipeline/tpch/tpch-sf100/conf/fe.conf | 78 ------------
.../pipeline/tpch/tpch-sf100/conf/odbcinst.ini | 43 -------
regression-test/pipeline/tpch/tpch-sf100/deploy.sh | 119 -------------------
.../pipeline/tpch/tpch-sf100/prepare.sh | 69 -----------
regression-test/pipeline/tpch/tpch-sf100/run.sh | 131 ---------------------
14 files changed, 11 insertions(+), 642 deletions(-)
diff --git a/.asf.yaml b/.asf.yaml
index cc730103843..3633289db79 100644
--- a/.asf.yaml
+++ b/.asf.yaml
@@ -57,6 +57,7 @@ github:
- External Regression (Doris External Regression)
- FE UT (Doris FE UT)
- BE UT (Doris BE UT)
+ - performance (Performance New)
- Build Broker
- Build Documents
- ShellCheck
@@ -92,6 +93,7 @@ github:
- External Regression (Doris External Regression)
- FE UT (Doris FE UT)
- BE UT (Doris BE UT)
+ - performance (Performance New)
- Build Broker
- ShellCheck
- Build Documents
diff --git a/.github/workflows/comment-to-trigger-teamcity.yml b/.github/workflows/comment-to-trigger-teamcity.yml
index 0fdd80ba28f..8ae0832fc9e 100644
--- a/.github/workflows/comment-to-trigger-teamcity.yml
+++ b/.github/workflows/comment-to-trigger-teamcity.yml
@@ -45,7 +45,6 @@ jobs:
"${COMMENT_BODY}" == *'run p1'* ||
"${COMMENT_BODY}" == *'run external'* ||
"${COMMENT_BODY}" == *'run pipelinex_p0'* ||
- "${COMMENT_BODY}" == *'run clickbench'* ||
"${COMMENT_BODY}" == *'run arm'* ||
"${COMMENT_BODY}" == *'run performance'* ]]; then
echo "comment_trigger=true" | tee -a "$GITHUB_OUTPUT"
@@ -63,7 +62,7 @@ jobs:
echo "TARGET_BRANCH='${TARGET_BRANCH}'" | tee -a "$GITHUB_OUTPUT"
echo "COMMENT_BODY='${COMMENT_BODY}'" | tee -a "$GITHUB_OUTPUT"
- reg="run (buildall|compile|p0|p1|feut|beut|external|clickbench|pipelinex_p0|arm|performance)( [1-9]*[0-9]+)*"
+ reg="run (buildall|compile|p0|p1|feut|beut|external|pipelinex_p0|arm|performance)( [1-9]*[0-9]+)*"
COMMENT_TRIGGER_TYPE="$(echo -e "${COMMENT_BODY}" | xargs | grep -E "${reg}" | awk -F' ' '{print $2}' | sed -n 1p | sed 's/\r//g')"
COMMENT_REPEAT_TIMES="$(echo -e "${COMMENT_BODY}" | xargs | grep -E "${reg}" | awk -F' ' '{print $3}' | sed -n 1p | sed 's/\r//g')"
echo "COMMENT_TRIGGER_TYPE=${COMMENT_TRIGGER_TYPE}" | tee -a "$GITHUB_OUTPUT"
@@ -90,11 +89,6 @@ jobs:
else
echo "changed_be_ut=false" | tee -a "$GITHUB_OUTPUT"
fi
- if file_changed_ckb; then
- echo "changed_ckb=true" | tee -a "$GITHUB_OUTPUT"
- else
- echo "changed_ckb=false" | tee -a "$GITHUB_OUTPUT"
- fi
if file_changed_regression_p0; then
echo "changed_p0=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_external=true" | tee -a "$GITHUB_OUTPUT"
@@ -120,7 +114,6 @@ jobs:
echo "INFO: failed to _get_pr_changed_files, default trigger all"
echo "changed_fe_ut=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_be_ut=true" | tee -a "$GITHUB_OUTPUT"
- echo "changed_ckb=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_p0=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_external=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_pipelinex_p0=true" | tee -a "$GITHUB_OUTPUT"
@@ -243,18 +236,6 @@ jobs:
"arm" \
"${{ steps.parse.outputs.COMMENT_REPEAT_TIMES }}"
- - name: "Trigger or Skip clickbench"
- if: ${{ fromJSON(steps.parse.outputs.comment_trigger) && contains(fromJSON('["clickbench", "buildall"]'), steps.parse.outputs.COMMENT_TRIGGER_TYPE) }}
- run: |
- source ./regression-test/pipeline/common/teamcity-utils.sh
- set -x
- trigger_or_skip_build \
- "${{ steps.changes.outputs.changed_ckb }}" \
- "${{ steps.parse.outputs.PULL_REQUEST_NUM }}" \
- "${{ steps.parse.outputs.COMMIT_ID_FROM_TRIGGER }}" \
- "clickbench" \
- "${{ steps.parse.outputs.COMMENT_REPEAT_TIMES }}"
-
- name: "Trigger or Skip performance"
if: ${{ fromJSON(steps.parse.outputs.comment_trigger) && contains(fromJSON('["performance", "buildall"]'), steps.parse.outputs.COMMENT_TRIGGER_TYPE) }}
run: |
diff --git a/regression-test/pipeline/common/doris-utils.sh b/regression-test/pipeline/common/doris-utils.sh
index 47bcedad351..327f00beac1 100644
--- a/regression-test/pipeline/common/doris-utils.sh
+++ b/regression-test/pipeline/common/doris-utils.sh
@@ -394,18 +394,18 @@ archive_doris_logs() {
print_doris_fe_log() {
if [[ ! -d "${DORIS_HOME:-}" ]]; then return 1; fi
- echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.out--------------------"
+ echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.out--------------------"
tail -n 100 "${DORIS_HOME}"/fe/log/fe.out
- echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.log--------------------"
+ echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.log--------------------"
tail -n 100 "${DORIS_HOME}"/fe/log/fe.log
- echo "WARNING: ----------------------------------------"
+ echo -e "WARNING: ----------------------------------------\n\n\n\n"
}
print_doris_be_log() {
if [[ ! -d "${DORIS_HOME:-}" ]]; then return 1; fi
- echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.out--------------------"
+ echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.out--------------------"
tail -n 100 "${DORIS_HOME}"/be/log/be.out
- echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.INFO--------------------"
+ echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.INFO--------------------"
tail -n 100 "${DORIS_HOME}"/be/log/be.INFO
- echo "WARNING: ----------------------------------------"
+ echo -e "WARNING: ----------------------------------------\n\n\n\n"
}
diff --git a/regression-test/pipeline/common/github-utils.sh b/regression-test/pipeline/common/github-utils.sh
index 317667d15b2..5a9d2ebb7b3 100644
--- a/regression-test/pipeline/common/github-utils.sh
+++ b/regression-test/pipeline/common/github-utils.sh
@@ -304,31 +304,6 @@ file_changed_regression_p1() {
file_changed_regression_p0
}
-file_changed_ckb() {
- local all_files
- all_files=$(cat all_files)
- if _only_modified_regression_conf; then echo "return no need" && return 1; fi
- if [[ -z ${all_files} ]]; then echo "return need" && return 0; fi
- for af in ${all_files}; do
- if [[ "${af}" == 'be'* ]] ||
- [[ "${af}" == 'bin'* ]] ||
- [[ "${af}" == 'conf'* ]] ||
- [[ "${af}" == 'fe'* ]] ||
- [[ "${af}" == 'gensrc'* ]] ||
- [[ "${af}" == 'thirdparty'* ]] ||
- [[ "${af}" == 'build.sh' ]] ||
- [[ "${af}" == 'env.sh' ]] ||
- [[ "${af}" == 'regression-test/pipeline/common/github-utils.sh' ]] ||
- [[ "${af}" == 'regression-test/pipeline/common/doris-utils.sh' ]] ||
- [[ "${af}" == 'regression-test/pipeline/common/oss-utils.sh' ]] ||
- [[ "${af}" == 'tools/tpch-tools/bin/run-tpch-queries.sh' ]] ||
- [[ "${af}" == 'regression-test/pipeline/tpch/tpch-sf100/'* ]]; then
- echo "clickbench performance related file changed, return need" && return 0
- fi
- done
- echo "return no need" && return 1
-}
-
file_changed_performance() {
local all_files
all_files=$(cat all_files)
diff --git a/regression-test/pipeline/performance/run-tpcds.sh b/regression-test/pipeline/performance/run-tpcds.sh
index d054b85ee4d..0ca31c57e74 100644
--- a/regression-test/pipeline/performance/run-tpcds.sh
+++ b/regression-test/pipeline/performance/run-tpcds.sh
@@ -125,6 +125,7 @@ exit_flag=0
echo "#### 3. run tpcds-sf${SF} query"
set_session_variable runtime_filter_mode global
bash "${teamcity_build_checkoutDir}"/tools/tpcds-tools/bin/run-tpcds-queries.sh -s "${SF}" | tee "${teamcity_build_checkoutDir}"/run-tpcds-queries.log
+ echo
cold_run_time_threshold=${cold_run_time_threshold_master:-315000} # ms
hot_run_time_threshold=${hot_run_time_threshold_master:-190000} # ms
if [[ "${target_branch}" == "branch-2.0" ]]; then
diff --git a/regression-test/pipeline/performance/run-tpch.sh b/regression-test/pipeline/performance/run-tpch.sh
index 1620c5f2922..f1e4c8df2a2 100644
--- a/regression-test/pipeline/performance/run-tpch.sh
+++ b/regression-test/pipeline/performance/run-tpch.sh
@@ -117,6 +117,7 @@ exit_flag=0
echo "#### 3. run tpch-sf${SF} query"
set_session_variable runtime_filter_mode global
bash "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh -s "${SF}" | tee "${teamcity_build_checkoutDir}"/run-tpch-queries.log
+ echo
cold_run_time_threshold=${cold_run_time_threshold_master:-120000} # ms
hot_run_time_threshold=${hot_run_time_threshold_master:-42000} # ms
if [[ "${target_branch}" == "branch-2.0" ]]; then
diff --git a/regression-test/pipeline/tpch/tpch-sf100/clean.sh b/regression-test/pipeline/tpch/tpch-sf100/clean.sh
deleted file mode 100644
index 16fa490ef9c..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/clean.sh
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env bash
-# 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.
-
-# Build Step: Command Line
-: <<EOF
-#!/bin/bash
-
-# Execute step even if some of the previous steps failed
-teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
-if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/clean.sh ]]; then
- cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
- bash -x clean.sh
-else
- echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/clean.sh" && exit 1
-fi
-EOF
-
-## clean.sh content ##
-
-# stop_doris
-source ../../common/doris-utils.sh
-
-DORIS_HOME="${teamcity_build_checkoutDir}/output"
-export DORIS_HOME
-stop_doris
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf b/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf
deleted file mode 100644
index cc23ae153bf..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf
+++ /dev/null
@@ -1,85 +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.
-
-CUR_DATE=`date +%Y%m%d-%H%M%S`
-
-PPROF_TMPDIR="$DORIS_HOME/log/"
-
-JAVA_OPTS="-Xmx1024m -DlogPath=$DORIS_HOME/log/jni.log -Xloggc:$DORIS_HOME/log/be.gc.log.$CUR_DATE -Djavax.security.auth.useSubjectCredsOnly=false -Dsun.security.krb5.debug=true -Dsun.java.command=DorisBE -XX:-CriticalJNINatives -DJDBC_MIN_POOL=1 -DJDBC_MAX_POOL=100 -DJDBC_MAX_IDLE_TIME=300000 -DJDBC_MAX_WAIT_TIME=5000"
-
-# For jdk 9+, this JAVA_OPTS will be used as default JVM options
-JAVA_OPTS_FOR_JDK_9="-Xmx1024m -DlogPath=$DORIS_HOME/log/jni.log -Xlog:gc:$DORIS_HOME/log/be.gc.log.$CUR_DATE -Djavax.security.auth.useSubjectCredsOnly=false -Dsun.security.krb5.debug=true -Dsun.java.command=DorisBE -XX:-CriticalJNINatives -DJDBC_MIN_POOL=1 -DJDBC_MAX_POOL=100 -DJDBC_MAX_IDLE_TIME=300000 -DJDBC_MAX_WAIT_TIME=5000"
-
-# since 1.2, the JAVA_HOME need to be set to run BE process.
-# JAVA_HOME=/path/to/jdk/
-
-# https://github.com/apache/doris/blob/master/docs/zh-CN/community/developer-guide/debug-tool.md#jemalloc-heap-profile
-# https://jemalloc.net/jemalloc.3.html
-JEMALLOC_CONF="percpu_arena:percpu,background_thread:true,metadata_thp:auto,muzzy_decay_ms:15000,dirty_decay_ms:15000,oversize_threshold:0,lg_tcache_max:20,prof:false,lg_prof_interval:32,lg_prof_sample:19,prof_gdump:false,prof_accum:false,prof_leak:false,prof_final:false"
-JEMALLOC_PROF_PRFIX=""
-
-# INFO, WARNING, ERROR, FATAL
-sys_log_level = INFO
-
-# ports for admin, web, heartbeat service
-be_port = 9060
-webserver_port = 8040
-heartbeat_service_port = 9050
-brpc_port = 8060
-arrow_flight_sql_port = -1
-
-# HTTPS configures
-enable_https = false
-# path of certificate in PEM format.
-ssl_certificate_path = "$DORIS_HOME/conf/cert.pem"
-# path of private key in PEM format.
-ssl_private_key_path = "$DORIS_HOME/conf/key.pem"
-
-
-# Choose one if there are more than one ip except loopback address.
-# Note that there should at most one ip match this list.
-# If no ip match this rule, will choose one randomly.
-# use CIDR format, e.g. 10.10.10.0/24 or IP format, e.g. 10.10.10.1
-# Default value is empty.
-# priority_networks = 10.10.10.0/24;192.168.0.0/16
-
-# data root path, separate by ';'
-# You can specify the storage type for each root path, HDD (cold data) or SSD (hot data)
-# eg:
-# storage_root_path = /home/disk1/doris;/home/disk2/doris;/home/disk2/doris
-# storage_root_path = /home/disk1/doris,medium:SSD;/home/disk2/doris,medium:SSD;/home/disk2/doris,medium:HDD
-# /home/disk2/doris,medium:HDD(default)
-#
-# you also can specify the properties by setting '<property>:<value>', separate by ','
-# property 'medium' has a higher priority than the extension of path
-#
-# Default value is ${DORIS_HOME}/storage, you should create it by hand.
-# storage_root_path = ${DORIS_HOME}/storage
-
-# Default dirs to put jdbc drivers,default value is ${DORIS_HOME}/jdbc_drivers
-# jdbc_drivers_dir = ${DORIS_HOME}/jdbc_drivers
-
-# Advanced configurations
-# sys_log_dir = ${DORIS_HOME}/log
-# sys_log_roll_mode = SIZE-MB-1024
-# sys_log_roll_num = 10
-# sys_log_verbose_modules = *
-# log_buffer_level = -1
-# palo_cgroups
-
-priority_networks=172.16.0.0/24
-storage_root_path=/mnt/datadisk0/doris-storage
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/external.json b/regression-test/pipeline/tpch/tpch-sf100/conf/external.json
deleted file mode 100644
index 9461d836e67..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/conf/external.json
+++ /dev/null
@@ -1,26 +0,0 @@
-[
- {
- "file": "docker/thirdparties/docker-compose/mysql/mysql-5.7.env",
- "replacements": {
- "DOCKER_MYSQL_57_EXTERNAL_PORT": 7111
- }
- },
- {
- "file": "docker/thirdparties/docker-compose/postgresql/postgresql-14.env",
- "replacements": {
- "DOCKER_PG_14_EXTERNAL_PORT": 7121
- }
- },
- {
- "file": "docker/thirdparties/docker-compose/hive/gen_env.sh",
- "replacements": {
- "FS_PORT": 7131,
- "HMS_PORT": 7141
- }
- }, {
- "file": "docker/thirdparties/start-thirdparties-docker.sh",
- "replacements": {
- "CONTAINER_UID": "doris-regression-fakeid-fakecommit"
- }
- }
-]
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf b/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf
deleted file mode 100644
index 7c02d3898dc..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf
+++ /dev/null
@@ -1,78 +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.
-
-#####################################################################
-## The uppercase properties are read and exported by bin/start_fe.sh.
-## To see all Frontend configurations,
-## see fe/src/org/apache/doris/common/Config.java
-#####################################################################
-
-CUR_DATE=`date +%Y%m%d-%H%M%S`
-
-# the output dir of stderr and stdout
-LOG_DIR = ${DORIS_HOME}/log
-
-JAVA_OPTS="-Dsun.security.krb5.debug=true -Djavax.security.auth.useSubjectCredsOnly=false -Xss4m -Xmx8192m -XX:+UseMembar -XX:SurvivorRatio=8 -XX:MaxTenuringThreshold=7 -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSClassUnloadingEnabled -XX:-CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=80 -XX:SoftRefLRUPolicyMSPerMB=0 -Xloggc:$DORIS_HOME/log/fe.gc.log.$CUR_DATE"
-
-# For jdk 9+, this JAVA_OPTS will be used as default JVM options
-JAVA_OPTS_FOR_JDK_9="-Dsun.security.krb5.debug=true -Djavax.security.auth.useSubjectCredsOnly=false -Xss4m -Xmx8192m -XX:SurvivorRatio=8 -XX:MaxTenuringThreshold=7 -XX:+CMSClassUnloadingEnabled -XX:-CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=80 -XX:SoftRefLRUPolicyMSPerMB=0 -Xlog:gc*:$DORIS_HOME/log/fe.gc.log.$CUR_DATE:time"
-
-##
-## the lowercase properties are read by main program.
-##
-
-# INFO, WARN, ERROR, FATAL
-sys_log_level = INFO
-
-# NORMAL, BRIEF, ASYNC
-sys_log_mode = NORMAL
-
-# store metadata, must be created before start FE.
-# Default value is ${DORIS_HOME}/doris-meta
-# meta_dir = ${DORIS_HOME}/doris-meta
-
-# Default dirs to put jdbc drivers,default value is ${DORIS_HOME}/jdbc_drivers
-# jdbc_drivers_dir = ${DORIS_HOME}/jdbc_drivers
-
-http_port = 8030
-rpc_port = 9020
-query_port = 9030
-edit_log_port = 9010
-arrow_flight_sql_port = -1
-
-# Choose one if there are more than one ip except loopback address.
-# Note that there should at most one ip match this list.
-# If no ip match this rule, will choose one randomly.
-# use CIDR format, e.g. 10.10.10.0/24 or IP format, e.g. 10.10.10.1
-# Default value is empty.
-# priority_networks = 10.10.10.0/24;192.168.0.0/16
-
-# Advanced configurations
-# log_roll_size_mb = 1024
-# sys_log_dir = ${DORIS_HOME}/log
-# sys_log_roll_num = 10
-# sys_log_verbose_modules = org.apache.doris
-# audit_log_dir = ${DORIS_HOME}/log
-# audit_log_modules = slow_query, query
-# audit_log_roll_num = 10
-# meta_delay_toleration_second = 10
-# qe_max_connection = 1024
-# qe_query_timeout_second = 300
-# qe_slow_log_ms = 5000
-
-priority_networks=172.16.0.0/24
-meta_dir=/mnt/datadisk0/doris-meta
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/odbcinst.ini b/regression-test/pipeline/tpch/tpch-sf100/conf/odbcinst.ini
deleted file mode 100644
index 41e21f92277..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/conf/odbcinst.ini
+++ /dev/null
@@ -1,43 +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.
-
-# Example driver definitions, you should not use the example odbc driver
-# before you prepare env in your server
-
-# Driver from the postgresql-odbc package
-# Setup from the unixODBC package
-[PostgreSQL]
-Description = ODBC for PostgreSQL
-Driver = /usr/lib/psqlodbc.so
-Setup = /usr/lib/libodbcpsqlS.so
-FileUsage = 1
-
-
-# Driver from the mysql-connector-odbc package
-# Setup from the unixODBC package
-[MySQL ODBC 8.0 Unicode Driver]
-Description = ODBC for MySQL
-Driver = /usr/lib64/libmyodbc8w.so
-FileUsage = 1
-
-# Driver from the oracle-connector-odbc package
-# Setup from the unixODBC package
-[Oracle 19 ODBC driver]
-Description=Oracle ODBC driver for Oracle 19
-Driver=/usr/lib/libsqora.so.19.1
-
-
diff --git a/regression-test/pipeline/tpch/tpch-sf100/deploy.sh b/regression-test/pipeline/tpch/tpch-sf100/deploy.sh
deleted file mode 100644
index 64d816f0aca..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/deploy.sh
+++ /dev/null
@@ -1,119 +0,0 @@
-#!/usr/bin/env bash
-# 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.
-
-# Build Step: Command Line
-: <<EOF
-#!/bin/bash
-
-teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
-if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/deploy.sh ]]; then
- cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
- bash -x deploy.sh
-else
- echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/deploy.sh" && exit 1
-fi
-EOF
-
-## deploy.sh content ##
-
-# download_oss_file
-source ../../common/oss-utils.sh
-# start_doris_fe, get_doris_conf_value, start_doris_be, stop_doris,
-# print_doris_fe_log, print_doris_be_log, archive_doris_logs
-source ../../common/doris-utils.sh
-
-echo "#### Check env"
-if [[ -z "${teamcity_build_checkoutDir}" ||
- -z "${pull_request_id}" ||
- -z "${commit_id}" ]]; then
- echo "ERROR: env teamcity_build_checkoutDir or pull_request_id or commit_id not set"
- exit 1
-fi
-if ${DEBUG:-false}; then
- pull_request_id="26465"
- commit_id="a532f7113f463e144e83918a37288f2649448482"
-fi
-
-echo "#### Deploy Doris ####"
-DORIS_HOME="${teamcity_build_checkoutDir}/output"
-export DORIS_HOME
-exit_flag=0
-need_backup_doris_logs=false
-
-echo "#### 1. try to kill old doris process and remove old doris binary"
-stop_doris && rm -rf output
-
-echo "#### 2. download doris binary tar ball"
-cd "${teamcity_build_checkoutDir}" || exit 1
-if download_oss_file "${pull_request_id:-}_${commit_id:-}.tar.gz"; then
- if ! command -v pigz >/dev/null; then sudo apt install -y pigz; fi
- tar -I pigz -xf "${pull_request_id:-}_${commit_id:-}.tar.gz"
- if [[ -d output && -d output/fe && -d output/be ]]; then
- echo "INFO: be version: $(./output/be/lib/doris_be --version)"
- rm -rf "${pull_request_id}_${commit_id}.tar.gz"
- fi
-else
- echo "ERROR: download compiled binary failed" && exit 1
-fi
-
-echo "#### 3. copy conf from regression-test/pipeline/tpch/tpch-sf100/conf/"
-rm -f "${DORIS_HOME}"/fe/conf/fe_custom.conf "${DORIS_HOME}"/be/conf/be_custom.conf
-if [[ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf &&
- -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf ]]; then
- cp -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf "${DORIS_HOME}"/fe/conf/
- cp -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf "${DORIS_HOME}"/be/conf/
-else
- echo "ERROR: doris conf file missing in ${teamcity_build_checkoutDir}/regression-test/pipeline/tpch/tpch-sf100/conf/"
- exit 1
-fi
-
-echo "#### 4. start Doris"
-meta_dir=$(get_doris_conf_value "${DORIS_HOME}"/fe/conf/fe.conf meta_dir)
-storage_root_path=$(get_doris_conf_value "${DORIS_HOME}"/be/conf/be.conf storage_root_path)
-mkdir -p "${meta_dir}"
-mkdir -p "${storage_root_path}"
-if ! start_doris_fe; then
- echo "ERROR: Start doris fe failed."
- print_doris_fe_log
- need_backup_doris_logs=true
- exit_flag=1
-fi
-if ! start_doris_be; then
- echo "ERROR: Start doris be failed."
- print_doris_be_log
- need_backup_doris_logs=true
- exit_flag=1
-fi
-
-# wait 10s for doris totally started, otherwize may encounter the error below,
-# ERROR 1105 (HY000) at line 102: errCode = 2, detailMessage = Failed to find enough backend, please check the replication num,replication tag and storage medium.
-sleep 10s
-
-echo "#### 5. set session variables"
-echo "TODO"
-
-echo "#### 6. check if need backup doris logs"
-if ${need_backup_doris_logs}; then
- print_doris_fe_log
- print_doris_be_log
- if file_name=$(archive_doris_logs "${pull_request_id}_${commit_id}_doris_logs.tar.gz"); then
- upload_doris_log_to_oss "${file_name}"
- fi
-fi
-
-exit "${exit_flag}"
diff --git a/regression-test/pipeline/tpch/tpch-sf100/prepare.sh b/regression-test/pipeline/tpch/tpch-sf100/prepare.sh
deleted file mode 100644
index 07959a03d6f..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/prepare.sh
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/env bash
-# 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.
-
-# Build Step: Command Line
-: <<EOF
-#!/bin/bash
-
-teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
-if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/prepare.sh ]]; then
- cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
- bash -x prepare.sh
-else
- echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/prepare.sh" && exit 1
-fi
-EOF
-
-## run.sh content ##
-
-echo "#### Check env"
-if [[ -z "${commit_id_from_trigger}" || -z ${commit_id:-} || -z ${pull_request_id:-} ]]; then
- echo "ERROR: env commit_id_from_trigger or commit_id or pull_request_id not set" && exit 1
-else
- commit_id_from_checkout=${commit_id}
-fi
-if ${DEBUG:-false}; then commit_id_from_trigger=${commit_id}; fi
-
-echo "Prepare to run tpch sf100 test"
-
-echo "#### 1. check if need run"
-if [[ "${commit_id_from_trigger}" != "${commit_id_from_checkout}" ]]; then
- echo -e "目前是在 clickbench 流水线 compile 完后触发本 tpch 流水线的,
-有可能 pr 在 clickbench 流水线还在跑的时候新提交了commit,
-这时候 tpch 流水线 checkout 出来的 commit 就不是触发时的传过来的 commit了,
-这种情况不需要跑"
- echo -e "ERROR: PR(${pull_request_id}),
- the lastest commit id
- ${commit_id_from_checkout}
- not equail to the commit_id_from_trigger
- ${commit_id_from_trigger}
- commit_id_from_trigger is outdate"
- exit 1
-fi
-
-echo "#### 2. check if depending files exist"
-if ! [[ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf &&
- -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf &&
- -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/deploy.sh &&
- -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/run.sh &&
- -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/common/oss-utils.sh &&
- -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/common/doris-utils.sh &&
- -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/common/github-utils.sh &&
- -f "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh ]]; then
- echo "ERROR: depending files missing" && exit 1
-fi
diff --git a/regression-test/pipeline/tpch/tpch-sf100/run.sh b/regression-test/pipeline/tpch/tpch-sf100/run.sh
deleted file mode 100644
index d9252f742c1..00000000000
--- a/regression-test/pipeline/tpch/tpch-sf100/run.sh
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/env bash
-# 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.
-
-# Build Step: Command Line
-: <<EOF
-#!/bin/bash
-
-teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
-if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/run.sh ]]; then
- cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
- bash -x run.sh
-else
- echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/run.sh" && exit 1
-fi
-EOF
-
-## run.sh content ##
-
-# check_tpch_table_rows, stop_doris, set_session_variable
-source ../../common/doris-utils.sh
-# create_an_issue_comment
-source ../../common/github-utils.sh
-# upload_doris_log_to_oss
-source ../../common/oss-utils.sh
-
-echo "#### Check env"
-if [[ -z "${teamcity_build_checkoutDir}" ||
- -z "${pull_request_id}" ||
- -z "${commit_id}" ]]; then
- echo "ERROR: env teamcity_build_checkoutDir or pull_request_id or commit_id not set"
- exit 1
-fi
-
-echo "#### Run tpch-sf100 test on Doris ####"
-DORIS_HOME="${teamcity_build_checkoutDir}/output"
-exit_flag=0
-
-check_tpch_result() {
- log_file="$1"
- if ! grep '^Total cold run time' "${log_file}" || ! grep '^Total hot run time' "${log_file}"; then
- echo "ERROR: can not find 'Total hot run time' in '${log_file}'"
- return 1
- else
- cold_run_time=$(grep '^Total cold run time' "${log_file}" | awk '{print $5}')
- hot_run_time=$(grep '^Total hot run time' "${log_file}" | awk '{print $5}')
- fi
- # 单位是毫秒
- cold_run_time_threshold=${cold_run_time_threshold:-50000}
- hot_run_time_threshold=${hot_run_time_threshold:-42000}
- if [[ ${cold_run_time} -gt 50000 || ${hot_run_time} -gt 42000 ]]; then
- echo "ERROR:
- cold_run_time ${cold_run_time} is great than the threshold ${cold_run_time_threshold},
- or, hot_run_time ${hot_run_time} is great than the threshold ${hot_run_time_threshold}"
- return 1
- else
- echo "INFO:
- cold_run_time ${cold_run_time} is less than the threshold ${cold_run_time_threshold},
- or, hot_run_time ${hot_run_time} is less than the threshold ${hot_run_time_threshold}"
- fi
-}
-
-(
- set -e
- shopt -s inherit_errexit
-
- echo "#### 1. check if need to load data"
- SF="100" # SCALE FACTOR
- if ${DEBUG:-false}; then SF="1"; fi
- db_name="tpch_sf${SF}"
- sed -i "s|^export DB=.*$|export DB='${db_name}'|g" \
- "${teamcity_build_checkoutDir}"/tools/tpch-tools/conf/doris-cluster.conf
- if ! check_tpch_table_rows "${db_name}" "${SF}"; then
- echo "ERROR: check_tpch_table_rows failed." && exit 1
- fi
-
- echo "#### 2. run tpch-sf${SF} query"
- set_session_variable runtime_filter_mode global
- sed -i "s|^SCALE_FACTOR=[0-9]\+$|SCALE_FACTOR=${SF}|g" "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh
- bash "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh | tee "${teamcity_build_checkoutDir}"/run-tpch-queries.log
- if ! check_tpch_result "${teamcity_build_checkoutDir}"/run-tpch-queries.log; then exit 1; fi
- line_end=$(sed -n '/^Total hot run time/=' "${teamcity_build_checkoutDir}"/run-tpch-queries.log)
- line_begin=$((line_end - 23))
- comment_body="Tpch sf${SF} test result on commit ${commit_id:-}, data reload: ${data_reload:-"false"}
-
-run tpch-sf${SF} query with default conf and session variables
-$(sed -n "${line_begin},${line_end}p" "${teamcity_build_checkoutDir}"/run-tpch-queries.log)"
-
- echo "#### 3. run tpch-sf${SF} query with runtime_filter_mode=off"
- set_session_variable runtime_filter_mode off
- bash "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh | tee "${teamcity_build_checkoutDir}"/run-tpch-queries.log
- if ! grep '^Total hot run time' "${teamcity_build_checkoutDir}"/run-tpch-queries.log >/dev/null; then exit 1; fi
- line_end=$(sed -n '/^Total hot run time/=' "${teamcity_build_checkoutDir}"/run-tpch-queries.log)
- line_begin=$((line_end - 23))
- comment_body="${comment_body}
-
-run tpch-sf${SF} query with default conf and set session variable runtime_filter_mode=off
-$(sed -n "${line_begin},${line_end}p" "${teamcity_build_checkoutDir}"/run-tpch-queries.log)"
-
- echo "#### 4. comment result on tpch"
- comment_body=$(echo "${comment_body}" | sed -e ':a;N;$!ba;s/\t/\\t/g;s/\n/\\n/g') # 将所有的 Tab字符替换为\t 换行符替换为\n
- create_an_issue_comment_tpch "${pull_request_id:-}" "${comment_body}"
-
- stop_doris
-)
-exit_flag="$?"
-
-echo "#### 5. check if need backup doris logs"
-if [[ ${exit_flag} != "0" ]]; then
- print_doris_fe_log
- print_doris_be_log
- if file_name=$(archive_doris_logs "${pull_request_id}_${commit_id}_doris_logs.tar.gz"); then
- upload_doris_log_to_oss "${file_name}"
- fi
-fi
-
-exit "${exit_flag}"
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 12/43: [opt](nereids) do not change RuntimeFilter Type from IN-OR_BLOOM to BLOOM on broadcast join (#30148)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 332b9cb6199bcfd533a7863bf2315e579f45c330
Author: minghong <en...@gmail.com>
AuthorDate: Mon Jan 22 09:22:19 2024 +0800
[opt](nereids) do not change RuntimeFilter Type from IN-OR_BLOOM to BLOOM on broadcast join (#30148)
1. do not change RuntimeFilter Type from IN-OR_BLOOM to BLOOM on broadcast join
tpcds1T, q48 improved from 4.x sec to 1.x sec
2. skip some redunant runtime filter
example: A join B on A.a1=B.b and A.a1 = A.a2
RF B.b->(A.a1, A.a2)
however, RF(B.b->A.a2) is implied by RF(B.a->A.a1) and A.a1=A.a2
we skip RF(B.b->A.a2)
Issue Number: close #xxx
---
.../glue/translator/RuntimeFilterTranslator.java | 6 -----
.../processor/post/RuntimeFilterGenerator.java | 2 +-
.../trees/plans/physical/AbstractPhysicalJoin.java | 15 ++++++++++++
.../trees/plans/physical/AbstractPhysicalPlan.java | 21 ++++++++++------
.../trees/plans/physical/RuntimeFilter.java | 4 ++++
.../rf_prune/query64.out | 16 ++++++-------
.../nereids_tpcds_shape_sf100_p0/shape/query64.out | 28 +++++++++++-----------
7 files changed, 56 insertions(+), 36 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/RuntimeFilterTranslator.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/RuntimeFilterTranslator.java
index 91f97906097..30a69ff97de 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/RuntimeFilterTranslator.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/RuntimeFilterTranslator.java
@@ -38,7 +38,6 @@ import org.apache.doris.planner.JoinNodeBase;
import org.apache.doris.planner.RuntimeFilter.RuntimeFilterTarget;
import org.apache.doris.planner.ScanNode;
import org.apache.doris.qe.ConnectContext;
-import org.apache.doris.qe.SessionVariable;
import org.apache.doris.statistics.StatisticalType;
import org.apache.doris.thrift.TRuntimeFilterType;
@@ -185,11 +184,6 @@ public class RuntimeFilterTranslator {
origFilter.markFinalized();
origFilter.assignToPlanNodes();
origFilter.extractTargetsPosition();
- // Number of parallel instances are large for pipeline engine, so we prefer bloom filter.
- if (origFilter.hasRemoteTargets() && origFilter.getType() == TRuntimeFilterType.IN_OR_BLOOM
- && SessionVariable.enablePipelineEngine()) {
- origFilter.setType(TRuntimeFilterType.BLOOM);
- }
return origFilter;
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/RuntimeFilterGenerator.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/RuntimeFilterGenerator.java
index 76d189ba63d..8a75ad36c5a 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/RuntimeFilterGenerator.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/RuntimeFilterGenerator.java
@@ -567,7 +567,7 @@ public class RuntimeFilterGenerator extends PlanPostProcessor {
PhysicalHashJoin<? extends Plan, ? extends Plan> join = innerEntry.getValue();
Preconditions.checkState(join != null);
TRuntimeFilterType type = TRuntimeFilterType.IN_OR_BLOOM;
- if (ctx.getSessionVariable().getEnablePipelineEngine()) {
+ if (ctx.getSessionVariable().getEnablePipelineEngine() && !join.isBroadCastJoin()) {
type = TRuntimeFilterType.BLOOM;
}
EqualTo newEqualTo = ((EqualTo) JoinUtils.swapEqualToForChildrenOrder(
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalJoin.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalJoin.java
index 16ba68aac62..7d1c65b5899 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalJoin.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalJoin.java
@@ -19,6 +19,8 @@ package org.apache.doris.nereids.trees.plans.physical;
import org.apache.doris.nereids.hint.DistributeHint;
import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.properties.DistributionSpec;
+import org.apache.doris.nereids.properties.DistributionSpecReplicated;
import org.apache.doris.nereids.properties.LogicalProperties;
import org.apache.doris.nereids.properties.PhysicalProperties;
import org.apache.doris.nereids.trees.expressions.Expression;
@@ -251,4 +253,17 @@ public abstract class AbstractPhysicalJoin<
return Utils.toSqlString(this.getClass().getSimpleName() + "[" + id.asInt() + "]" + getGroupIdWithPrefix(),
args.toArray());
}
+
+ /**
+ * true if this is a broadcast join
+ */
+ public boolean isBroadCastJoin() {
+ if (child(1) instanceof PhysicalDistribute) {
+ DistributionSpec distSpec = ((PhysicalDistribute) child(1)).getDistributionSpec();
+ if (distSpec instanceof DistributionSpecReplicated) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalPlan.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalPlan.java
index a2968ca8089..6a19abcc8fc 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalPlan.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/AbstractPhysicalPlan.java
@@ -112,19 +112,26 @@ public abstract class AbstractPhysicalPlan extends AbstractPlan implements Physi
// in-filter is not friendly to pipeline
if (type == TRuntimeFilterType.IN_OR_BLOOM
&& ctx.getSessionVariable().getEnablePipelineEngine()
- && RuntimeFilterGenerator.hasRemoteTarget(builderNode, scan)) {
+ && RuntimeFilterGenerator.hasRemoteTarget(builderNode, scan)
+ && !builderNode.isBroadCastJoin()) {
type = TRuntimeFilterType.BLOOM;
}
org.apache.doris.nereids.trees.plans.physical.RuntimeFilter filter =
ctx.getRuntimeFilterBySrcAndType(src, type, builderNode);
Preconditions.checkState(scanSlot != null, "scan slot is null");
if (filter != null) {
- this.addAppliedRuntimeFilter(filter);
- filter.addTargetSlot(scanSlot, scan);
- filter.addTargetExpression(scanSlot);
- ctx.addJoinToTargetMap(builderNode, scanSlot.getExprId());
- ctx.setTargetExprIdToFilter(scanSlot.getExprId(), filter);
- ctx.setTargetsOnScanNode(ctx.getAliasTransferPair((NamedExpression) probeExpr).first, scanSlot);
+ if (!filter.hasTargetScan(scan)) {
+ // A join B on A.a1=B.b and A.a1 = A.a2
+ // RF B.b->(A.a1, A.a2)
+ // however, RF(B.b->A.a2) is implied by RF(B.a->A.a1) and A.a1=A.a2
+ // we skip RF(B.b->A.a2)
+ this.addAppliedRuntimeFilter(filter);
+ filter.addTargetSlot(scanSlot, scan);
+ filter.addTargetExpression(scanSlot);
+ ctx.addJoinToTargetMap(builderNode, scanSlot.getExprId());
+ ctx.setTargetExprIdToFilter(scanSlot.getExprId(), filter);
+ ctx.setTargetsOnScanNode(ctx.getAliasTransferPair((NamedExpression) probeExpr).first, scanSlot);
+ }
} else {
filter = new RuntimeFilter(generator.getNextId(),
src, ImmutableList.of(scanSlot), type, exprOrder, builderNode, buildSideNdv, scan);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/RuntimeFilter.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/RuntimeFilter.java
index a8f4c3cd7c8..3a3b01daecd 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/RuntimeFilter.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/RuntimeFilter.java
@@ -148,6 +148,10 @@ public class RuntimeFilter {
return targetScans;
}
+ public boolean hasTargetScan(PhysicalRelation scan) {
+ return targetScans.contains(scan);
+ }
+
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
diff --git a/regression-test/data/nereids_tpcds_shape_sf100_p0/rf_prune/query64.out b/regression-test/data/nereids_tpcds_shape_sf100_p0/rf_prune/query64.out
index e5e915d4422..367d659e25c 100644
--- a/regression-test/data/nereids_tpcds_shape_sf100_p0/rf_prune/query64.out
+++ b/regression-test/data/nereids_tpcds_shape_sf100_p0/rf_prune/query64.out
@@ -16,22 +16,22 @@ PhysicalCteAnchor ( cteId=CTEId#1 )
--------------------------PhysicalProject
----------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_promo_sk = promotion.p_promo_sk)) otherCondition=()
------------------------------PhysicalProject
---------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_addr_sk = ad1.ca_address_sk)) otherCondition=() build RFs:RF16 ss_addr_sk->[ca_address_sk]
+--------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_addr_sk = ad1.ca_address_sk)) otherCondition=() build RFs:RF15 ss_addr_sk->[ca_address_sk]
----------------------------------PhysicalProject
-------------------------------------PhysicalOlapScan[customer_address] apply RFs: RF16
+------------------------------------PhysicalOlapScan[customer_address] apply RFs: RF15
----------------------------------PhysicalDistribute[DistributionSpecHash]
------------------------------------PhysicalProject
---------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = store_returns.sr_item_sk) and (store_sales.ss_ticket_number = store_returns.sr_ticket_number)) otherCondition=() build RFs:RF14 ss_item_sk->[sr_item_sk];RF15 ss_ticket_number->[sr_ticket_number]
+--------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = store_returns.sr_item_sk) and (store_sales.ss_ticket_number = store_returns.sr_ticket_number)) otherCondition=() build RFs:RF13 ss_item_sk->[sr_item_sk];RF14 ss_ticket_number->[sr_ticket_number]
----------------------------------------PhysicalProject
-------------------------------------------PhysicalOlapScan[store_returns] apply RFs: RF14 RF15
+------------------------------------------PhysicalOlapScan[store_returns] apply RFs: RF13 RF14
----------------------------------------PhysicalDistribute[DistributionSpecHash]
------------------------------------------PhysicalProject
---------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_cdemo_sk = cd1.cd_demo_sk)) otherCondition=() build RFs:RF13 ss_cdemo_sk->[cd_demo_sk]
+--------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_cdemo_sk = cd1.cd_demo_sk)) otherCondition=() build RFs:RF12 ss_cdemo_sk->[cd_demo_sk]
----------------------------------------------PhysicalDistribute[DistributionSpecHash]
------------------------------------------------PhysicalProject
---------------------------------------------------PhysicalOlapScan[customer_demographics] apply RFs: RF13
+--------------------------------------------------PhysicalOlapScan[customer_demographics] apply RFs: RF12
----------------------------------------------PhysicalDistribute[DistributionSpecHash]
-------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = item.i_item_sk)) otherCondition=() build RFs:RF11 i_item_sk->[ss_item_sk];RF12 i_item_sk->[cs_item_sk]
+------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = item.i_item_sk)) otherCondition=() build RFs:RF11 i_item_sk->[ss_item_sk,cs_item_sk]
--------------------------------------------------PhysicalProject
----------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_store_sk = store.s_store_sk)) otherCondition=()
------------------------------------------------------PhysicalProject
@@ -53,7 +53,7 @@ PhysicalCteAnchor ( cteId=CTEId#1 )
----------------------------------------------------------------------------------PhysicalProject
------------------------------------------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((catalog_sales.cs_item_sk = catalog_returns.cr_item_sk) and (catalog_sales.cs_order_number = catalog_returns.cr_order_number)) otherCondition=() build RFs:RF4 cr_order_number->[cs_order_number];RF5 cr_item_sk->[cs_item_sk]
--------------------------------------------------------------------------------------PhysicalProject
-----------------------------------------------------------------------------------------PhysicalOlapScan[catalog_sales] apply RFs: RF4 RF5 RF12
+----------------------------------------------------------------------------------------PhysicalOlapScan[catalog_sales] apply RFs: RF4 RF5 RF11
--------------------------------------------------------------------------------------PhysicalProject
----------------------------------------------------------------------------------------PhysicalOlapScan[catalog_returns]
------------------------------------------------------------------PhysicalDistribute[DistributionSpecReplicated]
diff --git a/regression-test/data/nereids_tpcds_shape_sf100_p0/shape/query64.out b/regression-test/data/nereids_tpcds_shape_sf100_p0/shape/query64.out
index 43bdb50fcce..d40500b774a 100644
--- a/regression-test/data/nereids_tpcds_shape_sf100_p0/shape/query64.out
+++ b/regression-test/data/nereids_tpcds_shape_sf100_p0/shape/query64.out
@@ -7,31 +7,31 @@ PhysicalCteAnchor ( cteId=CTEId#1 )
--------PhysicalDistribute[DistributionSpecHash]
----------hashAgg[LOCAL]
------------PhysicalProject
---------------hashJoin[INNER_JOIN] hashCondition=((customer.c_first_shipto_date_sk = d3.d_date_sk)) otherCondition=() build RFs:RF20 d_date_sk->[c_first_shipto_date_sk]
+--------------hashJoin[INNER_JOIN] hashCondition=((customer.c_first_shipto_date_sk = d3.d_date_sk)) otherCondition=() build RFs:RF19 d_date_sk->[c_first_shipto_date_sk]
----------------PhysicalProject
-------------------hashJoin[INNER_JOIN] hashCondition=((customer.c_first_sales_date_sk = d2.d_date_sk)) otherCondition=() build RFs:RF19 d_date_sk->[c_first_sales_date_sk]
+------------------hashJoin[INNER_JOIN] hashCondition=((customer.c_first_sales_date_sk = d2.d_date_sk)) otherCondition=() build RFs:RF18 d_date_sk->[c_first_sales_date_sk]
--------------------PhysicalProject
-----------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_customer_sk = customer.c_customer_sk)) otherCondition=(( not (cd_marital_status = cd_marital_status))) build RFs:RF18 c_customer_sk->[ss_customer_sk]
+----------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_customer_sk = customer.c_customer_sk)) otherCondition=(( not (cd_marital_status = cd_marital_status))) build RFs:RF17 c_customer_sk->[ss_customer_sk]
------------------------PhysicalDistribute[DistributionSpecHash]
--------------------------PhysicalProject
-----------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_promo_sk = promotion.p_promo_sk)) otherCondition=() build RFs:RF17 p_promo_sk->[ss_promo_sk]
+----------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_promo_sk = promotion.p_promo_sk)) otherCondition=() build RFs:RF16 p_promo_sk->[ss_promo_sk]
------------------------------PhysicalProject
---------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_addr_sk = ad1.ca_address_sk)) otherCondition=() build RFs:RF16 ss_addr_sk->[ca_address_sk]
+--------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_addr_sk = ad1.ca_address_sk)) otherCondition=() build RFs:RF15 ss_addr_sk->[ca_address_sk]
----------------------------------PhysicalProject
-------------------------------------PhysicalOlapScan[customer_address] apply RFs: RF16
+------------------------------------PhysicalOlapScan[customer_address] apply RFs: RF15
----------------------------------PhysicalDistribute[DistributionSpecHash]
------------------------------------PhysicalProject
---------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = store_returns.sr_item_sk) and (store_sales.ss_ticket_number = store_returns.sr_ticket_number)) otherCondition=() build RFs:RF14 ss_item_sk->[sr_item_sk];RF15 ss_ticket_number->[sr_ticket_number]
+--------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = store_returns.sr_item_sk) and (store_sales.ss_ticket_number = store_returns.sr_ticket_number)) otherCondition=() build RFs:RF13 ss_item_sk->[sr_item_sk];RF14 ss_ticket_number->[sr_ticket_number]
----------------------------------------PhysicalProject
-------------------------------------------PhysicalOlapScan[store_returns] apply RFs: RF14 RF15
+------------------------------------------PhysicalOlapScan[store_returns] apply RFs: RF13 RF14
----------------------------------------PhysicalDistribute[DistributionSpecHash]
------------------------------------------PhysicalProject
---------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_cdemo_sk = cd1.cd_demo_sk)) otherCondition=() build RFs:RF13 ss_cdemo_sk->[cd_demo_sk]
+--------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_cdemo_sk = cd1.cd_demo_sk)) otherCondition=() build RFs:RF12 ss_cdemo_sk->[cd_demo_sk]
----------------------------------------------PhysicalDistribute[DistributionSpecHash]
------------------------------------------------PhysicalProject
---------------------------------------------------PhysicalOlapScan[customer_demographics] apply RFs: RF13
+--------------------------------------------------PhysicalOlapScan[customer_demographics] apply RFs: RF12
----------------------------------------------PhysicalDistribute[DistributionSpecHash]
-------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = item.i_item_sk)) otherCondition=() build RFs:RF11 i_item_sk->[ss_item_sk];RF12 i_item_sk->[cs_item_sk]
+------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = item.i_item_sk)) otherCondition=() build RFs:RF11 i_item_sk->[ss_item_sk,cs_item_sk]
--------------------------------------------------PhysicalProject
----------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_store_sk = store.s_store_sk)) otherCondition=() build RFs:RF10 s_store_sk->[ss_store_sk]
------------------------------------------------------PhysicalProject
@@ -43,7 +43,7 @@ PhysicalCteAnchor ( cteId=CTEId#1 )
------------------------------------------------------------------PhysicalProject
--------------------------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((store_sales.ss_item_sk = cs_ui.cs_item_sk)) otherCondition=() build RFs:RF6 cs_item_sk->[ss_item_sk]
----------------------------------------------------------------------PhysicalProject
-------------------------------------------------------------------------PhysicalOlapScan[store_sales] apply RFs: RF6 RF7 RF8 RF10 RF11 RF17 RF18
+------------------------------------------------------------------------PhysicalOlapScan[store_sales] apply RFs: RF6 RF7 RF8 RF10 RF11 RF16 RF17
----------------------------------------------------------------------PhysicalDistribute[DistributionSpecReplicated]
------------------------------------------------------------------------PhysicalProject
--------------------------------------------------------------------------filter((sale > (2 * refund)))
@@ -53,7 +53,7 @@ PhysicalCteAnchor ( cteId=CTEId#1 )
----------------------------------------------------------------------------------PhysicalProject
------------------------------------------------------------------------------------hashJoin[INNER_JOIN] hashCondition=((catalog_sales.cs_item_sk = catalog_returns.cr_item_sk) and (catalog_sales.cs_order_number = catalog_returns.cr_order_number)) otherCondition=() build RFs:RF4 cr_order_number->[cs_order_number];RF5 cr_item_sk->[cs_item_sk]
--------------------------------------------------------------------------------------PhysicalProject
-----------------------------------------------------------------------------------------PhysicalOlapScan[catalog_sales] apply RFs: RF4 RF5 RF12
+----------------------------------------------------------------------------------------PhysicalOlapScan[catalog_sales] apply RFs: RF4 RF5 RF11
--------------------------------------------------------------------------------------PhysicalProject
----------------------------------------------------------------------------------------PhysicalOlapScan[catalog_returns]
------------------------------------------------------------------PhysicalDistribute[DistributionSpecReplicated]
@@ -86,7 +86,7 @@ PhysicalCteAnchor ( cteId=CTEId#1 )
--------------------------------------PhysicalProject
----------------------------------------hashJoin[INNER_JOIN] hashCondition=((customer.c_current_hdemo_sk = hd2.hd_demo_sk)) otherCondition=() build RFs:RF1 hd_demo_sk->[c_current_hdemo_sk]
------------------------------------------PhysicalProject
---------------------------------------------PhysicalOlapScan[customer] apply RFs: RF1 RF2 RF3 RF19 RF20
+--------------------------------------------PhysicalOlapScan[customer] apply RFs: RF1 RF2 RF3 RF18 RF19
------------------------------------------PhysicalDistribute[DistributionSpecReplicated]
--------------------------------------------PhysicalProject
----------------------------------------------hashJoin[INNER_JOIN] hashCondition=((hd2.hd_income_band_sk = ib2.ib_income_band_sk)) otherCondition=() build RFs:RF0 ib_income_band_sk->[hd_income_band_sk]
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 39/43: [fix](group commit) abort txn should use label if replay wal failed (#30219)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 9c742d46a231fb5e6af490a77d29a0d30e951a7e
Author: meiyi <my...@gmail.com>
AuthorDate: Mon Jan 22 20:33:00 2024 +0800
[fix](group commit) abort txn should use label if replay wal failed (#30219)
---
be/src/olap/wal/wal_manager.cpp | 10 ++++----
be/src/olap/wal/wal_table.cpp | 29 +++++++++++-----------
be/src/olap/wal/wal_table.h | 2 +-
be/src/runtime/group_commit_mgr.cpp | 12 ++++-----
.../apache/doris/service/FrontendServiceImpl.java | 24 ++++++++++++------
gensrc/thrift/FrontendService.thrift | 2 ++
6 files changed, 44 insertions(+), 35 deletions(-)
diff --git a/be/src/olap/wal/wal_manager.cpp b/be/src/olap/wal/wal_manager.cpp
index 621a1aa0806..45a9b58ff2d 100644
--- a/be/src/olap/wal/wal_manager.cpp
+++ b/be/src/olap/wal/wal_manager.cpp
@@ -198,9 +198,9 @@ size_t WalManager::get_wal_queue_size(int64_t table_id) {
return 0;
}
} else {
- //table_id is -1 meaning get all table wal size
- for (auto it = _wal_queues.begin(); it != _wal_queues.end(); it++) {
- count += it->second.size();
+ // table_id is -1 meaning get all table wal size
+ for (auto& [_, table_wals] : _wal_queues) {
+ count += table_wals.size();
}
}
return count;
@@ -372,8 +372,8 @@ size_t WalManager::get_wal_table_size(int64_t table_id) {
void WalManager::_stop_relay_wal() {
std::lock_guard<std::shared_mutex> wrlock(_table_lock);
- for (auto it = _table_map.begin(); it != _table_map.end(); it++) {
- it->second->stop();
+ for (auto& [_, wal_table] : _table_map) {
+ wal_table->stop();
}
}
diff --git a/be/src/olap/wal/wal_table.cpp b/be/src/olap/wal/wal_table.cpp
index a6d7a4054c8..8adc9cf5f50 100644
--- a/be/src/olap/wal/wal_table.cpp
+++ b/be/src/olap/wal/wal_table.cpp
@@ -58,28 +58,27 @@ void WalTable::_pick_relay_wals() {
std::lock_guard<std::mutex> lock(_replay_wal_lock);
std::vector<std::string> need_replay_wals;
std::vector<std::string> need_erase_wals;
- for (auto it = _replay_wal_map.begin(); it != _replay_wal_map.end(); it++) {
- auto wal_info = it->second;
+ for (const auto& [wal_path, wal_info] : _replay_wal_map) {
if (wal_info->get_retry_num() >= config::group_commit_replay_wal_retry_num) {
LOG(WARNING) << "All replay wal failed, db=" << _db_id << ", table=" << _table_id
- << ", wal=" << it->first << ", retry_num=" << wal_info->get_retry_num();
- auto st = _exec_env->wal_mgr()->rename_to_tmp_path(it->first, _table_id,
+ << ", wal=" << wal_path << ", retry_num=" << wal_info->get_retry_num();
+ auto st = _exec_env->wal_mgr()->rename_to_tmp_path(wal_path, _table_id,
wal_info->get_wal_id());
if (!st.ok()) {
- LOG(WARNING) << "rename " << it->first << " fail"
+ LOG(WARNING) << "rename " << wal_path << " fail"
<< ",st:" << st.to_string();
}
if (config::group_commit_wait_replay_wal_finish) {
- auto notify_st = _exec_env->wal_mgr()->notify_relay_wal(it->second->get_wal_id());
+ auto notify_st = _exec_env->wal_mgr()->notify_relay_wal(wal_info->get_wal_id());
if (!notify_st.ok()) {
- LOG(WARNING) << "notify wal " << it->second->get_wal_id() << " fail";
+ LOG(WARNING) << "notify wal " << wal_info->get_wal_id() << " fail";
}
}
- need_erase_wals.push_back(it->first);
+ need_erase_wals.push_back(wal_path);
continue;
}
if (_need_replay(wal_info)) {
- need_replay_wals.push_back(it->first);
+ need_replay_wals.push_back(wal_path);
}
}
for (const auto& wal : need_erase_wals) {
@@ -168,13 +167,13 @@ bool WalTable::_need_replay(std::shared_ptr<WalInfo> wal_info) {
#endif
}
-Status WalTable::_try_abort_txn(int64_t db_id, int64_t wal_id) {
+Status WalTable::_try_abort_txn(int64_t db_id, std::string& label) {
TLoadTxnRollbackRequest request;
request.__set_auth_code(0); // this is a fake, fe not check it now
request.__set_db_id(db_id);
// TODO should we use label, because the replay wal use the same label and different wal_id
- request.__set_txnId(wal_id);
- std::string reason = "relay wal " + std::to_string(wal_id);
+ request.__set_label(label);
+ std::string reason = "relay wal with label " + label;
request.__set_reason(reason);
TLoadTxnRollbackResult result;
TNetworkAddress master_addr = _exec_env->master_info()->network_address;
@@ -185,7 +184,7 @@ Status WalTable::_try_abort_txn(int64_t db_id, int64_t wal_id) {
},
10000L);
auto result_status = Status::create(result.status);
- LOG(INFO) << "abort txn " << wal_id << ",st:" << st << ",result_status:" << result_status;
+ LOG(INFO) << "abort label " << label << ", st:" << st << ", result_status:" << result_status;
return result_status;
}
@@ -196,9 +195,9 @@ Status WalTable::_replay_wal_internal(const std::string& wal) {
RETURN_IF_ERROR(_parse_wal_path(wal, wal_id, label));
#ifndef BE_TEST
if (!config::group_commit_wait_replay_wal_finish) {
- auto st = _try_abort_txn(_db_id, wal_id);
+ auto st = _try_abort_txn(_db_id, label);
if (!st.ok()) {
- LOG(WARNING) << "abort txn " << wal_id << " fail";
+ LOG(WARNING) << "failed to abort txn with label " << label;
}
}
#endif
diff --git a/be/src/olap/wal/wal_table.h b/be/src/olap/wal/wal_table.h
index 07287d8f7e6..9b1ead87a20 100644
--- a/be/src/olap/wal/wal_table.h
+++ b/be/src/olap/wal/wal_table.h
@@ -47,7 +47,7 @@ private:
Status _replay_wal_internal(const std::string& wal);
Status _parse_wal_path(const std::string& wal, int64_t& wal_id, std::string& label);
- Status _try_abort_txn(int64_t db_id, int64_t wal_id);
+ Status _try_abort_txn(int64_t db_id, std::string& label);
Status _get_column_info(int64_t db_id, int64_t tb_id,
std::map<int64_t, std::string>& column_info_map);
diff --git a/be/src/runtime/group_commit_mgr.cpp b/be/src/runtime/group_commit_mgr.cpp
index 3931306cd6f..d057dd92b92 100644
--- a/be/src/runtime/group_commit_mgr.cpp
+++ b/be/src/runtime/group_commit_mgr.cpp
@@ -191,14 +191,14 @@ Status GroupCommitTable::get_first_block_load_queue(
std::unique_lock l(_lock);
for (int i = 0; i < 3; i++) {
bool is_schema_version_match = true;
- for (auto it = _load_block_queues.begin(); it != _load_block_queues.end(); ++it) {
- if (!it->second->need_commit()) {
- if (base_schema_version == it->second->schema_version) {
- if (it->second->add_load_id(load_id).ok()) {
- load_block_queue = it->second;
+ for (const auto& [_, inner_block_queue] : _load_block_queues) {
+ if (!inner_block_queue->need_commit()) {
+ if (base_schema_version == inner_block_queue->schema_version) {
+ if (inner_block_queue->add_load_id(load_id).ok()) {
+ load_block_queue = inner_block_queue;
return Status::OK();
}
- } else if (base_schema_version < it->second->schema_version) {
+ } else if (base_schema_version < inner_block_queue->schema_version) {
is_schema_version_match = false;
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java b/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
index 1a1ceb799c7..85753a7330a 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
@@ -1663,15 +1663,23 @@ public class FrontendServiceImpl implements FrontendService.Iface {
throw new MetaNotFoundException("db " + request.getDb() + " does not exist");
}
long dbId = db.getId();
- TransactionState transactionState = Env.getCurrentGlobalTransactionMgr()
- .getTransactionState(dbId, request.getTxnId());
- if (transactionState == null) {
- throw new UserException("transaction [" + request.getTxnId() + "] not found");
+ if (request.getTxnId() != 0) { // txnId is required in thrift
+ TransactionState transactionState = Env.getCurrentGlobalTransactionMgr()
+ .getTransactionState(dbId, request.getTxnId());
+ if (transactionState == null) {
+ throw new UserException("transaction [" + request.getTxnId() + "] not found");
+ }
+ List<Table> tableList = db.getTablesOnIdOrderIfExist(transactionState.getTableIdList());
+ Env.getCurrentGlobalTransactionMgr().abortTransaction(dbId, request.getTxnId(),
+ request.isSetReason() ? request.getReason() : "system cancel",
+ TxnCommitAttachment.fromThrift(request.getTxnCommitAttachment()), tableList);
+ } else if (request.isSetLabel()) {
+ Env.getCurrentGlobalTransactionMgr()
+ .abortTransaction(db.getId(), request.getLabel(),
+ request.isSetReason() ? request.getReason() : "system cancel");
+ } else {
+ throw new UserException("must set txn_id or label");
}
- List<Table> tableList = db.getTablesOnIdOrderIfExist(transactionState.getTableIdList());
- Env.getCurrentGlobalTransactionMgr().abortTransaction(dbId, request.getTxnId(),
- request.isSetReason() ? request.getReason() : "system cancel",
- TxnCommitAttachment.fromThrift(request.getTxnCommitAttachment()), tableList);
}
@Override
diff --git a/gensrc/thrift/FrontendService.thrift b/gensrc/thrift/FrontendService.thrift
index 7d1c8c62ae9..98c876afbfc 100644
--- a/gensrc/thrift/FrontendService.thrift
+++ b/gensrc/thrift/FrontendService.thrift
@@ -816,6 +816,8 @@ struct TLoadTxnRollbackRequest {
11: optional string token
12: optional i64 db_id
13: optional list<string> tbls
+ 14: optional string auth_code_uuid
+ 15: optional string label
}
struct TLoadTxnRollbackResult {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 06/43: [doc](ranger) update ranger doc #30101
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 7180ca707c4f5d8e6db45fdad6deb7c276f4c4a7
Author: zhangdong <49...@qq.com>
AuthorDate: Sat Jan 20 22:39:37 2024 +0800
[doc](ranger) update ranger doc #30101
add some descriptions for ranger
---
docs/en/docs/lakehouse/multi-catalog/hive.md | 13 +++++++++++++
docs/zh-CN/docs/lakehouse/multi-catalog/hive.md | 13 +++++++++++++
2 files changed, 26 insertions(+)
diff --git a/docs/en/docs/lakehouse/multi-catalog/hive.md b/docs/en/docs/lakehouse/multi-catalog/hive.md
index 90db7fe3543..e5fc390a05d 100644
--- a/docs/en/docs/lakehouse/multi-catalog/hive.md
+++ b/docs/en/docs/lakehouse/multi-catalog/hive.md
@@ -415,6 +415,19 @@ To connect to the Hive Metastore with Ranger permission verification enabled, yo
"access_controller.class" = "org.apache.doris.catalog.authorizer.RangerHiveAccessControllerFactory",
```
+>Note:
+>
+>"access_controller.properties.ranger.service.name" It refers to the type of service, such as hive, hdfs, etc.
+> If the configuration of `ranger-hive-security.xml`is as follows, "access_controller.properties.ranger.service.name" should be set to `hive` instead of `testative`
+>
+
+```sql
+<property>
+ <name>ranger.plugin.hive.service.name</name>
+ <value>testhive</value>
+</property>
+```
+
2. Configure all FE environments:
1. Copy the configuration files ranger-hive-audit.xml, ranger-hive-security.xml, and ranger-policymgr-ssl.xml under the HMS conf directory to the FE conf directory.
diff --git a/docs/zh-CN/docs/lakehouse/multi-catalog/hive.md b/docs/zh-CN/docs/lakehouse/multi-catalog/hive.md
index 52e40fc1d0b..b5eedd62747 100644
--- a/docs/zh-CN/docs/lakehouse/multi-catalog/hive.md
+++ b/docs/zh-CN/docs/lakehouse/multi-catalog/hive.md
@@ -396,6 +396,19 @@ Apache Ranger是一个用来在Hadoop平台上进行监控,启用服务,以
"access_controller.class" = "org.apache.doris.catalog.authorizer.RangerHiveAccessControllerFactory",
```
+>注意:
+>
+>"access_controller.properties.ranger.service.name"指的是service的类型,例如hive,hdfs等
+> 如果`ranger-hive-security.xml`配置如下,"access_controller.properties.ranger.service.name"应设置为`hive`而不是`testhive`
+>
+
+```sql
+<property>
+ <name>ranger.plugin.hive.service.name</name>
+ <value>testhive</value>
+</property>
+```
+
2. 配置所有 FE 环境:
1. 将 HMS conf 目录下的配置文件ranger-hive-audit.xml,ranger-hive-security.xml,ranger-policymgr-ssl.xml复制到 FE 的 conf 目录下。
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 26/43: [fix](planner) should return outputTupleDesc's id instead of tupleIds if outputTupleDesc is set in Plan Node (#30150)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 24c0900b419b06e24396114b06eb12ce97e43bdc
Author: starocean999 <40...@users.noreply.github.com>
AuthorDate: Mon Jan 22 13:35:55 2024 +0800
[fix](planner) should return outputTupleDesc's id instead of tupleIds if outputTupleDesc is set in Plan Node (#30150)
---
.../java/org/apache/doris/planner/PlanNode.java | 3 ++
.../correctness_p0/test_nested_lateral_view.out | 15 ++++++
.../correctness_p0/test_nested_lateral_view.groovy | 55 ++++++++++++++++++++++
3 files changed, 73 insertions(+)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/planner/PlanNode.java b/fe/fe-core/src/main/java/org/apache/doris/planner/PlanNode.java
index 4cc535be09a..24fc40be2e1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/PlanNode.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/PlanNode.java
@@ -384,6 +384,9 @@ public abstract class PlanNode extends TreeNode<PlanNode> implements PlanStats {
}
public List<TupleId> getOutputTupleIds() {
+ if (outputTupleDesc != null) {
+ return Lists.newArrayList(outputTupleDesc.getId());
+ }
return tupleIds;
}
diff --git a/regression-test/data/correctness_p0/test_nested_lateral_view.out b/regression-test/data/correctness_p0/test_nested_lateral_view.out
new file mode 100644
index 00000000000..4bac7d8afe3
--- /dev/null
+++ b/regression-test/data/correctness_p0/test_nested_lateral_view.out
@@ -0,0 +1,15 @@
+-- This file is automatically generated. You should know what you did if you want to edit this
+-- !select_default --
+a,a,a,a 1
+a,a,a,a 1
+a,a,a,a 1
+a,a,a,a 1
+a,a,a,a 1
+a,a,a,a 1
+a,a,a,a 2
+a,a,a,a 2
+a,a,a,a 2
+a,a,a,a 2
+a,a,a,a 2
+a,a,a,a 2
+
diff --git a/regression-test/suites/correctness_p0/test_nested_lateral_view.groovy b/regression-test/suites/correctness_p0/test_nested_lateral_view.groovy
new file mode 100644
index 00000000000..1d42331ee88
--- /dev/null
+++ b/regression-test/suites/correctness_p0/test_nested_lateral_view.groovy
@@ -0,0 +1,55 @@
+// 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.
+
+suite("test_nested_lateral_view") {
+ sql """set enable_nereids_planner=true;"""
+ sql "SET enable_fallback_to_original_planner=false"
+ sql """drop table if exists ods_42378777c342d2da36d05db875393811;"""
+ sql """CREATE TABLE `ods_42378777c342d2da36d05db875393811` (
+ `57CE5E02901753F7_06a28` varchar(*) NULL,
+ `57CE5E02520653F7_06a28` varchar(*) NULL,
+ `65F695F4519253F7_06a28` varchar(*) NULL,
+ `65E5671F659C6760_06a28` varchar(*) NULL,
+ `57CE5E027A7A683C_06a28` varchar(*) NULL,
+ `57CE5E02767E520653F7_06a28a4` varchar(*) NULL,
+ `65705B575C0F657070B9_06a28a4` varchar(*) NULL,
+ `qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq_` DECIMAL(38, 10) NULL,
+ `5F88591A7B2653F7_06a28` varchar(*) NULL
+ ) ENGINE=OLAP
+ DUPLICATE KEY(`57CE5E02901753F7_06a28`)
+ COMMENT 'OLAP'
+ DISTRIBUTED BY RANDOM BUCKETS AUTO
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1",
+ "is_being_synced" = "false",
+ "storage_format" = "V2",
+ "light_schema_change" = "true",
+ "disable_auto_compaction" = "false",
+ "enable_single_replica_compaction" = "false"
+ );"""
+ sql """INSERT INTO ods_42378777c342d2da36d05db875393811 (`57CE5E02901753F7_06a28`,`57CE5E02520653F7_06a28`,`65F695F4519253F7_06a28`,`65E5671F659C6760_06a28`,`57CE5E027A7A683C_06a28`,`57CE5E02767E520653F7_06a28a4`,`65705B575C0F657070B9_06a28a4`,qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq_,`5F88591A7B2653F7_06a28`) VALUES
+ ('a,a,a,a','a;a;a;a','1899-12-31 15:11:22','2024-01-12 00:00:00','a a a a','a%a%a%a','33..33.*.@3',3.3300000000,''),
+ ('a,a,a,a','a;a;a;a','1899-12-31 00:11:22','2024-01-10 00:00:00','a a a a','a%a%a%a','99..99.*.@9',1.1100000000,'~!@#¥%……&*()——+=【】;‘,。、、'),
+ ('a,a,a,a','a;a;a;a','1899-12-31 12:11:22','2024-01-11 00:00:00','a a a a','a%a%a%a','22..22.*.@2',2.2200000000,'131.0');
+ """
+ qt_select_default """select * from (SELECT `t1`.`k0`, `f2`.`lt2`
+ FROM
+ (
+ SELECT `t0`.`57CE5E02901753F7_06a28` as `k0` FROM `ods_42378777c342d2da36d05db875393811` `t0`
+ LATERAL VIEW explode(ARRAY(1,2)) `f1` AS `lt1`)`t1`
+ LATERAL VIEW explode(ARRAY(1,2)) `f2` AS `lt2` ) ttt order by 1,2; """
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 43/43: [fix](fe) Upgrade mariadb client version from 3.0.4 to 3.0.9 (#30242)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit fb2145fe9616d85cb0df4df0f3593e1a9cbf679c
Author: Lei Zhang <27...@users.noreply.github.com>
AuthorDate: Tue Jan 23 01:56:52 2024 +0800
[fix](fe) Upgrade mariadb client version from 3.0.4 to 3.0.9 (#30242)
mariadb-java-client 3.0.4 has two serious problems:
* https://jira.mariadb.org/browse/CONJ-972
* https://jira.mariadb.org/browse/CONJ-973
---
fe/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/fe/pom.xml b/fe/pom.xml
index 36efe4890de..33959e978d6 100644
--- a/fe/pom.xml
+++ b/fe/pom.xml
@@ -322,7 +322,7 @@ under the License.
<httpclient.version>4.5.13</httpclient.version>
<httpcore.version>4.4.15</httpcore.version>
<aws-java-sdk.version>1.12.625</aws-java-sdk.version>
- <mariadb-java-client.version>3.0.4</mariadb-java-client.version>
+ <mariadb-java-client.version>3.0.9</mariadb-java-client.version>
<dlf-metastore-client-hive.version>0.2.14</dlf-metastore-client-hive.version>
<hadoop.version>3.3.6</hadoop.version>
<joda.version>2.8.1</joda.version>
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 32/43: [Improvement](doc) add table-buckets doc for flink connector (#29672)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 68e67470c0ad4be2f5885c5321ef5babc32a2e8a
Author: Petrichor <31...@users.noreply.github.com>
AuthorDate: Mon Jan 22 15:39:28 2024 +0800
[Improvement](doc) add table-buckets doc for flink connector (#29672)
---
docs/en/docs/ecosystem/flink-doris-connector.md | 4 ++--
docs/zh-CN/docs/ecosystem/flink-doris-connector.md | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/en/docs/ecosystem/flink-doris-connector.md b/docs/en/docs/ecosystem/flink-doris-connector.md
index 090f515bfc9..f1ef66b1cb5 100644
--- a/docs/en/docs/ecosystem/flink-doris-connector.md
+++ b/docs/en/docs/ecosystem/flink-doris-connector.md
@@ -531,12 +531,12 @@ insert into doris_sink select id,name,bank,age from cdc_mysql_source;
| --postgres-conf | Postgres CDCSource configuration, e.g. --postgres-conf hostname=127.0.0.1, you can find [here](https://ververica.github.io/flink-cdc-connectors/master/content/connectors/postgres-cdc.html) View all configurations Postgres-CDC where hostname/username/password/database-name/schema-name/slot.name is required. |
| --sqlserver-conf | SQLServer CDCSource configuration, for example --sqlserver-conf hostname=127.0.0.1, you can find it [here](https://ververica.github.io/flink-cdc-connectors/master/content/connectors/sqlserver-cdc.html) View all configurations SQLServer-CDC, where hostname/username/password/database-name/schema-name is required. |
| --sink-conf | All configurations of Doris Sink can be found [here](https://doris.apache.org/zh-CN/docs/dev/ecosystem/flink-doris-connector/#%E9%80%9A%E7%94%A8%E9%85%8D%E7%BD%AE%E9%A1%B9) View the complete configuration items. |
-| --table-conf | The configuration items of the Doris table, that is, the content contained in properties. For example --table-conf replication_num=1 |
+| --table-conf | The configuration items of the Doris table(The exception is table-buckets, non-properties attributes), that is, the content contained in properties. For example `--table-conf replication_num=1`, and the `--table-conf table-buckets="tbl1:10,tbl2:20,a.*:30,b.*:40,.*:50"` option specifies the number of buckets for different tables based on the order of regular expressions. If there is no match, the table is created with the default setting of BUCKETS AUTO. |
| --ignore-default-value | Turn off the default value of synchronizing mysql table structure. It is suitable for synchronizing mysql data to doris when the field has a default value but the actual inserted data is null. Reference [here](https://github.com/apache/doris-flink-connector/pull/152) |
| --use-new-schema-change | Whether to use the new schema change to support synchronization of MySQL multi-column changes and default values. Reference [here](https://github.com/apache/doris-flink-connector/pull/167) |
| --single-sink | Whether to use a single Sink to synchronize all tables. When turned on, newly created tables in the upstream can also be automatically recognized and tables automatically created. |
| --multi-to-one-origin | When writing multiple upstream tables into the same table, the configuration of the source table, for example: --multi-to-one-origin="a\_.\*|b_.\*", Reference [here](https://github.com/apache/doris-flink-connector/pull/208) |
-| --multi-to-one-target | Used with multi-to-one-origin, the configuration of the target table, such as:--multi-to-one-target="a\|b" |
+| --multi-to-one-target | Used with multi-to-one-origin, the configuration of the target table, such as: --multi-to-one-target="a\|b" |
>Note: When synchronizing, you need to add the corresponding Flink CDC dependencies in the $FLINK_HOME/lib directory, such as flink-sql-connector-mysql-cdc-${version}.jar, flink-sql-connector-oracle-cdc-${version}.jar
diff --git a/docs/zh-CN/docs/ecosystem/flink-doris-connector.md b/docs/zh-CN/docs/ecosystem/flink-doris-connector.md
index 6d9b2a8d976..321c7da4298 100644
--- a/docs/zh-CN/docs/ecosystem/flink-doris-connector.md
+++ b/docs/zh-CN/docs/ecosystem/flink-doris-connector.md
@@ -532,7 +532,7 @@ insert into doris_sink select id,name,bank,age from cdc_mysql_source;
| --postgres-conf | Postgres CDCSource 配置,例如--postgres-conf hostname=127.0.0.1 ,您可以在[这里](https://ververica.github.io/flink-cdc-connectors/master/content/connectors/postgres-cdc.html)查看所有配置Postgres-CDC,其中hostname/username/password/database-name/schema-name/slot.name 是必需的。 |
| --sqlserver-conf | SQLServer CDCSource 配置,例如--sqlserver-conf hostname=127.0.0.1 ,您可以在[这里](https://ververica.github.io/flink-cdc-connectors/master/content/connectors/sqlserver-cdc.html)查看所有配置SQLServer-CDC,其中hostname/username/password/database-name/schema-name 是必需的。 |
| --sink-conf | Doris Sink 的所有配置,可以在[这里](https://doris.apache.org/zh-CN/docs/dev/ecosystem/flink-doris-connector/#%E9%80%9A%E7%94%A8%E9%85%8D%E7%BD%AE%E9%A1%B9)查看完整的配置项。 |
-| --table-conf | Doris表的配置项,即properties中包含的内容。 例如 --table-conf replication_num=1 |
+| --table-conf | Doris表的配置项,即properties中包含的内容(其中table-buckets例外,非properties属性)。 例如 `--table-conf replication_num=1`, 而 `--table-conf table-buckets="tbl1:10,tbl2:20,a.*:30,b.*:40,.*:50"`表示按照正则表达式顺序指定不同表的buckets数量,如果没有匹配到则采用BUCKETS AUTO建表。 |
| --ignore-default-value | 关闭同步mysql表结构的默认值。适用于同步mysql数据到doris时,字段有默认值,但实际插入数据为null情况。参考[#152](https://github.com/apache/doris-flink-connector/pull/152) |
| --use-new-schema-change | 是否使用新的schema change,支持同步mysql多列变更、默认值。参考[#167](https://github.com/apache/doris-flink-connector/pull/167) |
| --single-sink | 是否使用单个Sink同步所有表,开启后也可自动识别上游新创建的表,自动创建表。 |
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 23/43: [temporary](log) Add temporary log for debug insert into lost result (#30140)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 5a7ce5cbf557fa100b1e6728ea0a690817379ca4
Author: HappenLee <ha...@hotmail.com>
AuthorDate: Mon Jan 22 13:24:02 2024 +0800
[temporary](log) Add temporary log for debug insert into lost result (#30140)
---
be/src/vec/exec/vunion_node.cpp | 4 +++-
be/src/vec/sink/writer/vtablet_writer.cpp | 4 +++-
2 files changed, 6 insertions(+), 2 deletions(-)
diff --git a/be/src/vec/exec/vunion_node.cpp b/be/src/vec/exec/vunion_node.cpp
index 8ee258ca056..e77fd9fee90 100644
--- a/be/src/vec/exec/vunion_node.cpp
+++ b/be/src/vec/exec/vunion_node.cpp
@@ -235,7 +235,9 @@ Status VUnionNode::get_next_const(RuntimeState* state, Block* block) {
}
}
block->set_columns(std::move(mblock.mutable_columns()));
-
+ LOG(INFO) << "temporary log query id: " << print_id(state->query_id())
+ << ", instance id: " << print_id(state->fragment_instance_id())
+ << ", block rows: " << block->rows();
// some insert query like "insert into string_test select 1, repeat('a', 1024 * 1024);"
// the const expr will be in output expr cause the union node return a empty block. so here we
// need add one row to make sure the union node exec const expr return at least one row
diff --git a/be/src/vec/sink/writer/vtablet_writer.cpp b/be/src/vec/sink/writer/vtablet_writer.cpp
index 7af7b115c43..0ca2f7d8ffb 100644
--- a/be/src/vec/sink/writer/vtablet_writer.cpp
+++ b/be/src/vec/sink/writer/vtablet_writer.cpp
@@ -1603,7 +1603,9 @@ Status VTabletWriter::write(doris::vectorized::Block& input_block) {
if (_state->query_options().dry_run_query) {
return status;
}
-
+ LOG(INFO) << "temporary log query id: " << print_id(_state->query_id())
+ << ", instance id: " << print_id(_state->fragment_instance_id())
+ << ", block rows: " << input_block.rows();
// check out of limit
RETURN_IF_ERROR(_send_new_partition_batch());
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 17/43: [regression test](schema change) add boolean type check for agg (#30186)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 06f8266ca21c66b3f646834e908843dff8fcc789
Author: Guangdong Liu <li...@gmail.com>
AuthorDate: Mon Jan 22 12:16:58 2024 +0800
[regression test](schema change) add boolean type check for agg (#30186)
---
.../schema_change_p0/test_schema_change_agg.groovy | 28 ++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/regression-test/suites/schema_change_p0/test_schema_change_agg.groovy b/regression-test/suites/schema_change_p0/test_schema_change_agg.groovy
index 3b2526cfbc1..2534c219ca2 100644
--- a/regression-test/suites/schema_change_p0/test_schema_change_agg.groovy
+++ b/regression-test/suites/schema_change_p0/test_schema_change_agg.groovy
@@ -191,5 +191,33 @@ suite("test_schema_change_agg", "p0") {
assertEquals(2, row[1]);
assertEquals(3, row[2]);
}
+
+ // boolean type
+ sql """ alter table ${tableName3} add column v15 boolean replace NOT NULL default "0" after k13 """
+
+ sleep(10)
+ max_try_num = 6000
+ while (max_try_num--) {
+ String res = getJobState(tableName3)
+ if (res == "FINISHED" || res == "CANCELLED") {
+ assertEquals("FINISHED", res)
+ sleep(3000)
+ break
+ } else {
+ sleep(2000)
+ if (max_try_num < 1){
+ assertEquals(1,2)
+ }
+ }
+ }
+
+ sql """ insert into ${tableName3} values (10002, 2, 3, 4, 5, 6.6, 1.7, 8.81,
+ 'a', 'b', 'c', '2021-10-30', '2021-10-30 00:00:00', true) """
+
+ test {
+ sql """ALTER table ${tableName3} modify COLUMN v15 int replace NOT NULL default "0" after k13"""
+ exception "Can not change BOOLEAN to INT"
+ }
+
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 27/43: [Fix](Job)Incorrect task query result of insert type (#30024)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 5c43708d9203cb4f3e48b3c4de0ecd648057b5c5
Author: Calvin Kirs <ac...@163.com>
AuthorDate: Mon Jan 22 14:46:40 2024 +0800
[Fix](Job)Incorrect task query result of insert type (#30024)
- IdToTask has no persistence, so the queried task will be lost once it is restarted.
- The cancel task does not update metadata after being removed from the running task.
- tvf displays an error when some fields in the query task result are empty
- cycle scheduling job should not be STOP when task fail
---
.../org/apache/doris/job/base/AbstractJob.java | 15 ++++---
.../doris/job/extensions/insert/InsertJob.java | 46 ++++++++++++++++------
.../doris/job/extensions/insert/InsertTask.java | 30 ++++++++------
.../org/apache/doris/job/manager/JobManager.java | 23 +++++++----
.../apache/doris/job/scheduler/JobScheduler.java | 6 +--
.../suites/job_p0/test_base_insert_job.groovy | 24 +++++++----
6 files changed, 95 insertions(+), 49 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/job/base/AbstractJob.java b/fe/fe-core/src/main/java/org/apache/doris/job/base/AbstractJob.java
index 2416a6bca5f..091ac158c1c 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/job/base/AbstractJob.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/job/base/AbstractJob.java
@@ -166,7 +166,7 @@ public abstract class AbstractJob<T extends AbstractTask, C> implements Job<T, C
throw new JobException("no running task");
}
runningTasks.stream().filter(task -> task.getTaskId().equals(taskId)).findFirst()
- .orElseThrow(() -> new JobException("no task id: " + taskId)).cancel();
+ .orElseThrow(() -> new JobException("Not found task id: " + taskId)).cancel();
runningTasks.removeIf(task -> task.getTaskId().equals(taskId));
if (jobConfig.getExecuteType().equals(JobExecuteType.ONE_TIME)) {
updateJobStatus(JobStatus.FINISHED);
@@ -289,19 +289,19 @@ public abstract class AbstractJob<T extends AbstractTask, C> implements Job<T, C
@Override
public void onTaskFail(T task) throws JobException {
- updateJobStatusIfEnd();
+ updateJobStatusIfEnd(false);
runningTasks.remove(task);
}
@Override
public void onTaskSuccess(T task) throws JobException {
- updateJobStatusIfEnd();
+ updateJobStatusIfEnd(true);
runningTasks.remove(task);
}
- private void updateJobStatusIfEnd() throws JobException {
+ private void updateJobStatusIfEnd(boolean taskSuccess) throws JobException {
JobExecuteType executeType = getJobConfig().getExecuteType();
if (executeType.equals(JobExecuteType.MANUAL)) {
return;
@@ -309,7 +309,12 @@ public abstract class AbstractJob<T extends AbstractTask, C> implements Job<T, C
switch (executeType) {
case ONE_TIME:
case INSTANT:
- Env.getCurrentEnv().getJobManager().getJob(jobId).updateJobStatus(JobStatus.FINISHED);
+ this.finishTimeMs = System.currentTimeMillis();
+ if (taskSuccess) {
+ Env.getCurrentEnv().getJobManager().getJob(jobId).updateJobStatus(JobStatus.FINISHED);
+ } else {
+ Env.getCurrentEnv().getJobManager().getJob(jobId).updateJobStatus(JobStatus.STOPPED);
+ }
break;
case RECURRING:
TimerDefinition timerDefinition = getJobConfig().getTimerDefinition();
diff --git a/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertJob.java b/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertJob.java
index ce918c426f8..15e0c37987f 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertJob.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertJob.java
@@ -30,6 +30,7 @@ import org.apache.doris.common.ErrorCode;
import org.apache.doris.common.ErrorReport;
import org.apache.doris.common.FeConstants;
import org.apache.doris.common.LabelAlreadyUsedException;
+import org.apache.doris.common.MetaNotFoundException;
import org.apache.doris.common.io.Text;
import org.apache.doris.common.util.LogBuilder;
import org.apache.doris.common.util.LogKey;
@@ -42,6 +43,7 @@ import org.apache.doris.job.common.JobType;
import org.apache.doris.job.common.TaskType;
import org.apache.doris.job.exception.JobException;
import org.apache.doris.load.FailMsg;
+import org.apache.doris.load.loadv2.LoadJob;
import org.apache.doris.load.loadv2.LoadStatistic;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.mysql.privilege.Privilege;
@@ -272,14 +274,15 @@ public class InsertJob extends AbstractJob<InsertTask, Map<Object, Object>> impl
}
if (CollectionUtils.isEmpty(historyTaskIdList)) {
historyTaskIdList = new ConcurrentLinkedQueue<>();
- Env.getCurrentEnv().getEditLog().logUpdateJob(this);
historyTaskIdList.add(id);
+ Env.getCurrentEnv().getEditLog().logUpdateJob(this);
return;
}
historyTaskIdList.add(id);
if (historyTaskIdList.size() >= Config.max_persistence_task_count) {
historyTaskIdList.poll();
}
+ Env.getCurrentEnv().getEditLog().logUpdateJob(this);
}
@Override
@@ -320,22 +323,44 @@ public class InsertJob extends AbstractJob<InsertTask, Map<Object, Object>> impl
}
//TODO it's will be refactor, we will storage task info in job inner and query from it
List<Long> taskIdList = new ArrayList<>(this.historyTaskIdList);
+ if (getJobConfig().getExecuteType().equals(JobExecuteType.INSTANT)) {
+ Collections.reverse(taskIdList);
+ return queryLoadTasksByTaskIds(taskIdList);
+ }
+ List<LoadJob> loadJobs = Env.getCurrentEnv().getLoadManager().queryLoadJobsByJobIds(taskIdList);
+ if (CollectionUtils.isEmpty(loadJobs)) {
+ return new ArrayList<>();
+ }
+ List<InsertTask> tasks = new ArrayList<>();
+ loadJobs.forEach(loadJob -> {
+ InsertTask task;
+ try {
+ task = new InsertTask(loadJob.getLabel(), loadJob.getDb().getFullName(), null, getCreateUser());
+ task.setCreateTimeMs(loadJob.getCreateTimestamp());
+ } catch (MetaNotFoundException e) {
+ log.warn("load job not found, job id is {}", loadJob.getId());
+ return;
+ }
+ task.setJobId(getJobId());
+ task.setTaskId(loadJob.getId());
+ task.setJobInfo(loadJob);
+ tasks.add(task);
+ });
+ return tasks;
- Collections.reverse(taskIdList);
- return queryLoadTasksByTaskIds(taskIdList);
}
public List<InsertTask> queryLoadTasksByTaskIds(List<Long> taskIdList) {
if (taskIdList.isEmpty()) {
return new ArrayList<>();
}
- List<InsertTask> jobs = new ArrayList<>();
+ List<InsertTask> tasks = new ArrayList<>();
taskIdList.forEach(id -> {
if (null != idToTasks.get(id)) {
- jobs.add(idToTasks.get(id));
+ tasks.add(idToTasks.get(id));
}
});
- return jobs;
+ return tasks;
}
@Override
@@ -354,14 +379,11 @@ public class InsertJob extends AbstractJob<InsertTask, Map<Object, Object>> impl
}
@Override
- public void onTaskFail(InsertTask task) {
- try {
- updateJobStatus(JobStatus.STOPPED);
+ public void onTaskFail(InsertTask task) throws JobException {
+ if (getJobConfig().getExecuteType().equals(JobExecuteType.INSTANT)) {
this.failMsg = new FailMsg(FailMsg.CancelType.LOAD_RUN_FAIL, task.getErrMsg());
- } catch (JobException e) {
- throw new RuntimeException(e);
}
- getRunningTasks().remove(task);
+ super.onTaskFail(task);
}
@Override
diff --git a/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertTask.java b/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertTask.java
index e85e7a1b027..b5d8ea7fc17 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertTask.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/InsertTask.java
@@ -21,11 +21,11 @@ import org.apache.doris.analysis.UserIdentity;
import org.apache.doris.catalog.Column;
import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.ScalarType;
-import org.apache.doris.common.FeConstants;
import org.apache.doris.common.util.TimeUtils;
import org.apache.doris.job.exception.JobException;
import org.apache.doris.job.task.AbstractTask;
import org.apache.doris.load.FailMsg;
+import org.apache.doris.load.loadv2.LoadJob;
import org.apache.doris.load.loadv2.LoadStatistic;
import org.apache.doris.nereids.parser.NereidsParser;
import org.apache.doris.nereids.trees.plans.commands.InsertIntoTableCommand;
@@ -89,7 +89,7 @@ public class InsertTask extends AbstractTask {
@Getter
@Setter
- private InsertJob jobInfo;
+ private LoadJob jobInfo;
private TaskType taskType = TaskType.PENDING;
private MergeType mergeType = MergeType.APPEND;
@@ -127,7 +127,7 @@ public class InsertTask extends AbstractTask {
}
public InsertTask(String labelName, InsertIntoTableCommand insertInto,
- ConnectContext ctx, StmtExecutor executor, LoadStatistic statistic) {
+ ConnectContext ctx, StmtExecutor executor, LoadStatistic statistic) {
this.labelName = labelName;
this.command = insertInto;
this.userIdentity = ctx.getCurrentUserIdentity();
@@ -216,23 +216,27 @@ public class InsertTask extends AbstractTask {
// if task not start, load job is null,return pending task show info
return getPendingTaskTVFInfo();
}
- trow.addToColumnValue(new TCell().setStringVal(String.valueOf(jobInfo.getJobId())));
+ trow.addToColumnValue(new TCell().setStringVal(String.valueOf(jobInfo.getId())));
trow.addToColumnValue(new TCell().setStringVal(String.valueOf(getJobId())));
trow.addToColumnValue(new TCell().setStringVal(labelName));
- trow.addToColumnValue(new TCell().setStringVal(jobInfo.getJobStatus().name()));
+ trow.addToColumnValue(new TCell().setStringVal(jobInfo.getState().name()));
// err msg
- String errMsg = FeConstants.null_string;
+ String errMsg = "";
if (failMsg != null) {
errMsg = "type:" + failMsg.getCancelType() + "; msg:" + failMsg.getMsg();
}
trow.addToColumnValue(new TCell().setStringVal(errMsg));
// create time
- trow.addToColumnValue(new TCell().setStringVal(TimeUtils.longToTimeString(jobInfo.getCreateTimeMs())));
+ trow.addToColumnValue(new TCell().setStringVal(TimeUtils.longToTimeString(jobInfo.getCreateTimestamp())));
// load end time
- trow.addToColumnValue(new TCell().setStringVal(TimeUtils.longToTimeString(jobInfo.getFinishTimeMs())));
+ trow.addToColumnValue(new TCell().setStringVal(TimeUtils.longToTimeString(jobInfo.getFinishTimestamp())));
// tracking url
trow.addToColumnValue(new TCell().setStringVal(trackingUrl));
- trow.addToColumnValue(new TCell().setStringVal(loadStatistic.toJson()));
+ if (null != loadStatistic) {
+ trow.addToColumnValue(new TCell().setStringVal(loadStatistic.toJson()));
+ } else {
+ trow.addToColumnValue(new TCell().setStringVal(""));
+ }
trow.addToColumnValue(new TCell().setStringVal(userIdentity.getQualifiedUser()));
return trow;
}
@@ -244,11 +248,11 @@ public class InsertTask extends AbstractTask {
trow.addToColumnValue(new TCell().setStringVal(String.valueOf(getJobId())));
trow.addToColumnValue(new TCell().setStringVal(getJobId() + LABEL_SPLITTER + getTaskId()));
trow.addToColumnValue(new TCell().setStringVal(getStatus().name()));
- trow.addToColumnValue(new TCell().setStringVal(FeConstants.null_string));
+ trow.addToColumnValue(new TCell().setStringVal(""));
trow.addToColumnValue(new TCell().setStringVal(TimeUtils.longToTimeString(getCreateTimeMs())));
- trow.addToColumnValue(new TCell().setStringVal(FeConstants.null_string));
- trow.addToColumnValue(new TCell().setStringVal(FeConstants.null_string));
- trow.addToColumnValue(new TCell().setStringVal(FeConstants.null_string));
+ trow.addToColumnValue(new TCell().setStringVal(""));
+ trow.addToColumnValue(new TCell().setStringVal(""));
+ trow.addToColumnValue(new TCell().setStringVal(""));
trow.addToColumnValue(new TCell().setStringVal(userIdentity.getQualifiedUser()));
return trow;
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/job/manager/JobManager.java b/fe/fe-core/src/main/java/org/apache/doris/job/manager/JobManager.java
index b069fd5eca6..7e8b01ce287 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/job/manager/JobManager.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/job/manager/JobManager.java
@@ -137,16 +137,21 @@ public class JobManager<T extends AbstractJob<?, C>, C> implements Writable {
* @param ifExists is is true, if job not exist,we will ignore job not exist exception, else throw exception
*/
public void unregisterJob(String jobName, boolean ifExists) throws JobException {
- T dropJob = null;
- for (T job : jobMap.values()) {
- if (job.getJobName().equals(jobName)) {
- dropJob = job;
+ try {
+ T dropJob = null;
+ for (T job : jobMap.values()) {
+ if (job.getJobName().equals(jobName)) {
+ dropJob = job;
+ }
}
+ if (dropJob == null && ifExists) {
+ return;
+ }
+ dropJob(dropJob, jobName);
+ } catch (Exception e) {
+ log.error("drop job error, jobName:" + jobName, e);
+ throw new JobException("unregister job error, jobName:" + jobName);
}
- if (dropJob == null && ifExists) {
- return;
- }
- dropJob(dropJob, jobName);
}
private void dropJob(T dropJob, String jobName) throws JobException {
@@ -284,6 +289,7 @@ public class JobManager<T extends AbstractJob<?, C>, C> implements Writable {
for (T job : jobMap.values()) {
if (job.getJobName().equals(jobName)) {
job.cancelTaskById(taskId);
+ job.logUpdateOperation();
return;
}
}
@@ -378,6 +384,7 @@ public class JobManager<T extends AbstractJob<?, C>, C> implements Writable {
}
}
+ //todo it's not belong to JobManager
public void cancelLoadJob(CancelLoadStmt cs)
throws JobException, AnalysisException, DdlException {
String dbName = cs.getDbName();
diff --git a/fe/fe-core/src/main/java/org/apache/doris/job/scheduler/JobScheduler.java b/fe/fe-core/src/main/java/org/apache/doris/job/scheduler/JobScheduler.java
index 597e39d96ed..a104d3895e1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/job/scheduler/JobScheduler.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/job/scheduler/JobScheduler.java
@@ -184,8 +184,8 @@ public class JobScheduler<T extends AbstractJob<?, C>, C> implements Closeable {
}
for (Map.Entry<Long, T> entry : jobMap.entrySet()) {
T job = entry.getValue();
- if (job.getJobStatus().equals(JobStatus.FINISHED)) {
- clearFinishedJob(job);
+ if (job.getJobStatus().equals(JobStatus.FINISHED) || job.getJobStatus().equals(JobStatus.STOPPED)) {
+ clearEndJob(job);
continue;
}
if (!job.getJobStatus().equals(JobStatus.RUNNING) && !job.getJobConfig().checkIsTimerJob()) {
@@ -195,7 +195,7 @@ public class JobScheduler<T extends AbstractJob<?, C>, C> implements Closeable {
}
}
- private void clearFinishedJob(T job) {
+ private void clearEndJob(T job) {
if (job.getFinishTimeMs() + FINISHED_JOB_CLEANUP_THRESHOLD_TIME_MS < System.currentTimeMillis()) {
return;
}
diff --git a/regression-test/suites/job_p0/test_base_insert_job.groovy b/regression-test/suites/job_p0/test_base_insert_job.groovy
index f4db5907fa2..d9ebb832152 100644
--- a/regression-test/suites/job_p0/test_base_insert_job.groovy
+++ b/regression-test/suites/job_p0/test_base_insert_job.groovy
@@ -71,9 +71,18 @@ suite("test_base_insert_job") {
CREATE JOB ${jobName} ON SCHEDULE every 1 second comment 'test' DO insert into ${tableName} (timestamp, type, user_id) values ('2023-03-18','1','12213');
"""
Thread.sleep(2500)
- def jobs = sql """select * from ${tableName}"""
- println jobs
- assert 3 >= jobs.size() >= (2 as Boolean) //at least 2 records, some times 3 records
+ sql """
+ PAUSE JOB where jobname = '${jobName}'
+ """
+ def tblDatas = sql """select * from ${tableName}"""
+ println tblDatas
+ assert 3 >= tblDatas.size() >= (2 as Boolean) //at least 2 records, some times 3 records
+ def pauseJobId = sql """select id from jobs("type"="insert") where Name='${jobName}'"""
+ def taskStatus = sql """select status from tasks("type"="insert") where jobid= '${pauseJobId.get(0).get(0)}'"""
+ println taskStatus
+ for (int i = 0; i < taskStatus.size(); i++) {
+ assert taskStatus.get(i).get(0) != "FAILED"||taskStatus.get(i).get(0) != "STOPPED"||taskStatus.get(i).get(0) != "STOPPED"
+ }
sql """
CREATE JOB ${jobMixedName} ON SCHEDULE every 1 second DO insert into ${tableName} (timestamp, type, user_id) values ('2023-03-18','1','12213');
"""
@@ -132,9 +141,8 @@ suite("test_base_insert_job") {
sql """cancel task where jobName='${jobName}' and taskId= ${taskId}"""
def cancelTask = sql """ select status from tasks("type"="insert") where jobid= ${onceJobId}"""
println cancelTask
- //check task status
- assert cancelTask.size() == 1
- assert cancelTask.get(0).get(0) == "CANCELED"
+ //check task size is 0, cancel task where be deleted
+ assert cancelTask.size() == 0
// check table data
def dataCount1 = sql """select count(1) from ${tableName}"""
assert dataCount1.get(0).get(0) == 0
@@ -161,14 +169,14 @@ suite("test_base_insert_job") {
assert job.size() == 1
def jobId = job.get(0).get(0);
def tasks = sql """ select status from tasks("type"="insert") where jobid= ${jobId} """
- assert tasks.size() == 1
+ assert tasks.size() == 0
sql """
RESUME JOB where jobname = '${jobName}'
"""
Thread.sleep(2500)
def resumeTasks = sql """ select status from tasks("type"="insert") where jobid= ${jobId} """
println resumeTasks
- assert resumeTasks.size() == 2
+ assert resumeTasks.size() == 1
// assert same job name
try {
sql """
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 22/43: [improvement](statistics) Optimize drop stats operation (#30144)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 62a46876b6284249935b1158f5bea44ed11f5428
Author: Jibing-Li <64...@users.noreply.github.com>
AuthorDate: Mon Jan 22 13:20:34 2024 +0800
[improvement](statistics) Optimize drop stats operation (#30144)
Before, drop stats operation need to call columns * followers times of isMaster() function and the same times of rpc to drop remote column stats. This pr is to reduce the rpc calls and use more efficient way to check master node instead of using isMaster()
---
.../org/apache/doris/analysis/DropStatsStmt.java | 19 ++++++
.../apache/doris/service/FrontendServiceImpl.java | 12 +++-
.../apache/doris/statistics/AnalysisManager.java | 70 ++++++++++++++++------
.../doris/statistics/InvalidateStatsTarget.java | 48 +++++++++++++++
.../apache/doris/statistics/StatisticsCache.java | 17 +-----
5 files changed, 133 insertions(+), 33 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/analysis/DropStatsStmt.java b/fe/fe-core/src/main/java/org/apache/doris/analysis/DropStatsStmt.java
index ac08f01f31e..5e3bd20c0f1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/analysis/DropStatsStmt.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/analysis/DropStatsStmt.java
@@ -53,7 +53,10 @@ public class DropStatsStmt extends DdlStmt {
private Set<String> columnNames;
// Flag to drop external table row count in table_statistics.
private boolean dropTableRowCount;
+ private boolean isAllColumns;
+ private long catalogId;
+ private long dbId;
private long tblId;
public DropStatsStmt(boolean dropExpired) {
@@ -100,10 +103,13 @@ public class DropStatsStmt extends DdlStmt {
DatabaseIf db = catalog.getDbOrAnalysisException(dbName);
TableIf table = db.getTableOrAnalysisException(tblName);
tblId = table.getId();
+ dbId = db.getId();
+ catalogId = catalog.getId();
// check permission
checkAnalyzePriv(db.getFullName(), table.getName());
// check columnNames
if (columnNames != null) {
+ isAllColumns = false;
for (String cName : columnNames) {
if (table.getColumn(cName) == null) {
ErrorReport.reportAnalysisException(
@@ -115,6 +121,7 @@ public class DropStatsStmt extends DdlStmt {
}
}
} else {
+ isAllColumns = true;
columnNames = table.getColumns().stream().map(Column::getName).collect(Collectors.toSet());
}
}
@@ -123,10 +130,22 @@ public class DropStatsStmt extends DdlStmt {
return tblId;
}
+ public long getDbId() {
+ return dbId;
+ }
+
+ public long getCatalogIdId() {
+ return catalogId;
+ }
+
public Set<String> getColumnNames() {
return columnNames;
}
+ public boolean isAllColumns() {
+ return isAllColumns;
+ }
+
public boolean dropTableRowCount() {
return dropTableRowCount;
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java b/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
index 9a98576b110..1a1ceb799c7 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/service/FrontendServiceImpl.java
@@ -95,9 +95,12 @@ import org.apache.doris.qe.QueryState;
import org.apache.doris.qe.StmtExecutor;
import org.apache.doris.qe.VariableMgr;
import org.apache.doris.service.arrowflight.FlightSqlConnectProcessor;
+import org.apache.doris.statistics.AnalysisManager;
import org.apache.doris.statistics.ColumnStatistic;
+import org.apache.doris.statistics.InvalidateStatsTarget;
import org.apache.doris.statistics.ResultRow;
import org.apache.doris.statistics.StatisticsCacheKey;
+import org.apache.doris.statistics.TableStatsMeta;
import org.apache.doris.statistics.query.QueryStats;
import org.apache.doris.system.Backend;
import org.apache.doris.system.Frontend;
@@ -3041,8 +3044,13 @@ public class FrontendServiceImpl implements FrontendService.Iface {
@Override
public TStatus invalidateStatsCache(TInvalidateFollowerStatsCacheRequest request) throws TException {
- StatisticsCacheKey k = GsonUtils.GSON.fromJson(request.key, StatisticsCacheKey.class);
- Env.getCurrentEnv().getStatisticsCache().invalidate(k.tableId, k.idxId, k.colName);
+ InvalidateStatsTarget target = GsonUtils.GSON.fromJson(request.key, InvalidateStatsTarget.class);
+ AnalysisManager analysisManager = Env.getCurrentEnv().getAnalysisManager();
+ TableStatsMeta tableStats = analysisManager.findTableStatsStatus(target.tableId);
+ if (tableStats == null) {
+ return new TStatus(TStatusCode.OK);
+ }
+ analysisManager.invalidateLocalStats(target.catalogId, target.dbId, target.tableId, target.columns, tableStats);
return new TStatus(TStatusCode.OK);
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/statistics/AnalysisManager.java b/fe/fe-core/src/main/java/org/apache/doris/statistics/AnalysisManager.java
index 8f927694dc7..fe64fb14142 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/statistics/AnalysisManager.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/AnalysisManager.java
@@ -58,6 +58,9 @@ import org.apache.doris.statistics.AnalysisInfo.JobType;
import org.apache.doris.statistics.AnalysisInfo.ScheduleType;
import org.apache.doris.statistics.util.DBObjects;
import org.apache.doris.statistics.util.StatisticsUtil;
+import org.apache.doris.system.Frontend;
+import org.apache.doris.system.SystemInfoService;
+import org.apache.doris.thrift.TInvalidateFollowerStatsCacheRequest;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
@@ -646,23 +649,16 @@ public class AnalysisManager implements Writable {
}
Set<String> cols = dropStatsStmt.getColumnNames();
+ long catalogId = dropStatsStmt.getCatalogIdId();
+ long dbId = dropStatsStmt.getDbId();
long tblId = dropStatsStmt.getTblId();
TableStatsMeta tableStats = findTableStatsStatus(dropStatsStmt.getTblId());
if (tableStats == null) {
return;
}
- if (cols == null) {
- tableStats.reset();
- } else {
- dropStatsStmt.getColumnNames().forEach(tableStats::removeColumn);
- StatisticsCache statisticsCache = Env.getCurrentEnv().getStatisticsCache();
- for (String col : cols) {
- statisticsCache.syncInvalidate(tblId, -1L, col);
- }
- tableStats.updatedTime = 0;
- }
- tableStats.userInjected = false;
- logCreateTableStats(tableStats);
+ invalidateLocalStats(catalogId, dbId, tblId, cols, tableStats);
+ // Drop stats ddl is master only operation.
+ invalidateRemoteStats(catalogId, dbId, tblId, cols, dropStatsStmt.isAllColumns());
StatisticsRepository.dropStatistics(tblId, cols);
}
@@ -671,15 +667,55 @@ public class AnalysisManager implements Writable {
if (tableStats == null) {
return;
}
+ long catalogId = table.getDatabase().getCatalog().getId();
+ long dbId = table.getDatabase().getId();
+ long tableId = table.getId();
Set<String> cols = table.getBaseSchema().stream().map(Column::getName).collect(Collectors.toSet());
+ invalidateLocalStats(catalogId, dbId, tableId, cols, tableStats);
+ // Drop stats ddl is master only operation.
+ invalidateRemoteStats(catalogId, dbId, tableId, cols, true);
+ StatisticsRepository.dropStatistics(table.getId(), cols);
+ }
+
+ public void invalidateLocalStats(long catalogId, long dbId, long tableId,
+ Set<String> columns, TableStatsMeta tableStats) {
+ if (tableStats == null) {
+ return;
+ }
StatisticsCache statisticsCache = Env.getCurrentEnv().getStatisticsCache();
- for (String col : cols) {
- tableStats.removeColumn(col);
- statisticsCache.syncInvalidate(table.getId(), -1L, col);
+ if (columns == null) {
+ TableIf table = StatisticsUtil.findTable(catalogId, dbId, tableId);
+ columns = table.getBaseSchema().stream().map(Column::getName).collect(Collectors.toSet());
+ }
+ for (String column : columns) {
+ tableStats.removeColumn(column);
+ statisticsCache.invalidate(tableId, -1, column);
}
tableStats.updatedTime = 0;
- logCreateTableStats(tableStats);
- StatisticsRepository.dropStatistics(table.getId(), cols);
+ tableStats.userInjected = false;
+ }
+
+ public void invalidateRemoteStats(long catalogId, long dbId, long tableId,
+ Set<String> columns, boolean isAllColumns) {
+ InvalidateStatsTarget target = new InvalidateStatsTarget(catalogId, dbId, tableId, columns, isAllColumns);
+ TInvalidateFollowerStatsCacheRequest request = new TInvalidateFollowerStatsCacheRequest();
+ request.key = GsonUtils.GSON.toJson(target);
+ StatisticsCache statisticsCache = Env.getCurrentEnv().getStatisticsCache();
+ SystemInfoService.HostInfo selfNode = Env.getCurrentEnv().getSelfNode();
+ boolean success = true;
+ for (Frontend frontend : Env.getCurrentEnv().getFrontends(null)) {
+ // Skip master
+ if (selfNode.equals(frontend.getHost())) {
+ continue;
+ }
+ success = success && statisticsCache.invalidateStats(frontend, request);
+ }
+ if (!success) {
+ // If any rpc failed, use edit log to sync table stats to non-master FEs.
+ LOG.warn("Failed to invalidate all remote stats by rpc for table {}, use edit log.", tableId);
+ TableStatsMeta tableStats = findTableStatsStatus(tableId);
+ logCreateTableStats(tableStats);
+ }
}
public void handleKillAnalyzeStmt(KillAnalysisJobStmt killAnalysisJobStmt) throws DdlException {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/statistics/InvalidateStatsTarget.java b/fe/fe-core/src/main/java/org/apache/doris/statistics/InvalidateStatsTarget.java
new file mode 100644
index 00000000000..e49048f8946
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/InvalidateStatsTarget.java
@@ -0,0 +1,48 @@
+// 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.
+
+package org.apache.doris.statistics;
+
+import com.google.gson.annotations.SerializedName;
+
+import java.util.Set;
+
+public class InvalidateStatsTarget {
+
+ @SerializedName("catalogId")
+ public final long catalogId;
+
+ @SerializedName("dbId")
+ public final long dbId;
+
+ @SerializedName("tableId")
+ public final long tableId;
+
+ @SerializedName("columns")
+ public final Set<String> columns;
+
+ public InvalidateStatsTarget(long catalogId, long dbId, long tableId, Set<String> columns, boolean isAllColumns) {
+ this.catalogId = catalogId;
+ this.dbId = dbId;
+ this.tableId = tableId;
+ if (isAllColumns) {
+ this.columns = null;
+ } else {
+ this.columns = columns;
+ }
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/statistics/StatisticsCache.java b/fe/fe-core/src/main/java/org/apache/doris/statistics/StatisticsCache.java
index fbec9a60fa0..0cf2808222e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/statistics/StatisticsCache.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/StatisticsCache.java
@@ -137,19 +137,6 @@ public class StatisticsCache {
columnStatisticsCache.synchronous().invalidate(new StatisticsCacheKey(tblId, idxId, colName));
}
- public void syncInvalidate(long tblId, long idxId, String colName) {
- StatisticsCacheKey cacheKey = new StatisticsCacheKey(tblId, idxId, colName);
- columnStatisticsCache.synchronous().invalidate(cacheKey);
- TInvalidateFollowerStatsCacheRequest request = new TInvalidateFollowerStatsCacheRequest();
- request.key = GsonUtils.GSON.toJson(cacheKey);
- for (Frontend frontend : Env.getCurrentEnv().getFrontends(FrontendNodeType.FOLLOWER)) {
- if (StatisticsUtil.isMaster(frontend)) {
- continue;
- }
- invalidateStats(frontend, request);
- }
- }
-
public void updateColStatsCache(long tblId, long idxId, String colName, ColumnStatistic statistic) {
columnStatisticsCache.synchronous().put(new StatisticsCacheKey(tblId, idxId, colName), Optional.of(statistic));
}
@@ -261,7 +248,7 @@ public class StatisticsCache {
}
@VisibleForTesting
- public void invalidateStats(Frontend frontend, TInvalidateFollowerStatsCacheRequest request) {
+ public boolean invalidateStats(Frontend frontend, TInvalidateFollowerStatsCacheRequest request) {
TNetworkAddress address = new TNetworkAddress(frontend.getHost(), frontend.getRpcPort());
FrontendService.Client client = null;
try {
@@ -269,11 +256,13 @@ public class StatisticsCache {
client.invalidateStatsCache(request);
} catch (Throwable t) {
LOG.warn("Failed to sync invalidate to follower: {}", address, t);
+ return false;
} finally {
if (client != null) {
ClientPool.frontendPool.returnObject(address, client);
}
}
+ return true;
}
public void putCache(StatisticsCacheKey k, ColumnStatistic c) {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 30/43: [docker](container)create data path after rm residual data avoiding docker start fail (#30141)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 9b100207d23da2caf3f3201ac7bf64855ccd5d6b
Author: chunping <ce...@163.com>
AuthorDate: Mon Jan 22 15:09:23 2024 +0800
[docker](container)create data path after rm residual data avoiding docker start fail (#30141)
---
docker/thirdparties/run-thirdparties-docker.sh | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/docker/thirdparties/run-thirdparties-docker.sh b/docker/thirdparties/run-thirdparties-docker.sh
index 3ff8a299976..1a3faba5617 100755
--- a/docker/thirdparties/run-thirdparties-docker.sh
+++ b/docker/thirdparties/run-thirdparties-docker.sh
@@ -198,8 +198,8 @@ if [[ "${RUN_MYSQL}" -eq 1 ]]; then
sed -i "s/doris--/${CONTAINER_UID}/g" "${ROOT}"/docker-compose/mysql/mysql-5.7.yaml
sudo docker compose -f "${ROOT}"/docker-compose/mysql/mysql-5.7.yaml --env-file "${ROOT}"/docker-compose/mysql/mysql-5.7.env down
if [[ "${STOP}" -ne 1 ]]; then
- sudo mkdir -p "${ROOT}"/docker-compose/mysql/data/
sudo rm "${ROOT}"/docker-compose/mysql/data/* -rf
+ sudo mkdir -p "${ROOT}"/docker-compose/mysql/data/
sudo docker compose -f "${ROOT}"/docker-compose/mysql/mysql-5.7.yaml --env-file "${ROOT}"/docker-compose/mysql/mysql-5.7.env up -d
fi
fi
@@ -210,8 +210,8 @@ if [[ "${RUN_PG}" -eq 1 ]]; then
sed -i "s/doris--/${CONTAINER_UID}/g" "${ROOT}"/docker-compose/postgresql/postgresql-14.yaml
sudo docker compose -f "${ROOT}"/docker-compose/postgresql/postgresql-14.yaml --env-file "${ROOT}"/docker-compose/postgresql/postgresql-14.env down
if [[ "${STOP}" -ne 1 ]]; then
- sudo mkdir -p "${ROOT}"/docker-compose/postgresql/data/data
sudo rm "${ROOT}"/docker-compose/postgresql/data/* -rf
+ sudo mkdir -p "${ROOT}"/docker-compose/postgresql/data/data
sudo docker compose -f "${ROOT}"/docker-compose/postgresql/postgresql-14.yaml --env-file "${ROOT}"/docker-compose/postgresql/postgresql-14.env up -d
fi
fi
@@ -222,8 +222,8 @@ if [[ "${RUN_ORACLE}" -eq 1 ]]; then
sed -i "s/doris--/${CONTAINER_UID}/g" "${ROOT}"/docker-compose/oracle/oracle-11.yaml
sudo docker compose -f "${ROOT}"/docker-compose/oracle/oracle-11.yaml --env-file "${ROOT}"/docker-compose/oracle/oracle-11.env down
if [[ "${STOP}" -ne 1 ]]; then
- sudo mkdir -p "${ROOT}"/docker-compose/oracle/data/
sudo rm "${ROOT}"/docker-compose/oracle/data/* -rf
+ sudo mkdir -p "${ROOT}"/docker-compose/oracle/data/
sudo docker compose -f "${ROOT}"/docker-compose/oracle/oracle-11.yaml --env-file "${ROOT}"/docker-compose/oracle/oracle-11.env up -d
fi
fi
@@ -234,8 +234,8 @@ if [[ "${RUN_SQLSERVER}" -eq 1 ]]; then
sed -i "s/doris--/${CONTAINER_UID}/g" "${ROOT}"/docker-compose/sqlserver/sqlserver.yaml
sudo docker compose -f "${ROOT}"/docker-compose/sqlserver/sqlserver.yaml --env-file "${ROOT}"/docker-compose/sqlserver/sqlserver.env down
if [[ "${STOP}" -ne 1 ]]; then
- sudo mkdir -p "${ROOT}"/docker-compose/sqlserver/data/
sudo rm "${ROOT}"/docker-compose/sqlserver/data/* -rf
+ sudo mkdir -p "${ROOT}"/docker-compose/sqlserver/data/
sudo docker compose -f "${ROOT}"/docker-compose/sqlserver/sqlserver.yaml --env-file "${ROOT}"/docker-compose/sqlserver/sqlserver.env up -d
fi
fi
@@ -246,8 +246,8 @@ if [[ "${RUN_CLICKHOUSE}" -eq 1 ]]; then
sed -i "s/doris--/${CONTAINER_UID}/g" "${ROOT}"/docker-compose/clickhouse/clickhouse.yaml
sudo docker compose -f "${ROOT}"/docker-compose/clickhouse/clickhouse.yaml --env-file "${ROOT}"/docker-compose/clickhouse/clickhouse.env down
if [[ "${STOP}" -ne 1 ]]; then
- sudo mkdir -p "${ROOT}"/docker-compose/clickhouse/data/
sudo rm "${ROOT}"/docker-compose/clickhouse/data/* -rf
+ sudo mkdir -p "${ROOT}"/docker-compose/clickhouse/data/
sudo docker compose -f "${ROOT}"/docker-compose/clickhouse/clickhouse.yaml --env-file "${ROOT}"/docker-compose/clickhouse/clickhouse.env up -d
fi
fi
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 29/43: [fix](exec_node) crashing caused by cancelled query in ExecNode (#30192)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 1b1e088e832122c753f066743b2263d55af4731c
Author: Jerry Hu <mr...@gmail.com>
AuthorDate: Mon Jan 22 15:04:27 2024 +0800
[fix](exec_node) crashing caused by cancelled query in ExecNode (#30192)
---
be/src/exec/exec_node.cpp | 20 ++++++++++----------
1 file changed, 10 insertions(+), 10 deletions(-)
diff --git a/be/src/exec/exec_node.cpp b/be/src/exec/exec_node.cpp
index 6bc6e07c563..d65e8f96bd2 100644
--- a/be/src/exec/exec_node.cpp
+++ b/be/src/exec/exec_node.cpp
@@ -558,22 +558,22 @@ Status ExecNode::get_next_after_projects(
RuntimeState* state, vectorized::Block* block, bool* eos,
const std::function<Status(RuntimeState*, vectorized::Block*, bool*)>& func,
bool clear_data) {
- Defer defer([block, this]() {
- if (block && !block->empty()) {
- COUNTER_UPDATE(_output_bytes_counter, block->allocated_bytes());
- COUNTER_UPDATE(_block_count_counter, 1);
- }
- });
if (_output_row_descriptor) {
if (clear_data) {
clear_origin_block();
}
- auto status = func(state, &_origin_block, eos);
- if (UNLIKELY(!status.ok())) return status;
- return do_projections(&_origin_block, block);
+ RETURN_IF_ERROR(func(state, &_origin_block, eos));
+ RETURN_IF_ERROR(do_projections(&_origin_block, block));
+ } else {
+ RETURN_IF_ERROR(func(state, block, eos));
}
_peak_memory_usage_counter->set(_mem_tracker->peak_consumption());
- return func(state, block, eos);
+
+ if (block && !block->empty()) {
+ COUNTER_UPDATE(_output_bytes_counter, block->allocated_bytes());
+ COUNTER_UPDATE(_block_count_counter, 1);
+ }
+ return Status::OK();
}
Status ExecNode::sink(RuntimeState* state, vectorized::Block* input_block, bool eos) {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 02/43: [enhance-wip](multi-catalog) Speed up consume rate of hms events. (#27666)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 8a75da0fec3a795117bb12244de350acd7ca8208
Author: Xiangyu Wang <du...@gmail.com>
AuthorDate: Fri Jan 19 15:24:12 2024 +0800
[enhance-wip](multi-catalog) Speed up consume rate of hms events. (#27666)
## Proposed changes
The current implement will persist all catalogs/databases of external catalogs, and only the master FE can handle hms events and make all slave nodes replay these events, this will bring some problems:
- The hms event processor ( `MetastoreEventsProcessor` ) can not consume the events in time. (Add journal log is a synchronized method, we can not speed up the consume rate by using concurrent processing, and each add-journal-log operation costs about tens of milliseconds) So the meta info of hive maybe out of date.
- Slave FE nodes maybe crashed if FE replays the journal logs of hms events failed. (In fact we have fixed some issues about this, but we can not make sure all the issues have been resolved)
- There are many journal logs which are produced by hms events, but in fact these logs are not used anymore after FE restart. It makes the start time of all FE nodes very long.
Now doris try to persis all databases/tables of external catalogs just to make sure that the dbId/tableId of databases/tables are the same through all FE nodes, it will be used by analysis jobs.
In this pr, we use a meta id manager called `ExternalMetaIdMgr` to manage these meta ids. On every loop when master fetches a batch of hms events, it handles the meta ids first and produce only one meta id mappings log, slave FE nodes will replay this log to sync the changes about these meta ids. `MetastoreEventsProcessor` will start on every FE nodes and try to consume these hms events as soon as possible.
## Further comments
I've submitted two prs ( #22869 #21589 ) to speed up the consume rate of hms events before, it works fine when there are many `AlterTableEvent` / `DropTableEvent` on hive cluster. But the improvement is not that significant when most of hms events are partition-events. Unfortunately, we performed a cluster upgrade (upgrade spark 2.x to spark 3.x), maybe this is the reason that resulting in the majority of Hive Metastore events became partition-events. This is also the reason for the [...]
Based on our observation, after merging this pull request, Doris is now capable of processing thousands of Hive Metastore events per second, compared to the previous capability of handling only a few dozen events.
```java
2023-12-07 05:17:03,518 INFO (replayer|105) [Env.replayJournal():2614] replayed journal id is 18287902, replay to journal id is 18287903
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEventFactory.mergeEvents():188] Event size on catalog [xxx] before merge is [1947], after merge is [1849]
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357955309 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[partitions=2022-05-27],partitionNameAfter:[partitions=2022-05-27]
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357955310 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[pday=20230318],partitionNameAfter:[pday=20230318]
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357955311 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[pday=20190826],partitionNameAfter:[pday=20190826]
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357955312 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[partitions=2021-09-16],partitionNameAfter:[partitions=2021-09-16]
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357955314 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[partitions=2020-04-26],partitionNameAfter:[partitions=2020-04-26]
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357955315 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[pday=20230702],partitionNameAfter:[pday=20230702]
2023-12-07 05:17:03,735 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357955317 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[pday=20211019],partitionNameAfter:[pday=20211019]
...
2023-12-07 05:17:03,989 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357957252 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[partitions=2021-08-27],partitionNameAfter:[partitions=2021-08-27]
2023-12-07 05:17:03,989 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEvent.infoLog():193] EventId: 357957253 EventType: ALTER_PARTITION catalogName:[xxx],dbName:[xxx],tableName:[xxx],partitionNameBefore:[partitions=2022-02-05],partitionNameAfter:[partitions=2022-02-05]
2023-12-07 05:17:04,661 INFO (replayer|105) [Env.replayJournal():2614] replayed journal id is 18287903, replay to journal id is 18287904
2023-12-07 05:17:05,028 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEventsProcessor.realRun():116] Events size are 587 on catalog [xxx]
2023-12-07 05:17:05,662 INFO (org.apache.doris.datasource.hive.event.MetastoreEventsProcessor|37) [MetastoreEventFactory.mergeEvents():188] Event size on catalog [xxx] before merge is [587], after merge is [587]
```
---
.../main/java/org/apache/doris/catalog/Env.java | 17 +-
.../doris/catalog/external/ExternalDatabase.java | 20 +-
.../catalog/external/HMSExternalDatabase.java | 13 +-
.../catalog/external/IcebergExternalDatabase.java | 4 +-
.../catalog/external/PaimonExternalDatabase.java | 4 +-
.../org/apache/doris/datasource/CatalogMgr.java | 257 +++----------------
.../apache/doris/datasource/ExternalCatalog.java | 14 +-
.../apache/doris/datasource/ExternalMetaIdMgr.java | 263 ++++++++++++++++++++
.../doris/datasource/HMSExternalCatalog.java | 107 ++------
.../org/apache/doris/datasource/InitTableLog.java | 67 -----
.../apache/doris/datasource/MetaIdMappingsLog.java | 274 +++++++++++++++++++++
.../datasource/hive/event/AddPartitionEvent.java | 16 ++
.../datasource/hive/event/AlterTableEvent.java | 6 +-
.../datasource/hive/event/CreateDatabaseEvent.java | 12 +
.../datasource/hive/event/CreateTableEvent.java | 14 +-
.../datasource/hive/event/DropDatabaseEvent.java | 11 +
.../datasource/hive/event/DropPartitionEvent.java | 17 +-
.../datasource/hive/event/DropTableEvent.java | 15 +-
.../datasource/hive/event/MetastoreEvent.java | 9 +
.../hive/event/MetastoreEventFactory.java | 26 +-
.../hive/event/MetastoreEventsProcessor.java | 225 ++++++++++++++---
.../org/apache/doris/journal/JournalEntity.java | 20 +-
.../java/org/apache/doris/persist/EditLog.java | 29 +--
.../org/apache/doris/persist/OperationType.java | 9 +
.../doris/datasource/ExternalMetaIdMgrTest.java | 76 ++++++
.../doris/datasource/MetaIdMappingsLogTest.java | 97 ++++++++
.../external/hms/MetastoreEventFactoryTest.java | 2 +-
27 files changed, 1138 insertions(+), 486 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
index 5941ea8305b..62c3a1a5265 100755
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
@@ -131,6 +131,7 @@ import org.apache.doris.datasource.CatalogIf;
import org.apache.doris.datasource.CatalogMgr;
import org.apache.doris.datasource.EsExternalCatalog;
import org.apache.doris.datasource.ExternalMetaCacheMgr;
+import org.apache.doris.datasource.ExternalMetaIdMgr;
import org.apache.doris.datasource.InternalCatalog;
import org.apache.doris.datasource.hive.HiveTransactionMgr;
import org.apache.doris.datasource.hive.event.MetastoreEventsProcessor;
@@ -362,6 +363,7 @@ public class Env {
private DbUsedDataQuotaInfoCollector dbUsedDataQuotaInfoCollector;
private PartitionInMemoryInfoCollector partitionInMemoryInfoCollector;
private CooldownConfHandler cooldownConfHandler;
+ private ExternalMetaIdMgr externalMetaIdMgr;
private MetastoreEventsProcessor metastoreEventsProcessor;
private ExportTaskRegister exportTaskRegister;
@@ -649,6 +651,7 @@ public class Env {
if (Config.enable_storage_policy) {
this.cooldownConfHandler = new CooldownConfHandler();
}
+ this.externalMetaIdMgr = new ExternalMetaIdMgr();
this.metastoreEventsProcessor = new MetastoreEventsProcessor();
this.jobManager = new JobManager<>();
this.labelProcessor = new LabelProcessor();
@@ -844,6 +847,14 @@ public class Env {
return workloadRuntimeStatusMgr;
}
+ public ExternalMetaIdMgr getExternalMetaIdMgr() {
+ return externalMetaIdMgr;
+ }
+
+ public MetastoreEventsProcessor getMetastoreEventsProcessor() {
+ return metastoreEventsProcessor;
+ }
+
// use this to get correct ClusterInfoService instance
public static SystemInfoService getCurrentSystemInfo() {
return getCurrentEnv().getClusterInfo();
@@ -1638,9 +1649,6 @@ public class Env {
streamLoadRecordMgr.start();
tabletLoadIndexRecorderMgr.start();
new InternalSchemaInitializer().start();
- if (Config.enable_hms_events_incremental_sync) {
- metastoreEventsProcessor.start();
- }
getRefreshManager().start();
// binlog gcer
@@ -1662,6 +1670,9 @@ public class Env {
domainResolver.start();
// fe disk updater
feDiskUpdater.start();
+ if (Config.enable_hms_events_incremental_sync) {
+ metastoreEventsProcessor.start();
+ }
}
private void transferToNonMaster(FrontendNodeType newType) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/ExternalDatabase.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/ExternalDatabase.java
index e6584d4a0b6..4af08e9b384 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/ExternalDatabase.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/ExternalDatabase.java
@@ -146,8 +146,15 @@ public abstract class ExternalDatabase<T extends ExternalTable>
Map<Long, T> tmpIdToTbl = Maps.newConcurrentMap();
for (int i = 0; i < log.getRefreshCount(); i++) {
T table = getTableForReplay(log.getRefreshTableIds().get(i));
- tmpTableNameToId.put(table.getName(), table.getId());
- tmpIdToTbl.put(table.getId(), table);
+ // When upgrade cluster with this pr: https://github.com/apache/doris/pull/27666
+ // Maybe there are some create table events will be skipped
+ // if the cluster has any hms catalog(s) with hms event listener enabled.
+ // So we need add a validation here to avoid table(s) not found, this is just a temporary solution
+ // because later we will remove all the logics about InitCatalogLog/InitDatabaseLog.
+ if (table != null) {
+ tmpTableNameToId.put(table.getName(), table.getId());
+ tmpIdToTbl.put(table.getId(), table);
+ }
}
for (int i = 0; i < log.getCreateCount(); i++) {
T table = getExternalTable(log.getCreateTableNames().get(i), log.getCreateTableIds().get(i), catalog);
@@ -195,8 +202,7 @@ public abstract class ExternalDatabase<T extends ExternalTable>
idToTbl = tmpIdToTbl;
}
- long currentTime = System.currentTimeMillis();
- lastUpdateTime = currentTime;
+ lastUpdateTime = System.currentTimeMillis();
initDatabaseLog.setLastUpdateTime(lastUpdateTime);
initialized = true;
Env.getCurrentEnv().getEditLog().logInitExternalDb(initDatabaseLog);
@@ -370,17 +376,13 @@ public abstract class ExternalDatabase<T extends ExternalTable>
throw new NotImplementedException("dropTable() is not implemented");
}
- public void dropTableForReplay(String tableName) {
- throw new NotImplementedException("replayDropTableFromEvent() is not implemented");
- }
-
@Override
public CatalogIf getCatalog() {
return extCatalog;
}
// Only used for sync hive metastore event
- public void createTableForReplay(String tableName, long tableId) {
+ public void createTable(String tableName, long tableId) {
throw new NotImplementedException("createTable() is not implemented");
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/HMSExternalDatabase.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/HMSExternalDatabase.java
index d75f86bd088..f586ea7ed8a 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/HMSExternalDatabase.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/HMSExternalDatabase.java
@@ -64,17 +64,6 @@ public class HMSExternalDatabase extends ExternalDatabase<HMSExternalTable> {
@Override
public void dropTable(String tableName) {
- LOG.debug("drop table [{}]", tableName);
- makeSureInitialized();
- Long tableId = tableNameToId.remove(tableName);
- if (tableId == null) {
- LOG.warn("drop table [{}] failed", tableName);
- }
- idToTbl.remove(tableId);
- }
-
- @Override
- public void dropTableForReplay(String tableName) {
LOG.debug("replayDropTableFromEvent [{}]", tableName);
Long tableId = tableNameToId.remove(tableName);
if (tableId == null) {
@@ -85,7 +74,7 @@ public class HMSExternalDatabase extends ExternalDatabase<HMSExternalTable> {
}
@Override
- public void createTableForReplay(String tableName, long tableId) {
+ public void createTable(String tableName, long tableId) {
LOG.debug("create table [{}]", tableName);
tableNameToId.put(tableName, tableId);
HMSExternalTable table = getExternalTable(tableName, tableId, extCatalog);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/IcebergExternalDatabase.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/IcebergExternalDatabase.java
index a915b3b2418..1b5cd805a0f 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/IcebergExternalDatabase.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/IcebergExternalDatabase.java
@@ -49,7 +49,7 @@ public class IcebergExternalDatabase extends ExternalDatabase<IcebergExternalTab
}
@Override
- public void dropTableForReplay(String tableName) {
+ public void dropTable(String tableName) {
LOG.debug("drop table [{}]", tableName);
Long tableId = tableNameToId.remove(tableName);
if (tableId == null) {
@@ -59,7 +59,7 @@ public class IcebergExternalDatabase extends ExternalDatabase<IcebergExternalTab
}
@Override
- public void createTableForReplay(String tableName, long tableId) {
+ public void createTable(String tableName, long tableId) {
LOG.debug("create table [{}]", tableName);
tableNameToId.put(tableName, tableId);
IcebergExternalTable table = new IcebergExternalTable(tableId, tableName, name,
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/PaimonExternalDatabase.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/PaimonExternalDatabase.java
index a839b31298f..0e6ee7332d0 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/external/PaimonExternalDatabase.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/external/PaimonExternalDatabase.java
@@ -49,7 +49,7 @@ public class PaimonExternalDatabase extends ExternalDatabase<PaimonExternalTable
}
@Override
- public void dropTableForReplay(String tableName) {
+ public void dropTable(String tableName) {
LOG.debug("drop table [{}]", tableName);
Long tableId = tableNameToId.remove(tableName);
if (tableId == null) {
@@ -59,7 +59,7 @@ public class PaimonExternalDatabase extends ExternalDatabase<PaimonExternalTable
}
@Override
- public void createTableForReplay(String tableName, long tableId) {
+ public void createTable(String tableName, long tableId) {
LOG.debug("create table [{}]", tableName);
tableNameToId.put(tableName, tableId);
PaimonExternalTable table = new PaimonExternalTable(tableId, tableName, name,
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/CatalogMgr.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/CatalogMgr.java
index d727ee620f6..d08d4042ace 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/CatalogMgr.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/CatalogMgr.java
@@ -32,6 +32,7 @@ import org.apache.doris.catalog.Resource.ReferenceType;
import org.apache.doris.catalog.TableIf;
import org.apache.doris.catalog.external.ExternalDatabase;
import org.apache.doris.catalog.external.ExternalTable;
+import org.apache.doris.catalog.external.HMSExternalDatabase;
import org.apache.doris.catalog.external.HMSExternalTable;
import org.apache.doris.cluster.ClusterNamespace;
import org.apache.doris.common.AnalysisException;
@@ -344,10 +345,10 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
writeLock();
try {
CatalogIf catalog = nameToCatalog.get(stmt.getCatalogName());
- Map<String, String> oldProperties = catalog.getProperties();
if (catalog == null) {
throw new DdlException("No catalog found with name: " + stmt.getCatalogName());
}
+ Map<String, String> oldProperties = catalog.getProperties();
if (stmt.getNewProperties().containsKey("type") && !catalog.getType()
.equalsIgnoreCase(stmt.getNewProperties().get("type"))) {
throw new DdlException("Can't modify the type of catalog property with name: " + stmt.getCatalogName());
@@ -681,12 +682,6 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
((HMSExternalTable) table).unsetObjectCreated();
((HMSExternalTable) table).setEventUpdateTime(updateTime);
Env.getCurrentEnv().getExtMetaCacheMgr().invalidateTableCache(catalog.getId(), dbName, tableName);
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(db.getId());
- log.setTableId(table.getId());
- log.setLastUpdateTime(updateTime);
- Env.getCurrentEnv().getEditLog().logRefreshExternalTable(log);
}
public void refreshExternalTable(String dbName, String tableName, String catalogName, boolean ignoreIfNotExists)
@@ -772,43 +767,16 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
}
return;
}
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(db.getId());
- log.setTableId(table.getId());
- log.setLastUpdateTime(System.currentTimeMillis());
- replayDropExternalTable(log);
- Env.getCurrentEnv().getEditLog().logDropExternalTable(log);
- }
- public void replayDropExternalTable(ExternalObjectLog log) {
- LOG.debug("ReplayDropExternalTable,catalogId:[{}],dbId:[{}],tableId:[{}]", log.getCatalogId(), log.getDbId(),
- log.getTableId());
- ExternalCatalog catalog = (ExternalCatalog) idToCatalog.get(log.getCatalogId());
- if (catalog == null) {
- LOG.warn("No catalog found with id:[{}], it may have been dropped.", log.getCatalogId());
- return;
- }
- ExternalDatabase db = catalog.getDbForReplay(log.getDbId());
- if (db == null) {
- LOG.warn("No db found with id:[{}], it may have been dropped.", log.getDbId());
- return;
- }
- ExternalTable table = db.getTableForReplay(log.getTableId());
- if (table == null) {
- LOG.warn("No table found with id:[{}], it may have been dropped.", log.getTableId());
- return;
- }
db.writeLock();
try {
- db.dropTableForReplay(table.getName());
- db.setLastUpdateTime(log.getLastUpdateTime());
+ db.dropTable(table.getName());
+ Env.getCurrentEnv().getExtMetaCacheMgr().invalidateTableCache(
+ catalog.getId(), db.getFullName(), table.getName());
+ ((HMSExternalDatabase) db).setLastUpdateTime(System.currentTimeMillis());
} finally {
db.writeUnlock();
}
-
- Env.getCurrentEnv().getExtMetaCacheMgr()
- .invalidateTableCache(catalog.getId(), db.getFullName(), table.getName());
}
public boolean externalTableExistInLocal(String dbName, String tableName, String catalogName) throws DdlException {
@@ -822,9 +790,9 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
return ((ExternalCatalog) catalog).tableExistInLocal(dbName, tableName);
}
- public void createExternalTableFromEvent(String dbName, String tableName, String catalogName,
- boolean ignoreIfExists)
- throws DdlException {
+ public void createExternalTableFromEvent(String dbName, String tableName,
+ String catalogName, long updateTime,
+ boolean ignoreIfExists) throws DdlException {
CatalogIf catalog = nameToCatalog.get(catalogName);
if (catalog == null) {
throw new DdlException("No catalog found with name: " + catalogName);
@@ -847,33 +815,21 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
}
return;
}
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(db.getId());
- log.setTableName(tableName);
- log.setTableId(Env.getCurrentEnv().getNextId());
- log.setLastUpdateTime(System.currentTimeMillis());
- replayCreateExternalTableFromEvent(log);
- Env.getCurrentEnv().getEditLog().logCreateExternalTable(log);
- }
- public void replayCreateExternalTableFromEvent(ExternalObjectLog log) {
- LOG.debug("ReplayCreateExternalTable,catalogId:[{}],dbId:[{}],tableId:[{}],tableName:[{}]", log.getCatalogId(),
- log.getDbId(), log.getTableId(), log.getTableName());
- ExternalCatalog catalog = (ExternalCatalog) idToCatalog.get(log.getCatalogId());
- if (catalog == null) {
- LOG.warn("No catalog found with id:[{}], it may have been dropped.", log.getCatalogId());
- return;
- }
- ExternalDatabase db = catalog.getDbForReplay(log.getDbId());
- if (db == null) {
- LOG.warn("No db found with id:[{}], it may have been dropped.", log.getDbId());
+ long tblId = Env.getCurrentEnv().getExternalMetaIdMgr().getTblId(catalog.getId(), dbName, tableName);
+ // -1L means it will be dropped later, ignore
+ if (tblId == ExternalMetaIdMgr.META_ID_FOR_NOT_EXISTS) {
return;
}
+
db.writeLock();
try {
- db.createTableForReplay(log.getTableName(), log.getTableId());
- db.setLastUpdateTime(log.getLastUpdateTime());
+ ((HMSExternalDatabase) db).createTable(tableName, tblId);
+ ((HMSExternalDatabase) db).setLastUpdateTime(System.currentTimeMillis());
+ table = db.getTableNullable(tableName);
+ if (table != null) {
+ ((HMSExternalTable) table).setEventUpdateTime(updateTime);
+ }
} finally {
db.writeUnlock();
}
@@ -895,34 +851,8 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
return;
}
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(db.getId());
- log.setInvalidCache(true);
- replayDropExternalDatabase(log);
- Env.getCurrentEnv().getEditLog().logDropExternalDatabase(log);
- }
-
- public void replayDropExternalDatabase(ExternalObjectLog log) {
- writeLock();
- try {
- LOG.debug("ReplayDropExternalTable,catalogId:[{}],dbId:[{}],tableId:[{}]", log.getCatalogId(),
- log.getDbId(), log.getTableId());
- ExternalCatalog catalog = (ExternalCatalog) idToCatalog.get(log.getCatalogId());
- if (catalog == null) {
- LOG.warn("No catalog found with id:[{}], it may have been dropped.", log.getCatalogId());
- return;
- }
- ExternalDatabase db = catalog.getDbForReplay(log.getDbId());
- if (db == null) {
- LOG.warn("No db found with id:[{}], it may have been dropped.", log.getDbId());
- return;
- }
- catalog.dropDatabaseForReplay(db.getFullName());
- Env.getCurrentEnv().getExtMetaCacheMgr().invalidateDbCache(catalog.getId(), db.getFullName());
- } finally {
- writeUnlock();
- }
+ ((HMSExternalCatalog) catalog).dropDatabase(dbName);
+ Env.getCurrentEnv().getExtMetaCacheMgr().invalidateDbCache(catalog.getId(), dbName);
}
public void createExternalDatabase(String dbName, String catalogName, boolean ignoreIfExists) throws DdlException {
@@ -941,28 +871,13 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
return;
}
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(Env.getCurrentEnv().getNextId());
- log.setDbName(dbName);
- replayCreateExternalDatabase(log);
- Env.getCurrentEnv().getEditLog().logCreateExternalDatabase(log);
- }
-
- public void replayCreateExternalDatabase(ExternalObjectLog log) {
- writeLock();
- try {
- LOG.debug("ReplayCreateExternalDatabase,catalogId:[{}],dbId:[{}],dbName:[{}]", log.getCatalogId(),
- log.getDbId(), log.getDbName());
- ExternalCatalog catalog = (ExternalCatalog) idToCatalog.get(log.getCatalogId());
- if (catalog == null) {
- LOG.warn("No catalog found with id:[{}], it may have been dropped.", log.getCatalogId());
- return;
- }
- catalog.createDatabaseForReplay(log.getDbId(), log.getDbName());
- } finally {
- writeUnlock();
+ long dbId = Env.getCurrentEnv().getExternalMetaIdMgr().getDbId(catalog.getId(), dbName);
+ // -1L means it will be dropped later, ignore
+ if (dbId == ExternalMetaIdMgr.META_ID_FOR_NOT_EXISTS) {
+ return;
}
+
+ ((HMSExternalCatalog) catalog).createDatabase(dbId, dbName);
}
public void addExternalPartitions(String catalogName, String dbName, String tableName,
@@ -998,48 +913,6 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
HMSExternalTable hmsTable = (HMSExternalTable) table;
Env.getCurrentEnv().getExtMetaCacheMgr().addPartitionsCache(catalog.getId(), hmsTable, partitionNames);
hmsTable.setEventUpdateTime(updateTime);
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(db.getId());
- log.setTableId(table.getId());
- log.setPartitionNames(partitionNames);
- log.setLastUpdateTime(updateTime);
- Env.getCurrentEnv().getEditLog().logAddExternalPartitions(log);
- }
-
- public void replayAddExternalPartitions(ExternalObjectLog log) {
- LOG.debug("ReplayAddExternalPartitions,catalogId:[{}],dbId:[{}],tableId:[{}]", log.getCatalogId(),
- log.getDbId(), log.getTableId());
- ExternalCatalog catalog = (ExternalCatalog) idToCatalog.get(log.getCatalogId());
- if (catalog == null) {
- LOG.warn("No catalog found with id:[{}], it may have been dropped.", log.getCatalogId());
- return;
- }
- ExternalDatabase db = catalog.getDbForReplay(log.getDbId());
- if (db == null) {
- LOG.warn("No db found with id:[{}], it may have been dropped.", log.getDbId());
- return;
- }
- ExternalTable table = db.getTableForReplay(log.getTableId());
- if (table == null) {
- LOG.warn("No table found with id:[{}], it may have been dropped.", log.getTableId());
- return;
- }
- if (!(table instanceof HMSExternalTable)) {
- LOG.warn("only support HMSTable");
- return;
- }
-
- HMSExternalTable hmsTable = (HMSExternalTable) table;
- try {
- Env.getCurrentEnv().getExtMetaCacheMgr()
- .addPartitionsCache(catalog.getId(), hmsTable, log.getPartitionNames());
- hmsTable.setEventUpdateTime(log.getLastUpdateTime());
- } catch (HMSClientException e) {
- LOG.warn("Network problem occurs or hms table has been deleted, fallback to invalidate table cache", e);
- Env.getCurrentEnv().getExtMetaCacheMgr().invalidateTableCache(catalog.getId(),
- db.getFullName(), table.getName());
- }
}
public void dropExternalPartitions(String catalogName, String dbName, String tableName,
@@ -1068,42 +941,9 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
return;
}
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(db.getId());
- log.setTableId(table.getId());
- log.setPartitionNames(partitionNames);
- log.setLastUpdateTime(updateTime);
- replayDropExternalPartitions(log);
- Env.getCurrentEnv().getEditLog().logDropExternalPartitions(log);
- }
-
- public void replayDropExternalPartitions(ExternalObjectLog log) {
- LOG.debug("ReplayDropExternalPartitions,catalogId:[{}],dbId:[{}],tableId:[{}]", log.getCatalogId(),
- log.getDbId(), log.getTableId());
- ExternalCatalog catalog = (ExternalCatalog) idToCatalog.get(log.getCatalogId());
- if (catalog == null) {
- LOG.warn("No catalog found with id:[{}], it may have been dropped.", log.getCatalogId());
- return;
- }
- ExternalDatabase db = catalog.getDbForReplay(log.getDbId());
- if (db == null) {
- LOG.warn("No db found with id:[{}], it may have been dropped.", log.getDbId());
- return;
- }
- ExternalTable table = db.getTableForReplay(log.getTableId());
- if (table == null) {
- LOG.warn("No table found with id:[{}], it may have been dropped.", log.getTableId());
- return;
- }
- if (!(table instanceof HMSExternalTable)) {
- LOG.warn("only support HMSTable");
- return;
- }
HMSExternalTable hmsTable = (HMSExternalTable) table;
- Env.getCurrentEnv().getExtMetaCacheMgr()
- .dropPartitionsCache(catalog.getId(), hmsTable, log.getPartitionNames());
- hmsTable.setEventUpdateTime(log.getLastUpdateTime());
+ Env.getCurrentEnv().getExtMetaCacheMgr().dropPartitionsCache(catalog.getId(), hmsTable, partitionNames);
+ hmsTable.setEventUpdateTime(updateTime);
}
public void refreshExternalPartitions(String catalogName, String dbName, String tableName,
@@ -1135,42 +975,9 @@ public class CatalogMgr implements Writable, GsonPostProcessable {
return;
}
- ExternalObjectLog log = new ExternalObjectLog();
- log.setCatalogId(catalog.getId());
- log.setDbId(db.getId());
- log.setTableId(table.getId());
- log.setPartitionNames(partitionNames);
- log.setLastUpdateTime(updateTime);
- replayRefreshExternalPartitions(log);
- Env.getCurrentEnv().getEditLog().logInvalidateExternalPartitions(log);
- }
-
- public void replayRefreshExternalPartitions(ExternalObjectLog log) {
- LOG.debug("replayRefreshExternalPartitions,catalogId:[{}],dbId:[{}],tableId:[{}]", log.getCatalogId(),
- log.getDbId(), log.getTableId());
- ExternalCatalog catalog = (ExternalCatalog) idToCatalog.get(log.getCatalogId());
- if (catalog == null) {
- LOG.warn("No catalog found with id:[{}], it may have been dropped.", log.getCatalogId());
- return;
- }
- ExternalDatabase db = catalog.getDbForReplay(log.getDbId());
- if (db == null) {
- LOG.warn("No db found with id:[{}], it may have been dropped.", log.getDbId());
- return;
- }
- ExternalTable table = db.getTableForReplay(log.getTableId());
- if (table == null) {
- LOG.warn("No table found with id:[{}], it may have been dropped.", log.getTableId());
- return;
- }
- if (!(table instanceof HMSExternalTable)) {
- LOG.warn("only support HMSTable");
- return;
- }
- Env.getCurrentEnv().getExtMetaCacheMgr()
- .invalidatePartitionsCache(catalog.getId(), db.getFullName(), table.getName(),
- log.getPartitionNames());
- ((HMSExternalTable) table).setEventUpdateTime(log.getLastUpdateTime());
+ Env.getCurrentEnv().getExtMetaCacheMgr().invalidatePartitionsCache(
+ catalog.getId(), db.getFullName(), table.getName(), partitionNames);
+ ((HMSExternalTable) table).setEventUpdateTime(updateTime);
}
public void registerCatalogRefreshListener(Env env) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalCatalog.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalCatalog.java
index 3ff599d0ab4..6fcd495b67f 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalCatalog.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalCatalog.java
@@ -521,13 +521,6 @@ public abstract class ExternalCatalog
return null;
}
- /**
- * External catalog has no cluster semantics.
- */
- protected static String getRealTableName(String tableName) {
- return ClusterNamespace.getNameFromFullName(tableName);
- }
-
public static ExternalCatalog read(DataInput in) throws IOException {
String json = Text.readString(in);
return GsonUtils.GSON.fromJson(json, ExternalCatalog.class);
@@ -546,9 +539,6 @@ public abstract class ExternalCatalog
db.setTableExtCatalog(this);
}
objectCreated = false;
- if (this instanceof HMSExternalCatalog) {
- ((HMSExternalCatalog) this).setLastSyncedEventId(-1L);
- }
// TODO: This code is to compatible with older version of metadata.
// Could only remove after all users upgrate to the new version.
if (logType == null) {
@@ -569,11 +559,11 @@ public abstract class ExternalCatalog
dbNameToId.put(ClusterNamespace.getNameFromFullName(db.getFullName()), db.getId());
}
- public void dropDatabaseForReplay(String dbName) {
+ public void dropDatabase(String dbName) {
throw new NotImplementedException("dropDatabase not implemented");
}
- public void createDatabaseForReplay(long dbId, String dbName) {
+ public void createDatabase(long dbId, String dbName) {
throw new NotImplementedException("createDatabase not implemented");
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalMetaIdMgr.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalMetaIdMgr.java
new file mode 100644
index 00000000000..621c25b3698
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/ExternalMetaIdMgr.java
@@ -0,0 +1,263 @@
+// 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.
+
+package org.apache.doris.datasource;
+
+import org.apache.doris.catalog.Env;
+import org.apache.doris.datasource.hive.event.MetastoreEventsProcessor;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.Map;
+import javax.annotation.Nullable;
+import javax.validation.constraints.NotNull;
+
+/**
+ * <pre>
+ * ExternalMetaIdMgr is responsible for managing external meta ids.
+ * Now it just manages the external meta ids of hms events,
+ * but it will be extended to manage other external meta ids in the future.
+ * </pre>
+ * TODO: remove InitCatalogLog and InitDatabaseLog, manage external meta ids at ExternalMetaIdMgr
+ */
+public class ExternalMetaIdMgr {
+
+ private static final Logger LOG = LogManager.getLogger(ExternalMetaIdMgr.class);
+
+ public static final long META_ID_FOR_NOT_EXISTS = -1L;
+
+ private final Map<Long, CtlMetaIdMgr> idToCtlMgr = Maps.newConcurrentMap();
+
+ public ExternalMetaIdMgr() {
+ }
+
+ // invoke this method only on master
+ public static long nextMetaId() {
+ return Env.getCurrentEnv().getNextId();
+ }
+
+ // return the db id of the specified db, -1 means not exists
+ public long getDbId(long catalogId, String dbName) {
+ DbMetaIdMgr dbMetaIdMgr = getDbMetaIdMgr(catalogId, dbName);
+ if (dbMetaIdMgr == null) {
+ return META_ID_FOR_NOT_EXISTS;
+ }
+ return dbMetaIdMgr.dbId;
+ }
+
+ // return the tbl id of the specified tbl, -1 means not exists
+ public long getTblId(long catalogId, String dbName, String tblName) {
+ TblMetaIdMgr tblMetaIdMgr = getTblMetaIdMgr(catalogId, dbName, tblName);
+ if (tblMetaIdMgr == null) {
+ return META_ID_FOR_NOT_EXISTS;
+ }
+ return tblMetaIdMgr.tblId;
+ }
+
+ // return the partition id of the specified partition, -1 means not exists
+ public long getPartitionId(long catalogId, String dbName,
+ String tblName, String partitionName) {
+ PartitionMetaIdMgr partitionMetaIdMgr = getPartitionMetaIdMgr(catalogId, dbName, tblName, partitionName);
+ if (partitionMetaIdMgr == null) {
+ return META_ID_FOR_NOT_EXISTS;
+ }
+ return partitionMetaIdMgr.partitionId;
+ }
+
+ private @Nullable DbMetaIdMgr getDbMetaIdMgr(long catalogId, String dbName) {
+ CtlMetaIdMgr ctlMetaIdMgr = idToCtlMgr.get(catalogId);
+ if (ctlMetaIdMgr == null) {
+ return null;
+ }
+ return ctlMetaIdMgr.dbNameToMgr.get(dbName);
+ }
+
+ private @Nullable TblMetaIdMgr getTblMetaIdMgr(long catalogId, String dbName, String tblName) {
+ DbMetaIdMgr dbMetaIdMgr = getDbMetaIdMgr(catalogId, dbName);
+ if (dbMetaIdMgr == null) {
+ return null;
+ }
+ return dbMetaIdMgr.tblNameToMgr.get(tblName);
+ }
+
+ private PartitionMetaIdMgr getPartitionMetaIdMgr(long catalogId, String dbName,
+ String tblName, String partitionName) {
+ TblMetaIdMgr tblMetaIdMgr = getTblMetaIdMgr(catalogId, dbName, tblName);
+ if (tblMetaIdMgr == null) {
+ return null;
+ }
+ return tblMetaIdMgr.partitionNameToMgr.get(partitionName);
+ }
+
+ public void replayMetaIdMappingsLog(@NotNull MetaIdMappingsLog log) {
+ Preconditions.checkNotNull(log);
+ long catalogId = log.getCatalogId();
+ CtlMetaIdMgr ctlMetaIdMgr = idToCtlMgr.computeIfAbsent(catalogId, CtlMetaIdMgr::new);
+ for (MetaIdMappingsLog.MetaIdMapping mapping : log.getMetaIdMappings()) {
+ handleMetaIdMapping(mapping, ctlMetaIdMgr);
+ }
+ if (log.isFromHmsEvent()) {
+ CatalogIf<?> catalogIf = Env.getCurrentEnv().getCatalogMgr().getCatalog(log.getCatalogId());
+ if (catalogIf != null) {
+ MetastoreEventsProcessor metastoreEventsProcessor = Env.getCurrentEnv().getMetastoreEventsProcessor();
+ metastoreEventsProcessor.updateMasterLastSyncedEventId(
+ (HMSExternalCatalog) catalogIf, log.getLastSyncedEventId());
+ }
+ }
+ }
+
+ // no lock because the operations is serialized currently
+ private void handleMetaIdMapping(MetaIdMappingsLog.MetaIdMapping mapping, CtlMetaIdMgr ctlMetaIdMgr) {
+ MetaIdMappingsLog.OperationType opType = MetaIdMappingsLog.getOperationType(mapping.getOpType());
+ MetaIdMappingsLog.MetaObjectType objType = MetaIdMappingsLog.getMetaObjectType(mapping.getMetaObjType());
+ switch (opType) {
+ case ADD:
+ handleAddMetaIdMapping(mapping, ctlMetaIdMgr, objType);
+ break;
+
+ case DELETE:
+ handleDelMetaIdMapping(mapping, ctlMetaIdMgr, objType);
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ private static void handleDelMetaIdMapping(MetaIdMappingsLog.MetaIdMapping mapping,
+ CtlMetaIdMgr ctlMetaIdMgr,
+ MetaIdMappingsLog.MetaObjectType objType) {
+ TblMetaIdMgr tblMetaIdMgr;
+ DbMetaIdMgr dbMetaIdMgr;
+ switch (objType) {
+ case DATABASE:
+ ctlMetaIdMgr.dbNameToMgr.remove(mapping.getDbName());
+ break;
+
+ case TABLE:
+ dbMetaIdMgr = ctlMetaIdMgr.dbNameToMgr.get(mapping.getDbName());
+ if (dbMetaIdMgr != null) {
+ dbMetaIdMgr.tblNameToMgr.remove(mapping.getTblName());
+ }
+ break;
+
+ case PARTITION:
+ dbMetaIdMgr = ctlMetaIdMgr.dbNameToMgr.get(mapping.getDbName());
+ if (dbMetaIdMgr != null) {
+ tblMetaIdMgr = dbMetaIdMgr.tblNameToMgr.get(mapping.getTblName());
+ if (tblMetaIdMgr != null) {
+ tblMetaIdMgr.partitionNameToMgr.remove(mapping.getPartitionName());
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ private static void handleAddMetaIdMapping(MetaIdMappingsLog.MetaIdMapping mapping,
+ CtlMetaIdMgr ctlMetaIdMgr,
+ MetaIdMappingsLog.MetaObjectType objType) {
+ DbMetaIdMgr dbMetaIdMgr;
+ TblMetaIdMgr tblMetaIdMgr;
+ switch (objType) {
+ case DATABASE:
+ ctlMetaIdMgr.dbNameToMgr.put(mapping.getDbName(),
+ new DbMetaIdMgr(mapping.getId(), mapping.getDbName()));
+ break;
+
+ case TABLE:
+ dbMetaIdMgr = ctlMetaIdMgr.dbNameToMgr
+ .computeIfAbsent(mapping.getDbName(), DbMetaIdMgr::new);
+ dbMetaIdMgr.tblNameToMgr.put(mapping.getTblName(),
+ new TblMetaIdMgr(mapping.getId(), mapping.getTblName()));
+ break;
+
+ case PARTITION:
+ dbMetaIdMgr = ctlMetaIdMgr.dbNameToMgr
+ .computeIfAbsent(mapping.getDbName(), DbMetaIdMgr::new);
+ tblMetaIdMgr = dbMetaIdMgr.tblNameToMgr
+ .computeIfAbsent(mapping.getTblName(), TblMetaIdMgr::new);
+ tblMetaIdMgr.partitionNameToMgr.put(mapping.getPartitionName(),
+ new PartitionMetaIdMgr(mapping.getId(), mapping.getPartitionName()));
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ public static class CtlMetaIdMgr {
+ protected final long catalogId;
+
+ protected CtlMetaIdMgr(long catalogId) {
+ this.catalogId = catalogId;
+ }
+
+ protected Map<String, DbMetaIdMgr> dbNameToMgr = Maps.newConcurrentMap();
+ }
+
+ public static class DbMetaIdMgr {
+ protected volatile long dbId = META_ID_FOR_NOT_EXISTS;
+ protected final String dbName;
+
+ protected DbMetaIdMgr(long dbId, String dbName) {
+ this.dbId = dbId;
+ this.dbName = dbName;
+ }
+
+ protected DbMetaIdMgr(String dbName) {
+ this.dbName = dbName;
+ }
+
+ protected Map<String, TblMetaIdMgr> tblNameToMgr = Maps.newConcurrentMap();
+ }
+
+ public static class TblMetaIdMgr {
+ protected volatile long tblId = META_ID_FOR_NOT_EXISTS;
+ protected final String tblName;
+
+ protected TblMetaIdMgr(long tblId, String tblName) {
+ this.tblId = tblId;
+ this.tblName = tblName;
+ }
+
+ protected TblMetaIdMgr(String tblName) {
+ this.tblName = tblName;
+ }
+
+ protected Map<String, PartitionMetaIdMgr> partitionNameToMgr = Maps.newConcurrentMap();
+ }
+
+ public static class PartitionMetaIdMgr {
+ protected volatile long partitionId = META_ID_FOR_NOT_EXISTS;
+ protected final String partitionName;
+
+ protected PartitionMetaIdMgr(long partitionId, String partitionName) {
+ this.partitionId = partitionId;
+ this.partitionName = partitionName;
+ }
+
+ protected PartitionMetaIdMgr(String partitionName) {
+ this.partitionName = partitionName;
+ }
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/HMSExternalCatalog.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/HMSExternalCatalog.java
index ae6b5f04738..dd6788ade2c 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/HMSExternalCatalog.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/HMSExternalCatalog.java
@@ -23,23 +23,19 @@ import org.apache.doris.catalog.HdfsResource;
import org.apache.doris.catalog.external.ExternalDatabase;
import org.apache.doris.catalog.external.ExternalTable;
import org.apache.doris.catalog.external.HMSExternalDatabase;
+import org.apache.doris.cluster.ClusterNamespace;
import org.apache.doris.common.Config;
import org.apache.doris.common.DdlException;
import org.apache.doris.datasource.hive.HMSCachedClient;
import org.apache.doris.datasource.hive.HMSCachedClientFactory;
-import org.apache.doris.datasource.hive.event.MetastoreNotificationFetchException;
import org.apache.doris.datasource.jdbc.client.JdbcClientConfig;
import org.apache.doris.datasource.property.PropertyConverter;
import org.apache.doris.datasource.property.constants.HMSProperties;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
-import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
-import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId;
-import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -57,10 +53,7 @@ public class HMSExternalCatalog extends ExternalCatalog {
private static final int MIN_CLIENT_POOL_SIZE = 8;
protected HMSCachedClient client;
- // Record the latest synced event id when processing hive events
- // Must set to -1 otherwise client.getNextNotification will throw exception
- // Reference to https://github.com/apDdlache/doris/issues/18251
- private long lastSyncedEventId = -1L;
+
public static final String ENABLE_SELF_SPLITTER = "enable.self.splitter";
public static final String FILE_META_CACHE_TTL_SECOND = "file.meta.cache.ttl-second";
// broker name for file split and query scan.
@@ -132,18 +125,6 @@ public class HMSExternalCatalog extends ExternalCatalog {
}
}
- public String getHiveMetastoreUris() {
- return catalogProperty.getOrDefault(HMSProperties.HIVE_METASTORE_URIS, "");
- }
-
- public String getHiveVersion() {
- return catalogProperty.getOrDefault(HMSProperties.HIVE_VERSION, "");
- }
-
- protected List<String> listDatabaseNames() {
- return client.getAllDatabases();
- }
-
@Override
protected void initLocalObjectsImpl() {
HiveConf hiveConf = null;
@@ -195,13 +176,13 @@ public class HMSExternalCatalog extends ExternalCatalog {
hmsExternalDatabase.getTables().forEach(table -> names.add(table.getName()));
return names;
} else {
- return client.getAllTables(getRealTableName(dbName));
+ return client.getAllTables(ClusterNamespace.getNameFromFullName(dbName));
}
}
@Override
public boolean tableExist(SessionContext ctx, String dbName, String tblName) {
- return client.tableExists(getRealTableName(dbName), tblName);
+ return client.tableExists(ClusterNamespace.getNameFromFullName(dbName), tblName);
}
@Override
@@ -211,7 +192,7 @@ public class HMSExternalCatalog extends ExternalCatalog {
if (hmsExternalDatabase == null) {
return false;
}
- return hmsExternalDatabase.getTable(getRealTableName(tblName)).isPresent();
+ return hmsExternalDatabase.getTable(ClusterNamespace.getNameFromFullName(tblName)).isPresent();
}
public HMSCachedClient getClient() {
@@ -219,69 +200,8 @@ public class HMSExternalCatalog extends ExternalCatalog {
return client;
}
- public void setLastSyncedEventId(long lastSyncedEventId) {
- this.lastSyncedEventId = lastSyncedEventId;
- }
-
- public NotificationEventResponse getNextEventResponse(HMSExternalCatalog hmsExternalCatalog)
- throws MetastoreNotificationFetchException {
- makeSureInitialized();
- long currentEventId = getCurrentEventId();
- if (lastSyncedEventId < 0) {
- refreshCatalog(hmsExternalCatalog);
- // invoke getCurrentEventId() and save the event id before refresh catalog to avoid missing events
- // but set lastSyncedEventId to currentEventId only if there is not any problems when refreshing catalog
- lastSyncedEventId = currentEventId;
- LOG.info(
- "First pulling events on catalog [{}],refreshCatalog and init lastSyncedEventId,"
- + "lastSyncedEventId is [{}]",
- hmsExternalCatalog.getName(), lastSyncedEventId);
- return null;
- }
-
- LOG.debug("Catalog [{}] getNextEventResponse, currentEventId is {},lastSyncedEventId is {}",
- hmsExternalCatalog.getName(), currentEventId, lastSyncedEventId);
- if (currentEventId == lastSyncedEventId) {
- LOG.info("Event id not updated when pulling events on catalog [{}]", hmsExternalCatalog.getName());
- return null;
- }
-
- try {
- return client.getNextNotification(lastSyncedEventId, Config.hms_events_batch_size_per_rpc, null);
- } catch (MetastoreNotificationFetchException e) {
- // Need a fallback to handle this because this error state can not be recovered until restarting FE
- if (StringUtils.isNotEmpty(e.getMessage())
- && e.getMessage().contains(HiveMetaStoreClient.REPL_EVENTS_MISSING_IN_METASTORE)) {
- refreshCatalog(hmsExternalCatalog);
- // set lastSyncedEventId to currentEventId after refresh catalog successfully
- lastSyncedEventId = currentEventId;
- LOG.warn("Notification events are missing, maybe an event can not be handled "
- + "or processing rate is too low, fallback to refresh the catalog");
- return null;
- }
- throw e;
- }
- }
-
- private void refreshCatalog(HMSExternalCatalog hmsExternalCatalog) {
- CatalogLog log = new CatalogLog();
- log.setCatalogId(hmsExternalCatalog.getId());
- log.setInvalidCache(true);
- Env.getCurrentEnv().getCatalogMgr().refreshCatalog(log);
- }
-
- private long getCurrentEventId() {
- makeSureInitialized();
- CurrentNotificationEventId currentNotificationEventId = client.getCurrentNotificationEventId();
- if (currentNotificationEventId == null) {
- LOG.warn("Get currentNotificationEventId is null");
- return -1;
- }
- return currentNotificationEventId.getEventId();
- }
-
@Override
- public void dropDatabaseForReplay(String dbName) {
+ public void dropDatabase(String dbName) {
LOG.debug("drop database [{}]", dbName);
Long dbId = dbNameToId.remove(dbName);
if (dbId == null) {
@@ -291,7 +211,7 @@ public class HMSExternalCatalog extends ExternalCatalog {
}
@Override
- public void createDatabaseForReplay(long dbId, String dbName) {
+ public void createDatabase(long dbId, String dbName) {
LOG.debug("create database [{}]", dbName);
dbNameToId.put(dbName, dbId);
ExternalDatabase<? extends ExternalTable> db = getDbForInit(dbName, dbId, logType);
@@ -317,4 +237,17 @@ public class HMSExternalCatalog extends ExternalCatalog {
catalogProperty.addProperty(PROP_ALLOW_FALLBACK_TO_SIMPLE_AUTH, "true");
}
}
+
+ public String getHiveMetastoreUris() {
+ return catalogProperty.getOrDefault(HMSProperties.HIVE_METASTORE_URIS, "");
+ }
+
+ public String getHiveVersion() {
+ return catalogProperty.getOrDefault(HMSProperties.HIVE_VERSION, "");
+ }
+
+ protected List<String> listDatabaseNames() {
+ return client.getAllDatabases();
+ }
+
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/InitTableLog.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/InitTableLog.java
deleted file mode 100644
index 2f462b551c7..00000000000
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/InitTableLog.java
+++ /dev/null
@@ -1,67 +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.
-
-package org.apache.doris.datasource;
-
-import org.apache.doris.catalog.Column;
-import org.apache.doris.common.io.Text;
-import org.apache.doris.common.io.Writable;
-import org.apache.doris.persist.gson.GsonUtils;
-
-import com.google.gson.annotations.SerializedName;
-import lombok.Data;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-import java.util.List;
-
-@Data
-public class InitTableLog implements Writable {
- enum Type {
- HMS,
- ES,
- UNKNOWN;
- }
-
- @SerializedName(value = "catalogId")
- private long catalogId;
-
- @SerializedName(value = "dbId")
- private long dbId;
-
- @SerializedName(value = "tableId")
- private long tableId;
-
- @SerializedName(value = "type")
- private Type type;
-
- @SerializedName(value = "schema")
- protected volatile List<Column> schema;
-
- public InitTableLog() {}
-
- @Override
- public void write(DataOutput out) throws IOException {
- Text.writeString(out, GsonUtils.GSON.toJson(this));
- }
-
- public static InitTableLog read(DataInput in) throws IOException {
- String json = Text.readString(in);
- return GsonUtils.GSON.fromJson(json, InitTableLog.class);
- }
-}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/MetaIdMappingsLog.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/MetaIdMappingsLog.java
new file mode 100644
index 00000000000..629b4d13a40
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/MetaIdMappingsLog.java
@@ -0,0 +1,274 @@
+// 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.
+
+package org.apache.doris.datasource;
+
+import org.apache.doris.common.io.Text;
+import org.apache.doris.common.io.Writable;
+import org.apache.doris.persist.gson.GsonUtils;
+
+import com.google.common.collect.Lists;
+import com.google.gson.annotations.SerializedName;
+import lombok.Data;
+import lombok.Getter;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+@Data
+public class MetaIdMappingsLog implements Writable {
+
+ public static final short OPERATION_TYPE_IGNORE = 0;
+ public static final short OPERATION_TYPE_ADD = 1;
+ public static final short OPERATION_TYPE_DELETE = 2;
+
+ public static final short META_OBJECT_TYPE_IGNORE = 0;
+ public static final short META_OBJECT_TYPE_DATABASE = 1;
+ public static final short META_OBJECT_TYPE_TABLE = 2;
+ public static final short META_OBJECT_TYPE_PARTITION = 3;
+
+ @SerializedName(value = "ctlId")
+ private long catalogId = -1L;
+
+ @SerializedName(value = "fromEvent")
+ private boolean fromHmsEvent = false;
+
+ // The synced event id of master
+ @SerializedName(value = "lastEventId")
+ private long lastSyncedEventId = -1L;
+
+ @SerializedName(value = "metaIdMappings")
+ private List<MetaIdMapping> metaIdMappings = Lists.newLinkedList();
+
+ public MetaIdMappingsLog() {
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(catalogId, lastSyncedEventId,
+ metaIdMappings == null ? 0 : Arrays.hashCode(metaIdMappings.toArray()));
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof MetaIdMappingsLog)) {
+ return false;
+ }
+ return Objects.equals(this.catalogId, ((MetaIdMappingsLog) obj).catalogId)
+ && Objects.equals(this.fromHmsEvent, ((MetaIdMappingsLog) obj).fromHmsEvent)
+ && Objects.equals(this.lastSyncedEventId, ((MetaIdMappingsLog) obj).lastSyncedEventId)
+ && Objects.equals(this.metaIdMappings, ((MetaIdMappingsLog) obj).metaIdMappings);
+ }
+
+ @Override
+ public void write(DataOutput out) throws IOException {
+ Text.writeString(out, GsonUtils.GSON.toJson(this));
+ }
+
+ public static MetaIdMappingsLog read(DataInput in) throws IOException {
+ String json = Text.readString(in);
+ return GsonUtils.GSON.fromJson(json, MetaIdMappingsLog.class);
+ }
+
+ public void addMetaIdMapping(MetaIdMapping metaIdMapping) {
+ this.metaIdMappings.add(metaIdMapping);
+ }
+
+ public void addMetaIdMappings(List<MetaIdMapping> metaIdMappings) {
+ this.metaIdMappings.addAll(metaIdMappings);
+ }
+
+ public static OperationType getOperationType(short opType) {
+ switch (opType) {
+ case OPERATION_TYPE_ADD:
+ return OperationType.ADD;
+ case OPERATION_TYPE_DELETE:
+ return OperationType.DELETE;
+ default:
+ return OperationType.IGNORE;
+ }
+ }
+
+ public static MetaObjectType getMetaObjectType(short metaObjType) {
+ switch (metaObjType) {
+ case META_OBJECT_TYPE_DATABASE:
+ return MetaObjectType.DATABASE;
+ case META_OBJECT_TYPE_TABLE:
+ return MetaObjectType.TABLE;
+ case META_OBJECT_TYPE_PARTITION:
+ return MetaObjectType.PARTITION;
+ default:
+ return MetaObjectType.IGNORE;
+ }
+ }
+
+ @Getter
+ public static class MetaIdMapping {
+
+ @SerializedName(value = "opType")
+ private short opType;
+ @SerializedName(value = "metaObjType")
+ private short metaObjType;
+ // name of Database
+ @SerializedName(value = "dbName")
+ private String dbName;
+ // name of Table
+ @SerializedName(value = "tblName")
+ private String tblName;
+ // name of Partition
+ @SerializedName(value = "pName")
+ private String partitionName;
+ // id of Database/Table/Partition
+ @SerializedName(value = "id")
+ private long id;
+
+ public MetaIdMapping() {}
+
+ public MetaIdMapping(short opType,
+ short metaObjType,
+ String dbName,
+ String tblName,
+ String partitionName,
+ long id) {
+ this.opType = opType;
+ this.metaObjType = metaObjType;
+ this.dbName = dbName;
+ this.tblName = tblName;
+ this.partitionName = partitionName;
+ this.id = id;
+ }
+
+ public MetaIdMapping(short opType,
+ short metaObjType,
+ String dbName,
+ String tblName,
+ String partitionName) {
+ this.opType = opType;
+ this.metaObjType = metaObjType;
+ this.dbName = dbName;
+ this.tblName = tblName;
+ this.partitionName = partitionName;
+ this.id = -1L;
+ }
+
+ public MetaIdMapping(short opType,
+ short metaObjType,
+ String dbName,
+ String tblName,
+ long id) {
+ this.opType = opType;
+ this.metaObjType = metaObjType;
+ this.dbName = dbName;
+ this.tblName = tblName;
+ this.partitionName = null;
+ this.id = id;
+ }
+
+ public MetaIdMapping(short opType,
+ short metaObjType,
+ String dbName,
+ String tblName) {
+ this.opType = opType;
+ this.metaObjType = metaObjType;
+ this.dbName = dbName;
+ this.tblName = tblName;
+ this.partitionName = null;
+ this.id = -1L;
+ }
+
+ public MetaIdMapping(short opType,
+ short metaObjType,
+ String dbName,
+ long id) {
+ this.opType = opType;
+ this.metaObjType = metaObjType;
+ this.dbName = dbName;
+ this.tblName = null;
+ this.partitionName = null;
+ this.id = id;
+ }
+
+ public MetaIdMapping(short opType,
+ short metaObjType,
+ String dbName) {
+ this.opType = opType;
+ this.metaObjType = metaObjType;
+ this.dbName = dbName;
+ this.tblName = null;
+ this.partitionName = null;
+ this.id = -1L;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(opType, metaObjType, dbName, tblName, partitionName, id);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof MetaIdMapping)) {
+ return false;
+ }
+ return Objects.equals(this.opType, ((MetaIdMapping) obj).opType)
+ && Objects.equals(this.metaObjType, ((MetaIdMapping) obj).metaObjType)
+ && Objects.equals(this.dbName, ((MetaIdMapping) obj).dbName)
+ && Objects.equals(this.tblName, ((MetaIdMapping) obj).tblName)
+ && Objects.equals(this.partitionName, ((MetaIdMapping) obj).partitionName)
+ && Objects.equals(this.id, ((MetaIdMapping) obj).id);
+ }
+
+ }
+
+ public enum OperationType {
+ IGNORE(OPERATION_TYPE_IGNORE),
+ // Add a Database/Table/Partition
+ ADD(OPERATION_TYPE_ADD),
+ // Delete Database/Table/Partition
+ DELETE(OPERATION_TYPE_DELETE);
+
+ private final short opType;
+
+ OperationType(short opType) {
+ this.opType = opType;
+ }
+
+ public short getOperationType() {
+ return opType;
+ }
+ }
+
+ public enum MetaObjectType {
+ IGNORE(META_OBJECT_TYPE_IGNORE),
+ DATABASE(META_OBJECT_TYPE_DATABASE),
+ TABLE(META_OBJECT_TYPE_TABLE),
+ PARTITION(META_OBJECT_TYPE_PARTITION);
+
+ private final short metaObjType;
+
+ MetaObjectType(short metaObjType) {
+ this.metaObjType = metaObjType;
+ }
+
+ public short getMetaObjectType() {
+ return metaObjType;
+ }
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AddPartitionEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AddPartitionEvent.java
index e1dacbd0b29..ffc7b95ff59 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AddPartitionEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AddPartitionEvent.java
@@ -20,8 +20,11 @@ package org.apache.doris.datasource.hive.event;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.DdlException;
+import org.apache.doris.datasource.ExternalMetaIdMgr;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.apache.hadoop.hive.common.FileUtils;
@@ -109,4 +112,17 @@ public class AddPartitionEvent extends MetastorePartitionEvent {
debugString("Failed to process event"), e);
}
}
+
+ @Override
+ protected List<MetaIdMappingsLog.MetaIdMapping> transferToMetaIdMappings() {
+ List<MetaIdMappingsLog.MetaIdMapping> metaIdMappings = Lists.newArrayList();
+ for (String partitionName : this.getAllPartitionNames()) {
+ MetaIdMappingsLog.MetaIdMapping metaIdMapping = new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_PARTITION,
+ dbName, tblName, partitionName, ExternalMetaIdMgr.nextMetaId());
+ metaIdMappings.add(metaIdMapping);
+ }
+ return ImmutableList.copyOf(metaIdMappings);
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AlterTableEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AlterTableEvent.java
index 6de71fbbc59..c69812a22b3 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AlterTableEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/AlterTableEvent.java
@@ -100,7 +100,8 @@ public class AlterTableEvent extends MetastoreTableEvent {
Env.getCurrentEnv().getCatalogMgr()
.dropExternalTable(tableBefore.getDbName(), tableBefore.getTableName(), catalogName, true);
Env.getCurrentEnv().getCatalogMgr()
- .createExternalTableFromEvent(tableAfter.getDbName(), tableAfter.getTableName(), catalogName, true);
+ .createExternalTableFromEvent(
+ tableAfter.getDbName(), tableAfter.getTableName(), catalogName, eventTime, true);
}
private void processRename() throws DdlException {
@@ -118,7 +119,8 @@ public class AlterTableEvent extends MetastoreTableEvent {
Env.getCurrentEnv().getCatalogMgr()
.dropExternalTable(tableBefore.getDbName(), tableBefore.getTableName(), catalogName, true);
Env.getCurrentEnv().getCatalogMgr()
- .createExternalTableFromEvent(tableAfter.getDbName(), tableAfter.getTableName(), catalogName, true);
+ .createExternalTableFromEvent(
+ tableAfter.getDbName(), tableAfter.getTableName(), catalogName, eventTime, true);
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateDatabaseEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateDatabaseEvent.java
index 42d813319cc..d79d23824ab 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateDatabaseEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateDatabaseEvent.java
@@ -20,8 +20,11 @@ package org.apache.doris.datasource.hive.event;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.DdlException;
+import org.apache.doris.datasource.ExternalMetaIdMgr;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
@@ -59,4 +62,13 @@ public class CreateDatabaseEvent extends MetastoreEvent {
debugString("Failed to process event"), e);
}
}
+
+ @Override
+ protected List<MetaIdMappingsLog.MetaIdMapping> transferToMetaIdMappings() {
+ MetaIdMappingsLog.MetaIdMapping metaIdMapping = new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ dbName, ExternalMetaIdMgr.nextMetaId());
+ return ImmutableList.of(metaIdMapping);
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateTableEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateTableEvent.java
index 4c3615fbda8..246ce8626f4 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateTableEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/CreateTableEvent.java
@@ -19,8 +19,11 @@ package org.apache.doris.datasource.hive.event;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.DdlException;
+import org.apache.doris.datasource.ExternalMetaIdMgr;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
import org.apache.hadoop.hive.metastore.api.Table;
@@ -77,10 +80,19 @@ public class CreateTableEvent extends MetastoreTableEvent {
try {
infoLog("catalogName:[{}],dbName:[{}],tableName:[{}]", catalogName, dbName, tblName);
Env.getCurrentEnv().getCatalogMgr()
- .createExternalTableFromEvent(dbName, hmsTbl.getTableName(), catalogName, true);
+ .createExternalTableFromEvent(dbName, hmsTbl.getTableName(), catalogName, eventTime, true);
} catch (DdlException e) {
throw new MetastoreNotificationException(
debugString("Failed to process event"), e);
}
}
+
+ @Override
+ protected List<MetaIdMappingsLog.MetaIdMapping> transferToMetaIdMappings() {
+ MetaIdMappingsLog.MetaIdMapping metaIdMapping = new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_TABLE,
+ dbName, tblName, ExternalMetaIdMgr.nextMetaId());
+ return ImmutableList.of(metaIdMapping);
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropDatabaseEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropDatabaseEvent.java
index 3481f832fe0..ca69e6f14d0 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropDatabaseEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropDatabaseEvent.java
@@ -20,8 +20,10 @@ package org.apache.doris.datasource.hive.event;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.DdlException;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
@@ -59,4 +61,13 @@ public class DropDatabaseEvent extends MetastoreEvent {
debugString("Failed to process event"), e);
}
}
+
+ @Override
+ protected List<MetaIdMappingsLog.MetaIdMapping> transferToMetaIdMappings() {
+ MetaIdMappingsLog.MetaIdMapping metaIdMapping = new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ dbName);
+ return ImmutableList.of(metaIdMapping);
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropPartitionEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropPartitionEvent.java
index f71f44cf5ab..dd443010289 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropPartitionEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropPartitionEvent.java
@@ -20,8 +20,10 @@ package org.apache.doris.datasource.hive.event;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.DdlException;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
@@ -124,7 +126,7 @@ public class DropPartitionEvent extends MetastorePartitionEvent {
return false;
}
- // `that` event can be batched if this event's partitions contains all of the partitions which `that` event has
+ // `that` event can be batched if this event's partitions contains all the partitions which `that` event has
// else just remove `that` event's relevant partitions
for (String partitionName : getAllPartitionNames()) {
if (thatPartitionEvent instanceof AddPartitionEvent) {
@@ -136,4 +138,17 @@ public class DropPartitionEvent extends MetastorePartitionEvent {
return getAllPartitionNames().containsAll(thatPartitionEvent.getAllPartitionNames());
}
+
+ @Override
+ protected List<MetaIdMappingsLog.MetaIdMapping> transferToMetaIdMappings() {
+ List<MetaIdMappingsLog.MetaIdMapping> metaIdMappings = Lists.newArrayList();
+ for (String partitionName : this.getAllPartitionNames()) {
+ MetaIdMappingsLog.MetaIdMapping metaIdMapping = new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ dbName, tblName, partitionName);
+ metaIdMappings.add(metaIdMapping);
+ }
+ return ImmutableList.copyOf(metaIdMappings);
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropTableEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropTableEvent.java
index c333506cad2..0f62e246082 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropTableEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/DropTableEvent.java
@@ -20,8 +20,10 @@ package org.apache.doris.datasource.hive.event;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.DdlException;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
import org.apache.hadoop.hive.metastore.messaging.json.JSONDropTableMessage;
@@ -89,14 +91,23 @@ public class DropTableEvent extends MetastoreTableEvent {
return false;
}
- /**
+ /*
* Check if `that` event is a rename event, a rename event can not be batched
* because the process of `that` event will change the reference relation of this table,
* otherwise it can be batched because this event is a drop-table event
* and the process of this event will drop the whole table,
* and `that` event must be a MetastoreTableEvent event otherwise `isSameTable` will return false
- * */
+ */
MetastoreTableEvent thatTblEvent = (MetastoreTableEvent) that;
return !thatTblEvent.willChangeTableName();
}
+
+ @Override
+ protected List<MetaIdMappingsLog.MetaIdMapping> transferToMetaIdMappings() {
+ MetaIdMappingsLog.MetaIdMapping metaIdMapping = new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_TABLE,
+ dbName, tblName);
+ return ImmutableList.of(metaIdMapping);
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEvent.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEvent.java
index f9771562ed4..a9d165b4d03 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEvent.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEvent.java
@@ -17,8 +17,10 @@
package org.apache.doris.datasource.hive.event;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import org.apache.doris.datasource.hive.HMSCachedClient;
+import com.google.common.collect.ImmutableList;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -227,6 +229,13 @@ public abstract class MetastoreEvent {
return name.toString();
}
+ /**
+ * Create a MetaIdMapping list from the event if the event is a create/add/drop event
+ */
+ protected List<MetaIdMappingsLog.MetaIdMapping> transferToMetaIdMappings() {
+ return ImmutableList.of();
+ }
+
@Override
public String toString() {
return String.format(STR_FORMAT_EVENT_ID_TYPE, eventId, eventType);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventFactory.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventFactory.java
index aabc562dba1..a3ba092703b 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventFactory.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventFactory.java
@@ -18,7 +18,9 @@
package org.apache.doris.datasource.hive.event;
+import org.apache.doris.catalog.Env;
import org.apache.doris.datasource.HMSExternalCatalog;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
@@ -77,23 +79,39 @@ public class MetastoreEventFactory implements EventFactory {
for (NotificationEvent event : events) {
metastoreEvents.addAll(transferNotificationEventToMetastoreEvents(event, catalogName));
}
- return createBatchEvents(catalogName, metastoreEvents);
+ List<MetastoreEvent> mergedEvents = mergeEvents(catalogName, metastoreEvents);
+ if (Env.getCurrentEnv().isMaster()) {
+ logMetaIdMappings(hmsExternalCatalog.getId(), events.get(events.size() - 1).getEventId(), mergedEvents);
+ }
+ return mergedEvents;
+ }
+
+ private void logMetaIdMappings(long catalogId, long lastSyncedEventId, List<MetastoreEvent> mergedEvents) {
+ MetaIdMappingsLog log = new MetaIdMappingsLog();
+ log.setCatalogId(catalogId);
+ log.setFromHmsEvent(true);
+ log.setLastSyncedEventId(lastSyncedEventId);
+ for (MetastoreEvent event : mergedEvents) {
+ log.addMetaIdMappings(event.transferToMetaIdMappings());
+ }
+ Env.getCurrentEnv().getExternalMetaIdMgr().replayMetaIdMappingsLog(log);
+ Env.getCurrentEnv().getEditLog().logMetaIdMappingsLog(log);
}
/**
* Merge events to reduce the cost time on event processing, currently mainly handles MetastoreTableEvent
* because merge MetastoreTableEvent is simple and cost-effective.
* For example, consider there are some events as following:
- *
+ * <pre>
* event1: alter table db1.t1 add partition p1;
* event2: alter table db1.t1 drop partition p2;
* event3: alter table db1.t2 add partition p3;
* event4: alter table db2.t3 rename to t4;
* event5: drop table db1.t1;
- *
+ * </pre>
* Only `event3 event4 event5` will be reserved and other events will be skipped.
* */
- public List<MetastoreEvent> createBatchEvents(String catalogName, List<MetastoreEvent> events) {
+ public List<MetastoreEvent> mergeEvents(String catalogName, List<MetastoreEvent> events) {
List<MetastoreEvent> eventsCopy = Lists.newArrayList(events);
Map<MetastoreTableEvent.TableKey, List<Integer>> indexMap = Maps.newLinkedHashMap();
for (int i = 0; i < events.size(); i++) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventsProcessor.java b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventsProcessor.java
index 622d84428fa..28793aecf21 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventsProcessor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/event/MetastoreEventsProcessor.java
@@ -18,13 +18,22 @@
package org.apache.doris.datasource.hive.event;
+import org.apache.doris.analysis.RedirectStatus;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.Config;
import org.apache.doris.common.util.MasterDaemon;
import org.apache.doris.datasource.CatalogIf;
+import org.apache.doris.datasource.CatalogLog;
import org.apache.doris.datasource.HMSClientException;
import org.apache.doris.datasource.HMSExternalCatalog;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.MasterOpExecutor;
+import org.apache.doris.qe.OriginStatement;
+import com.google.common.collect.Maps;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
import org.apache.hadoop.hive.metastore.api.NotificationEventResponse;
@@ -35,6 +44,7 @@ import org.apache.logging.log4j.Logger;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
/**
* A metastore event is a instance of the class
@@ -68,6 +78,13 @@ public class MetastoreEventsProcessor extends MasterDaemon {
// event factory which is used to get or create MetastoreEvents
private final MetastoreEventFactory metastoreEventFactory;
+ // manager the lastSyncedEventId of hms catalogs
+ // use HashMap is fine because all operations are in one thread
+ private final Map<Long, Long> lastSyncedEventIdMap = Maps.newHashMap();
+
+ // manager the masterLastSyncedEventId of hms catalogs
+ private final Map<Long, Long> masterLastSyncedEventIdMap = Maps.newHashMap();
+
private boolean isRunning;
public MetastoreEventsProcessor() {
@@ -76,13 +93,56 @@ public class MetastoreEventsProcessor extends MasterDaemon {
this.isRunning = false;
}
+ @Override
+ protected void runAfterCatalogReady() {
+ if (isRunning) {
+ LOG.warn("Last task not finished,ignore current task.");
+ return;
+ }
+ isRunning = true;
+ try {
+ realRun();
+ } catch (Exception ex) {
+ LOG.warn("Task failed", ex);
+ }
+ isRunning = false;
+ }
+
+ private void realRun() {
+ List<Long> catalogIds = Env.getCurrentEnv().getCatalogMgr().getCatalogIds();
+ for (Long catalogId : catalogIds) {
+ CatalogIf catalog = Env.getCurrentEnv().getCatalogMgr().getCatalog(catalogId);
+ if (catalog instanceof HMSExternalCatalog) {
+ HMSExternalCatalog hmsExternalCatalog = (HMSExternalCatalog) catalog;
+ try {
+ List<NotificationEvent> events = getNextHMSEvents(hmsExternalCatalog);
+ if (!events.isEmpty()) {
+ LOG.info("Events size are {} on catalog [{}]", events.size(),
+ hmsExternalCatalog.getName());
+ processEvents(events, hmsExternalCatalog);
+ }
+ } catch (MetastoreNotificationFetchException e) {
+ LOG.warn("Failed to fetch hms events on {}. msg: ", hmsExternalCatalog.getName(), e);
+ } catch (Exception ex) {
+ LOG.warn("Failed to process hive metastore [{}] events .",
+ hmsExternalCatalog.getName(), ex);
+ }
+ }
+ }
+ }
+
/**
* Fetch the next batch of NotificationEvents from metastore. The default batch size is
* <code>{@link Config#hms_events_batch_size_per_rpc}</code>
*/
- private List<NotificationEvent> getNextHMSEvents(HMSExternalCatalog hmsExternalCatalog) {
+ private List<NotificationEvent> getNextHMSEvents(HMSExternalCatalog hmsExternalCatalog) throws Exception {
LOG.debug("Start to pull events on catalog [{}]", hmsExternalCatalog.getName());
- NotificationEventResponse response = hmsExternalCatalog.getNextEventResponse(hmsExternalCatalog);
+ NotificationEventResponse response;
+ if (Env.getCurrentEnv().isMaster()) {
+ response = getNextEventResponseForMaster(hmsExternalCatalog);
+ } else {
+ response = getNextEventResponseForSlave(hmsExternalCatalog);
+ }
if (response == null) {
return Collections.emptyList();
@@ -99,11 +159,11 @@ public class MetastoreEventsProcessor extends MasterDaemon {
&& hmsClientException.getCause() instanceof NoSuchObjectException) {
LOG.warn(event.debugString("Failed to process event and skip"), hmsClientException);
} else {
- hmsExternalCatalog.setLastSyncedEventId(event.getEventId() - 1);
+ updateLastSyncedEventId(hmsExternalCatalog, event.getEventId() - 1);
throw hmsClientException;
}
} catch (Exception e) {
- hmsExternalCatalog.setLastSyncedEventId(event.getEventId() - 1);
+ updateLastSyncedEventId(hmsExternalCatalog, event.getEventId() - 1);
throw e;
}
}
@@ -116,45 +176,142 @@ public class MetastoreEventsProcessor extends MasterDaemon {
//transfer
List<MetastoreEvent> metastoreEvents = metastoreEventFactory.getMetastoreEvents(events, hmsExternalCatalog);
doExecute(metastoreEvents, hmsExternalCatalog);
- hmsExternalCatalog.setLastSyncedEventId(events.get(events.size() - 1).getEventId());
+ updateLastSyncedEventId(hmsExternalCatalog, events.get(events.size() - 1).getEventId());
}
- @Override
- protected void runAfterCatalogReady() {
- if (isRunning) {
- LOG.warn("Last task not finished,ignore current task.");
- return;
+ private NotificationEventResponse getNextEventResponseForMaster(HMSExternalCatalog hmsExternalCatalog)
+ throws MetastoreNotificationFetchException {
+ long lastSyncedEventId = getLastSyncedEventId(hmsExternalCatalog);
+ long currentEventId = getCurrentHmsEventId(hmsExternalCatalog);
+ if (lastSyncedEventId < 0) {
+ refreshCatalogForMaster(hmsExternalCatalog);
+ // invoke getCurrentEventId() and save the event id before refresh catalog to avoid missing events
+ // but set lastSyncedEventId to currentEventId only if there is not any problems when refreshing catalog
+ updateLastSyncedEventId(hmsExternalCatalog, currentEventId);
+ LOG.info(
+ "First pulling events on catalog [{}],refreshCatalog and init lastSyncedEventId,"
+ + "lastSyncedEventId is [{}]",
+ hmsExternalCatalog.getName(), lastSyncedEventId);
+ return null;
}
- isRunning = true;
+
+ LOG.debug("Catalog [{}] getNextEventResponse, currentEventId is {}, lastSyncedEventId is {}",
+ hmsExternalCatalog.getName(), currentEventId, lastSyncedEventId);
+ if (currentEventId == lastSyncedEventId) {
+ LOG.info("Event id not updated when pulling events on catalog [{}]", hmsExternalCatalog.getName());
+ return null;
+ }
+
try {
- realRun();
- } catch (Exception ex) {
- LOG.warn("Task failed", ex);
+ return hmsExternalCatalog.getClient().getNextNotification(lastSyncedEventId,
+ Config.hms_events_batch_size_per_rpc, null);
+ } catch (MetastoreNotificationFetchException e) {
+ // Need a fallback to handle this because this error state can not be recovered until restarting FE
+ if (StringUtils.isNotEmpty(e.getMessage())
+ && e.getMessage().contains(HiveMetaStoreClient.REPL_EVENTS_MISSING_IN_METASTORE)) {
+ refreshCatalogForMaster(hmsExternalCatalog);
+ // set lastSyncedEventId to currentEventId after refresh catalog successfully
+ updateLastSyncedEventId(hmsExternalCatalog, currentEventId);
+ LOG.warn("Notification events are missing, maybe an event can not be handled "
+ + "or processing rate is too low, fallback to refresh the catalog");
+ return null;
+ }
+ throw e;
}
- isRunning = false;
}
- private void realRun() {
- List<Long> catalogIds = Env.getCurrentEnv().getCatalogMgr().getCatalogIds();
- for (Long catalogId : catalogIds) {
- CatalogIf catalog = Env.getCurrentEnv().getCatalogMgr().getCatalog(catalogId);
- if (catalog instanceof HMSExternalCatalog) {
- HMSExternalCatalog hmsExternalCatalog = (HMSExternalCatalog) catalog;
- try {
- List<NotificationEvent> events = getNextHMSEvents(hmsExternalCatalog);
- if (!events.isEmpty()) {
- LOG.info("Events size are {} on catalog [{}]", events.size(),
- hmsExternalCatalog.getName());
- processEvents(events, hmsExternalCatalog);
- }
- } catch (MetastoreNotificationFetchException e) {
- LOG.warn("Failed to fetch hms events on {}. msg: ", hmsExternalCatalog.getName(), e);
- } catch (Exception ex) {
- LOG.warn("Failed to process hive metastore [{}] events .",
- hmsExternalCatalog.getName(), ex);
- }
+ private NotificationEventResponse getNextEventResponseForSlave(HMSExternalCatalog hmsExternalCatalog)
+ throws Exception {
+ long lastSyncedEventId = getLastSyncedEventId(hmsExternalCatalog);
+ long masterLastSyncedEventId = getMasterLastSyncedEventId(hmsExternalCatalog);
+ // do nothing if masterLastSyncedEventId has not been synced
+ if (masterLastSyncedEventId == -1L) {
+ LOG.info("LastSyncedEventId of master has not been synced on catalog [{}]", hmsExternalCatalog.getName());
+ return null;
+ }
+ // do nothing if lastSyncedEventId is equals to masterLastSyncedEventId
+ if (lastSyncedEventId == masterLastSyncedEventId) {
+ LOG.info("Event id not updated when pulling events on catalog [{}]", hmsExternalCatalog.getName());
+ return null;
+ }
+
+ if (lastSyncedEventId < 0) {
+ refreshCatalogForSlave(hmsExternalCatalog);
+ // Use masterLastSyncedEventId to avoid missing events
+ updateLastSyncedEventId(hmsExternalCatalog, masterLastSyncedEventId);
+ LOG.info(
+ "First pulling events on catalog [{}],refreshCatalog and init lastSyncedEventId,"
+ + "lastSyncedEventId is [{}]",
+ hmsExternalCatalog.getName(), lastSyncedEventId);
+ return null;
+ }
+
+ LOG.debug("Catalog [{}] getNextEventResponse, masterLastSyncedEventId is {}, lastSyncedEventId is {}",
+ hmsExternalCatalog.getName(), masterLastSyncedEventId, lastSyncedEventId);
+
+ // For slave FE nodes, only fetch events which id is lower than masterLastSyncedEventId
+ int maxEventSize = Math.min((int) (masterLastSyncedEventId - lastSyncedEventId),
+ Config.hms_events_batch_size_per_rpc);
+ try {
+ return hmsExternalCatalog.getClient().getNextNotification(lastSyncedEventId, maxEventSize, null);
+ } catch (MetastoreNotificationFetchException e) {
+ // Need a fallback to handle this because this error state can not be recovered until restarting FE
+ if (StringUtils.isNotEmpty(e.getMessage())
+ && e.getMessage().contains(HiveMetaStoreClient.REPL_EVENTS_MISSING_IN_METASTORE)) {
+ refreshCatalogForMaster(hmsExternalCatalog);
+ // set masterLastSyncedEventId to lastSyncedEventId after refresh catalog successfully
+ updateLastSyncedEventId(hmsExternalCatalog, masterLastSyncedEventId);
+ LOG.warn("Notification events are missing, maybe an event can not be handled "
+ + "or processing rate is too low, fallback to refresh the catalog");
+ return null;
}
+ throw e;
+ }
+ }
+
+ private long getCurrentHmsEventId(HMSExternalCatalog hmsExternalCatalog) {
+ CurrentNotificationEventId currentNotificationEventId = hmsExternalCatalog.getClient()
+ .getCurrentNotificationEventId();
+ if (currentNotificationEventId == null) {
+ LOG.warn("Get currentNotificationEventId is null");
+ return -1L;
}
+ return currentNotificationEventId.getEventId();
+ }
+
+ private long getLastSyncedEventId(HMSExternalCatalog hmsExternalCatalog) {
+ // Returns to -1 if not exists, otherwise client.getNextNotification will throw exception
+ // Reference to https://github.com/apDdlache/doris/issues/18251
+ return lastSyncedEventIdMap.getOrDefault(hmsExternalCatalog.getId(), -1L);
+ }
+
+ private void updateLastSyncedEventId(HMSExternalCatalog hmsExternalCatalog, long eventId) {
+ lastSyncedEventIdMap.put(hmsExternalCatalog.getId(), eventId);
+ }
+
+ private long getMasterLastSyncedEventId(HMSExternalCatalog hmsExternalCatalog) {
+ return masterLastSyncedEventIdMap.getOrDefault(hmsExternalCatalog.getId(), -1L);
+ }
+
+ public void updateMasterLastSyncedEventId(HMSExternalCatalog hmsExternalCatalog, long eventId) {
+ masterLastSyncedEventIdMap.put(hmsExternalCatalog.getId(), eventId);
+ }
+
+ private void refreshCatalogForMaster(HMSExternalCatalog hmsExternalCatalog) {
+ CatalogLog log = new CatalogLog();
+ log.setCatalogId(hmsExternalCatalog.getId());
+ log.setInvalidCache(true);
+ Env.getCurrentEnv().getCatalogMgr().replayRefreshCatalog(log);
+ }
+
+ private void refreshCatalogForSlave(HMSExternalCatalog hmsExternalCatalog) throws Exception {
+ // Transfer to master to refresh catalog
+ String sql = "REFRESH CATALOG " + hmsExternalCatalog.getName();
+ OriginStatement originStmt = new OriginStatement(sql, 0);
+ MasterOpExecutor masterOpExecutor = new MasterOpExecutor(originStmt, new ConnectContext(),
+ RedirectStatus.FORWARD_WITH_SYNC, false);
+ LOG.debug("Transfer to master to refresh catalog, stmt: {}", sql);
+ masterOpExecutor.execute();
}
public static MessageDeserializer getMessageDeserializer(String messageFormat) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/journal/JournalEntity.java b/fe/fe-core/src/main/java/org/apache/doris/journal/JournalEntity.java
index 1bedda0a7e9..d74c519407f 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/journal/JournalEntity.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/journal/JournalEntity.java
@@ -42,7 +42,7 @@ import org.apache.doris.datasource.CatalogLog;
import org.apache.doris.datasource.ExternalObjectLog;
import org.apache.doris.datasource.InitCatalogLog;
import org.apache.doris.datasource.InitDatabaseLog;
-import org.apache.doris.datasource.InitTableLog;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import org.apache.doris.ha.MasterInfo;
import org.apache.doris.insertoverwrite.InsertOverwriteLog;
import org.apache.doris.job.base.AbstractJob;
@@ -746,19 +746,18 @@ public class JournalEntity implements Writable {
isRead = true;
break;
}
- case OperationType.OP_INIT_EXTERNAL_TABLE: {
- data = InitTableLog.read(in);
- isRead = true;
- break;
- }
- case OperationType.OP_REFRESH_EXTERNAL_DB:
+ case OperationType.OP_INIT_EXTERNAL_TABLE:
case OperationType.OP_DROP_EXTERNAL_TABLE:
case OperationType.OP_CREATE_EXTERNAL_TABLE:
case OperationType.OP_DROP_EXTERNAL_DB:
case OperationType.OP_CREATE_EXTERNAL_DB:
case OperationType.OP_ADD_EXTERNAL_PARTITIONS:
case OperationType.OP_DROP_EXTERNAL_PARTITIONS:
- case OperationType.OP_REFRESH_EXTERNAL_PARTITIONS:
+ case OperationType.OP_REFRESH_EXTERNAL_PARTITIONS: {
+ isRead = true;
+ break;
+ }
+ case OperationType.OP_REFRESH_EXTERNAL_DB:
case OperationType.OP_REFRESH_EXTERNAL_TABLE: {
data = ExternalObjectLog.read(in);
isRead = true;
@@ -906,6 +905,11 @@ public class JournalEntity implements Writable {
isRead = true;
break;
}
+ case OperationType.OP_ADD_META_ID_MAPPINGS: {
+ data = MetaIdMappingsLog.read(in);
+ isRead = true;
+ break;
+ }
default: {
IOException e = new IOException();
LOG.error("UNKNOWN Operation Type {}", opCode, e);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java b/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java
index 8c2424d4837..958277dd6b7 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java
@@ -51,6 +51,7 @@ import org.apache.doris.datasource.CatalogLog;
import org.apache.doris.datasource.ExternalObjectLog;
import org.apache.doris.datasource.InitCatalogLog;
import org.apache.doris.datasource.InitDatabaseLog;
+import org.apache.doris.datasource.MetaIdMappingsLog;
import org.apache.doris.ha.MasterInfo;
import org.apache.doris.insertoverwrite.InsertOverwriteLog;
import org.apache.doris.job.base.AbstractJob;
@@ -1011,38 +1012,24 @@ public class EditLog {
break;
}
case OperationType.OP_DROP_EXTERNAL_TABLE: {
- final ExternalObjectLog log = (ExternalObjectLog) journal.getData();
- env.getCatalogMgr().replayDropExternalTable(log);
break;
}
case OperationType.OP_CREATE_EXTERNAL_TABLE: {
- final ExternalObjectLog log = (ExternalObjectLog) journal.getData();
- env.getCatalogMgr().replayCreateExternalTableFromEvent(log);
break;
}
case OperationType.OP_DROP_EXTERNAL_DB: {
- final ExternalObjectLog log = (ExternalObjectLog) journal.getData();
- env.getCatalogMgr().replayDropExternalDatabase(log);
break;
}
case OperationType.OP_CREATE_EXTERNAL_DB: {
- final ExternalObjectLog log = (ExternalObjectLog) journal.getData();
- env.getCatalogMgr().replayCreateExternalDatabase(log);
break;
}
case OperationType.OP_ADD_EXTERNAL_PARTITIONS: {
- final ExternalObjectLog log = (ExternalObjectLog) journal.getData();
- env.getCatalogMgr().replayAddExternalPartitions(log);
break;
}
case OperationType.OP_DROP_EXTERNAL_PARTITIONS: {
- final ExternalObjectLog log = (ExternalObjectLog) journal.getData();
- env.getCatalogMgr().replayDropExternalPartitions(log);
break;
}
case OperationType.OP_REFRESH_EXTERNAL_PARTITIONS: {
- final ExternalObjectLog log = (ExternalObjectLog) journal.getData();
- env.getCatalogMgr().replayRefreshExternalPartitions(log);
break;
}
case OperationType.OP_CREATE_WORKLOAD_GROUP: {
@@ -1165,6 +1152,10 @@ public class EditLog {
env.getBackupHandler().getRepoMgr().alterRepo(repository, true);
break;
}
+ case OperationType.OP_ADD_META_ID_MAPPINGS: {
+ env.getExternalMetaIdMgr().replayMetaIdMappingsLog((MetaIdMappingsLog) journal.getData());
+ break;
+ }
case OperationType.OP_LOG_UPDATE_ROWS:
case OperationType.OP_LOG_NEW_PARTITION_LOADED:
case OperationType.OP_LOG_ALTER_COLUMN_STATS: {
@@ -1886,26 +1877,32 @@ public class EditLog {
logEdit(OperationType.OP_REFRESH_EXTERNAL_TABLE, log);
}
+ @Deprecated
public void logDropExternalTable(ExternalObjectLog log) {
logEdit(OperationType.OP_DROP_EXTERNAL_TABLE, log);
}
+ @Deprecated
public void logCreateExternalTable(ExternalObjectLog log) {
logEdit(OperationType.OP_CREATE_EXTERNAL_TABLE, log);
}
+ @Deprecated
public void logDropExternalDatabase(ExternalObjectLog log) {
logEdit(OperationType.OP_DROP_EXTERNAL_DB, log);
}
+ @Deprecated
public void logCreateExternalDatabase(ExternalObjectLog log) {
logEdit(OperationType.OP_CREATE_EXTERNAL_DB, log);
}
+ @Deprecated
public void logAddExternalPartitions(ExternalObjectLog log) {
logEdit(OperationType.OP_ADD_EXTERNAL_PARTITIONS, log);
}
+ @Deprecated
public void logDropExternalPartitions(ExternalObjectLog log) {
logEdit(OperationType.OP_DROP_EXTERNAL_PARTITIONS, log);
}
@@ -2005,6 +2002,10 @@ public class EditLog {
logEdit(OperationType.OP_INSERT_OVERWRITE, log);
}
+ public void logMetaIdMappingsLog(MetaIdMappingsLog log) {
+ logEdit(OperationType.OP_ADD_META_ID_MAPPINGS, log);
+ }
+
public String getNotReadyReason() {
if (journal == null) {
return "journal is null";
diff --git a/fe/fe-core/src/main/java/org/apache/doris/persist/OperationType.java b/fe/fe-core/src/main/java/org/apache/doris/persist/OperationType.java
index 0945dc0f151..0868d7f371b 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/persist/OperationType.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/persist/OperationType.java
@@ -288,12 +288,19 @@ public class OperationType {
public static final short OP_ADD_CONSTRAINT = 346;
public static final short OP_DROP_CONSTRAINT = 347;
+ @Deprecated
public static final short OP_DROP_EXTERNAL_TABLE = 350;
+ @Deprecated
public static final short OP_DROP_EXTERNAL_DB = 351;
+ @Deprecated
public static final short OP_CREATE_EXTERNAL_TABLE = 352;
+ @Deprecated
public static final short OP_CREATE_EXTERNAL_DB = 353;
+ @Deprecated
public static final short OP_ADD_EXTERNAL_PARTITIONS = 354;
+ @Deprecated
public static final short OP_DROP_EXTERNAL_PARTITIONS = 355;
+ @Deprecated
public static final short OP_REFRESH_EXTERNAL_PARTITIONS = 356;
public static final short OP_ALTER_USER = 400;
@@ -364,6 +371,8 @@ public class OperationType {
public static final short OP_LOG_ALTER_COLUMN_STATS = 464;
+ public static final short OP_ADD_META_ID_MAPPINGS = 470;
+
/**
* Get opcode name by op code.
**/
diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalMetaIdMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalMetaIdMgrTest.java
new file mode 100644
index 00000000000..12e018a4cff
--- /dev/null
+++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalMetaIdMgrTest.java
@@ -0,0 +1,76 @@
+// 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.
+
+package org.apache.doris.datasource;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class ExternalMetaIdMgrTest {
+
+ @Test
+ public void testReplayMetaIdMappingsLog() {
+ ExternalMetaIdMgr mgr = new ExternalMetaIdMgr();
+ MetaIdMappingsLog log1 = new MetaIdMappingsLog();
+ log1.setCatalogId(1L);
+ log1.setFromHmsEvent(false);
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ "db1", ExternalMetaIdMgr.nextMetaId()));
+ mgr.replayMetaIdMappingsLog(log1);
+ Assertions.assertNotEquals(-1L, mgr.getDbId(1L, "db1"));
+
+ MetaIdMappingsLog log2 = new MetaIdMappingsLog();
+ log2.setCatalogId(1L);
+ log2.setFromHmsEvent(false);
+ log2.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ "db1"));
+ mgr.replayMetaIdMappingsLog(log2);
+ Assertions.assertEquals(-1L, mgr.getDbId(1L, "db1"));
+
+ MetaIdMappingsLog log3 = new MetaIdMappingsLog();
+ log3.setCatalogId(1L);
+ log3.setFromHmsEvent(false);
+ log3.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_TABLE,
+ "db1", "tbl1", ExternalMetaIdMgr.nextMetaId()));
+ mgr.replayMetaIdMappingsLog(log3);
+ Assertions.assertEquals(-1L, mgr.getDbId(1L, "db1"));
+ Assertions.assertNotEquals(-1L, mgr.getTblId(1L, "db1", "tbl1"));
+
+ MetaIdMappingsLog log4 = new MetaIdMappingsLog();
+ log4.setCatalogId(1L);
+ log4.setFromHmsEvent(false);
+ log4.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_TABLE,
+ "db1", "tbl1"));
+ log4.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_PARTITION,
+ "db1", "tbl1", "p1", ExternalMetaIdMgr.nextMetaId()));
+ mgr.replayMetaIdMappingsLog(log4);
+ Assertions.assertEquals(-1L, mgr.getDbId(1L, "db1"));
+ Assertions.assertEquals(-1L, mgr.getTblId(1L, "db1", "tbl1"));
+ Assertions.assertNotEquals(-1L, mgr.getPartitionId(1L, "db1", "tbl1", "p1"));
+ }
+
+}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/MetaIdMappingsLogTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/MetaIdMappingsLogTest.java
new file mode 100644
index 00000000000..fec57c29eda
--- /dev/null
+++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/MetaIdMappingsLogTest.java
@@ -0,0 +1,97 @@
+// 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.
+
+package org.apache.doris.datasource;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+public class MetaIdMappingsLogTest {
+
+ @Test
+ public void testSerialization() throws Exception {
+ // 1. Write objects to file
+ MetaIdMappingsLog log1 = new MetaIdMappingsLog();
+ Path path = Files.createFile(Paths.get("./metaIdMappingsLogTest.txt"));
+ try (DataOutputStream dos = new DataOutputStream(Files.newOutputStream(path))) {
+ log1.setFromHmsEvent(true);
+ log1.setLastSyncedEventId(-1L);
+ log1.setCatalogId(1L);
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ "db1", ExternalMetaIdMgr.nextMetaId()));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_TABLE,
+ "db1", "tbl1", ExternalMetaIdMgr.nextMetaId()));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_TABLE,
+ "db1", "tbl2", ExternalMetaIdMgr.nextMetaId()));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ "db2"));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_PARTITION,
+ "db1", "tbl1", "p1", ExternalMetaIdMgr.nextMetaId()));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_ADD,
+ MetaIdMappingsLog.META_OBJECT_TYPE_PARTITION,
+ "db1", "tbl1", "p2", ExternalMetaIdMgr.nextMetaId()));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_DATABASE,
+ "db2"));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_TABLE,
+ "db1", "tbl1", ExternalMetaIdMgr.nextMetaId()));
+ log1.addMetaIdMapping(new MetaIdMappingsLog.MetaIdMapping(
+ MetaIdMappingsLog.OPERATION_TYPE_DELETE,
+ MetaIdMappingsLog.META_OBJECT_TYPE_PARTITION,
+ "db1", "tbl1", "p2", ExternalMetaIdMgr.nextMetaId()));
+ log1.write(dos);
+ dos.flush();
+ } catch (Throwable throwable) {
+ throwable.printStackTrace();
+ Files.deleteIfExists(path);
+ Assertions.fail();
+ }
+
+ // 2. Read objects from file
+ MetaIdMappingsLog log2;
+ try (DataInputStream dis = new DataInputStream(Files.newInputStream(path))) {
+ log2 = MetaIdMappingsLog.read(dis);
+ Assertions.assertEquals(log1, log2);
+ } catch (Throwable throwable) {
+ throwable.printStackTrace();
+ Assertions.fail();
+ } finally {
+ Files.deleteIfExists(path);
+ }
+ }
+
+}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/external/hms/MetastoreEventFactoryTest.java b/fe/fe-core/src/test/java/org/apache/doris/external/hms/MetastoreEventFactoryTest.java
index c9e566dc9d8..136cac6b712 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/external/hms/MetastoreEventFactoryTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/external/hms/MetastoreEventFactoryTest.java
@@ -454,7 +454,7 @@ public class MetastoreEventFactoryTest {
for (int j = 0; j < 1000; j++) {
events.add(producer.produceOneEvent(j));
}
- List<MetastoreEvent> mergedEvents = factory.createBatchEvents(testCtl, events);
+ List<MetastoreEvent> mergedEvents = factory.mergeEvents(testCtl, events);
for (MetastoreEvent event : events) {
processEvent(validateCatalog, event);
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 08/43: Revert "[ci](perf) add required (#30155)" (#30165)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit ec898f26770f1a257f20706fb793981bc5beed70
Author: shuke <37...@users.noreply.github.com>
AuthorDate: Sun Jan 21 09:04:23 2024 +0800
Revert "[ci](perf) add required (#30155)" (#30165)
This reverts commit f9c274c338afbe14f97cc16d1327e9a548e524b3.
---
.github/workflows/comment-to-trigger-teamcity.yml | 21 +++-
regression-test/pipeline/common/doris-utils.sh | 12 +-
regression-test/pipeline/common/github-utils.sh | 25 ++++
regression-test/pipeline/performance/run-tpcds.sh | 1 -
regression-test/pipeline/performance/run-tpch.sh | 1 -
regression-test/pipeline/tpch/tpch-sf100/clean.sh | 40 +++++++
.../pipeline/tpch/tpch-sf100/conf/be.conf | 85 +++++++++++++
.../pipeline/tpch/tpch-sf100/conf/external.json | 26 ++++
.../pipeline/tpch/tpch-sf100/conf/fe.conf | 78 ++++++++++++
.../pipeline/tpch/tpch-sf100/conf/odbcinst.ini | 43 +++++++
regression-test/pipeline/tpch/tpch-sf100/deploy.sh | 119 +++++++++++++++++++
.../pipeline/tpch/tpch-sf100/prepare.sh | 69 +++++++++++
regression-test/pipeline/tpch/tpch-sf100/run.sh | 131 +++++++++++++++++++++
13 files changed, 642 insertions(+), 9 deletions(-)
diff --git a/.github/workflows/comment-to-trigger-teamcity.yml b/.github/workflows/comment-to-trigger-teamcity.yml
index 8ae0832fc9e..0fdd80ba28f 100644
--- a/.github/workflows/comment-to-trigger-teamcity.yml
+++ b/.github/workflows/comment-to-trigger-teamcity.yml
@@ -45,6 +45,7 @@ jobs:
"${COMMENT_BODY}" == *'run p1'* ||
"${COMMENT_BODY}" == *'run external'* ||
"${COMMENT_BODY}" == *'run pipelinex_p0'* ||
+ "${COMMENT_BODY}" == *'run clickbench'* ||
"${COMMENT_BODY}" == *'run arm'* ||
"${COMMENT_BODY}" == *'run performance'* ]]; then
echo "comment_trigger=true" | tee -a "$GITHUB_OUTPUT"
@@ -62,7 +63,7 @@ jobs:
echo "TARGET_BRANCH='${TARGET_BRANCH}'" | tee -a "$GITHUB_OUTPUT"
echo "COMMENT_BODY='${COMMENT_BODY}'" | tee -a "$GITHUB_OUTPUT"
- reg="run (buildall|compile|p0|p1|feut|beut|external|pipelinex_p0|arm|performance)( [1-9]*[0-9]+)*"
+ reg="run (buildall|compile|p0|p1|feut|beut|external|clickbench|pipelinex_p0|arm|performance)( [1-9]*[0-9]+)*"
COMMENT_TRIGGER_TYPE="$(echo -e "${COMMENT_BODY}" | xargs | grep -E "${reg}" | awk -F' ' '{print $2}' | sed -n 1p | sed 's/\r//g')"
COMMENT_REPEAT_TIMES="$(echo -e "${COMMENT_BODY}" | xargs | grep -E "${reg}" | awk -F' ' '{print $3}' | sed -n 1p | sed 's/\r//g')"
echo "COMMENT_TRIGGER_TYPE=${COMMENT_TRIGGER_TYPE}" | tee -a "$GITHUB_OUTPUT"
@@ -89,6 +90,11 @@ jobs:
else
echo "changed_be_ut=false" | tee -a "$GITHUB_OUTPUT"
fi
+ if file_changed_ckb; then
+ echo "changed_ckb=true" | tee -a "$GITHUB_OUTPUT"
+ else
+ echo "changed_ckb=false" | tee -a "$GITHUB_OUTPUT"
+ fi
if file_changed_regression_p0; then
echo "changed_p0=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_external=true" | tee -a "$GITHUB_OUTPUT"
@@ -114,6 +120,7 @@ jobs:
echo "INFO: failed to _get_pr_changed_files, default trigger all"
echo "changed_fe_ut=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_be_ut=true" | tee -a "$GITHUB_OUTPUT"
+ echo "changed_ckb=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_p0=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_external=true" | tee -a "$GITHUB_OUTPUT"
echo "changed_pipelinex_p0=true" | tee -a "$GITHUB_OUTPUT"
@@ -236,6 +243,18 @@ jobs:
"arm" \
"${{ steps.parse.outputs.COMMENT_REPEAT_TIMES }}"
+ - name: "Trigger or Skip clickbench"
+ if: ${{ fromJSON(steps.parse.outputs.comment_trigger) && contains(fromJSON('["clickbench", "buildall"]'), steps.parse.outputs.COMMENT_TRIGGER_TYPE) }}
+ run: |
+ source ./regression-test/pipeline/common/teamcity-utils.sh
+ set -x
+ trigger_or_skip_build \
+ "${{ steps.changes.outputs.changed_ckb }}" \
+ "${{ steps.parse.outputs.PULL_REQUEST_NUM }}" \
+ "${{ steps.parse.outputs.COMMIT_ID_FROM_TRIGGER }}" \
+ "clickbench" \
+ "${{ steps.parse.outputs.COMMENT_REPEAT_TIMES }}"
+
- name: "Trigger or Skip performance"
if: ${{ fromJSON(steps.parse.outputs.comment_trigger) && contains(fromJSON('["performance", "buildall"]'), steps.parse.outputs.COMMENT_TRIGGER_TYPE) }}
run: |
diff --git a/regression-test/pipeline/common/doris-utils.sh b/regression-test/pipeline/common/doris-utils.sh
index 327f00beac1..47bcedad351 100644
--- a/regression-test/pipeline/common/doris-utils.sh
+++ b/regression-test/pipeline/common/doris-utils.sh
@@ -394,18 +394,18 @@ archive_doris_logs() {
print_doris_fe_log() {
if [[ ! -d "${DORIS_HOME:-}" ]]; then return 1; fi
- echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.out--------------------"
+ echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.out--------------------"
tail -n 100 "${DORIS_HOME}"/fe/log/fe.out
- echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.log--------------------"
+ echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/fe/log/fe.log--------------------"
tail -n 100 "${DORIS_HOME}"/fe/log/fe.log
- echo -e "WARNING: ----------------------------------------\n\n\n\n"
+ echo "WARNING: ----------------------------------------"
}
print_doris_be_log() {
if [[ ! -d "${DORIS_HOME:-}" ]]; then return 1; fi
- echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.out--------------------"
+ echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.out--------------------"
tail -n 100 "${DORIS_HOME}"/be/log/be.out
- echo -e "\n\n\n\nWARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.INFO--------------------"
+ echo "WARNING: --------------------tail -n 100 ${DORIS_HOME}/be/log/be.INFO--------------------"
tail -n 100 "${DORIS_HOME}"/be/log/be.INFO
- echo -e "WARNING: ----------------------------------------\n\n\n\n"
+ echo "WARNING: ----------------------------------------"
}
diff --git a/regression-test/pipeline/common/github-utils.sh b/regression-test/pipeline/common/github-utils.sh
index 5a9d2ebb7b3..317667d15b2 100644
--- a/regression-test/pipeline/common/github-utils.sh
+++ b/regression-test/pipeline/common/github-utils.sh
@@ -304,6 +304,31 @@ file_changed_regression_p1() {
file_changed_regression_p0
}
+file_changed_ckb() {
+ local all_files
+ all_files=$(cat all_files)
+ if _only_modified_regression_conf; then echo "return no need" && return 1; fi
+ if [[ -z ${all_files} ]]; then echo "return need" && return 0; fi
+ for af in ${all_files}; do
+ if [[ "${af}" == 'be'* ]] ||
+ [[ "${af}" == 'bin'* ]] ||
+ [[ "${af}" == 'conf'* ]] ||
+ [[ "${af}" == 'fe'* ]] ||
+ [[ "${af}" == 'gensrc'* ]] ||
+ [[ "${af}" == 'thirdparty'* ]] ||
+ [[ "${af}" == 'build.sh' ]] ||
+ [[ "${af}" == 'env.sh' ]] ||
+ [[ "${af}" == 'regression-test/pipeline/common/github-utils.sh' ]] ||
+ [[ "${af}" == 'regression-test/pipeline/common/doris-utils.sh' ]] ||
+ [[ "${af}" == 'regression-test/pipeline/common/oss-utils.sh' ]] ||
+ [[ "${af}" == 'tools/tpch-tools/bin/run-tpch-queries.sh' ]] ||
+ [[ "${af}" == 'regression-test/pipeline/tpch/tpch-sf100/'* ]]; then
+ echo "clickbench performance related file changed, return need" && return 0
+ fi
+ done
+ echo "return no need" && return 1
+}
+
file_changed_performance() {
local all_files
all_files=$(cat all_files)
diff --git a/regression-test/pipeline/performance/run-tpcds.sh b/regression-test/pipeline/performance/run-tpcds.sh
index 0ca31c57e74..d054b85ee4d 100644
--- a/regression-test/pipeline/performance/run-tpcds.sh
+++ b/regression-test/pipeline/performance/run-tpcds.sh
@@ -125,7 +125,6 @@ exit_flag=0
echo "#### 3. run tpcds-sf${SF} query"
set_session_variable runtime_filter_mode global
bash "${teamcity_build_checkoutDir}"/tools/tpcds-tools/bin/run-tpcds-queries.sh -s "${SF}" | tee "${teamcity_build_checkoutDir}"/run-tpcds-queries.log
- echo
cold_run_time_threshold=${cold_run_time_threshold_master:-315000} # ms
hot_run_time_threshold=${hot_run_time_threshold_master:-190000} # ms
if [[ "${target_branch}" == "branch-2.0" ]]; then
diff --git a/regression-test/pipeline/performance/run-tpch.sh b/regression-test/pipeline/performance/run-tpch.sh
index f1e4c8df2a2..1620c5f2922 100644
--- a/regression-test/pipeline/performance/run-tpch.sh
+++ b/regression-test/pipeline/performance/run-tpch.sh
@@ -117,7 +117,6 @@ exit_flag=0
echo "#### 3. run tpch-sf${SF} query"
set_session_variable runtime_filter_mode global
bash "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh -s "${SF}" | tee "${teamcity_build_checkoutDir}"/run-tpch-queries.log
- echo
cold_run_time_threshold=${cold_run_time_threshold_master:-120000} # ms
hot_run_time_threshold=${hot_run_time_threshold_master:-42000} # ms
if [[ "${target_branch}" == "branch-2.0" ]]; then
diff --git a/regression-test/pipeline/tpch/tpch-sf100/clean.sh b/regression-test/pipeline/tpch/tpch-sf100/clean.sh
new file mode 100644
index 00000000000..16fa490ef9c
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/clean.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# 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.
+
+# Build Step: Command Line
+: <<EOF
+#!/bin/bash
+
+# Execute step even if some of the previous steps failed
+teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
+if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/clean.sh ]]; then
+ cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
+ bash -x clean.sh
+else
+ echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/clean.sh" && exit 1
+fi
+EOF
+
+## clean.sh content ##
+
+# stop_doris
+source ../../common/doris-utils.sh
+
+DORIS_HOME="${teamcity_build_checkoutDir}/output"
+export DORIS_HOME
+stop_doris
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf b/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf
new file mode 100644
index 00000000000..cc23ae153bf
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf
@@ -0,0 +1,85 @@
+# 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.
+
+CUR_DATE=`date +%Y%m%d-%H%M%S`
+
+PPROF_TMPDIR="$DORIS_HOME/log/"
+
+JAVA_OPTS="-Xmx1024m -DlogPath=$DORIS_HOME/log/jni.log -Xloggc:$DORIS_HOME/log/be.gc.log.$CUR_DATE -Djavax.security.auth.useSubjectCredsOnly=false -Dsun.security.krb5.debug=true -Dsun.java.command=DorisBE -XX:-CriticalJNINatives -DJDBC_MIN_POOL=1 -DJDBC_MAX_POOL=100 -DJDBC_MAX_IDLE_TIME=300000 -DJDBC_MAX_WAIT_TIME=5000"
+
+# For jdk 9+, this JAVA_OPTS will be used as default JVM options
+JAVA_OPTS_FOR_JDK_9="-Xmx1024m -DlogPath=$DORIS_HOME/log/jni.log -Xlog:gc:$DORIS_HOME/log/be.gc.log.$CUR_DATE -Djavax.security.auth.useSubjectCredsOnly=false -Dsun.security.krb5.debug=true -Dsun.java.command=DorisBE -XX:-CriticalJNINatives -DJDBC_MIN_POOL=1 -DJDBC_MAX_POOL=100 -DJDBC_MAX_IDLE_TIME=300000 -DJDBC_MAX_WAIT_TIME=5000"
+
+# since 1.2, the JAVA_HOME need to be set to run BE process.
+# JAVA_HOME=/path/to/jdk/
+
+# https://github.com/apache/doris/blob/master/docs/zh-CN/community/developer-guide/debug-tool.md#jemalloc-heap-profile
+# https://jemalloc.net/jemalloc.3.html
+JEMALLOC_CONF="percpu_arena:percpu,background_thread:true,metadata_thp:auto,muzzy_decay_ms:15000,dirty_decay_ms:15000,oversize_threshold:0,lg_tcache_max:20,prof:false,lg_prof_interval:32,lg_prof_sample:19,prof_gdump:false,prof_accum:false,prof_leak:false,prof_final:false"
+JEMALLOC_PROF_PRFIX=""
+
+# INFO, WARNING, ERROR, FATAL
+sys_log_level = INFO
+
+# ports for admin, web, heartbeat service
+be_port = 9060
+webserver_port = 8040
+heartbeat_service_port = 9050
+brpc_port = 8060
+arrow_flight_sql_port = -1
+
+# HTTPS configures
+enable_https = false
+# path of certificate in PEM format.
+ssl_certificate_path = "$DORIS_HOME/conf/cert.pem"
+# path of private key in PEM format.
+ssl_private_key_path = "$DORIS_HOME/conf/key.pem"
+
+
+# Choose one if there are more than one ip except loopback address.
+# Note that there should at most one ip match this list.
+# If no ip match this rule, will choose one randomly.
+# use CIDR format, e.g. 10.10.10.0/24 or IP format, e.g. 10.10.10.1
+# Default value is empty.
+# priority_networks = 10.10.10.0/24;192.168.0.0/16
+
+# data root path, separate by ';'
+# You can specify the storage type for each root path, HDD (cold data) or SSD (hot data)
+# eg:
+# storage_root_path = /home/disk1/doris;/home/disk2/doris;/home/disk2/doris
+# storage_root_path = /home/disk1/doris,medium:SSD;/home/disk2/doris,medium:SSD;/home/disk2/doris,medium:HDD
+# /home/disk2/doris,medium:HDD(default)
+#
+# you also can specify the properties by setting '<property>:<value>', separate by ','
+# property 'medium' has a higher priority than the extension of path
+#
+# Default value is ${DORIS_HOME}/storage, you should create it by hand.
+# storage_root_path = ${DORIS_HOME}/storage
+
+# Default dirs to put jdbc drivers,default value is ${DORIS_HOME}/jdbc_drivers
+# jdbc_drivers_dir = ${DORIS_HOME}/jdbc_drivers
+
+# Advanced configurations
+# sys_log_dir = ${DORIS_HOME}/log
+# sys_log_roll_mode = SIZE-MB-1024
+# sys_log_roll_num = 10
+# sys_log_verbose_modules = *
+# log_buffer_level = -1
+# palo_cgroups
+
+priority_networks=172.16.0.0/24
+storage_root_path=/mnt/datadisk0/doris-storage
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/external.json b/regression-test/pipeline/tpch/tpch-sf100/conf/external.json
new file mode 100644
index 00000000000..9461d836e67
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/conf/external.json
@@ -0,0 +1,26 @@
+[
+ {
+ "file": "docker/thirdparties/docker-compose/mysql/mysql-5.7.env",
+ "replacements": {
+ "DOCKER_MYSQL_57_EXTERNAL_PORT": 7111
+ }
+ },
+ {
+ "file": "docker/thirdparties/docker-compose/postgresql/postgresql-14.env",
+ "replacements": {
+ "DOCKER_PG_14_EXTERNAL_PORT": 7121
+ }
+ },
+ {
+ "file": "docker/thirdparties/docker-compose/hive/gen_env.sh",
+ "replacements": {
+ "FS_PORT": 7131,
+ "HMS_PORT": 7141
+ }
+ }, {
+ "file": "docker/thirdparties/start-thirdparties-docker.sh",
+ "replacements": {
+ "CONTAINER_UID": "doris-regression-fakeid-fakecommit"
+ }
+ }
+]
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf b/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf
new file mode 100644
index 00000000000..7c02d3898dc
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf
@@ -0,0 +1,78 @@
+# 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.
+
+#####################################################################
+## The uppercase properties are read and exported by bin/start_fe.sh.
+## To see all Frontend configurations,
+## see fe/src/org/apache/doris/common/Config.java
+#####################################################################
+
+CUR_DATE=`date +%Y%m%d-%H%M%S`
+
+# the output dir of stderr and stdout
+LOG_DIR = ${DORIS_HOME}/log
+
+JAVA_OPTS="-Dsun.security.krb5.debug=true -Djavax.security.auth.useSubjectCredsOnly=false -Xss4m -Xmx8192m -XX:+UseMembar -XX:SurvivorRatio=8 -XX:MaxTenuringThreshold=7 -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSClassUnloadingEnabled -XX:-CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=80 -XX:SoftRefLRUPolicyMSPerMB=0 -Xloggc:$DORIS_HOME/log/fe.gc.log.$CUR_DATE"
+
+# For jdk 9+, this JAVA_OPTS will be used as default JVM options
+JAVA_OPTS_FOR_JDK_9="-Dsun.security.krb5.debug=true -Djavax.security.auth.useSubjectCredsOnly=false -Xss4m -Xmx8192m -XX:SurvivorRatio=8 -XX:MaxTenuringThreshold=7 -XX:+CMSClassUnloadingEnabled -XX:-CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=80 -XX:SoftRefLRUPolicyMSPerMB=0 -Xlog:gc*:$DORIS_HOME/log/fe.gc.log.$CUR_DATE:time"
+
+##
+## the lowercase properties are read by main program.
+##
+
+# INFO, WARN, ERROR, FATAL
+sys_log_level = INFO
+
+# NORMAL, BRIEF, ASYNC
+sys_log_mode = NORMAL
+
+# store metadata, must be created before start FE.
+# Default value is ${DORIS_HOME}/doris-meta
+# meta_dir = ${DORIS_HOME}/doris-meta
+
+# Default dirs to put jdbc drivers,default value is ${DORIS_HOME}/jdbc_drivers
+# jdbc_drivers_dir = ${DORIS_HOME}/jdbc_drivers
+
+http_port = 8030
+rpc_port = 9020
+query_port = 9030
+edit_log_port = 9010
+arrow_flight_sql_port = -1
+
+# Choose one if there are more than one ip except loopback address.
+# Note that there should at most one ip match this list.
+# If no ip match this rule, will choose one randomly.
+# use CIDR format, e.g. 10.10.10.0/24 or IP format, e.g. 10.10.10.1
+# Default value is empty.
+# priority_networks = 10.10.10.0/24;192.168.0.0/16
+
+# Advanced configurations
+# log_roll_size_mb = 1024
+# sys_log_dir = ${DORIS_HOME}/log
+# sys_log_roll_num = 10
+# sys_log_verbose_modules = org.apache.doris
+# audit_log_dir = ${DORIS_HOME}/log
+# audit_log_modules = slow_query, query
+# audit_log_roll_num = 10
+# meta_delay_toleration_second = 10
+# qe_max_connection = 1024
+# qe_query_timeout_second = 300
+# qe_slow_log_ms = 5000
+
+priority_networks=172.16.0.0/24
+meta_dir=/mnt/datadisk0/doris-meta
diff --git a/regression-test/pipeline/tpch/tpch-sf100/conf/odbcinst.ini b/regression-test/pipeline/tpch/tpch-sf100/conf/odbcinst.ini
new file mode 100644
index 00000000000..41e21f92277
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/conf/odbcinst.ini
@@ -0,0 +1,43 @@
+# 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.
+
+# Example driver definitions, you should not use the example odbc driver
+# before you prepare env in your server
+
+# Driver from the postgresql-odbc package
+# Setup from the unixODBC package
+[PostgreSQL]
+Description = ODBC for PostgreSQL
+Driver = /usr/lib/psqlodbc.so
+Setup = /usr/lib/libodbcpsqlS.so
+FileUsage = 1
+
+
+# Driver from the mysql-connector-odbc package
+# Setup from the unixODBC package
+[MySQL ODBC 8.0 Unicode Driver]
+Description = ODBC for MySQL
+Driver = /usr/lib64/libmyodbc8w.so
+FileUsage = 1
+
+# Driver from the oracle-connector-odbc package
+# Setup from the unixODBC package
+[Oracle 19 ODBC driver]
+Description=Oracle ODBC driver for Oracle 19
+Driver=/usr/lib/libsqora.so.19.1
+
+
diff --git a/regression-test/pipeline/tpch/tpch-sf100/deploy.sh b/regression-test/pipeline/tpch/tpch-sf100/deploy.sh
new file mode 100644
index 00000000000..64d816f0aca
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/deploy.sh
@@ -0,0 +1,119 @@
+#!/usr/bin/env bash
+# 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.
+
+# Build Step: Command Line
+: <<EOF
+#!/bin/bash
+
+teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
+if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/deploy.sh ]]; then
+ cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
+ bash -x deploy.sh
+else
+ echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/deploy.sh" && exit 1
+fi
+EOF
+
+## deploy.sh content ##
+
+# download_oss_file
+source ../../common/oss-utils.sh
+# start_doris_fe, get_doris_conf_value, start_doris_be, stop_doris,
+# print_doris_fe_log, print_doris_be_log, archive_doris_logs
+source ../../common/doris-utils.sh
+
+echo "#### Check env"
+if [[ -z "${teamcity_build_checkoutDir}" ||
+ -z "${pull_request_id}" ||
+ -z "${commit_id}" ]]; then
+ echo "ERROR: env teamcity_build_checkoutDir or pull_request_id or commit_id not set"
+ exit 1
+fi
+if ${DEBUG:-false}; then
+ pull_request_id="26465"
+ commit_id="a532f7113f463e144e83918a37288f2649448482"
+fi
+
+echo "#### Deploy Doris ####"
+DORIS_HOME="${teamcity_build_checkoutDir}/output"
+export DORIS_HOME
+exit_flag=0
+need_backup_doris_logs=false
+
+echo "#### 1. try to kill old doris process and remove old doris binary"
+stop_doris && rm -rf output
+
+echo "#### 2. download doris binary tar ball"
+cd "${teamcity_build_checkoutDir}" || exit 1
+if download_oss_file "${pull_request_id:-}_${commit_id:-}.tar.gz"; then
+ if ! command -v pigz >/dev/null; then sudo apt install -y pigz; fi
+ tar -I pigz -xf "${pull_request_id:-}_${commit_id:-}.tar.gz"
+ if [[ -d output && -d output/fe && -d output/be ]]; then
+ echo "INFO: be version: $(./output/be/lib/doris_be --version)"
+ rm -rf "${pull_request_id}_${commit_id}.tar.gz"
+ fi
+else
+ echo "ERROR: download compiled binary failed" && exit 1
+fi
+
+echo "#### 3. copy conf from regression-test/pipeline/tpch/tpch-sf100/conf/"
+rm -f "${DORIS_HOME}"/fe/conf/fe_custom.conf "${DORIS_HOME}"/be/conf/be_custom.conf
+if [[ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf &&
+ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf ]]; then
+ cp -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf "${DORIS_HOME}"/fe/conf/
+ cp -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf "${DORIS_HOME}"/be/conf/
+else
+ echo "ERROR: doris conf file missing in ${teamcity_build_checkoutDir}/regression-test/pipeline/tpch/tpch-sf100/conf/"
+ exit 1
+fi
+
+echo "#### 4. start Doris"
+meta_dir=$(get_doris_conf_value "${DORIS_HOME}"/fe/conf/fe.conf meta_dir)
+storage_root_path=$(get_doris_conf_value "${DORIS_HOME}"/be/conf/be.conf storage_root_path)
+mkdir -p "${meta_dir}"
+mkdir -p "${storage_root_path}"
+if ! start_doris_fe; then
+ echo "ERROR: Start doris fe failed."
+ print_doris_fe_log
+ need_backup_doris_logs=true
+ exit_flag=1
+fi
+if ! start_doris_be; then
+ echo "ERROR: Start doris be failed."
+ print_doris_be_log
+ need_backup_doris_logs=true
+ exit_flag=1
+fi
+
+# wait 10s for doris totally started, otherwize may encounter the error below,
+# ERROR 1105 (HY000) at line 102: errCode = 2, detailMessage = Failed to find enough backend, please check the replication num,replication tag and storage medium.
+sleep 10s
+
+echo "#### 5. set session variables"
+echo "TODO"
+
+echo "#### 6. check if need backup doris logs"
+if ${need_backup_doris_logs}; then
+ print_doris_fe_log
+ print_doris_be_log
+ if file_name=$(archive_doris_logs "${pull_request_id}_${commit_id}_doris_logs.tar.gz"); then
+ upload_doris_log_to_oss "${file_name}"
+ fi
+fi
+
+exit "${exit_flag}"
diff --git a/regression-test/pipeline/tpch/tpch-sf100/prepare.sh b/regression-test/pipeline/tpch/tpch-sf100/prepare.sh
new file mode 100644
index 00000000000..07959a03d6f
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/prepare.sh
@@ -0,0 +1,69 @@
+#!/usr/bin/env bash
+# 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.
+
+# Build Step: Command Line
+: <<EOF
+#!/bin/bash
+
+teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
+if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/prepare.sh ]]; then
+ cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
+ bash -x prepare.sh
+else
+ echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/prepare.sh" && exit 1
+fi
+EOF
+
+## run.sh content ##
+
+echo "#### Check env"
+if [[ -z "${commit_id_from_trigger}" || -z ${commit_id:-} || -z ${pull_request_id:-} ]]; then
+ echo "ERROR: env commit_id_from_trigger or commit_id or pull_request_id not set" && exit 1
+else
+ commit_id_from_checkout=${commit_id}
+fi
+if ${DEBUG:-false}; then commit_id_from_trigger=${commit_id}; fi
+
+echo "Prepare to run tpch sf100 test"
+
+echo "#### 1. check if need run"
+if [[ "${commit_id_from_trigger}" != "${commit_id_from_checkout}" ]]; then
+ echo -e "目前是在 clickbench 流水线 compile 完后触发本 tpch 流水线的,
+有可能 pr 在 clickbench 流水线还在跑的时候新提交了commit,
+这时候 tpch 流水线 checkout 出来的 commit 就不是触发时的传过来的 commit了,
+这种情况不需要跑"
+ echo -e "ERROR: PR(${pull_request_id}),
+ the lastest commit id
+ ${commit_id_from_checkout}
+ not equail to the commit_id_from_trigger
+ ${commit_id_from_trigger}
+ commit_id_from_trigger is outdate"
+ exit 1
+fi
+
+echo "#### 2. check if depending files exist"
+if ! [[ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/fe.conf &&
+ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/conf/be.conf &&
+ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/deploy.sh &&
+ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/run.sh &&
+ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/common/oss-utils.sh &&
+ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/common/doris-utils.sh &&
+ -f "${teamcity_build_checkoutDir}"/regression-test/pipeline/common/github-utils.sh &&
+ -f "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh ]]; then
+ echo "ERROR: depending files missing" && exit 1
+fi
diff --git a/regression-test/pipeline/tpch/tpch-sf100/run.sh b/regression-test/pipeline/tpch/tpch-sf100/run.sh
new file mode 100644
index 00000000000..d9252f742c1
--- /dev/null
+++ b/regression-test/pipeline/tpch/tpch-sf100/run.sh
@@ -0,0 +1,131 @@
+#!/usr/bin/env bash
+# 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.
+
+# Build Step: Command Line
+: <<EOF
+#!/bin/bash
+
+teamcity_build_checkoutDir="%teamcity.build.checkoutDir%"
+if [[ -f "${teamcity_build_checkoutDir:-}"/regression-test/pipeline/tpch/tpch-sf100/run.sh ]]; then
+ cd "${teamcity_build_checkoutDir}"/regression-test/pipeline/tpch/tpch-sf100/
+ bash -x run.sh
+else
+ echo "Build Step file missing: regression-test/pipeline/tpch/tpch-sf100/run.sh" && exit 1
+fi
+EOF
+
+## run.sh content ##
+
+# check_tpch_table_rows, stop_doris, set_session_variable
+source ../../common/doris-utils.sh
+# create_an_issue_comment
+source ../../common/github-utils.sh
+# upload_doris_log_to_oss
+source ../../common/oss-utils.sh
+
+echo "#### Check env"
+if [[ -z "${teamcity_build_checkoutDir}" ||
+ -z "${pull_request_id}" ||
+ -z "${commit_id}" ]]; then
+ echo "ERROR: env teamcity_build_checkoutDir or pull_request_id or commit_id not set"
+ exit 1
+fi
+
+echo "#### Run tpch-sf100 test on Doris ####"
+DORIS_HOME="${teamcity_build_checkoutDir}/output"
+exit_flag=0
+
+check_tpch_result() {
+ log_file="$1"
+ if ! grep '^Total cold run time' "${log_file}" || ! grep '^Total hot run time' "${log_file}"; then
+ echo "ERROR: can not find 'Total hot run time' in '${log_file}'"
+ return 1
+ else
+ cold_run_time=$(grep '^Total cold run time' "${log_file}" | awk '{print $5}')
+ hot_run_time=$(grep '^Total hot run time' "${log_file}" | awk '{print $5}')
+ fi
+ # 单位是毫秒
+ cold_run_time_threshold=${cold_run_time_threshold:-50000}
+ hot_run_time_threshold=${hot_run_time_threshold:-42000}
+ if [[ ${cold_run_time} -gt 50000 || ${hot_run_time} -gt 42000 ]]; then
+ echo "ERROR:
+ cold_run_time ${cold_run_time} is great than the threshold ${cold_run_time_threshold},
+ or, hot_run_time ${hot_run_time} is great than the threshold ${hot_run_time_threshold}"
+ return 1
+ else
+ echo "INFO:
+ cold_run_time ${cold_run_time} is less than the threshold ${cold_run_time_threshold},
+ or, hot_run_time ${hot_run_time} is less than the threshold ${hot_run_time_threshold}"
+ fi
+}
+
+(
+ set -e
+ shopt -s inherit_errexit
+
+ echo "#### 1. check if need to load data"
+ SF="100" # SCALE FACTOR
+ if ${DEBUG:-false}; then SF="1"; fi
+ db_name="tpch_sf${SF}"
+ sed -i "s|^export DB=.*$|export DB='${db_name}'|g" \
+ "${teamcity_build_checkoutDir}"/tools/tpch-tools/conf/doris-cluster.conf
+ if ! check_tpch_table_rows "${db_name}" "${SF}"; then
+ echo "ERROR: check_tpch_table_rows failed." && exit 1
+ fi
+
+ echo "#### 2. run tpch-sf${SF} query"
+ set_session_variable runtime_filter_mode global
+ sed -i "s|^SCALE_FACTOR=[0-9]\+$|SCALE_FACTOR=${SF}|g" "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh
+ bash "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh | tee "${teamcity_build_checkoutDir}"/run-tpch-queries.log
+ if ! check_tpch_result "${teamcity_build_checkoutDir}"/run-tpch-queries.log; then exit 1; fi
+ line_end=$(sed -n '/^Total hot run time/=' "${teamcity_build_checkoutDir}"/run-tpch-queries.log)
+ line_begin=$((line_end - 23))
+ comment_body="Tpch sf${SF} test result on commit ${commit_id:-}, data reload: ${data_reload:-"false"}
+
+run tpch-sf${SF} query with default conf and session variables
+$(sed -n "${line_begin},${line_end}p" "${teamcity_build_checkoutDir}"/run-tpch-queries.log)"
+
+ echo "#### 3. run tpch-sf${SF} query with runtime_filter_mode=off"
+ set_session_variable runtime_filter_mode off
+ bash "${teamcity_build_checkoutDir}"/tools/tpch-tools/bin/run-tpch-queries.sh | tee "${teamcity_build_checkoutDir}"/run-tpch-queries.log
+ if ! grep '^Total hot run time' "${teamcity_build_checkoutDir}"/run-tpch-queries.log >/dev/null; then exit 1; fi
+ line_end=$(sed -n '/^Total hot run time/=' "${teamcity_build_checkoutDir}"/run-tpch-queries.log)
+ line_begin=$((line_end - 23))
+ comment_body="${comment_body}
+
+run tpch-sf${SF} query with default conf and set session variable runtime_filter_mode=off
+$(sed -n "${line_begin},${line_end}p" "${teamcity_build_checkoutDir}"/run-tpch-queries.log)"
+
+ echo "#### 4. comment result on tpch"
+ comment_body=$(echo "${comment_body}" | sed -e ':a;N;$!ba;s/\t/\\t/g;s/\n/\\n/g') # 将所有的 Tab字符替换为\t 换行符替换为\n
+ create_an_issue_comment_tpch "${pull_request_id:-}" "${comment_body}"
+
+ stop_doris
+)
+exit_flag="$?"
+
+echo "#### 5. check if need backup doris logs"
+if [[ ${exit_flag} != "0" ]]; then
+ print_doris_fe_log
+ print_doris_be_log
+ if file_name=$(archive_doris_logs "${pull_request_id}_${commit_id}_doris_logs.tar.gz"); then
+ upload_doris_log_to_oss "${file_name}"
+ fi
+fi
+
+exit "${exit_flag}"
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 09/43: [feature](function) support ip function is_ipv4_compat, is_ipv4_mapped (#29954)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit ead3b4ac1db66d6d021ad9b03da23d5b5356ba6d
Author: Chester <42...@users.noreply.github.com>
AuthorDate: Sun Jan 21 10:51:58 2024 +0800
[feature](function) support ip function is_ipv4_compat, is_ipv4_mapped (#29954)
---
be/src/vec/common/unaligned.h | 33 +++++-
be/src/vec/functions/function_ip.cpp | 4 +
be/src/vec/functions/function_ip.h | 130 ++++++++++++++-------
.../sql-functions/ip-functions/is-ipv4-compat.md | 65 +++++++++++
.../sql-functions/ip-functions/is-ipv4-mapped.md | 69 +++++++++++
docs/sidebars.json | 7 +-
.../sql-functions/ip-functions/is-ipv4-compat.md | 65 +++++++++++
.../sql-functions/ip-functions/is-ipv4-mapped.md | 68 +++++++++++
.../doris/catalog/BuiltinScalarFunctions.java | 4 +
.../expressions/functions/scalar/IsIpv4Compat.java | 67 +++++++++++
.../expressions/functions/scalar/IsIpv4Mapped.java | 67 +++++++++++
.../expressions/visitor/ScalarFunctionVisitor.java | 10 ++
gensrc/script/doris_builtins_functions.py | 4 +
.../data/nereids_function_p0/ip_functions.out | 32 ++++-
.../ip_functions/test_ip_functions.out | 32 ++++-
.../suites/nereids_function_p0/ip_functions.groovy | 12 ++
.../ip_functions/test_ip_functions.groovy | 12 ++
17 files changed, 635 insertions(+), 46 deletions(-)
diff --git a/be/src/vec/common/unaligned.h b/be/src/vec/common/unaligned.h
index d56eca59b23..ee807c606e5 100644
--- a/be/src/vec/common/unaligned.h
+++ b/be/src/vec/common/unaligned.h
@@ -20,8 +20,9 @@
#pragma once
-#include <string.h>
-
+#include <bit>
+#include <cstdint>
+#include <cstring>
#include <type_traits>
template <typename T>
@@ -40,3 +41,31 @@ void unaligned_store(void* address, const typename std::enable_if<true, T>::type
static_assert(std::is_trivially_copyable_v<T>);
memcpy(address, &src, sizeof(src));
}
+
+inline void reverse_memcpy(void* dst, const void* src, size_t size) {
+ uint8_t* uint_dst = reinterpret_cast<uint8_t*>(dst) + size; // Perform addition here
+ const uint8_t* uint_src = reinterpret_cast<const uint8_t*>(src);
+
+ while (size) {
+ --uint_dst;
+ *uint_dst = *uint_src;
+ ++uint_src;
+ --size;
+ }
+}
+
+template <std::endian endian, typename T>
+inline T unaligned_load_endian(const void* address) {
+ T res {};
+ if constexpr (std::endian::native == endian) {
+ memcpy(&res, address, sizeof(res));
+ } else {
+ reverse_memcpy(&res, address, sizeof(res));
+ }
+ return res;
+}
+
+template <typename T>
+inline T unaligned_load_little_endian(const void* address) {
+ return unaligned_load_endian<std::endian::little, T>(address);
+}
\ No newline at end of file
diff --git a/be/src/vec/functions/function_ip.cpp b/be/src/vec/functions/function_ip.cpp
index 3faa6a42d8c..140100d22b3 100644
--- a/be/src/vec/functions/function_ip.cpp
+++ b/be/src/vec/functions/function_ip.cpp
@@ -27,6 +27,7 @@ void register_function_ip(SimpleFunctionFactory& factory) {
factory.register_function<FunctionIPv4StringToNum<IPStringToNumExceptionMode::Null>>();
factory.register_alias(FunctionIPv4StringToNum<IPStringToNumExceptionMode::Throw>::name,
"inet_aton");
+
factory.register_function<FunctionIPv6NumToString>();
factory.register_alias(FunctionIPv6NumToString::name, "inet6_ntoa");
factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Throw>>();
@@ -34,6 +35,9 @@ void register_function_ip(SimpleFunctionFactory& factory) {
factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Null>>();
factory.register_alias(FunctionIPv6StringToNum<IPStringToNumExceptionMode::Throw>::name,
"inet6_aton");
+
+ factory.register_function<FunctionIsIPv4Compat>();
+ factory.register_function<FunctionIsIPv4Mapped>();
factory.register_function<FunctionIsIPString<IPv4>>();
factory.register_function<FunctionIsIPString<IPv6>>();
factory.register_function<FunctionIsIPAddressInRange>();
diff --git a/be/src/vec/functions/function_ip.h b/be/src/vec/functions/function_ip.h
index 313ad0fdd65..8a260b8fd82 100644
--- a/be/src/vec/functions/function_ip.h
+++ b/be/src/vec/functions/function_ip.h
@@ -364,44 +364,6 @@ ColumnPtr convertToIPv6(const StringColumnType& string_column,
vec_null_map_to = &col_null_map_to->get_data();
}
- /// This is a special treatment for source column of type String
- /// to preserve previous behavior when IPv6 was a domain type of String
- if constexpr (std::is_same_v<StringColumnType, ColumnString>) {
- if (string_column.get_offsets()[0] - 1 == IPV6_BINARY_LENGTH) {
- if constexpr (std::is_same_v<ToColumn, ColumnString>) {
- auto col_res = ColumnString::create();
-
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
- col_null_map_to = ColumnUInt8::create(column_size, false);
- if (null_map) {
- memcpy(col_null_map_to->get_data().data(), null_map->data(), column_size);
- }
-
- return ColumnNullable::create(std::move(col_res), std::move(col_null_map_to));
- }
-
- return col_res;
- } else {
- auto col_res = ColumnIPv6::create();
- auto& vec_res = col_res->get_data();
-
- vec_res.resize(column_size);
- memcpy(vec_res.data(), string_column.get_chars().data(),
- column_size * IPV6_BINARY_LENGTH);
-
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
- col_null_map_to = ColumnUInt8::create(column_size, false);
- if (null_map) {
- memcpy(col_null_map_to->get_data().data(), null_map->data(), column_size);
- }
- return ColumnNullable::create(std::move(col_res), std::move(col_null_map_to));
- }
-
- return col_res;
- }
- }
- }
-
auto column_create = [](size_t column_size) -> typename ToColumn::MutablePtr {
if constexpr (std::is_same_v<ToColumn, ColumnString>) {
auto column_string = ColumnString::create();
@@ -833,4 +795,94 @@ private:
}
};
-} // namespace doris::vectorized
\ No newline at end of file
+class FunctionIsIPv4Compat : public IFunction {
+public:
+ static constexpr auto name = "is_ipv4_compat";
+ static FunctionPtr create() { return std::make_shared<FunctionIsIPv4Compat>(); }
+
+ String get_name() const override { return name; }
+
+ size_t get_number_of_arguments() const override { return 1; }
+
+ DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
+ return std::make_shared<DataTypeUInt8>();
+ }
+
+ Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
+ size_t result, size_t input_rows_count) const override {
+ const ColumnPtr& column = block.get_by_position(arguments[0]).column;
+ const auto* col_in = check_and_get_column<ColumnString>(column.get());
+
+ if (!col_in)
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "Illegal column {} of argument of function {}, expected String",
+ column->get_name(), get_name());
+ size_t col_size = col_in->size();
+ auto col_res = ColumnUInt8::create(col_size, 0);
+ auto& col_res_data = col_res->get_data();
+
+ for (size_t i = 0; i < col_size; ++i) {
+ auto ipv4_in = col_in->get_data_at(i);
+ if (is_ipv4_compat(reinterpret_cast<const UInt8*>(ipv4_in.data))) {
+ col_res_data[i] = 1;
+ }
+ }
+
+ block.replace_by_position(result, std::move(col_res));
+ return Status::OK();
+ }
+
+private:
+ static bool is_ipv4_compat(const UInt8* address) {
+ return (unaligned_load_little_endian<UInt64>(address) == 0) &&
+ (unaligned_load_little_endian<UInt32>(address + 8) == 0) &&
+ (unaligned_load_little_endian<UInt32>(address + 12) != 0);
+ }
+};
+
+class FunctionIsIPv4Mapped : public IFunction {
+public:
+ static constexpr auto name = "is_ipv4_mapped";
+ static FunctionPtr create() { return std::make_shared<FunctionIsIPv4Mapped>(); }
+
+ String get_name() const override { return name; }
+
+ size_t get_number_of_arguments() const override { return 1; }
+
+ DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
+ return std::make_shared<DataTypeUInt8>();
+ }
+
+ Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
+ size_t result, size_t input_rows_count) const override {
+ const ColumnPtr& column = block.get_by_position(arguments[0]).column;
+ const auto* col_in = check_and_get_column<ColumnString>(column.get());
+
+ if (!col_in)
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "Illegal column {} of argument of function {}, expected String",
+ column->get_name(), get_name());
+ size_t col_size = col_in->size();
+ auto col_res = ColumnUInt8::create(col_size, 0);
+ auto& col_res_data = col_res->get_data();
+
+ for (size_t i = 0; i < col_size; ++i) {
+ auto ipv4_in = col_in->get_data_at(i);
+ if (is_ipv4_mapped(reinterpret_cast<const UInt8*>(ipv4_in.data))) {
+ col_res_data[i] = 1;
+ }
+ }
+
+ block.replace_by_position(result, std::move(col_res));
+ return Status::OK();
+ }
+
+private:
+ static bool is_ipv4_mapped(const UInt8* address) {
+ return (unaligned_load_little_endian<UInt64>(address) == 0) &&
+ ((unaligned_load_little_endian<UInt64>(address + 8) & 0x00000000FFFFFFFFULL) ==
+ 0x00000000FFFF0000ULL);
+ }
+};
+
+} // namespace doris::vectorized
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-compat.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-compat.md
new file mode 100644
index 00000000000..84c5aff9b63
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-compat.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "IS_IPV4_COMPAT",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV4_COMPAT
+
+<version since="dev">
+
+IS_IPV4_COMPAT
+
+</version>
+
+### description
+
+#### Syntax
+
+`VARCHAR IS_IPV4_COMPAT(INET6_ATON(VARCHAR ipv4_addr))`
+
+This function takes an IPv6 address represented in numeric form as a binary string, as returned by INET6_ATON().
+It returns 1 if the argument is a valid IPv4-compatible IPv6 address, 0 otherwise (unless expr is NULL, in which case the function returns NULL).
+IPv4-compatible addresses have the form ::ipv4_address.
+
+### example
+
+```
+mysql> SELECT IS_IPV4_COMPAT(INET6_ATON('::ffff:10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 0 |
++-----------+
+1 row in set (0.02 sec)
+
+mysql> SELECT IS_IPV4_COMPAT(INET6_ATON('::10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 1 |
++-----------+
+1 row in set (0.03 sec)
+```
+
+### keywords
+
+IS_IPV4_COMPAT, IP
\ No newline at end of file
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md
new file mode 100644
index 00000000000..9e338eb1353
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md
@@ -0,0 +1,69 @@
+---
+{
+"title": "IS_IPV4_MAPPED",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV4_MAPPED
+
+<version since="dev">
+
+IS_IPV4_MAPPED
+
+</version>
+
+### description
+
+#### Syntax
+
+`VARCHAR IS_IPV4_MAPPED(INET6_ATON(VARCHAR ipv4_addr))`
+
+This function takes an IPv6 address represented in numeric form as a binary string, as returned by INET6_ATON().
+It returns 1 if the argument is a valid IPv4-mapped IPv6 address, 0 otherwise, unless expr is NULL, in which case the function returns NULL.
+IPv4-mapped addresses have the form ::ffff:ipv4_address.
+
+### notice
+
+`When the source input doesn't have a prefix of '::ffff:', but if it's still a valid ipv4 address, this result will also be 1 for the reason that the INET6_ATON() automatically adds the prefix for it.`
+
+### example
+
+```
+mysql> SELECT IS_IPV4_MAPPED(INET6_ATON('::ffff:10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 1 |
++-----------+
+1 row in set (0.02 sec)
+
+mysql> SELECT IS_IPV4_MAPPED(INET6_ATON('::10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 0 |
++-----------+
+1 row in set (0.03 sec)
+```
+
+### keywords
+
+IS_IPV4_MAPPED, IP
\ No newline at end of file
diff --git a/docs/sidebars.json b/docs/sidebars.json
index 6b94989d180..bda6b8da310 100644
--- a/docs/sidebars.json
+++ b/docs/sidebars.json
@@ -811,11 +811,12 @@
"sql-manual/sql-functions/ip-functions/ipv4-string-to-num-or-null",
"sql-manual/sql-functions/ip-functions/ipv6-num-to-string",
"sql-manual/sql-functions/ip-functions/inet6-ntoa",
- "sql-manual/sql-functions/ip-functions/ipv6-num-to-string",
+ "sql-manual/sql-functions/ip-functions/ipv6-string-to-num",
"sql-manual/sql-functions/ip-functions/inet6-aton",
"sql-manual/sql-functions/ip-functions/ipv6-string-to-num-or-default",
- "sql-manual/sql-functions/ip-functions/ipv6-string-to-num-or-null"
-
+ "sql-manual/sql-functions/ip-functions/ipv6-string-to-num-or-null",
+ "sql-manual/sql-functions/ip-functions/is-ipv4-compat",
+ "sql-manual/sql-functions/ip-functions/is-ipv4-mapped"
]
},
{
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-compat.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-compat.md
new file mode 100644
index 00000000000..fba93b83430
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-compat.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "IS_IPV4_COMPAT",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV4_COMPAT
+
+<version since="dev">
+
+IS_IPV4_COMPAT
+
+</version>
+
+### description
+
+#### Syntax
+
+`VARCHAR IS_IPV4_COMPAT(INET6_ATON(VARCHAR ipv4_addr))`
+
+该函数采用以数字形式表示的二进制字符串形式的 IPv6 地址,由 INET6_ATON() 返回。
+如果参数是有效的 IPv4 兼容 IPv6 地址,则返回 1,否则返回 0(除非 expr 为 NULL,在这种情况下该函数返回 NULL)。
+IPv4 兼容地址的格式为::ipv4_address。
+
+### example
+
+```
+mysql> SELECT IS_IPV4_COMPAT(INET6_ATON('::ffff:10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 0 |
++-----------+
+1 row in set (0.02 sec)
+
+mysql> SELECT IS_IPV4_COMPAT(INET6_ATON('::10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 1 |
++-----------+
+1 row in set (0.03 sec)
+```
+
+### keywords
+
+IS_IPV4_COMPAT, IP
\ No newline at end of file
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md
new file mode 100644
index 00000000000..66de4022209
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-mapped.md
@@ -0,0 +1,68 @@
+---
+{
+"title": "IS_IPV4_MAPPED",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV4_MAPPED
+
+<version since="dev">
+
+IS_IPV4_MAPPED
+
+</version>
+
+### description
+
+#### Syntax
+
+`VARCHAR IS_IPV4_MAPPED(INET6_ATON(VARCHAR ipv4_addr))`
+
+该函数采用以数字形式表示的二进制字符串形式的lPv6地址,由INET6_ATON返回。
+如果参数是有效的IPv4映射IPv6地址,则返回1,否则返回0,除非expr为 NULL,在这种情况下该函数返回NULL。
+IPv4映射地址的格式为::ffff:ipv4_address
+
+### notice
+`当源输入没有'::ffff:'前缀时,但如果它仍然是有效的ipv4地址,则该结果也将为1,因为INET6_ATON()会自动为有效的ipv4地址添加前缀。`
+
+### example
+
+```
+mysql> SELECT IS_IPV4_MAPPED(INET6_ATON('::ffff:10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 1 |
++-----------+
+1 row in set (0.02 sec)
+
+mysql> SELECT IS_IPV4_MAPPED(INET6_ATON('::10.0.5.9')) AS is_result;
++-----------+
+| is_result |
++-----------+
+| 0 |
++-----------+
+1 row in set (0.03 sec)
+```
+
+### keywords
+
+IS_IPV4_MAPPED, IP
\ No newline at end of file
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
index f4f7af5cf38..68da4df08ab 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
@@ -203,6 +203,8 @@ import org.apache.doris.nereids.trees.expressions.functions.scalar.Ipv6StringToN
import org.apache.doris.nereids.trees.expressions.functions.scalar.Ipv6StringToNumOrDefault;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Ipv6StringToNumOrNull;
import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpAddressInRange;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv4Compat;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv4Mapped;
import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv4String;
import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv6String;
import org.apache.doris.nereids.trees.expressions.functions.scalar.JsonArray;
@@ -609,6 +611,8 @@ public class BuiltinScalarFunctions implements FunctionHelper {
scalar(Ipv6StringToNum.class, "ipv6_string_to_num", "inet6_aton"),
scalar(Ipv6StringToNumOrDefault.class, "ipv6_string_to_num_or_default"),
scalar(Ipv6StringToNumOrNull.class, "ipv6_string_to_num_or_null"),
+ scalar(IsIpv4Compat.class, "is_ipv4_compat"),
+ scalar(IsIpv4Mapped.class, "is_ipv4_mapped"),
scalar(IsIpv4String.class, "is_ipv4_string"),
scalar(IsIpv6String.class, "is_ipv6_string"),
scalar(IsIpAddressInRange.class, "is_ip_address_in_range"),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Compat.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Compat.java
new file mode 100644
index 00000000000..684eee0e9c9
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Compat.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.BooleanType;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function is_ipv4_compat
+ */
+public class IsIpv4Compat extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, PropagateNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(BooleanType.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(BooleanType.INSTANCE).args(StringType.INSTANCE));
+
+ public IsIpv4Compat(Expression arg0) {
+ super("is_ipv4_compat", arg0);
+ }
+
+ @Override
+ public IsIpv4Compat withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "is_ipv4_compat accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new IsIpv4Compat(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitIsIpv4Compat(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Mapped.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Mapped.java
new file mode 100644
index 00000000000..c3640af5437
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/IsIpv4Mapped.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.BooleanType;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function is_ipv4_mapped
+ */
+public class IsIpv4Mapped extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, PropagateNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(BooleanType.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(BooleanType.INSTANCE).args(StringType.INSTANCE));
+
+ public IsIpv4Mapped(Expression arg0) {
+ super("is_ipv4_mapped", arg0);
+ }
+
+ @Override
+ public IsIpv4Mapped withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "is_ipv4_mapped accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new IsIpv4Mapped(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitIsIpv4Mapped(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
index 899a31abbd7..01823f78199 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
@@ -199,6 +199,8 @@ import org.apache.doris.nereids.trees.expressions.functions.scalar.Ipv6StringToN
import org.apache.doris.nereids.trees.expressions.functions.scalar.Ipv6StringToNumOrDefault;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Ipv6StringToNumOrNull;
import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpAddressInRange;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv4Compat;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv4Mapped;
import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv4String;
import org.apache.doris.nereids.trees.expressions.functions.scalar.IsIpv6String;
import org.apache.doris.nereids.trees.expressions.functions.scalar.JsonArray;
@@ -1155,6 +1157,14 @@ public interface ScalarFunctionVisitor<R, C> {
return visitScalarFunction(ipv6StringToNumOrNull, context);
}
+ default R visitIsIpv4Compat(IsIpv4Compat isIpv4Compat, C context) {
+ return visitScalarFunction(isIpv4Compat, context);
+ }
+
+ default R visitIsIpv4Mapped(IsIpv4Mapped isIpv4Mapped, C context) {
+ return visitScalarFunction(isIpv4Mapped, context);
+ }
+
default R visitIsIpv4String(IsIpv4String isIpv4String, C context) {
return visitScalarFunction(isIpv4String, context);
}
diff --git a/gensrc/script/doris_builtins_functions.py b/gensrc/script/doris_builtins_functions.py
index 973a4675621..6a6ff96e83d 100644
--- a/gensrc/script/doris_builtins_functions.py
+++ b/gensrc/script/doris_builtins_functions.py
@@ -2014,6 +2014,10 @@ visible_functions = {
[['ipv6_string_to_num_or_default'], 'STRING', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
[['ipv6_string_to_num_or_null'], 'VARCHAR', ['VARCHAR'], 'ALWAYS_NULLABLE'],
[['ipv6_string_to_num_or_null'], 'STRING', ['STRING'], 'ALWAYS_NULLABLE'],
+ [['is_ipv4_compat'], 'BOOLEAN', ['VARCHAR'], ''],
+ [['is_ipv4_compat'], 'BOOLEAN', ['STRING'], ''],
+ [['is_ipv4_mapped'], 'BOOLEAN', ['VARCHAR'], ''],
+ [['is_ipv4_mapped'], 'BOOLEAN', ['STRING'], ''],
[['is_ipv4_string'], 'BOOLEAN', ['VARCHAR'], ''],
[['is_ipv4_string'], 'BOOLEAN', ['STRING'], ''],
[['is_ipv6_string'], 'BOOLEAN', ['VARCHAR'], ''],
diff --git a/regression-test/data/nereids_function_p0/ip_functions.out b/regression-test/data/nereids_function_p0/ip_functions.out
index 2e3b749a152..914b5ccd683 100644
--- a/regression-test/data/nereids_function_p0/ip_functions.out
+++ b/regression-test/data/nereids_function_p0/ip_functions.out
@@ -162,4 +162,34 @@ false
true
-- !ip55 --
-false
\ No newline at end of file
+false
+
+-- !ip56 --
+true
+
+-- !ip57 --
+false
+
+-- !ip58 --
+false
+
+-- !ip59 --
+true
+
+-- !ip60 --
+false
+
+-- !ip61 --
+true
+
+-- !ip62 --
+false
+
+-- !ip63 --
+true
+
+-- !ip64 --
+false
+
+-- !ip65 --
+true
\ No newline at end of file
diff --git a/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out b/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out
index 71f02449d3b..1837acc4bab 100644
--- a/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out
+++ b/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out
@@ -137,4 +137,34 @@ AAAAAAAAFFFFFFFFFFFFFFFFAAAAAAAA
00000000000000000000FFFFC0A80001
-- !sql --
-2A0206B8000000000000000000000011
\ No newline at end of file
+2A0206B8000000000000000000000011
+
+-- !sql --
+true
+
+-- !sql --
+false
+
+-- !sql --
+false
+
+-- !sql --
+true
+
+-- !sql --
+false
+
+-- !sql --
+true
+
+-- !sql --
+false
+
+-- !sql --
+true
+
+-- !sql --
+false
+
+-- !sql --
+true
\ No newline at end of file
diff --git a/regression-test/suites/nereids_function_p0/ip_functions.groovy b/regression-test/suites/nereids_function_p0/ip_functions.groovy
index 1ac00102094..b5d4d177e89 100644
--- a/regression-test/suites/nereids_function_p0/ip_functions.groovy
+++ b/regression-test/suites/nereids_function_p0/ip_functions.groovy
@@ -77,4 +77,16 @@ suite("ip_functions") {
qt_ip53 "SELECT is_ipv4_string('255.255.255.256');"
qt_ip54 "SELECT is_ipv6_string('2001:5b0:23ff:fffa::113');"
qt_ip55 "SELECT is_ipv6_string('2001:da8:e000:1691:2eaa:7eff:ffe7:7924e');"
+
+ qt_ip56 "SELECT is_ipv4_compat(inet6_aton('::10.0.5.9'));"
+ qt_ip57 "SELECT is_ipv4_compat(inet6_aton('::ffff:10.0.5.9'));"
+ qt_ip58 "SELECT is_ipv4_compat(inet6_aton('::'));"
+ qt_ip59 "SELECT is_ipv4_compat(inet6_aton('::c0a8:0001'));"
+ qt_ip60 "SELECT is_ipv4_compat(inet6_aton('::0.0.0.0'));"
+ qt_ip61 "SELECT is_ipv4_compat(inet6_aton('::255.255.255.255'));"
+
+ qt_ip62 "SELECT is_ipv4_mapped(inet6_aton('::10.0.5.9'));"
+ qt_ip63 "SELECT is_ipv4_mapped(inet6_aton('::ffff:10.0.5.9'));"
+ qt_ip64 "SELECT is_ipv4_mapped(inet6_aton('::'));"
+ qt_ip65 "SELECT is_ipv4_mapped(inet6_aton('::ffff:c0a8:0001'));"
}
\ No newline at end of file
diff --git a/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy b/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy
index 828de6cbe41..c5ff6d36a13 100644
--- a/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy
+++ b/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy
@@ -67,4 +67,16 @@ suite("test_ip_functions", "arrow_flight_sql") {
qt_sql "SELECT hex(ipv6_string_to_num_or_null('aaaa:aaaa:ffff:ffff:ffff:ffff:aaaa:aaaa'));"
qt_sql "SELECT hex(inet6_aton('192.168.0.1'));"
qt_sql "SELECT hex(inet6_aton('2a02:6b8::11'));"
+
+ qt_sql "SELECT is_ipv4_compat(inet6_aton('::10.0.5.9'));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton('::ffff:10.0.5.9'));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton('::'));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton('::c0a8:0001'));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton('::0.0.0.0'));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton('::255.255.255.255'));"
+
+ qt_sql "SELECT is_ipv4_mapped(inet6_aton('::10.0.5.9'));"
+ qt_sql "SELECT is_ipv4_mapped(inet6_aton('::ffff:10.0.5.9'));"
+ qt_sql "SELECT is_ipv4_mapped(inet6_aton('::'));"
+ qt_sql "SELECT is_ipv4_mapped(inet6_aton('::ffff:c0a8:0001'));"
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 03/43: [fix](tablet meta) stale rowset is not loaded while BE start (#30077)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 21db1ecff2078cdc61e23cca1fd618b5defb9eec
Author: zhannngchen <48...@users.noreply.github.com>
AuthorDate: Fri Jan 19 15:59:01 2024 +0800
[fix](tablet meta) stale rowset is not loaded while BE start (#30077)
---
be/src/olap/tablet_meta.cpp | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/be/src/olap/tablet_meta.cpp b/be/src/olap/tablet_meta.cpp
index 3246e947d13..75ed4a909f3 100644
--- a/be/src/olap/tablet_meta.cpp
+++ b/be/src/olap/tablet_meta.cpp
@@ -561,6 +561,13 @@ void TabletMeta::init_from_pb(const TabletMetaPB& tablet_meta_pb) {
_rs_metas.push_back(std::move(rs_meta));
}
+ // init _stale_rs_metas
+ for (auto& it : tablet_meta_pb.stale_rs_metas()) {
+ RowsetMetaSharedPtr rs_meta(new RowsetMeta());
+ rs_meta->init_from_pb(it);
+ _stale_rs_metas.push_back(std::move(rs_meta));
+ }
+
// For mow table, delete bitmap of stale rowsets has not been persisted.
// When be restart, query should not read the stale rowset, otherwise duplicate keys
// will be read out. Therefore, we don't add them to _stale_rs_meta for mow table.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 40/43: [fix](routine-load) pause job when json path is invalid #30197
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 32c5153999ddf59325fed9688fd568574b417e42
Author: HHoflittlefish777 <77...@users.noreply.github.com>
AuthorDate: Mon Jan 22 20:34:14 2024 +0800
[fix](routine-load) pause job when json path is invalid #30197
If jsonpaths is set wrong, routine load job will report error but running all time.For example:
CREATE ROUTINE LOAD jobName ON tableName
PROPERTIES
(
"format" = "json",
"max_batch_interval" = "5",
"max_batch_rows" = "300000",
"max_batch_size" = "209715200",
"jsonpaths" = "[\'t\',\'a\']"
)
FROM KAFKA
(
"kafka_broker_list" = "$IP:PORT",
"kafka_topic" = "XXX",
"property.kafka_default_offsets" = "OFFSET_BEGINNING"
);
Jsonpaths ['t','a'] is invalid, but job will running all time.
---
be/src/common/status.h | 2 +
be/src/vec/exec/format/json/new_json_reader.cpp | 6 +-
.../doris/load/routineload/RoutineLoadJob.java | 10 ++
.../apache/doris/transaction/TransactionState.java | 3 +-
gensrc/thrift/Status.thrift | 1 +
.../routine_load/data/invalid_json_path.json | 20 ++++
.../routine_load/test_routine_load_error.groovy | 110 +++++++++++++++++++++
7 files changed, 148 insertions(+), 4 deletions(-)
diff --git a/be/src/common/status.h b/be/src/common/status.h
index bea168299e1..c22f4c568ff 100644
--- a/be/src/common/status.h
+++ b/be/src/common/status.h
@@ -35,6 +35,7 @@ namespace ErrorCode {
TStatusError(MEM_ALLOC_FAILED, true); \
TStatusError(BUFFER_ALLOCATION_FAILED, true); \
TStatusError(INVALID_ARGUMENT, false); \
+ TStatusError(INVALID_JSON_PATH, false); \
TStatusError(MINIMUM_RESERVATION_UNAVAILABLE, true); \
TStatusError(CORRUPTION, true); \
TStatusError(IO_ERROR, true); \
@@ -403,6 +404,7 @@ public:
ERROR_CTOR(MemoryAllocFailed, MEM_ALLOC_FAILED)
ERROR_CTOR(BufferAllocFailed, BUFFER_ALLOCATION_FAILED)
ERROR_CTOR(InvalidArgument, INVALID_ARGUMENT)
+ ERROR_CTOR(InvalidJsonPath, INVALID_JSON_PATH)
ERROR_CTOR(MinimumReservationUnavailable, MINIMUM_RESERVATION_UNAVAILABLE)
ERROR_CTOR(Corruption, CORRUPTION)
ERROR_CTOR(IOError, IO_ERROR)
diff --git a/be/src/vec/exec/format/json/new_json_reader.cpp b/be/src/vec/exec/format/json/new_json_reader.cpp
index 21b99ff9720..97affdcd0bb 100644
--- a/be/src/vec/exec/format/json/new_json_reader.cpp
+++ b/be/src/vec/exec/format/json/new_json_reader.cpp
@@ -414,12 +414,12 @@ Status NewJsonReader::_parse_jsonpath_and_json_root() {
rapidjson::Document jsonpaths_doc;
if (!jsonpaths_doc.Parse(_jsonpaths.c_str(), _jsonpaths.length()).HasParseError()) {
if (!jsonpaths_doc.IsArray()) {
- return Status::InvalidArgument("Invalid json path: {}", _jsonpaths);
+ return Status::InvalidJsonPath("Invalid json path: {}", _jsonpaths);
}
for (int i = 0; i < jsonpaths_doc.Size(); i++) {
const rapidjson::Value& path = jsonpaths_doc[i];
if (!path.IsString()) {
- return Status::InvalidArgument("Invalid json path: {}", _jsonpaths);
+ return Status::InvalidJsonPath("Invalid json path: {}", _jsonpaths);
}
std::vector<JsonPath> parsed_paths;
JsonFunctions::parse_json_paths(path.GetString(), &parsed_paths);
@@ -427,7 +427,7 @@ Status NewJsonReader::_parse_jsonpath_and_json_root() {
}
} else {
- return Status::InvalidArgument("Invalid json path: {}", _jsonpaths);
+ return Status::InvalidJsonPath("Invalid json path: {}", _jsonpaths);
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
index 889d240ce29..9ce8bb2e5ac 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
@@ -1145,6 +1145,16 @@ public abstract class RoutineLoadJob extends AbstractTxnStateChangeCallback impl
String msg;
if (txnStatusChangeReason != null) {
switch (txnStatusChangeReason) {
+ case INVALID_JSON_PATH:
+ msg = "be " + taskBeId + " abort task,"
+ + " task id: " + routineLoadTaskInfo.getId()
+ + " job id: " + routineLoadTaskInfo.getJobId()
+ + " with reason: " + txnStatusChangeReasonString
+ + " please check the jsonpaths";
+ updateState(JobState.PAUSED,
+ new ErrorReason(InternalErrorCode.TASKS_ABORT_ERR, msg),
+ false /* not replay */);
+ return;
case OFFSET_OUT_OF_RANGE:
msg = "be " + taskBeId + " abort task,"
+ " task id: " + routineLoadTaskInfo.getId()
diff --git a/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java b/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java
index c4fc6de761d..f9a094eceb9 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java
@@ -108,7 +108,8 @@ public class TransactionState implements Writable {
TIMEOUT,
OFFSET_OUT_OF_RANGE,
PAUSE,
- NO_PARTITIONS;
+ NO_PARTITIONS,
+ INVALID_JSON_PATH;
public static TxnStatusChangeReason fromString(String reasonString) {
for (TxnStatusChangeReason txnStatusChangeReason : TxnStatusChangeReason.values()) {
diff --git a/gensrc/thrift/Status.thrift b/gensrc/thrift/Status.thrift
index 06083b9a93c..cb80350fb6e 100644
--- a/gensrc/thrift/Status.thrift
+++ b/gensrc/thrift/Status.thrift
@@ -75,6 +75,7 @@ enum TStatusCode {
INCOMPLETE = 44,
OLAP_ERR_VERSION_ALREADY_MERGED = 45,
DATA_QUALITY_ERROR = 46,
+ INVALID_JSON_PATH = 47,
VEC_EXCEPTION = 50,
VEC_LOGIC_ERROR = 51,
diff --git a/regression-test/suites/load_p0/routine_load/data/invalid_json_path.json b/regression-test/suites/load_p0/routine_load/data/invalid_json_path.json
new file mode 100644
index 00000000000..6ef920fcad9
--- /dev/null
+++ b/regression-test/suites/load_p0/routine_load/data/invalid_json_path.json
@@ -0,0 +1,20 @@
+{"k00": "21", "k01": "2023-08-18", "k02": "0", "k03": "63", "k04": "-27847", "k05": "-35409596", "k06": "8638201997392767650", "k07": "4919963231735304178", "k08": "-23382.541", "k09": "-1803403621.4263129", "k10": "-22009767", "k11": "\\N", "k12": "2023-03-31 10:56:14", "k13": "2023-01-20", "k14": "2023-02-18 13:37:52", "k15": "N", "k16": "T", "k17": "PSiFwUEx3eVFNtjlnQ70YkgZNvKrGmQ2DN5K9yYHiSdFWeEDB1UpL3Frt8z1kEAIWRDWqXZuyi", "k18": "\\N"}
+{"k00": "8", "k01": "2023-08-14", "k02": "1", "k03": "109", "k04": "-31573", "k05": "-1362465190", "k06": "3990845741226497177", "k07": "2732763251146840270", "k08": "-25698.553", "k09": "1312831962.5678179", "k10": "\\N", "k11": "\\N", "k12": "2023-03-07 14:13:19", "k13": "2022-10-18", "k14": "2023-07-16 05:03:13", "k15": "D", "k16": "", "k17": "PBn1wa6X8WneZYLMac11zzyhGl7tPXB5XgjmOV8L6uav9ja5oY433ktb2yhyQQIqBveZPkme", "k18": "\\N"}
+{"k00": "91", "k01": "2023-08-27", "k02": "1", "k03": "90", "k04": "2465", "k05": "702240964", "k06": "6373830997821598984", "k07": "305860046137409400", "k08": "15991.356", "k09": "1599972327.386147", "k10": "\\N", "k11": "\\N", "k12": "2023-04-26 19:31:10", "k13": "2023-07-21", "k14": "\\N", "k15": "2", "k16": "", "k17": "B7YKYBYT8w0YC926bZ8Yz1VzyiWw2NWDAiTlEoPVyz9AXGti2Npg1FxWqWk4hEaALw0ZBSuiAIPj41lq36g5QRpPmAjNPK", "k18": "\\N"}
+{"k00": "80", "k01": "2023-08-18", "k02": "0", "k03": "-18", "k04": "-8971", "k05": "679027874", "k06": "6535956962935330265", "k07": "3960889045799757165", "k08": "-13219.76", "k09": "1187161924.505394", "k10": "\\N", "k11": "\\N", "k12": "2023-03-11 07:40:00", "k13": "2022-11-29", "k14": "2023-01-14 07:24:07", "k15": "N", "k16": "D", "k17": "3Nhx6xX1qdwaq7lxwLRSKMtJFbC03swWv12mpySSVysH3igGZTiGPuKMsYW7HAkf6CWc7c0nzqDsjuH3FYVMNCWRmfxMrmY8rykQCC4Ve", "k18": "\\N"}
+{"k00": "20", "k01": "2023-08-17", "k02": "0", "k03": "-5", "k04": "18158", "k05": "784479801", "k06": "1485484354598941738", "k07": "-6632681928222776815", "k08": "9708.4307", "k09": "-330432620.706069", "k10": "\\N", "k11": "\\N", "k12": "2022-09-15 21:40:55", "k13": "2023-02-23", "k14": "2023-08-13 21:31:54", "k15": "O", "k16": "X", "k17": "2pYmX2vAhfEEHZZYPsgAmda1G7otnwx5TmUC879FPhDeIjvWI79ksBZpfFG2gp7jhCSbpZiecKGklB5SvG8tm31i5SUqe1xrWgLt4HSq7lMJWp75tx2kxD7pRIOpn", "k18": "\\N"}
+{"k00": "66", "k01": "2023-08-15", "k02": "1", "k03": "-91", "k04": "28378", "k05": "609923317", "k06": "4872185586197131212", "k07": "1207709464099378591", "k08": "\\N", "k09": "-1863683325.9851229", "k10": "\\N", "k11": "\\N", "k12": "2022-09-24 10:39:23", "k13": "2022-09-24", "k14": "2022-10-16 18:36:43", "k15": "Y", "k16": "z", "k17": "AI1BSPQdKiHJiQH1kguyLSWsDXkC7zwy7PwgWnyGSaa9tBKRex8vHBdxg2QSKZKL2mV2lHz7iI1PnsTd4MXDcIKhqiHyPuQPt2tEtgt0UgF6", "k18": "\\N"}
+{"k00": "49", "k01": "2023-08-08", "k02": "0", "k03": "\\N", "k04": "16275", "k05": "-2144851675", "k06": "-2303421957908954634", "k07": "-46526938720058765", "k08": "-13141.143", "k09": "-686632233.2302", "k10": "\\N", "k11": "\\N", "k12": "2022-09-01 00:16:01", "k13": "2023-03-25", "k14": "2022-09-07 14:59:03", "k15": "s", "k16": "", "k17": "yvuILR2iNxfe8RRml", "k18": "\\N"}
+{"k00": "57", "k01": "2023-08-19", "k02": "1", "k03": "2", "k04": "-25462", "k05": "-74112029", "k06": "6458082754318544493", "k07": "-7910671781690629051", "k08": "-15205.859", "k09": "-306870797.484914", "k10": "\\N", "k11": "\\N", "k12": "2023-07-10 18:39:10", "k13": "2023-02-12", "k14": "2023-01-27 07:26:06", "k15": "y", "k16": "", "k17": "Xi9nDVrLv8m6AwEpUxmtzFAuK48sQ", "k18": "\\N"}
+{"k00": "31", "k01": "2023-08-27", "k02": "0", "k03": "17", "k04": "-18849", "k05": "1728109133", "k06": "3266501886640700374", "k07": "527195452623418935", "k08": "-24062.328", "k09": "-1514348021.262435", "k10": "\\N", "k11": "\\N", "k12": "2022-10-07 03:24:23", "k13": "2022-09-25", "k14": "\\N", "k15": "0", "k16": "8", "k17": "yKMiAntORoRa8svnMfcxlOPwwND1m5s2fdS26Xu6cfs6HK5SAibqIp9h8sZcpjHy4", "k18": "\\N"}
+{"k00": "81", "k01": "2023-08-23", "k02": "0", "k03": "106", "k04": "11492", "k05": "-667795397", "k06": "4480250461471356146", "k07": "-5346660566234294101", "k08": "9082.75", "k09": "385167225.902608", "k10": "\\N", "k11": "\\N", "k12": "2023-03-20 03:33:16", "k13": "2022-11-24", "k14": "2023-02-16 18:29:41", "k15": "G", "k16": "9", "k17": "Lk3eNVQNjucbekD1rZmUlGPiXS5JvcWr2LQzRU8GSGIbSag", "k18": "\\N"}
+{"k00": "58", "k01": "2023-08-22", "k02": "\\N", "k03": "0", "k04": "-18231", "k05": "1832867360", "k06": "6997858407575297145", "k07": "2480714305422728023", "k08": "-5450.4888", "k09": "1475901032.138386", "k10": "\\N", "k11": "\\N", "k12": "2023-02-02 05:13:24", "k13": "2022-09-18", "k14": "2023-04-23 10:51:15", "k15": "k", "k16": "", "k17": "LdFXF7Kmfzgmnn2R6zLsXdmi3A2cLBLq4G4WDVNDhxvH7dYH8Kga2WA47uSIxp6NSrwPSdw0ssB1TS8RFJTDJAB0Uba3e05NL2Aiw0ja", "k18": "\\N"}
+{"k00": "85", "k01": "2023-08-11", "k02": "1", "k03": "-7", "k04": "24304", "k05": "-2043877415", "k06": "-2024144417867729183", "k07": "\\N", "k08": "5363.0244", "k09": "-578615669.042831", "k10": "\\N", "k11": "\\N", "k12": "2023-07-15 01:07:41", "k13": "2023-08-13", "k14": "2023-01-20 11:57:48", "k15": "i", "k16": "", "k17": "WQ9dh9ajPu0y", "k18": "\\N"}
+{"k00": "60", "k01": "2023-08-27", "k02": "0", "k03": "-52", "k04": "-2338", "k05": "-757056972", "k06": "1047567408607120856", "k07": "6541476642780646552", "k08": "6614.0894", "k09": "-1204448798.5178549", "k10": "\\N", "k11": "\\N", "k12": "2022-12-29 14:47:30", "k13": "2022-09-24", "k14": "2023-08-01 12:41:59", "k15": "O", "k16": "F", "k17": "RM4F1Ke7lkcnuxF2nK0j9VBW3MDcgyHR4pseBjtFnqS6GUkVFuzF6u3Cp9Nv7ab0O6UYrpP4DhU", "k18": "\\N"}
+{"k00": "41", "k01": "2023-08-27", "k02": "1", "k03": "-104", "k04": "22750", "k05": "\\N", "k06": "8527773271030840740", "k07": "5554497317268279215", "k08": "-5296.8281", "k09": "-1715646888.01304", "k10": "\\N", "k11": "\\N", "k12": "2022-12-02 17:56:44", "k13": "2022-10-12", "k14": "2023-02-19 07:02:54", "k15": "V", "k16": "", "k17": "E9GzQdTwX1ITUQz27IVznAs6Ca4WwprKk6Odjs6SH75D2F1089QiY3HQ52LXRD1V6xAWjhLE2hWgW3EdHuAOnUDVrb5V", "k18": "\\N"}
+{"k00": "62", "k01": "2023-08-21", "k02": "0", "k03": "81", "k04": "20302", "k05": "-200761532", "k06": "6365479976421007608", "k07": "\\N", "k08": "-29916.533", "k09": "1709141750.8284781", "k10": "\\N", "k11": "\\N", "k12": "2023-05-04 01:14:51", "k13": "2022-09-17", "k14": "2022-12-04 19:30:09", "k15": "d", "k16": "v", "k17": "BKWy9dTNg1aZW7ancEJAmEDOPK5TwFsNSHbI78emu9gymeIlx5NoLmyii0QAqdzRvSQPZKiqKkwInGCTIBnK1yYkK7zD", "k18": "\\N"}
+{"k00": "50", "k01": "2023-08-24", "k02": "1", "k03": "15", "k04": "14403", "k05": "\\N", "k06": "-6418906115745394180", "k07": "9205303779366462513", "k08": "-4331.5488", "k09": "-615112179.557648", "k10": "\\N", "k11": "\\N", "k12": "2022-12-29 02:27:20", "k13": "2023-06-01", "k14": "2023-08-12 04:50:04", "k15": "a", "k16": "", "k17": "eCl38sztIvBQvGvGKyYZmyMXy9vIJx197iu3JwP9doJGcrYUl9Uova0rz4iCCgrjlAiZU18Fs9YtCq830nhM", "k18": "\\N"}
+{"k00": "50", "k01": "2023-08-06", "k02": "1", "k03": "109", "k04": "-6330", "k05": "1479023892", "k06": "-8630800697573159428", "k07": "-1645095773540208759", "k08": "17880.961", "k09": "-1453844792.0139489", "k10": "\\N", "k11": "\\N", "k12": "2022-09-22 02:03:21", "k13": "2023-05-14", "k14": "2023-03-25 02:18:34", "k15": "m", "k16": "", "k17": "JKnIgXvGVidGiWl9YRSi3mFI7wHKt1sBpWSadKF8VX3LAuElm4sdc9gtxREaUr57oikSYlU8We8h1MWqQlYNiJObl", "k18": "\\N"}
+{"k00": "68", "k01": "2023-08-23", "k02": "1", "k03": "-73", "k04": "20117", "k05": "1737338128", "k06": "795638676048937749", "k07": "-5551546237562433901", "k08": "-30627.039", "k09": "68589475.684545", "k10": "\\N", "k11": "\\N", "k12": "2022-12-28 20:26:51", "k13": "2022-10-04", "k14": "2023-07-30 00:20:06", "k15": "y", "k16": "", "k17": "keZ3JlWWpdnPBejf0cuiCQCVBBTd5gjvO08NVdcAFewqL7nRT4N9lnvSU6pWmletA5VbPQCeQapJdcnQCHfZUDCf4ulCnczyqr7SGrbGRT0XYcd7iktKM", "k18": "\\N"}
+{"k00": "90", "k01": "2023-08-27", "k02": "1", "k03": "22", "k04": "16456", "k05": "-1476824962", "k06": "-3279894870153540825", "k07": "8990195191470116763", "k08": "26651.906", "k09": "206860148.942546", "k10": "\\N", "k11": "\\N", "k12": "2022-10-07 03:11:03", "k13": "2023-03-18", "k14": "2023-04-15 00:38:33", "k15": "T", "k16": "L", "k17": "QW0GQ3GoMtHgxPQOWGfVaveynahNpsNs09siMFA1OtO6QEDBQTdivmGyq7bFzejAqwbbVQQpREAmeLjcFSXLnQuou2KbwYD", "k18": "\\N"}
+{"k00": "65", "k01": "2023-08-09", "k02": "0", "k03": "94", "k04": "31514", "k05": "814994517", "k06": "-297697460695940343", "k07": "734910652450318597", "k08": "-13061.892", "k09": "62750847.041706", "k10": "-9808654", "k11": "\\N", "k12": "2023-08-14 22:01:27", "k13": "2023-05-19", "k14": "2022-11-13 13:44:28", "k15": "V", "k16": "", "k17": "aGeMsI24O12chGlP5ak0AHghAz7bu5MargJBStHnt0yMnChH0JnfYhsfH1u59XIHkJKMsHYktBqORkGlovu8V47E74KeFpaqxn5yLyXfDbhhzUKf", "k18": "\\N"}
diff --git a/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy b/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy
index c4180e35f4d..191ea4381fd 100644
--- a/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy
+++ b/regression-test/suites/load_p0/routine_load/test_routine_load_error.groovy
@@ -25,6 +25,10 @@ suite("test_routine_load_error","p0") {
"multi_table_load_invalid_table",
]
+ def kafkaJsonTopics = [
+ "invalid_json_path",
+ ]
+
String enabled = context.config.otherConfigs.get("enableKafkaTest")
String kafka_port = context.config.otherConfigs.get("kafka_port")
String externalEnvIp = context.config.otherConfigs.get("externalEnvIp")
@@ -48,6 +52,15 @@ suite("test_routine_load_error","p0") {
producer.send(record)
}
}
+ for (String kafkaJsonTopic in kafkaJsonTopics) {
+ def kafkaJson = new File("""${context.file.parent}/data/${kafkaJsonTopic}.json""").text
+ def lines = kafkaJson.readLines()
+ lines.each { line ->
+ logger.info("=====${line}========")
+ def record = new ProducerRecord<>(kafkaJsonTopic, null, line)
+ producer.send(record)
+ }
+ }
}
def i = 0
@@ -138,4 +151,101 @@ suite("test_routine_load_error","p0") {
sql "stop routine load for ${jobName}"
}
}
+
+ // test json path is invalid
+ if (enabled != null && enabled.equalsIgnoreCase("true")) {
+ def tableName = "test_invalid_json_path"
+ def jobName = "invalid_json_path"
+ try {
+ sql """ DROP TABLE IF EXISTS ${tableName} """
+ sql """
+ CREATE TABLE IF NOT EXISTS ${tableName}
+ (
+ k00 INT NOT NULL,
+ k01 array<BOOLEAN> NULL,
+ k02 array<TINYINT> NULL,
+ k03 array<SMALLINT> NULL,
+ k04 array<INT> NULL,
+ k05 array<BIGINT> NULL,
+ k06 array<LARGEINT> NULL,
+ k07 array<FLOAT> NULL,
+ k08 array<DOUBLE> NULL,
+ k09 array<DECIMAL> NULL,
+ k10 array<DECIMALV3> NULL,
+ k11 array<DATE> NULL,
+ k12 array<DATETIME> NULL,
+ k13 array<DATEV2> NULL,
+ k14 array<DATETIMEV2> NULL,
+ k15 array<CHAR> NULL,
+ k16 array<VARCHAR> NULL,
+ k17 array<STRING> NULL,
+ kd01 array<BOOLEAN> NOT NULL DEFAULT "[]",
+ kd02 array<TINYINT> NOT NULL DEFAULT "[]",
+ kd03 array<SMALLINT> NOT NULL DEFAULT "[]",
+ kd04 array<INT> NOT NULL DEFAULT "[]",
+ kd05 array<BIGINT> NOT NULL DEFAULT "[]",
+ kd06 array<LARGEINT> NOT NULL DEFAULT "[]",
+ kd07 array<FLOAT> NOT NULL DEFAULT "[]",
+ kd08 array<DOUBLE> NOT NULL DEFAULT "[]",
+ kd09 array<DECIMAL> NOT NULL DEFAULT "[]",
+ kd10 array<DECIMALV3> NOT NULL DEFAULT "[]",
+ kd11 array<DATE> NOT NULL DEFAULT "[]",
+ kd12 array<DATETIME> NOT NULL DEFAULT "[]",
+ kd13 array<DATEV2> NOT NULL DEFAULT "[]",
+ kd14 array<DATETIMEV2> NOT NULL DEFAULT "[]",
+ kd15 array<CHAR> NOT NULL DEFAULT "[]",
+ kd16 array<VARCHAR> NOT NULL DEFAULT "[]",
+ kd17 array<STRING> NOT NULL DEFAULT "[]"
+ )
+ UNIQUE KEY(k00)
+ DISTRIBUTED BY HASH(k00) BUCKETS 32
+ PROPERTIES (
+ "replication_num" = "1",
+ "enable_unique_key_merge_on_write" = "true"
+ );
+ """
+
+ sql """
+ CREATE ROUTINE LOAD ${jobName} ON ${tableName}
+ COLUMNS(k00,k01,k02,k03,k04,k05,k06,k07,k08,k09,k10,k11,k12,k13,k14,k15,k16,k17)
+ PROPERTIES
+ (
+ "format" = "json",
+ "max_batch_interval" = "5",
+ "max_batch_rows" = "300000",
+ "max_batch_size" = "209715200",
+ "jsonpaths" = "[\'t\',\'a\']"
+ )
+ FROM KAFKA
+ (
+ "kafka_broker_list" = "${externalEnvIp}:${kafka_port}",
+ "kafka_topic" = "${jobName}",
+ "property.kafka_default_offsets" = "OFFSET_BEGINNING"
+ );
+ """
+
+ def count = 0
+ while (true) {
+ sleep(1000)
+ def res = sql "show routine load for ${jobName}"
+ def state = res[0][8].toString()
+ log.info("routine load state: ${res[0][8].toString()}".toString())
+ log.info("routine load statistic: ${res[0][14].toString()}".toString())
+ log.info("reason of state changed: ${res[0][17].toString()}".toString())
+ if (state != "PAUSED") {
+ count++
+ if (count > 60) {
+ assertEquals(1, 2)
+ }
+ continue;
+ }
+ log.info("reason of state changed: ${res[0][17].toString()}".toString())
+ assertTrue(res[0][17].toString().contains("Invalid json path"))
+ break;
+ }
+ } finally {
+ sql "stop routine load for ${jobName}"
+ sql """ DROP TABLE IF EXISTS ${tableName} """
+ }
+ }
}
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 04/43: [pipelineX](filescan) Support parallel executing for external table scanning (#30121)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit caf7790797c3367069a022e8af180bdaa066cb50
Author: Gabriel <ga...@gmail.com>
AuthorDate: Fri Jan 19 16:12:35 2024 +0800
[pipelineX](filescan) Support parallel executing for external table scanning (#30121)
---
.../src/main/java/org/apache/doris/planner/OlapScanNode.java | 5 +++++
.../src/main/java/org/apache/doris/planner/ScanNode.java | 7 +++++--
.../org/apache/doris/planner/external/FileQueryScanNode.java | 12 ++++++++++++
3 files changed, 22 insertions(+), 2 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java b/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java
index e5381a2018f..be2c9a24c91 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java
@@ -1736,6 +1736,11 @@ public class OlapScanNode extends ScanNode {
return true;
}
+
+ @Override
+ public int getScanRangeNum() {
+ return getScanTabletIds().size();
+ }
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/planner/ScanNode.java b/fe/fe-core/src/main/java/org/apache/doris/planner/ScanNode.java
index 7ddf2ae1d4c..9881fe6f6e3 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/ScanNode.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/ScanNode.java
@@ -725,8 +725,11 @@ public abstract class ScanNode extends PlanNode {
&& context.getSessionVariable().isIgnoreStorageDataDistribution()
&& context.getSessionVariable().getEnablePipelineXEngine()
&& !fragment.isHasNullAwareLeftAntiJoin()
- && ((this instanceof OlapScanNode) && ((OlapScanNode) this).getScanTabletIds().size()
- < ConnectContext.get().getSessionVariable().getParallelExecInstanceNum());
+ && getScanRangeNum() < ConnectContext.get().getSessionVariable().getParallelExecInstanceNum();
+ }
+
+ public int getScanRangeNum() {
+ return Integer.MAX_VALUE;
}
public boolean haveLimitAndConjunts() {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/planner/external/FileQueryScanNode.java b/fe/fe-core/src/main/java/org/apache/doris/planner/external/FileQueryScanNode.java
index 71c731498a6..4a3c3d2ff9a 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/external/FileQueryScanNode.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/external/FileQueryScanNode.java
@@ -485,6 +485,18 @@ public abstract class FileQueryScanNode extends FileScanNode {
params.setSlotNameToSchemaPos(columnNameToPosition);
}
+ @Override
+ public int getScanRangeNum() {
+ Preconditions.checkNotNull(scanRangeLocations);
+ int i = 0;
+ for (TScanRangeLocations tScanRangeLocations : scanRangeLocations) {
+ TScanRange tScanRange = tScanRangeLocations.getScanRange();
+ TFileScanRange tFileScanRange = tScanRange.getExtScanRange().getFileScanRange();
+ i += tFileScanRange.getRangesSize();
+ }
+ return i;
+ }
+
protected abstract TFileType getLocationType() throws UserException;
protected abstract TFileType getLocationType(String location) throws UserException;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 24/43: [docs](ip function) add ipv4/v6 datatype and some ip functions' docs (#30194)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit cd0ca2b3af0c531cfa28c6e623b169cbbc3f2a6c
Author: yangshijie <sj...@zju.edu.cn>
AuthorDate: Mon Jan 22 13:25:28 2024 +0800
[docs](ip function) add ipv4/v6 datatype and some ip functions' docs (#30194)
---
.../ip-functions/ipv4-cidr-to-range.md | 72 ++++++++++++++++++
.../ip-functions/ipv6-cidr-to-range.md | 72 ++++++++++++++++++
.../ip-functions/is-ip-address-in-range.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/is-ipv4-string.md | 80 ++++++++++++++++++++
.../sql-functions/ip-functions/is-ipv6-string.md | 80 ++++++++++++++++++++
.../ip-functions/to-ipv4-or-default.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv4-or-null.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv4.md | 60 +++++++++++++++
.../ip-functions/to-ipv6-or-default.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv6-or-null.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv6.md | 60 +++++++++++++++
.../sql-manual/sql-reference/Data-Types/IPV4.md | 85 ++++++++++++++++++++++
.../sql-manual/sql-reference/Data-Types/IPV6.md | 83 +++++++++++++++++++++
.../sql-manual/sql-reference/Data-Types/STRUCT.md | 2 +-
docs/sidebars.json | 17 ++++-
.../ip-functions/ipv4-cidr-to-range.md | 72 ++++++++++++++++++
.../ip-functions/ipv6-cidr-to-range.md | 72 ++++++++++++++++++
.../ip-functions/is-ip-address-in-range.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/is-ipv4-string.md | 80 ++++++++++++++++++++
.../sql-functions/ip-functions/is-ipv6-string.md | 80 ++++++++++++++++++++
.../ip-functions/to-ipv4-or-default.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv4-or-null.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv4.md | 60 +++++++++++++++
.../ip-functions/to-ipv6-or-default.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv6-or-null.md | 65 +++++++++++++++++
.../sql-functions/ip-functions/to-ipv6.md | 60 +++++++++++++++
.../sql-manual/sql-reference/Data-Types/IPV4.md | 85 ++++++++++++++++++++++
.../sql-manual/sql-reference/Data-Types/IPV6.md | 83 +++++++++++++++++++++
28 files changed, 1850 insertions(+), 3 deletions(-)
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md
new file mode 100644
index 00000000000..f5367a577f0
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md
@@ -0,0 +1,72 @@
+---
+{
+"title": "IPV4_CIDR_TO_RANGE",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV4_CIDR_TO_RANGE
+
+<version since="dev">
+
+IPV4_CIDR_TO_RANGE
+
+</version>
+
+### description
+
+#### Syntax
+
+`STRUCT<IPV4, IPV4> IPV4_CIDR_TO_RANGE(IPV4 ip_v4, INT16 cidr)`
+
+Receive an IPv4 and an Int16 value containing CIDR. Returns a struct that contains two IPv4 fields representing the lower range (min) and higher range (max) of the subnet, respectively.
+
+### notice
+
+`If the input parameter is NULL, return NULL, indicating invalid input`
+
+### example
+
+```
+mysql> SELECT ipv4_cidr_to_range(ipv4_string_to_num('192.168.5.2'), 16);
++-----------------------------------------------------------+
+| ipv4_cidr_to_range(ipv4_string_to_num('192.168.5.2'), 16) |
++-----------------------------------------------------------+
+| {"min": "192.168.0.0", "max": "192.168.255.255"} |
++-----------------------------------------------------------+
+
+mysql> SELECT ipv4_cidr_to_range(to_ipv4('192.168.5.2'), 16);
++--------------------------------------------------+
+| ipv4_cidr_to_range(to_ipv4('192.168.5.2'), 16) |
++--------------------------------------------------+
+| {"min": "192.168.0.0", "max": "192.168.255.255"} |
++--------------------------------------------------+
+
+mysql> SELECT ipv4_cidr_to_range(NULL, NULL);
++--------------------------------+
+| ipv4_cidr_to_range(NULL, NULL) |
++--------------------------------+
+| NULL |
++--------------------------------+
+```
+
+### keywords
+
+IPV4_CIDR_TO_RANGE, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md
new file mode 100644
index 00000000000..bf5c74c167d
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md
@@ -0,0 +1,72 @@
+---
+{
+"title": "IPV6_CIDR_TO_RANGE",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV6_CIDR_TO_RANGE
+
+<version since="dev">
+
+IPV6_CIDR_TO_RANGE
+
+</version>
+
+### description
+
+#### Syntax
+
+`STRUCT<IPV6, IPV6> IPV6_CIDR_TO_RANGE(IPV6 ip_v6, INT16 cidr)`
+
+Receive an IPv6 and an Int16 value containing CIDR. Returns a struct that contains two IPv6 fields representing the lower range (min) and higher range (max) of the subnet, respectively.
+
+### notice
+
+`If the input parameter is NULL, return NULL, indicating invalid input`
+
+### example
+
+```
+mysql> SELECT ipv6_cidr_to_range(ipv6_string_to_num('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32);
++---------------------------------------------------------------------------------------+
+| ipv6_cidr_to_range(ipv6_string_to_num('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32) |
++---------------------------------------------------------------------------------------+
+| {"min": "2001:db8::", "max": "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff"} |
++---------------------------------------------------------------------------------------+
+
+mysql> SELECT ipv6_cidr_to_range(to_ipv6('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32);
++----------------------------------------------------------------------------+
+| ipv6_cidr_to_range(to_ipv6('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32) |
++----------------------------------------------------------------------------+
+| {"min": "2001:db8::", "max": "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff"} |
++----------------------------------------------------------------------------+
+
+mysql> SELECT ipv6_cidr_to_range(NULL, NULL);
++--------------------------------+
+| ipv6_cidr_to_range(NULL, NULL) |
++--------------------------------+
+| NULL |
++--------------------------------+
+```
+
+### keywords
+
+IPV6_CIDR_TO_RANGE, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md
new file mode 100644
index 00000000000..7a47537f855
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "IS_IP_ADDRESS_IN_RANGE",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IP_ADDRESS_IN_RANGE
+
+<version since="dev">
+
+IS_IP_ADDRESS_IN_RANGE
+
+</version>
+
+### description
+
+#### Syntax
+
+`BOOLEAN IS_IP_ADDRESS_IN_RANGE(STRING ip_str, STRING cidr_prefix)`
+
+Determine whether the IP (IPv4 or IPv6) address is included in the network represented by CIDR notation. If yes, return true; otherwise, return false.
+
+### notice
+
+`ip_str and cidr_prefix both cannot be NULL`
+
+### example
+
+```
+mysql> SELECT is_ip_address_in_range('127.0.0.1', '127.0.0.0/8');
++----------------------------------------------------+
+| is_ip_address_in_range('127.0.0.1', '127.0.0.0/8') |
++----------------------------------------------------+
+| 1 |
++----------------------------------------------------+
+
+mysql> SELECT is_ip_address_in_range('::ffff:192.168.0.1', '::ffff:192.168.0.4/128');
++------------------------------------------------------------------------+
+| is_ip_address_in_range('::ffff:192.168.0.1', '::ffff:192.168.0.4/128') |
++------------------------------------------------------------------------+
+| 0 |
++------------------------------------------------------------------------+
+```
+
+### keywords
+
+IS_IP_ADDRESS_IN_RANGE, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md
new file mode 100644
index 00000000000..9aca93afc0a
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md
@@ -0,0 +1,80 @@
+---
+{
+"title": "IS_IPV4_STRING",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV4_STRING
+
+<version since="dev">
+
+IS_IPV4_STRING
+
+</version>
+
+### description
+
+#### Syntax
+
+`BOOLEAN IS_IPV4_STRING(STRING ipv4_str)`
+
+Receive an IPv4 address in the form of a string as a parameter. If it is a correctly formatted and valid IPv4 address, return true; On the contrary, return false.
+
+### notice
+
+`If the input parameter is NULL, return NULL, indicating invalid input`
+
+### example
+
+```
+mysql> select is_ipv4_string(NULL);
++----------------------+
+| is_ipv4_string(NULL) |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> CREATE TABLE `test_is_ipv4_string` (
+ `id` int,
+ `ip_v4` string
+ ) ENGINE=OLAP
+ DISTRIBUTED BY HASH(`id`) BUCKETS 4
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1"
+ );
+
+mysql> insert into test_is_ipv4_string values(0, NULL), (1, '0.0.0.'), (2, ''), (3, '.'), (4, '255.255.255.255');
+
+mysql> select id, is_ipv4_string(ip_v4) from test_is_ipv4_string order by id;
++------+-----------------------+
+| id | is_ipv4_string(ip_v4) |
++------+-----------------------+
+| 0 | NULL |
+| 1 | 0 |
+| 2 | 0 |
+| 3 | 0 |
+| 4 | 1 |
++------+-----------------------+
+```
+
+### keywords
+
+IS_IPV4_STRING, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md
new file mode 100644
index 00000000000..6f3731e2618
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md
@@ -0,0 +1,80 @@
+---
+{
+"title": "IS_IPV6_STRING",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV6_STRING
+
+<version since="dev">
+
+IS_IPV6_STRING
+
+</version>
+
+### description
+
+#### Syntax
+
+`BOOLEAN IS_IPV6_STRING(STRING ipv6_str)`
+
+Receive an IPv6 address in the form of a string as a parameter, and return true if it is a properly formatted and valid IPv6 address; On the contrary, return false.
+
+### notice
+
+`If the input parameter is NULL, return NULL, indicating invalid input`
+
+### example
+
+```
+mysql> select is_ipv6_string(NULL);
++----------------------+
+| is_ipv6_string(NULL) |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> CREATE TABLE `test_is_ipv6_string` (
+ `id` int,
+ `ip_v6` string
+ ) ENGINE=OLAP
+ DISTRIBUTED BY HASH(`id`) BUCKETS 4
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1"
+ );
+
+mysql> insert into test_is_ipv6_string values(0, NULL), (1, '::'), (2, ''), (3, '2001:1b70:a1:610::b102:2'), (4, 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffffg');
+
+mysql> select id, is_ipv6_string(ip_v6) from test_is_ipv6_string order by id;
++------+-----------------------+
+| id | is_ipv6_string(ip_v6) |
++------+-----------------------+
+| 0 | NULL |
+| 1 | 1 |
+| 2 | 0 |
+| 3 | 1 |
+| 4 | 0 |
++------+-----------------------+
+```
+
+### keywords
+
+IS_IPV6_STRING, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-default.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-default.md
new file mode 100644
index 00000000000..d5770906b88
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-default.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV4_OR_DEFAULT",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV4_OR_DEFAULT
+
+<version since="dev">
+
+TO_IPV4_OR_DEFAULT
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV4 TO_IPV4_OR_DEFAULT(STRING ipv4_str)`
+
+Same as to_ipv4, but if the IPv4 address has an invalid format, it returns 0.0.0.0 (0 as IPv4).
+
+### notice
+
+`If input is NULL, return 0.0.0.0 (0 as IPv4).`
+
+### example
+
+```
+mysql> select to_ipv4_or_default('.');
++-------------------------+
+| to_ipv4_or_default('.') |
++-------------------------+
+| 0.0.0.0 |
++-------------------------+
+
+mysql> select to_ipv4_or_default(NULL);
++--------------------------+
+| to_ipv4_or_default(NULL) |
++--------------------------+
+| 0.0.0.0 |
++--------------------------+
+```
+
+### keywords
+
+TO_IPV4_OR_DEFAULT, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-null.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-null.md
new file mode 100644
index 00000000000..35377b233a7
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-null.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV4_OR_NULL",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV4_OR_NULL
+
+<version since="dev">
+
+TO_IPV4_OR_NULL
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV4 TO_IPV4_OR_NULL(STRING ipv4_str)`
+
+Same as to_ipv4, but if the IPv4 address has an invalid format, it returns NULL.
+
+### notice
+
+`If input is NULL, return NULL.`
+
+### example
+
+```
+mysql> select to_ipv4_or_null('.');
++----------------------+
+| to_ipv4_or_null('.') |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> select to_ipv4_or_null(NULL);
++-----------------------+
+| to_ipv4_or_null(NULL) |
++-----------------------+
+| NULL |
++-----------------------+
+```
+
+### keywords
+
+TO_IPV4_OR_NULL, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4.md
new file mode 100644
index 00000000000..24747ae0ed0
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv4.md
@@ -0,0 +1,60 @@
+---
+{
+"title": "TO_IPV4",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV4
+
+<version since="dev">
+
+TO_IPV4
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV4 TO_IPV4(STRING ipv4_str)`
+
+This function like ipv4_string_to_num that takes a string form of IPv4 address and returns value of IPv4 type,
+which is binary equal to value returned by ipv4_string_to_num.
+If the IPv4 address has an invalid format, throw an exception.
+
+### notice
+
+`Input cannot be NULL. If it is NULL, an exception will be thrown.`
+
+### example
+
+```
+mysql> select to_ipv4('255.255.255.255');
++----------------------------+
+| to_ipv4('255.255.255.255') |
++----------------------------+
+| 255.255.255.255 |
++----------------------------+
+```
+
+### keywords
+
+TO_IPV4, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-default.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-default.md
new file mode 100644
index 00000000000..c0cc118e9bb
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-default.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV6_OR_DEFAULT",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV6_OR_DEFAULT
+
+<version since="dev">
+
+TO_IPV6_OR_DEFAULT
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV6 TO_IPV6_OR_DEFAULT(STRING ipv6_str)`
+
+Same as to_ipv6, but if the IPv6 address has an invalid format, it returns :: (0 as IPv6).
+
+### notice
+
+`If input is NULL, return :: (0 as IPv6).`
+
+### example
+
+```
+mysql> select to_ipv6_or_default('.');
++-------------------------+
+| to_ipv6_or_default('.') |
++-------------------------+
+| :: |
++-------------------------+
+
+mysql> select to_ipv6_or_default(NULL);
++--------------------------+
+| to_ipv6_or_default(NULL) |
++--------------------------+
+| :: |
++--------------------------+
+```
+
+### keywords
+
+TO_IPV6_OR_DEFAULT, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-null.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-null.md
new file mode 100644
index 00000000000..863cb383973
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-null.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV6_OR_NULL",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV6_OR_NULL
+
+<version since="dev">
+
+TO_IPV6_OR_NULL
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV6 TO_IPV6_OR_NULL(STRING ipv6_str)`
+
+Same as to_ipv6, but if the IPv6 address has an invalid format, it returns NULL.
+
+### notice
+
+`If input is NULL, return NULL.`
+
+### example
+
+```
+mysql> select to_ipv6_or_null('.');
++----------------------+
+| to_ipv6_or_null('.') |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> select to_ipv6_or_null(NULL);
++-----------------------+
+| to_ipv6_or_null(NULL) |
++-----------------------+
+| NULL |
++-----------------------+
+```
+
+### keywords
+
+TO_IPV6_OR_NULL, IP
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6.md
new file mode 100644
index 00000000000..aad7d42b94f
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/to-ipv6.md
@@ -0,0 +1,60 @@
+---
+{
+"title": "TO_IPV6",
+"language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV6
+
+<version since="dev">
+
+TO_IPV6
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV6 TO_IPV6(STRING ipv6_str)`
+
+Convert a string form of IPv6 address to IPv6 type.
+If the IPv6 address has an invalid format, throw an exception.
+Similar to ipv6_string_to_num function, which converts IPv6 address to binary format.
+
+### notice
+
+`Input cannot be NULL. If it is NULL, an exception will be thrown.`
+
+### example
+
+```
+mysql> select to_ipv6('::');
++---------------+
+| to_ipv6('::') |
++---------------+
+| :: |
++---------------+
+```
+
+### keywords
+
+TO_IPV6, IP
diff --git a/docs/en/docs/sql-manual/sql-reference/Data-Types/IPV4.md b/docs/en/docs/sql-manual/sql-reference/Data-Types/IPV4.md
new file mode 100644
index 00000000000..07ab836e4eb
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-reference/Data-Types/IPV4.md
@@ -0,0 +1,85 @@
+---
+{
+ "title": "IPV4",
+ "language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV4
+
+<version since="dev">
+
+IPV4
+
+</version>
+
+### description
+
+IPV4
+IPv4 type, stored in the form of UInt32 in 4 bytes, used to represent IPv4 addresses.
+The range of values is ['0.0.0.0', '255.255.255.255'].
+
+`Inputs that exceed the value range or have invalid format will return NULL`
+
+### example
+
+Create table example:
+
+```
+CREATE TABLE ipv4_test (
+ `id` int,
+ `ip_v4` ipv4
+) ENGINE=OLAP
+DISTRIBUTED BY HASH(`id`) BUCKETS 4
+PROPERTIES (
+"replication_allocation" = "tag.location.default: 1"
+);
+```
+
+Insert data example:
+
+```
+insert into ipv4_test values(1, '0.0.0.0');
+insert into ipv4_test values(2, '127.0.0.1');
+insert into ipv4_test values(3, '59.50.185.152');
+insert into ipv4_test values(4, '255.255.255.255');
+insert into ipv4_test values(5, '255.255.255.256'); // invalid data
+```
+
+Select data example:
+
+```
+mysql> select * from ipv4_test order by id;
++------+-----------------+
+| id | ip_v4 |
++------+-----------------+
+| 1 | 0.0.0.0 |
+| 2 | 127.0.0.1 |
+| 3 | 59.50.185.152 |
+| 4 | 255.255.255.255 |
+| 5 | NULL |
++------+-----------------+
+```
+
+### keywords
+
+IPV4
diff --git a/docs/en/docs/sql-manual/sql-reference/Data-Types/IPV6.md b/docs/en/docs/sql-manual/sql-reference/Data-Types/IPV6.md
new file mode 100644
index 00000000000..dcf46813240
--- /dev/null
+++ b/docs/en/docs/sql-manual/sql-reference/Data-Types/IPV6.md
@@ -0,0 +1,83 @@
+---
+{
+ "title": "IPV6",
+ "language": "en"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV6
+
+<version since="dev">
+
+IPV6
+
+</version>
+
+### description
+
+IPV6
+IPv6 type, stored in Int128 format in 16 bytes, used to represent IPv6 addresses.
+The range of values is ['::', 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'].
+
+`Inputs that exceed the value range or have invalid format will return NULL`
+
+### example
+
+Create table example:
+
+```
+CREATE TABLE ipv6_test (
+ `id` int,
+ `ip_v6` ipv6
+) ENGINE=OLAP
+DISTRIBUTED BY HASH(`id`) BUCKETS 4
+PROPERTIES (
+"replication_allocation" = "tag.location.default: 1"
+);
+```
+
+Insert data example:
+
+```
+insert into ipv6_test values(1, '::');
+insert into ipv6_test values(2, '2001:16a0:2:200a::2');
+insert into ipv6_test values(3, 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff');
+insert into ipv6_test values(4, 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffffg'); // invalid data
+```
+
+Select data example:
+
+```
+mysql> select * from ipv6_test order by id;
++------+-----------------------------------------+
+| id | ip_v6 |
++------+-----------------------------------------+
+| 1 | :: |
+| 2 | 2001:16a0:2:200a::2 |
+| 3 | ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff |
+| 4 | NULL |
++------+-----------------------------------------+
+```
+
+### keywords
+
+IPV6
diff --git a/docs/en/docs/sql-manual/sql-reference/Data-Types/STRUCT.md b/docs/en/docs/sql-manual/sql-reference/Data-Types/STRUCT.md
index abab4148889..ba0faaf6375 100644
--- a/docs/en/docs/sql-manual/sql-reference/Data-Types/STRUCT.md
+++ b/docs/en/docs/sql-manual/sql-reference/Data-Types/STRUCT.md
@@ -62,7 +62,7 @@ DATEV2, DATETIME, DATETIMEV2, CHAR, VARCHAR, STRING
We have a todo list for future version:
```
-TODO:支持嵌套 STRUCT 或其他的复杂类型
+TODO: Supports nested Struct or other complex types
```
### example
diff --git a/docs/sidebars.json b/docs/sidebars.json
index bda6b8da310..cc8e5cfe39d 100644
--- a/docs/sidebars.json
+++ b/docs/sidebars.json
@@ -816,7 +816,18 @@
"sql-manual/sql-functions/ip-functions/ipv6-string-to-num-or-default",
"sql-manual/sql-functions/ip-functions/ipv6-string-to-num-or-null",
"sql-manual/sql-functions/ip-functions/is-ipv4-compat",
- "sql-manual/sql-functions/ip-functions/is-ipv4-mapped"
+ "sql-manual/sql-functions/ip-functions/is-ipv4-mapped",
+ "sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range",
+ "sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range",
+ "sql-manual/sql-functions/ip-functions/is-ip-address-in-range",
+ "sql-manual/sql-functions/ip-functions/is-ipv4-string",
+ "sql-manual/sql-functions/ip-functions/is-ipv6-string",
+ "sql-manual/sql-functions/ip-functions/to-ipv4",
+ "sql-manual/sql-functions/ip-functions/to-ipv4-or-default",
+ "sql-manual/sql-functions/ip-functions/to-ipv4-or-null",
+ "sql-manual/sql-functions/ip-functions/to-ipv6",
+ "sql-manual/sql-functions/ip-functions/to-ipv6-or-default",
+ "sql-manual/sql-functions/ip-functions/to-ipv6-or-null"
]
},
{
@@ -926,7 +937,9 @@
"sql-manual/sql-reference/Data-Types/STRUCT",
"sql-manual/sql-reference/Data-Types/JSON",
"sql-manual/sql-reference/Data-Types/AGG_STATE",
- "sql-manual/sql-reference/Data-Types/VARIANT"
+ "sql-manual/sql-reference/Data-Types/VARIANT",
+ "sql-manual/sql-reference/Data-Types/IPV4",
+ "sql-manual/sql-reference/Data-Types/IPV6"
]
},
{
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md
new file mode 100644
index 00000000000..ca1803db630
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv4-cidr-to-range.md
@@ -0,0 +1,72 @@
+---
+{
+"title": "IPV4_CIDR_TO_RANGE",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV4_CIDR_TO_RANGE
+
+<version since="dev">
+
+IPV4_CIDR_TO_RANGE
+
+</version>
+
+### description
+
+#### Syntax
+
+`STRUCT<IPV4, IPV4> IPV4_CIDR_TO_RANGE(IPV4 ip_v4, INT16 cidr)`
+
+接收一个IPv4和一个包含CIDR的Int16值。返回一个结构体,其中包含两个IPv4字段分别表示子网的较低范围(min)和较高范围(max)。
+
+### notice
+
+`如果入参为NULL,则返回NULL,表示无效输入`
+
+### example
+
+```
+mysql> SELECT ipv4_cidr_to_range(ipv4_string_to_num('192.168.5.2'), 16);
++------------------------------------------------------------+
+| ipv4_cidr_to_range(ipv4_string_to_num('192.168.5.2'), 16) |
++------------------------------------------------------------+
+| {"min": "192.168.0.0", "max": "192.168.255.255"} |
++------------------------------------------------------------+
+
+mysql> SELECT ipv4_cidr_to_range(to_ipv4('192.168.5.2'), 16);
++--------------------------------------------------+
+| ipv4_cidr_to_range(to_ipv4('192.168.5.2'), 16) |
++--------------------------------------------------+
+| {"min": "192.168.0.0", "max": "192.168.255.255"} |
++--------------------------------------------------+
+
+mysql> SELECT ipv4_cidr_to_range(NULL, NULL);
++--------------------------------+
+| ipv4_cidr_to_range(NULL, NULL) |
++--------------------------------+
+| NULL |
++--------------------------------+
+```
+
+### keywords
+
+IPV4_CIDR_TO_RANGE, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md
new file mode 100644
index 00000000000..a88fa5651e1
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/ipv6-cidr-to-range.md
@@ -0,0 +1,72 @@
+---
+{
+"title": "IPV6_CIDR_TO_RANGE",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV6_CIDR_TO_RANGE
+
+<version since="dev">
+
+IPV6_CIDR_TO_RANGE
+
+</version>
+
+### description
+
+#### Syntax
+
+`STRUCT<IPV6, IPV6> IPV6_CIDR_TO_RANGE(IPV6 ip_v6, INT16 cidr)`
+
+接收一个IPv6和一个包含CIDR的Int16值。返回一个结构体,其中包含两个IPv6字段分别表示子网的较低范围(min)和较高范围(max)。
+
+### notice
+
+`如果入参为NULL,则返回NULL,表示无效输入`
+
+### example
+
+```
+mysql> SELECT ipv6_cidr_to_range(ipv6_string_to_num('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32);
++---------------------------------------------------------------------------------------+
+| ipv6_cidr_to_range(ipv6_string_to_num('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32) |
++---------------------------------------------------------------------------------------+
+| {"min": "2001:db8::", "max": "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff"} |
++---------------------------------------------------------------------------------------+
+
+mysql> SELECT ipv6_cidr_to_range(to_ipv6('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32);
++----------------------------------------------------------------------------+
+| ipv6_cidr_to_range(to_ipv6('2001:0db8:0000:85a3:0000:0000:ac1f:8001'), 32) |
++----------------------------------------------------------------------------+
+| {"min": "2001:db8::", "max": "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff"} |
++----------------------------------------------------------------------------+
+
+mysql> SELECT ipv6_cidr_to_range(NULL, NULL);
++--------------------------------+
+| ipv6_cidr_to_range(NULL, NULL) |
++--------------------------------+
+| NULL |
++--------------------------------+
+```
+
+### keywords
+
+IPV6_CIDR_TO_RANGE, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md
new file mode 100644
index 00000000000..16c8d31a9b3
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ip-address-in-range.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "IS_IP_ADDRESS_IN_RANGE",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IP_ADDRESS_IN_RANGE
+
+<version since="dev">
+
+IS_IP_ADDRESS_IN_RANGE
+
+</version>
+
+### description
+
+#### Syntax
+
+`BOOLEAN IS_IP_ADDRESS_IN_RANGE(STRING ip_str, STRING cidr_prefix)`
+
+判断IP(IPv4或IPv6)地址是否包含在以CIDR表示法表示的网络中。如果是,则返回true,否则返回false。
+
+### notice
+
+`入参ip_str和cidr_prefix均不能为NULL`
+
+### example
+
+```
+mysql> SELECT is_ip_address_in_range('127.0.0.1', '127.0.0.0/8');
++----------------------------------------------------+
+| is_ip_address_in_range('127.0.0.1', '127.0.0.0/8') |
++----------------------------------------------------+
+| 1 |
++----------------------------------------------------+
+
+mysql> SELECT is_ip_address_in_range('::ffff:192.168.0.1', '::ffff:192.168.0.4/128');
++------------------------------------------------------------------------+
+| is_ip_address_in_range('::ffff:192.168.0.1', '::ffff:192.168.0.4/128') |
++------------------------------------------------------------------------+
+| 0 |
++------------------------------------------------------------------------+
+```
+
+### keywords
+
+IS_IP_ADDRESS_IN_RANGE, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md
new file mode 100644
index 00000000000..8cd691ab878
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv4-string.md
@@ -0,0 +1,80 @@
+---
+{
+"title": "IS_IPV4_STRING",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV4_STRING
+
+<version since="dev">
+
+IS_IPV4_STRING
+
+</version>
+
+### description
+
+#### Syntax
+
+`BOOLEAN IS_IPV4_STRING(STRING ipv4_str)`
+
+接收一个表示形式为字符串的IPv4地址作为参数,如果为格式正确且合法的IPv4地址,返回true;反之,返回false。
+
+### notice
+
+`如果入参为NULL,则返回NULL,表示无效输入`
+
+### example
+
+```
+mysql> select is_ipv4_string(NULL);
++----------------------+
+| is_ipv4_string(NULL) |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> CREATE TABLE `test_is_ipv4_string` (
+ `id` int,
+ `ip_v4` string
+ ) ENGINE=OLAP
+ DISTRIBUTED BY HASH(`id`) BUCKETS 4
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1"
+ );
+
+mysql> insert into test_is_ipv4_string values(0, NULL), (1, '0.0.0.'), (2, ''), (3, '.'), (4, '255.255.255.255');
+
+mysql> select id, is_ipv4_string(ip_v4) from test_is_ipv4_string order by id;
++------+-----------------------+
+| id | is_ipv4_string(ip_v4) |
++------+-----------------------+
+| 0 | NULL |
+| 1 | 0 |
+| 2 | 0 |
+| 3 | 0 |
+| 4 | 1 |
++------+-----------------------+
+```
+
+### keywords
+
+IS_IPV4_STRING, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md
new file mode 100644
index 00000000000..5aa9ca6087e
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/is-ipv6-string.md
@@ -0,0 +1,80 @@
+---
+{
+"title": "IS_IPV6_STRING",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IS_IPV6_STRING
+
+<version since="dev">
+
+IS_IPV6_STRING
+
+</version>
+
+### description
+
+#### Syntax
+
+`BOOLEAN IS_IPV6_STRING(STRING ipv6_str)`
+
+接收一个表示形式为字符串的IPv6地址作为参数,如果为格式正确且合法的IPv6地址,返回true;反之,返回false。
+
+### notice
+
+`如果入参为NULL,则返回NULL,表示无效输入`
+
+### example
+
+```
+mysql> select is_ipv6_string(NULL);
++----------------------+
+| is_ipv6_string(NULL) |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> CREATE TABLE `test_is_ipv6_string` (
+ `id` int,
+ `ip_v6` string
+ ) ENGINE=OLAP
+ DISTRIBUTED BY HASH(`id`) BUCKETS 4
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1"
+ );
+
+mysql> insert into test_is_ipv6_string values(0, NULL), (1, '::'), (2, ''), (3, '2001:1b70:a1:610::b102:2'), (4, 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffffg');
+
+mysql> select id, is_ipv6_string(ip_v6) from test_is_ipv6_string order by id;
++------+-----------------------+
+| id | is_ipv6_string(ip_v6) |
++------+-----------------------+
+| 0 | NULL |
+| 1 | 1 |
+| 2 | 0 |
+| 3 | 1 |
+| 4 | 0 |
++------+-----------------------+
+```
+
+### keywords
+
+IS_IPV6_STRING, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-default.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-default.md
new file mode 100644
index 00000000000..f33cf4ea61a
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-default.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV4_OR_DEFAULT",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV4_OR_DEFAULT
+
+<version since="dev">
+
+TO_IPV4_OR_DEFAULT
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV4 TO_IPV4_OR_DEFAULT(STRING ipv4_str)`
+
+与to_ipv4函数类似,但如果IPv4地址的格式非法,则返回0.0.0.0。
+
+### notice
+
+`入参ipv4_str如果为NULL,则返回0.0.0.0。`
+
+### example
+
+```
+mysql> select to_ipv4_or_default('.');
++-------------------------+
+| to_ipv4_or_default('.') |
++-------------------------+
+| 0.0.0.0 |
++-------------------------+
+
+mysql> select to_ipv4_or_default(NULL);
++--------------------------+
+| to_ipv4_or_default(NULL) |
++--------------------------+
+| 0.0.0.0 |
++--------------------------+
+```
+
+### keywords
+
+TO_IPV4_OR_DEFAULT, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-null.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-null.md
new file mode 100644
index 00000000000..9ffa174e0bb
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4-or-null.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV4_OR_NULL",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV4_OR_NULL
+
+<version since="dev">
+
+TO_IPV4_OR_NULL
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV4 TO_IPV4_OR_NULL(STRING ipv4_str)`
+
+与to_ipv4函数类似,但如果IPv4地址的格式非法,则返回NULL。
+
+### notice
+
+`入参ipv4_str如果为NULL,则返回NULL。`
+
+### example
+
+```
+mysql> select to_ipv4_or_null('.');
++----------------------+
+| to_ipv4_or_null('.') |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> select to_ipv4_or_null(NULL);
++-----------------------+
+| to_ipv4_or_null(NULL) |
++-----------------------+
+| NULL |
++-----------------------+
+```
+
+### keywords
+
+TO_IPV4_OR_NULL, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4.md
new file mode 100644
index 00000000000..f484da2905c
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv4.md
@@ -0,0 +1,60 @@
+---
+{
+"title": "TO_IPV4",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV4
+
+<version since="dev">
+
+TO_IPV4
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV4 TO_IPV4(STRING ipv4_str)`
+
+该函数类似ipv4_string_to_num,输入IPv4地址的字符串形式,并返回IPv4类型的值。
+该值的二进制形式等于ipv4_string_to_num函数返回值的二进制形式。
+如果IPv4地址为非法格式,则抛出异常。
+
+### notice
+
+`入参ipv4_str不能为NULL,若为NULL,则抛出异常。`
+
+### example
+
+```
+mysql> select to_ipv4('255.255.255.255');
++----------------------------+
+| to_ipv4('255.255.255.255') |
++----------------------------+
+| 255.255.255.255 |
++----------------------------+
+```
+
+### keywords
+
+TO_IPV4, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-default.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-default.md
new file mode 100644
index 00000000000..679fbf1e85b
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-default.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV6_OR_DEFAULT",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV6_OR_DEFAULT
+
+<version since="dev">
+
+TO_IPV6_OR_DEFAULT
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV6 TO_IPV6_OR_DEFAULT(STRING ipv6_str)`
+
+与to_ipv6函数类似,但如果IPv6地址的格式非法,则返回::。
+
+### notice
+
+`入参ipv6_str如果为NULL,则返回::。`
+
+### example
+
+```
+mysql> select to_ipv6_or_default('.');
++-------------------------+
+| to_ipv6_or_default('.') |
++-------------------------+
+| :: |
++-------------------------+
+
+mysql> select to_ipv6_or_default(NULL);
++--------------------------+
+| to_ipv6_or_default(NULL) |
++--------------------------+
+| :: |
++--------------------------+
+```
+
+### keywords
+
+TO_IPV6_OR_DEFAULT, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-null.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-null.md
new file mode 100644
index 00000000000..f09fd1cf691
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6-or-null.md
@@ -0,0 +1,65 @@
+---
+{
+"title": "TO_IPV6_OR_NULL",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV6_OR_NULL
+
+<version since="dev">
+
+TO_IPV6_OR_NULL
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV6 TO_IPV6_OR_NULL(STRING ipv6_str)`
+
+与to_ipv6函数类似,但如果IPv6地址的格式非法,则返回NULL。
+
+### notice
+
+`入参ipv6_str如果为NULL,则返回NULL。`
+
+### example
+
+```
+mysql> select to_ipv6_or_null('.');
++----------------------+
+| to_ipv6_or_null('.') |
++----------------------+
+| NULL |
++----------------------+
+
+mysql> select to_ipv6_or_null(NULL);
++-----------------------+
+| to_ipv6_or_null(NULL) |
++-----------------------+
+| NULL |
++-----------------------+
+```
+
+### keywords
+
+TO_IPV6_OR_NULL, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6.md
new file mode 100644
index 00000000000..ac7297204d2
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/to-ipv6.md
@@ -0,0 +1,60 @@
+---
+{
+"title": "TO_IPV6",
+"language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## TO_IPV6
+
+<version since="dev">
+
+TO_IPV6
+
+</version>
+
+### description
+
+#### Syntax
+
+`IPV6 TO_IPV6(STRING ipv6_str)`
+
+该函数类似ipv6_string_to_num,输入IPv6地址的字符串形式,并返回IPv6类型的值。
+该值的二进制形式等于ipv6_string_to_num函数返回值的二进制形式。
+如果IPv6地址为非法格式,则抛出异常。
+
+### notice
+
+`入参ipv6_str不能为NULL,若为NULL,则抛出异常。`
+
+### example
+
+```
+mysql> select to_ipv6('::');
++---------------+
+| to_ipv6('::') |
++---------------+
+| :: |
++---------------+
+```
+
+### keywords
+
+TO_IPV6, IP
diff --git a/docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV4.md b/docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV4.md
new file mode 100644
index 00000000000..2766a20580e
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV4.md
@@ -0,0 +1,85 @@
+---
+{
+ "title": "IPV4",
+ "language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV4
+
+<version since="dev">
+
+IPV4
+
+</version>
+
+### description
+
+IPV4
+IPv4类型,以UInt32的形式存储在4个字节中,用于表示IPv4地址。
+取值范围是 ['0.0.0.0', '255.255.255.255']。
+
+`超出取值范围或者格式非法的输入将返回NULL`
+
+### example
+
+建表示例如下:
+
+```
+CREATE TABLE ipv4_test (
+ `id` int,
+ `ip_v4` ipv4
+) ENGINE=OLAP
+DISTRIBUTED BY HASH(`id`) BUCKETS 4
+PROPERTIES (
+"replication_allocation" = "tag.location.default: 1"
+);
+```
+
+插入数据示例:
+
+```
+insert into ipv4_test values(1, '0.0.0.0');
+insert into ipv4_test values(2, '127.0.0.1');
+insert into ipv4_test values(3, '59.50.185.152');
+insert into ipv4_test values(4, '255.255.255.255');
+insert into ipv4_test values(5, '255.255.255.256'); // invalid data
+```
+
+查询数据示例:
+
+```
+mysql> select * from ipv4_test order by id;
++------+-----------------+
+| id | ip_v4 |
++------+-----------------+
+| 1 | 0.0.0.0 |
+| 2 | 127.0.0.1 |
+| 3 | 59.50.185.152 |
+| 4 | 255.255.255.255 |
+| 5 | NULL |
++------+-----------------+
+```
+
+### keywords
+
+IPV4
diff --git a/docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV6.md b/docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV6.md
new file mode 100644
index 00000000000..678b404a672
--- /dev/null
+++ b/docs/zh-CN/docs/sql-manual/sql-reference/Data-Types/IPV6.md
@@ -0,0 +1,83 @@
+---
+{
+ "title": "IPV6",
+ "language": "zh-CN"
+}
+---
+
+<!--
+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.
+-->
+
+## IPV6
+
+<version since="dev">
+
+IPV6
+
+</version>
+
+### description
+
+IPV6
+IPv6类型,以Int128的形式存储在16个字节中,用于表示IPv6地址。
+取值范围是 ['::', 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff']。
+
+`超出取值范围或者格式非法的输入将返回NULL`
+
+### example
+
+建表示例如下:
+
+```
+CREATE TABLE ipv6_test (
+ `id` int,
+ `ip_v6` ipv6
+) ENGINE=OLAP
+DISTRIBUTED BY HASH(`id`) BUCKETS 4
+PROPERTIES (
+"replication_allocation" = "tag.location.default: 1"
+);
+```
+
+插入数据示例:
+
+```
+insert into ipv6_test values(1, '::');
+insert into ipv6_test values(2, '2001:16a0:2:200a::2');
+insert into ipv6_test values(3, 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff');
+insert into ipv6_test values(4, 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffffg'); // invalid data
+```
+
+查询数据示例:
+
+```
+mysql> select * from ipv6_test order by id;
++------+-----------------------------------------+
+| id | ip_v6 |
++------+-----------------------------------------+
+| 1 | :: |
+| 2 | 2001:16a0:2:200a::2 |
+| 3 | ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff |
+| 4 | NULL |
++------+-----------------------------------------+
+```
+
+### keywords
+
+IPV6
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 33/43: [feature](function) support ip functions named to_ipv4[or_default, or_null](string) and to_ipv6[or_default, or_null](string) (#29838)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit d5d0e5e611807e47e41d02cb61ad59f3b16486f0
Author: yangshijie <sj...@zju.edu.cn>
AuthorDate: Mon Jan 22 16:19:47 2024 +0800
[feature](function) support ip functions named to_ipv4[or_default, or_null](string) and to_ipv6[or_default, or_null](string) (#29838)
---
be/src/vec/functions/function_ip.cpp | 26 +--
be/src/vec/functions/function_ip.h | 223 +++++++++++++++++----
.../doris/catalog/BuiltinScalarFunctions.java | 12 ++
.../trees/expressions/functions/scalar/ToIpv4.java | 67 +++++++
.../functions/scalar/ToIpv4OrDefault.java | 67 +++++++
.../expressions/functions/scalar/ToIpv4OrNull.java | 67 +++++++
.../trees/expressions/functions/scalar/ToIpv6.java | 67 +++++++
.../functions/scalar/ToIpv6OrDefault.java | 67 +++++++
.../expressions/functions/scalar/ToIpv6OrNull.java | 67 +++++++
.../expressions/visitor/ScalarFunctionVisitor.java | 30 +++
gensrc/script/doris_builtins_functions.py | 12 ++
.../ip_functions/test_to_ip_functions.out | 21 ++
.../ip_functions/test_to_ip_functions.groovy | 49 +++++
13 files changed, 720 insertions(+), 55 deletions(-)
diff --git a/be/src/vec/functions/function_ip.cpp b/be/src/vec/functions/function_ip.cpp
index 349e095b4a2..7eed9c13364 100644
--- a/be/src/vec/functions/function_ip.cpp
+++ b/be/src/vec/functions/function_ip.cpp
@@ -22,25 +22,27 @@ namespace doris::vectorized {
void register_function_ip(SimpleFunctionFactory& factory) {
factory.register_function<FunctionIPv4NumToString>();
factory.register_alias(FunctionIPv4NumToString::name, "inet_ntoa");
- factory.register_function<FunctionIPv4StringToNum<IPStringToNumExceptionMode::Throw>>();
- factory.register_function<FunctionIPv4StringToNum<IPStringToNumExceptionMode::Default>>();
- factory.register_function<FunctionIPv4StringToNum<IPStringToNumExceptionMode::Null>>();
- factory.register_alias(FunctionIPv4StringToNum<IPStringToNumExceptionMode::Null>::name,
- "inet_aton");
-
+ factory.register_function<FunctionIPv4StringToNum<IPExceptionMode::Throw>>();
+ factory.register_function<FunctionIPv4StringToNum<IPExceptionMode::Default>>();
+ factory.register_function<FunctionIPv4StringToNum<IPExceptionMode::Null>>();
+ factory.register_alias(FunctionIPv4StringToNum<IPExceptionMode::Null>::name, "inet_aton");
factory.register_function<FunctionIPv6NumToString>();
factory.register_alias(FunctionIPv6NumToString::name, "inet6_ntoa");
- factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Throw>>();
- factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Default>>();
- factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Null>>();
- factory.register_alias(FunctionIPv6StringToNum<IPStringToNumExceptionMode::Null>::name,
- "inet6_aton");
-
+ factory.register_function<FunctionIPv6StringToNum<IPExceptionMode::Throw>>();
+ factory.register_function<FunctionIPv6StringToNum<IPExceptionMode::Default>>();
+ factory.register_function<FunctionIPv6StringToNum<IPExceptionMode::Null>>();
+ factory.register_alias(FunctionIPv6StringToNum<IPExceptionMode::Null>::name, "inet6_aton");
factory.register_function<FunctionIsIPv4Compat>();
factory.register_function<FunctionIsIPv4Mapped>();
factory.register_function<FunctionIsIPString<IPv4>>();
factory.register_function<FunctionIsIPString<IPv6>>();
factory.register_function<FunctionIsIPAddressInRange>();
factory.register_function<FunctionIPv6CIDRToRange>();
+ factory.register_function<FunctionToIP<IPExceptionMode::Throw, IPv4>>();
+ factory.register_function<FunctionToIP<IPExceptionMode::Default, IPv4>>();
+ factory.register_function<FunctionToIP<IPExceptionMode::Null, IPv4>>();
+ factory.register_function<FunctionToIP<IPExceptionMode::Throw, IPv6>>();
+ factory.register_function<FunctionToIP<IPExceptionMode::Default, IPv6>>();
+ factory.register_function<FunctionToIP<IPExceptionMode::Null, IPv6>>();
}
} // namespace doris::vectorized
\ No newline at end of file
diff --git a/be/src/vec/functions/function_ip.h b/be/src/vec/functions/function_ip.h
index 8a260b8fd82..359cafe7e34 100644
--- a/be/src/vec/functions/function_ip.h
+++ b/be/src/vec/functions/function_ip.h
@@ -117,13 +117,13 @@ public:
}
};
-enum class IPStringToNumExceptionMode : uint8_t { Throw, Default, Null };
+enum class IPExceptionMode : uint8_t { Throw, Default, Null };
static inline bool tryParseIPv4(const char* pos, Int64& result_value) {
return parseIPv4whole(pos, reinterpret_cast<unsigned char*>(&result_value));
}
-template <IPStringToNumExceptionMode exception_mode, typename ToColumn>
+template <IPExceptionMode exception_mode, typename ToColumn>
ColumnPtr convertToIPv4(ColumnPtr column, const PaddedPODArray<UInt8>* null_map = nullptr) {
const ColumnString* column_string = check_and_get_column<ColumnString>(column.get());
@@ -138,7 +138,7 @@ ColumnPtr convertToIPv4(ColumnPtr column, const PaddedPODArray<UInt8>* null_map
ColumnUInt8::MutablePtr col_null_map_to;
ColumnUInt8::Container* vec_null_map_to = nullptr;
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
col_null_map_to = ColumnUInt8::create(column_size, false);
vec_null_map_to = &col_null_map_to->get_data();
}
@@ -156,7 +156,7 @@ ColumnPtr convertToIPv4(ColumnPtr column, const PaddedPODArray<UInt8>* null_map
if (null_map && (*null_map)[i]) {
vec_res[i] = 0;
prev_offset = offsets_src[i];
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
(*vec_null_map_to)[i] = true;
}
continue;
@@ -169,11 +169,11 @@ ColumnPtr convertToIPv4(ColumnPtr column, const PaddedPODArray<UInt8>* null_map
bool parse_result = tryParseIPv4(src.c_str(), vec_res[i]);
if (!parse_result) {
- if constexpr (exception_mode == IPStringToNumExceptionMode::Throw) {
+ if constexpr (exception_mode == IPExceptionMode::Throw) {
throw Exception(ErrorCode::INVALID_ARGUMENT, "Invalid IPv4 value");
- } else if constexpr (exception_mode == IPStringToNumExceptionMode::Default) {
+ } else if constexpr (exception_mode == IPExceptionMode::Default) {
vec_res[i] = 0;
- } else if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ } else if constexpr (exception_mode == IPExceptionMode::Null) {
(*vec_null_map_to)[i] = true;
vec_res[i] = 0;
}
@@ -182,20 +182,20 @@ ColumnPtr convertToIPv4(ColumnPtr column, const PaddedPODArray<UInt8>* null_map
prev_offset = offsets_src[i];
}
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null)
+ if constexpr (exception_mode == IPExceptionMode::Null)
return ColumnNullable::create(std::move(col_res), std::move(col_null_map_to));
return col_res;
}
-template <IPStringToNumExceptionMode exception_mode>
+template <IPExceptionMode exception_mode>
class FunctionIPv4StringToNum : public IFunction {
public:
- static constexpr auto name = exception_mode == IPStringToNumExceptionMode::Throw
- ? "ipv4_string_to_num"
- : (exception_mode == IPStringToNumExceptionMode::Default
- ? "ipv4_string_to_num_or_default"
- : "ipv4_string_to_num_or_null");
+ static constexpr auto name =
+ exception_mode == IPExceptionMode::Throw
+ ? "ipv4_string_to_num"
+ : (exception_mode == IPExceptionMode::Default ? "ipv4_string_to_num_or_default"
+ : "ipv4_string_to_num_or_null");
static FunctionPtr create() {
return std::make_shared<FunctionIPv4StringToNum<exception_mode>>();
@@ -213,7 +213,7 @@ public:
}
auto result_type = std::make_shared<DataTypeInt64>();
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
return make_nullable(result_type);
}
@@ -343,8 +343,7 @@ public:
};
namespace detail {
-template <IPStringToNumExceptionMode exception_mode, typename ToColumn = ColumnIPv6,
- typename StringColumnType>
+template <IPExceptionMode exception_mode, typename ToColumn = ColumnIPv6, typename StringColumnType>
ColumnPtr convertToIPv6(const StringColumnType& string_column,
const PaddedPODArray<UInt8>* null_map = nullptr) {
if constexpr (!std::is_same_v<ToColumn, ColumnString> &&
@@ -359,7 +358,7 @@ ColumnPtr convertToIPv6(const StringColumnType& string_column,
ColumnUInt8::MutablePtr col_null_map_to;
ColumnUInt8::Container* vec_null_map_to = nullptr;
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
col_null_map_to = ColumnUInt8::create(column_size, false);
vec_null_map_to = &col_null_map_to->get_data();
}
@@ -420,9 +419,9 @@ ColumnPtr convertToIPv6(const StringColumnType& string_column,
}
if (null_map && (*null_map)[i]) {
- if (exception_mode == IPStringToNumExceptionMode::Throw) {
+ if (exception_mode == IPExceptionMode::Throw) {
throw Exception(ErrorCode::INVALID_ARGUMENT, "Invalid IPv6 value");
- } else if (exception_mode == IPStringToNumExceptionMode::Default) {
+ } else if (exception_mode == IPExceptionMode::Default) {
std::fill_n(&vec_res[out_offset], offset_inc, 0);
} else {
std::fill_n(&vec_res[out_offset], offset_inc, 0);
@@ -463,7 +462,7 @@ ColumnPtr convertToIPv6(const StringColumnType& string_column,
col_res->insert_data(reinterpret_cast<const char*>(res_value), IPV6_BINARY_LENGTH);
}
} else {
- if (exception_mode == IPStringToNumExceptionMode::Throw) {
+ if (exception_mode == IPExceptionMode::Throw) {
throw Exception(ErrorCode::INVALID_ARGUMENT, "Invalid IPv6 value");
}
std::fill_n(&vec_res[out_offset], offset_inc, 0);
@@ -471,21 +470,21 @@ ColumnPtr convertToIPv6(const StringColumnType& string_column,
auto* column_string = assert_cast<ColumnString*>(col_res.get());
column_string->get_offsets().push_back((i + 1) * IPV6_BINARY_LENGTH);
}
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
(*vec_null_map_to)[i] = true;
}
}
src_offset = src_next_offset;
}
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
return ColumnNullable::create(std::move(col_res), std::move(col_null_map_to));
}
return col_res;
}
} // namespace detail
-template <IPStringToNumExceptionMode exception_mode, typename ToColumn = ColumnIPv6>
+template <IPExceptionMode exception_mode, typename ToColumn = ColumnIPv6>
ColumnPtr convertToIPv6(ColumnPtr column, const PaddedPODArray<UInt8>* null_map = nullptr) {
if (const auto* column_input_string = check_and_get_column<ColumnString>(column.get())) {
auto result =
@@ -497,14 +496,14 @@ ColumnPtr convertToIPv6(ColumnPtr column, const PaddedPODArray<UInt8>* null_map
}
}
-template <IPStringToNumExceptionMode exception_mode>
+template <IPExceptionMode exception_mode>
class FunctionIPv6StringToNum : public IFunction {
public:
- static constexpr auto name = exception_mode == IPStringToNumExceptionMode::Throw
- ? "ipv6_string_to_num"
- : (exception_mode == IPStringToNumExceptionMode::Default
- ? "ipv6_string_to_num_or_default"
- : "ipv6_string_to_num_or_null");
+ static constexpr auto name =
+ exception_mode == IPExceptionMode::Throw
+ ? "ipv6_string_to_num"
+ : (exception_mode == IPExceptionMode::Default ? "ipv6_string_to_num_or_default"
+ : "ipv6_string_to_num_or_null");
static FunctionPtr create() {
return std::make_shared<FunctionIPv6StringToNum<exception_mode>>();
@@ -525,7 +524,7 @@ public:
auto result_type = std::make_shared<DataTypeString>();
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
return make_nullable(result_type);
}
@@ -541,7 +540,7 @@ public:
if (column->is_nullable()) {
const auto* column_nullable = assert_cast<const ColumnNullable*>(column.get());
column = column_nullable->get_nested_column_ptr();
- if constexpr (exception_mode == IPStringToNumExceptionMode::Null) {
+ if constexpr (exception_mode == IPExceptionMode::Null) {
null_map_column = column_nullable->get_null_map_column_ptr();
null_map = &column_nullable->get_null_map_data();
}
@@ -640,29 +639,33 @@ public:
Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
size_t result, size_t input_rows_count) const override {
- ColumnPtr& addr_column = block.get_by_position(arguments[0]).column;
- ColumnPtr& cidr_column = block.get_by_position(arguments[1]).column;
+ const auto& addr_column_with_type_and_name = block.get_by_position(arguments[0]);
+ const auto& cidr_column_with_type_and_name = block.get_by_position(arguments[1]);
+ WhichDataType addr_type(addr_column_with_type_and_name.type);
+ WhichDataType cidr_type(cidr_column_with_type_and_name.type);
+ const ColumnPtr& addr_column = addr_column_with_type_and_name.column;
+ const ColumnPtr& cidr_column = cidr_column_with_type_and_name.column;
const ColumnString* str_addr_column = nullptr;
const ColumnString* str_cidr_column = nullptr;
- const NullMap* nullmap_addr = nullptr;
- const NullMap* nullmap_cidr = nullptr;
+ const NullMap* null_map_addr = nullptr;
+ const NullMap* null_map_cidr = nullptr;
- if (addr_column->is_nullable()) {
+ if (addr_type.is_nullable()) {
const auto* addr_column_nullable =
assert_cast<const ColumnNullable*>(addr_column.get());
str_addr_column =
check_and_get_column<ColumnString>(addr_column_nullable->get_nested_column());
- nullmap_addr = &addr_column_nullable->get_null_map_data();
+ null_map_addr = &addr_column_nullable->get_null_map_data();
} else {
str_addr_column = check_and_get_column<ColumnString>(addr_column.get());
}
- if (cidr_column->is_nullable()) {
+ if (cidr_type.is_nullable()) {
const auto* cidr_column_nullable =
assert_cast<const ColumnNullable*>(cidr_column.get());
str_cidr_column =
check_and_get_column<ColumnString>(cidr_column_nullable->get_nested_column());
- nullmap_cidr = &cidr_column_nullable->get_null_map_data();
+ null_map_cidr = &cidr_column_nullable->get_null_map_data();
} else {
str_cidr_column = check_and_get_column<ColumnString>(cidr_column.get());
}
@@ -683,12 +686,12 @@ public:
auto& col_res_data = col_res->get_data();
for (size_t i = 0; i < input_rows_count; ++i) {
- if (nullmap_addr && (*nullmap_addr)[i]) {
+ if (null_map_addr && (*null_map_addr)[i]) {
throw Exception(ErrorCode::INVALID_ARGUMENT,
"The arguments of function {} must be String, not NULL",
get_name());
}
- if (nullmap_cidr && (*nullmap_cidr)[i]) {
+ if (null_map_cidr && (*null_map_cidr)[i]) {
throw Exception(ErrorCode::INVALID_ARGUMENT,
"The arguments of function {} must be String, not NULL",
get_name());
@@ -885,4 +888,138 @@ private:
}
};
-} // namespace doris::vectorized
+template <IPExceptionMode exception_mode, typename Type>
+inline constexpr auto to_ip_func_name() {
+ if constexpr (std::is_same_v<Type, IPv4>) {
+ return exception_mode == IPExceptionMode::Throw
+ ? "to_ipv4"
+ : (exception_mode == IPExceptionMode::Default ? "to_ipv4_or_default"
+ : "to_ipv4_or_null");
+ } else {
+ return exception_mode == IPExceptionMode::Throw
+ ? "to_ipv6"
+ : (exception_mode == IPExceptionMode::Default ? "to_ipv6_or_default"
+ : "to_ipv6_or_null");
+ }
+}
+
+template <IPExceptionMode exception_mode, typename Type>
+class FunctionToIP : public IFunction {
+ static_assert(std::is_same_v<Type, IPv4> || std::is_same_v<Type, IPv6>);
+
+public:
+ static constexpr auto name = to_ip_func_name<exception_mode, Type>();
+
+ static FunctionPtr create() { return std::make_shared<FunctionToIP<exception_mode, Type>>(); }
+
+ String get_name() const override { return name; }
+
+ size_t get_number_of_arguments() const override { return 1; }
+
+ DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
+ if (!is_string(remove_nullable(arguments[0]))) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "Illegal type {} of argument of function {}, expected String",
+ arguments[0]->get_name(), get_name());
+ }
+
+ DataTypePtr result_type;
+
+ if constexpr (std::is_same_v<Type, IPv4>) {
+ result_type = std::make_shared<DataTypeIPv4>();
+ } else {
+ result_type = std::make_shared<DataTypeIPv6>();
+ }
+
+ if constexpr (exception_mode == IPExceptionMode::Null) {
+ return make_nullable(result_type);
+ } else {
+ return result_type;
+ }
+ }
+
+ bool use_default_implementation_for_nulls() const override { return false; }
+
+ Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
+ size_t result, size_t input_rows_count) const override {
+ const auto& addr_column_with_type_and_name = block.get_by_position(arguments[0]);
+ WhichDataType addr_type(addr_column_with_type_and_name.type);
+ const ColumnPtr& addr_column = addr_column_with_type_and_name.column;
+ const ColumnString* str_addr_column = nullptr;
+ const NullMap* addr_null_map = nullptr;
+
+ if (addr_type.is_nullable()) {
+ const auto* addr_column_nullable =
+ assert_cast<const ColumnNullable*>(addr_column.get());
+ str_addr_column =
+ check_and_get_column<ColumnString>(addr_column_nullable->get_nested_column());
+ addr_null_map = &addr_column_nullable->get_null_map_data();
+ } else {
+ str_addr_column = check_and_get_column<ColumnString>(addr_column.get());
+ }
+
+ auto col_res = ColumnVector<Type>::create(input_rows_count, 0);
+ auto res_null_map = ColumnUInt8::create(input_rows_count, 0);
+ auto& col_res_data = col_res->get_data();
+ auto& res_null_map_data = res_null_map->get_data();
+
+ for (size_t i = 0; i < input_rows_count; ++i) {
+ if (addr_null_map && (*addr_null_map)[i]) {
+ if constexpr (exception_mode == IPExceptionMode::Throw) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "The arguments of function {} must be String, not NULL",
+ get_name());
+ } else if constexpr (exception_mode == IPExceptionMode::Default) {
+ col_res_data[i] = 0; // '0.0.0.0' or '::'
+ continue;
+ } else {
+ res_null_map_data[i] = 1;
+ continue;
+ }
+ }
+
+ if constexpr (std::is_same_v<Type, IPv4>) {
+ StringRef ipv4_str = str_addr_column->get_data_at(i);
+ IPv4 ipv4_val = 0;
+ if (IPv4Value::from_string(ipv4_val, ipv4_str.data, ipv4_str.size)) {
+ col_res_data[i] = ipv4_val;
+ } else {
+ if constexpr (exception_mode == IPExceptionMode::Throw) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT, "Invalid IPv4 value '{}'",
+ ipv4_str.to_string_view());
+ } else if constexpr (exception_mode == IPExceptionMode::Default) {
+ col_res_data[i] = 0; // '0.0.0.0'
+ } else {
+ res_null_map_data[i] = 1;
+ }
+ }
+ } else {
+ StringRef ipv6_str = str_addr_column->get_data_at(i);
+ IPv6 ipv6_val = 0;
+ if (IPv6Value::from_string(ipv6_val, ipv6_str.data, ipv6_str.size)) {
+ col_res_data[i] = ipv6_val;
+ } else {
+ if constexpr (exception_mode == IPExceptionMode::Throw) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT, "Invalid IPv6 value '{}'",
+ ipv6_str.to_string_view());
+ } else if constexpr (exception_mode == IPExceptionMode::Default) {
+ col_res_data[i] = 0; // '::'
+ } else if constexpr (exception_mode == IPExceptionMode::Null) {
+ res_null_map_data[i] = 1;
+ }
+ }
+ }
+ }
+
+ if constexpr (exception_mode == IPExceptionMode::Null) {
+ block.replace_by_position(
+ result, ColumnNullable::create(std::move(col_res), std::move(res_null_map)));
+ } else {
+ block.replace_by_position(result, std::move(col_res));
+ }
+
+ return Status::OK();
+ }
+};
+
+} // namespace doris::vectorized
\ No newline at end of file
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
index 492c561f0a1..1a40365b523 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
@@ -393,6 +393,12 @@ import org.apache.doris.nereids.trees.expressions.functions.scalar.ToBitmapWithC
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToDate;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToDateV2;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToDays;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv4;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv4OrDefault;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv4OrNull;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv6;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv6OrDefault;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv6OrNull;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToMonday;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToQuantileState;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Tokenize;
@@ -623,6 +629,12 @@ public class BuiltinScalarFunctions implements FunctionHelper {
scalar(IsIpv6String.class, "is_ipv6_string"),
scalar(IsIpAddressInRange.class, "is_ip_address_in_range"),
scalar(Ipv6CIDRToRange.class, "ipv6_cidr_to_range"),
+ scalar(ToIpv4.class, "to_ipv4"),
+ scalar(ToIpv4OrDefault.class, "to_ipv4_or_default"),
+ scalar(ToIpv4OrNull.class, "to_ipv4_or_null"),
+ scalar(ToIpv6.class, "to_ipv6"),
+ scalar(ToIpv6OrDefault.class, "to_ipv6_or_default"),
+ scalar(ToIpv6OrNull.class, "to_ipv6_or_null"),
scalar(JsonArray.class, "json_array"),
scalar(JsonObject.class, "json_object"),
scalar(JsonQuote.class, "json_quote"),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4.java
new file mode 100644
index 00000000000..590c16a6000
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNotNullable;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.IPv4Type;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function to_ipv4
+ */
+public class ToIpv4 extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNotNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(IPv4Type.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(IPv4Type.INSTANCE).args(StringType.INSTANCE));
+
+ public ToIpv4(Expression arg0) {
+ super("to_ipv4", arg0);
+ }
+
+ @Override
+ public ToIpv4 withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "to_ipv4 accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new ToIpv4(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitToIpv4(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrDefault.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrDefault.java
new file mode 100644
index 00000000000..e77e8120d71
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrDefault.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNotNullable;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.IPv4Type;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function to_ipv4_or_default
+ */
+public class ToIpv4OrDefault extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNotNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(IPv4Type.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(IPv4Type.INSTANCE).args(StringType.INSTANCE));
+
+ public ToIpv4OrDefault(Expression arg0) {
+ super("to_ipv4_or_default", arg0);
+ }
+
+ @Override
+ public ToIpv4OrDefault withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "to_ipv4_or_default accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new ToIpv4OrDefault(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitToIpv4OrDefault(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrNull.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrNull.java
new file mode 100644
index 00000000000..940ae4c3971
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv4OrNull.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNullable;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.IPv4Type;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function to_ipv4_or_null
+ */
+public class ToIpv4OrNull extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(IPv4Type.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(IPv4Type.INSTANCE).args(StringType.INSTANCE));
+
+ public ToIpv4OrNull(Expression arg0) {
+ super("to_ipv4_or_null", arg0);
+ }
+
+ @Override
+ public ToIpv4OrNull withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "to_ipv4_or_null accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new ToIpv4OrNull(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitToIpv4OrNull(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6.java
new file mode 100644
index 00000000000..4261862147b
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNotNullable;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.IPv6Type;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function to_ipv6
+ */
+public class ToIpv6 extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNotNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(IPv6Type.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(IPv6Type.INSTANCE).args(StringType.INSTANCE));
+
+ public ToIpv6(Expression arg0) {
+ super("to_ipv6", arg0);
+ }
+
+ @Override
+ public ToIpv6 withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "to_ipv6 accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new ToIpv6(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitToIpv6(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrDefault.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrDefault.java
new file mode 100644
index 00000000000..da9ec1083b0
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrDefault.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNotNullable;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.IPv6Type;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function to_ipv6_or_default
+ */
+public class ToIpv6OrDefault extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNotNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(IPv6Type.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(IPv6Type.INSTANCE).args(StringType.INSTANCE));
+
+ public ToIpv6OrDefault(Expression arg0) {
+ super("to_ipv6_or_default", arg0);
+ }
+
+ @Override
+ public ToIpv6OrDefault withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "to_ipv6_or_default accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new ToIpv6OrDefault(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitToIpv6OrDefault(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrNull.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrNull.java
new file mode 100644
index 00000000000..6a3a3e0973c
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ToIpv6OrNull.java
@@ -0,0 +1,67 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNullable;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.IPv6Type;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * scalar function to_ipv6_or_null
+ */
+public class ToIpv6OrNull extends ScalarFunction
+ implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNullable {
+
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+ FunctionSignature.ret(IPv6Type.INSTANCE).args(VarcharType.SYSTEM_DEFAULT),
+ FunctionSignature.ret(IPv6Type.INSTANCE).args(StringType.INSTANCE));
+
+ public ToIpv6OrNull(Expression arg0) {
+ super("to_ipv6_or_null", arg0);
+ }
+
+ @Override
+ public ToIpv6OrNull withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1,
+ "to_ipv6_or_null accept 1 args, but got %s (%s)",
+ children.size(),
+ children);
+ return new ToIpv6OrNull(children.get(0));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitToIpv6OrNull(this, context);
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
index 8629d15b2bc..d10c384c55e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
@@ -383,6 +383,12 @@ import org.apache.doris.nereids.trees.expressions.functions.scalar.ToBitmapWithC
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToDate;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToDateV2;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToDays;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv4;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv4OrDefault;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv4OrNull;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv6;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv6OrDefault;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ToIpv6OrNull;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToMonday;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ToQuantileState;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Tokenize;
@@ -1196,6 +1202,30 @@ public interface ScalarFunctionVisitor<R, C> {
return visitScalarFunction(ipv6CIDRToRange, context);
}
+ default R visitToIpv4(ToIpv4 toIpv4, C context) {
+ return visitScalarFunction(toIpv4, context);
+ }
+
+ default R visitToIpv4OrDefault(ToIpv4OrDefault toIpv4OrDefault, C context) {
+ return visitScalarFunction(toIpv4OrDefault, context);
+ }
+
+ default R visitToIpv4OrNull(ToIpv4OrNull toIpv4OrNull, C context) {
+ return visitScalarFunction(toIpv4OrNull, context);
+ }
+
+ default R visitToIpv6(ToIpv6 toIpv6, C context) {
+ return visitScalarFunction(toIpv6, context);
+ }
+
+ default R visitToIpv6OrDefault(ToIpv6OrDefault toIpv6OrDefault, C context) {
+ return visitScalarFunction(toIpv6OrDefault, context);
+ }
+
+ default R visitToIpv6OrNull(ToIpv6OrNull toIpv6OrNull, C context) {
+ return visitScalarFunction(toIpv6OrNull, context);
+ }
+
default R visitJsonArray(JsonArray jsonArray, C context) {
return visitScalarFunction(jsonArray, context);
}
diff --git a/gensrc/script/doris_builtins_functions.py b/gensrc/script/doris_builtins_functions.py
index a9d2fe26dc2..9faf1e092ec 100644
--- a/gensrc/script/doris_builtins_functions.py
+++ b/gensrc/script/doris_builtins_functions.py
@@ -2035,6 +2035,18 @@ visible_functions = {
[['is_ip_address_in_range'], 'BOOLEAN', ['STRING', 'STRING'], 'ALWAYS_NOT_NULLABLE'],
[['ipv6_cidr_to_range'], 'STRUCT<IPV6, IPV6>', ['VARCHAR', 'SMALLINT'], ''],
[['ipv6_cidr_to_range'], 'STRUCT<IPV6, IPV6>', ['STRING', 'SMALLINT'], ''],
+ [['to_ipv4'], 'IPV4', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv4'], 'IPV4', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv4_or_default'], 'IPV4', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv4_or_default'], 'IPV4', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv4_or_null'], 'IPV4', ['VARCHAR'], 'ALWAYS_NULLABLE'],
+ [['to_ipv4_or_null'], 'IPV4', ['STRING'], 'ALWAYS_NULLABLE'],
+ [['to_ipv6'], 'IPV6', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv6'], 'IPV6', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv6_or_default'], 'IPV6', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv6_or_default'], 'IPV6', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
+ [['to_ipv6_or_null'], 'IPV6', ['VARCHAR'], 'ALWAYS_NULLABLE'],
+ [['to_ipv6_or_null'], 'IPV6', ['STRING'], 'ALWAYS_NULLABLE'],
],
"NonNullalbe": [
diff --git a/regression-test/data/query_p0/sql_functions/ip_functions/test_to_ip_functions.out b/regression-test/data/query_p0/sql_functions/ip_functions/test_to_ip_functions.out
new file mode 100644
index 00000000000..8015d0eef30
--- /dev/null
+++ b/regression-test/data/query_p0/sql_functions/ip_functions/test_to_ip_functions.out
@@ -0,0 +1,21 @@
+-- !sql --
+0.0.0.0 ::
+192.168.0.1 ::1
+127.0.0.1 2001:1b70:a1:610::b102:2
+255.255.255.255 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
+
+-- !sql --
+0.0.0.0 ::
+0.0.0.0 ::
+192.168.0.1 ::1
+127.0.0.1 2001:1b70:a1:610::b102:2
+255.255.255.255 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
+0.0.0.0 ::
+
+-- !sql --
+\N \N
+0.0.0.0 ::
+192.168.0.1 ::1
+127.0.0.1 2001:1b70:a1:610::b102:2
+255.255.255.255 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
+\N \N
diff --git a/regression-test/suites/query_p0/sql_functions/ip_functions/test_to_ip_functions.groovy b/regression-test/suites/query_p0/sql_functions/ip_functions/test_to_ip_functions.groovy
new file mode 100644
index 00000000000..aefe338b959
--- /dev/null
+++ b/regression-test/suites/query_p0/sql_functions/ip_functions/test_to_ip_functions.groovy
@@ -0,0 +1,49 @@
+// 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.
+suite("test_to_ip_functions") {
+ sql """ DROP TABLE IF EXISTS test_to_ip_functions """
+
+ sql """ SET enable_nereids_planner=true """
+ sql """ SET enable_fallback_to_original_planner=false """
+
+ sql """
+ CREATE TABLE `test_to_ip_functions` (
+ `id` int,
+ `ip_v4` string,
+ `ip_v6` string
+ ) ENGINE=OLAP
+ DISTRIBUTED BY HASH(`id`) BUCKETS 4
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1"
+ );
+ """
+ sql """
+ insert into test_to_ip_functions values
+ (0, NULL, NULL),
+ (1, '0.0.0.0', '::'),
+ (2, '192.168.0.1', '::1'),
+ (3, '127.0.0.1', '2001:1b70:a1:610::b102:2'),
+ (4, '255.255.255.255', 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'),
+ (5, '255.255.255.256', 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffg')
+ """
+
+ qt_sql "select to_ipv4(ip_v4), to_ipv6(ip_v6) from test_to_ip_functions where id in (1, 2, 3, 4) order by id"
+ qt_sql "select to_ipv4_or_default(ip_v4), to_ipv6_or_default(ip_v6) from test_to_ip_functions order by id"
+ qt_sql "select to_ipv4_or_null(ip_v4), to_ipv6_or_null(ip_v6) from test_to_ip_functions order by id"
+
+ sql "DROP TABLE test_to_ip_functions"
+}
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 16/43: [improvement](function) switch inet(6)_aton alias origin function (#30196)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit dfde10d4c8ae462e4106bc3470e99ab47d5b9a28
Author: Chester <42...@users.noreply.github.com>
AuthorDate: Mon Jan 22 11:33:04 2024 +0800
[improvement](function) switch inet(6)_aton alias origin function (#30196)
---
be/src/vec/functions/function_ip.cpp | 4 +--
.../sql-functions/ip-functions/inet-aton.md | 20 ++++++++----
.../sql-functions/ip-functions/inet6-aton.md | 30 ++++++++++-------
.../sql-functions/ip-functions/inet-aton.md | 19 +++++++----
.../sql-functions/ip-functions/inet6-aton.md | 29 ++++++++++-------
.../doris/catalog/BuiltinScalarFunctions.java | 8 ++---
.../org/apache/doris/rewrite/FunctionAlias.java | 4 +--
gensrc/script/doris_builtins_functions.py | 16 ++++-----
.../data/nereids_function_p0/ip_functions.out | 38 +++++++++++++++++++++-
.../ip_functions/test_ip_functions.out | 38 +++++++++++++++++++++-
.../suites/nereids_function_p0/ip_functions.groovy | 12 +++++++
.../ip_functions/test_ip_functions.groovy | 12 +++++++
12 files changed, 174 insertions(+), 56 deletions(-)
diff --git a/be/src/vec/functions/function_ip.cpp b/be/src/vec/functions/function_ip.cpp
index 140100d22b3..349e095b4a2 100644
--- a/be/src/vec/functions/function_ip.cpp
+++ b/be/src/vec/functions/function_ip.cpp
@@ -25,7 +25,7 @@ void register_function_ip(SimpleFunctionFactory& factory) {
factory.register_function<FunctionIPv4StringToNum<IPStringToNumExceptionMode::Throw>>();
factory.register_function<FunctionIPv4StringToNum<IPStringToNumExceptionMode::Default>>();
factory.register_function<FunctionIPv4StringToNum<IPStringToNumExceptionMode::Null>>();
- factory.register_alias(FunctionIPv4StringToNum<IPStringToNumExceptionMode::Throw>::name,
+ factory.register_alias(FunctionIPv4StringToNum<IPStringToNumExceptionMode::Null>::name,
"inet_aton");
factory.register_function<FunctionIPv6NumToString>();
@@ -33,7 +33,7 @@ void register_function_ip(SimpleFunctionFactory& factory) {
factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Throw>>();
factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Default>>();
factory.register_function<FunctionIPv6StringToNum<IPStringToNumExceptionMode::Null>>();
- factory.register_alias(FunctionIPv6StringToNum<IPStringToNumExceptionMode::Throw>::name,
+ factory.register_alias(FunctionIPv6StringToNum<IPStringToNumExceptionMode::Null>::name,
"inet6_aton");
factory.register_function<FunctionIsIPv4Compat>();
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/inet-aton.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/inet-aton.md
index 1120a4852f4..56f9308f347 100644
--- a/docs/en/docs/sql-manual/sql-functions/ip-functions/inet-aton.md
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/inet-aton.md
@@ -40,20 +40,26 @@ Takes a string containing an IPv4 address in the format A.B.C.D (dot-separated n
### notice
-`will return an error if the input string is not a valid IPv4 address`
+`It is the alias of ipv4_string_to_num_or_null.
+It will return NULL if the input string is not a valid IP address or NULL, which is the same with MySQL`
### example
```
mysql> select inet_aton('192.168.0.1');
-+--------------------------------+
-| inet_aton('192.168.0.1') |
-+--------------------------------+
-| 3232235521 |
-+--------------------------------+
++-------------------------------------------+
+| ipv4_string_to_num_or_null('192.168.0.1') |
++-------------------------------------------+
+| 3232235521 |
++-------------------------------------------+
1 row in set (0.01 sec)
mysql> SELECT inet_aton('192.168');
-ERROR 1105 (HY000): errCode = 2, detailMessage = (172.17.0.2)[CANCELLED][INVALID_ARGUMENT][E33] Invalid IPv4 value
++---------------------------------------+
+| ipv4_string_to_num_or_null('192.168') |
++---------------------------------------+
+| NULL |
++---------------------------------------+
+1 row in set (0.01 sec)
```
### keywords
diff --git a/docs/en/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md b/docs/en/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md
index 69bf4a44861..25f60b2cb8c 100644
--- a/docs/en/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md
+++ b/docs/en/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md
@@ -41,28 +41,34 @@ If the input string contains a valid IPv4 address, returns its IPv6 equivalent.
### notice
-`will return an error if the input string is not a valid IP address`
+`It is the alias of ipv6_string_to_num_or_null.
+It will return NULL if the input string is not a valid IP address or NULL, which is the same with MySQL`
### example
```
mysql> select hex(inet6_aton('1111::ffff'));
-+----------------------------------+
-| hex(inet6_aton('1111::ffff')) |
-+----------------------------------+
-| 1111000000000000000000000000FFFF |
-+----------------------------------+
++-----------------------------------------------+
+| hex(ipv6_string_to_num_or_null('1111::ffff')) |
++-----------------------------------------------+
+| 1111000000000000000000000000FFFF |
++-----------------------------------------------+
1 row in set (0.02 sec)
mysql> select hex(inet6_aton('192.168.0.1'));
-+----------------------------------+
-| hex(inet6_aton('192.168.0.1')) |
-+----------------------------------+
-| 00000000000000000000FFFFC0A80001 |
-+----------------------------------+
++------------------------------------------------+
+| hex(ipv6_string_to_num_or_null('192.168.0.1')) |
++------------------------------------------------+
+| 00000000000000000000FFFFC0A80001 |
++------------------------------------------------+
1 row in set (0.02 sec)
mysql> select hex(inet6_aton('notaaddress'));
-ERROR 1105 (HY000): errCode = 2, detailMessage = (172.17.0.2)[CANCELLED][E33] Invalid IPv6 value
++--------------------------------------------------+
+| hex(ipv6_string_to_num_or_null('notaaddress')) |
++--------------------------------------------------+
+| NULL |
++--------------------------------------------------+
+1 row in set (0.02 sec)
```
### keywords
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet-aton.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet-aton.md
index 2260dfbc49d..50a31f17994 100644
--- a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet-aton.md
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet-aton.md
@@ -40,20 +40,25 @@ inet_aton
### notice
-`如果输入字符串不是有效的 IPv4 地址,将返回错误`
+`该函数为ipv4_string_to_num_or_null的别称。如果输入字符串不是有效的 IPv4 地址或者NULL,将返回NULL,和MySQL一样`
### example
```
mysql> select inet_aton('192.168.0.1');
-+--------------------------------+
-| inet_aton('192.168.0.1') |
-+--------------------------------+
-| 3232235521 |
-+--------------------------------+
++-------------------------------------------+
+| ipv4_string_to_num_or_null('192.168.0.1') |
++-------------------------------------------+
+| 3232235521 |
++-------------------------------------------+
1 row in set (0.01 sec)
mysql> SELECT inet_aton('192.168');
-ERROR 1105 (HY000): errCode = 2, detailMessage = (172.17.0.2)[CANCELLED][INVALID_ARGUMENT][E33] Invalid IPv4 value
++---------------------------------------+
+| ipv4_string_to_num_or_null('192.168') |
++---------------------------------------+
+| NULL |
++---------------------------------------+
+1 row in set (0.01 sec)
```
### keywords
diff --git a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md
index cc2bd6f04d2..53eac5cb900 100644
--- a/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md
+++ b/docs/zh-CN/docs/sql-manual/sql-functions/ip-functions/inet6-aton.md
@@ -41,28 +41,33 @@ IPv6NumToString 的反向函数,它接受一个 IP 地址字符串并返回二
### notice
-`如果输入非法的IP地址,会抛出异常`
+`该函数为ipv6_string_to_num_or_null的别称。如果输入字符串不是有效的 IPv4 地址或者NULL,将返回NULL,和MySQL一样`
### example
```
mysql> select hex(inet6_aton('1111::ffff'));
-+----------------------------------+
-| hex(inet6_aton('1111::ffff')) |
-+----------------------------------+
-| 1111000000000000000000000000FFFF |
-+----------------------------------+
++-----------------------------------------------+
+| hex(ipv6_string_to_num_or_null('1111::ffff')) |
++-----------------------------------------------+
+| 1111000000000000000000000000FFFF |
++-----------------------------------------------+
1 row in set (0.02 sec)
mysql> select hex(inet6_aton('192.168.0.1'));
-+----------------------------------+
-| hex(inet6_aton('192.168.0.1')) |
-+----------------------------------+
-| 00000000000000000000FFFFC0A80001 |
-+----------------------------------+
++------------------------------------------------+
+| hex(ipv6_string_to_num_or_null('192.168.0.1')) |
++------------------------------------------------+
+| 00000000000000000000FFFFC0A80001 |
++------------------------------------------------+
1 row in set (0.02 sec)
mysql> select hex(inet6_aton('notaaddress'));
-ERROR 1105 (HY000): errCode = 2, detailMessage = (172.17.0.2)[CANCELLED][E33] Invalid IPv6 value
++--------------------------------------------------+
+| hex(ipv6_string_to_num_or_null('notaaddress')) |
++--------------------------------------------------+
+| NULL |
++--------------------------------------------------+
+1 row in set (0.02 sec)
```
### keywords
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
index 68da4df08ab..fcc2a351bf0 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
@@ -604,13 +604,13 @@ public class BuiltinScalarFunctions implements FunctionHelper {
scalar(InnerProduct.class, "inner_product"),
scalar(Instr.class, "instr"),
scalar(Ipv4NumToString.class, "ipv4_num_to_string", "inet_ntoa"),
- scalar(Ipv4StringToNum.class, "ipv4_string_to_num", "inet_aton"),
+ scalar(Ipv4StringToNum.class, "ipv4_string_to_num"),
scalar(Ipv4StringToNumOrDefault.class, "ipv4_string_to_num_or_default"),
- scalar(Ipv4StringToNumOrNull.class, "ipv4_string_to_num_or_null"),
+ scalar(Ipv4StringToNumOrNull.class, "ipv4_string_to_num_or_null", "inet_aton"),
scalar(Ipv6NumToString.class, "ipv6_num_to_string", "inet6_ntoa"),
- scalar(Ipv6StringToNum.class, "ipv6_string_to_num", "inet6_aton"),
+ scalar(Ipv6StringToNum.class, "ipv6_string_to_num"),
scalar(Ipv6StringToNumOrDefault.class, "ipv6_string_to_num_or_default"),
- scalar(Ipv6StringToNumOrNull.class, "ipv6_string_to_num_or_null"),
+ scalar(Ipv6StringToNumOrNull.class, "ipv6_string_to_num_or_null", "inet6_aton"),
scalar(IsIpv4Compat.class, "is_ipv4_compat"),
scalar(IsIpv4Mapped.class, "is_ipv4_mapped"),
scalar(IsIpv4String.class, "is_ipv4_string"),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/rewrite/FunctionAlias.java b/fe/fe-core/src/main/java/org/apache/doris/rewrite/FunctionAlias.java
index 9e9c6dc9f75..b32cc9919b1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/rewrite/FunctionAlias.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/rewrite/FunctionAlias.java
@@ -38,8 +38,8 @@ public final class FunctionAlias implements ExprRewriteRule {
.put("char_length", "character_length").put("curdate", "current_date").put("curtime", "current_time")
.put("schema", "database").put("day", "dayofmonth").put("date_add", "days_add").put("adddate", "days_add")
.put("date_sub", "days_sub").put("subdate", "days_sub").put("inet_ntoa", "ipv4_num_to_string")
- .put("inet_aton", "ipv4_string_to_num").put("inet6_ntoa", "ipv6_num_to_string")
- .put("inet6_aton", "ipv6_string_to_num").put("lcase", "lower").put("add_months", "months_add")
+ .put("inet_aton", "ipv4_string_to_num_or_null").put("inet6_ntoa", "ipv6_num_to_string")
+ .put("inet6_aton", "ipv6_string_to_num_or_null").put("lcase", "lower").put("add_months", "months_add")
.put("current_timestamp", "now").put("localtime", "now").put("localtimestamp", "now").put("ifnull", "nvl")
.put("rand", "random").put("sha", "sha1").put("substr", "substring").put("ucase", "upper").build();
diff --git a/gensrc/script/doris_builtins_functions.py b/gensrc/script/doris_builtins_functions.py
index 6a6ff96e83d..183b38bdfda 100644
--- a/gensrc/script/doris_builtins_functions.py
+++ b/gensrc/script/doris_builtins_functions.py
@@ -1998,22 +1998,22 @@ visible_functions = {
[['ipv4_num_to_string','inet_ntoa'], 'VARCHAR', ['SMALLINT'], 'ALWAYS_NULLABLE'],
[['ipv4_num_to_string','inet_ntoa'], 'VARCHAR', ['INT'], 'ALWAYS_NULLABLE'],
[['ipv4_num_to_string','inet_ntoa'], 'VARCHAR', ['BIGINT'], 'ALWAYS_NULLABLE'],
- [['ipv4_string_to_num','inet_aton'], 'BIGINT', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
- [['ipv4_string_to_num','inet_aton'], 'BIGINT', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
+ [['ipv4_string_to_num'], 'BIGINT', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
+ [['ipv4_string_to_num'], 'BIGINT', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
[['ipv4_string_to_num_or_default'], 'BIGINT', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
[['ipv4_string_to_num_or_default'], 'BIGINT', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
- [['ipv4_string_to_num_or_null'], 'BIGINT', ['VARCHAR'], 'ALWAYS_NULLABLE'],
- [['ipv4_string_to_num_or_null'], 'BIGINT', ['STRING'], 'ALWAYS_NULLABLE'],
+ [['ipv4_string_to_num_or_null','inet_aton'], 'BIGINT', ['VARCHAR'], 'ALWAYS_NULLABLE'],
+ [['ipv4_string_to_num_or_null','inet_aton'], 'BIGINT', ['STRING'], 'ALWAYS_NULLABLE'],
[['ipv6_num_to_string','inet6_ntoa'], 'VARCHAR', ['VARCHAR'], 'ALWAYS_NULLABLE'],
[['ipv6_num_to_string','inet6_ntoa'], 'STRING', ['STRING'], 'ALWAYS_NULLABLE'],
[['ipv6_num_to_string','inet6_ntoa'], 'VARCHAR', ['IPV6'], 'ALWAYS_NULLABLE'],
[['ipv6_num_to_string','inet6_ntoa'], 'STRING', ['IPV6'], 'ALWAYS_NULLABLE'],
- [['ipv6_string_to_num','inet6_aton'], 'VARCHAR', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
- [['ipv6_string_to_num','inet6_aton'], 'STRING', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
+ [['ipv6_string_to_num'], 'VARCHAR', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
+ [['ipv6_string_to_num'], 'STRING', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
[['ipv6_string_to_num_or_default'], 'VARCHAR', ['VARCHAR'], 'ALWAYS_NOT_NULLABLE'],
[['ipv6_string_to_num_or_default'], 'STRING', ['STRING'], 'ALWAYS_NOT_NULLABLE'],
- [['ipv6_string_to_num_or_null'], 'VARCHAR', ['VARCHAR'], 'ALWAYS_NULLABLE'],
- [['ipv6_string_to_num_or_null'], 'STRING', ['STRING'], 'ALWAYS_NULLABLE'],
+ [['ipv6_string_to_num_or_null','inet6_aton'], 'VARCHAR', ['VARCHAR'], 'ALWAYS_NULLABLE'],
+ [['ipv6_string_to_num_or_null','inet6_aton'], 'STRING', ['STRING'], 'ALWAYS_NULLABLE'],
[['is_ipv4_compat'], 'BOOLEAN', ['VARCHAR'], ''],
[['is_ipv4_compat'], 'BOOLEAN', ['STRING'], ''],
[['is_ipv4_mapped'], 'BOOLEAN', ['VARCHAR'], ''],
diff --git a/regression-test/data/nereids_function_p0/ip_functions.out b/regression-test/data/nereids_function_p0/ip_functions.out
index 914b5ccd683..a89ca34fe60 100644
--- a/regression-test/data/nereids_function_p0/ip_functions.out
+++ b/regression-test/data/nereids_function_p0/ip_functions.out
@@ -35,6 +35,15 @@
-- !ip12 --
3232235521
+-- !ip12_1 --
+\N
+
+-- !ip12_2 --
+\N
+
+-- !ip12_3 --
+\N
+
-- !ip13 --
\N
@@ -152,6 +161,15 @@ AAAAAAAAFFFFFFFFFFFFFFFFAAAAAAAA
-- !ip51 --
2A0206B8000000000000000000000011
+-- !ip51_1 --
+\N
+
+-- !ip51_2 --
+\N
+
+-- !ip51_3 --
+\N
+
-- !ip52 --
true
@@ -182,6 +200,15 @@ false
-- !ip61 --
true
+-- !ip61_1 --
+\N
+
+-- !ip61_2 --
+\N
+
+-- !ip61_3 --
+\N
+
-- !ip62 --
false
@@ -192,4 +219,13 @@ true
false
-- !ip65 --
-true
\ No newline at end of file
+true
+
+-- !ip65_1 --
+\N
+
+-- !ip65_2 --
+\N
+
+-- !ip65_3 --
+\N
\ No newline at end of file
diff --git a/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out b/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out
index 1837acc4bab..569dc78a1e0 100644
--- a/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out
+++ b/regression-test/data/query_p0/sql_functions/ip_functions/test_ip_functions.out
@@ -25,6 +25,15 @@
-- !sql --
\N
+-- !sql --
+\N
+
+-- !sql --
+\N
+
+-- !sql --
+\N
+
-- !sql --
2a02:6b8::11
@@ -139,6 +148,15 @@ AAAAAAAAFFFFFFFFFFFFFFFFAAAAAAAA
-- !sql --
2A0206B8000000000000000000000011
+-- !sql --
+\N
+
+-- !sql --
+\N
+
+-- !sql --
+\N
+
-- !sql --
true
@@ -157,6 +175,15 @@ false
-- !sql --
true
+-- !sql --
+\N
+
+-- !sql --
+\N
+
+-- !sql --
+\N
+
-- !sql --
false
@@ -167,4 +194,13 @@ true
false
-- !sql --
-true
\ No newline at end of file
+true
+
+-- !sql --
+\N
+
+-- !sql --
+\N
+
+-- !sql --
+\N
\ No newline at end of file
diff --git a/regression-test/suites/nereids_function_p0/ip_functions.groovy b/regression-test/suites/nereids_function_p0/ip_functions.groovy
index b5d4d177e89..98a2574e62f 100644
--- a/regression-test/suites/nereids_function_p0/ip_functions.groovy
+++ b/regression-test/suites/nereids_function_p0/ip_functions.groovy
@@ -31,6 +31,9 @@ suite("ip_functions") {
qt_ip10 "SELECT ipv4_string_to_num_or_null('');"
qt_ip11 "SELECT ipv4_string_to_num_or_default('');"
qt_ip12 "SELECT inet_aton('192.168.0.1');"
+ qt_ip12_1 "SELECT inet_aton('192.168');"
+ qt_ip12_2 "SELECT inet_aton('');"
+ qt_ip12_3 "SELECT inet_aton(NULL);"
qt_ip13 "SELECT ipv6_num_to_string(unhex('0A0005091'));"
qt_ip14 "SELECT ipv6_num_to_string(unhex('2A0206B8000000000000000000000011'));"
@@ -72,6 +75,9 @@ suite("ip_functions") {
qt_ip49 "SELECT hex(ipv6_string_to_num_or_null('aaaa:aaaa:ffff:ffff:ffff:ffff:aaaa:aaaa'));"
qt_ip50 "SELECT hex(inet6_aton('192.168.0.1'));"
qt_ip51 "SELECT hex(inet6_aton('2a02:6b8::11'));"
+ qt_ip51_1 "SELECT hex(inet6_aton(''));"
+ qt_ip51_2 "SELECT hex(inet6_aton(NULL));"
+ qt_ip51_3 "SELECT hex(inet6_aton('KK'));"
qt_ip52 "SELECT is_ipv4_string('255.255.255.255');"
qt_ip53 "SELECT is_ipv4_string('255.255.255.256');"
@@ -84,9 +90,15 @@ suite("ip_functions") {
qt_ip59 "SELECT is_ipv4_compat(inet6_aton('::c0a8:0001'));"
qt_ip60 "SELECT is_ipv4_compat(inet6_aton('::0.0.0.0'));"
qt_ip61 "SELECT is_ipv4_compat(inet6_aton('::255.255.255.255'));"
+ qt_ip61_1 "SELECT is_ipv4_compat(inet6_aton(''));"
+ qt_ip61_2 "SELECT is_ipv4_compat(inet6_aton(NULL));"
+ qt_ip61_3 "SELECT is_ipv4_compat(inet6_aton('KK'));"
qt_ip62 "SELECT is_ipv4_mapped(inet6_aton('::10.0.5.9'));"
qt_ip63 "SELECT is_ipv4_mapped(inet6_aton('::ffff:10.0.5.9'));"
qt_ip64 "SELECT is_ipv4_mapped(inet6_aton('::'));"
qt_ip65 "SELECT is_ipv4_mapped(inet6_aton('::ffff:c0a8:0001'));"
+ qt_ip65_1 "SELECT is_ipv4_mapped(inet6_aton(''));"
+ qt_ip65_2 "SELECT is_ipv4_mapped(inet6_aton(NULL));"
+ qt_ip65_3 "SELECT is_ipv4_mapped(inet6_aton('KK'));"
}
\ No newline at end of file
diff --git a/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy b/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy
index c5ff6d36a13..5cbf59ac36c 100644
--- a/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy
+++ b/regression-test/suites/query_p0/sql_functions/ip_functions/test_ip_functions.groovy
@@ -26,6 +26,9 @@ suite("test_ip_functions", "arrow_flight_sql") {
qt_sql "SELECT ipv4_string_to_num_or_null('');"
qt_sql "SELECT ipv4_string_to_num_or_default('');"
qt_sql "SELECT inet_aton('192.168.0.1');"
+ qt_sql "SELECT inet_aton('192.168');"
+ qt_sql "SELECT inet_aton('');"
+ qt_sql "SELECT inet_aton(NULL);"
qt_sql "SELECT ipv6_num_to_string(unhex('0A0005091'));"
qt_sql "SELECT ipv6_num_to_string(unhex('2A0206B8000000000000000000000011'));"
@@ -67,6 +70,9 @@ suite("test_ip_functions", "arrow_flight_sql") {
qt_sql "SELECT hex(ipv6_string_to_num_or_null('aaaa:aaaa:ffff:ffff:ffff:ffff:aaaa:aaaa'));"
qt_sql "SELECT hex(inet6_aton('192.168.0.1'));"
qt_sql "SELECT hex(inet6_aton('2a02:6b8::11'));"
+ qt_sql "SELECT hex(inet6_aton(''));"
+ qt_sql "SELECT hex(inet6_aton(NULL));"
+ qt_sql "SELECT hex(inet6_aton('KK'));"
qt_sql "SELECT is_ipv4_compat(inet6_aton('::10.0.5.9'));"
qt_sql "SELECT is_ipv4_compat(inet6_aton('::ffff:10.0.5.9'));"
@@ -74,9 +80,15 @@ suite("test_ip_functions", "arrow_flight_sql") {
qt_sql "SELECT is_ipv4_compat(inet6_aton('::c0a8:0001'));"
qt_sql "SELECT is_ipv4_compat(inet6_aton('::0.0.0.0'));"
qt_sql "SELECT is_ipv4_compat(inet6_aton('::255.255.255.255'));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton(''));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton(NULL));"
+ qt_sql "SELECT is_ipv4_compat(inet6_aton('KK'));"
qt_sql "SELECT is_ipv4_mapped(inet6_aton('::10.0.5.9'));"
qt_sql "SELECT is_ipv4_mapped(inet6_aton('::ffff:10.0.5.9'));"
qt_sql "SELECT is_ipv4_mapped(inet6_aton('::'));"
qt_sql "SELECT is_ipv4_mapped(inet6_aton('::ffff:c0a8:0001'));"
+ qt_sql "SELECT is_ipv4_mapped(inet6_aton(''));"
+ qt_sql "SELECT is_ipv4_mapped(inet6_aton(NULL));"
+ qt_sql "SELECT is_ipv4_mapped(inet6_aton('KK'));"
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 11/43: [fix](group commit) Fix some group commit case (#30132)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 1bb1d35f7099d548e8819a3c5741a720450e6c32
Author: meiyi <my...@gmail.com>
AuthorDate: Sun Jan 21 11:42:25 2024 +0800
[fix](group commit) Fix some group commit case (#30132)
---
.../org/apache/doris/alter/SchemaChangeJobV2.java | 15 ++++++-------
.../java/org/apache/doris/alter/SystemHandler.java | 11 +++++-----
.../apache/doris/analysis/NativeInsertStmt.java | 2 +-
.../doris/httpv2/rest/CheckWalSizeAction.java | 3 +--
.../org/apache/doris/httpv2/rest/LoadAction.java | 23 +++++++++-----------
.../org/apache/doris/load/GroupCommitManager.java | 25 +++++++++-------------
.../apache/doris/planner/GroupCommitPlanner.java | 3 ---
gensrc/proto/internal_service.proto | 6 +++---
8 files changed, 38 insertions(+), 50 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeJobV2.java b/fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeJobV2.java
index eef902dea82..5c74164ae33 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeJobV2.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeJobV2.java
@@ -48,7 +48,6 @@ import org.apache.doris.common.SchemaVersionAndHash;
import org.apache.doris.common.io.Text;
import org.apache.doris.common.util.DbUtil;
import org.apache.doris.common.util.TimeUtils;
-import org.apache.doris.load.GroupCommitManager.SchemaChangeStatus;
import org.apache.doris.persist.gson.GsonUtils;
import org.apache.doris.task.AgentBatchTask;
import org.apache.doris.task.AgentTask;
@@ -602,8 +601,8 @@ public class SchemaChangeJobV2 extends AlterJobV2 {
private void waitWalFinished() {
// wait wal done here
- Env.getCurrentEnv().getGroupCommitManager().setStatus(tableId, SchemaChangeStatus.BLOCK);
- LOG.info("block table {}", tableId);
+ Env.getCurrentEnv().getGroupCommitManager().blockTable(tableId);
+ LOG.info("block group commit for table={} when schema change", tableId);
List<Long> aliveBeIds = Env.getCurrentSystemInfo().getAllBackendIds(true);
long expireTime = System.currentTimeMillis() + Config.check_wal_queue_timeout_threshold;
while (true) {
@@ -611,21 +610,21 @@ public class SchemaChangeJobV2 extends AlterJobV2 {
boolean walFinished = Env.getCurrentEnv().getGroupCommitManager()
.isPreviousWalFinished(tableId, aliveBeIds);
if (walFinished) {
- LOG.info("all wal is finished");
+ LOG.info("all wal is finished for table={}", tableId);
break;
} else if (System.currentTimeMillis() > expireTime) {
- LOG.warn("waitWalFinished time out");
+ LOG.warn("waitWalFinished time out for table={}", tableId);
break;
} else {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
- LOG.info("schema change job sleep wait for wal InterruptedException: ", ie);
+ LOG.warn("failed to wait for wal for table={} when schema change", tableId, ie);
}
}
}
- Env.getCurrentEnv().getGroupCommitManager().setStatus(tableId, SchemaChangeStatus.NORMAL);
- LOG.info("release table {}", tableId);
+ Env.getCurrentEnv().getGroupCommitManager().unblockTable(tableId);
+ LOG.info("unblock group commit for table={} when schema change", tableId);
}
private void onFinished(OlapTable tbl) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/alter/SystemHandler.java b/fe/fe-core/src/main/java/org/apache/doris/alter/SystemHandler.java
index 935dcf36293..86551ba0735 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/alter/SystemHandler.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/alter/SystemHandler.java
@@ -83,7 +83,8 @@ public class SystemHandler extends AlterHandler {
}
List<Long> backendTabletIds = invertedIndex.getTabletIdsByBackendId(beId);
- if (Config.drop_backend_after_decommission && checkTablets(beId, backendTabletIds) && checkWal(backend)) {
+ boolean hasWal = checkWal(backend);
+ if (Config.drop_backend_after_decommission && checkTablets(beId, backendTabletIds) && hasWal) {
try {
systemInfoService.dropBackend(beId);
LOG.info("no available tablet on decommission backend {}, drop it", beId);
@@ -94,8 +95,9 @@ public class SystemHandler extends AlterHandler {
continue;
}
- LOG.info("backend {} lefts {} replicas to decommission: {}", beId, backendTabletIds.size(),
- backendTabletIds.subList(0, Math.min(10, backendTabletIds.size())));
+ LOG.info("backend {} lefts {} replicas to decommission: {}{}", beId, backendTabletIds.size(),
+ backendTabletIds.subList(0, Math.min(10, backendTabletIds.size())),
+ hasWal ? "; and has unfinished WALs" : "");
}
}
@@ -197,8 +199,7 @@ public class SystemHandler extends AlterHandler {
}
private boolean checkWal(Backend backend) {
- return Env.getCurrentEnv().getGroupCommitManager()
- .getAllWalQueueSize(backend) == 0;
+ return Env.getCurrentEnv().getGroupCommitManager().getAllWalQueueSize(backend) == 0;
}
private List<Backend> checkDecommission(DecommissionBackendClause decommissionBackendClause)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/analysis/NativeInsertStmt.java b/fe/fe-core/src/main/java/org/apache/doris/analysis/NativeInsertStmt.java
index d69ca40ceca..96dbb2e0edf 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/analysis/NativeInsertStmt.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/analysis/NativeInsertStmt.java
@@ -1140,7 +1140,7 @@ public class NativeInsertStmt extends InsertStmt {
return;
}
boolean partialUpdate = ConnectContext.get().getSessionVariable().isEnableUniqueKeyPartialUpdate();
- if (!partialUpdate && ConnectContext.get().getSessionVariable().isEnableInsertGroupCommit()
+ if (!isExplain() && !partialUpdate && ConnectContext.get().getSessionVariable().isEnableInsertGroupCommit()
&& ConnectContext.get().getSessionVariable().getSqlMode() != SqlModeHelper.MODE_NO_BACKSLASH_ESCAPES
&& targetTable instanceof OlapTable
&& ((OlapTable) targetTable).getTableProperty().getUseSchemaLightChange()
diff --git a/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/CheckWalSizeAction.java b/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/CheckWalSizeAction.java
index f7822580fb7..fdc39e8badd 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/CheckWalSizeAction.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/CheckWalSizeAction.java
@@ -84,8 +84,7 @@ public class CheckWalSizeAction extends RestBaseController {
List<Backend> backends = getBackends(hostInfos);
List<String> backendsList = new ArrayList<>();
for (Backend backend : backends) {
- long size = Env.getCurrentEnv().getGroupCommitManager()
- .getAllWalQueueSize(backend);
+ long size = Env.getCurrentEnv().getGroupCommitManager().getAllWalQueueSize(backend);
backendsList.add(backend.getHost() + ":" + backend.getHeartbeatPort() + ":" + size);
}
return ResponseEntityBuilder.ok(backendsList);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/LoadAction.java b/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/LoadAction.java
index a78a7e9fa58..6952bd37b5c 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/LoadAction.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/LoadAction.java
@@ -88,12 +88,11 @@ public class LoadAction extends RestBaseController {
@PathVariable(value = DB_KEY) String db, @PathVariable(value = TABLE_KEY) String table) {
boolean groupCommit = false;
String groupCommitStr = request.getHeader("group_commit");
- if (groupCommitStr != null && groupCommitStr.equals("async_mode")) {
+ if (groupCommitStr != null && groupCommitStr.equalsIgnoreCase("async_mode")) {
groupCommit = true;
try {
- String[] pair = new String[] {db, table};
- if (isGroupCommitBlock(pair)) {
- String msg = "insert table " + pair[1] + " is blocked on schema change";
+ if (isGroupCommitBlock(db, table)) {
+ String msg = "insert table " + table + " is blocked on schema change";
return new RestBaseResult(msg);
}
} catch (Exception e) {
@@ -122,19 +121,17 @@ public class LoadAction extends RestBaseController {
}
}
- @RequestMapping(path = "/api/_http_stream",
- method = RequestMethod.PUT)
- public Object streamLoadWithSql(HttpServletRequest request,
- HttpServletResponse response) {
+ @RequestMapping(path = "/api/_http_stream", method = RequestMethod.PUT)
+ public Object streamLoadWithSql(HttpServletRequest request, HttpServletResponse response) {
String sql = request.getHeader("sql");
LOG.info("streaming load sql={}", sql);
boolean groupCommit = false;
String groupCommitStr = request.getHeader("group_commit");
- if (groupCommitStr != null && groupCommitStr.equals("async_mode")) {
+ if (groupCommitStr != null && groupCommitStr.equalsIgnoreCase("async_mode")) {
groupCommit = true;
try {
String[] pair = parseDbAndTb(sql);
- if (isGroupCommitBlock(pair)) {
+ if (isGroupCommitBlock(pair[0], pair[1])) {
String msg = "insert table " + pair[1] + " is blocked on schema change";
return new RestBaseResult(msg);
}
@@ -164,11 +161,11 @@ public class LoadAction extends RestBaseController {
}
}
- private boolean isGroupCommitBlock(String[] pair) throws TException {
- String fullDbName = getFullDbName(pair[0]);
+ private boolean isGroupCommitBlock(String db, String table) throws TException {
+ String fullDbName = getFullDbName(db);
Database dbObj = Env.getCurrentInternalCatalog()
.getDbOrException(fullDbName, s -> new TException("database is invalid for dbName: " + s));
- Table tblObj = dbObj.getTableOrException(pair[1], s -> new TException("table is invalid: " + s));
+ Table tblObj = dbObj.getTableOrException(table, s -> new TException("table is invalid: " + s));
return Env.getCurrentEnv().getGroupCommitManager().isBlock(tblObj.getId());
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/load/GroupCommitManager.java b/fe/fe-core/src/main/java/org/apache/doris/load/GroupCommitManager.java
index 3b9719b2594..12410945e9f 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/load/GroupCommitManager.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/load/GroupCommitManager.java
@@ -17,7 +17,6 @@
package org.apache.doris.load;
-
import org.apache.doris.catalog.Env;
import org.apache.doris.common.Config;
import org.apache.doris.proto.InternalService.PGetWalQueueSizeRequest;
@@ -30,31 +29,27 @@ import org.apache.doris.thrift.TStatusCode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+import java.util.HashSet;
import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
+import java.util.Set;
import java.util.concurrent.Future;
public class GroupCommitManager {
- public enum SchemaChangeStatus {
- BLOCK, NORMAL
- }
-
private static final Logger LOG = LogManager.getLogger(GroupCommitManager.class);
- private final Map<Long, SchemaChangeStatus> statusMap = new ConcurrentHashMap<>();
+ private Set<Long> blockedTableIds = new HashSet<>();
public boolean isBlock(long tableId) {
- if (statusMap.containsKey(tableId)) {
- return statusMap.get(tableId) == SchemaChangeStatus.BLOCK;
- }
- return false;
+ return blockedTableIds.contains(tableId);
+ }
+
+ public void blockTable(long tableId) {
+ blockedTableIds.add(tableId);
}
- public void setStatus(long tableId, SchemaChangeStatus status) {
- LOG.debug("Setting status for tableId {}: {}", tableId, status);
- statusMap.put(tableId, status);
+ public void unblockTable(long tableId) {
+ blockedTableIds.remove(tableId);
}
/**
diff --git a/fe/fe-core/src/main/java/org/apache/doris/planner/GroupCommitPlanner.java b/fe/fe-core/src/main/java/org/apache/doris/planner/GroupCommitPlanner.java
index 8b9f6b18331..b69ece3b9ae 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/GroupCommitPlanner.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/GroupCommitPlanner.java
@@ -153,9 +153,6 @@ public class GroupCommitPlanner {
}
}
PGroupCommitInsertRequest request = PGroupCommitInsertRequest.newBuilder()
- .setDbId(db.getId())
- .setTableId(table.getId())
- .setBaseSchemaVersion(table.getBaseSchemaVersion())
.setExecPlanFragmentRequest(InternalService.PExecPlanFragmentRequest.newBuilder()
.setRequest(execPlanFragmentParamsBytes)
.setCompact(false).setVersion(InternalService.PFragmentRequestVersion.VERSION_2).build())
diff --git a/gensrc/proto/internal_service.proto b/gensrc/proto/internal_service.proto
index f197cd162dc..b7c1a949202 100644
--- a/gensrc/proto/internal_service.proto
+++ b/gensrc/proto/internal_service.proto
@@ -721,11 +721,11 @@ message PGlobResponse {
}
message PGroupCommitInsertRequest {
- optional int64 db_id = 1;
- optional int64 table_id = 2;
+ optional int64 db_id = 1; // deprecated
+ optional int64 table_id = 2; // deprecated
// Descriptors.TDescriptorTable
// optional bytes desc_tbl = 3;
- optional int64 base_schema_version = 4;
+ optional int64 base_schema_version = 4; // deprecated
// TExecPlanFragmentParams -> TPlanFragment -> PlanNodes.TPlan
// optional bytes plan_node = 5;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 35/43: [fix](Nereids) result nullable of sum distinct in scalar agg is wrong (#30221)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit ce47354d598b099fb0ebe2784b38978c13a4c808
Author: morrySnow <10...@users.noreply.github.com>
AuthorDate: Mon Jan 22 17:53:25 2024 +0800
[fix](Nereids) result nullable of sum distinct in scalar agg is wrong (#30221)
---
.../AdjustAggregateNullableForEmptySet.java | 3 +-
.../rules/implementation/AggregateStrategies.java | 44 ++++++++--------------
.../trees/expressions/functions/agg/Sum.java | 6 +++
.../data/nereids_syntax_p0/agg_with_empty_set.out | 3 ++
.../nereids_syntax_p0/agg_with_empty_set.groovy | 1 +
5 files changed, 26 insertions(+), 31 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AdjustAggregateNullableForEmptySet.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AdjustAggregateNullableForEmptySet.java
index 75400a8e6b0..86a70d35ccc 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AdjustAggregateNullableForEmptySet.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AdjustAggregateNullableForEmptySet.java
@@ -90,8 +90,7 @@ public class AdjustAggregateNullableForEmptySet implements RewriteRuleFactory {
@Override
public Expression visitNullableAggregateFunction(NullableAggregateFunction nullableAggregateFunction,
Boolean alwaysNullable) {
- return nullableAggregateFunction.isDistinct() ? nullableAggregateFunction
- : nullableAggregateFunction.withAlwaysNullable(alwaysNullable);
+ return nullableAggregateFunction.withAlwaysNullable(alwaysNullable);
}
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/AggregateStrategies.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/AggregateStrategies.java
index a0eb011ba92..c9907ae7c3d 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/AggregateStrategies.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/implementation/AggregateStrategies.java
@@ -50,7 +50,6 @@ import org.apache.doris.nereids.trees.expressions.functions.agg.GroupConcat;
import org.apache.doris.nereids.trees.expressions.functions.agg.Max;
import org.apache.doris.nereids.trees.expressions.functions.agg.Min;
import org.apache.doris.nereids.trees.expressions.functions.agg.MultiDistinctCount;
-import org.apache.doris.nereids.trees.expressions.functions.agg.MultiDistinctSum;
import org.apache.doris.nereids.trees.expressions.functions.agg.Sum;
import org.apache.doris.nereids.trees.expressions.functions.scalar.If;
import org.apache.doris.nereids.trees.expressions.literal.Literal;
@@ -108,9 +107,9 @@ public class AggregateStrategies implements ImplementationRuleFactory {
logicalAggregate(
logicalFilter(
logicalOlapScan().when(this::isDupOrMowKeyTable).when(this::isInvertedIndexEnabledOnTable)
- ).when(filter -> filter.getConjuncts().size() > 0))
+ ).when(filter -> !filter.getConjuncts().isEmpty()))
.when(agg -> enablePushDownCountOnIndex())
- .when(agg -> agg.getGroupByExpressions().size() == 0)
+ .when(agg -> agg.getGroupByExpressions().isEmpty())
.when(agg -> {
Set<AggregateFunction> funcs = agg.getAggregateFunctions();
return !funcs.isEmpty() && funcs.stream()
@@ -128,9 +127,9 @@ public class AggregateStrategies implements ImplementationRuleFactory {
logicalProject(
logicalFilter(
logicalOlapScan().when(this::isDupOrMowKeyTable).when(this::isInvertedIndexEnabledOnTable)
- ).when(filter -> filter.getConjuncts().size() > 0)))
+ ).when(filter -> !filter.getConjuncts().isEmpty())))
.when(agg -> enablePushDownCountOnIndex())
- .when(agg -> agg.getGroupByExpressions().size() == 0)
+ .when(agg -> agg.getGroupByExpressions().isEmpty())
.when(agg -> {
Set<AggregateFunction> funcs = agg.getAggregateFunctions();
return !funcs.isEmpty() && funcs.stream().allMatch(f -> f instanceof Count && !f.isDistinct());
@@ -154,7 +153,7 @@ public class AggregateStrategies implements ImplementationRuleFactory {
Expression childExpr = filter.getConjuncts().iterator().next().children().get(0);
if (childExpr instanceof SlotReference) {
Optional<Column> column = ((SlotReference) childExpr).getColumn();
- return column.isPresent() ? column.get().isDeleteSignColumn() : false;
+ return column.map(Column::isDeleteSignColumn).orElse(false);
}
return false;
})
@@ -187,8 +186,7 @@ public class AggregateStrategies implements ImplementationRuleFactory {
.children().get(0);
if (childExpr instanceof SlotReference) {
Optional<Column> column = ((SlotReference) childExpr).getColumn();
- return column.isPresent() ? column.get().isDeleteSignColumn()
- : false;
+ return column.map(Column::isDeleteSignColumn).orElse(false);
}
return false;
}))
@@ -253,12 +251,12 @@ public class AggregateStrategies implements ImplementationRuleFactory {
),
RuleType.ONE_PHASE_AGGREGATE_WITHOUT_DISTINCT.build(
basePattern
- .when(agg -> agg.getDistinctArguments().size() == 0)
+ .when(agg -> agg.getDistinctArguments().isEmpty())
.thenApplyMulti(ctx -> onePhaseAggregateWithoutDistinct(ctx.root, ctx.connectContext))
),
RuleType.TWO_PHASE_AGGREGATE_WITHOUT_DISTINCT.build(
basePattern
- .when(agg -> agg.getDistinctArguments().size() == 0)
+ .when(agg -> agg.getDistinctArguments().isEmpty())
.thenApplyMulti(ctx -> twoPhaseAggregateWithoutDistinct(ctx.root, ctx.connectContext))
),
// RuleType.TWO_PHASE_AGGREGATE_WITH_COUNT_DISTINCT_MULTI.build(
@@ -435,12 +433,7 @@ public class AggregateStrategies implements ImplementationRuleFactory {
boolean onlyContainsSlotOrNumericCastSlot = aggregateFunctions.stream()
.map(ExpressionTrait::getArguments)
.flatMap(List::stream)
- .allMatch(argument -> {
- if (argument instanceof SlotReference) {
- return true;
- }
- return false;
- });
+ .allMatch(argument -> argument instanceof SlotReference);
if (!onlyContainsSlotOrNumericCastSlot) {
return false;
}
@@ -457,19 +450,13 @@ public class AggregateStrategies implements ImplementationRuleFactory {
}
onlyContainsSlotOrNumericCastSlot = argumentsOfAggregateFunction
.stream()
- .allMatch(argument -> {
- if (argument instanceof SlotReference) {
- return true;
- }
- return false;
- });
+ .allMatch(argument -> argument instanceof SlotReference);
if (!onlyContainsSlotOrNumericCastSlot) {
return false;
}
Set<SlotReference> aggUsedSlots = ExpressionUtils.collect(argumentsOfAggregateFunction,
SlotReference.class::isInstance);
- List<SlotReference> usedSlotInTable = (List<SlotReference>) Project.findProject(aggUsedSlots,
- outPutSlots);
+ List<SlotReference> usedSlotInTable = (List<SlotReference>) Project.findProject(aggUsedSlots, outPutSlots);
for (SlotReference slot : usedSlotInTable) {
Column column = slot.getColumn().get();
PrimitiveType colType = column.getType().getPrimitiveType();
@@ -630,7 +617,7 @@ public class AggregateStrategies implements ImplementationRuleFactory {
if (logicalScan instanceof LogicalOlapScan) {
PhysicalOlapScan physicalScan = (PhysicalOlapScan) new LogicalOlapScanToPhysicalOlapScan()
.build()
- .transform((LogicalOlapScan) logicalScan, cascadesContext)
+ .transform(logicalScan, cascadesContext)
.get(0);
if (project != null) {
@@ -647,7 +634,7 @@ public class AggregateStrategies implements ImplementationRuleFactory {
} else if (logicalScan instanceof LogicalFileScan) {
PhysicalFileScan physicalScan = (PhysicalFileScan) new LogicalFileScanToPhysicalFileScan()
.build()
- .transform((LogicalFileScan) logicalScan, cascadesContext)
+ .transform(logicalScan, cascadesContext)
.get(0);
if (project != null) {
return aggregate.withChildren(ImmutableList.of(
@@ -1193,8 +1180,7 @@ public class AggregateStrategies implements ImplementationRuleFactory {
return new AggregateExpression(nonDistinct, AggregateParam.LOCAL_RESULT);
} else {
Alias alias = nonDistinctAggFunctionToAliasPhase1.get(outputChild);
- return new AggregateExpression(
- aggregateFunction, bufferToResultParam, alias.toSlot());
+ return new AggregateExpression(aggregateFunction, bufferToResultParam, alias.toSlot());
}
} else {
return outputChild;
@@ -1582,7 +1568,7 @@ public class AggregateStrategies implements ImplementationRuleFactory {
return new MultiDistinctCount(function.getArgument(0),
function.getArguments().subList(1, function.arity()).toArray(new Expression[0]));
} else if (function instanceof Sum && function.isDistinct()) {
- return new MultiDistinctSum(function.getArgument(0));
+ return ((Sum) function).convertToMultiDistinct();
} else if (function instanceof GroupConcat && function.isDistinct()) {
return ((GroupConcat) function).convertToMultiDistinct();
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/Sum.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/Sum.java
index f0dbd839583..0b00536d6a8 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/Sum.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/Sum.java
@@ -78,6 +78,12 @@ public class Sum extends NullableAggregateFunction
super("sum", distinct, alwaysNullable, arg);
}
+ public MultiDistinctSum convertToMultiDistinct() {
+ Preconditions.checkArgument(distinct,
+ "can't convert to multi_distinct_sum because there is no distinct args");
+ return new MultiDistinctSum(false, alwaysNullable, child());
+ }
+
@Override
public void checkLegalityBeforeTypeCoercion() {
DataType argType = child().getDataType();
diff --git a/regression-test/data/nereids_syntax_p0/agg_with_empty_set.out b/regression-test/data/nereids_syntax_p0/agg_with_empty_set.out
index 1db851c70c1..ffe8f93eb58 100644
--- a/regression-test/data/nereids_syntax_p0/agg_with_empty_set.out
+++ b/regression-test/data/nereids_syntax_p0/agg_with_empty_set.out
@@ -18,3 +18,6 @@
-- !select6 --
0 \N \N \N \N
+-- !ditinct_sum --
+\N
+
diff --git a/regression-test/suites/nereids_syntax_p0/agg_with_empty_set.groovy b/regression-test/suites/nereids_syntax_p0/agg_with_empty_set.groovy
index 5fc117445a4..bdcb4526a2c 100644
--- a/regression-test/suites/nereids_syntax_p0/agg_with_empty_set.groovy
+++ b/regression-test/suites/nereids_syntax_p0/agg_with_empty_set.groovy
@@ -29,4 +29,5 @@ suite("agg_with_empty_set") {
(select min(c_custkey) from customer)"""
qt_select6 """select count(c_custkey), max(c_custkey), min(c_custkey), avg(c_custkey), sum(c_custkey) from customer where c_custkey <
(select min(c_custkey) from customer) having min(c_custkey) is null"""
+ qt_ditinct_sum """select sum(distinct ifnull(c_custkey, 0)) from customer where 1 = 0"""
}
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 18/43: [refactor](Nereids): Eager Aggregation unify pushdown agg function (#30142)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit ad1c19bd65644bc19392eef6ebc2e845b342fd37
Author: jakevin <ja...@gmail.com>
AuthorDate: Mon Jan 22 12:23:50 2024 +0800
[refactor](Nereids): Eager Aggregation unify pushdown agg function (#30142)
---
.../rules/rewrite/PushDownMinMaxThroughJoin.java | 17 ++-
.../rules/rewrite/PushDownSumThroughJoin.java | 4 +-
.../rewrite/PushDownSumThroughJoinOneSide.java | 117 +--------------------
3 files changed, 19 insertions(+), 119 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownMinMaxThroughJoin.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownMinMaxThroughJoin.java
index 48ded00defe..3057f1eafc4 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownMinMaxThroughJoin.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownMinMaxThroughJoin.java
@@ -81,7 +81,7 @@ public class PushDownMinMaxThroughJoin implements RewriteRuleFactory {
return null;
}
LogicalAggregate<LogicalJoin<Plan, Plan>> agg = ctx.root;
- return pushMinMax(agg, agg.child(), ImmutableList.of());
+ return pushMinMaxSum(agg, agg.child(), ImmutableList.of());
})
.toRule(RuleType.PUSH_DOWN_MIN_MAX_THROUGH_JOIN),
logicalAggregate(logicalProject(innerLogicalJoin()))
@@ -102,13 +102,16 @@ public class PushDownMinMaxThroughJoin implements RewriteRuleFactory {
return null;
}
LogicalAggregate<LogicalProject<LogicalJoin<Plan, Plan>>> agg = ctx.root;
- return pushMinMax(agg, agg.child().child(), agg.child().getProjects());
+ return pushMinMaxSum(agg, agg.child().child(), agg.child().getProjects());
})
.toRule(RuleType.PUSH_DOWN_MIN_MAX_THROUGH_JOIN)
);
}
- private LogicalAggregate<Plan> pushMinMax(LogicalAggregate<? extends Plan> agg,
+ /**
+ * Push down Min/Max/Sum through join.
+ */
+ public static LogicalAggregate<Plan> pushMinMaxSum(LogicalAggregate<? extends Plan> agg,
LogicalJoin<Plan, Plan> join, List<NamedExpression> projects) {
List<Slot> leftOutput = join.left().getOutput();
List<Slot> rightOutput = join.right().getOutput();
@@ -125,6 +128,9 @@ public class PushDownMinMaxThroughJoin implements RewriteRuleFactory {
throw new IllegalStateException("Slot " + slot + " not found in join output");
}
}
+ if (leftFuncs.isEmpty() && rightFuncs.isEmpty()) {
+ return null;
+ }
Set<Slot> leftGroupBy = new HashSet<>();
Set<Slot> rightGroupBy = new HashSet<>();
@@ -177,6 +183,11 @@ public class PushDownMinMaxThroughJoin implements RewriteRuleFactory {
Preconditions.checkState(left != join.left() || right != join.right());
Plan newJoin = join.withChildren(left, right);
+ // top agg
+ // replace
+ // min(x) -> min(min#)
+ // max(x) -> max(max#)
+ // sum(x) -> sum(sum#)
List<NamedExpression> newOutputExprs = new ArrayList<>();
for (NamedExpression ne : agg.getOutputExpressions()) {
if (ne instanceof Alias && ((Alias) ne).child() instanceof AggregateFunction) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoin.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoin.java
index 91cb2a6050b..e8987e670a5 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoin.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoin.java
@@ -53,12 +53,12 @@ import java.util.Set;
* | *
* (x)
* ->
- * aggregate: Sum(min1)
+ * aggregate: Sum(sum1)
* |
* join
* | \
* | *
- * aggregate: Sum(x) as min1
+ * aggregate: Sum(x) as sum1
* </pre>
*/
public class PushDownSumThroughJoin implements RewriteRuleFactory {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoinOneSide.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoinOneSide.java
index 3f4fa09cd71..88b13b383a3 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoinOneSide.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownSumThroughJoinOneSide.java
@@ -19,9 +19,6 @@ package org.apache.doris.nereids.rules.rewrite;
import org.apache.doris.nereids.rules.Rule;
import org.apache.doris.nereids.rules.RuleType;
-import org.apache.doris.nereids.trees.expressions.Alias;
-import org.apache.doris.nereids.trees.expressions.Expression;
-import org.apache.doris.nereids.trees.expressions.NamedExpression;
import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction;
import org.apache.doris.nereids.trees.expressions.functions.agg.Sum;
@@ -30,15 +27,9 @@ import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
-import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Set;
/**
@@ -79,7 +70,7 @@ public class PushDownSumThroughJoinOneSide implements RewriteRuleFactory {
return null;
}
LogicalAggregate<LogicalJoin<Plan, Plan>> agg = ctx.root;
- return pushSum(agg, agg.child(), ImmutableList.of());
+ return PushDownMinMaxThroughJoin.pushMinMaxSum(agg, agg.child(), ImmutableList.of());
})
.toRule(RuleType.PUSH_DOWN_SUM_THROUGH_JOIN),
logicalAggregate(logicalProject(innerLogicalJoin()))
@@ -98,112 +89,10 @@ public class PushDownSumThroughJoinOneSide implements RewriteRuleFactory {
return null;
}
LogicalAggregate<LogicalProject<LogicalJoin<Plan, Plan>>> agg = ctx.root;
- return pushSum(agg, agg.child().child(), agg.child().getProjects());
+ return PushDownMinMaxThroughJoin.pushMinMaxSum(agg, agg.child().child(),
+ agg.child().getProjects());
})
.toRule(RuleType.PUSH_DOWN_SUM_THROUGH_JOIN)
);
}
-
- private LogicalAggregate<Plan> pushSum(LogicalAggregate<? extends Plan> agg,
- LogicalJoin<Plan, Plan> join, List<NamedExpression> projects) {
- List<Slot> leftOutput = join.left().getOutput();
- List<Slot> rightOutput = join.right().getOutput();
-
- List<Sum> leftSums = new ArrayList<>();
- List<Sum> rightSums = new ArrayList<>();
- for (AggregateFunction f : agg.getAggregateFunctions()) {
- Sum sum = (Sum) f;
- Slot slot = (Slot) sum.child();
- if (leftOutput.contains(slot)) {
- leftSums.add(sum);
- } else if (rightOutput.contains(slot)) {
- rightSums.add(sum);
- } else {
- throw new IllegalStateException("Slot " + slot + " not found in join output");
- }
- }
- if (leftSums.isEmpty() && rightSums.isEmpty()) {
- return null;
- }
-
- Set<Slot> leftGroupBy = new HashSet<>();
- Set<Slot> rightGroupBy = new HashSet<>();
- for (Expression e : agg.getGroupByExpressions()) {
- Slot slot = (Slot) e;
- if (leftOutput.contains(slot)) {
- leftGroupBy.add(slot);
- } else if (rightOutput.contains(slot)) {
- rightGroupBy.add(slot);
- } else {
- return null;
- }
- }
- join.getHashJoinConjuncts().forEach(e -> e.getInputSlots().forEach(slot -> {
- if (leftOutput.contains(slot)) {
- leftGroupBy.add(slot);
- } else if (rightOutput.contains(slot)) {
- rightGroupBy.add(slot);
- } else {
- throw new IllegalStateException("Slot " + slot + " not found in join output");
- }
- }));
-
- Plan left = join.left();
- Plan right = join.right();
-
- Map<Slot, NamedExpression> leftSumSlotToOutput = new HashMap<>();
- Map<Slot, NamedExpression> rightSumSlotToOutput = new HashMap<>();
-
- // left Sum agg
- if (!leftSums.isEmpty()) {
- Builder<NamedExpression> leftSumAggOutputBuilder = ImmutableList.<NamedExpression>builder()
- .addAll(leftGroupBy);
- leftSums.forEach(func -> {
- Alias alias = func.alias(func.getName());
- leftSumSlotToOutput.put((Slot) func.child(0), alias);
- leftSumAggOutputBuilder.add(alias);
- });
- left = new LogicalAggregate<>(ImmutableList.copyOf(leftGroupBy), leftSumAggOutputBuilder.build(),
- join.left());
- }
-
- // right Sum agg
- if (!rightSums.isEmpty()) {
- Builder<NamedExpression> rightSumAggOutputBuilder = ImmutableList.<NamedExpression>builder()
- .addAll(rightGroupBy);
- rightSums.forEach(func -> {
- Alias alias = func.alias(func.getName());
- rightSumSlotToOutput.put((Slot) func.child(0), alias);
- rightSumAggOutputBuilder.add(alias);
- });
- right = new LogicalAggregate<>(ImmutableList.copyOf(rightGroupBy), rightSumAggOutputBuilder.build(),
- join.right());
- }
-
- Preconditions.checkState(left != join.left() || right != join.right());
- Plan newJoin = join.withChildren(left, right);
-
- // top Sum agg
- // replace sum(x) -> sum(sum#)
- List<NamedExpression> newOutputExprs = new ArrayList<>();
- for (NamedExpression ne : agg.getOutputExpressions()) {
- if (ne instanceof Alias && ((Alias) ne).child() instanceof Sum) {
- Sum oldTopSum = (Sum) ((Alias) ne).child();
-
- Slot slot = (Slot) oldTopSum.child(0);
- if (leftSumSlotToOutput.containsKey(slot)) {
- Expression expr = new Sum(leftSumSlotToOutput.get(slot).toSlot());
- newOutputExprs.add((NamedExpression) ne.withChildren(expr));
- } else if (rightSumSlotToOutput.containsKey(slot)) {
- Expression expr = new Sum(rightSumSlotToOutput.get(slot).toSlot());
- newOutputExprs.add((NamedExpression) ne.withChildren(expr));
- } else {
- throw new IllegalStateException("Slot " + slot + " not found in join output");
- }
- } else {
- newOutputExprs.add(ne);
- }
- }
- return agg.withAggOutputChild(newOutputExprs, newJoin);
- }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 42/43: [fix](mtmv)return MTMV with at least one available partition #30156
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit 510d88f31505e964a49b7701358fa0302fb78cf3
Author: zhangdong <49...@qq.com>
AuthorDate: Mon Jan 22 20:42:25 2024 +0800
[fix](mtmv)return MTMV with at least one available partition #30156
---
.../org/apache/doris/mtmv/MTMVRelationManager.java | 21 ++++++++++++++++-----
.../mv/InitMaterializationContextHook.java | 2 +-
2 files changed, 17 insertions(+), 6 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVRelationManager.java b/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVRelationManager.java
index 35bf777acb5..77414e4fc88 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVRelationManager.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVRelationManager.java
@@ -33,6 +33,7 @@ import org.apache.doris.nereids.trees.plans.commands.info.RefreshMTMVInfo;
import org.apache.doris.nereids.trees.plans.commands.info.ResumeMTMVInfo;
import org.apache.doris.nereids.trees.plans.commands.info.TableNameInfo;
import org.apache.doris.persist.AlterMTMV;
+import org.apache.doris.qe.ConnectContext;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
@@ -53,16 +54,26 @@ public class MTMVRelationManager implements MTMVHookService {
private static final Logger LOG = LogManager.getLogger(MTMVRelationManager.class);
private Map<BaseTableInfo, Set<BaseTableInfo>> tableMTMVs = Maps.newConcurrentMap();
- public Set<BaseTableInfo> getMtmvsByBaseTable(BaseTableInfo table) {
+ private Set<BaseTableInfo> getMtmvsByBaseTable(BaseTableInfo table) {
return tableMTMVs.getOrDefault(table, ImmutableSet.of());
}
- public Set<MTMV> getAvailableMTMVs(List<BaseTableInfo> tableInfos) {
+ /**
+ * if At least one partition is available, return this mtmv
+ *
+ * @param tableInfos
+ * @param ctx
+ * @return
+ */
+ public Set<MTMV> getAvailableMTMVs(List<BaseTableInfo> tableInfos, ConnectContext ctx) {
Set<MTMV> res = Sets.newHashSet();
- Set<BaseTableInfo> mvInfos = getAvailableMTMVInfos(tableInfos);
+ Set<BaseTableInfo> mvInfos = getMTMVInfos(tableInfos);
for (BaseTableInfo tableInfo : mvInfos) {
try {
- res.add((MTMV) MTMVUtil.getTable(tableInfo));
+ MTMV mtmv = (MTMV) MTMVUtil.getTable(tableInfo);
+ if (!CollectionUtils.isEmpty(MTMVUtil.getMTMVCanRewritePartitions(mtmv, ctx))) {
+ res.add(mtmv);
+ }
} catch (AnalysisException e) {
// not throw exception to client, just ignore it
LOG.warn("getTable failed: {}", tableInfo.toString(), e);
@@ -71,7 +82,7 @@ public class MTMVRelationManager implements MTMVHookService {
return res;
}
- public Set<BaseTableInfo> getAvailableMTMVInfos(List<BaseTableInfo> tableInfos) {
+ private Set<BaseTableInfo> getMTMVInfos(List<BaseTableInfo> tableInfos) {
Set<BaseTableInfo> mvInfos = Sets.newHashSet();
for (BaseTableInfo tableInfo : tableInfos) {
mvInfos.addAll(getMtmvsByBaseTable(tableInfo));
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/InitMaterializationContextHook.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/InitMaterializationContextHook.java
index 07a4ff208bc..baf714fe280 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/InitMaterializationContextHook.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/InitMaterializationContextHook.java
@@ -70,7 +70,7 @@ public class InitMaterializationContextHook implements PlannerHook {
List<BaseTableInfo> usedBaseTables =
collectedTables.stream().map(BaseTableInfo::new).collect(Collectors.toList());
Set<MTMV> availableMTMVs = Env.getCurrentEnv().getMtmvService().getRelationManager()
- .getAvailableMTMVs(usedBaseTables);
+ .getAvailableMTMVs(usedBaseTables, cascadesContext.getConnectContext());
if (availableMTMVs.isEmpty()) {
return;
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 20/43: [fix](routine-load) optimize error msg when meet out of range (#30118)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit d0dd0904586bc72213955f1b6a599c6514a169f4
Author: HHoflittlefish777 <77...@users.noreply.github.com>
AuthorDate: Mon Jan 22 13:15:46 2024 +0800
[fix](routine-load) optimize error msg when meet out of range (#30118)
---
.../org/apache/doris/load/routineload/RoutineLoadJob.java | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
index 0a947701ef5..889d240ce29 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
@@ -1142,11 +1142,24 @@ public abstract class RoutineLoadJob extends AbstractTxnStateChangeCallback impl
if (txnStatusChangeReasonString != null) {
txnStatusChangeReason =
TransactionState.TxnStatusChangeReason.fromString(txnStatusChangeReasonString);
+ String msg;
if (txnStatusChangeReason != null) {
switch (txnStatusChangeReason) {
case OFFSET_OUT_OF_RANGE:
+ msg = "be " + taskBeId + " abort task,"
+ + " task id: " + routineLoadTaskInfo.getId()
+ + " job id: " + routineLoadTaskInfo.getJobId()
+ + " with reason: " + txnStatusChangeReasonString
+ + " the offset used by job does not exist in kafka,"
+ + " please check the offset,"
+ + " using the Alter ROUTINE LOAD command to modify it,"
+ + " and resume the job";
+ updateState(JobState.PAUSED,
+ new ErrorReason(InternalErrorCode.TASKS_ABORT_ERR, msg),
+ false /* not replay */);
+ return;
case PAUSE:
- String msg = "be " + taskBeId + " abort task "
+ msg = "be " + taskBeId + " abort task "
+ "with reason: " + txnStatusChangeReasonString;
updateState(JobState.PAUSED,
new ErrorReason(InternalErrorCode.TASKS_ABORT_ERR, msg),
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org
(doris) 10/43: [Bug](fix) try to fix the coredump of streambyte decode of sse (#30190)
Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-2.1
in repository https://gitbox.apache.org/repos/asf/doris.git
commit a9ab094614109630d1098a3384b5a9b9949ccad3
Author: HappenLee <ha...@hotmail.com>
AuthorDate: Sun Jan 21 10:54:47 2024 +0800
[Bug](fix) try to fix the coredump of streambyte decode of sse (#30190)
---
be/src/vec/core/block.cpp | 3 ++-
be/src/vec/data_types/data_type_decimal.cpp | 2 --
2 files changed, 2 insertions(+), 3 deletions(-)
diff --git a/be/src/vec/core/block.cpp b/be/src/vec/core/block.cpp
index e3ce4885cb0..dc9c90a3397 100644
--- a/be/src/vec/core/block.cpp
+++ b/be/src/vec/core/block.cpp
@@ -23,6 +23,7 @@
#include <fmt/format.h>
#include <gen_cpp/data.pb.h>
#include <snappy.h>
+#include <streamvbyte.h>
#include <sys/types.h>
#include <algorithm>
@@ -869,7 +870,7 @@ Status Block::serialize(int be_exec_version, PBlock* pblock,
*uncompressed_bytes = content_uncompressed_size;
const size_t serialize_bytes = buf - column_values.data();
*compressed_bytes = serialize_bytes;
- column_values.resize(serialize_bytes);
+ column_values.resize(serialize_bytes + STREAMVBYTE_PADDING);
// compress
if (compression_type != segment_v2::NO_COMPRESSION && content_uncompressed_size > 0) {
diff --git a/be/src/vec/data_types/data_type_decimal.cpp b/be/src/vec/data_types/data_type_decimal.cpp
index 4e4c7ddd819..0573a17729e 100644
--- a/be/src/vec/data_types/data_type_decimal.cpp
+++ b/be/src/vec/data_types/data_type_decimal.cpp
@@ -25,8 +25,6 @@
#include <streamvbyte.h>
#include <string.h>
-#include <utility>
-
#include "runtime/decimalv2_value.h"
#include "util/string_parser.hpp"
#include "vec/columns/column.h"
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org