Coverage Report

Created: 2026-07-13 04:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/point_query_executor.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "service/point_query_executor.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/Exprs_types.h>
23
#include <gen_cpp/PaloInternalService_types.h>
24
#include <gen_cpp/internal_service.pb.h>
25
#include <glog/logging.h>
26
#include <google/protobuf/extension_set.h>
27
#include <stdlib.h>
28
29
#include <memory>
30
#include <unordered_map>
31
#include <vector>
32
33
#include "cloud/cloud_tablet.h"
34
#include "cloud/config.h"
35
#include "common/cast_set.h"
36
#include "common/consts.h"
37
#include "common/status.h"
38
#include "core/data_type/data_type_factory.hpp"
39
#include "core/data_type_serde/data_type_serde.h"
40
#include "exec/sink/writer/vmysql_result_writer.h"
41
#include "exprs/vexpr.h"
42
#include "exprs/vexpr_context.h"
43
#include "exprs/vexpr_fwd.h"
44
#include "exprs/vslot_ref.h"
45
#include "io/cache/remote_scan_cache_write_limiter.h"
46
#include "io/io_common.h"
47
#include "runtime/descriptors.h"
48
#include "runtime/exec_env.h"
49
#include "runtime/result_block_buffer.h"
50
#include "runtime/runtime_profile.h"
51
#include "runtime/runtime_state.h"
52
#include "runtime/thread_context.h"
53
#include "storage/row_cursor.h"
54
#include "storage/rowset/beta_rowset.h"
55
#include "storage/rowset/rowset_fwd.h"
56
#include "storage/segment/column_reader.h"
57
#include "storage/tablet/tablet_schema.h"
58
#include "storage/utils.h"
59
#include "util/defer_op.h"
60
#include "util/jsonb/serialize.h"
61
#include "util/lru_cache.h"
62
#include "util/simd/bits.h"
63
#include "util/thrift_util.h"
64
65
namespace doris {
66
67
class PointQueryResultBlockBuffer final : public MySQLResultBlockBuffer {
68
public:
69
0
    PointQueryResultBlockBuffer(RuntimeState* state) : MySQLResultBlockBuffer(state) {}
70
0
    ~PointQueryResultBlockBuffer() override = default;
71
0
    std::shared_ptr<TFetchDataResult> get_block() {
72
0
        std::lock_guard<std::mutex> l(_lock);
73
0
        DCHECK_EQ(_result_batch_queue.size(), 1);
74
0
        auto result = std::move(_result_batch_queue.front());
75
0
        _result_batch_queue.pop_front();
76
0
        return result;
77
0
    }
78
};
79
80
4.09k
Reusable::~Reusable() = default;
81
82
// get missing and include column ids
83
// input include_cids : the output expr slots columns unique ids
84
// missing_cids : the output expr columns that not in row columns cids
85
static void get_missing_and_include_cids(const TabletSchema& schema,
86
                                         const std::vector<SlotDescriptor*>& slots,
87
                                         int target_rs_column_id,
88
                                         std::unordered_set<int>& missing_cids,
89
4.04k
                                         std::unordered_set<int>& include_cids) {
90
4.04k
    missing_cids.clear();
91
4.04k
    include_cids.clear();
92
4.04k
    for (auto* slot : slots) {
93
4.04k
        missing_cids.insert(slot->col_unique_id());
94
4.04k
    }
95
    // insert delete sign column id
96
4.04k
    missing_cids.insert(schema.columns()[schema.delete_sign_idx()]->unique_id());
97
4.04k
    if (target_rs_column_id == -1) {
98
        // no row store columns
99
4.04k
        return;
100
4.04k
    }
101
0
    const TabletColumn& target_rs_column = schema.column_by_uid(target_rs_column_id);
102
0
    DCHECK(target_rs_column.is_row_store_column());
103
    // The full column group is considered a full match, thus no missing cids
104
0
    if (schema.row_columns_uids().empty()) {
105
0
        missing_cids.clear();
106
0
        return;
107
0
    }
108
0
    for (int cid : schema.row_columns_uids()) {
109
0
        missing_cids.erase(cid);
110
0
        include_cids.insert(cid);
111
0
    }
112
0
}
113
114
constexpr static int s_preallocted_blocks_num = 32;
115
116
static void extract_slot_ref(const VExprSPtr& expr, TupleDescriptor* tuple_desc,
117
4.04k
                             std::vector<SlotDescriptor*>& slots) {
118
4.04k
    const auto& children = expr->children();
119
4.04k
    for (const auto& i : children) {
120
0
        extract_slot_ref(i, tuple_desc, slots);
121
0
    }
122
123
4.04k
    auto node_type = expr->node_type();
124
4.04k
    if (node_type == TExprNodeType::SLOT_REF) {
125
4.04k
        int column_id = static_cast<const VSlotRef*>(expr.get())->column_id();
126
4.04k
        auto* slot_desc = tuple_desc->slots()[column_id];
127
4.04k
        slots.push_back(slot_desc);
128
4.04k
    }
129
4.04k
}
130
131
Status Reusable::init(const TDescriptorTable& t_desc_tbl, const std::vector<TExpr>& output_exprs,
132
                      const TQueryOptions& query_options, const TabletSchema& schema,
133
4.04k
                      size_t block_size) {
134
4.04k
    _runtime_state = RuntimeState::create_unique();
135
4.04k
    _runtime_state->set_query_options(query_options);
136
4.04k
    RETURN_IF_ERROR(DescriptorTbl::create(_runtime_state->obj_pool(), t_desc_tbl, &_desc_tbl));
137
4.04k
    _runtime_state->set_desc_tbl(_desc_tbl);
138
89.0k
    for (const auto* slot : tuple_desc()->slots()) {
139
89.0k
        if (!slot->all_access_paths().empty() || !slot->predicate_access_paths().empty()) {
140
0
            return Status::InternalError(
141
0
                    "Short-circuit point query does not support nested column access paths, "
142
0
                    "slot: {}. Please upgrade FE to disable nested column pruning for "
143
0
                    "short-circuit point queries.",
144
0
                    slot->col_name());
145
0
        }
146
89.0k
    }
147
4.04k
    _block_pool.resize(block_size);
148
8.09k
    for (auto& i : _block_pool) {
149
8.09k
        i = Block::create_unique(tuple_desc()->slots(), 2);
150
        // Name is useless but cost space
151
8.09k
        i->clear_names();
152
8.09k
    }
153
154
4.04k
    RETURN_IF_ERROR(VExpr::create_expr_trees(output_exprs, _output_exprs_ctxs));
155
4.04k
    RowDescriptor row_desc(tuple_desc());
156
    // Prepare the exprs to run.
157
4.04k
    RETURN_IF_ERROR(VExpr::prepare(_output_exprs_ctxs, _runtime_state.get(), row_desc));
158
4.04k
    RETURN_IF_ERROR(VExpr::open(_output_exprs_ctxs, _runtime_state.get()));
159
4.04k
    _create_timestamp = butil::gettimeofday_ms();
160
4.04k
    _data_type_serdes = create_data_type_serdes(tuple_desc()->slots());
161
4.04k
    _col_default_values.resize(tuple_desc()->slots().size());
162
4.04k
    bool has_delete_sign = false;
163
93.0k
    for (int i = 0; i < tuple_desc()->slots().size(); ++i) {
164
89.0k
        auto* slot = tuple_desc()->slots()[i];
165
89.0k
        if (slot->col_name() == DELETE_SIGN) {
166
0
            has_delete_sign = true;
167
0
        }
168
89.0k
        _col_uid_to_idx[slot->col_unique_id()] = i;
169
89.0k
        _col_default_values[i] = slot->col_default_value();
170
89.0k
    }
171
172
    // Get the output slot descriptors
173
4.04k
    std::vector<SlotDescriptor*> output_slot_descs;
174
4.04k
    for (const auto& expr : _output_exprs_ctxs) {
175
4.04k
        extract_slot_ref(expr->root(), tuple_desc(), output_slot_descs);
176
4.04k
    }
177
178
    // get the delete sign idx in block
179
4.04k
    if (has_delete_sign) {
180
0
        _delete_sign_idx = _col_uid_to_idx[schema.columns()[schema.delete_sign_idx()]->unique_id()];
181
0
    }
182
183
4.04k
    if (schema.have_column(BeConsts::ROW_STORE_COL)) {
184
0
        const auto& column = *DORIS_TRY(schema.column(BeConsts::ROW_STORE_COL));
185
0
        _row_store_column_ids = column.unique_id();
186
0
    }
187
4.04k
    get_missing_and_include_cids(schema, output_slot_descs, _row_store_column_ids,
188
4.04k
                                 _missing_col_uids, _include_col_uids);
189
190
4.04k
    return Status::OK();
191
4.04k
}
192
193
0
std::unique_ptr<Block> Reusable::get_block() {
194
0
    std::lock_guard lock(_block_mutex);
195
0
    if (_block_pool.empty()) {
196
0
        auto block = Block::create_unique(tuple_desc()->slots(), 2);
197
        // Name is useless but cost space
198
0
        block->clear_names();
199
0
        return block;
200
0
    }
201
0
    auto block = std::move(_block_pool.back());
202
0
    CHECK(block != nullptr);
203
0
    _block_pool.pop_back();
204
0
    return block;
205
0
}
206
207
0
void Reusable::return_block(std::unique_ptr<Block>& block) {
208
0
    std::lock_guard lock(_block_mutex);
209
0
    if (block == nullptr) {
210
0
        return;
211
0
    }
212
0
    block->clear_column_data();
213
0
    _block_pool.push_back(std::move(block));
214
0
    if (_block_pool.size() > s_preallocted_blocks_num) {
215
0
        _block_pool.resize(s_preallocted_blocks_num);
216
0
    }
217
0
}
218
219
0
LookupConnectionCache* LookupConnectionCache::create_global_instance(size_t capacity) {
220
0
    DCHECK(ExecEnv::GetInstance()->get_lookup_connection_cache() == nullptr);
221
0
    auto* res = new LookupConnectionCache(capacity);
222
0
    return res;
223
0
}
224
225
RowCache::RowCache(int64_t capacity, int num_shards)
226
3
        : LRUCachePolicy(CachePolicy::CacheType::POINT_QUERY_ROW_CACHE, capacity,
227
3
                         LRUCacheType::SIZE, config::point_query_row_cache_stale_sweep_time_sec,
228
3
                         num_shards, /*element count capacity */ 0,
229
3
                         /*enable prune*/ true, /*is lru-k*/ true) {}
230
231
// Create global instance of this class
232
0
RowCache* RowCache::create_global_cache(int64_t capacity, uint32_t num_shards) {
233
0
    DCHECK(ExecEnv::GetInstance()->get_row_cache() == nullptr);
234
0
    auto* res = new RowCache(capacity, num_shards);
235
0
    return res;
236
0
}
237
238
0
RowCache* RowCache::instance() {
239
0
    return ExecEnv::GetInstance()->get_row_cache();
240
0
}
241
242
4
bool RowCache::lookup(const RowCacheKey& key, CacheHandle* handle) {
243
4
    const std::string& encoded_key = key.encode();
244
4
    auto* lru_handle = LRUCachePolicy::lookup(encoded_key);
245
4
    if (!lru_handle) {
246
        // cache miss
247
3
        return false;
248
3
    }
249
1
    *handle = CacheHandle(this, lru_handle);
250
1
    return true;
251
4
}
252
253
11
void RowCache::insert(const RowCacheKey& key, const Slice& value) {
254
11
    char* cache_value = static_cast<char*>(malloc(value.size));
255
11
    memcpy(cache_value, value.data, value.size);
256
11
    auto* row_cache_value = new RowCacheValue;
257
11
    row_cache_value->cache_value = cache_value;
258
11
    const std::string& encoded_key = key.encode();
259
11
    auto* handle = LRUCachePolicy::insert(encoded_key, row_cache_value, value.size, value.size,
260
11
                                          CachePriority::NORMAL);
261
    // handle will released
262
11
    auto tmp = CacheHandle {this, handle};
263
11
}
264
265
1
void RowCache::erase(const RowCacheKey& key) {
266
1
    const std::string& encoded_key = key.encode();
267
1
    LRUCachePolicy::erase(encoded_key);
268
1
}
269
270
2.09k
LookupConnectionCache::CacheValue::~CacheValue() {
271
2.09k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
272
2.09k
            ExecEnv::GetInstance()->point_query_executor_mem_tracker());
273
2.09k
    item.reset();
274
2.09k
}
275
276
0
PointQueryExecutor::~PointQueryExecutor() {
277
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
278
0
            ExecEnv::GetInstance()->point_query_executor_mem_tracker());
