• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

realm / realm-core / nicola.cabiddu_1042

27 Sep 2023 06:04PM UTC coverage: 91.085% (-1.8%) from 92.915%
nicola.cabiddu_1042

Pull #6766

Evergreen

nicola-cab
Fix logic for dictionaries
Pull Request #6766: Client Reset for collections in mixed / nested collections

97276 of 178892 branches covered (0.0%)

1994 of 2029 new or added lines in 7 files covered. (98.28%)

4556 existing lines in 112 files now uncovered.

237059 of 260260 relevant lines covered (91.09%)

6321099.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.33
/src/realm/index_string.cpp
1
/*************************************************************************
2
 *
3
 * Copyright 2016 Realm Inc.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * 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, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 *
17
 **************************************************************************/
18

19
#include <cstdio>
20
#include <iomanip>
21
#include <list>
22

23
#ifdef REALM_DEBUG
24
#include <iostream>
25
#endif
26

27
#include <realm/exceptions.hpp>
28
#include <realm/index_string.hpp>
29
#include <realm/table.hpp>
30
#include <realm/timestamp.hpp>
31
#include <realm/column_integer.hpp>
32
#include <realm/unicode.hpp>
33
#include <realm/tokenizer.hpp>
34

35
using namespace realm;
36
using namespace realm::util;
37

38
namespace {
39

40
void get_child(Array& parent, size_t child_ref_ndx, Array& child) noexcept
41
{
19,892,763✔
42
    ref_type child_ref = parent.get_as_ref(child_ref_ndx);
19,892,763✔
43
    child.init_from_ref(child_ref);
19,892,763✔
44
    child.set_parent(&parent, child_ref_ndx);
19,892,763✔
45
}
19,892,763✔
46

47
// This method reconstructs the string inserted in the search index based on a string
48
// that matches so far and the last key (only works if complete strings are stored in the index)
49
static StringData reconstruct_string(size_t offset, StringIndex::key_type key, StringData new_string)
50
{
1,086✔
51
    if (key == 0)
1,086✔
52
        return StringData();
×
53

543✔
54
    size_t rest_len = 4;
1,086✔
55
    char* k = reinterpret_cast<char*>(&key);
1,086✔
56
    if (k[0] == 'X')
1,086✔
57
        rest_len = 3;
234✔
58
    else if (k[1] == 'X')
852✔
59
        rest_len = 2;
360✔
60
    else if (k[2] == 'X')
492✔
61
        rest_len = 1;
228✔
62
    else if (k[3] == 'X')
264✔
63
        rest_len = 0;
36✔
64

543✔
65
    REALM_ASSERT(offset + rest_len <= new_string.size());
1,086✔
66

543✔
67
    return StringData(new_string.data(), offset + rest_len);
1,086✔
68
}
1,086✔
69

70

71
} // anonymous namespace
72

73
DataType ClusterColumn::get_data_type() const
74
{
×
75
    const Table* table = m_cluster_tree->get_owning_table();
×
76
    return table->get_column_type(m_column_key);
×
77
}
×
78

79
Mixed ClusterColumn::get_value(ObjKey key) const
80
{
43,578,255✔
81
    const Obj obj{m_cluster_tree->get(key)};
43,578,255✔
82
    return obj.get_any(m_column_key);
43,578,255✔
83
}
43,578,255✔
84

85
std::vector<ObjKey> ClusterColumn::get_all_keys() const
86
{
18✔
87
    std::vector<ObjKey> ret;
18✔
88
    ret.reserve(m_cluster_tree->size());
18✔
89
    m_cluster_tree->traverse([&ret](const Cluster* cluster) {
18✔
90
        auto sz = cluster->node_size();
18✔
91
        for (size_t i = 0; i < sz; i++) {
198✔
92
            ret.push_back(cluster->get_real_key(i));
180✔
93
        }
180✔
94

9✔
95
        return IteratorControl::AdvanceToNext;
18✔
96
    });
18✔
97
    return ret;
18✔
98
}
18✔
99

100
template <>
101
int64_t IndexArray::from_list<index_FindFirst>(const Mixed& value, InternalFindResult& /* result_ref */,
102
                                               const IntegerColumn& key_values, const ClusterColumn& column) const
103
{
5,283✔
104
    SortedListComparator slc(column);
5,283✔
105

2,808✔
106
    IntegerColumn::const_iterator it_end = key_values.cend();
5,283✔
107
    IntegerColumn::const_iterator lower = std::lower_bound(key_values.cbegin(), it_end, value, slc);
5,283✔
108
    if (lower == it_end)
5,283✔
109
        return null_key.value;
×
110

2,808✔
111
    int64_t first_key_value = *lower;
5,283✔
112

2,808✔
113
    Mixed actual = column.get_value(ObjKey(first_key_value));
5,283✔
114
    if (actual != value)
5,283✔
115
        return null_key.value;
×
116

2,808✔
117
    return first_key_value;
5,283✔
118
}
5,283✔
119

120
template <>
121
int64_t IndexArray::from_list<index_Count>(const Mixed& value, InternalFindResult& /* result_ref */,
122
                                           const IntegerColumn& key_values, const ClusterColumn& column) const
123
{
8,166✔
124
    SortedListComparator slc(column);
8,166✔
125

4,062✔
126
    IntegerColumn::const_iterator it_end = key_values.cend();
8,166✔
127
    IntegerColumn::const_iterator lower = std::lower_bound(key_values.cbegin(), it_end, value, slc);
8,166✔
128
    if (lower == it_end)
8,166✔
129
        return 0;
24✔
130

4,050✔
131
    int64_t first_key_value = *lower;
8,142✔
132

4,050✔
133
    Mixed actual = column.get_value(ObjKey(first_key_value));
8,142✔
134
    if (actual != value)
8,142✔
135
        return 0;
24✔
136

4,038✔
137
    IntegerColumn::const_iterator upper = std::upper_bound(lower, it_end, value, slc);
8,118✔
138
    int64_t cnt = upper - lower;
8,118✔
139

4,038✔
140
    return cnt;
8,118✔
141
}
8,118✔
142

143
template <>
144
int64_t IndexArray::from_list<index_FindAll_nocopy>(const Mixed& value, InternalFindResult& result_ref,
145
                                                    const IntegerColumn& key_values,
146
                                                    const ClusterColumn& column) const
147
{
2,220✔
148
    SortedListComparator slc(column);
2,220✔
149
    IntegerColumn::const_iterator it_end = key_values.cend();
2,220✔
150
    IntegerColumn::const_iterator lower = std::lower_bound(key_values.cbegin(), it_end, value, slc);
2,220✔
151
    if (lower == it_end)
2,220✔
152
        return size_t(FindRes_not_found);
57✔
153

1,089✔
154
    ObjKey first_key = ObjKey(*lower);
2,163✔
155

1,089✔
156
    Mixed actual = column.get_value(ObjKey(first_key));
2,163✔
157
    if (actual != value)
2,163✔
158
        return size_t(FindRes_not_found);
60✔
159

1,059✔
160
    // Optimization: check the last entry before trying upper bound.
1,059✔
161
    IntegerColumn::const_iterator upper = it_end;
2,103✔
162
    --upper;
2,103✔
163
    // Single result if upper matches lower
1,059✔
164
    if (upper == lower) {
2,103✔
165
        result_ref.payload = *lower;
339✔
166
        return size_t(FindRes_single);
339✔
167
    }
339✔
168

888✔
169
    // Check string value at upper, if equal return matches in (lower, upper]
888✔
170
    ObjKey last_key = ObjKey(*upper);
1,764✔
171
    actual = column.get_value(ObjKey(last_key));
1,764✔
172
    if (actual == value) {
1,764✔
173
        result_ref.payload = from_ref(key_values.get_ref());
1,212✔
174
        result_ref.start_ndx = lower.get_position();
1,212✔
175
        result_ref.end_ndx = upper.get_position() + 1; // one past last match
1,212✔
176
        return size_t(FindRes_column);
1,212✔
177
    }
1,212✔
178

273✔
179
    // Last result is not equal, find the upper bound of the range of results.
273✔
180
    // Note that we are passing upper which is cend() - 1 here as we already
273✔
181
    // checked the last item manually.
273✔
182
    upper = std::upper_bound(lower, upper, value, slc);
552✔
183

273✔
184
    result_ref.payload = from_ref(key_values.get_ref());
552✔
185
    result_ref.start_ndx = lower.get_position();
552✔
186
    result_ref.end_ndx = upper.get_position();
552✔
187
    return size_t(FindRes_column);
552✔
188
}
552✔
189

190

191
template <IndexMethod method>
192
int64_t IndexArray::index_string(const Mixed& value, InternalFindResult& result_ref,
193
                                 const ClusterColumn& column) const
194
{
2,272,182✔
195
    // Return`realm::not_found`, or an index to the (any) match
1,128,225✔
196
    constexpr bool first(method == index_FindFirst);
2,272,182✔
197
    // Return 0, or the number of items that match the specified `value`
1,128,225✔
198
    constexpr bool get_count(method == index_Count);
2,272,182✔
199
    // Same as `index_FindAll` but does not copy matching rows into `column`
1,128,225✔
200
    // returns FindRes_not_found if there are no matches
1,128,225✔
201
    // returns FindRes_single and the row index (literal) in result_ref.payload
1,128,225✔
202
    // or returns FindRes_column and the reference to a column of duplicates in
1,128,225✔
203
    // result_ref.result with the results in the bounds start_ndx, and end_ndx
1,128,225✔
204
    constexpr bool allnocopy(method == index_FindAll_nocopy);
2,272,182✔
205

1,128,225✔
206
    constexpr int64_t local_not_found = allnocopy ? int64_t(FindRes_not_found) : first ? null_key.value : 0;
2,272,182✔
207

1,128,225✔
208
    const char* data = m_data;
2,272,182✔
209
    const char* header;
2,272,182✔
210
    uint_least8_t width = m_width;
2,272,182✔
211
    bool is_inner_node = m_is_inner_bptree_node;
2,272,182✔
212
    typedef StringIndex::key_type key_type;
2,272,182✔
213
    size_t stringoffset = 0;
2,272,182✔
214

1,128,225✔
215
    StringConversionBuffer buffer;
2,272,182✔
216
    StringData index_data = value.get_index_data(buffer);
2,272,182✔
217

1,128,225✔
218
    // Create 4 byte index key
1,128,225✔
219
    key_type key = StringIndex::create_key(index_data, stringoffset);
2,272,182✔
220

1,128,225✔
221
    for (;;) {
2,767,365✔
222
        // Get subnode table
1,379,220✔
223
        ref_type offsets_ref = to_ref(get_direct(data, width, 0));
2,767,365✔
224

1,379,220✔
225
        // Find the position matching the key
1,379,220✔
226
        const char* offsets_header = m_alloc.translate(offsets_ref);
2,767,365✔
227
        const char* offsets_data = get_data_from_header(offsets_header);
2,767,365✔
228
        size_t offsets_size = get_size_from_header(offsets_header);
2,767,365✔
229
        size_t pos = ::lower_bound<32>(offsets_data, offsets_size, key); // keys are always 32 bits wide
2,767,365✔
230

1,379,220✔
231
        // If key is outside range, we know there can be no match
1,379,220✔
232
        if (pos == offsets_size)
2,767,365✔
233
            return local_not_found;
905,814✔
234

928,419✔
235
        // Get entry under key
928,419✔
236
        size_t pos_refs = pos + 1; // first entry in refs points to offsets
1,861,551✔
237
        uint64_t ref = get_direct(data, width, pos_refs);
1,861,551✔
238

928,419✔
239
        if (is_inner_node) {
1,861,551✔
240
            // Set vars for next iteration
26,652✔
241
            header = m_alloc.translate(to_ref(ref));
62,262✔
242
            data = get_data_from_header(header);
62,262✔
243
            width = get_width_from_header(header);
62,262✔
244
            is_inner_node = get_is_inner_bptree_node_from_header(header);
62,262✔
245
            continue;
62,262✔
246
        }
62,262✔
247

901,767✔
248
        key_type stored_key = key_type(get_direct<32>(offsets_data, pos));
1,799,289✔
249

901,767✔
250
        if (stored_key != key)
1,799,289✔
251
            return local_not_found;
280,128✔
252

769,923✔
253
        // Literal row index (tagged)
769,923✔
254
        if (ref & 1) {
1,519,161✔
255
            int64_t key_value = int64_t(ref >> 1);
1,070,436✔
256

537,561✔
257
            Mixed a = column.is_fulltext() ? reconstruct_string(stringoffset, key, index_data)
537,645✔
258
                                           : column.get_value(ObjKey(key_value));
1,070,352✔
259
            if (a == value) {
1,070,436✔
260
                result_ref.payload = key_value;
1,067,625✔
261
                return first ? key_value : get_count ? 1 : FindRes_single;
1,058,484✔
262
            }
1,067,625✔
263
            return local_not_found;
2,811✔
264
        }
2,811✔
265

232,362✔
266
        const char* sub_header = m_alloc.translate(ref_type(ref));
448,725✔
267
        const bool sub_isindex = get_context_flag_from_header(sub_header);
448,725✔
268

232,362✔
269
        // List of row indices with common prefix up to this point, in sorted order.
232,362✔
270
        if (!sub_isindex) {
448,725✔
271
            const IntegerColumn sub(m_alloc, ref_type(ref));
15,957✔
272
            if (column.is_fulltext()) {
15,957✔
273
                result_ref.payload = ref;
288✔
274
                result_ref.start_ndx = 0;
288✔
275
                result_ref.end_ndx = sub.size();
288✔
276
                return FindRes_column;
288✔
277
            }
288✔
278

7,986✔
279
            return from_list<method>(value, result_ref, sub, column);
15,669✔
280
        }
15,669✔
281

224,232✔
282
        // Recurse into sub-index;
224,232✔
283
        header = sub_header;
432,768✔
284
        data = get_data_from_header(header);
432,768✔
285
        width = get_width_from_header(header);
432,768✔
286
        is_inner_node = get_is_inner_bptree_node_from_header(header);
432,768✔
287

224,232✔
288
        // Go to next key part of the string. If the offset exceeds the string length, the key will be 0
224,232✔
289
        stringoffset += 4;
432,768✔
290

224,232✔
291
        // Update 4 byte index key
224,232✔
292
        key = StringIndex::create_key(index_data, stringoffset);
432,768✔
293
    }
432,768✔
294
}
2,272,182✔
295

