Coverage Report

Created: 2026-10-14 06:18

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