279
0
    _tablet.reset();
280
0
    _reusable.reset();
281
0
    _result_block.reset();
282
0
    _row_read_ctxs.clear();
283
0
}
284
285
0
void PointQueryExecutor::_init_remote_scan_cache_write_limiter() {
286
0
    const auto& query_options = _reusable->runtime_state()->query_options();
287
0
    const bool initialize_remote_scan_cache_write_limiter =
288
0
            config::is_cloud_mode() && config::enable_file_cache &&
289
0
            query_options.__isset.file_cache_query_limit_bytes &&
290
0
            query_options.file_cache_query_limit_bytes >= 0 &&
291
0
            query_options.query_type == TQueryType::SELECT;
292
0
    if (initialize_remote_scan_cache_write_limiter) {
293
0
        _remote_scan_cache_write_limiter = std::make_unique<io::RemoteScanCacheWriteLimiter>(
294
0
                _reusable->runtime_state()->query_id(), query_options.file_cache_query_limit_bytes);
295
0
    }
296
0
}
297
298
Status PointQueryExecutor::init(const PTabletKeyLookupRequest* request,
299
0
                                PTabletKeyLookupResponse* response) {
300
0
    SCOPED_TIMER(&_profile_metrics.init_ns);
301
0
    _response = response;
302
    // using cache
303
0
    __int128_t uuid =
304
0
            static_cast<__int128_t>(request->uuid().uuid_high()) << 64 | request->uuid().uuid_low();
305
0
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->point_query_executor_mem_tracker());
306
0
    auto cache_handle = LookupConnectionCache::instance()->get(uuid);