296

297
void IndexArray::from_list_all_ins(StringData upper_value, std::vector<ObjKey>& result, const IntegerColumn& rows,
298
                                   const ClusterColumn& column) const
299
{
1,422✔
300
    // optimization for the most common case, where all the strings under a given subindex are equal
711✔
301
    Mixed first = column.get_value(ObjKey(*rows.cbegin()));
1,422✔
302
    Mixed last = column.get_value(ObjKey(*(rows.cend() - 1)));
1,422✔
303
    if (first == last) {
1,422✔
304
        if (!first.is_type(type_String))
102✔
UNCOV
305
            return;
×
306
        auto first_str_upper = case_map(first.get_string(), true);
102✔
307
        if (first_str_upper != upper_value) {
102✔
308
            return;
24✔
309
        }
24✔
310

39✔
311
        size_t sz = result.size() + rows.size();
78✔
312
        result.reserve(sz);
78✔
313
        for (IntegerColumn::const_iterator it = rows.cbegin(); it != rows.cend(); ++it) {
246✔
314
            result.push_back(ObjKey(*it));
168✔
315
        }
168✔
316
        return;
78✔
317
    }
78✔
318

660✔
319
    // special case for very long strings, where they might have a common prefix and end up in the
660✔
320
    // same subindex column, but still not be identical
660✔
321
    for (IntegerColumn::const_iterator it = rows.cbegin(); it != rows.cend(); ++it) {
66,792✔
322
        ObjKey key = ObjKey(*it);
65,472✔
323
        Mixed val = column.get_value(key);
65,472✔
324
        if (val.is_type(type_String)) {
65,472✔
325
            auto upper_str = case_map(val.get_string(), true);
65,472✔
326
            if (upper_str == upper_value) {
65,472✔
327
                result.push_back(key);
1,440✔
328
            }
1,440✔
329
        }
65,472✔
330
    }
65,472✔
331

660✔
332
    return;
1,320✔
333
}
1,320✔
334

335

336
void IndexArray::from_list_all(const Mixed& value, std::vector<ObjKey>& result, const IntegerColumn& rows,
337
                               const ClusterColumn& column) const
338
{
42,885✔
339
    SortedListComparator slc(column);
42,885✔
340

21,135✔
341
    IntegerColumn::const_iterator it_end = rows.cend();
42,885✔
342
    IntegerColumn::const_iterator lower = std::lower_bound(rows.cbegin(), it_end, value, slc);
42,885✔
343
    if (lower == it_end)
42,885✔
UNCOV
344
        return;
×
345

21,135✔
346
    ObjKey key = ObjKey(*lower);
42,885✔
347

21,135✔
348
    Mixed a = column.get_value(key);
42,885✔
349
    if (a != value)
42,885✔
UNCOV
350
        return;
×
351

21,135✔
352
    IntegerColumn::const_iterator upper = std::upper_bound(lower, it_end, value, slc);
42,885✔
353

21,135✔
354
    // Copy all matches into result column
21,135✔
355
    size_t sz = result.size() + (upper - lower);
42,885✔
356
    result.reserve(sz);
42,885✔
357
    for (IntegerColumn::const_iterator it = lower; it != upper; ++it) {
813,783✔
358
        result.push_back(ObjKey(*it));
770,898✔
359
    }
770,898✔
360

21,135✔
361
    return;
42,885✔
362
}
42,885✔
363

364

365
namespace {
366

367
// Helper functions for SearchList (index_string_all_ins) for generating permutations of index keys
368

369
// replicates the 4 least significant bits each times 8
370
// eg: abcd -> aaaaaaaabbbbbbbbccccccccdddddddd
371
uint32_t replicate_4_lsb_x8(uint32_t i)
372
{
3,123,744✔
373
    REALM_ASSERT_DEBUG(i <= 15);
3,123,744✔
374
    i *= 0x204081;
3,123,744✔
375
    i &= 0x1010101;
3,123,744✔
376
    i *= 0xff;
3,123,744✔
377
    return i;
3,123,744✔
378
}
3,123,744✔
379

380
int32_t select_from_mask(int32_t a, int32_t b, int32_t mask) {
3,123,744✔
381
    return a ^ ((a ^ b) & mask);
3,123,744✔
382
}
3,123,744✔
383

384
// Given upper and lower keys: "ABCD" and "abcd", the 4 LSBs in the permutation argument determine the
385
// final key:
386
// Permutation 0  = "ABCD"
387
// Permutation 1  = "ABCd"
388
// Permutation 8  = "aBCD"
389
// Permutation 15 = "abcd"
390
using key_type = StringIndex::key_type;
391
static key_type generate_key(key_type upper, key_type lower, int permutation)
392
{
3,123,744✔
393
    return select_from_mask(upper, lower, replicate_4_lsb_x8(permutation));
3,123,744✔
394
}
3,123,744✔
395

396

397
// Helper structure for IndexArray::index_string_all_ins to generate and keep track of search key permutations,
398
// when traversing the trees.
399
struct SearchList {
400
    struct Item {
401
        const char* header;
402
        size_t string_offset;
403
        key_type key;
404
    };
405

406
    SearchList(const util::Optional<std::string>& upper_value, const util::Optional<std::string>& lower_value)
407
        : m_upper_value(upper_value)
408
        , m_lower_value(lower_value)
409
    {
6,582✔
410
        m_keys_seen.reserve(num_permutations);
6,582✔
411
    }
6,582✔
412

413
    // Add all unique keys for this level to the internal work stack
414
    void add_all_for_level(const char* header, size_t string_offset)
415
    {
195,234✔
416
        m_keys_seen.clear();
195,234✔
417
        const key_type upper_key = StringIndex::create_key(m_upper_value, string_offset);
195,234✔
418
        const key_type lower_key = StringIndex::create_key(m_lower_value, string_offset);
195,234✔
419
        for (int p = 0; p < num_permutations; ++p) {
3,318,978✔
420
            // FIXME: This might still be incorrect due to multi-byte unicode characters (crossing the 4 byte key
1,561,872✔
421
            // size) being combined incorrectly.
1,561,872✔
422
            const key_type key = generate_key(upper_key, lower_key, p);
3,123,744✔
423
            const bool new_key = std::find(m_keys_seen.cbegin(), m_keys_seen.cend(), key) == m_keys_seen.cend();
3,123,744✔
424
            if (new_key) {
3,123,744✔
425
                m_keys_seen.push_back(key);
3,059,706✔
426
                add_next(header, string_offset, key);
3,059,706✔
427
            }
3,059,706✔
428
        }
3,123,744✔
429
    }
195,234✔
430

431
    bool empty() const
432
    {
3,066,288✔
433
        return m_items.empty();
3,066,288✔
434
    }
3,066,288✔
435

436
    Item get_next()
437
    {
3,059,706✔
438
        Item item = m_items.back();
3,059,706✔
439
        m_items.pop_back();
3,059,706✔
440
        return item;
3,059,706✔
441
    }
3,059,706✔
442

443
    // Add a single entry to the internal work stack. Used to traverse the inner trees (same key)
444
    void add_next(const char* header, size_t string_offset, key_type key)
445
    {
3,059,706✔
446
        m_items.push_back({header, string_offset, key});
3,059,706✔
447
    }
3,059,706✔
448

449
private:
450
    static constexpr int num_permutations = 1 << sizeof(key_type); // 4 bytes gives up to 16 search keys
451

452
    std::vector<Item> m_items;
453

454
    const util::Optional<std::string> m_upper_value;
455
    const util::Optional<std::string> m_lower_value;
456

457
    std::vector<key_type> m_keys_seen;
458
};
459

460

461
} // namespace
462

463

464
void IndexArray::index_string_all_ins(StringData value, std::vector<ObjKey>& result,
465
                                      const ClusterColumn& column) const
466
{
6,582✔
467
    REALM_ASSERT(!value.is_null());
6,582✔
468

3,291✔
469
    const util::Optional<std::string> upper_value = case_map(value, true);
6,582✔
470
    const util::Optional<std::string> lower_value = case_map(value, false);
6,582✔
471
    SearchList search_list(upper_value, lower_value);
6,582✔
472

3,291✔
473
    const char* top_header = get_header_from_data(m_data);
6,582✔
474
    search_list.add_all_for_level(top_header, 0);
6,582✔
475

3,291✔
476
    while (!search_list.empty()) {
3,066,288✔
477
        SearchList::Item item = search_list.get_next();
3,059,706✔
478

1,529,853✔
479
        const char* const header = item.header;
3,059,706✔
480
        const size_t string_offset = item.string_offset;
3,059,706✔
481
        const key_type key = item.key;
3,059,706✔
482
        const char* const data = get_data_from_header(header);
3,059,706✔
483
        const uint_least8_t width = get_width_from_header(header);
3,059,706✔
484
        const bool is_inner_node = get_is_inner_bptree_node_from_header(header);
3,059,706✔
485

1,529,853✔
486
        // Get subnode table
1,529,853✔
487
        ref_type offsets_ref = to_ref(get_direct(data, width, 0));
3,059,706✔
488

1,529,853✔
489
        // Find the position matching the key
1,529,853✔
490
        const char* const offsets_header = m_alloc.translate(offsets_ref);
3,059,706✔
491
        const char* const offsets_data = get_data_from_header(offsets_header);
3,059,706✔
492
        const size_t offsets_size = get_size_from_header(offsets_header);
3,059,706✔
493
        const size_t pos = ::lower_bound<32>(offsets_data, offsets_size, key); // keys are always 32 bits wide
3,059,706✔
494

1,529,853✔
495
        // If key is outside range, we know there can be no match
1,529,853✔
496
        if (pos == offsets_size)
3,059,706✔
497
            continue;
858✔
498

1,529,424✔
499
        // Get entry under key
1,529,424✔
500
        const size_t pos_refs = pos + 1; // first entry in refs points to offsets
3,058,848✔
501
        const uint64_t ref = get_direct(data, width, pos_refs);
3,058,848✔
502

1,529,424✔
503
        if (is_inner_node) {
3,058,848✔
504
            // Set vars for next iteration
505
            const char* const inner_header = m_alloc.translate(to_ref(ref));
×
506
            search_list.add_next(inner_header, string_offset, key);
×
UNCOV
507
            continue;
×
UNCOV
508
        }
×
509

1,529,424✔
510
        const key_type stored_key = key_type(get_direct<32>(offsets_data, pos));
3,058,848✔
511

1,529,424✔
512
        if (stored_key != key)
3,058,848✔
513
            continue;
2,863,128✔
514

97,860✔
515
        // Literal row index (tagged)
97,860✔
516
        if (ref & 1) {
195,720✔
517
            ObjKey k(int64_t(ref >> 1));
5,646✔
518

2,823✔
519
            // The buffer is needed when for when this is an integer index.
2,823✔
520
            StringConversionBuffer buffer;
5,646✔
521
            const StringData str = column.get_value(k).get_index_data(buffer);
5,646✔
522
            const util::Optional<std::string> upper_str = case_map(str, true);
5,646✔
523
            if (upper_str == upper_value) {
5,646✔
524
                result.push_back(k);
5,598✔
525
            }
5,598✔
526
            continue;
5,646✔
527
        }
5,646✔
528

95,037✔
529
        const char* const sub_header = m_alloc.translate(ref_type(ref));
190,074✔
530
        const bool sub_isindex = get_context_flag_from_header(sub_header);
190,074✔
531

95,037✔
532
        // List of row indices with common prefix up to this point, in sorted order.
95,037✔
533
        if (!sub_isindex) {
190,074✔
534
            const IntegerColumn sub(m_alloc, ref_type(ref));
1,422✔
535
            from_list_all_ins(upper_value, result, sub, column);
1,422✔
536
            continue;
1,422✔
537
        }
1,422✔
538

94,326✔
539
        // Recurse into sub-index;
94,326✔
540
        search_list.add_all_for_level(sub_header, string_offset + 4);
188,652✔
541
    }
188,652✔
542

3,291✔
543
    // sort the result and return a std::vector
3,291✔
544
    std::sort(result.begin(), result.end());
6,582✔
545
}
6,582✔
546

