Coverage Report

Created: 2026-03-15 17:28

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