307
0
    _binary_row_format = request->is_binary_row();
308
0
    _tablet = DORIS_TRY(ExecEnv::get_tablet(request->tablet_id()));
309
0
    if (cache_handle != nullptr) {
310
0
        _reusable = cache_handle;
311
0
        _profile_metrics.hit_lookup_cache = true;
312
0
    } else {
313
        // Lightweight request: FE may omit reusable query context and rely on uuid cache.
314
        // If cache miss and required parameters are absent, ask FE to resend a full request.
315
0
        if (uuid != 0 && (!request->has_desc_tbl() || request->desc_tbl().empty() ||
316
0
                          !request->has_output_expr() || request->output_expr().empty() ||
317
0
                          !request->has_query_options() || request->query_options().empty())) {
318
0
            if (VLOG_DEBUG_IS_ON) {
319
0
                VLOG_DEBUG << "lookup connection cache miss, ask FE to resend query context"
320
0
                           << ", tablet_id=" << request->tablet_id()
321
0
                           << ", uuid_high=" << request->uuid().uuid_high()
322
0
                           << ", uuid_low=" << request->uuid().uuid_low();
323
0
            }
324
0
            response->set_need_resend_query_context(true);
325
0
            return Status::OK();
326
0
        }
327
0
        if (uuid == 0 && (!request->has_desc_tbl() || request->desc_tbl().empty() ||
328
0
                          !request->has_output_expr() || request->output_expr().empty())) {
329
0
            return Status::InvalidArgument(
330
0
                    "tablet_fetch_data requires desc_tbl/output_expr when uuid is not set");
331
0
        }
332
        // init handle
333
0
        auto reusable_ptr = std::make_shared<Reusable>();
334
0
        TDescriptorTable t_desc_tbl;
335
0
        TExprList t_output_exprs;
336
0
        auto len = cast_set<uint32_t>(request->desc_tbl().size());
337
0
        RETURN_IF_ERROR(
338
0
                deserialize_thrift_msg(reinterpret_cast<const uint8_t*>(request->desc_tbl().data()),
339
0
                                       &len, false, &t_desc_tbl));
340
0
        len = cast_set<uint32_t>(request->output_expr().size());
341
0
        RETURN_IF_ERROR(deserialize_thrift_msg(
342
0
                reinterpret_cast<const uint8_t*>(request->output_expr().data()), &len, false,
343
0
                &t_output_exprs));
344
0
        _reusable = reusable_ptr;
345
0
        TQueryOptions t_query_options;
346
0
        len = cast_set<uint32_t>(request->query_options().size());
347
0
        if (request->has_query_options()) {
348
0
            RETURN_IF_ERROR(deserialize_thrift_msg(
349
0
                    reinterpret_cast<const uint8_t*>(request->query_options().data()), &len, false,
350
0
                    &t_query_options));
351
0
        }
352
0
        if (uuid != 0) {
353
            // could be reused by requests after, pre allocte more blocks
354
0
            RETURN_IF_ERROR(reusable_ptr->init(t_desc_tbl, t_output_exprs.exprs, t_query_options,
355
0
                                               *_tablet->tablet_schema(),
356
0
                                               s_preallocted_blocks_num));
357
0
            LookupConnectionCache::instance()->add(uuid, reusable_ptr);
358
0
        } else {
359
0
            RETURN_IF_ERROR(reusable_ptr->init(t_desc_tbl, t_output_exprs.exprs, t_query_options,
360
0
                                               *_tablet->tablet_schema(), 1));
361
0
        }
362
0
    }
