Coverage Report

Created: 2026-05-16 15:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/partial_update_info.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 "storage/partial_update_info.h"
19
20
#include <gen_cpp/olap_file.pb.h>
21
22
#include <cstdint>
23
24
#include "common/consts.h"
25
#include "common/logging.h"
26
#include "core/assert_cast.h"
27
#include "core/block/block.h"
28
#include "core/data_type/data_type_number.h" // IWYU pragma: keep
29
#include "core/value/bitmap_value.h"
30
#include "storage/iterator/olap_data_convertor.h"
31
#include "storage/olap_common.h"
32
#include "storage/rowset/rowset.h"
33
#include "storage/rowset/rowset_writer_context.h"
34
#include "storage/segment/historical_row_retriever.h"
35
#include "storage/segment/vertical_segment_writer.h"
36
#include "storage/tablet/base_tablet.h"
37
#include "storage/tablet/tablet_meta.h"
38
#include "storage/tablet/tablet_schema.h"
39
#include "storage/utils.h"
40
41
namespace doris {
42
Status PartialUpdateInfo::init(int64_t tablet_id, int64_t txn_id, const TabletSchema& tablet_schema,
43
                               UniqueKeyUpdateModePB unique_key_update_mode,
44
                               PartialUpdateNewRowPolicyPB policy,
45
                               const std::set<std::string>& partial_update_cols,
46
                               bool is_strict_mode_, int64_t timestamp_ms_, int32_t nano_seconds_,
47
                               const std::string& timezone_,
48
                               const std::string& auto_increment_column,
49
193k
                               int32_t sequence_map_col_uid, int64_t cur_max_version) {
50
193k
    partial_update_mode = unique_key_update_mode;
51
193k
    partial_update_new_key_policy = policy;
52
193k
    partial_update_input_columns = partial_update_cols;
53
193k
    max_version_in_flush_phase = cur_max_version;
54
193k
    sequence_map_col_unqiue_id = sequence_map_col_uid;
55
193k
    timestamp_ms = timestamp_ms_;
56
193k
    nano_seconds = nano_seconds_;
57
193k
    timezone = timezone_;
58
193k
    missing_cids.clear();
59
193k
    update_cids.clear();
60
61
193k
    if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
62
        // partial_update_cols should include all key columns
63
11.3k
        for (std::size_t i {0}; i < tablet_schema.num_key_columns(); i++) {
64
7.75k
            const auto key_col = tablet_schema.column(i);
65
7.75k
            if (!partial_update_cols.contains(key_col.name())) {
66
0
                auto msg = fmt::format(
67
0
                        "Unable to do partial update on shadow index's tablet, tablet_id={}, "
68
0
                        "txn_id={}. Missing key column {}.",
69
0
                        tablet_id, txn_id, key_col.name());
70
0
                LOG_WARNING(msg);
71
0
                return Status::Aborted<false>(msg);
72
0
            }
73
7.75k
        }
74
3.54k
    }
75
193k
    if (is_partial_update()) {
76
36.8k
        for (auto i = 0; i < tablet_schema.num_columns(); ++i) {
77
33.0k
            if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
78
29.2k
                auto tablet_column = tablet_schema.column(i);
79
29.2k
                if (!partial_update_input_columns.contains(tablet_column.name())) {
80
17.0k
                    missing_cids.emplace_back(i);
81
17.0k
                    if (!tablet_column.has_default_value() && !tablet_column.is_nullable() &&
82
17.0k
                        tablet_schema.auto_increment_column() != tablet_column.name()) {
83
1.20k
                        can_insert_new_rows_in_partial_update = false;
84
1.20k
                    }
85
17.0k
                } else {
86
12.1k
                    update_cids.emplace_back(i);
87
12.1k
                }
88
29.2k
                if (auto_increment_column == tablet_column.name()) {
89
238
                    is_schema_contains_auto_inc_column = true;
90
238
                }
91
29.2k
            } else {
92
                // in flexible partial update, missing cids is all non sort keys' cid
93
3.85k
                if (i >= tablet_schema.num_key_columns()) {
94
3.59k
                    missing_cids.emplace_back(i);
95
3.59k
                }
96
3.85k
            }
97
33.0k
        }
98
3.81k
        _generate_default_values_for_missing_cids(tablet_schema);
99
3.81k
    }
100
193k
    is_strict_mode = is_strict_mode_;
101
193k
    is_input_columns_contains_auto_inc_column =
102
193k
            is_fixed_partial_update() &&
103
193k
            partial_update_input_columns.contains(auto_increment_column);
104
193k
    return Status::OK();
105
193k
}
106
107
304
void PartialUpdateInfo::to_pb(PartialUpdateInfoPB* partial_update_info_pb) const {
108
304
    partial_update_info_pb->set_partial_update_mode(partial_update_mode);
109
304
    partial_update_info_pb->set_partial_update_new_key_policy(partial_update_new_key_policy);
110
304
    partial_update_info_pb->set_max_version_in_flush_phase(max_version_in_flush_phase);
111
1.60k
    for (const auto& col : partial_update_input_columns) {
112
1.60k
        partial_update_info_pb->add_partial_update_input_columns(col);
113
1.60k
    }
114
1.74k
    for (auto cid : missing_cids) {
115
1.74k
        partial_update_info_pb->add_missing_cids(cid);
116
1.74k
    }
117
1.60k
    for (auto cid : update_cids) {
118
1.60k
        partial_update_info_pb->add_update_cids(cid);
119
1.60k
    }
120
304
    partial_update_info_pb->set_can_insert_new_rows_in_partial_update(
121
304
            can_insert_new_rows_in_partial_update);
122
304
    partial_update_info_pb->set_is_strict_mode(is_strict_mode);
123
304
    partial_update_info_pb->set_timestamp_ms(timestamp_ms);
124
304
    partial_update_info_pb->set_nano_seconds(nano_seconds);
125
304
    partial_update_info_pb->set_timezone(timezone);
126
304
    partial_update_info_pb->set_is_input_columns_contains_auto_inc_column(
127
304
            is_input_columns_contains_auto_inc_column);
128
304
    partial_update_info_pb->set_is_schema_contains_auto_inc_column(
129
304
            is_schema_contains_auto_inc_column);
130
1.74k
    for (const auto& value : default_values) {
131
1.74k
        partial_update_info_pb->add_default_values(value);
132
1.74k
    }
133
304
}
134
135
0
void PartialUpdateInfo::from_pb(PartialUpdateInfoPB* partial_update_info_pb) {
136
0
    if (!partial_update_info_pb->has_partial_update_mode()) {
137
        // for backward compatibility
138
0
        if (partial_update_info_pb->is_partial_update()) {
139
0
            partial_update_mode = UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS;
140
0
        } else {
141
0
            partial_update_mode = UniqueKeyUpdateModePB::UPSERT;
142
0
        }
143
0
    } else {
144
0
        partial_update_mode = partial_update_info_pb->partial_update_mode();
145
0
    }
146
0
    if (partial_update_info_pb->has_partial_update_new_key_policy()) {
147
0
        partial_update_new_key_policy = partial_update_info_pb->partial_update_new_key_policy();
148
0
    }
149
0
    max_version_in_flush_phase = partial_update_info_pb->has_max_version_in_flush_phase()
150
0
                                         ? partial_update_info_pb->max_version_in_flush_phase()
151
0
                                         : -1;
152
0
    partial_update_input_columns.clear();
153
0
    for (const auto& col : partial_update_info_pb->partial_update_input_columns()) {
154
0
        partial_update_input_columns.insert(col);
155
0
    }
156
0
    missing_cids.clear();
157
0
    for (auto cid : partial_update_info_pb->missing_cids()) {
158
0
        missing_cids.push_back(cid);
159
0
    }
160
0
    update_cids.clear();
161
0
    for (auto cid : partial_update_info_pb->update_cids()) {
162
0
        update_cids.push_back(cid);
163
0
    }
164
0
    can_insert_new_rows_in_partial_update =
165
0
            partial_update_info_pb->can_insert_new_rows_in_partial_update();
166
0
    is_strict_mode = partial_update_info_pb->is_strict_mode();
167
0
    timestamp_ms = partial_update_info_pb->timestamp_ms();
168
0
    timezone = partial_update_info_pb->timezone();
169
0
    is_input_columns_contains_auto_inc_column =
170
0
            partial_update_info_pb->is_input_columns_contains_auto_inc_column();
171
0
    is_schema_contains_auto_inc_column =
172
0
            partial_update_info_pb->is_schema_contains_auto_inc_column();
173
0
    if (partial_update_info_pb->has_nano_seconds()) {
174
0
        nano_seconds = partial_update_info_pb->nano_seconds();
175
0
    }
176
0
    default_values.clear();
177
0
    for (const auto& value : partial_update_info_pb->default_values()) {
178
0
        default_values.push_back(value);
179
0
    }
180
0
}
181
182
0
std::string PartialUpdateInfo::summary() const {
183
0
    std::string mode;
184
0
    switch (partial_update_mode) {
185
0
    case UniqueKeyUpdateModePB::UPSERT:
186
0
        mode = "upsert";
187
0
        break;
188
0
    case UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS:
189
0
        mode = "fixed partial update";
190
0
        break;
191
0
    case UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS:
192
0
        mode = "flexible partial update";
193
0
        break;
194
0
    }
195
0
    return fmt::format(
196
0
            "mode={}, update_cids={}, missing_cids={}, is_strict_mode={}, "
197
0
            "max_version_in_flush_phase={}",
198
0
            mode, update_cids.size(), missing_cids.size(), is_strict_mode,
199
0
            max_version_in_flush_phase);
200
0
}
201
202
Status PartialUpdateInfo::handle_new_key(const TabletSchema& tablet_schema,
203
                                         const std::function<std::string()>& line,
204
558
                                         BitmapValue* skip_bitmap) {
205
558
    switch (partial_update_new_key_policy) {
206
522
    case doris::PartialUpdateNewRowPolicyPB::APPEND: {
207
522
        if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
208
237
            if (!can_insert_new_rows_in_partial_update) {
209
10
                std::string error_column;
210
18
                for (auto cid : missing_cids) {
211
18
                    const TabletColumn& col = tablet_schema.column(cid);
212
18
                    if (!col.has_default_value() && !col.is_nullable() &&
213
18
                        !(tablet_schema.auto_increment_column() == col.name())) {
214
10
                        error_column = col.name();
215
10
                        break;
216
10
                    }
217
18
                }
218
10
                return Status::Error<ErrorCode::INVALID_SCHEMA, false>(
219
10
                        "the unmentioned column `{}` should have default value or be nullable "
220
10
                        "for newly inserted rows in non-strict mode partial update",
221
10
                        error_column);
222
10
            }
223
285
        } else if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS) {
224
285
            DCHECK(skip_bitmap != nullptr);
225
285
            bool can_insert_new_row {true};
226
285
            std::string error_column;
227
3.89k
            for (auto cid : missing_cids) {
228
3.89k
                const TabletColumn& col = tablet_schema.column(cid);
229
3.89k
                if (skip_bitmap->contains(col.unique_id()) && !col.has_default_value() &&
230
3.89k
                    !col.is_nullable() && !col.is_auto_increment()) {
231
0
                    error_column = col.name();
232
0
                    can_insert_new_row = false;
233
0
                    break;
234
0
                }
235
3.89k
            }
236
285
            if (!can_insert_new_row) {
237
0
                return Status::Error<ErrorCode::INVALID_SCHEMA, false>(
238
0
                        "the unmentioned column `{}` should have default value or be "
239
0
                        "nullable for newly inserted rows in non-strict mode flexible partial "
240
0
                        "update",
241
0
                        error_column);
242
0
            }
243
285
        }
244
522
    } break;
