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

realm / realm-core / jorgen.edelbo_138

13 Mar 2024 08:41AM UTC coverage: 91.77% (-0.3%) from 92.078%
jorgen.edelbo_138

Pull #7356

Evergreen

jedelbo
Add ability to get path to modified collections in object notifications
Pull Request #7356: Add ability to get path to modified collections in object notifications

94532 of 174642 branches covered (54.13%)

118 of 163 new or added lines in 16 files covered. (72.39%)

765 existing lines in 41 files now uncovered.

242808 of 264584 relevant lines covered (91.77%)

5878961.32 hits per line

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

84.22
/src/realm/dictionary.cpp
1
/*************************************************************************
2
 *
3
 * Copyright 2019 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 <realm/dictionary.hpp>
20
#include <realm/aggregate_ops.hpp>
21
#include <realm/array_mixed.hpp>
22
#include <realm/array_ref.hpp>
23
#include <realm/group.hpp>
24
#include <realm/list.hpp>
25
#include <realm/set.hpp>
26
#include <realm/replication.hpp>
27

28
#include <algorithm>
29

30
namespace realm {
31

32
namespace {
33
void validate_key_value(const Mixed& key)
34
{
122,292✔
35
    if (key.is_type(type_String)) {
122,295✔
36
        auto str = key.get_string();
122,295✔
37
        if (str.size()) {
122,295✔
38
            if (str[0] == '$')
122,232✔
39
                throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not start with '$'");
12✔
40
            if (memchr(str.data(), '.', str.size()))
122,220✔
41
                throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not contain '.'");
12✔
42
        }
122,220✔
43
    }
122,295✔
44
}
122,292✔
45

46
} // namespace
47

48

49
/******************************** Dictionary *********************************/
50

51
Dictionary::Dictionary(ColKey col_key, size_t level)
52
    : Base(col_key)
53
    , CollectionParent(level)
54
{
172,398✔
55
    if (!(col_key.is_dictionary() || col_key.get_type() == col_type_Mixed)) {
172,398✔
56
        throw InvalidArgument(ErrorCodes::TypeMismatch, "Property not a dictionary");
×
57
    }
×
58
}
172,398✔
59

60
Dictionary::Dictionary(Allocator& alloc, ColKey col_key, ref_type ref)
61
    : Base(Obj{}, col_key)
62
    , m_key_type(type_String)
63
{
27,909✔
64
    set_alloc(alloc);
27,909✔
65
    REALM_ASSERT(ref);
27,909✔
66
    m_dictionary_top.reset(new Array(alloc));
27,909✔
67
    m_dictionary_top->init_from_ref(ref);
27,909✔
68
    m_keys.reset(new BPlusTree<StringData>(alloc));
27,909✔
69
    m_values.reset(new BPlusTreeMixed(alloc));
27,909✔
70
    m_keys->set_parent(m_dictionary_top.get(), 0);
27,909✔
71
    m_values->set_parent(m_dictionary_top.get(), 1);
27,909✔
72
    m_keys->init_from_parent();
27,909✔
73
    m_values->init_from_parent();
27,909✔
74
}
27,909✔
75

76
Dictionary::~Dictionary() = default;
208,149✔
77

78
Dictionary& Dictionary::operator=(const Dictionary& other)
79
{
6,732✔
80
    Base::operator=(static_cast<const Base&>(other));
6,732✔
81

3,366✔
82
    if (this != &other) {
6,732✔
83
        // Back to scratch
3,366✔
84
        m_dictionary_top.reset();
6,732✔
85
        reset_content_version();
6,732✔
86
    }
6,732✔
87

3,366✔
88
    return *this;
6,732✔
89
}
6,732✔
90

91
size_t Dictionary::size() const
92
{
394,644✔
93
    if (!update())
394,644✔
94
        return 0;
41,808✔
95

176,145✔
96
    return m_values->size();
352,836✔
97
}
352,836✔
98

99
DataType Dictionary::get_key_data_type() const
100
{
17,880✔
101
    return m_key_type;
17,880✔
102
}
17,880✔
103

104
DataType Dictionary::get_value_data_type() const
105
{
14,238✔
106
    return DataType(m_col_key.get_type());
14,238✔
107
}
14,238✔
108

109
bool Dictionary::is_null(size_t ndx) const
110
{
×
111
    return get_any(ndx).is_null();
×
112
}
×
113

114
Mixed Dictionary::get_any(size_t ndx) const
115
{
16,341✔
116
    // Note: `size()` calls `update_if_needed()`.
8,169✔
117
    auto current_size = size();
16,341✔
118
    CollectionBase::validate_index("get_any()", ndx, current_size);
16,341✔
119
    return do_get(ndx);
16,341✔
120
}
16,341✔
121

122
std::pair<Mixed, Mixed> Dictionary::get_pair(size_t ndx) const
123
{
93,666✔
124
    // Note: `size()` calls `update_if_needed()`.
46,686✔
125
    auto current_size = size();
93,666✔
126
    CollectionBase::validate_index("get_pair()", ndx, current_size);
93,666✔
127
    return do_get_pair(ndx);
93,666✔
128
}
93,666✔
129

130
Mixed Dictionary::get_key(size_t ndx) const
131
{
54,450✔
132
    // Note: `size()` calls `update_if_needed()`.
27,189✔
133
    CollectionBase::validate_index("get_key()", ndx, size());
54,450✔
134
    return do_get_key(ndx);
54,450✔
135
}
54,450✔
136

137
size_t Dictionary::find_any(Mixed value) const
138
{
3,198✔
139
    return size() ? m_values->find_first(value) : realm::not_found;
2,952✔
140
}
3,198✔
141

142
size_t Dictionary::find_any_key(Mixed key) const noexcept
143
{
39,018✔
144
    if (update()) {
39,018✔
145
        return do_find_key(key);
30,990✔
146
    }
30,990✔
147

4,014✔
148
    return realm::npos;
8,028✔
149
}
8,028✔
150

151
template <typename AggregateType>
152
void Dictionary::do_accumulate(size_t* return_ndx, AggregateType& agg) const
153
{
17,784✔
154
    size_t ndx = realm::npos;
17,784✔
155

8,892✔
156
    m_values->traverse([&](BPlusTreeNode* node, size_t offset) {
17,784✔
157
        auto leaf = static_cast<BPlusTree<Mixed>::LeafNode*>(node);
17,784✔
158
        size_t e = leaf->size();
17,784✔
159
        for (size_t i = 0; i < e; i++) {
68,460✔
160
            auto val = leaf->get(i);
50,676✔
161
            if (agg.accumulate(val)) {
50,676✔
162
                ndx = i + offset;
38,598✔
163
            }
38,598✔
164
        }
50,676✔
165
        // Continue
8,892✔
166
        return IteratorControl::AdvanceToNext;
17,784✔
167
    });
17,784✔
168

8,892✔
169
    if (return_ndx)
17,784✔
170
        *return_ndx = ndx;
12✔
171
}
17,784✔
172