363
0
    _init_remote_scan_cache_write_limiter();
364
    // Set timezone from request for functions like from_unixtime()
365
0
    if (request->has_time_zone() && !request->time_zone().empty()) {
366
0
        _reusable->runtime_state()->set_timezone(request->time_zone());
367
0
    }
368
0
    if (request->has_version() && request->version() >= 0) {
369
0
        _version = request->version();
370
0
    }
371
0
    RETURN_IF_ERROR(_init_keys(request));
372
0
    _result_block = _reusable->get_block();
373
0
    CHECK(_result_block != nullptr);
374
375
0
    return Status::OK();
376
0
}
377
378
0
Status PointQueryExecutor::lookup_up() {
379
0
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->point_query_executor_mem_tracker());
380
0
    RETURN_IF_ERROR(_lookup_row_key());
381
0
    RETURN_IF_ERROR(_lookup_row_data());
382
0
    RETURN_IF_ERROR(_output_data());
383
0
    return Status::OK();
384
0
}
385
386
0
void PointQueryExecutor::print_profile() {
387
0
    auto init_us = _profile_metrics.init_ns.value() / 1000;
388
0
    auto init_key_us = _profile_metrics.init_key_ns.value() / 1000;
389
0
    auto lookup_key_us = _profile_metrics.lookup_key_ns.value() / 1000;
390
0
    auto lookup_data_us = _profile_metrics.lookup_data_ns.value() / 1000;
391
0
    auto output_data_us = _profile_metrics.output_data_ns.value() / 1000;
392
0
    auto load_segments_key_us = _profile_metrics.load_segment_key_stage_ns.value() / 1000;
393
0
    auto load_segments_data_us = _profile_metrics.load_segment_data_stage_ns.value() / 1000;
394
0
    auto total_us = init_us + lookup_key_us + lookup_data_us + output_data_us;
395
0
    auto read_stats = _profile_metrics.read_stats;
396
0
    const std::string stats_str = fmt::format(
397
0
            "[lookup profile:{}us] init:{}us, init_key:{}us,"
398
0
            " lookup_key:{}us, load_segments_key:{}us, lookup_data:{}us, load_segments_data:{}us,"
399
0
            " output_data:{}us, "
400
0
            "hit_lookup_cache:{}"
401
0
            ", is_binary_row:{}, output_columns:{}, total_keys:{}, row_cache_hits:{}"
402
0
            ", hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
403
0
            "io_latency:{}ns, "
404
0
            "uncompressed_bytes_read:{}, result_data_bytes:{}, row_hits:{}"
405
0
            ", rs_column_uid:{}, bytes_read_from_local:{}, bytes_read_from_remote:{}, "
406
0
            "local_io_timer:{}, remote_io_timer:{}, local_write_timer:{}",
407
0
            total_us, init_us, init_key_us, lookup_key_us, load_segments_key_us, lookup_data_us,
408
0
            load_segments_data_us, output_data_us, _profile_metrics.hit_lookup_cache,
409
0
            _binary_row_format, _reusable->output_exprs().size(), _row_read_ctxs.size(),
410
0
            _profile_metrics.row_cache_hits, read_stats.cached_pages_num,
411
0
            read_stats.total_pages_num, read_stats.compressed_bytes_read, read_stats.io_ns,
412
0
            read_stats.uncompressed_bytes_read, _profile_metrics.result_data_bytes, _row_hits,
413
0
            _reusable->rs_column_uid(),
414
0
            _profile_metrics.read_stats.file_cache_stats.bytes_read_from_local,
415
0
            _profile_metrics.read_stats.file_cache_stats.bytes_read_from_remote,
416
0
            _profile_metrics.read_stats.file_cache_stats.local_io_timer,
417
0
            _profile_metrics.read_stats.file_cache_stats.remote_io_timer,
418
0
            _profile_metrics.read_stats.file_cache_stats.write_cache_io_timer);
419
420
0
    constexpr static int kSlowThreholdUs = 50 * 1000; // 50ms
421
0
    if (total_us > kSlowThreholdUs) {
422
0
        LOG(WARNING) << "slow query, " << stats_str;
423
0
    } else if (VLOG_DEBUG_IS_ON) {
424
0
        VLOG_DEBUG << stats_str;
425
0
    } else {
426
0
        LOG_EVERY_N(INFO, 1000) << stats_str;
427
0
    }
428
0
}
429
430
0
Status PointQueryExecutor::_init_keys(const PTabletKeyLookupRequest* request) {
431
0
    SCOPED_TIMER(&_profile_metrics.init_key_ns);
432
0
    const auto& schema = _tablet->tablet_schema();
433
    // Point query is only supported on merge-on-write unique key tables.
434
0
    DCHECK(schema->keys_type() == UNIQUE_KEYS && _tablet->enable_unique_key_merge_on_write());
435
0
    if (schema->keys_type() != UNIQUE_KEYS || !_tablet->enable_unique_key_merge_on_write()) {
436
0
        return Status::InvalidArgument(
437
0
                "Point query is only supported on merge-on-write unique key tables, "
438
0
                "tablet_id={}",
439
0
                _tablet->tablet_id());
440
0
    }
441
    // 1. get primary key from conditions
442
0
    _row_read_ctxs.resize(request->key_tuples().size());
443
    // get row cursor and encode keys
444
0
    for (int i = 0; i < request->key_tuples().size(); ++i) {
445
0
        const KeyTuple& key_tuple = request->key_tuples(i);
446
0
        if (UNLIKELY(cast_set<size_t>(key_tuple.key_column_literals_size()) !=
447
0
                     schema->num_key_columns())) {
448
0
            return Status::InvalidArgument(
449
0
                    "Key column count mismatch. expected={}, actual={}, tablet_id={}",
450
0
                    schema->num_key_columns(), key_tuple.key_column_literals_size(),
451
0
                    _tablet->tablet_id());
452
0
        }
453
0
        RowCursor cursor;
454
0
        std::vector<Field> key_fields;
455
0
        key_fields.reserve(key_tuple.key_column_literals_size());
456
0
        for (int j = 0; j < key_tuple.key_column_literals_size(); ++j) {
457
0
            const auto& literal_bytes = key_tuple.key_column_literals(j);
458
0
            TExprNode expr_node;
459
0
            auto len = cast_set<uint32_t>(literal_bytes.size());
460
0
            RETURN_IF_ERROR(
461
0
                    deserialize_thrift_msg(reinterpret_cast<const uint8_t*>(literal_bytes.data()),
462
0
                                           &len, false, &expr_node));
463
0
            const auto& col = schema->column(j);
464
0
            auto data_type = DataTypeFactory::instance().create_data_type(
465
0
                    col.type(), col.precision(), col.frac(), col.length());
466
0
            key_fields.push_back(data_type->get_field(expr_node));
467
0
        }
468
0
        RETURN_IF_ERROR(cursor.init_scan_key(_tablet->tablet_schema(), std::move(key_fields)));
469
0
        cursor.encode_key_with_padding<true>(&_row_read_ctxs[i]._primary_key,
470
0
                                             _tablet->tablet_schema()->num_key_columns(), true);
471
0
    }
472
0
    return Status::OK();
473
0
}
474
475
0
Status PointQueryExecutor::_lookup_row_key() {
476
0
    SCOPED_TIMER(&_profile_metrics.lookup_key_ns);
477
    // 2. lookup row location
478
0
    Status st;
479
0
    if (_version >= 0) {
480
0
        CHECK(config::is_cloud_mode()) << "Only cloud mode support snapshot read at present";
481
0
        SyncOptions options;
482
0
        options.query_version = _version;
483
0
        RETURN_IF_ERROR(std::dynamic_pointer_cast<CloudTablet>(_tablet)->sync_rowsets(options));
484
0
    }
485
0
    std::vector<RowsetSharedPtr> specified_rowsets;
486
0
    {
487
0
        std::shared_lock rlock(_tablet->get_header_lock());
488
0
        specified_rowsets = _tablet->get_rowset_by_ids(nullptr);
489
0
    }
490
0
    io::IOContext io_ctx;
491
0
    io_ctx.reader_type = ReaderType::READER_QUERY;
492
0
    io_ctx.file_cache_stats = &_profile_metrics.read_stats.file_cache_stats;
493
0
    io_ctx.remote_scan_cache_write_limiter = _remote_scan_cache_write_limiter.get();
494
0
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
495
0
    for (size_t i = 0; i < _row_read_ctxs.size(); ++i) {
496
0
        RowLocation location;
497
0
        if (!config::disable_storage_row_cache) {
498
0
            RowCache::CacheHandle cache_handle;
499
0
            auto hit_cache = RowCache::instance()->lookup(
500
0
                    {_tablet->tablet_id(), _row_read_ctxs[i]._primary_key}, &cache_handle);
501
0
            if (hit_cache) {
502
0
                _row_read_ctxs[i]._cached_row_data = std::move(cache_handle);
503
0
                ++_profile_metrics.row_cache_hits;
504
0
                continue;
505
0
            }
506
0
        }
507
        // Get rowlocation and rowset, ctx._rowset_ptr will acquire wrap this ptr
508
0
        auto rowset_ptr = std::make_unique<RowsetSharedPtr>();
509
0
        st = (_tablet->lookup_row_key(_row_read_ctxs[i]._primary_key, nullptr, false,
510
0
                                      specified_rowsets, &location, INT32_MAX /*rethink?*/,
511
0
                                      segment_caches, rowset_ptr.get(), false, nullptr,
512
0
                                      &_profile_metrics.read_stats, nullptr, &io_ctx));
513
0
        if (st.is<ErrorCode::KEY_NOT_FOUND>()) {
514
0
            continue;
515
0
        }
516
0
        RETURN_IF_ERROR(st);
517
0
        _row_read_ctxs[i]._row_location = location;
518
        // acquire and wrap this rowset
519
0
        (*rowset_ptr)->acquire();
520
0
        VLOG_DEBUG << "aquire rowset " << (*rowset_ptr)->rowset_id();
521
0
        _row_read_ctxs[i]._rowset_ptr = std::unique_ptr<RowsetSharedPtr, decltype(&release_rowset)>(
522
0
                rowset_ptr.release(), &release_rowset);
523
0
        _row_hits++;
524
0
    }
525
0
    return Status::OK();
526
0
}
527
528
0
Status PointQueryExecutor::_lookup_row_data() {
529
    // 3. get values
530
0
    SCOPED_TIMER(&_profile_metrics.lookup_data_ns);
531
0
    {
532
0
        auto result_columns_guard = _result_block->mutate_columns_scoped();
533
0
        MutableColumns& result_columns = result_columns_guard.mutable_columns();
534
0
        for (size_t i = 0; i < _row_read_ctxs.size(); ++i) {
535
0
            if (_row_read_ctxs[i]._cached_row_data.valid()) {
536
0
                RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
537
0
                        _reusable->get_data_type_serdes(),
538
0
                        _row_read_ctxs[i]._cached_row_data.data().data,
539
0
                        _row_read_ctxs[i]._cached_row_data.data().size,
540
0
                        _reusable->get_col_uid_to_idx(), result_columns,
541
0
                        _reusable->get_col_default_values(), _reusable->include_col_uids()));
542
0
                continue;
543
0
            }
544
0
            if (!_row_read_ctxs[i]._row_location.has_value()) {
545
0
                continue;
546
0
            }
547
0
            std::string value;
548
            // fill block by row store
549
0
            if (_reusable->rs_column_uid() != -1) {
550
0
                bool use_row_cache = !config::disable_storage_row_cache;
551
0
                io::IOContext io_ctx;
552
0
                io_ctx.reader_type = ReaderType::READER_QUERY;
553
0
                io_ctx.file_cache_stats = &_profile_metrics.read_stats.file_cache_stats;
554
0
                io_ctx.remote_scan_cache_write_limiter = _remote_scan_cache_write_limiter.get();
555
0
                RETURN_IF_ERROR(_tablet->lookup_row_data(
556
0
                        _row_read_ctxs[i]._primary_key, _row_read_ctxs[i]._row_location.value(),
557
0
                        *(_row_read_ctxs[i]._rowset_ptr), _profile_metrics.read_stats, value,
558
0
                        use_row_cache, &io_ctx));
559
                // serialize value to block, currently only jsonb row format
560
0
                RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
561
0
                        _reusable->get_data_type_serdes(), value.data(), value.size(),
562
0
                        _reusable->get_col_uid_to_idx(), result_columns,
563
0
                        _reusable->get_col_default_values(), _reusable->include_col_uids()));