245
512
    case doris::PartialUpdateNewRowPolicyPB::ERROR: {
246
36
        return Status::Error<ErrorCode::NEW_ROWS_IN_PARTIAL_UPDATE, false>(
247
36
                "Can't append new rows in partial update when partial_update_new_key_behavior is "
248
36
                "ERROR. Row with key=[{}] is not in table.",
249
36
                line());
250
522
    } break;
251
558
    }
252
511
    return Status::OK();
253
558
}
254
255
void PartialUpdateInfo::_generate_default_values_for_missing_cids(
256
3.81k
        const TabletSchema& tablet_schema) {
257
20.5k
    for (unsigned int cur_cid : missing_cids) {
258
20.5k
        const auto& column = tablet_schema.column(cur_cid);
259
20.5k
        if (column.has_default_value()) {
260
7.74k
            std::string default_value;
261
7.74k
            if (UNLIKELY((column.type() == FieldType::OLAP_FIELD_TYPE_DATETIMEV2 ||
262
7.74k
                          column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ) &&
263
7.74k
                         to_lower(column.default_value()).find(to_lower("CURRENT_TIMESTAMP")) !=
264
7.74k
                                 std::string::npos)) {
265
133
                auto pos = to_lower(column.default_value()).find('(');
266
133
                if (pos == std::string::npos) {
267
64
                    DateV2Value<DateTimeV2ValueType> dtv;
268
64
                    dtv.from_unixtime(timestamp_ms / 1000, timezone);
269
64
                    default_value = dtv.to_string();
270
64
                    if (column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ) {
271
0
                        default_value += timezone;
272
0
                    }
273
69
                } else {
274
69
                    int precision = std::stoi(column.default_value().substr(pos + 1));
275
69
                    DateV2Value<DateTimeV2ValueType> dtv;
276
69
                    dtv.from_unixtime(timestamp_ms / 1000, nano_seconds, timezone, precision);
277
69
                    default_value = dtv.to_string();
278
69
                    if (column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ) {
279
0
                        default_value += timezone;
280
0
                    }
281
69
                }
282
7.61k
            } else if (UNLIKELY(column.type() == FieldType::OLAP_FIELD_TYPE_DATEV2 &&
283
7.61k
                                to_lower(column.default_value()).find(to_lower("CURRENT_DATE")) !=
284
7.61k
                                        std::string::npos)) {
285
81
                DateV2Value<DateV2ValueType> dv;
286
81
                dv.from_unixtime(timestamp_ms / 1000, timezone);
287
81
                default_value = dv.to_string();
288
7.52k
            } else if (UNLIKELY(column.type() == FieldType::OLAP_FIELD_TYPE_BITMAP &&
289
7.52k
                                to_lower(column.default_value()).find(to_lower("BITMAP_EMPTY")) !=
290
7.52k
                                        std::string::npos)) {
291
0
                BitmapValue v = BitmapValue {};
292
0
                default_value = v.to_string();
293
7.52k
            } else {
294
7.52k
                default_value = column.default_value();
295
7.52k
            }
296
7.74k
            default_values.emplace_back(default_value);
297
12.8k
        } else {
298
            // place an empty string here
299
12.8k
            default_values.emplace_back();
300
12.8k
        }
301
20.5k
    }
302
3.81k
    CHECK_EQ(missing_cids.size(), default_values.size());
303
3.81k
}
304
305
9
bool FixedReadPlan::empty() const {
306
9
    return plan.empty();
307
9
}
308
309
22.7k
void FixedReadPlan::prepare_to_read(const RowLocation& row_location, size_t pos) {
310
22.7k
    plan[row_location.rowset_id][row_location.segment_id].emplace_back(row_location.row_id, pos);
311
22.7k
}
312
313
// read columns by read plan
314
// read_index: ori_pos-> block_idx
315
Status FixedReadPlan::read_columns_by_plan(
316
        const TabletSchema& tablet_schema, std::vector<uint32_t> cids_to_read,
317
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block& block,
318
        std::map<uint32_t, uint32_t>* read_index, bool force_read_old_delete_signs,
319
1.39k
        const signed char* __restrict cur_delete_signs) const {
320
1.39k
    if (force_read_old_delete_signs) {
321
        // always read delete sign column from historical data
322
1.37k
        if (block.get_position_by_name(DELETE_SIGN) == -1) {
323
845
            auto del_col_cid = tablet_schema.field_index(DELETE_SIGN);
324
845
            cids_to_read.emplace_back(del_col_cid);
325
845
            block.swap(tablet_schema.create_block_by_cids(cids_to_read));
326
845
        }
327
1.37k
    }
328
1.39k
    bool has_row_column = tablet_schema.has_row_store_for_all_columns();
329
1.39k
    auto mutable_columns = block.mutate_columns();
330
1.39k
    uint32_t read_idx = 0;
331
1.39k
    for (const auto& [rowset_id, segment_row_mappings] : plan) {
332
624
        for (const auto& [segment_id, mappings] : segment_row_mappings) {
333
624
            auto rowset_iter = rsid_to_rowset.find(rowset_id);
334
624
            CHECK(rowset_iter != rsid_to_rowset.end());
335
624
            std::vector<uint32_t> rids;
336
22.7k
            for (auto [rid, pos] : mappings) {
337
22.7k
                if (cur_delete_signs && cur_delete_signs[pos]) {
338
4
                    continue;
339
4
                }
340
22.7k
                rids.emplace_back(rid);
341
22.7k
                (*read_index)[static_cast<uint32_t>(pos)] = read_idx++;
342
22.7k
            }
343
624
            if (has_row_column) {
344
178
                auto st = BaseTablet::fetch_value_through_row_column(
345
178
                        rowset_iter->second, tablet_schema, segment_id, rids, cids_to_read, block);
346
178
                if (!st.ok()) {
347
0
                    LOG(WARNING) << "failed to fetch value through row column";
348
0
                    return st;
349
0
                }
350
178
                continue;
351
178
            }
352
2.57k
            for (size_t cid = 0; cid < mutable_columns.size(); ++cid) {
353
2.12k
                TabletColumn tablet_column = tablet_schema.column(cids_to_read[cid]);
354
2.12k
                auto st = doris::BaseTablet::fetch_value_by_rowids(
355
2.12k
                        rowset_iter->second, segment_id, rids, tablet_column, mutable_columns[cid]);
356
                // set read value to output block
357
2.12k
                if (!st.ok()) {
358
0
                    LOG(WARNING) << "failed to fetch value";
359
0
                    return st;
360
0
                }
361
2.12k
            }
362
446
        }
363
624
    }
364
1.39k
    block.set_columns(std::move(mutable_columns));
365
1.39k
    return Status::OK();
366
1.39k
}
367
368
Status FixedReadPlan::fill_missing_columns(
369
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
370
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
371
        const TabletSchema& tablet_schema, Block& full_block,
372
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
373
1.35k
        uint32_t segment_start_pos, const Block* block) const {
374
1.35k
    auto mutable_full_columns = full_block.mutate_columns();
375
    // create old value columns
376
1.35k
    DCHECK(historical_context.partial_update_info != nullptr);
377
1.35k
    DCHECK(historical_context.tablet_schema != nullptr);
378
1.35k
    const auto& partial_update_info = *historical_context.partial_update_info;
379
1.35k
    const auto& missing_cids = partial_update_info.missing_cids;
380
1.35k
    bool have_input_seq_column = false;
381
1.35k
    if (tablet_schema.has_sequence_col()) {
382
224
        const std::vector<uint32_t>& including_cids = partial_update_info.update_cids;
383
224
        have_input_seq_column =
384
224
                (std::find(including_cids.cbegin(), including_cids.cend(),
385
224
                           tablet_schema.sequence_col_idx()) != including_cids.cend());
386
224
    }
387
388
1.35k
    auto old_value_block = tablet_schema.create_block_by_cids(missing_cids);
389
1.35k
    CHECK_EQ(missing_cids.size(), old_value_block.columns());
390
391
    // segment pos to write -> rowid to read in old_value_block
392
1.35k
    std::map<uint32_t, uint32_t> read_index;
393
1.35k
    RETURN_IF_ERROR(read_columns_by_plan(tablet_schema, missing_cids, rsid_to_rowset,
394
1.35k
                                         old_value_block, &read_index, true, nullptr));
395
396
1.35k
    const auto* old_delete_signs = BaseTablet::get_delete_sign_column_data(old_value_block);
397
1.35k
    if (old_delete_signs == nullptr) {
398
0
        return Status::InternalError("old delete signs column not found, block: {}",
399
0
                                     old_value_block.dump_structure());
400
0
    }
401
    // build default value columns
402
1.35k
    auto default_value_block = old_value_block.clone_empty();
403
1.35k
    RETURN_IF_ERROR(BaseTablet::generate_default_value_block(tablet_schema, missing_cids,
404
1.35k
                                                             partial_update_info.default_values,
405
1.35k
                                                             old_value_block, default_value_block));
406
1.35k
    auto mutable_default_value_columns = default_value_block.mutate_columns();
407
408
    // fill all missing value from mutable_old_columns, need to consider default value and null value
409
25.8k
    for (auto idx = 0; idx < use_default_or_null_flag.size(); idx++) {
410
24.4k
        auto segment_pos = idx + segment_start_pos;
411
24.4k
        auto pos_in_old_block = read_index[segment_pos];
412
413
116k
        for (auto i = 0; i < missing_cids.size(); ++i) {
414
            // if the column has default value, fill it with default value
415
            // otherwise, if the column is nullable, fill it with null value
416
92.1k
            const auto& tablet_column = tablet_schema.column(missing_cids[i]);
417
92.1k
            auto& missing_col = mutable_full_columns[missing_cids[i]];
418
419
92.1k
            bool should_use_default = use_default_or_null_flag[idx];
420
92.1k
            if (!should_use_default) {
421
79.1k
                bool old_row_delete_sign =
422
79.1k
                        (old_delete_signs != nullptr && old_delete_signs[pos_in_old_block] != 0);
423
79.1k
                if (old_row_delete_sign) {
424
151
                    if (!tablet_schema.has_sequence_col()) {
425
70
                        should_use_default = true;
426
81
                    } else if (have_input_seq_column || (!tablet_column.is_seqeunce_col())) {
427
                        // to keep the sequence column value not decreasing, we should read values of seq column
428
                        // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
429
                        // it may cause the merge-on-read based compaction to produce incorrect results
430
77
                        should_use_default = true;
431
77
                    }
432
151
                }
433
79.1k
            }
434
435
92.1k
            if (should_use_default) {
436
13.2k
                if (tablet_column.has_default_value()) {
437
2.92k
                    missing_col->insert_from(*mutable_default_value_columns[i], 0);
438
10.2k
                } else if (tablet_column.is_nullable()) {
439
8.75k
                    auto* nullable_column = assert_cast<ColumnNullable*>(missing_col.get());
440
8.75k
                    nullable_column->insert_many_defaults(1);
441
8.75k
                } else if (tablet_schema.auto_increment_column() == tablet_column.name()) {
442
41
                    const auto& column = *DORIS_TRY(
443
41
                            historical_context.tablet_schema->column(tablet_column.name()));
444
41
                    DCHECK(column.type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
445
41
                    auto* auto_inc_column = assert_cast<ColumnInt64*>(missing_col.get());
446
41
                    int pos = block->get_position_by_name(BeConsts::PARTIAL_UPDATE_AUTO_INC_COL);
447
41
                    if (pos == -1) {
448
0
                        return Status::InternalError("auto increment column not found in block {}",
449
0
                                                     block->dump_structure());
450
0
                    }
451
41
                    auto_inc_column->insert_from(*block->get_by_position(pos).column.get(), idx);
452
1.48k
                } else {
453
                    // If the control flow reaches this branch, the column neither has default value
454
                    // nor is nullable. It means that the row's delete sign is marked, and the value
455
                    // columns are useless and won't be read. So we can just put arbitary values in the cells
456
1.48k
                    missing_col->insert_default();
457
1.48k
                }
458
78.9k
            } else {
459
78.9k
                missing_col->insert_from(*old_value_block.get_by_position(i).column,
460
78.9k
                                         pos_in_old_block);
461
78.9k
            }
462
92.1k
        }
463
24.4k
    }
464
1.35k
    full_block.set_columns(std::move(mutable_full_columns));
465
1.35k
    return Status::OK();
466
1.35k
}
467
468
void FlexibleReadPlan::prepare_to_read(const RowLocation& row_location, size_t pos,
469
1.78k
                                       const BitmapValue& skip_bitmap) {
470
1.78k
    if (!use_row_store) {
471
3.88k
        for (uint64_t col_uid : skip_bitmap) {
472
3.88k
            plan[row_location.rowset_id][row_location.segment_id][static_cast<uint32_t>(col_uid)]
473
3.88k
                    .emplace_back(row_location.row_id, pos);
474
3.88k
        }
475
932
    } else {
476
854
        row_store_plan[row_location.rowset_id][row_location.segment_id].emplace_back(
477
854
                row_location.row_id, pos);
478
854
    }
479
1.78k
}
480
481
Status FlexibleReadPlan::read_columns_by_plan(
482
        const TabletSchema& tablet_schema,
483
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block& old_value_block,
484
145
        std::map<uint32_t, std::map<uint32_t, uint32_t>>* read_index) const {
485
145
    auto mutable_columns = old_value_block.mutate_columns();
486
487
    // cid -> next rid to fill in block
488
145
    std::map<uint32_t, uint32_t> next_read_idx;
489
2.16k
    for (uint32_t cid {0}; cid < tablet_schema.num_columns(); cid++) {
490
2.01k
        next_read_idx[cid] = 0;
491
2.01k
    }
492
493
180
    for (const auto& [rowset_id, segment_mappings] : plan) {
494
180
        for (const auto& [segment_id, uid_mappings] : segment_mappings) {
495
1.48k
            for (const auto& [col_uid, mappings] : uid_mappings) {
496
1.48k
                auto rowset_iter = rsid_to_rowset.find(rowset_id);
497
1.48k
                CHECK(rowset_iter != rsid_to_rowset.end());
498
1.48k
                auto cid = tablet_schema.field_index(col_uid);
499
1.48k
                DCHECK_NE(cid, -1);
500
1.48k
                DCHECK_GE(cid, tablet_schema.num_key_columns());
501
1.48k
                std::vector<uint32_t> rids;
502
3.91k
                for (auto [rid, pos] : mappings) {
503
3.91k
                    rids.emplace_back(rid);
504
3.91k
                    (*read_index)[cid][static_cast<uint32_t>(pos)] = next_read_idx[cid]++;
505
3.91k
                }
506
507
1.48k
                TabletColumn tablet_column = tablet_schema.column(cid);
508
1.48k
                auto idx = cid - tablet_schema.num_key_columns();
509
1.48k
                RETURN_IF_ERROR(doris::BaseTablet::fetch_value_by_rowids(
510
1.48k
                        rowset_iter->second, segment_id, rids, tablet_column,
511
1.48k
                        mutable_columns[idx]));
512
1.48k
            }
513
180
        }
514
180
    }
515
    // !!!ATTENTION!!!: columns in block may have different size because every row has different columns to update
516
145
    old_value_block.set_columns(std::move(mutable_columns));
517
145
    return Status::OK();
518
145
}
519
520
Status FlexibleReadPlan::read_columns_by_plan(
521
        const TabletSchema& tablet_schema, const std::vector<uint32_t>& cids_to_read,
522
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block& old_value_block,
523
119
        std::map<uint32_t, uint32_t>* read_index) const {
524
119
    DCHECK(use_row_store);
525
119
    uint32_t read_idx = 0;
526
158
    for (const auto& [rowset_id, segment_row_mappings] : row_store_plan) {
527
158
        for (const auto& [segment_id, mappings] : segment_row_mappings) {
528
158
            auto rowset_iter = rsid_to_rowset.find(rowset_id);
529
158
            CHECK(rowset_iter != rsid_to_rowset.end());
530
158
            std::vector<uint32_t> rids;
531
859
            for (auto [rid, pos] : mappings) {
532
859
                rids.emplace_back(rid);
533
859
                (*read_index)[static_cast<uint32_t>(pos)] = read_idx++;
534
859
            }
535
158
            auto st = BaseTablet::fetch_value_through_row_column(rowset_iter->second, tablet_schema,
536
158
                                                                 segment_id, rids, cids_to_read,
537
158
                                                                 old_value_block);
538
158
            if (!st.ok()) {
539
0
                LOG(WARNING) << "failed to fetch value through row column";
540
0
                return st;
541
0
            }
542
158
        }
543
158
    }
544
119
    return Status::OK();
545
119
}
546
547
Status FlexibleReadPlan::fill_non_primary_key_columns(
548
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
549
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
550
        const TabletSchema& tablet_schema, Block& full_block,
551
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
552
        uint32_t segment_start_pos, uint32_t block_start_pos, const Block* block,
553
264
        std::vector<BitmapValue>* skip_bitmaps) const {
554
264
    auto mutable_full_columns = full_block.mutate_columns();
555
264
    DCHECK(historical_context.partial_update_info != nullptr);
556
557
    // missing_cids are all non sort key columns' cids
558
264
    const auto& non_sort_key_cids = historical_context.partial_update_info->missing_cids;
559
264
    auto old_value_block = tablet_schema.create_block_by_cids(non_sort_key_cids);
560
264
    CHECK_EQ(non_sort_key_cids.size(), old_value_block.columns());
561
562
264
    if (!use_row_store) {
563
145
        RETURN_IF_ERROR(fill_non_primary_key_columns_for_column_store(
564
145
                historical_context, rsid_to_rowset, tablet_schema, non_sort_key_cids,
565
145
                old_value_block, mutable_full_columns, use_default_or_null_flag,
566
145
                has_default_or_nullable, segment_start_pos, block_start_pos, block, skip_bitmaps));
567
145
    } else {
568
119
        RETURN_IF_ERROR(fill_non_primary_key_columns_for_row_store(
569
119
                historical_context, rsid_to_rowset, tablet_schema, non_sort_key_cids,
570
119
                old_value_block, mutable_full_columns, use_default_or_null_flag,
571
119
                has_default_or_nullable, segment_start_pos, block_start_pos, block, skip_bitmaps));
572
119
    }
573
264
    full_block.set_columns(std::move(mutable_full_columns));
574
264
    return Status::OK();
575
264
}
576
577
static void fill_non_primary_key_cell_for_column_store(
578
        const TabletColumn& tablet_column, uint32_t cid, MutableColumnPtr& new_col,
579
        const IColumn& default_value_col, const IColumn& old_value_col, const IColumn& cur_col,
580
        std::size_t block_pos, uint32_t segment_pos, bool skipped, bool row_has_sequence_col,
581
        bool use_default, const signed char* delete_sign_column_data,
582
        const TabletSchema& tablet_schema,
583
        std::map<uint32_t, std::map<uint32_t, uint32_t>>& read_index,
584
16.9k
        const PartialUpdateInfo* info) {
585
16.9k
    if (skipped) {
586
4.78k
        DCHECK(cid != tablet_schema.skip_bitmap_col_idx());
587
4.78k
        DCHECK(cid != tablet_schema.version_col_idx());
588
4.78k
        DCHECK(!tablet_column.is_row_store_column());
589
590
4.78k
        if (!use_default) {
591
3.91k
            if (delete_sign_column_data != nullptr) {
592
3.91k
                bool old_row_delete_sign = false;
593
3.91k
                if (auto it = read_index[tablet_schema.delete_sign_idx()].find(segment_pos);
594
3.91k
                    it != read_index[tablet_schema.delete_sign_idx()].end()) {
595
3.79k
                    old_row_delete_sign = (delete_sign_column_data[it->second] != 0);
596
3.79k
                }
597
598
3.91k
                if (old_row_delete_sign) {
599
7
                    if (!tablet_schema.has_sequence_col()) {
600
2
                        use_default = true;
601
5
                    } else if (row_has_sequence_col ||
602
5
                               (!tablet_column.is_seqeunce_col() &&
603
5
                                (tablet_column.unique_id() != info->sequence_map_col_uid()))) {
604
                        // to keep the sequence column value not decreasing, we should read values of seq column(and seq map column)
605
                        // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
606
                        // it may cause the merge-on-read based compaction to produce incorrect results
607
3
                        use_default = true;
608
3
                    }
609
7
                }
610
3.91k
            }
611
3.91k
        }
612
4.78k
        if (!use_default && tablet_column.is_on_update_current_timestamp()) {
613
6
            use_default = true;
614
6
        }
615
4.78k
        if (use_default) {
616
873
            if (tablet_column.has_default_value()) {
617
424
                new_col->insert_from(default_value_col, 0);
618
449
            } else if (tablet_column.is_nullable()) {
619
426
                assert_cast<ColumnNullable*, TypeCheckOnRelease::DISABLE>(new_col.get())
620
426
                        ->insert_many_defaults(1);
621
426
            } else if (tablet_column.is_auto_increment()) {
622
                // In flexible partial update, the skip bitmap indicates whether a cell
623
                // is specified in the original load, so the generated auto-increment value is filled
624
                // in current block in place if needed rather than using a seperate column to
625
                // store the generated auto-increment value in fixed partial update
626
2
                new_col->insert_from(cur_col, block_pos);
627
21
            } else {
628
21
                new_col->insert_default();
629
21
            }
630
3.90k
        } else {
631
3.90k
            auto pos_in_old_block = read_index.at(cid).at(segment_pos);
632
3.90k
            new_col->insert_from(old_value_col, pos_in_old_block);
633
3.90k
        }
634
12.1k
    } else {
635
12.1k
        new_col->insert_from(cur_col, block_pos);
636
12.1k
    }
637
16.9k
}
638
639
Status FlexibleReadPlan::fill_non_primary_key_columns_for_column_store(
640
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
641
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
642
        const TabletSchema& tablet_schema, const std::vector<uint32_t>& non_sort_key_cids,
643
        Block& old_value_block, MutableColumns& mutable_full_columns,
644
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
645
        uint32_t segment_start_pos, uint32_t block_start_pos, const Block* block,
646
145
        std::vector<BitmapValue>* skip_bitmaps) const {
647
145
    auto* info = historical_context.partial_update_info.get();
648
145
    int32_t seq_col_unique_id = -1;
649
145
    if (tablet_schema.has_sequence_col()) {
650
22
        seq_col_unique_id = tablet_schema.column(tablet_schema.sequence_col_idx()).unique_id();
651
22
    }
652
    // cid -> segment pos to write -> rowid to read in old_value_block
653
145
    std::map<uint32_t, std::map<uint32_t, uint32_t>> read_index;
654
145
    RETURN_IF_ERROR(
655
145
            read_columns_by_plan(tablet_schema, rsid_to_rowset, old_value_block, &read_index));
656
    // !!!ATTENTION!!!: columns in old_value_block may have different size because every row has different columns to update
657
658
145
    const auto* delete_sign_column_data = BaseTablet::get_delete_sign_column_data(old_value_block);
659
    // build default value columns
660
145
    auto default_value_block = old_value_block.clone_empty();
661
145
    if (has_default_or_nullable || delete_sign_column_data != nullptr) {
662
145
        RETURN_IF_ERROR(BaseTablet::generate_default_value_block(
663
145
                tablet_schema, non_sort_key_cids, info->default_values, old_value_block,
664
145
                default_value_block));
665
145
    }
666
667
    // fill all non sort key columns from mutable_old_columns, need to consider default value and null value
668
2.00k
    for (std::size_t i {0}; i < non_sort_key_cids.size(); i++) {
669
1.86k
        auto cid = non_sort_key_cids[i];
670
1.86k
        const auto& tablet_column = tablet_schema.column(cid);
671
1.86k
        auto col_uid = tablet_column.unique_id();
672
18.8k
        for (auto idx = 0; idx < use_default_or_null_flag.size(); idx++) {
673
16.9k
            auto segment_pos = segment_start_pos + idx;
674
16.9k
            auto block_pos = block_start_pos + idx;
675
676
16.9k
            fill_non_primary_key_cell_for_column_store(
677
16.9k
                    tablet_column, cid, mutable_full_columns[cid],
678
16.9k
                    *default_value_block.get_by_position(i).column,
679
16.9k
                    *old_value_block.get_by_position(i).column, *block->get_by_position(cid).column,
680
16.9k
                    block_pos, segment_pos, skip_bitmaps->at(block_pos).contains(col_uid),
681
16.9k
                    tablet_schema.has_sequence_col()
682
16.9k
                            ? !skip_bitmaps->at(block_pos).contains(seq_col_unique_id)
683
16.9k
                            : false,
684
16.9k
                    use_default_or_null_flag[idx], delete_sign_column_data, tablet_schema,
685
16.9k
                    read_index, info);
686
16.9k
        }
687
1.86k
    }
688
145
    return Status::OK();
689
145
}
690
691
static void fill_non_primary_key_cell_for_row_store(
692
        const TabletColumn& tablet_column, uint32_t cid, MutableColumnPtr& new_col,
693
        const IColumn& default_value_col, const IColumn& old_value_col, const IColumn& cur_col,
694
        std::size_t block_pos, bool skipped, bool row_has_sequence_col, bool use_default,
695
        const signed char* delete_sign_column_data, uint32_t pos_in_old_block,
696
16.5k
        const TabletSchema& tablet_schema, const PartialUpdateInfo* info) {
697
16.5k
    if (skipped) {
698
4.16k
        DCHECK(cid != tablet_schema.skip_bitmap_col_idx());
699
4.16k
        DCHECK(cid != tablet_schema.version_col_idx());
700
4.16k
        DCHECK(!tablet_column.is_row_store_column());
701
4.16k
        if (!use_default) {
702
3.64k
            if (delete_sign_column_data != nullptr) {
703
3.64k
                bool old_row_delete_sign = (delete_sign_column_data[pos_in_old_block] != 0);
704
3.64k
                if (old_row_delete_sign) {
705
7
                    if (!tablet_schema.has_sequence_col()) {
706
2
                        use_default = true;
707
5
                    } else if (row_has_sequence_col ||
708
5
                               (!tablet_column.is_seqeunce_col() &&
709
5
                                (tablet_column.unique_id() != info->sequence_map_col_uid()))) {
710
                        // to keep the sequence column value not decreasing, we should read values of seq column(and seq map column)
711
                        // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
712
                        // it may cause the merge-on-read based compaction to produce incorrect results
713
3
                        use_default = true;
714
3
                    }
715
7
                }
716
3.64k
            }
717
3.64k
        }
718
719
4.16k
        if (!use_default && tablet_column.is_on_update_current_timestamp()) {
720
6
            use_default = true;
721
6
        }
722
4.16k
        if (use_default) {
723
529
            if (tablet_column.has_default_value()) {
724
175
                new_col->insert_from(default_value_col, 0);
725
354
            } else if (tablet_column.is_nullable()) {
726
350
                assert_cast<ColumnNullable*, TypeCheckOnRelease::DISABLE>(new_col.get())
727
350
                        ->insert_many_defaults(1);
728
350
            } else if (tablet_column.is_auto_increment()) {
729
                // In flexible partial update, the skip bitmap indicates whether a cell
730
                // is specified in the original load, so the generated auto-increment value is filled
731
                // in current block in place if needed rather than using a seperate column to
732
                // store the generated auto-increment value in fixed partial update
733
2
                new_col->insert_from(cur_col, block_pos);
734
2
            } else {
735
2
                new_col->insert_default();
736
2
            }
737
3.63k
        } else {
738
3.63k
            new_col->insert_from(old_value_col, pos_in_old_block);
739
3.63k
        }
740
12.3k
    } else {
741
12.3k
        new_col->insert_from(cur_col, block_pos);
742
12.3k
    }
743
16.5k
}
744
745
Status FlexibleReadPlan::fill_non_primary_key_columns_for_row_store(
746
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
747
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
748
        const TabletSchema& tablet_schema, const std::vector<uint32_t>& non_sort_key_cids,
749
        Block& old_value_block, MutableColumns& mutable_full_columns,
750
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
751
        uint32_t segment_start_pos, uint32_t block_start_pos, const Block* block,
752
119
        std::vector<BitmapValue>* skip_bitmaps) const {
753
119
    auto* info = historical_context.partial_update_info.get();
754
119
    int32_t seq_col_unique_id = -1;
755
119
    if (tablet_schema.has_sequence_col()) {
756
3
        seq_col_unique_id = tablet_schema.column(tablet_schema.sequence_col_idx()).unique_id();
757
3
    }
758
    // segment pos to write -> rowid to read in old_value_block
759
119
    std::map<uint32_t, uint32_t> read_index;
760
119
    RETURN_IF_ERROR(read_columns_by_plan(tablet_schema, non_sort_key_cids, rsid_to_rowset,
761
119
                                         old_value_block, &read_index));
762
763
119
    const auto* delete_sign_column_data = BaseTablet::get_delete_sign_column_data(old_value_block);
764
    // build default value columns
765
119
    auto default_value_block = old_value_block.clone_empty();
766
119
    if (has_default_or_nullable || delete_sign_column_data != nullptr) {
767
119
        RETURN_IF_ERROR(BaseTablet::generate_default_value_block(
768
119
                tablet_schema, non_sort_key_cids, info->default_values, old_value_block,
769
119
                default_value_block));
770
119
    }
771
772
    // fill all non sort key columns from mutable_old_columns, need to consider default value and null value
773
1.87k
    for (std::size_t i {0}; i < non_sort_key_cids.size(); i++) {
774
1.75k
        auto cid = non_sort_key_cids[i];
775
1.75k
        const auto& tablet_column = tablet_schema.column(cid);
776
1.75k
        auto col_uid = tablet_column.unique_id();
777
18.2k
        for (auto idx = 0; idx < use_default_or_null_flag.size(); idx++) {
778
16.5k
            auto segment_pos = segment_start_pos + idx;
779
16.5k
            auto block_pos = block_start_pos + idx;
780
16.5k
            auto pos_in_old_block = read_index[segment_pos];
781
782
16.5k
            fill_non_primary_key_cell_for_row_store(
783
16.5k
                    tablet_column, cid, mutable_full_columns[cid],
784
16.5k
                    *default_value_block.get_by_position(i).column,
785
16.5k
                    *old_value_block.get_by_position(i).column, *block->get_by_position(cid).column,
786
16.5k
                    block_pos, skip_bitmaps->at(block_pos).contains(col_uid),
787
16.5k
                    tablet_schema.has_sequence_col()
788
16.5k
                            ? !skip_bitmaps->at(block_pos).contains(seq_col_unique_id)
789
16.5k
                            : false,
790
16.5k
                    use_default_or_null_flag[idx], delete_sign_column_data, pos_in_old_block,
791
16.5k
                    tablet_schema, info);
792
16.5k
        }
793
1.75k
    }
794
119
    return Status::OK();
795
119
}
796
797
BlockAggregator::BlockAggregator(segment_v2::VerticalSegmentWriter& vertical_segment_writer)
798
57.1k
        : _writer(vertical_segment_writer), _tablet_schema(*_writer._tablet_schema) {}
799
800
void BlockAggregator::merge_one_row(MutableBlock& dst_block, Block* src_block, int rid,
801
153
                                    BitmapValue& skip_bitmap) {
802
1.57k
    for (size_t cid {_tablet_schema.num_key_columns()}; cid < _tablet_schema.num_columns(); cid++) {
803
1.42k
        if (cid == _tablet_schema.skip_bitmap_col_idx()) {
804
153
            auto& cur_skip_bitmap =
805
153
                    assert_cast<ColumnBitmap*>(dst_block.mutable_columns()[cid].get())
806
153
                            ->get_data()
807
153
                            .back();
808
153
            const auto& new_row_skip_bitmap =
809
153
                    assert_cast<ColumnBitmap*>(
810
153
                            src_block->get_by_position(cid).column->assume_mutable().get())
811
153
                            ->get_data()[rid];
812
153
            cur_skip_bitmap &= new_row_skip_bitmap;
813
153
            continue;
814
153
        }
815
1.27k
        if (!skip_bitmap.contains(_tablet_schema.column(cid).unique_id())) {
816
460
            dst_block.mutable_columns()[cid]->pop_back(1);
817
460
            dst_block.mutable_columns()[cid]->insert_from(*src_block->get_by_position(cid).column,
818
460
                                                          rid);
819
460
        }
820
1.27k
    }
821
153
    VLOG_DEBUG << fmt::format("merge a row, after merge, output_block.rows()={}, state: {}",
822
0
                              dst_block.rows(), _state.to_string());
823
153
}
824
825
252
void BlockAggregator::append_one_row(MutableBlock& dst_block, Block* src_block, int rid) {
826
252
    dst_block.add_row(src_block, rid);
827
252
    _state.rows++;
828
252
    VLOG_DEBUG << fmt::format("append a new row, after append, output_block.rows()={}, state: {}",
829
0
                              dst_block.rows(), _state.to_string());
830
252
}
831
832
123
void BlockAggregator::remove_last_n_rows(MutableBlock& dst_block, int n) {
833
123
    if (n > 0) {
834
968
        for (size_t cid {0}; cid < _tablet_schema.num_columns(); cid++) {
835
880
            DCHECK_GE(dst_block.mutable_columns()[cid]->size(), n);
836
880
            dst_block.mutable_columns()[cid]->pop_back(n);
837
880
        }
838
88
    }
839
123
}
840
841
void BlockAggregator::append_or_merge_row(MutableBlock& dst_block, Block* src_block, int rid,
842
405
                                          BitmapValue& skip_bitmap, bool have_delete_sign) {
843
405
    if (have_delete_sign) {
844
        // remove all the previous batched rows
845
123
        remove_last_n_rows(dst_block, _state.rows);
846
123
        _state.rows = 0;
847
123
        _state.has_row_with_delete_sign = true;
848
849
123
        append_one_row(dst_block, src_block, rid);
850
282
    } else {
851
282
        if (_state.should_merge()) {
852
153
            merge_one_row(dst_block, src_block, rid, skip_bitmap);
853
153
        } else {
854
129
            append_one_row(dst_block, src_block, rid);
855
129
        }
856
282
    }
857
405
};
858
859
Status BlockAggregator::aggregate_rows(
860
        MutableBlock& output_block, Block* block, int start, int end, std::string key,
861
        std::vector<BitmapValue>* skip_bitmaps, const signed char* delete_signs,
862
        IOlapColumnDataAccessor* seq_column, const std::vector<RowsetSharedPtr>& specified_rowsets,
863
133
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
864
133
    VLOG_DEBUG << fmt::format("merge rows in range=[{}-{})", start, end);
865
133
    if (end - start == 1) {
866
34
        output_block.add_row(block, start);
867
34
        VLOG_DEBUG << fmt::format("append a row directly, rid={}", start);
868
34
        return Status::OK();
869
34
    }
870
871
99
    auto seq_col_unique_id = _tablet_schema.column(_tablet_schema.sequence_col_idx()).unique_id();
872
99
    auto delete_sign_col_unique_id =
873
99
            _tablet_schema.column(_tablet_schema.delete_sign_idx()).unique_id();
874
875
99
    _state.reset();
876
877
99
    RowLocation loc;
878
99
    RowsetSharedPtr rowset;
879
99
    std::string previous_encoded_seq_value {};
880
99
    Status st = _writer._tablet->lookup_row_key(
881
99
            key, &_tablet_schema, false, specified_rowsets, &loc, _writer._mow_context->max_version,
882
99
            segment_caches, &rowset, true, &previous_encoded_seq_value);
883
99
    int pos = start;
884
99
    bool is_expected_st = (st.is<ErrorCode::KEY_NOT_FOUND>() || st.ok());
885
99
    DCHECK(is_expected_st || st.is<ErrorCode::MEM_LIMIT_EXCEEDED>())
886
0
            << "[BlockAggregator::aggregate_rows] unexpected error status while lookup_row_key:"
887
0
            << st;
888
99
    if (!is_expected_st) {
889
0
        return st;
890
0
    }
891
892
99
    std::string cur_seq_val;
893
99
    if (st.ok()) {
894
97
        for (pos = start; pos < end; pos++) {
895
97
            auto& skip_bitmap = skip_bitmaps->at(pos);
896
97
            bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
897
            // Discard all the rows whose seq value is smaller than previous_encoded_seq_value.
898
97
            if (row_has_sequence_col) {
899
56
                std::string seq_val {};
900
56
                _writer._encode_seq_column(seq_column, pos, &seq_val);
901
56
                if (Slice {seq_val}.compare(Slice {previous_encoded_seq_value}) < 0) {
902
19
                    continue;
903
19
                }
904
37
                cur_seq_val = std::move(seq_val);
905
37
                break;
906
56
            }
907
41
            cur_seq_val = std::move(previous_encoded_seq_value);
908
41
            break;
909
97
        }
910
78
    } else {
911
21
        pos = start;
912
21
        auto& skip_bitmap = skip_bitmaps->at(pos);
913
21
        bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
914
21
        if (row_has_sequence_col) {
915
15
            std::string seq_val {};
916
            // for rows that don't specify seqeunce col, seq_val will be encoded to minial value
917
15
            _writer._encode_seq_column(seq_column, pos, &seq_val);
918
15
            cur_seq_val = std::move(seq_val);
919
15
        } else {
920
6
            cur_seq_val.clear();
921
6
            RETURN_IF_ERROR(_writer._generate_encoded_default_seq_value(
922
6
                    _tablet_schema, *_writer._opts.rowset_ctx->partial_update_info, &cur_seq_val));
923
6
        }
924
21
    }
925
926
562
    for (int rid {pos}; rid < end; rid++) {
927
463
        auto& skip_bitmap = skip_bitmaps->at(rid);
928
463
        bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
929
463
        bool have_delete_sign =
930
463
                (!skip_bitmap.contains(delete_sign_col_unique_id) && delete_signs[rid] != 0);
931
463
        if (!row_has_sequence_col) {
932
193
            append_or_merge_row(output_block, block, rid, skip_bitmap, have_delete_sign);
933
270
        } else {
934
270
            std::string seq_val {};
935
270
            _writer._encode_seq_column(seq_column, rid, &seq_val);
936
270
            if (Slice {seq_val}.compare(Slice {cur_seq_val}) >= 0) {
937
212
                append_or_merge_row(output_block, block, rid, skip_bitmap, have_delete_sign);
938
212
                cur_seq_val = std::move(seq_val);
939
212
            } else {
940
58
                VLOG_DEBUG << fmt::format(
941
0
                        "skip rid={} becasue its seq value is lower than the previous", rid);
942
58
            }
943
270
        }
944
463
    }
945
99
    return Status::OK();
946
99
};
947
948
Status BlockAggregator::aggregate_for_sequence_column(
949
        Block* block, int num_rows, const std::vector<IOlapColumnDataAccessor*>& key_columns,
950
        IOlapColumnDataAccessor* seq_column, const std::vector<RowsetSharedPtr>& specified_rowsets,
951
25
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
952
25
    DCHECK_EQ(block->columns(), _tablet_schema.num_columns());
953
    // the process logic here is the same as MemTable::_aggregate_for_flexible_partial_update_without_seq_col()
954
    // after this function, there will be at most 2 rows for a specified key
955
25
    std::vector<BitmapValue>* skip_bitmaps = &(
956
25
            assert_cast<ColumnBitmap*>(block->get_by_position(_tablet_schema.skip_bitmap_col_idx())
957
25
                                               .column->assume_mutable()
958
25
                                               .get())
959
25
                    ->get_data());
960
25
    const auto* delete_signs = BaseTablet::get_delete_sign_column_data(*block, num_rows);
961
962
25
    auto filtered_block = _tablet_schema.create_block();
963
25
    MutableBlock output_block = MutableBlock::build_mutable_block(&filtered_block);
964
965
25
    int same_key_rows {0};
966
25
    std::string previous_key {};
967
541
    for (int block_pos {0}; block_pos < num_rows; block_pos++) {
968
516
        std::string key = _writer._full_encode_keys(key_columns, block_pos);
969
516
        if (block_pos > 0 && previous_key == key) {
970
383
            same_key_rows++;
971
383
        } else {
972
133
            if (same_key_rows > 0) {
973
108
                RETURN_IF_ERROR(aggregate_rows(output_block, block, block_pos - same_key_rows,
974
108
                                               block_pos, std::move(previous_key), skip_bitmaps,
975
108
                                               delete_signs, seq_column, specified_rowsets,
976
108
                                               segment_caches));
977
108
            }
978
133
            same_key_rows = 1;
979
133
        }
980
516
        previous_key = std::move(key);
981
516
    }
982
25
    if (same_key_rows > 0) {
983
25
        RETURN_IF_ERROR(aggregate_rows(output_block, block, num_rows - same_key_rows, num_rows,
984
25
                                       std::move(previous_key), skip_bitmaps, delete_signs,
985
25
                                       seq_column, specified_rowsets, segment_caches));
986
25
    }
987
988
25
    block->swap(output_block.to_block());
989
25
    return Status::OK();
990
25
}
991
992
Status BlockAggregator::fill_sequence_column(Block* block, size_t num_rows,
993
                                             const FixedReadPlan& read_plan,
994
4
                                             std::vector<BitmapValue>& skip_bitmaps) {
995
4
    DCHECK(_tablet_schema.has_sequence_col());
996
4
    std::vector<uint32_t> cids {static_cast<uint32_t>(_tablet_schema.sequence_col_idx())};
997
4
    auto seq_col_unique_id = _tablet_schema.column(_tablet_schema.sequence_col_idx()).unique_id();
998
999
4
    auto seq_col_block = _tablet_schema.create_block_by_cids(cids);
1000
4
    auto tmp_block = _tablet_schema.create_block_by_cids(cids);
1001
4
    std::map<uint32_t, uint32_t> read_index;
1002
4
    RETURN_IF_ERROR(read_plan.read_columns_by_plan(_tablet_schema, cids, _writer._rsid_to_rowset,
1003
4
                                                   seq_col_block, &read_index, false));
1004
1005
4
    auto new_seq_col_ptr = tmp_block.get_by_position(0).column->assume_mutable();
1006
4
    const auto& old_seq_col_ptr = *seq_col_block.get_by_position(0).column;
1007
4
    const auto& cur_seq_col_ptr = *block->get_by_position(_tablet_schema.sequence_col_idx()).column;
1008
80
    for (uint32_t block_pos {0}; block_pos < num_rows; block_pos++) {
1009
76
        if (read_index.contains(block_pos)) {
1010
14
            new_seq_col_ptr->insert_from(old_seq_col_ptr, read_index[block_pos]);
1011
14
            skip_bitmaps[block_pos].remove(seq_col_unique_id);
1012
62
        } else {
1013
62
            new_seq_col_ptr->insert_from(cur_seq_col_ptr, block_pos);
1014
62
        }
1015
76
    }
1016
4
    block->replace_by_position(_tablet_schema.sequence_col_idx(), std::move(new_seq_col_ptr));
1017
4
    return Status::OK();
1018
4
}
1019
1020
Status BlockAggregator::aggregate_for_insert_after_delete(
1021
        Block* block, size_t num_rows, const std::vector<IOlapColumnDataAccessor*>& key_columns,
1022
        const std::vector<RowsetSharedPtr>& specified_rowsets,
1023
265
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
1024
265
    DCHECK_EQ(block->columns(), _tablet_schema.num_columns());
1025
    // there will be at most 2 rows for a specified key in block when control flow reaches here
1026
    // after this function, there will not be duplicate rows in block
1027
1028
265
    std::vector<BitmapValue>* skip_bitmaps = &(
1029
265
            assert_cast<ColumnBitmap*>(block->get_by_position(_tablet_schema.skip_bitmap_col_idx())
1030
265
                                               .column->assume_mutable()
1031
265
                                               .get())
1032
265
                    ->get_data());
1033
265
    const auto* delete_signs = BaseTablet::get_delete_sign_column_data(*block, num_rows);
1034
1035
265
    auto filter_column = ColumnUInt8::create(num_rows, 1);
1036
265
    auto* __restrict filter_map = filter_column->get_data().data();
1037
265
    std::string previous_key {};
1038
265
    bool previous_has_delete_sign {false};
1039
265
    int duplicate_rows {0};
1040
265
    int32_t delete_sign_col_unique_id =
1041
265
            _tablet_schema.column(_tablet_schema.delete_sign_idx()).unique_id();
1042
265
    auto seq_col_unique_id =
1043
265
            (_tablet_schema.sequence_col_idx() != -1)
1044
265
                    ? _tablet_schema.column(_tablet_schema.sequence_col_idx()).unique_id()
1045
265
                    : -1;
1046
265
    FixedReadPlan read_plan;
1047
2.45k
    for (size_t block_pos {0}; block_pos < num_rows; block_pos++) {
1048
2.19k
        size_t delta_pos = block_pos;
1049
2.19k
        auto& skip_bitmap = skip_bitmaps->at(block_pos);
1050
2.19k
        std::string key = _writer._full_encode_keys(key_columns, delta_pos);
1051
2.19k
        bool have_delete_sign =
1052
2.19k
                (!skip_bitmap.contains(delete_sign_col_unique_id) && delete_signs[block_pos] != 0);
1053
2.19k
        if (delta_pos > 0 && previous_key == key) {
1054
            // !!ATTENTION!!: We can only remove the row with delete sign if there is a insert with the same key after this row.
1055
            // If there is only a row with delete sign, we should keep it and can't remove it from block, because
1056
            // compaction will not use the delete bitmap when reading data. So there may still be rows with delete sign
1057
            // in later process
1058
43
            DCHECK(previous_has_delete_sign);
1059
43
            DCHECK(!have_delete_sign);
1060
43
            ++duplicate_rows;
1061
43
            RowLocation loc;
1062
43
            RowsetSharedPtr rowset;
1063
43
            Status st = _writer._tablet->lookup_row_key(
1064
43
                    key, &_tablet_schema, false, specified_rowsets, &loc,
1065
43
                    _writer._mow_context->max_version, segment_caches, &rowset, true);
1066
43
            bool is_expected_st = (st.is<ErrorCode::KEY_NOT_FOUND>() || st.ok());
1067
43
            DCHECK(is_expected_st || st.is<ErrorCode::MEM_LIMIT_EXCEEDED>())
1068
0
                    << "[BlockAggregator::aggregate_for_insert_after_delete] unexpected error "
1069
0
                       "status while lookup_row_key:"
1070
0
                    << st;
1071
43
            if (!is_expected_st) {
1072
0
                return st;
1073
0
            }
1074
1075
43
            Slice previous_seq_slice {};
1076
43
            if (st.ok()) {
1077
38
                if (_tablet_schema.has_sequence_col()) {
1078
                    // if the insert row doesn't specify the sequence column, we need to
1079
                    // read the historical's sequence column value so that we don't need
1080
                    // to handle seqeunce column in append_block_with_flexible_content()
1081
                    // for this row
1082
34
                    bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
1083
34
                    if (!row_has_sequence_col) {
1084
14
                        read_plan.prepare_to_read(loc, block_pos);
1085
14
                        _writer._rsid_to_rowset.emplace(rowset->rowset_id(), rowset);
1086
14
                    }
1087
34
                }
1088
                // delete the existing row
1089
38
                _writer._mow_context->delete_bitmap->add(
1090
38
                        {loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
1091
38
                        loc.row_id);
1092
38
            }
1093
            // and remove the row with delete sign from the current block
1094
43
            filter_map[block_pos - 1] = 0;
1095
43
        }
1096
2.19k
        previous_has_delete_sign = have_delete_sign;
1097
2.19k
        previous_key = std::move(key);
1098
2.19k
    }
1099
265
    if (duplicate_rows > 0) {
1100
9
        if (!read_plan.empty()) {
1101
            // fill sequence column value for some rows
1102
4
            RETURN_IF_ERROR(fill_sequence_column(block, num_rows, read_plan, *skip_bitmaps));
1103
4
        }
1104
9
        RETURN_IF_ERROR(filter_block(block, num_rows, std::move(filter_column), duplicate_rows,
1105
9
                                     "__filter_insert_after_delete_col__"));
1106
9
    }
1107
265
    return Status::OK();
1108
265
}
1109
1110
Status BlockAggregator::filter_block(Block* block, size_t num_rows, MutableColumnPtr filter_column,
1111
9
                                     int duplicate_rows, std::string col_name) {
1112
9
    auto num_cols = block->columns();
1113
9
    block->insert({std::move(filter_column), std::make_shared<DataTypeUInt8>(), col_name});
1114
9
    RETURN_IF_ERROR(Block::filter_block(block, num_cols, num_cols));
1115
9
    DCHECK_EQ(num_cols, block->columns());
1116
9
    size_t merged_rows = num_rows - block->rows();
1117
9
    if (duplicate_rows != merged_rows) {
1118
0
        auto msg = fmt::format(
1119
0
                "filter_block_for_flexible_partial_update {}: duplicate_rows != merged_rows, "
1120
0
                "duplicate_keys={}, merged_rows={}, num_rows={}, mutable_block->rows()={}",
1121
0
                col_name, duplicate_rows, merged_rows, num_rows, block->rows());
1122
0
        DCHECK(false) << msg;
1123
0
        return Status::InternalError<false>(msg);
1124
0
    }
1125
9
    return Status::OK();
1126
9
}
1127
1128
Status BlockAggregator::convert_pk_columns(Block* block, size_t row_pos, size_t num_rows,
1129
544
                                           std::vector<IOlapColumnDataAccessor*>& key_columns) {
1130
544
    key_columns.clear();
1131
1.14k
    for (uint32_t cid {0}; cid < _tablet_schema.num_key_columns(); cid++) {
1132
605
        RETURN_IF_ERROR(_writer._olap_data_convertor->set_source_content_with_specifid_column(
1133
605
                block->get_by_position(cid), row_pos, num_rows, cid));
1134
605
        auto [status, column] = _writer._olap_data_convertor->convert_column_data(cid);
1135
605
        if (!status.ok()) {
1136
0
            return status;
1137
0
        }
1138
605
        key_columns.push_back(column);
1139
605
    }
1140
544
    return Status::OK();
1141
544
}
1142
1143
Status BlockAggregator::convert_seq_column(Block* block, size_t row_pos, size_t num_rows,
1144
544
                                           IOlapColumnDataAccessor*& seq_column) {
1145
544
    seq_column = nullptr;
1146
544
    if (_tablet_schema.has_sequence_col()) {
1147
65
        auto seq_col_idx = _tablet_schema.sequence_col_idx();
1148
65
        RETURN_IF_ERROR(_writer._olap_data_convertor->set_source_content_with_specifid_column(
1149
65
                block->get_by_position(seq_col_idx), row_pos, num_rows, seq_col_idx));
1150
65
        auto [status, column] = _writer._olap_data_convertor->convert_column_data(seq_col_idx);
1151
65
        if (!status.ok()) {
1152
0
            return status;
1153
0
        }
1154
65
        seq_column = column;
1155
65
    }
1156
544
    return Status::OK();
1157
544
};
1158
1159
Status BlockAggregator::aggregate_for_flexible_partial_update(
1160
        Block* block, size_t num_rows, const std::vector<RowsetSharedPtr>& specified_rowsets,
1161
264
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
1162
264
    std::vector<IOlapColumnDataAccessor*> key_columns {};
1163
264
    IOlapColumnDataAccessor* seq_column {nullptr};
1164
1165
264
    RETURN_IF_ERROR(convert_pk_columns(block, 0, num_rows, key_columns));
1166
264
    RETURN_IF_ERROR(convert_seq_column(block, 0, num_rows, seq_column));
1167
1168
    // 1. merge duplicate rows when table has sequence column
1169
    // When there are multiple rows with the same keys in memtable, some of them specify specify the sequence column,
1170
    // some of them don't. We can't do the de-duplication in memtable because we don't know the historical data. We must
1171
    // de-duplicate them here.
1172
264
    if (_tablet_schema.has_sequence_col()) {
1173
25
        RETURN_IF_ERROR(aggregate_for_sequence_column(block, static_cast<int>(num_rows),
1174
25
                                                      key_columns, seq_column, specified_rowsets,
1175
25
                                                      segment_caches));
1176
25
    }
1177
1178
    // 2. merge duplicate rows and handle insert after delete
1179
264
    if (block->rows() != num_rows) {
1180
15
        num_rows = block->rows();
1181
        // data in block has changed, should re-encode key columns, sequence column
1182
15
        _writer._olap_data_convertor->clear_source_content();
1183
15
        RETURN_IF_ERROR(convert_pk_columns(block, 0, num_rows, key_columns));
1184
15
        RETURN_IF_ERROR(convert_seq_column(block, 0, num_rows, seq_column));
1185
15
    }
1186
264
    RETURN_IF_ERROR(aggregate_for_insert_after_delete(block, num_rows, key_columns,
1187
264
                                                      specified_rowsets, segment_caches));
1188
264
    return Status::OK();
1189
264
}
1190
1191
} // namespace doris