173
util::Optional<Mixed> Dictionary::do_min(size_t* return_ndx) const
174
{
4,104✔
175
    aggregate_operations::Minimum<Mixed> agg;
4,104✔
176
    do_accumulate(return_ndx, agg);
4,104✔
177
    return agg.is_null() ? Mixed{} : agg.result();
4,104✔
178
}
4,104✔
179

180
util::Optional<Mixed> Dictionary::do_max(size_t* return_ndx) const
181
{
5,424✔
182
    aggregate_operations::Maximum<Mixed> agg;
5,424✔
183
    do_accumulate(return_ndx, agg);
5,424✔
184
    return agg.is_null() ? Mixed{} : agg.result();
5,424✔
185
}
5,424✔
186

187
util::Optional<Mixed> Dictionary::do_sum(size_t* return_cnt) const
188
{
4,164✔
189
    auto type = get_value_data_type();
4,164✔
190
    if (type == type_Int) {
4,164✔
191
        aggregate_operations::Sum<Int> agg;
42✔
192
        do_accumulate(nullptr, agg);
42✔
193
        if (return_cnt)
42✔
194
            *return_cnt = agg.items_counted();
18✔
195
        return Mixed{agg.result()};
42✔
196
    }
42✔
197
    else if (type == type_Double) {
4,122✔
198
        aggregate_operations::Sum<Double> agg;
84✔
199
        do_accumulate(nullptr, agg);
84✔
200
        if (return_cnt)
84✔
201
            *return_cnt = agg.items_counted();
×
202
        return Mixed{agg.result()};
84✔
203
    }
84✔
204
    else if (type == type_Float) {
4,038✔
205
        aggregate_operations::Sum<Float> agg;
84✔
206
        do_accumulate(nullptr, agg);
84✔
207
        if (return_cnt)
84✔
208
            *return_cnt = agg.items_counted();
×
209
        return Mixed{agg.result()};
84✔
210
    }
84✔
211

1,977✔
212
    aggregate_operations::Sum<Mixed> agg;
3,954✔
213
    do_accumulate(nullptr, agg);
3,954✔
214
    if (return_cnt)
3,954✔
215
        *return_cnt = agg.items_counted();
×
216
    return Mixed{agg.result()};
3,954✔
217
}
3,954✔
218

219
util::Optional<Mixed> Dictionary::do_avg(size_t* return_cnt) const
220
{
4,092✔
221
    auto type = get_value_data_type();
4,092✔
222
    if (type == type_Int) {
4,092✔
223
        aggregate_operations::Average<Int> agg;
42✔
224
        do_accumulate(nullptr, agg);
42✔
225
        if (return_cnt)
42✔
226
            *return_cnt = agg.items_counted();
18✔
227
        return agg.is_null() ? Mixed{} : agg.result();
42✔
228
    }
42✔
229
    else if (type == type_Double) {
4,050✔
230
        aggregate_operations::Average<Double> agg;
60✔
231
        do_accumulate(nullptr, agg);
60✔
232
        if (return_cnt)
60✔
233
            *return_cnt = agg.items_counted();
×
234
        return agg.is_null() ? Mixed{} : agg.result();
60✔
235
    }
60✔
236
    else if (type == type_Float) {
3,990✔
237
        aggregate_operations::Average<Float> agg;
60✔
238
        do_accumulate(nullptr, agg);
60✔
239
        if (return_cnt)
60✔
240
            *return_cnt = agg.items_counted();
×
241
        return agg.is_null() ? Mixed{} : agg.result();
60✔
242
    }
60✔
243
    // Decimal128 is covered with mixed as well.
1,965✔
244
    aggregate_operations::Average<Mixed> agg;
3,930✔
245
    do_accumulate(nullptr, agg);
3,930✔
246
    if (return_cnt)
3,930✔
247
        *return_cnt = agg.items_counted();
×
248
    return agg.is_null() ? Mixed{} : agg.result();
3,930✔
249
}
3,930✔
250

251
namespace {
252
bool can_minmax(DataType type)
253
{
606✔
254
    switch (type) {
606✔
255
        case type_Int:
228✔
256
        case type_Float:
252✔
257
        case type_Double:
276✔
258
        case type_Decimal:
300✔
259
        case type_Mixed:
342✔
260
        case type_Timestamp:
366✔
261
            return true;
366✔
262
        default:
303✔
263
            return false;
240✔
264
    }
606✔
265
}
606✔
266
bool can_sum(DataType type)
267
{
600✔
268
    switch (type) {
600✔
269
        case type_Int:
198✔
270
        case type_Float:
222✔
271
        case type_Double:
246✔
272
        case type_Decimal:
270✔
273
        case type_Mixed:
312✔
274
            return true;
312✔
275
        default:
300✔
276
            return false;
288✔
277
    }
600✔
278
}
600✔
279
} // anonymous namespace
280

281
util::Optional<Mixed> Dictionary::min(size_t* return_ndx) const
282
{
300✔
283
    if (!can_minmax(get_value_data_type())) {
300✔
284
        return std::nullopt;
120✔
285
    }
120✔
286
    if (update()) {
180✔
287
        return do_min(return_ndx);
108✔
288
    }
108✔
289
    if (return_ndx)
72✔
290
        *return_ndx = realm::not_found;
×
291
    return Mixed{};
72✔
292
}
72✔
293

294
util::Optional<Mixed> Dictionary::max(size_t* return_ndx) const
295
{
306✔
296
    if (!can_minmax(get_value_data_type())) {
306✔
297
        return std::nullopt;
120✔
298
    }
120✔
299
    if (update()) {
186✔
300
        return do_max(return_ndx);
108✔
301
    }
108✔
302
    if (return_ndx)
78✔
303
        *return_ndx = realm::not_found;
6✔
304
    return Mixed{};
78✔
305
}
78✔
306

307
util::Optional<Mixed> Dictionary::sum(size_t* return_cnt) const
308
{
300✔
309
    if (!can_sum(get_value_data_type())) {
300✔
310
        return std::nullopt;
144✔
311
    }
144✔
312
    if (update()) {
156✔
313
        return do_sum(return_cnt);
96✔
314
    }
96✔
315
    if (return_cnt)
60✔
316
        *return_cnt = 0;
×
317
    return Mixed{0};
60✔
318
}
60✔
319

320
util::Optional<Mixed> Dictionary::avg(size_t* return_cnt) const
321
{
300✔
322
    if (!can_sum(get_value_data_type())) {
300✔
323
        return std::nullopt;
144✔
324
    }
144✔
325
    if (update()) {
156✔
326
        return do_avg(return_cnt);
96✔
327
    }
96✔
328
    if (return_cnt)
60✔
329
        *return_cnt = 0;
×
330
    return Mixed{};
60✔
331
}
60✔
332

333
void Dictionary::align_indices(std::vector<size_t>& indices) const
334
{
5,046✔
335
    auto sz = size();
5,046✔
336
    auto sz2 = indices.size();
5,046✔
337
    indices.reserve(sz);
5,046✔
338
    if (sz < sz2) {
5,046✔
339
        // If list size has decreased, we have to start all over
340
        indices.clear();
×
341
        sz2 = 0;
×
342
    }
×
343
    for (size_t i = sz2; i < sz; i++) {
23,358✔
344
        // If list size has increased, just add the missing indices
9,156✔
345
        indices.push_back(i);
18,312✔
346
    }
18,312✔
347
}
5,046✔
348