564
0
            }
565
0
            if (!_reusable->missing_col_uids().empty()) {
566
0
                if (!_reusable->runtime_state()->enable_short_circuit_query_access_column_store()) {
567
0
                    std::string missing_columns;
568
0
                    for (int cid : _reusable->missing_col_uids()) {
569
0
                        missing_columns +=
570
0
                                _tablet->tablet_schema()->column_by_uid(cid).name() + ",";
571
0
                    }
572
0
                    return Status::InternalError(
573
0
                            "Not support column store, set store_row_column=true or "
574
0
                            "row_store_columns in table properties, missing columns: " +
575
0
                            missing_columns + " should be added to row store");
576
0
                }
577
                // fill missing columns by column store
578
0
                RowLocation row_loc = _row_read_ctxs[i]._row_location.value();
579
0
                BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(
580
0
                        _tablet->get_rowset(row_loc.rowset_id));
581
0
                SegmentCacheHandle segment_cache;
582
0
                io::IOContext io_ctx;
583
0
                io_ctx.reader_type = ReaderType::READER_QUERY;
584
0
                io_ctx.file_cache_stats = &_read_stats.file_cache_stats;
585
0
                io_ctx.remote_scan_cache_write_limiter = _remote_scan_cache_write_limiter.get();
586
0
                {
587
0
                    SCOPED_TIMER(&_profile_metrics.load_segment_data_stage_ns);
588
0
                    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
589
0
                            rowset, &segment_cache, true, false, &_read_stats, &io_ctx));