547

548
void IndexArray::index_string_all(const Mixed& value, std::vector<ObjKey>& result, const ClusterColumn& column) const
549
{
50,982✔
550
    const char* data = m_data;
50,982✔
551
    const char* header;
50,982✔
552
    uint_least8_t width = m_width;
50,982✔
553
    bool is_inner_node = m_is_inner_bptree_node;
50,982✔
554
    size_t stringoffset = 0;
50,982✔
555

25,080✔
556
    StringConversionBuffer buffer;
50,982✔
557
    StringData index_data = value.get_index_data(buffer);
50,982✔
558
    // Create 4 byte index key
25,080✔
559
    key_type key = StringIndex::create_key(index_data, stringoffset);
50,982✔
560

25,080✔
561
    for (;;) {
84,390✔
562
        // Get subnode table
40,719✔
563
        ref_type offsets_ref = to_ref(get_direct(data, width, 0));
84,390✔
564

40,719✔
565
        // Find the position matching the key
40,719✔
566
        const char* offsets_header = m_alloc.translate(offsets_ref);
84,390✔
567
        const char* offsets_data = get_data_from_header(offsets_header);
84,390✔
568
        size_t offsets_size = get_size_from_header(offsets_header);
84,390✔
569
        size_t pos = ::lower_bound<32>(offsets_data, offsets_size, key); // keys are always 32 bits wide
84,390✔
570

40,719✔
571
        // If key is outside range, we know there can be no match
40,719✔
572
        if (pos == offsets_size)
84,390✔
UNCOV
573
            return;
×
574

40,719✔
575
        // Get entry under key
40,719✔
576
        size_t pos_refs = pos + 1; // first entry in refs points to offsets
84,390✔
577
        uint64_t ref = get_direct(data, width, pos_refs);
84,390✔
578

40,719✔
579
        if (is_inner_node) {
84,390✔
580
            // Set vars for next iteration
581
            header = m_alloc.translate(ref_type(ref));
×
582
            data = get_data_from_header(header);
×
583
            width = get_width_from_header(header);
×
584
            is_inner_node = get_is_inner_bptree_node_from_header(header);
×
UNCOV
585
            continue;
×
UNCOV
586
        }
×
587

40,719✔
588
        key_type stored_key = key_type(get_direct<32>(offsets_data, pos));
84,390✔
589

40,719✔
590
        if (stored_key != key)
84,390✔
591
            return;
6,120✔
592

37,659✔
593
        // Literal row index (tagged)
37,659✔
594
        if (ref & 1) {
78,270✔
595
            ObjKey k(int64_t(ref >> 1));
1,977✔
596

885✔
597
            Mixed a = column.get_value(k);
1,977✔
598
            if (a == value) {
1,977✔
599
                result.push_back(k);
1,977✔
600
                return;
1,977✔
601
            }
1,977✔
UNCOV
602
            return;
×
UNCOV
603
        }
×
604

36,774✔
605
        const char* sub_header = m_alloc.translate(ref_type(ref));
76,293✔
606
        const bool sub_isindex = get_context_flag_from_header(sub_header);
76,293✔
607

36,774✔
608
        // List of row indices with common prefix up to this point, in sorted order.
36,774✔
609
        if (!sub_isindex) {
76,293✔
610
            const IntegerColumn sub(m_alloc, ref_type(ref));
42,885✔
611
            return from_list_all(value, result, sub, column);
42,885✔
612
        }
42,885✔
613

15,639✔
614
        // Recurse into sub-index;
15,639✔
615
        header = sub_header;
33,408✔
616
        data = get_data_from_header(header);
33,408✔
617
        width = get_width_from_header(header);
33,408✔
618
        is_inner_node = get_is_inner_bptree_node_from_header(header);
33,408✔
619

15,639✔
620
        // Go to next key part of the string. If the offset exceeds the string length, the key will be 0
15,639✔
621
        stringoffset += 4;
33,408✔
622

15,639✔
623
        // Update 4 byte index key
15,639✔
624
        key = StringIndex::create_key(index_data, stringoffset);
33,408✔
625
    }
33,408✔
626
}
50,982✔
627

628
static void get_all_keys_below(std::set<int64_t>& result, ref_type ref, Allocator& alloc)
629
{
72✔
630
    const char* sub_header = alloc.translate(ref_type(ref));
72✔
631
    const bool sub_isindex = NodeHeader::get_context_flag_from_header(sub_header);
72✔
632

36✔
633
    if (sub_isindex) {
72✔
634
        Array tree(alloc);
36✔
635
        tree.init_from_ref(ref);
36✔
636
        auto sz = tree.size();
36✔
637
        for (size_t n = 1; n < sz; n++) {
90✔
638
            auto rot = tree.get_as_ref_or_tagged(n);
54✔
639
            // Literal row index (tagged)
27✔
640
            if (rot.is_tagged()) {
54✔
641
                result.insert(rot.get_as_int());
30✔
642
            }
30✔
643
            else {
24✔
644
                get_all_keys_below(result, rot.get_as_ref(), alloc);
24✔
645
            }
24✔
646
        }
54✔
647
    }
36✔
648
    else {
36✔
649
        IntegerColumn tree(alloc, ref);
36✔
650
        tree.for_all([&result](int64_t i) {
84✔
651
            result.insert(i);
84✔
652
        });
84✔
653
    }
36✔
654
}
72✔
655

656
void IndexArray::_index_string_find_all_prefix(std::set<int64_t>& result, StringData str, const char* header) const
657
{
48✔
658
    size_t stringoffset = 0;
48✔
659

24✔
660
    for (;;) {
72✔
661
        const char* data = NodeHeader::get_data_from_header(header);
72✔
662
        uint_least8_t width = get_width_from_header(header);
72✔
663

36✔
664
        // Create 4 byte lower and upper key
36✔
665
        key_type lower = 0;
72✔
666
        size_t i = 0;
72✔
667
        size_t n = str.size() - stringoffset;
72✔
668
        bool is_at_string_end = (n <= 4);
72✔
669
        if (!is_at_string_end) {
72✔
670
            n = 4;
24✔
671
        }
24✔
672
        while (i < n) {
282✔
673
            lower <<= 8;
210✔
674
            lower += str[stringoffset + i++];
210✔
675
        }
210✔
676
        size_t shift = (4 - i) * 8;
72✔
677
        key_type upper = lower + 1;
72✔
678
        lower <<= shift;
72✔
679
        upper <<= shift;
72✔
680
        upper--;
72✔
681

36✔
682
        // Get index array
36✔
683
        ref_type offsets_ref = to_ref(get_direct(data, width, 0));
72✔
684

36✔
685
        // Find the position matching the key
36✔
686
        const char* offsets_header = m_alloc.translate(offsets_ref);
72✔
687
        const char* offsets_data = get_data_from_header(offsets_header);
72✔
688
        size_t offsets_size = get_size_from_header(offsets_header);
72✔
689
        size_t pos = ::lower_bound<32>(offsets_data, offsets_size, lower); // keys are always 32 bits wide
72✔
690
        // If key is outside range, we know there can be no match
36✔
691
        if (pos == offsets_size)
72✔
UNCOV
692
            return;
×
693

36✔
694
        size_t pos_refs = pos + 1; // first entry in refs points to offsets
72✔
695

36✔
696
        if (NodeHeader::get_is_inner_bptree_node_from_header(header)) {
72✔
697
            bool done = false;
×
698
            while (!done) {
×
699
                // Recursively call with child node
700
                const char* header = m_alloc.translate(to_ref(get_direct(data, width, pos_refs++)));
×
701
                _index_string_find_all_prefix(result, str, header);
×
702

703
                // Check if current node is past end of key range or last node
704
                auto key = get_direct<32>(offsets_data, pos++);
×
705
                done = key > upper || pos == offsets_size;
×
706
            }
×
UNCOV
707
            return;
×
UNCOV
708
        }
×
709

36✔
710
        size_t end = ::upper_bound<32>(offsets_data, offsets_size, upper); // keys are always 32 bits wide
72✔
711
        if (is_at_string_end) {
72✔
712
            // now get all entries from start to end
24✔
713
            for (size_t ndx = pos_refs; ndx <= end; ndx++) {
108✔
714
                uint64_t ref = get_direct(data, width, ndx);
60✔
715
                // Literal row index (tagged)
30✔
716
                if (ref & 1) {
60✔
717
                    result.emplace(int64_t(ref >> 1));
12✔
718
                }
12✔
719
                else {
48✔
720
                    get_all_keys_below(result, to_ref(ref), m_alloc);
48✔
721
                }
48✔
722
            }
60✔
723
            return;
48✔
724
        }
48✔
725

12✔
726
        // When we are not at end of string then we are comparing against the whole key
12✔
727
        // and we can have at most one match
12✔
728
        REALM_ASSERT(end == pos + 1);
24✔
729
        header = m_alloc.translate(to_ref(get_direct(data, width, pos_refs)));
24✔
730
        stringoffset += 4;
24✔
731
    }
24✔
732
}
48✔
733

734
ObjKey IndexArray::index_string_find_first(const Mixed& value, const ClusterColumn& column) const
735
{
1,600,734✔
736
    InternalFindResult unused;
1,600,734✔
737
    return ObjKey(index_string<index_FindFirst>(value, unused, column));
1,600,734✔
738
}
1,600,734✔
739

740

741
void IndexArray::index_string_find_all(std::vector<ObjKey>& result, const Mixed& value, const ClusterColumn& column,
742
                                       bool case_insensitive) const
743
{
57,564✔
744
    if (case_insensitive && value.is_type(type_String)) {
57,564✔
745
        index_string_all_ins(value.get_string(), result, column);
6,582✔
746
    }
6,582✔
747
    else {
50,982✔
748
        index_string_all(value, result, column);
50,982✔
749
    }
50,982✔
750
}
57,564✔
751

752
FindRes IndexArray::index_string_find_all_no_copy(const Mixed& value, const ClusterColumn& column,
753
                                                  InternalFindResult& result) const
754
{
658,602✔
755
    return static_cast<FindRes>(index_string<index_FindAll_nocopy>(value, result, column));
658,602✔
756
}
658,602✔
757

758
size_t IndexArray::index_string_count(const Mixed& value, const ClusterColumn& column) const
759
{
12,864✔
760
    InternalFindResult unused;
12,864✔
761
    return to_size_t(index_string<index_Count>(value, unused, column));
12,864✔
762
}
12,864✔
763