349
namespace {
350
template <class T>
351
void do_sort(std::vector<size_t>& indices, bool ascending, const std::vector<T>& values)
352
{
4,416✔
353
    auto b = indices.begin();
4,416✔
354
    auto e = indices.end();
4,416✔
355
    std::sort(b, e, [ascending, &values](size_t i1, size_t i2) {
36,144✔
356
        return ascending ? values[i1] < values[i2] : values[i2] < values[i1];
35,502✔
357
    });
36,144✔
358
}
4,416✔
359
} // anonymous namespace
360

361
void Dictionary::sort(std::vector<size_t>& indices, bool ascending) const
362
{
3,786✔
363
    align_indices(indices);
3,786✔
364
    do_sort(indices, ascending, m_values->get_all());
3,786✔
365
}
3,786✔
366

367
void Dictionary::distinct(std::vector<size_t>& indices, util::Optional<bool> ascending) const
368
{
630✔
369
    align_indices(indices);
630✔
370
    auto values = m_values->get_all();
630✔
371
    do_sort(indices, ascending.value_or(true), values);
630✔
372
    indices.erase(std::unique(indices.begin(), indices.end(),
630✔
373
                              [&values](size_t i1, size_t i2) {
1,800✔
374
                                  return values[i1] == values[i2];
1,800✔
375
                              }),
1,800✔
376
                  indices.end());
630✔
377

315✔
378
    if (!ascending) {
630✔
379
        // need to return indices in original ordering
63✔
380
        std::sort(indices.begin(), indices.end(), std::less<size_t>());
126✔
381
    }
126✔
382
}
630✔
383

384
void Dictionary::sort_keys(std::vector<size_t>& indices, bool ascending) const
385
{
504✔
386
    align_indices(indices);
504✔
387
#ifdef REALM_DEBUG
504✔
388
    if (indices.size() > 1) {
504✔
389
        // We rely in the design that the keys are already sorted
252✔
390
        switch (m_key_type) {
504✔
391
            case type_String: {
504✔
392
                IteratorAdapter help(static_cast<BPlusTree<StringData>*>(m_keys.get()));
504✔
393
                auto is_sorted = std::is_sorted(help.begin(), help.end());
504✔
394
                REALM_ASSERT(is_sorted);
504✔
395
                break;
504✔
396
            }
×
397
            case type_Int: {
✔
398
                IteratorAdapter help(static_cast<BPlusTree<Int>*>(m_keys.get()));
×
399
                auto is_sorted = std::is_sorted(help.begin(), help.end());
×
400
                REALM_ASSERT(is_sorted);
×
401
                break;
×
402
            }
×
403
            default:
✔
404
                break;
×
405
        }
504✔
406
    }
504✔
407
#endif
504✔
408
    if (ascending) {
504✔
409
        std::sort(indices.begin(), indices.end());
252✔
410
    }
252✔
411
    else {
252✔
412
        std::sort(indices.begin(), indices.end(), std::greater<size_t>());
252✔
413
    }
252✔
414
}
504✔
415

416
void Dictionary::distinct_keys(std::vector<size_t>& indices, util::Optional<bool>) const
417
{
126✔
418
    // we rely on the design of dictionary to assume that the keys are unique
63✔
419
    align_indices(indices);
126✔
420
}
126✔
421

422

423
Obj Dictionary::create_and_insert_linked_object(Mixed key)
424
{
4,344✔
425
    Table& t = *get_target_table();
4,344✔
426
    auto o = t.is_embedded() ? t.create_linked_object() : t.create_object();
4,344✔
427
    insert(key, o.get_key());
4,344✔
428
    return o;
4,344✔
429
}
4,344✔
430

431
void Dictionary::insert_collection(const PathElement& path_elem, CollectionType dict_or_list)
432
{
1,530✔
433
    if (dict_or_list == CollectionType::Set) {
1,530✔
434
        throw IllegalOperation("Set nested in Dictionary is not supported");
×
435
    }
×
436

765✔
437
    check_level();
1,530✔
438
    ensure_created();
1,530✔
439
    Mixed new_val(0, dict_or_list);
1,530✔
440
    auto old_val = try_get(path_elem.get_key());
1,530✔
441
    if (!old_val || *old_val != new_val) {
1,530✔
442
        m_values->ensure_keys();
1,389✔
443
        auto [it, inserted] = insert(path_elem.get_key(), new_val);
1,389✔
444
        set_key(*m_values, it.index());
1,389✔
445
    }
1,389✔
446
}
1,530✔
447

448
DictionaryPtr Dictionary::get_dictionary(const PathElement& path_elem) const
449
{
660✔
450
    update();
660✔
451
    auto weak = const_cast<Dictionary*>(this)->weak_from_this();
660✔
452
    auto shared = weak.expired() ? std::make_shared<Dictionary>(*this) : weak.lock();
582✔
453
    DictionaryPtr ret = std::make_shared<Dictionary>(m_col_key, get_level() + 1);
660✔
454
    ret->set_owner(shared, build_index(path_elem.get_key()));
660✔
455
    return ret;
660✔
456
}
660✔
457

458
std::shared_ptr<Lst<Mixed>> Dictionary::get_list(const PathElement& path_elem) const
459
{
1,194✔
460
    update();
1,194✔
461
    auto weak = const_cast<Dictionary*>(this)->weak_from_this();
1,194✔
462
    auto shared = weak.expired() ? std::make_shared<Dictionary>(*this) : weak.lock();
1,065✔
463
    std::shared_ptr<Lst<Mixed>> ret = std::make_shared<Lst<Mixed>>(m_col_key, get_level() + 1);
1,194✔
464
    ret->set_owner(shared, build_index(path_elem.get_key()));
1,194✔
465
    return ret;
1,194✔
466
}
1,194✔
467

468
Mixed Dictionary::get(Mixed key) const
469
{
15,228✔
470
    if (auto opt_val = try_get(key)) {
15,228✔
471
        return *opt_val;
15,204✔
472
    }
15,204✔
473
    throw KeyNotFound("Dictionary::get");
24✔
474
}
24✔
475

476
util::Optional<Mixed> Dictionary::try_get(Mixed key) const
477
{
843,102✔
478
    if (update()) {
843,102✔
479
        auto ndx = do_find_key(key);
842,106✔
480
        if (ndx != realm::npos) {
842,106✔
481
            return do_get(ndx);
838,770✔
482
        }
838,770✔
483
    }
4,332✔
484
    return {};
4,332✔
485
}
4,332✔
486

487
Dictionary::Iterator Dictionary::begin() const
488
{
23,391✔
489
    // Need an update because the `Dictionary::Iterator` constructor relies on
11,439✔
490
    // `m_clusters` to determine if it was already at end.
11,439✔
491
    update();
23,391✔
492
    return Iterator(this, 0);
23,391✔
493
}
23,391✔
494