590
0
                }
591
                // find segment
592
0
                auto it = std::find_if(segment_cache.get_segments().cbegin(),
593
0
                                       segment_cache.get_segments().cend(),
594
0
                                       [&](const segment_v2::SegmentSharedPtr& seg) {
595
0
                                           return seg->id() == row_loc.segment_id;
596
0
                                       });
597
0
                const auto& segment = *it;
598
0
                for (int cid : _reusable->missing_col_uids()) {
599
0
                    int pos = _reusable->get_col_uid_to_idx().at(cid);
600
0
                    std::vector<segment_v2::rowid_t> row_ids {
601
0
                            static_cast<segment_v2::rowid_t>(row_loc.row_id)};
602
0
                    auto& column = result_columns[pos];
603
0
                    std::unique_ptr<ColumnIterator> iter;
604
0
                    SlotDescriptor* slot = _reusable->tuple_desc()->slots()[pos];
605
0
                    StorageReadOptions storage_read_options;
606
0
                    storage_read_options.stats = &_read_stats;
607
0
                    storage_read_options.io_ctx = io_ctx;
608
0
                    RETURN_IF_ERROR(segment->seek_and_read_by_rowid(*_tablet->tablet_schema(), slot,
609
0
                                                                    row_ids, column,
610
0
                                                                    storage_read_options, iter));
611
0
                }