764
std::unique_ptr<IndexArray> StringIndex::create_node(Allocator& alloc, bool is_leaf)
765
{
179,949✔
766
    Array::Type type = is_leaf ? Array::type_HasRefs : Array::type_InnerBptreeNode;
179,910✔
767
    std::unique_ptr<IndexArray> top(new IndexArray(alloc)); // Throws
179,949✔
768
    top->create(type);                                      // Throws
179,949✔
769

88,173✔
770
    // Mark that this is part of index
88,173✔
771
    // (as opposed to columns under leaves)
88,173✔
772
    top->set_context_flag(true);
179,949✔
773

88,173✔
774
    // Add subcolumns for leaves
88,173✔
775
    Array values(alloc);
179,949✔
776
    values.create(Array::type_Normal);       // Throws
179,949✔
777
    values.ensure_minimum_width(0x7FFFFFFF); // This ensures 31 bits plus a sign bit
179,949✔
778
    top->add(values.get_ref());              // first entry in refs points to offsets
179,949✔
779

88,173✔
780
    return top;
179,949✔
781
}
179,949✔
782

783
StringIndex::key_type StringIndex::get_last_key() const
784
{
119,181✔
785
    Array offsets(m_array->get_alloc());
119,181✔
786
    get_child(*m_array, 0, offsets);
119,181✔
787
    return key_type(offsets.back());
119,181✔
788
}
119,181✔
789

790

791
void StringIndex::insert_with_offset(ObjKey obj_key, StringData index_data, const Mixed& value, size_t offset)
792
{
9,233,298✔
793
    // Create 4 byte index key
4,596,636✔
794
    key_type key = create_key(index_data, offset);
9,233,298✔
795
    TreeInsert(obj_key, key, offset, index_data, value); // Throws
9,233,298✔
796
}
9,233,298✔
797

798
void StringIndex::insert_to_existing_list_at_lower(ObjKey key, Mixed value, IntegerColumn& list,
799
                                                   const IntegerColumnIterator& lower)
800
{
2,064,276✔
801
    SortedListComparator slc(m_target_column);
2,064,276✔
802
    // At this point there exists duplicates of this value, we need to
1,032,684✔
803
    // insert value beside it's duplicates so that rows are also sorted
1,032,684✔
804
    // in ascending order.
1,032,684✔
805
    IntegerColumn::const_iterator upper = std::upper_bound(lower, list.cend(), value, slc);
2,064,276✔
806
    // find insert position (the list has to be kept in sorted order)
1,032,684✔
807
    // In most cases the refs will be added to the end. So we test for that
1,032,684✔
808
    // first to see if we can avoid the binary search for insert position
1,032,684✔
809
    IntegerColumn::const_iterator last = upper - ptrdiff_t(1);
2,064,276✔
810
    int64_t last_key_value = *last;
2,064,276✔
811
    if (key.value >= last_key_value) {
2,064,276✔
812
        list.insert(upper.get_position(), key.value);
2,028,432✔
813
    }
2,028,432✔
814
    else {
35,844✔
815
        IntegerColumn::const_iterator inner_lower = std::lower_bound(lower, upper, key.value);
35,844✔
816
        list.insert(inner_lower.get_position(), key.value);
35,844✔
817
    }
35,844✔
818
}
2,064,276✔
819

820
void StringIndex::insert_to_existing_list(ObjKey key, Mixed value, IntegerColumn& list)
821
{
1,890✔
822
    SortedListComparator slc(m_target_column);
1,890✔
823
    IntegerColumn::const_iterator it_end = list.cend();
1,890✔
824
    IntegerColumn::const_iterator lower = std::lower_bound(list.cbegin(), it_end, value, slc);
1,890✔
825

969✔
826
    if (lower == it_end) {
1,890✔
827
        // Not found and everything is less, just append it to the end.
762✔
828
        list.add(key.value);
1,512✔
829
    }
1,512✔
830
    else {
378✔
831
        ObjKey lower_key = ObjKey(*lower);
378✔
832
        Mixed lower_value = get(lower_key);
378✔
833

207✔
834
        if (lower_value != value) {
378✔
835
            list.insert(lower.get_position(), key.value);
378✔
836
        }
378✔
UNCOV
837
        else {
×
838
            // At this point there exists duplicates of this value, we need to
839
            // insert value beside it's duplicates so that rows are also sorted
840
            // in ascending order.
841
            insert_to_existing_list_at_lower(key, value, list, lower);
×
842
        }
×
843
    }
378✔
844
}
1,890✔
845

846

847
void StringIndex::insert_row_list(size_t ref, size_t offset, StringData index_data)
848
{
2,445✔
849
    REALM_ASSERT(!m_array->is_inner_bptree_node()); // only works in leaves
2,445✔
850

1,383✔
851
    // Create 4 byte index key
1,383✔
852
    key_type key = create_key(index_data, offset);
2,445✔
853

1,383✔
854
    // Get subnode table
1,383✔
855
    Allocator& alloc = m_array->get_alloc();
2,445✔
856
    Array values(alloc);
2,445✔
857
    get_child(*m_array, 0, values);
2,445✔
858
    REALM_ASSERT(m_array->size() == values.size() + 1);
2,445✔
859

1,383✔
860
    size_t ins_pos = values.lower_bound_int(key);
2,445✔
861
    if (ins_pos == values.size()) {
2,445✔
862
        // When key is outside current range, we can just add it
1,383✔
863
        values.add(key);
2,445✔
864
        m_array->add(ref);
2,445✔
865
        return;
2,445✔
866
    }
2,445✔
867

UNCOV
868
#ifdef REALM_DEBUG // LCOV_EXCL_START ignore debug code
×
869
    // Since we only use this for moving existing values to new
870
    // subindexes, there should never be an existing match.
871
    key_type k = key_type(values.get(ins_pos));
×
872
    REALM_ASSERT(k != key);
×
873
#endif // LCOV_EXCL_STOP ignore debug code
×
874

875
    // If key is not present we add it at the correct location
876
    values.insert(ins_pos, key);
×
877
    m_array->insert(ins_pos + 1, ref);
×
878
}
×
879

880

881
void StringIndex::TreeInsert(ObjKey obj_key, key_type key, size_t offset, StringData index_data, const Mixed& value)
882
{
9,238,281✔
883
    NodeChange nc = do_insert(obj_key, key, offset, index_data, value);
9,238,281✔
884
    switch (nc.type) {
9,238,281✔
885
        case NodeChange::change_None:
9,243,261✔
886
            return;
9,243,261✔
UNCOV
887
        case NodeChange::change_InsertBefore: {
✔
UNCOV
888
            StringIndex new_node(inner_node_tag(), m_array->get_alloc());
×
UNCOV
889
            new_node.node_add_key(nc.ref1);
×
UNCOV
890
            new_node.node_add_key(get_ref());
×
891
            m_array->init_from_ref(new_node.get_ref());
×
892
            m_array->update_parent();
×
893
            return;
×
894
        }
×
895
        case NodeChange::change_InsertAfter: {
6✔
896
            StringIndex new_node(inner_node_tag(), m_array->get_alloc());
6✔
897
            new_node.node_add_key(get_ref());
6✔
898
            new_node.node_add_key(nc.ref1);
6✔
899
            m_array->init_from_ref(new_node.get_ref());
6✔
900
            m_array->update_parent();
6✔
901
            return;
6✔
UNCOV
902
        }
×
903
        case NodeChange::change_Split: {
63✔
904
            StringIndex new_node(inner_node_tag(), m_array->get_alloc());
63✔
905
            new_node.node_add_key(nc.ref1);
63✔
906
            new_node.node_add_key(nc.ref2);
63✔
907
            m_array->init_from_ref(new_node.get_ref());
63✔
908
            m_array->update_parent();
63✔
909
            return;
63✔
UNCOV
910
        }
×
UNCOV
911
    }
×
UNCOV
912
    REALM_ASSERT(false); // LCOV_EXCL_LINE; internal Realm error
×
UNCOV
913
}
×
914

915

916
StringIndex::NodeChange StringIndex::do_insert(ObjKey obj_key, key_type key, size_t offset, StringData index_data,
917
                                               const Mixed& value)
918
{
9,299,523✔
919
    Allocator& alloc = m_array->get_alloc();
9,299,523✔
920
    if (m_array->is_inner_bptree_node()) {
9,299,523✔
921
        // Get subnode table
22,626✔
922
        Array keys(alloc);
54,513✔
923
        get_child(*m_array, 0, keys);
54,513✔
924
        REALM_ASSERT(m_array->size() == keys.size() + 1);
54,513✔
925

22,626✔
926
        // Find the subnode containing the item
22,626✔
927
        size_t node_ndx = keys.lower_bound_int(key);
54,513✔
928
        if (node_ndx == keys.size()) {
54,513✔
929
            // node can never be empty, so try to fit in last item
9,306✔
930
            node_ndx = keys.size() - 1;
18,645✔
931
        }
18,645✔
932

22,626✔
933
        // Get sublist
22,626✔
934
        size_t refs_ndx = node_ndx + 1; // first entry in refs points to offsets
54,513✔
935
        ref_type ref = m_array->get_as_ref(refs_ndx);
54,513✔
936
        StringIndex target(ref, m_array.get(), refs_ndx, m_target_column, alloc);
54,513✔
937

22,626✔
938
        // Insert item
22,626✔
939
        NodeChange nc = target.do_insert(obj_key, key, offset, index_data, value);
54,513✔
940
        if (nc.type == NodeChange::change_None) {
54,513✔
941
            // update keys
22,611✔
942
            key_type last_key = target.get_last_key();
54,474✔
943
            keys.set(node_ndx, last_key);
54,474✔
944
            return NodeChange::change_None; // no new nodes
54,474✔
945
        }
54,474✔
946

15✔
947
        if (nc.type == NodeChange::change_InsertAfter) {
39✔
948
            ++node_ndx;
18✔
949
            ++refs_ndx;
18✔
950
        }
18✔
951

15✔
952
        // If there is room, just update node directly
15✔
953
        if (keys.size() < REALM_MAX_BPNODE_SIZE) {
39✔
954
            if (nc.type == NodeChange::change_Split) {
39✔
955
                node_insert_split(node_ndx, nc.ref2);
21✔
956
            }
21✔
957
            else {
18✔
958
                node_insert(node_ndx, nc.ref1); // ::INSERT_BEFORE/AFTER
18✔
959
            }
18✔
960
            return NodeChange::change_None;
39✔
961
        }
39✔
962

963
        // Else create new node
UNCOV
964
        StringIndex new_node(inner_node_tag(), alloc);
×
UNCOV
965
        if (nc.type == NodeChange::change_Split) {
×
966
            // update offset for left node
967
            key_type last_key = target.get_last_key();
×
968
            keys.set(node_ndx, last_key);
×
969

970
            new_node.node_add_key(nc.ref2);
×
971
            ++node_ndx;
×
972
            ++refs_ndx;
×
973
        }
×
974
        else {
×
975
            new_node.node_add_key(nc.ref1);
×
976
        }
×
977

978
        switch (node_ndx) {
×
979
            case 0: // insert before
×
980
                return NodeChange(NodeChange::change_InsertBefore, new_node.get_ref());
×
981
            case REALM_MAX_BPNODE_SIZE: // insert after
×
982
                if (nc.type == NodeChange::change_Split)
×
983
                    return NodeChange(NodeChange::change_Split, get_ref(), new_node.get_ref());
×
984
                return NodeChange(NodeChange::change_InsertAfter, new_node.get_ref());
×
985
            default: // split
×
986
                // Move items after split to new node
987
                size_t len = m_array->size();
×
988
                for (size_t i = refs_ndx; i < len; ++i) {
×
989
                    ref_type ref_i = m_array->get_as_ref(i);
×
990
                    new_node.node_add_key(ref_i);
×
991
                }
×
992
                keys.truncate(node_ndx);
×
993
                m_array->truncate(refs_ndx);
×
994
                return NodeChange(NodeChange::change_Split, get_ref(), new_node.get_ref());
×
995
        }
9,245,010✔
996
    }
9,245,010✔
997
    else {
9,245,010✔
998
        // Is there room in the list?
4,608,576✔
999
        Array old_keys(alloc);
9,245,010✔
1000
        get_child(*m_array, 0, old_keys);
9,245,010✔
1001
        const size_t old_offsets_size = old_keys.size();
9,245,010✔
1002
        REALM_ASSERT_EX(m_array->size() == old_offsets_size + 1, m_array->size(), old_offsets_size + 1);
9,245,010✔
1003

4,608,576✔
1004
        bool noextend = old_offsets_size >= REALM_MAX_BPNODE_SIZE;
9,245,010✔
1005

4,608,576✔
1006
        // See if we can fit entry into current leaf
4,608,576✔
1007
        // Works if there is room or it can join existing entries
4,608,576✔
1008
        if (leaf_insert(obj_key, key, offset, index_data, value, noextend))
9,245,010✔
1009
            return NodeChange::change_None;
9,246,027✔
1010

2,147,483,647✔
1011
        // Create new list for item (a leaf)
2,147,483,647✔
1012
        StringIndex new_list(m_target_column, alloc);
2,147,483,818✔
1013

2,147,483,647✔
1014
        new_list.leaf_insert(obj_key, key, offset, index_data, value);
2,147,483,818✔
1015

2,147,483,647✔
1016
        size_t ndx = old_keys.lower_bound_int(key);
2,147,483,818✔
1017

2,147,483,647✔
1018
        // insert before
2,147,483,647✔
1019
        if (ndx == 0)
2,147,483,818✔
UNCOV
1020
            return NodeChange(NodeChange::change_InsertBefore, new_list.get_ref());
×
1021

2,147,483,647✔
1022
        // insert after
2,147,483,647✔
1023
        if (ndx == old_offsets_size)
2,147,483,818✔
1024
            return NodeChange(NodeChange::change_InsertAfter, new_list.get_ref());
24✔
1025

2,147,483,647✔
1026
        // split
2,147,483,647✔
1027
        Array new_keys(alloc);
2,147,483,806✔
1028
        get_child(*new_list.m_array, 0, new_keys);
2,147,483,806✔
1029
        // Move items after split to new list
2,147,483,647✔
1030
        for (size_t i = ndx; i < old_offsets_size; ++i) {
2,147,507,449✔
1031
            int64_t v2 = old_keys.get(i);
40,122✔
1032
            int64_t v3 = m_array->get(i + 1);
40,122✔
1033

16,479✔
1034
            new_keys.add(v2);
40,122✔
1035
            new_list.m_array->add(v3);
40,122✔
1036
        }
40,122✔
1037
        old_keys.truncate(ndx);
2,147,483,806✔
1038
        m_array->truncate(ndx + 1);
2,147,483,806✔
1039

2,147,483,647✔
1040
        return NodeChange(NodeChange::change_Split, get_ref(), new_list.get_ref());
2,147,483,806✔
1041
    }
2,147,483,806✔
1042
}
9,299,523✔
1043

