Coverage Report

Created: 2026-04-14 03:58

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