Coverage Report

Created: 2026-07-28 21:09

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