1044

1045
void StringIndex::node_insert_split(size_t ndx, size_t new_ref)
1046
{
21✔
1047
    REALM_ASSERT(m_array->is_inner_bptree_node());
21✔
1048
    REALM_ASSERT(new_ref);
21✔
1049

6✔
1050
    Allocator& alloc = m_array->get_alloc();
21✔
1051
    Array offsets(alloc);
21✔
1052
    get_child(*m_array, 0, offsets);
21✔
1053

6✔
1054
    REALM_ASSERT(m_array->size() == offsets.size() + 1);
21✔
1055
    REALM_ASSERT(ndx < offsets.size());
21✔
1056
    REALM_ASSERT(offsets.size() < REALM_MAX_BPNODE_SIZE);
21✔
1057

6✔
1058
    // Get sublists
6✔
1059
    size_t refs_ndx = ndx + 1; // first entry in refs points to offsets
21✔
1060
    ref_type orig_ref = m_array->get_as_ref(refs_ndx);
21✔
1061
    StringIndex orig_col(orig_ref, m_array.get(), refs_ndx, m_target_column, alloc);
21✔
1062
    StringIndex new_col(new_ref, nullptr, 0, m_target_column, alloc);
21✔
1063

6✔
1064
    // Update original key
6✔
1065
    key_type last_key = orig_col.get_last_key();
21✔
1066
    offsets.set(ndx, last_key);
21✔
1067

6✔
1068
    // Insert new ref
6✔
1069
    key_type new_key = new_col.get_last_key();
21✔
1070
    offsets.insert(ndx + 1, new_key);
21✔
1071
    m_array->insert(ndx + 2, new_ref);
21✔
1072
}
21✔
1073

1074

1075
void StringIndex::node_insert(size_t ndx, size_t ref)
1076
{
18✔
1077
    REALM_ASSERT(ref);
18✔
1078
    REALM_ASSERT(m_array->is_inner_bptree_node());
18✔
1079

9✔
1080
    Allocator& alloc = m_array->get_alloc();
18✔
1081
    Array offsets(alloc);
18✔
1082
    get_child(*m_array, 0, offsets);
18✔
1083
    REALM_ASSERT(m_array->size() == offsets.size() + 1);
18✔
1084

9✔
1085
    REALM_ASSERT(ndx <= offsets.size());
18✔
1086
    REALM_ASSERT(offsets.size() < REALM_MAX_BPNODE_SIZE);
18✔
1087

9✔
1088
    StringIndex col(ref, nullptr, 0, m_target_column, alloc);
18✔
1089
    key_type last_key = col.get_last_key();
18✔
1090

9✔
1091
    offsets.insert(ndx, last_key);
18✔
1092
    m_array->insert(ndx + 1, ref);
18✔
1093
}
18✔
1094

1095
bool StringIndex::leaf_insert(ObjKey obj_key, key_type key, size_t offset, StringData index_data, const Mixed& value,
1096
                              bool noextend)
1097
{
9,223,743✔
1098
    REALM_ASSERT(!m_array->is_inner_bptree_node());
9,223,743✔
1099

4,595,658✔
1100
    // Get subnode table
4,595,658✔
1101
    Allocator& alloc = m_array->get_alloc();
9,223,743✔
1102
    Array keys(alloc);
9,223,743✔
1103
    get_child(*m_array, 0, keys);
9,223,743✔
1104
    REALM_ASSERT(m_array->size() == keys.size() + 1);
9,223,743✔
1105

4,595,658✔
1106
    // If we are keeping the complete string in the index
4,595,658✔
1107
    // we want to know if this is the last part
4,595,658✔
1108
    bool is_at_string_end = offset + 4 >= index_data.size();
9,223,743✔
1109

4,595,658✔
1110
    size_t ins_pos = keys.lower_bound_int(key);
9,223,743✔
1111
    size_t ins_pos_refs = ins_pos + 1; // first entry in refs points to offsets
9,223,743✔
1112

4,595,658✔
1113
    if (ins_pos == keys.size()) {
9,223,743✔
1114
        if (noextend)
335,739✔
1115
            return false;
24✔
1116

163,752✔
1117
        // When key is outside current range, we can just add it
163,752✔
1118
        keys.add(key);
335,715✔
1119
        if (!m_target_column.is_fulltext() || is_at_string_end) {
335,715✔
1120
            int64_t shifted = int64_t((uint64_t(obj_key.value) << 1) + 1); // shift to indicate literal
334,902✔
1121
            m_array->add(shifted);
334,902✔
1122
        }
334,902✔
1123
        else {
813✔
1124
            // create subindex for rest of string
408✔
1125
            StringIndex subindex(m_target_column, m_array->get_alloc());
813✔
1126
            subindex.insert_with_offset(obj_key, index_data, value, offset + 4);
813✔
1127
            m_array->add(subindex.get_ref());
813✔
1128
        }
813✔
1129
        return true;
335,715✔
1130
    }
335,715✔
1131

4,431,894✔
1132
    key_type k = key_type(keys.get(ins_pos));
8,888,004✔
1133

4,431,894✔
1134
    // If key is not present we add it at the correct location
4,431,894✔
1135
    if (k != key) {
8,888,004✔
1136
        if (noextend)
723,018✔
1137
            return false;
84✔
1138

353,166✔
1139
        keys.insert(ins_pos, key);
722,934✔
1140
        if (!m_target_column.is_fulltext() || is_at_string_end) {
722,934✔
1141
            int64_t shifted = int64_t((uint64_t(obj_key.value) << 1) + 1); // shift to indicate literal
721,323✔
1142
            m_array->insert(ins_pos_refs, shifted);
721,323✔
1143
        }
721,323✔
1144
        else {
1,611✔
1145
            // create subindex for rest of string
795✔
1146
            StringIndex subindex(m_target_column, m_array->get_alloc());
1,611✔
1147
            subindex.insert_with_offset(obj_key, index_data, value, offset + 4);
1,611✔
1148
            m_array->insert(ins_pos_refs, subindex.get_ref());
1,611✔
1149
        }
1,611✔
1150
        return true;
722,934✔
1151
    }
722,934✔
1152

4,078,695✔
1153
    // This leaf already has a slot for for the key
4,078,695✔
1154

4,078,695✔
1155
    uint64_t slot_value = uint64_t(m_array->get(ins_pos_refs));
8,164,986✔
1156
    size_t suboffset = offset + s_index_key_length;
8,164,986✔
1157

4,078,695✔
1158
    // Single match (lowest bit set indicates literal row_ndx)
4,078,695✔
1159
    if ((slot_value & 1) != 0) {
8,164,986✔
1160
        ObjKey obj_key2 = ObjKey(int64_t(slot_value >> 1));
50,922✔
1161
        Mixed v2 = m_target_column.is_fulltext() ? reconstruct_string(offset, key, index_data) : get(obj_key2);
50,640✔
1162
        if (v2 == value) {
50,922✔
1163
            // Strings are equal but this is not a list.
4,671✔
1164
            // Create a list and add both rows.
4,671✔
1165

4,671✔
1166
            // convert to list (in sorted order)
4,671✔
1167
            Array row_list(alloc);
9,432✔
1168
            row_list.create(Array::type_Normal); // Throws
9,432✔
1169
            row_list.add(obj_key < obj_key2 ? obj_key.value : obj_key2.value);
8,751✔
1170
            row_list.add(obj_key < obj_key2 ? obj_key2.value : obj_key.value);
8,751✔
1171
            m_array->set(ins_pos_refs, row_list.get_ref());
9,432✔
1172
        }
9,432✔
1173
        else {
41,490✔
1174
            StringConversionBuffer buffer;
41,490✔
1175
            auto index_data_2 = v2.get_index_data(buffer);
41,490✔
1176
            if (index_data == index_data_2 || suboffset > s_max_offset) {
41,490✔
1177
                // These strings have the same prefix up to this point but we
258✔
1178
                // don't want to recurse further, create a list in sorted order.
258✔
1179
                bool row_ndx_first = value.compare_signed(v2) < 0;
549✔
1180
                Array row_list(alloc);
549✔
1181
                row_list.create(Array::type_Normal); // Throws
549✔
1182
                row_list.add(row_ndx_first ? obj_key.value : obj_key2.value);
423✔
1183
                row_list.add(row_ndx_first ? obj_key2.value : obj_key.value);
423✔
1184
                m_array->set(ins_pos_refs, row_list.get_ref());
549✔
1185
            }
549✔
1186
            else {
40,941✔
1187
                // These strings have the same prefix up to this point but they
19,125✔
1188
                // are actually not equal. Extend the tree recursivly until the
19,125✔
1189
                // prefix of these strings is different.
19,125✔
1190
                StringIndex subindex(m_target_column, m_array->get_alloc());
40,941✔
1191
                subindex.insert_with_offset(obj_key2, index_data_2, v2, suboffset);
40,941✔
1192
                subindex.insert_with_offset(obj_key, index_data, value, suboffset);
40,941✔
1193
                // Join the string of SubIndices to the current position of m_array
19,125✔
1194
                m_array->set(ins_pos_refs, subindex.get_ref());
40,941✔
1195
            }
40,941✔
1196
        }
41,490✔
1197
        return true;
50,922✔
1198
    }
50,922✔
1199

4,054,641✔
1200
    // If there already is a list of matches, we see if we fit there
4,054,641✔
1201
    // or it has to be split into a subindex
4,054,641✔
1202
    ref_type ref = ref_type(slot_value);
8,114,064✔
1203
    char* header = alloc.translate(ref);
8,114,064✔
1204
    if (!Array::get_context_flag_from_header(header)) {
8,114,064✔
1205
        IntegerColumn sub(alloc, ref); // Throws
2,068,308✔
1206
        sub.set_parent(m_array.get(), ins_pos_refs);
2,068,308✔
1207

1,034,877✔
1208
        IntegerColumn::const_iterator it_end = sub.cend();
2,068,308✔
1209
        IntegerColumn::const_iterator lower = it_end;
2,068,308✔
1210

1,034,877✔
1211
        auto value_exists_in_list = [&]() {
2,068,671✔
1212
            if (m_target_column.is_fulltext()) {
2,068,671✔
1213
                return reconstruct_string(offset, key, index_data) == value.get_string();
348✔
1214
            }
348✔
1215
            SortedListComparator slc(m_target_column);
2,068,323✔
1216
            lower = std::lower_bound(sub.cbegin(), it_end, value, slc);
2,068,323✔
1217

1,034,937✔
1218
            if (lower != it_end) {
2,068,323✔
1219
                Mixed lower_value = get(ObjKey(*lower));
2,064,660✔
1220
                if (lower_value == value) {
2,064,660✔
1221
                    return true;
2,064,006✔
1222
                }
2,064,006✔
1223
            }
4,317✔
1224
            return false;
4,317✔
1225
        };
4,317✔
1226

1,034,877✔
1227
        // If we found the value in this list, add the duplicate to the list.
1,034,877✔
1228
        if (value_exists_in_list()) {
2,068,308✔
1229
            insert_to_existing_list_at_lower(obj_key, value, sub, lower);
2,064,330✔
1230
        }
2,064,330✔
1231
        else {
3,978✔
1232
            // If the list only stores duplicates we are free to branch and
2,169✔
1233
            // and create a sub index with this existing list as one of the
2,169✔
1234
            // leafs, but if the list doesn't only contain duplicates we
2,169✔
1235
            // must respect that we store a common key prefix up to this
2,169✔
1236
            // point and insert into the existing list.
2,169✔
1237
            ObjKey key_of_any_dup = ObjKey(sub.get(0));
3,978✔
1238
            StringConversionBuffer buffer;
3,978✔
1239
            StringData index_data_2 = m_target_column.is_fulltext() ? reconstruct_string(offset, key, index_data)
2,172✔
1240
                                                                    : get(key_of_any_dup).get_index_data(buffer);
3,975✔
1241
            if (index_data == index_data_2 || suboffset > s_max_offset) {
4,329✔
1242
                insert_to_existing_list(obj_key, value, sub);
1,890✔
1243
            }
1,890✔
1244
            else {
2,088✔
1245
#ifdef REALM_DEBUG
2,088✔
1246
                bool contains_only_duplicates = true;
2,088✔
1247
                if (!m_target_column.is_fulltext() && sub.size() > 1) {
2,439✔
1248
                    ObjKey first_key = ObjKey(sub.get(0));
1,611✔
1249
                    ObjKey last_key = ObjKey(sub.back());
1,611✔
1250
                    auto first = get(first_key);
1,611✔
1251
                    auto last = get(last_key);
1,611✔
1252
                    // Since the list is kept in sorted order, the first and
1,083✔
1253
                    // last values will be the same only if the whole list is
1,083✔
1254
                    // storing duplicate values.
1,083✔
1255
                    if (first != last) {
1,611✔
UNCOV
1256
                        contains_only_duplicates = false; // LCOV_EXCL_LINE
×
UNCOV
1257
                    }
×
1258
                }
1,611✔
1259
                REALM_ASSERT_DEBUG(contains_only_duplicates);
2,088✔
1260
#endif
2,088✔
1261
                // The buffer is needed for when this is an integer index.
1,200✔
1262
                StringIndex subindex(m_target_column, m_array->get_alloc());
2,088✔
1263
                subindex.insert_row_list(sub.get_ref(), suboffset, index_data_2);
2,088✔
1264
                subindex.insert_with_offset(obj_key, index_data, value, suboffset);
2,088✔
1265
                m_array->set(ins_pos_refs, subindex.get_ref());
2,088✔
1266
            }
2,088✔
1267
        }
3,978✔
1268
        return true;
2,068,308✔
1269
    }
2,068,308✔
1270

3,019,764✔
1271
    // The key matches, but there is a subindex here so go down a level in the tree.
3,019,764✔
1272
    StringIndex subindex(ref, m_array.get(), ins_pos_refs, m_target_column, alloc);
6,045,756✔
1273
    subindex.insert_with_offset(obj_key, index_data, value, suboffset);
6,045,756✔
1274

3,019,764✔
1275
    return true;
6,045,756✔
1276
}
6,045,756✔
1277