495
Dictionary::Iterator Dictionary::end() const
496
{
84,951✔
497
    return Iterator(this, size());
84,951✔
498
}
84,951✔
499

500
std::pair<Dictionary::Iterator, bool> Dictionary::insert(Mixed key, Mixed value)
501
{
110,100✔
502
    auto my_table = get_table_unchecked();
110,100✔
503
    if (key.get_type() != m_key_type) {
110,100✔
UNCOV
504
        throw InvalidArgument(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: Invalid key type");
×
UNCOV
505
    }
×
506
    if (m_col_key) {
110,100✔
507
        if (value.is_null()) {
110,094✔
508
            if (!m_col_key.is_nullable()) {
5,280✔
509
                throw InvalidArgument(ErrorCodes::InvalidDictionaryValue, "Dictionary::insert: Value cannot be null");
×
UNCOV
510
            }
×
511
        }
104,814✔
512
        else {
104,814✔
513
            if (m_col_key.get_type() == col_type_Link && value.get_type() == type_TypedLink) {
104,814✔
514
                if (my_table->get_opposite_table_key(m_col_key) != value.get<ObjLink>().get_table_key()) {
2,826✔
515
                    throw InvalidArgument(ErrorCodes::InvalidDictionaryValue,
6✔
516
                                          "Dictionary::insert: Wrong object type");
6✔
517
                }
6✔
518
            }
101,988✔
519
            else if (m_col_key.get_type() != col_type_Mixed && value.get_type() != DataType(m_col_key.get_type())) {
101,988✔
UNCOV
520
                throw InvalidArgument(ErrorCodes::InvalidDictionaryValue, "Dictionary::insert: Wrong value type");
×
UNCOV
521
            }
×
522
            else if (value.is_type(type_Link) && m_col_key.get_type() != col_type_Link) {
101,988✔
UNCOV
523
                throw InvalidArgument(ErrorCodes::InvalidDictionaryValue,
×
524
                                      "Dictionary::insert: No target table for link");
×
525
            }
×
526
        }
110,094✔
527
    }
110,094✔
528

54,855✔
529
    validate_key_value(key);
110,094✔
530
    ensure_created();
110,094✔
531

54,855✔
532
    ObjLink new_link;
110,094✔
533
    if (value.is_type(type_TypedLink)) {
110,094✔
534
        new_link = value.get<ObjLink>();
8,160✔
535
        if (!new_link.is_unresolved())
8,160✔
536
            my_table->get_parent_group()->validate(new_link);
7,920✔
537
    }
8,160✔
538
    else if (value.is_type(type_Link)) {
101,934✔
539
        auto target_table = my_table->get_opposite_table(m_col_key);
12,990✔
540
        auto key = value.get<ObjKey>();
12,990✔
541
        if (!key.is_unresolved() && !target_table->is_valid(key)) {
12,990✔
542
            throw InvalidArgument(ErrorCodes::KeyNotFound, "Target object not found");
6✔
543
        }
6✔
544
        new_link = ObjLink(target_table->get_key(), key);
12,984✔
545
        value = Mixed(new_link);
12,984✔
546
    }
12,984✔
547

54,855✔
548
    if (!m_dictionary_top) {
110,091✔
UNCOV
549
        throw StaleAccessor("Stale dictionary");
×
UNCOV
550
    }
×
551

54,852✔
552
    bool old_entry = false;
110,088✔
553
    auto [ndx, actual_key] = find_impl(key);
110,088✔
554
    if (actual_key != key) {
110,088✔
555
        // key does not already exist
49,929✔
556
        switch (m_key_type) {
100,239✔
557
            case type_String:
100,239✔
558
                static_cast<BPlusTree<StringData>*>(m_keys.get())->insert(ndx, key.get_string());
100,239✔
559
                break;
100,239✔
UNCOV
560
            case type_Int:
✔
UNCOV
561
                static_cast<BPlusTree<Int>*>(m_keys.get())->insert(ndx, key.get_int());
×
UNCOV
562
                break;
×
UNCOV
563
            default:
✔
564
                break;
×
565
        }
100,239✔
566
        m_values->insert(ndx, value);
100,239✔
567
    }
100,239✔
568
    else {
9,849✔
569
        old_entry = true;
9,849✔
570
    }
9,849✔
571

54,852✔
572
    if (Replication* repl = get_replication()) {
110,088✔
573
        if (old_entry) {
96,444✔
574
            repl->dictionary_set(*this, ndx, key, value);
8,592✔
575
        }
8,592✔
576
        else {
87,852✔
577
            repl->dictionary_insert(*this, ndx, key, value);
87,852✔
578
        }
87,852✔
579
    }
96,444✔
580

54,852✔
581
    bump_content_version();
110,088✔
582

54,852✔
583
    ObjLink old_link;
110,088✔
584
    if (old_entry) {
110,088✔
585
        Mixed old_value = m_values->get(ndx);
9,792✔
586
        if (old_value.is_type(type_TypedLink)) {
9,792✔
587
            old_link = old_value.get<ObjLink>();
768✔
588
        }
768✔
589
        m_values->set(ndx, value);
9,792✔
590
    }
9,792✔
591

54,852✔
592
    if (new_link != old_link) {
110,088✔
593
        CascadeState cascade_state(CascadeState::Mode::Strong);
21,192✔
594
        bool recurse = Base::replace_backlink(m_col_key, old_link, new_link, cascade_state);
21,192✔
595
        if (recurse)
21,192✔
596
            _impl::TableFriend::remove_recursive(*my_table, cascade_state); // Throws
294✔
597
    }
21,192✔
598

54,852✔
599
    return {Iterator(this, ndx), !old_entry};
110,088✔
600
}
110,088✔
601

602
const Mixed Dictionary::operator[](Mixed key)
603
{
812,802✔
604
    auto ret = try_get(key);
812,802✔
605
    if (!ret) {
812,802✔
606
        ret = Mixed{};
6✔
607
        insert(key, Mixed{});
6✔
608
    }
6✔
609

406,401✔
610
    return *ret;
812,802✔
611
}
812,802✔
612

613
Obj Dictionary::get_object(StringData key)
614
{
12,417✔
615
    if (auto val = try_get(key)) {
12,417✔
616
        if ((*val).is_type(type_TypedLink)) {
9,219✔
617
            return get_table()->get_parent_group()->get_object((*val).get_link());
9,099✔
618
        }
9,099✔
619
    }
3,318✔
620
    return {};
3,318✔
621
}
3,318✔
622

623
bool Dictionary::contains(Mixed key) const noexcept
624
{
3,072✔
625
    return find_any_key(key) != realm::npos;
3,072✔
626
}
3,072✔
627

628
Dictionary::Iterator Dictionary::find(Mixed key) const noexcept
629
{
34,854✔
630
    auto ndx = find_any_key(key);
34,854✔
631
    if (ndx != realm::npos) {
34,854✔
632
        return Iterator(this, ndx);
19,512✔
633
    }
19,512✔
634
    return end();
15,342✔
635
}
15,342✔
636

637

638
void Dictionary::translate_path(const StablePath& stable_path, Path& path) const
639
{
36✔
640
    auto& index = stable_path[m_level];
36✔
641
    auto ndx = find_index(index);
36✔
642
    StringData key = do_get_key(ndx).get_string();
36✔
643
    path.emplace_back(key);
36✔
644
    if (stable_path.size() > size_t(m_level) + 1) {
36✔
NEW
645
        Mixed val = do_get(ndx);
×
NEW
646
        if (val.is_type(type_Dictionary)) {
×
NEW
647
            DummyParent parent(this->get_table(), val.get_ref());
×
NEW
648
            Dictionary dict(parent, 0);
×
NEW
649
            dict.translate_path(stable_path, path);
×
NEW
650
        }
×
NEW
651
        else if (val.is_type(type_List)) {
×
NEW
652
            DummyParent parent(this->get_table(), val.get_ref());
×
NEW
653
            Lst<Mixed> list(parent, 0);
×
NEW
654
            list.translate_path(stable_path, path);
×
NEW
655
        }
×
NEW
656
    }
×
657
}
36✔
658

659
void Dictionary::add_index(Path& path, const Index& index) const
660
{
1,008✔
661
    auto ndx = m_values->find_key(index.get_salt());
1,008✔
662
    auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
1,008✔
663
    path.emplace_back(keys->get(ndx));
1,008✔
664
}
1,008✔
665

666
size_t Dictionary::find_index(const Index& index) const
667
{
342✔
668
    update();
342✔
669
    return m_values->find_key(index.get_salt());
342✔
670
}
342✔
671

672
UpdateStatus Dictionary::do_update_if_needed(bool allow_create) const
673
{
1,506,231✔
674
    switch (get_update_status()) {
1,506,231✔
675
        case UpdateStatus::Detached: {
6✔
676
            m_dictionary_top.reset();
6✔
677
            return UpdateStatus::Detached;
6✔
UNCOV
678
        }
×
679
        case UpdateStatus::NoChange: {
1,313,937✔
680
            if (m_dictionary_top && m_dictionary_top->is_attached()) {
1,313,937✔
681
                return UpdateStatus::NoChange;
1,268,463✔
682
            }
1,268,463✔
683
            // The tree has not been initialized yet for this accessor, so
22,557✔
684
            // perform lazy initialization by treating it as an update.
22,557✔
685
            [[fallthrough]];
45,474✔
686
        }
45,474✔
687
        case UpdateStatus::Updated:
237,759✔
688
            return init_from_parent(allow_create);
237,759✔
UNCOV
689
    }
×
690
    REALM_UNREACHABLE();
UNCOV
691
}
×
692

693
UpdateStatus Dictionary::update_if_needed() const
694
{
1,394,628✔
695
    constexpr bool allow_create = false;
1,394,628✔
696
    return do_update_if_needed(allow_create);
1,394,628✔
697
}
1,394,628✔
698

699
void Dictionary::ensure_created()
700
{
111,600✔
701
    constexpr bool allow_create = true;
111,600✔
702
    if (do_update_if_needed(allow_create) == UpdateStatus::Detached) {
111,600✔
UNCOV
703
        throw StaleAccessor("Dictionary no longer exists");
×
UNCOV
704
    }
×
705
}
111,600✔
706

707
bool Dictionary::try_erase(Mixed key)
708
{
12,207✔
709
    validate_key_value(key);
12,207✔
710
    if (!update())
12,207✔
UNCOV
711
        return false;
×
712

6,162✔
713
    auto ndx = do_find_key(key);
12,207✔
714
    if (ndx == realm::npos) {
12,207✔
715
        return false;
1,230✔
716
    }
1,230✔
717

5,547✔
718
    do_erase(ndx, key);
10,977✔
719

5,547✔
720
    return true;
10,977✔
721
}
10,977✔
722

723
void Dictionary::erase(Mixed key)
724
{
11,097✔
725
    if (!try_erase(key)) {
11,097✔
726
        throw KeyNotFound(util::format("Cannot remove key %1 from dictionary: key not found", key));
618✔
727
    }
618✔
728
}
11,097✔
729

730
auto Dictionary::erase(Iterator it) -> Iterator
731
{
2,616✔
732
    auto pos = it.m_ndx;
2,616✔
733
    CollectionBase::validate_index("erase()", pos, size());
2,616✔
734

1,308✔
735
    do_erase(pos, do_get_key(pos));
2,616✔
736
    if (pos < size())
2,616✔
737
        pos++;
480✔
738
    return {this, pos};
2,616✔
739
}
2,616✔
740

741
void Dictionary::nullify(size_t ndx)
742
{
726✔
743
    REALM_ASSERT(m_dictionary_top);
726✔
744
    REALM_ASSERT(ndx != realm::npos);
726✔
745

363✔
746
    if (Replication* repl = get_replication()) {
726✔
747
        auto key = do_get_key(ndx);
708✔
748
        repl->dictionary_set(*this, ndx, key, Mixed());
708✔
749
    }
708✔
750

363✔
751
    m_values->set(ndx, Mixed());
726✔
752
}
726✔
753

754
bool Dictionary::nullify(ObjLink target_link)
755
{
738✔
756
    size_t ndx = find_first(target_link);
738✔
757
    if (ndx != realm::not_found) {
738✔
758
        nullify(ndx);
726✔
759
        return true;
726✔
760
    }
726✔
761
    else {
12✔
762
        // There must be a link in a nested collection
6✔
763
        size_t sz = size();
12✔
764
        for (size_t ndx = 0; ndx < sz; ndx++) {
18✔
765
            auto val = m_values->get(ndx);
12✔
766
            auto key = do_get_key(ndx);
12✔
767
            if (val.is_type(type_Dictionary)) {
12✔
UNCOV
768
                auto dict = get_dictionary(key.get_string());
×
UNCOV
769
                if (dict->nullify(target_link)) {
×
UNCOV
770
                    return true;
×
UNCOV
771
                }
×
772
            }
12✔
773
            if (val.is_type(type_List)) {
12✔
774
                auto list = get_list(key.get_string());
6✔
775
                if (list->nullify(target_link)) {
6✔
776
                    return true;
6✔
777
                }
6✔
778
            }
6✔
779
        }
12✔
780
    }
12✔
781
    return false;
372✔
782
}
738✔
783

784
bool Dictionary::replace_link(ObjLink old_link, ObjLink replace_link)
785
{
264✔
786
    size_t ndx = find_first(old_link);
264✔
787
    if (ndx != realm::not_found) {
264✔
788
        auto key = do_get_key(ndx);
264✔
789
        insert(key, replace_link);
264✔
790
        return true;
264✔
791
    }
264✔
UNCOV
792
    else {
×
793
        // There must be a link in a nested collection
UNCOV
794
        size_t sz = size();
×
UNCOV
795
        for (size_t ndx = 0; ndx < sz; ndx++) {
×
UNCOV
796
            auto val = m_values->get(ndx);
×
UNCOV
797
            auto key = do_get_key(ndx);
×
UNCOV
798
            if (val.is_type(type_Dictionary)) {
×
UNCOV
799
                auto dict = get_dictionary(key.get_string());
×
UNCOV
800
                if (dict->replace_link(old_link, replace_link)) {
×
801
                    return true;
×
UNCOV
802
                }
×
803
            }
×
804
            if (val.is_type(type_List)) {
×
805
                auto list = get_list(key.get_string());
×
806
                if (list->replace_link(old_link, replace_link)) {
×
807
                    return true;
×
808
                }
×
809
            }
×
810
        }
×
811
    }
×
812
    return false;
132✔
813
}
264✔
814

815
bool Dictionary::remove_backlinks(CascadeState& state) const
816
{
3,054✔
817
    size_t sz = size();
3,054✔
818
    bool recurse = false;
3,054✔
819
    for (size_t ndx = 0; ndx < sz; ndx++) {
13,968✔
820
        if (clear_backlink(ndx, state)) {
10,914✔
821
            recurse = true;
369✔
822
        }
369✔
823
    }
10,914✔
824
    return recurse;
3,054✔
825
}
3,054✔
826

827
size_t Dictionary::find_first(Mixed value) const
828
{
46,596✔
829
    return update() ? m_values->find_first(value) : realm::not_found;
46,596✔
830
}
46,596✔
831

832
void Dictionary::clear()
833
{
2,724✔
834
    if (size() > 0) {
2,724✔
835
        if (Replication* repl = get_replication()) {
2,490✔
836
            repl->dictionary_clear(*this);
2,478✔
837
        }
2,478✔
838
        CascadeState cascade_state(CascadeState::Mode::Strong);
2,490✔
839
        bool recurse = remove_backlinks(cascade_state);
2,490✔
840

1,245✔
841
        // Just destroy the whole cluster
1,245✔
842
        m_dictionary_top->destroy_deep();
2,490✔
843
        m_dictionary_top.reset();
2,490✔
844

1,245✔
845
        update_child_ref(0, 0);
2,490✔
846

1,245✔
847
        if (recurse)
2,490✔
848
            _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
6✔
849
    }
2,490✔
850
}
2,724✔
851

852
UpdateStatus Dictionary::init_from_parent(bool allow_create) const
853
{
237,759✔
854
    Base::update_content_version();
237,759✔
855
    try {
237,759✔
856
        auto ref = Base::get_collection_ref();
237,759✔
857
        if ((ref || allow_create) && !m_dictionary_top) {
237,759✔
858
            Allocator& alloc = get_alloc();
145,605✔
859
            m_dictionary_top.reset(new Array(alloc));
145,605✔
860
            m_dictionary_top->set_parent(const_cast<Dictionary*>(this), 0);
145,605✔
861
            switch (m_key_type) {
145,605✔
862
                case type_String: {
145,602✔
863
                    m_keys.reset(new BPlusTree<StringData>(alloc));
145,602✔
864
                    break;
145,602✔
UNCOV
865
                }
×
UNCOV
866
                case type_Int: {
✔
UNCOV
867
                    m_keys.reset(new BPlusTree<Int>(alloc));
×
UNCOV
868
                    break;
×
UNCOV
869
                }
×
UNCOV
870
                default:
✔
UNCOV
871
                    break;
×
872
            }
145,605✔
873
            m_keys->set_parent(m_dictionary_top.get(), 0);
145,605✔
874
            m_values.reset(new BPlusTreeMixed(alloc));
145,605✔
875
            m_values->set_parent(m_dictionary_top.get(), 1);
145,605✔
876
        }
145,605✔
877

118,287✔
878
        if (ref) {
237,759✔
879
            m_dictionary_top->init_from_ref(ref);
146,178✔
880
            m_keys->init_from_parent();
146,178✔
881
            m_values->init_from_parent();
146,178✔
882
        }
146,178✔
883
        else {
91,581✔
884
            // dictionary detached
45,330✔
885
            if (!allow_create) {
91,581✔
886
                m_dictionary_top.reset();
61,008✔
887
                return UpdateStatus::Detached;
61,008✔
888
            }
61,008✔
889

15,246✔
890
            // Create dictionary
15,246✔
891
            m_dictionary_top->create(Array::type_HasRefs, false, 2, 0);
30,573✔
892
            m_values->create();
30,573✔
893
            m_keys->create();
30,573✔
894
            m_dictionary_top->update_parent();
30,573✔
895
        }
30,573✔
896

118,287✔
897
        return UpdateStatus::Updated;
206,835✔
898
    }
30✔
899
    catch (...) {
30✔
900
        m_dictionary_top.reset();
30✔
901
        throw;
30✔
902
    }
30✔
903
}
237,759✔
904

905
size_t Dictionary::do_find_key(Mixed key) const noexcept
906
{
885,291✔
907
    auto [ndx, actual_key] = find_impl(key);
885,291✔
908
    if (actual_key == key) {
885,291✔
909
        return ndx;
871,773✔
910
    }
871,773✔
911
    return realm::npos;
13,518✔
912
}
13,518✔
913

914
std::pair<size_t, Mixed> Dictionary::find_impl(Mixed key) const noexcept
915
{
995,376✔
916
    auto sz = m_keys->size();
995,376✔
917
    Mixed actual;
995,376✔
918
    if (sz && key.is_type(m_key_type)) {
995,376✔
919
        switch (m_key_type) {
962,901✔
920
            case type_String: {
962,901✔
921
                auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
962,901✔
922
                StringData val = key.get<StringData>();
962,901✔
923
                IteratorAdapter help(keys);
962,901✔
924
                auto it = std::lower_bound(help.begin(), help.end(), val);
962,901✔
925
                if (it.index() < sz) {
962,901✔
926
                    actual = *it;
911,346✔
927
                }
911,346✔
928
                return {it.index(), actual};
962,901✔
UNCOV
929
                break;
×
UNCOV
930
            }
×
UNCOV
931
            case type_Int: {
✔
UNCOV
932
                auto keys = static_cast<BPlusTree<Int>*>(m_keys.get());
×
UNCOV
933
                Int val = key.get<Int>();
×
UNCOV
934
                IteratorAdapter help(keys);
×
UNCOV
935
                auto it = std::lower_bound(help.begin(), help.end(), val);
×
UNCOV
936
                if (it.index() < sz) {
×
937
                    actual = *it;
×
938
                }
×
939
                return {it.index(), actual};
×
940
                break;
×
941
            }
×
942
            default:
✔
943
                break;
×
944
        }
32,475✔
945
    }
32,475✔
946

16,197✔
947
    return {sz, actual};
32,475✔
948
}
32,475✔
949

950
Mixed Dictionary::do_get(size_t ndx) const
951
{
949,299✔
952
    Mixed val = m_values->get(ndx);
949,299✔
953

474,555✔
954
    // Filter out potential unresolved links
474,555✔
955
    if (val.is_type(type_TypedLink) && val.get<ObjKey>().is_unresolved()) {
949,299✔
956
        return {};
1,104✔
957
    }
1,104✔
958
    return val;
948,195✔
959
}
948,195✔
960

961
void Dictionary::do_erase(size_t ndx, Mixed key)
962
{
13,581✔
963
    CascadeState cascade_state(CascadeState::Mode::Strong);
13,581✔
964
    bool recurse = clear_backlink(ndx, cascade_state);
13,581✔
965

6,849✔
966
    if (recurse)
13,581✔
967
        _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
102✔
968

6,849✔
969
    if (Replication* repl = get_replication()) {
13,581✔
970
        repl->dictionary_erase(*this, ndx, key);
12,327✔
971
    }
12,327✔
972

6,849✔
973
    m_keys->erase(ndx);
13,581✔
974
    m_values->erase(ndx);
13,581✔
975
    bump_content_version();
13,581✔
976
}
13,581✔
977

978
Mixed Dictionary::do_get_key(size_t ndx) const
979
{
152,364✔
980
    switch (m_key_type) {
152,364✔
981
        case type_String: {
152,364✔
982
            return static_cast<BPlusTree<StringData>*>(m_keys.get())->get(ndx);
152,364✔
UNCOV
983
        }
×
UNCOV
984
        case type_Int: {
✔
UNCOV
985
            return static_cast<BPlusTree<Int>*>(m_keys.get())->get(ndx);
×
UNCOV
986
        }
×
UNCOV
987
        default:
✔
UNCOV
988
            break;
×
UNCOV
989
    }
×
990

991
    return {};
×
992
}
×
993

994
std::pair<Mixed, Mixed> Dictionary::do_get_pair(size_t ndx) const
995
{
93,660✔
996
    return {do_get_key(ndx), do_get(ndx)};
93,660✔
997
}
93,660✔
998

999
bool Dictionary::clear_backlink(size_t ndx, CascadeState& state) const
1000
{
24,495✔
1001
    auto value = m_values->get(ndx);
24,495✔
1002
    if (value.is_type(type_TypedLink)) {
24,495✔
1003
        return Base::remove_backlink(m_col_key, value.get_link(), state);
7,836✔
1004
    }
7,836✔
1005
    if (value.is_type(type_Dictionary)) {
16,659✔
1006
        auto key = do_get_key(ndx);
30✔
1007
        return get_dictionary(key.get_string())->remove_backlinks(state);
30✔
1008
    }
30✔
1009
    if (value.is_type(type_List)) {
16,629✔
1010
        auto key = do_get_key(ndx);
60✔
1011
        return get_list(key.get_string())->remove_backlinks(state);
60✔
1012
    }
60✔
1013
    return false;
16,569✔
1014
}
16,569✔
1015

1016
void Dictionary::swap_content(Array& fields1, Array& fields2, size_t index1, size_t index2)
UNCOV
1017
{
×
UNCOV
1018
    std::string buf1, buf2;
×
1019

1020
    // Swap keys
UNCOV
1021
    REALM_ASSERT(m_key_type == type_String);
×
UNCOV
1022
    ArrayString keys(get_alloc());
×
UNCOV
1023
    keys.set_parent(&fields1, 1);
×
UNCOV
1024
    keys.init_from_parent();
×
1025
    buf1 = keys.get(index1);
×
1026

UNCOV
1027
    keys.set_parent(&fields2, 1);
×
UNCOV
1028
    keys.init_from_parent();
×
1029
    buf2 = keys.get(index2);
×
1030
    keys.set(index2, buf1);
×
1031

1032
    keys.set_parent(&fields1, 1);
×
1033
    keys.init_from_parent();
×
UNCOV
1034
    keys.set(index1, buf2);
×
1035

1036
    // Swap values
1037
    ArrayMixed values(get_alloc());
×
1038
    values.set_parent(&fields1, 2);
×
UNCOV
1039
    values.init_from_parent();
×
1040
    Mixed val1 = values.get(index1);
×
1041
    val1.use_buffer(buf1);
×
1042

UNCOV
1043
    values.set_parent(&fields2, 2);
×
UNCOV
1044
    values.init_from_parent();
×
1045
    Mixed val2 = values.get(index2);
×
1046
    val2.use_buffer(buf2);
×
1047
    values.set(index2, val1);
×
1048

1049
    values.set_parent(&fields1, 2);
×
UNCOV
1050
    values.init_from_parent();
×
1051
    values.set(index1, val2);
×
1052
}
×
1053

1054
Mixed Dictionary::find_value(Mixed value) const noexcept
1055
{
×
UNCOV
1056
    size_t ndx = update() ? m_values->find_first(value) : realm::npos;
×
1057
    return (ndx == realm::npos) ? Mixed{} : do_get_key(ndx);
×
1058
}
×
1059

1060
StableIndex Dictionary::build_index(Mixed key) const
1061
{
3,066✔
1062
    auto it = find(key);
3,066✔
1063
    int64_t index = (it != end()) ? m_values->get_key(it.index()) : 0;
3,066✔
1064
    return {index};
3,066✔
1065
}
3,066✔
1066

1067

1068
void Dictionary::verify() const
1069
{
12,177✔
1070
    m_keys->verify();
12,177✔
1071
    m_values->verify();
12,177✔
1072
    REALM_ASSERT(m_keys->size() == m_values->size());
12,177✔
1073
}
12,177✔
1074

1075
void Dictionary::get_key_type()
1076
{
172,398✔
1077
    m_key_type = get_table()->get_dictionary_key_type(m_col_key);
172,398✔
1078
    if (!(m_key_type == type_String || m_key_type == type_Int))
172,398!
UNCOV
1079
        throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary keys can only be strings or integers");
×
1080
}
172,398✔
1081

1082
void Dictionary::migrate()
1083
{
6✔
1084
    // Dummy implementation of legacy dictionary cluster tree
3✔
1085
    class DictionaryClusterTree : public ClusterTree {
6✔
1086
    public:
6✔
1087
        DictionaryClusterTree(ArrayParent* owner, Allocator& alloc, size_t ndx)
6✔
1088
            : ClusterTree(nullptr, alloc, ndx)
6✔
1089
            , m_owner(owner)
6✔
1090
        {
6✔
1091
        }
6✔
1092

3✔
1093
        std::unique_ptr<ClusterNode> get_root_from_parent() final
6✔
1094
        {
6✔
1095
            return create_root_from_parent(m_owner, m_top_position_for_cluster_tree);
6✔
1096
        }
6✔
1097

3✔
1098
    private:
6✔
1099
        ArrayParent* m_owner;
6✔
1100
    };
6✔
1101

3✔
1102
    if (auto dict_ref = Base::get_collection_ref()) {
6✔
1103
        Allocator& alloc = get_alloc();
6✔
1104
        DictionaryClusterTree cluster_tree(this, alloc, 0);
6✔
1105
        if (cluster_tree.init_from_parent()) {
6✔
1106
            // Create an empty dictionary in the old ones place
3✔
1107
            Base::set_collection_ref(0);
6✔
1108
            ensure_created();
6✔
1109

3✔
1110
            ArrayString keys(alloc); // We only support string type keys.
6✔
1111
            ArrayMixed values(alloc);
6✔
1112
            constexpr ColKey key_col(ColKey::Idx{0}, col_type_String, ColumnAttrMask(), 0);
6✔
1113
            constexpr ColKey value_col(ColKey::Idx{1}, col_type_Mixed, ColumnAttrMask(), 0);
6✔
1114
            size_t nb_elements = cluster_tree.size();
6✔
1115
            cluster_tree.traverse([&](const Cluster* cluster) {
6✔
1116
                cluster->init_leaf(key_col, &keys);
6✔
1117
                cluster->init_leaf(value_col, &values);
6✔
1118
                auto sz = cluster->node_size();
6✔
1119
                for (size_t i = 0; i < sz; i++) {
60✔
1120
                    // Just use low level functions to insert elements. All keys must be legal and
27✔
1121
                    // unique and all values must match expected type. Links should just be preserved
27✔
1122
                    // so no need to worry about backlinks.
27✔
1123
                    StringData key = keys.get(i);
54✔
1124
                    auto [ndx, actual_key] = find_impl(key);
54✔
1125
                    REALM_ASSERT(actual_key != key);
54✔
1126
                    static_cast<BPlusTree<StringData>*>(m_keys.get())->insert(ndx, key);
54✔
1127
                    m_values->insert(ndx, values.get(i));
54✔
1128
                }
54✔
1129
                return IteratorControl::AdvanceToNext;
6✔
1130
            });
6✔
1131
            REALM_ASSERT(size() == nb_elements);
6✔
1132
            Array::destroy_deep(to_ref(dict_ref), alloc);
6✔
1133
        }
6✔
UNCOV
1134
        else {
×
1135
            REALM_UNREACHABLE();
UNCOV
1136
        }
×
1137
    }
6✔
1138
}
6✔
1139

1140
template <>
1141
void CollectionBaseImpl<DictionaryBase>::to_json(std::ostream&, JSONOutputMode,
1142
                                                 util::FunctionRef<void(const Mixed&)>) const
UNCOV
1143
{
×
1144
}
×
1145

1146
void Dictionary::to_json(std::ostream& out, JSONOutputMode output_mode,
1147
                         util::FunctionRef<void(const Mixed&)> fn) const
1148
{
438✔
1149
    if (output_mode == output_mode_xjson_plus) {
438✔
1150
        out << "{ \"$dictionary\": ";
156✔
1151
    }
156✔
1152
    out << "{";
438✔
1153

219✔
1154
    auto sz = size();
438✔
1155
    for (size_t i = 0; i < sz; i++) {
966✔
1156
        if (i > 0)
528✔
1157
            out << ",";
126✔
1158
        out << do_get_key(i) << ":";
528✔
1159
        Mixed val = do_get(i);
528✔
1160
        if (val.is_type(type_TypedLink)) {
528✔
1161
            fn(val);
144✔
1162
        }
144✔
1163
        else if (val.is_type(type_Dictionary)) {
384✔
1164
            DummyParent parent(this->get_table(), val.get_ref());
12✔
1165
            Dictionary dict(parent, 0);
12✔
1166
            dict.to_json(out, output_mode, fn);
12✔
1167
        }
12✔
1168
        else if (val.is_type(type_List)) {
372✔
1169
            DummyParent parent(this->get_table(), val.get_ref());
12✔
1170
            Lst<Mixed> list(parent, 0);
12✔
1171
            list.to_json(out, output_mode, fn);
12✔
1172
        }
12✔
1173
        else {
360✔
1174
            val.to_json(out, output_mode);
360✔
1175
        }
360✔
1176
    }
528✔
1177

219✔
1178
    out << "}";
438✔
1179
    if (output_mode == output_mode_xjson_plus) {
438✔
1180
        out << "}";
156✔
1181
    }
156✔
1182
}
438✔
1183

1184
ref_type Dictionary::get_collection_ref(Index index, CollectionType type) const
1185
{
6,522✔
1186
    auto ndx = m_values->find_key(index.get_salt());
6,522✔
1187
    if (ndx != realm::not_found) {
6,522✔
1188
        auto val = m_values->get(ndx);
6,516✔
1189
        if (val.is_type(DataType(int(type)))) {
6,516✔
1190
            return val.get_ref();
6,516✔
1191
        }
6,516✔
UNCOV
1192
        throw realm::IllegalOperation(util::format("Not a %1", type));
×
UNCOV
1193
    }
×
1194
    throw StaleAccessor("This collection is no more");
6✔
1195
}
6✔
1196

1197
bool Dictionary::check_collection_ref(Index index, CollectionType type) const noexcept
1198
{
1,014✔
1199
    auto ndx = m_values->find_key(index.get_salt());
1,014✔
1200
    if (ndx != realm::not_found) {
1,014✔
1201
        return m_values->get(ndx).is_type(DataType(int(type)));
996✔
1202
    }
996✔
1203
    return false;
18✔
1204
}
18✔
1205

1206
void Dictionary::set_collection_ref(Index index, ref_type ref, CollectionType type)
1207
{
1,650✔
1208
    auto ndx = m_values->find_key(index.get_salt());
1,650✔
1209
    if (ndx == realm::not_found) {
1,650✔
UNCOV
1210
        throw StaleAccessor("Collection has been deleted");
×
UNCOV
1211
    }
×
1212
    m_values->set(ndx, Mixed(ref, type));
1,650✔
1213
}
1,650✔
1214

1215
/************************* DictionaryLinkValues *************************/
1216

1217
DictionaryLinkValues::DictionaryLinkValues(const Obj& obj, ColKey col_key)
1218
    : m_source(obj, col_key)
1219
{
×
1220
    REALM_ASSERT_EX(col_key.get_type() == col_type_Link, col_key.get_type());
×
UNCOV
1221
}
×
1222

1223
DictionaryLinkValues::DictionaryLinkValues(const Dictionary& source)
1224
    : m_source(source)
1225
{
3,114✔
1226
    REALM_ASSERT_EX(source.get_value_data_type() == type_Link, source.get_value_data_type());
3,114✔
1227
}
3,114✔
1228

1229
ObjKey DictionaryLinkValues::get_key(size_t ndx) const
1230
{
72✔
1231
    Mixed val = m_source.get_any(ndx);
72✔
1232
    if (val.is_type(type_Link, type_TypedLink)) {
72✔
1233
        return val.get<ObjKey>();
48✔
1234
    }
48✔
1235
    return {};
24✔
1236
}
24✔
1237

1238
Obj DictionaryLinkValues::get_object(size_t row_ndx) const
1239
{
2,400✔
1240
    Mixed val = m_source.get_any(row_ndx);
2,400✔
1241
    if (val.is_type(type_TypedLink)) {
2,400✔
1242
        return get_table()->get_parent_group()->get_object(val.get_link());
2,382✔
1243
    }
2,382✔
1244
    return {};
18✔
1245
}
18✔
1246

1247
} // namespace realm
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