612
0
            }
613
0
        }
614
0
        if (result_columns.size() > _reusable->include_col_uids().size()) {
615
            // Padding rows for some columns that no need to output to mysql client
616
            // eg. SELECT k1,v1,v2 FROM TABLE WHERE k1 = 1, k1 is not in output slots, tuple as bellow
617
            // TupleDescriptor{id=1, tbl=table_with_column_group}
618
            // SlotDescriptor{id=8, col=v1, colUniqueId=1 ...}
619
            // SlotDescriptor{id=9, col=v2, colUniqueId=2 ...}
620
            // thus missing in include_col_uids and missing_col_uids
621
0
            for (auto& column : result_columns) {
622
0
                int padding_rows = _row_hits - cast_set<int>(column->size());
623
0
                if (padding_rows > 0) {
624
0
                    column->insert_many_defaults(padding_rows);
625
0
                }
626
0
            }
627
0
        }
628
0
    }
629
    // filter rows by delete sign
630
0
    if (_row_hits > 0 && _reusable->delete_sign_idx() != -1) {
631
0
        size_t filtered = 0;
632
0
        size_t total = 0;
633
0
        {
634
            // clear_column_data will check reference of ColumnPtr, so we need to release
635
            // reference before clear_column_data
636
0
            ColumnPtr delete_filter_columns =
637
0
                    _result_block->get_columns()[_reusable->delete_sign_idx()];
638
0
            const auto& filter =
639
0
                    assert_cast<const ColumnInt8*>(delete_filter_columns.get())->get_data();
640
0
            filtered = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
641
0
            total = filter.size();
642
0
        }
643
644
0
        if (filtered == total) {
645
0
            _result_block->clear_column_data();
646
0
        } else if (filtered > 0) {
647
0
            return Status::NotSupported("Not implemented since only single row at present");
648
0
        }
649
0
    }