1278
Mixed StringIndex::get(ObjKey key) const
1279
{
3,760,713✔
1280
    return m_target_column.get_value(key);
3,760,713✔
1281
}
3,760,713✔
1282

1283
void StringIndex::erase(ObjKey key)
1284
{
976,221✔
1285
    StringConversionBuffer buffer;
976,221✔
1286
    std::string_view value{(get(key).get_index_data(buffer))};
976,221✔
1287
    if (m_target_column.is_fulltext()) {
976,221✔
1288
        auto words = Tokenizer::get_instance()->reset(value).get_all_tokens();
72✔
1289
        for (auto& w : words) {
2,460✔
1290
            erase_string(key, w);
2,460✔
1291
        }
2,460✔
1292
    }
72✔
1293
    else {
976,149✔
1294
        erase_string(key, value);
976,149✔
1295
    }
976,149✔
1296
}
976,221✔
1297

1298
namespace {
1299
template <typename T>
1300
void intersect(std::vector<ObjKey>& result, T& keys)
1301
{
276✔
1302
    if (result.empty()) {
276✔
1303
        result.reserve(keys.size());
180✔
1304
        for (auto k : keys) {
498✔
1305
            result.emplace_back(k);
498✔
1306
        }
498✔
1307
    }
180✔
1308
    else {
96✔
1309
        auto it = result.begin();
96✔
1310
        auto keep = it;
96✔
1311
        auto m = keys.begin();
96✔
1312

48✔
1313
        // only keep intersection
48✔
1314
        while (it != result.end() && m != keys.end()) {
354✔
1315
            int64_t int_val = *m;
258✔
1316
            if (it->value < int_val) {
258✔
1317
                it++; // don't keep if match is not in new set
18✔
1318
            }
18✔
1319
            else if (it->value > int_val) {
240✔
1320
                ++m; // ignore new matches
102✔
1321
            }
102✔
1322
            else {
138✔
1323
                // Found both places - make sure it is kept
69✔
1324
                if (keep < it)
138✔
1325
                    *keep = *it;
6✔
1326
                ++keep;
138✔
1327
                ++it;
138✔
1328
                ++m;
138✔
1329
            }
138✔
1330
        }
258✔
1331
        if (keep != result.end()) {
96✔
1332
            result.erase(keep, result.end());
24✔
1333
        }
24✔
1334
    }
96✔
1335
}
276✔
1336

1337
struct FindResWrapper {
1338
    InternalFindResult& res;
1339
    IntegerColumn& indexes;
1340
    size_t n = 0;
1341
    size_t size()
1342
    {
144✔
1343
        return res.end_ndx - res.start_ndx;
144✔
1344
    }
144✔
1345
    auto begin()
1346
    {
228✔
1347
        return indexes.cbegin();
228✔
1348
    }
228✔
1349
    auto end()
1350
    {
384✔
1351
        return indexes.cend();
384✔
1352
    }
384✔
1353
};
1354
} // namespace
1355

1356
void StringIndex::find_all_fulltext(std::vector<ObjKey>& result, StringData value) const
1357
{
360✔
1358
    InternalFindResult res;
360✔
1359
    REALM_ASSERT(result.empty());
360✔
1360

180✔
1361
    auto tokenizer = Tokenizer::get_instance();
360✔
1362
    tokenizer->reset({value.data(), value.size()});
360✔
1363
    auto [includes, excludes] = tokenizer->get_search_tokens();
360✔
1364
    if (includes.empty()) {
360✔
1365
        if (excludes.empty()) {
24✔
1366
            throw InvalidArgument("Missing search token");
6✔
1367
        }
6✔
1368
        result = m_target_column.get_all_keys();
18✔
1369
    }
18✔
1370
    else {
336✔
1371
        for (auto& token : includes) {
414✔
1372
            if (token.back() == '*') {
414✔
1373
                std::set<int64_t> keys;
48✔
1374
                m_array->index_string_find_all_prefix(keys, StringData(token.data(), token.size() - 1));
48✔
1375
                intersect(result, keys);
48✔
1376
            }
48✔
1377
            else {
366✔
1378
                switch (find_all_no_copy(StringData{token}, res)) {
366✔
1379
                    case FindRes_not_found:
12✔
1380
                        result.clear();
12✔
1381
                        break;
12✔
1382
                    case FindRes_column: {
228✔
1383
                        IntegerColumn indexes(m_array->get_alloc(), ref_type(res.payload));
228✔
1384
                        FindResWrapper wrapper{res, indexes};
228✔
1385
                        intersect(result, wrapper);
228✔
1386
                        break;
228✔
UNCOV
1387
                    }
×
1388
                    case FindRes_single:
126✔
1389
                        // merge in single res
63✔
1390
                        if (result.empty()) {
126✔
1391
                            result.emplace_back(res.payload);
96✔
1392
                        }
96✔
1393
                        else {
30✔
1394
                            ObjKey key(res.payload);
30✔
1395
                            auto pos = std::lower_bound(result.begin(), result.end(), key);
30✔
1396
                            if (pos != result.end() && key == *pos) {
30✔
1397
                                result.clear();
30✔
1398
                                result.push_back(key);
30✔
1399
                            }
30✔
UNCOV
1400
                            else {
×
UNCOV
1401
                                result.clear();
×
UNCOV
1402
                            }
×
1403
                        }
30✔
1404
                        break;
126✔
1405
                }
414✔
1406
            }
414✔
1407
            if (result.empty())
414✔
1408
                return;
18✔
1409
        }
414✔
1410
    }
336✔
1411

180✔
1412
    for (auto& token : excludes) {
348✔
1413
        if (token.back() == '*') {
96✔
UNCOV
1414
            throw IllegalOperation("Exclude by prefix is not implemented");
×
UNCOV
1415
        }
×
1416
        if (result.empty())
96✔
UNCOV
1417
            return;
×
1418

48✔
1419
        switch (find_all_no_copy(StringData{token}, res)) {
96✔
UNCOV
1420
            case FindRes_not_found:
✔
1421
                // Nothing to exclude
UNCOV
1422
                break;
×
1423
            case FindRes_column: {
60✔
1424
                IntegerColumn indexes(m_array->get_alloc(), ref_type(res.payload));
60✔
1425

30✔
1426
                auto it = result.begin();
60✔
1427
                auto keep = it;
60✔
1428
                size_t m = res.start_ndx;
60✔
1429
                auto idx_val = indexes.get(m);
60✔
1430

30✔
1431
                while (it != result.end()) {
390✔
1432
                    if (it->value < idx_val) {
330✔
1433
                        // Not found in excludes
78✔
1434
                        if (keep < it)
156✔
1435
                            *keep = *it;
156✔
1436
                        ++keep;
156✔
1437
                        ++it;
156✔
1438
                    }
156✔
1439
                    else {
174✔
1440
                        if (it->value == idx_val) {
174✔
1441
                            // found in excludes - don't keep
75✔
1442
                            ++it;
150✔
1443
                        }
150✔
1444
                        ++m;
174✔
1445
                        idx_val = m < res.end_ndx ? indexes.get(m) : std::numeric_limits<int64_t>::max();
153✔
1446
                    }
174✔
1447
                }
330✔
1448
                if (keep != result.end()) {
60✔
1449
                    result.erase(keep, result.end());
60✔
1450
                }
60✔
1451
                break;
60✔
UNCOV
1452
            }
×
1453
            case FindRes_single: {
36✔
1454
                // exclude single res
18✔
1455
                ObjKey key(res.payload);
36✔
1456
                auto pos = std::lower_bound(result.begin(), result.end(), key);
36✔
1457
                if (pos != result.end() && key == *pos) {
36✔
1458
                    result.erase(pos);
36✔
1459
                }
36✔
1460
                break;
36✔
UNCOV
1461
            }
×
1462
        }
96✔
1463
    }
96✔
1464
}
336✔
1465

1466

1467
void StringIndex::clear()
1468
{
2,262✔
1469
    Array values(m_array->get_alloc());
2,262✔
1470
    get_child(*m_array, 0, values);
2,262✔
1471
    REALM_ASSERT(m_array->size() == values.size() + 1);
2,262✔
1472

474✔
1473
    values.clear();
2,262✔
1474
    values.ensure_minimum_width(0x7FFFFFFF); // This ensures 31 bits plus a sign bit
2,262✔
1475

474✔
1476
    size_t size = 1;
2,262✔
1477
    m_array->truncate_and_destroy_children(size); // Don't touch `values` array
2,262✔
1478

474✔
1479
    m_array->set_type(Array::type_HasRefs);
2,262✔
1480
}
2,262✔
1481

1482

1483
void StringIndex::do_delete(ObjKey obj_key, StringData index_data, size_t offset)
1484
{
1,284,045✔
1485
    Allocator& alloc = m_array->get_alloc();
1,284,045✔
1486
    Array values(alloc);
1,284,045✔
1487
    get_child(*m_array, 0, values);
1,284,045✔
1488
    REALM_ASSERT(m_array->size() == values.size() + 1);
1,284,045✔
1489

646,044✔
1490
    // Create 4 byte index key
646,044✔
1491
    key_type key = create_key(index_data, offset);
1,284,045✔
1492

646,044✔
1493
    const size_t pos = values.lower_bound_int(key);
1,284,045✔
1494
    const size_t pos_refs = pos + 1; // first entry in refs points to offsets
1,284,045✔
1495
    REALM_ASSERT(pos != values.size());
1,284,045✔
1496

646,044✔
1497
    if (m_array->is_inner_bptree_node()) {
1,284,045✔
1498
        ref_type ref = m_array->get_as_ref(pos_refs);
64,755✔
1499
        StringIndex node(ref, m_array.get(), pos_refs, m_target_column, alloc);
64,755✔
1500
        node.do_delete(obj_key, index_data, offset);
64,755✔
1501

32,310✔
1502
        // Update the ref
32,310✔
1503
        if (node.is_empty()) {
64,755✔
1504
            values.erase(pos);
108✔
1505
            m_array->erase(pos_refs);
108✔
1506
            node.destroy();
108✔
1507
        }
108✔
1508
        else {
64,647✔
1509
            key_type max_val = node.get_last_key();
64,647✔
1510
            if (max_val != key_type(values.get(pos)))
64,647✔
1511
                values.set(pos, max_val);
108✔
1512
        }
64,647✔
1513
    }
64,755✔
1514
    else {
1,219,290✔
1515
        uint64_t ref = m_array->get(pos_refs);
1,219,290✔
1516
        if (ref & 1) {
1,219,290✔
1517
            REALM_ASSERT(int64_t(ref >> 1) == obj_key.value);
632,442✔
1518
            values.erase(pos);
632,442✔
1519
            m_array->erase(pos_refs);
632,442✔
1520
        }
632,442✔
1521
        else {
586,848✔
1522
            // A real ref either points to a list or a subindex
297,786✔
1523
            char* header = alloc.translate(ref_type(ref));
586,848✔
1524
            if (Array::get_context_flag_from_header(header)) {
586,848✔
1525
                StringIndex subindex(ref_type(ref), m_array.get(), pos_refs, m_target_column, alloc);
240,879✔
1526
                subindex.do_delete(obj_key, index_data, offset + s_index_key_length);
240,879✔
1527

124,302✔
1528
                if (subindex.is_empty()) {
240,879✔
1529
                    values.erase(pos);
12,978✔
1530
                    m_array->erase(pos_refs);
12,978✔
1531
                    subindex.destroy();
12,978✔
1532
                }
12,978✔
1533
            }
240,879✔
1534
            else {
345,969✔
1535
                IntegerColumn sub(alloc, ref_type(ref)); // Throws
345,969✔
1536
                sub.set_parent(m_array.get(), pos_refs);
345,969✔
1537
                size_t r = sub.find_first(obj_key.value);
345,969✔
1538
                size_t sub_size = sub.size(); // Slow
345,969✔
1539
                REALM_ASSERT_EX(r != sub_size, r, sub_size);
345,969✔
1540
                sub.erase(r);
345,969✔
1541

173,484✔
1542
                if (sub_size == 1) {
345,969✔
1543
                    values.erase(pos);
3,096✔
1544
                    m_array->erase(pos_refs);
3,096✔
1545
                    sub.destroy();
3,096✔
1546
                }
3,096✔
1547
            }
345,969✔
1548
        }
586,848✔
1549
    }
1,219,290✔
1550
}
1,284,045✔
1551

1552
void StringIndex::erase_string(ObjKey key, StringData value)
1553
{
978,651✔
1554
    do_delete(key, value, 0);
978,651✔
1555

489,609✔
1556
    // Collapse top nodes with single item
489,609✔
1557
    while (m_array->is_inner_bptree_node()) {
978,657✔
1558
        REALM_ASSERT(m_array->size() > 1); // node cannot be empty
64,755✔
1559
        if (m_array->size() > 2)
64,755✔
1560
            break;
64,749✔
1561

3✔
1562
        ref_type ref = m_array->get_as_ref(1);
6✔
1563
        m_array->set(1, 1); // avoid destruction of the extracted ref
6✔
1564
        m_array->destroy_deep();
6✔
1565
        m_array->init_from_ref(ref);
6✔
1566
        m_array->update_parent();
6✔
1567
    }
6✔
1568
}
978,651✔
1569

1570
namespace {
1571

1572
bool has_duplicate_values(const Array& node, const ClusterColumn& target_col) noexcept
1573
{
6,366✔
1574
    Allocator& alloc = node.get_alloc();
6,366✔
1575
    Array child(alloc);
6,366✔
1576
    size_t n = node.size();
6,366✔
1577
    REALM_ASSERT(n >= 1);
6,366✔
1578
    if (node.is_inner_bptree_node()) {
6,366✔
1579
        // Inner node
UNCOV
1580
        for (size_t i = 1; i < n; ++i) {
×
UNCOV
1581
            ref_type ref = node.get_as_ref(i);
×
UNCOV
1582
            child.init_from_ref(ref);
×
1583
            if (has_duplicate_values(child, target_col))
×
1584
                return true;
×
1585
        }
×
1586
        return false;
×
1587
    }
6,366✔
1588

3,183✔
1589
    // Leaf node
3,183✔
1590
    for (size_t i = 1; i < n; ++i) {
32,850✔
1591
        int_fast64_t value = node.get(i);
28,740✔
1592
        bool is_single_row_index = (value & 1) != 0;
28,740✔
1593
        if (is_single_row_index)
28,740✔
1594
            continue;
23,280✔
1595

2,730✔
1596
        ref_type ref = to_ref(value);
5,460✔
1597
        child.init_from_ref(ref);
5,460✔
1598

2,730✔
1599
        bool is_subindex = child.get_context_flag();
5,460✔
1600
        if (is_subindex) {
5,460✔
1601
            if (has_duplicate_values(child, target_col))
4,872✔
1602
                return true;
1,800✔
1603
            continue;
3,072✔
1604
        }
3,072✔
1605

294✔
1606
        // Child is root of B+-tree of row indexes
294✔
1607
        IntegerColumn sub(alloc, ref);
588✔
1608
        if (sub.size() > 1) {
588✔
1609
            ObjKey first_key = ObjKey(sub.get(0));
480✔
1610
            ObjKey last_key = ObjKey(sub.back());
480✔
1611
            Mixed first = target_col.get_value(first_key);
480✔
1612
            Mixed last = target_col.get_value(last_key);
480✔
1613
            // Since the list is kept in sorted order, the first and
240✔
1614
            // last values will be the same only if the whole list is
240✔
1615
            // storing duplicate values.
240✔
1616
            if (first == last) {
480✔
1617
                return true;
432✔
1618
            }
432✔
1619
            // There may also be several short lists combined, so we need to
24✔
1620
            // check each of these individually for duplicates.
24✔
1621
            IntegerColumn::const_iterator it = sub.cbegin();
48✔
1622
            IntegerColumn::const_iterator it_end = sub.cend();
48✔
1623
            SortedListComparator slc(target_col);
48✔
1624
            while (it != it_end) {
144✔
1625
                Mixed it_data = target_col.get_value(ObjKey(*it));
120✔
1626
                IntegerColumn::const_iterator next = std::upper_bound(it, it_end, it_data, slc);
120✔
1627
                size_t count_of_value = next - it; // row index subtraction in `sub`
120✔
1628
                if (count_of_value > 1) {
120✔
1629
                    return true;
24✔
1630
                }
24✔
1631
                it = next;
96✔
1632
            }
96✔
1633
        }
48✔
1634
    }
588✔
1635

3,183✔
1636
    return false;
5,238✔
1637
}
6,366✔
1638

1639
} // anonymous namespace
1640

1641

1642
bool StringIndex::has_duplicate_values() const noexcept
1643
{
1,494✔
1644
    return ::has_duplicate_values(*m_array, m_target_column);
1,494✔
1645
}
1,494✔
1646

1647

1648
bool StringIndex::is_empty() const
1649
{
305,838✔
1650
    return m_array->size() == 1; // first entry in refs points to offsets
305,838✔
1651
}
305,838✔
1652

1653
void StringIndex::insert(ObjKey key, const Mixed& value)
1654
{
2,453,934✔
1655
    StringConversionBuffer buffer;
2,453,934✔
1656
    constexpr size_t offset = 0; // First key from beginning of string
2,453,934✔
1657

1,216,452✔
1658
    if (this->m_target_column.is_fulltext()) {
2,453,934✔
1659
        if (value.is_type(type_String)) {
198✔
1660
            auto words = Tokenizer::get_instance()->reset(std::string_view(value.get<StringData>())).get_all_tokens();
198✔
1661
            for (auto& word : words) {
936✔
1662
                Mixed m(word);
936✔
1663
                insert_with_offset(key, m.get_index_data(buffer), m, offset); // Throws
936✔
1664
            }
936✔
1665
        }
198✔
1666
    }
198✔
1667
    else {
2,453,736✔
1668
        insert_with_offset(key, value.get_index_data(buffer), value, offset); // Throws
2,453,736✔
1669
    }
2,453,736✔
1670
}
2,453,934✔
1671

1672
void StringIndex::set(ObjKey key, const Mixed& new_value)
1673
{
663,702✔
1674
    StringConversionBuffer buffer;
663,702✔
1675
    Mixed old_value = get(key);
663,702✔
1676

331,980✔
1677
    if (this->m_target_column.is_fulltext()) {
663,702✔
1678
        auto tokenizer = Tokenizer::get_instance();
168✔
1679
        StringData old_string = old_value.get_index_data(buffer);
168✔
1680
        std::set<std::string> old_words;
168✔
1681

84✔
1682
        if (old_string.size() > 0) {
168✔
1683
            tokenizer->reset({old_string.data(), old_string.size()});
6✔
1684
            old_words = tokenizer->get_all_tokens();
6✔
1685
        }
6✔
1686
        std::set<std::string> new_words;
168✔
1687
        if (new_value.is_type(type_String)) {
168✔
1688
            new_words = tokenizer->reset(std::string_view(new_value.get<StringData>())).get_all_tokens();
168✔
1689
        }
168✔
1690

84✔
1691
        auto w1 = old_words.begin();
168✔
1692
        auto w2 = new_words.begin();
168✔
1693

84✔
1694
        // Do a diff, deleting words no longer present and
84✔
1695
        // inserting new words
84✔
1696
        while (w1 != old_words.end() && w2 != new_words.end()) {
540✔
1697
            if (*w1 < *w2) {
372✔
1698
                erase_string(key, *w1);
126✔
1699
                ++w1;
126✔
1700
            }
126✔
1701
            else if (*w2 < *w1) {
246✔
1702
                Mixed m(*w2);
198✔
1703
                insert_with_offset(key, m.get_index_data(buffer), m, 0);
198✔
1704
                ++w2;
198✔
1705
            }
198✔
1706
            else {
48✔
1707
                ++w1;
48✔
1708
                ++w2;
48✔
1709
            }
48✔
1710
        }
372✔
1711
        while (w1 != old_words.end()) {
168✔
UNCOV
1712
            erase_string(key, *w1);
×
UNCOV
1713
            ++w1;
×
UNCOV
1714
        }
×
1715
        while (w2 != new_words.end()) {
3,354✔
1716
            Mixed m(*w2);
3,186✔
1717
            insert_with_offset(key, m.get_index_data(buffer), m, 0);
3,186✔
1718

1,593✔
1719
            ++w2;
3,186✔
1720
        }
3,186✔
1721
    }
168✔
1722
    else {
663,534✔
1723
        if (REALM_LIKELY(new_value != old_value)) {
663,534✔
1724
            // We must erase this row first because erase uses find_first which
316,701✔
1725
            // might find the duplicate if we insert before erasing.
316,701✔
1726
            erase(key); // Throws
633,357✔
1727

316,701✔
1728
            auto index_data = new_value.get_index_data(buffer);
633,357✔
1729
            insert_with_offset(key, index_data, new_value, 0); // Throws
633,357✔
1730
        }
633,357✔
1731
    }
663,534✔
1732
}
663,702✔
1733