650
0
    return Status::OK();
651
0
}
652
653
0
Status serialize_block(std::shared_ptr<TFetchDataResult> res, PTabletKeyLookupResponse* response) {
654
0
    uint8_t* buf = nullptr;
655
0
    uint32_t len = 0;
656
0
    ThriftSerializer ser(false, 4096);
657
0
    RETURN_IF_ERROR(ser.serialize(&(res->result_batch), &len, &buf));
658
0
    response->set_row_batch(std::string((const char*)buf, len));
659
0
    return Status::OK();
660
0
}
661
662
0
Status PointQueryExecutor::_output_data() {
663
    // 4. exprs exec and serialize to mysql row batches
664
0
    SCOPED_TIMER(&_profile_metrics.output_data_ns);
665
0
    if (_result_block->rows()) {
666
0
        RuntimeState state;
667
0
        auto buffer = std::make_shared<PointQueryResultBlockBuffer>(&state);
668
        // TODO reuse mysql_writer
669
0
        VMysqlResultWriter mysql_writer(buffer, _reusable->output_exprs(), nullptr,
670
0
                                        _binary_row_format);
671
0
        RETURN_IF_ERROR(mysql_writer.init(_reusable->runtime_state()));
672
0
        _result_block->clear_names();
673
0
        RETURN_IF_ERROR(mysql_writer.write(_reusable->runtime_state(), *_result_block));
674
0
        RETURN_IF_ERROR(serialize_block(buffer->get_block(), _response));
675
0
        VLOG_DEBUG << "dump block " << _result_block->dump_data();
676
0
    } else {
677
0
        _response->set_empty_batch(true);
678
0
    }
679
0
    _profile_metrics.result_data_bytes = _result_block->bytes();
680
0
    _reusable->return_block(_result_block);
681
0
    return Status::OK();
682
0
}
683
684
} // namespace doris