1734
void StringIndex::node_add_key(ref_type ref)
1735
{
138✔
1736
    REALM_ASSERT(ref);
138✔
1737
    REALM_ASSERT(m_array->is_inner_bptree_node());
138✔
1738

60✔
1739
    Allocator& alloc = m_array->get_alloc();
138✔
1740
    Array offsets(alloc);
138✔
1741
    get_child(*m_array, 0, offsets);
138✔
1742
    REALM_ASSERT(m_array->size() == offsets.size() + 1);
138✔
1743
    REALM_ASSERT(offsets.size() < REALM_MAX_BPNODE_SIZE + 1);
138✔
1744

60✔
1745
    Array new_top(alloc);
138✔
1746
    Array new_offsets(alloc);
138✔
1747
    new_top.init_from_ref(ref);
138✔
1748
    new_offsets.init_from_ref(new_top.get_as_ref(0));
138✔
1749
    REALM_ASSERT(!new_offsets.is_empty());
138✔
1750

60✔
1751
    int64_t key = new_offsets.back();
138✔
1752
    offsets.add(key);
138✔
1753
    m_array->add(ref);
138✔
1754
}
138✔
1755

1756
// Must return true if value of object(key) is less than needle.
1757
bool SortedListComparator::operator()(int64_t key_value, Mixed needle) // used in lower_bound
1758
{
20,410,323✔
1759
    Mixed a = m_column.get_value(ObjKey(key_value));
20,410,323✔
1760
    if (a.is_null() && !needle.is_null())
20,410,323✔
1761
        return true;
690✔
1762
    else if (needle.is_null() && !a.is_null())
20,409,633✔
UNCOV
1763
        return false;
×
1764
    else if (a.is_null() && needle.is_null())
20,409,633✔
1765
        return false;
347,292✔
1766

10,033,719✔
1767
    if (a == needle)
20,062,341✔
1768
        return false;
20,061,756✔
1769

5,823✔
1770
    // The Mixed::operator< uses a lexicograpical comparison, therefore we
5,823✔
1771
    // cannot use our utf8_compare here because we need to be consistent with
5,823✔
1772
    // using the same compare method as how these strings were they were put
5,823✔
1773
    // into this ordered column in the first place.
5,823✔
1774
    return a.compare_signed(needle) < 0;
2,147,489,470✔
1775
}
2,147,489,470✔
1776

1777

1778
// Must return true if value of needle is less than value of object(key).
1779
bool SortedListComparator::operator()(Mixed needle, int64_t key_value) // used in upper_bound
1780
{
18,299,328✔
1781
    Mixed a = m_column.get_value(ObjKey(key_value));
18,299,328✔
1782
    if (needle == a) {
18,320,241✔
1783
        return false;
18,320,241✔
1784
    }
18,320,241✔
1785
    return !(*this)(key_value, needle);
4,294,967,294✔
1786
}
4,294,967,294✔
1787

1788
// LCOV_EXCL_START ignore debug functions
1789

1790
#ifdef REALM_DEBUG
1791
void StringIndex::print() const
UNCOV
1792
{
×
UNCOV
1793
    dump_node_structure(*m_array, std::cout, 0);
×
UNCOV
1794
}
×
1795
#endif // REALM_DEBUG
1796

1797
void StringIndex::verify() const
1798
{
1,320✔
1799
#ifdef REALM_DEBUG
1,320✔
1800
    m_array->verify();
1,320✔
1801

660✔
1802
    Allocator& alloc = m_array->get_alloc();
1,320✔
1803
    const size_t array_size = m_array->size();
1,320✔
1804

660✔
1805
    // Get first matching row for every key
660✔
1806
    if (m_array->is_inner_bptree_node()) {
1,320✔
1807
        for (size_t i = 1; i < array_size; ++i) {
×
1808
            size_t ref = m_array->get_as_ref(i);
×
1809
            StringIndex ndx(ref, nullptr, 0, m_target_column, alloc);
×
1810
            ndx.verify();
×
1811
        }
×
UNCOV
1812
    }
×
1813
    else {
1,320✔
1814
        size_t column_size = m_target_column.size();
1,320✔
1815
        for (size_t i = 1; i < array_size; ++i) {
2,736✔
1816
            int64_t ref = m_array->get(i);
1,416✔
1817

708✔
1818
            // low bit set indicate literal ref (shifted)
708✔
1819
            if (ref & 1) {
1,416✔
1820
                size_t r = to_size_t((uint64_t(ref) >> 1));
96✔
1821
                REALM_ASSERT_EX(r < column_size, r, column_size);
96✔
1822
            }
96✔
1823
            else {
1,320✔
1824
                // A real ref either points to a list or a subindex
660✔
1825
                char* header = alloc.translate(to_ref(ref));
1,320✔
1826
                if (Array::get_context_flag_from_header(header)) {
1,320✔
1827
                    StringIndex ndx(to_ref(ref), m_array.get(), i, m_target_column, alloc);
1,296✔
1828
                    ndx.verify();
1,296✔
1829
                }
1,296✔
1830
                else {
24✔
1831
                    IntegerColumn sub(alloc, to_ref(ref)); // Throws
24✔
1832
                    IntegerColumn::const_iterator it = sub.cbegin();
24✔
1833
                    IntegerColumn::const_iterator it_end = sub.cend();
24✔
1834
                    SortedListComparator slc(m_target_column);
24✔
1835
                    Mixed previous = get(ObjKey(*it));
24✔
1836
                    size_t last_row = to_size_t(*it);
24✔
1837

12✔
1838
                    // Check that strings listed in sub are in sorted order
12✔
1839
                    // and if there are duplicates, that the row numbers are
12✔
1840
                    // sorted in the group of duplicates.
12✔
1841
                    while (it != it_end) {
96✔
1842
                        Mixed it_data = get(ObjKey(*it));
72✔
1843
                        size_t it_row = to_size_t(*it);
72✔
1844
                        REALM_ASSERT(previous.compare_signed(it_data) <= 0);
72✔
1845
                        if (it != sub.cbegin() && previous == it_data) {
72✔
1846
                            REALM_ASSERT_EX(it_row > last_row, it_row, last_row);
×
UNCOV
1847
                        }
×
1848
                        last_row = it_row;
72✔
1849
                        previous = get(ObjKey(*it));
72✔
1850
                        ++it;
72✔
1851
                    }
72✔
1852
                }
24✔
1853
            }
1,320✔
1854
        }
1,416✔
1855
    }
1,320✔
1856
// FIXME: Extend verification along the lines of IntegerColumn::verify().
660✔
1857
#endif
1,320✔
1858
}
1,320✔
1859

1860
#ifdef REALM_DEBUG
1861

1862
template <class T>
1863
void StringIndex::verify_entries(const ClusterColumn& column) const
1864
{
1865
    std::vector<ObjKey> results;
1866

1867
    auto it = column.begin();
1868
    auto end = column.end();
1869
    auto col = column.get_column_key();
1870
    while (it != end) {
1871
        ObjKey key = it->get_key();
1872
        T value = it->get<T>(col);
1873

1874
        find_all(results, value);
1875

1876
        auto ndx = find(results.begin(), results.end(), key);
1877
        REALM_ASSERT(ndx != results.end());
1878
        size_t found = count(value);
1879
        REALM_ASSERT_EX(found >= 1, found);
1880
        results.clear();
1881
    }
1882
}
1883

1884
namespace {
1885

1886
namespace {
1887

1888
bool is_chars(uint64_t val)
1889
{
×
1890
    if (val == 0)
×
1891
        return true;
×
1892
    if (is_chars(val >> 8)) {
×
1893
        char c = val & 0xFF;
×
UNCOV
1894
        if (!c || std::isalpha(c)) {
×
UNCOV
1895
            return true;
×
UNCOV
1896
        }
×
UNCOV
1897
    }
×
1898
    return false;
×
1899
}
×
1900

1901
void out_char(std::ostream& out, uint64_t val)
1902
{
×
1903
    if (val) {
×
1904
        out_char(out, val >> 8);
×
1905
        char c = val & 0xFF;
×
1906
        if (c && c != 'X') {
×
1907
            out << c;
×
1908
        }
×
1909
    }
×
1910
}
×
1911

1912
void out_hex(std::ostream& out, uint64_t val)
1913
{
×
1914
    if (is_chars(val)) {
×
1915
        out_char(out, val);
×
1916
    }
×
1917
    else {
×
1918
        out << int(val);
×
1919
    }
×
1920
}
×
1921

1922
} // namespace
1923

1924
} // namespace
1925

1926
void StringIndex::dump_node_structure(const Array& node, std::ostream& out, int level)
1927
{
×
1928
    int indent = level * 2;
×
1929
    Allocator& alloc = node.get_alloc();
×
1930
    Array subnode(alloc);
×
1931

1932
    size_t node_size = node.size();
×
1933
    REALM_ASSERT(node_size >= 1);
×
1934

1935
    out << std::hex;
×
1936

1937
    bool node_is_leaf = !node.is_inner_bptree_node();
×
1938
    if (node_is_leaf) {
×
1939
        out << std::setw(indent) << ""
×
1940
            << "Leaf (B+ tree) (ref: " << node.get_ref() << ")\n";
×
1941
    }
×
1942
    else {
×
1943
        out << std::setw(indent) << ""
×
1944
            << "Inner node (B+ tree) (ref: " << node.get_ref() << ")\n";
×
1945
    }
×
1946

1947
    subnode.init_from_ref(to_ref(node.front()));
×
1948
    out << std::setw(indent) << ""
×
1949
        << "  Keys (keys_ref: " << subnode.get_ref() << ", ";
×
1950
    if (subnode.is_empty()) {
×
1951
        out << "no keys";
×
1952
    }
×
1953
    else {
×
1954
        out << "keys: ";
×
1955
        for (size_t i = 0; i != subnode.size(); ++i) {
×
1956
            if (i != 0)
×
1957
                out << ", ";
×
1958
            out_hex(out, uint32_t(subnode.get(i)));
×
1959
        }
×
1960
    }
×
1961
    out << ")\n";
×
1962

1963
    if (node_is_leaf) {
×
1964
        for (size_t i = 1; i != node_size; ++i) {
×
1965
            int_fast64_t value = node.get(i);
×
1966
            bool is_single_row_index = (value & 1) != 0;
×
1967
            if (is_single_row_index) {
×
UNCOV
1968
                out << std::setw(indent) << ""
×
UNCOV
1969
                    << "  Single row index (value: " << (value / 2) << ")\n";
×
UNCOV
1970
                continue;
×
1971
            }
×
1972
            subnode.init_from_ref(to_ref(value));
×
1973
            bool is_subindex = subnode.get_context_flag();
×
UNCOV
1974
            if (is_subindex) {
×
UNCOV
1975
                out << std::setw(indent) << ""
×
UNCOV
1976
                    << "  Subindex\n";
×
UNCOV
1977
                dump_node_structure(subnode, out, level + 2);
×
UNCOV
1978
                continue;
×
UNCOV
1979
            }
×
UNCOV
1980
            IntegerColumn indexes(alloc, to_ref(value));
×
UNCOV
1981
            out << std::setw(indent) << ""
×
UNCOV
1982
                << "  List of row indexes\n";
×
UNCOV
1983
            indexes.dump_values(out, level + 2);
×
UNCOV
1984
        }
×
UNCOV
1985
        return;
×
UNCOV
1986
    }
×
1987

1988

UNCOV
1989
    size_t num_children = node_size - 1;
×
UNCOV
1990
    size_t child_ref_begin = 1;
×
UNCOV
1991
    size_t child_ref_end = 1 + num_children;
×
UNCOV
1992
    for (size_t i = child_ref_begin; i != child_ref_end; ++i) {
×
UNCOV
1993
        subnode.init_from_ref(node.get_as_ref(i));
×
UNCOV
1994
        dump_node_structure(subnode, out, level + 1);
×
UNCOV
1995
    }
×
UNCOV
1996
}
×
1997

1998

1999
void StringIndex::do_dump_node_structure(std::ostream& out, int level) const
UNCOV
2000
{
×
UNCOV
2001
    dump_node_structure(*m_array, out, level);
×
UNCOV
2002
}
×
2003

2004
#endif // LCOV_EXCL_STOP ignore debug functions
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc