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

realm / realm-core / thomas.goyne_232

13 Mar 2024 01:00AM UTC coverage: 91.787% (+0.9%) from 90.924%
thomas.goyne_232

Pull #7402

Evergreen

tgoyne
Add more UpdateIfNeeded tests
Pull Request #7402: Make Obj trivial and add a separate ObjCollectionParent type

94460 of 174600 branches covered (54.1%)

496 of 559 new or added lines in 21 files covered. (88.73%)

848 existing lines in 34 files now uncovered.

242761 of 264484 relevant lines covered (91.79%)

6342666.36 hits per line

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

85.13
/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,295✔
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,235✔
39
                throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not start with '$'");
12✔
40
            if (memchr(str.data(), '.', str.size()))
122,223✔
41
                throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not contain '.'");
12✔
42
        }
122,223✔
43
    }
122,295✔
44
}
122,295✔
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,443✔
55
    if (!(col_key.is_dictionary() || col_key.get_type() == col_type_Mixed)) {
172,443✔
56
        throw InvalidArgument(ErrorCodes::TypeMismatch, "Property not a dictionary");
×
57
    }
×
58
}
172,443✔
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,194✔
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,725✔
93
    if (!update())
394,725✔
94
        return 0;
41,808✔
95

176,130✔
96
    return m_values->size();
352,917✔
97
}
352,917✔
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,583✔
163
            }
38,583✔
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,117✔
356
        return ascending ? values[i1] < values[i2] : values[i2] < values[i1];
35,475✔
357
    });
36,117✔
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,392✔
443
        auto [it, inserted] = insert(path_elem.get_key(), new_val);
1,392✔
444
        set_key(*m_values, it.index());
1,392✔
445
    }
1,392✔
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,135✔
470
    if (auto opt_val = try_get(key)) {
15,135✔
471
        return *opt_val;
15,111✔
472
    }
15,111✔
473
    throw KeyNotFound("Dictionary::get");
24✔
474
}
24✔
475

476
util::Optional<Mixed> Dictionary::try_get(Mixed key) const
477
{
843,009✔
478
    if (update()) {
843,009✔
479
        auto ndx = do_find_key(key);
842,013✔
480
        if (ndx != realm::npos) {
842,013✔
481
            return do_get(ndx);
838,677✔
482
        }
838,677✔
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,193✔
502
    auto my_table = get_table_unchecked();
110,193✔
503
    if (key.get_type() != m_key_type) {
110,193✔
504
        throw InvalidArgument(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: Invalid key type");
×
505
    }
×
506
    if (m_col_key) {
110,193✔
507
        if (value.is_null()) {
110,187✔
508
            if (!m_col_key.is_nullable()) {
5,280✔
509
                throw InvalidArgument(ErrorCodes::InvalidDictionaryValue, "Dictionary::insert: Value cannot be null");
×
510
            }
×
511
        }
104,907✔
512
        else {
104,907✔
513
            if (m_col_key.get_type() == col_type_Link && value.get_type() == type_TypedLink) {
104,907✔
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
            }
102,081✔
519
            else if (m_col_key.get_type() != col_type_Mixed && value.get_type() != DataType(m_col_key.get_type())) {
102,081✔
520
                throw InvalidArgument(ErrorCodes::InvalidDictionaryValue, "Dictionary::insert: Wrong value type");
×
521
            }
×
522
            else if (value.is_type(type_Link) && m_col_key.get_type() != col_type_Link) {
102,081✔
523
                throw InvalidArgument(ErrorCodes::InvalidDictionaryValue,
×
524
                                      "Dictionary::insert: No target table for link");
×
525
            }
×
526
        }
110,187✔
527
    }
110,187✔
528

54,966✔
529
    validate_key_value(key);
110,187✔
530
    ensure_created();
110,187✔
531

54,966✔
532
    ObjLink new_link;
110,187✔
533
    if (value.is_type(type_TypedLink)) {
110,187✔
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)) {
102,027✔
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,966✔
548
    if (!m_dictionary_top) {
110,184✔
549
        throw StaleAccessor("Stale dictionary");
×
550
    }
×
551

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

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

54,963✔
581
    bump_content_version();
110,181✔
582

54,963✔
583
    ObjLink old_link;
110,181✔
584
    if (old_entry) {
110,181✔
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,963✔
592
    if (new_link != old_link) {
110,181✔
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,963✔
599
    return {Iterator(this, ndx), !old_entry};
110,181✔
600
}
110,181✔
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
void Dictionary::add_index(Path& path, const Index& index) const
638
{
1,008✔
639
    auto ndx = m_values->find_key(index.get_salt());
1,008✔
640
    auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
1,008✔
641
    path.emplace_back(keys->get(ndx));
1,008✔
642
}
1,008✔
643

644
size_t Dictionary::find_index(const Index& index) const
645
{
306✔
646
    update();
306✔
647
    return m_values->find_key(index.get_salt());
306✔
648
}
306✔
649

650
UpdateStatus Dictionary::do_update_if_needed(bool allow_create) const
651
{
1,506,183✔
652
    switch (get_update_status()) {
1,506,183✔
653
        case UpdateStatus::Detached: {
6✔
654
            m_dictionary_top.reset();
6✔
655
            return UpdateStatus::Detached;
6✔
656
        }
×
657
        case UpdateStatus::NoChange: {
1,313,745✔
658
            if (m_dictionary_top && m_dictionary_top->is_attached()) {
1,313,745✔
659
                return UpdateStatus::NoChange;
1,268,373✔
660
            }
1,268,373✔
661
            // The tree has not been initialized yet for this accessor, so
22,470✔
662
            // perform lazy initialization by treating it as an update.
22,470✔
663
            [[fallthrough]];
45,372✔
664
        }
45,372✔
665
        case UpdateStatus::Updated:
237,807✔
666
            return init_from_parent(allow_create);
237,807✔
UNCOV
667
    }
×
668
    REALM_UNREACHABLE();
669
}
×
670

671
UpdateStatus Dictionary::update_if_needed() const
672
{
1,394,481✔
673
    constexpr bool allow_create = false;
1,394,481✔
674
    return do_update_if_needed(allow_create);
1,394,481✔
675
}
1,394,481✔
676

677
void Dictionary::ensure_created()
678
{
111,699✔
679
    constexpr bool allow_create = true;
111,699✔
680
    if (do_update_if_needed(allow_create) == UpdateStatus::Detached) {
111,699✔
NEW
681
        throw StaleAccessor("Dictionary no longer exists");
×
UNCOV
682
    }
×
683
}
111,699✔
684

685
bool Dictionary::try_erase(Mixed key)
686
{
12,114✔
687
    validate_key_value(key);
12,114✔
688
    if (!update())
12,114✔
689
        return false;
×
690

6,051✔
691
    auto ndx = do_find_key(key);
12,114✔
692
    if (ndx == realm::npos) {
12,114✔
693
        return false;
1,230✔
694
    }
1,230✔
695

5,436✔
696
    do_erase(ndx, key);
10,884✔
697

5,436✔
698
    return true;
10,884✔
699
}
10,884✔
700

701
void Dictionary::erase(Mixed key)
702
{
11,004✔
703
    if (!try_erase(key)) {
11,004✔
704
        throw KeyNotFound(util::format("Cannot remove key %1 from dictionary: key not found", key));
618✔
705
    }
618✔
706
}
11,004✔
707

708
auto Dictionary::erase(Iterator it) -> Iterator
709
{
2,616✔
710
    auto pos = it.m_ndx;
2,616✔
711
    CollectionBase::validate_index("erase()", pos, size());
2,616✔
712

1,308✔
713
    do_erase(pos, do_get_key(pos));
2,616✔
714
    if (pos < size())
2,616✔
715
        pos++;
480✔
716
    return {this, pos};
2,616✔
717
}
2,616✔
718

719
void Dictionary::nullify(size_t ndx)
720
{
726✔
721
    REALM_ASSERT(m_dictionary_top);
726✔
722
    REALM_ASSERT(ndx != realm::npos);
726✔
723

363✔
724
    if (Replication* repl = get_replication()) {
726✔
725
        auto key = do_get_key(ndx);
708✔
726
        repl->dictionary_set(*this, ndx, key, Mixed());
708✔
727
    }
708✔
728

363✔
729
    m_values->set(ndx, Mixed());
726✔
730
}
726✔
731

732
bool Dictionary::nullify(ObjLink target_link)
733
{
738✔
734
    size_t ndx = find_first(target_link);
738✔
735
    if (ndx != realm::not_found) {
738✔
736
        nullify(ndx);
726✔
737
        return true;
726✔
738
    }
726✔
739
    else {
12✔
740
        // There must be a link in a nested collection
6✔
741
        size_t sz = size();
12✔
742
        for (size_t ndx = 0; ndx < sz; ndx++) {
18✔
743
            auto val = m_values->get(ndx);
12✔
744
            auto key = do_get_key(ndx);
12✔
745
            if (val.is_type(type_Dictionary)) {
12✔
UNCOV
746
                auto dict = get_dictionary(key.get_string());
×
747
                if (dict->nullify(target_link)) {
×
748
                    return true;
×
749
                }
×
750
            }
12✔
751
            if (val.is_type(type_List)) {
12✔
752
                auto list = get_list(key.get_string());
6✔
753
                if (list->nullify(target_link)) {
6✔
754
                    return true;
6✔
755
                }
6✔
756
            }
6✔
757
        }
12✔
758
    }
12✔
759
    return false;
372✔
760
}
738✔
761

762
bool Dictionary::replace_link(ObjLink old_link, ObjLink replace_link)
763
{
264✔
764
    size_t ndx = find_first(old_link);
264✔
765
    if (ndx != realm::not_found) {
264✔
766
        auto key = do_get_key(ndx);
264✔
767
        insert(key, replace_link);
264✔
768
        return true;
264✔
769
    }
264✔
UNCOV
770
    else {
×
771
        // There must be a link in a nested collection
UNCOV
772
        size_t sz = size();
×
773
        for (size_t ndx = 0; ndx < sz; ndx++) {
×
774
            auto val = m_values->get(ndx);
×
775
            auto key = do_get_key(ndx);
×
776
            if (val.is_type(type_Dictionary)) {
×
777
                auto dict = get_dictionary(key.get_string());
×
778
                if (dict->replace_link(old_link, replace_link)) {
×
779
                    return true;
×
780
                }
×
781
            }
×
782
            if (val.is_type(type_List)) {
×
783
                auto list = get_list(key.get_string());
×
784
                if (list->replace_link(old_link, replace_link)) {
×
785
                    return true;
×
786
                }
×
787
            }
×
788
        }
×
789
    }
×
790
    return false;
132✔
791
}
264✔
792

793
bool Dictionary::remove_backlinks(CascadeState& state) const
794
{
3,054✔
795
    size_t sz = size();
3,054✔
796
    bool recurse = false;
3,054✔
797
    for (size_t ndx = 0; ndx < sz; ndx++) {
13,968✔
798
        if (clear_backlink(ndx, state)) {
10,914✔
799
            recurse = true;
369✔
800
        }
369✔
801
    }
10,914✔
802
    return recurse;
3,054✔
803
}
3,054✔
804

805
size_t Dictionary::find_first(Mixed value) const
806
{
46,596✔
807
    return update() ? m_values->find_first(value) : realm::not_found;
46,596✔
808
}
46,596✔
809

810
void Dictionary::clear()
811
{
2,724✔
812
    if (size() > 0) {
2,724✔
813
        if (Replication* repl = get_replication()) {
2,490✔
814
            repl->dictionary_clear(*this);
2,478✔
815
        }
2,478✔
816
        CascadeState cascade_state(CascadeState::Mode::Strong);
2,490✔
817
        bool recurse = remove_backlinks(cascade_state);
2,490✔
818

1,245✔
819
        // Just destroy the whole cluster
1,245✔
820
        m_dictionary_top->destroy_deep();
2,490✔
821
        m_dictionary_top.reset();
2,490✔
822

1,245✔
823
        update_child_ref(0, 0);
2,490✔
824

1,245✔
825
        if (recurse)
2,490✔
826
            _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
6✔
827
    }
2,490✔
828
}
2,724✔
829

830
UpdateStatus Dictionary::init_from_parent(bool allow_create) const
831
{
237,807✔
832
    Base::update_content_version();
237,807✔
833
    try {
237,807✔
834
        auto ref = Base::get_collection_ref();
237,807✔
835
        if ((ref || allow_create) && !m_dictionary_top) {
237,807✔
836
            Allocator& alloc = get_alloc();
145,650✔
837
            m_dictionary_top.reset(new Array(alloc));
145,650✔
838
            m_dictionary_top->set_parent(const_cast<Dictionary*>(this), 0);
145,650✔
839
            switch (m_key_type) {
145,650✔
840
                case type_String: {
145,650✔
841
                    m_keys.reset(new BPlusTree<StringData>(alloc));
145,650✔
842
                    break;
145,650✔
UNCOV
843
                }
×
844
                case type_Int: {
✔
845
                    m_keys.reset(new BPlusTree<Int>(alloc));
×
846
                    break;
×
847
                }
×
848
                default:
✔
849
                    break;
×
850
            }
145,650✔
851
            m_keys->set_parent(m_dictionary_top.get(), 0);
145,650✔
852
            m_values.reset(new BPlusTreeMixed(alloc));
145,650✔
853
            m_values->set_parent(m_dictionary_top.get(), 1);
145,650✔
854
        }
145,650✔
855

118,254✔
856
        if (ref) {
237,807✔
857
            m_dictionary_top->init_from_ref(ref);
146,223✔
858
            m_keys->init_from_parent();
146,223✔
859
            m_values->init_from_parent();
146,223✔
860
        }
146,223✔
861
        else {
91,584✔
862
            // dictionary detached
45,330✔
863
            if (!allow_create) {
91,584✔
864
                m_dictionary_top.reset();
61,008✔
865
                return UpdateStatus::Detached;
61,008✔
866
            }
61,008✔
867

15,246✔
868
            // Create dictionary
15,246✔
869
            m_dictionary_top->create(Array::type_HasRefs, false, 2, 0);
30,576✔
870
            m_values->create();
30,576✔
871
            m_keys->create();
30,576✔
872
            m_dictionary_top->update_parent();
30,576✔
873
        }
30,576✔
874

118,254✔
875
        return UpdateStatus::Updated;
206,883✔
876
    }
30✔
877
    catch (...) {
30✔
878
        m_dictionary_top.reset();
30✔
879
        throw;
30✔
880
    }
30✔
881
}
237,807✔
882

883
size_t Dictionary::do_find_key(Mixed key) const noexcept
884
{
885,105✔
885
    auto [ndx, actual_key] = find_impl(key);
885,105✔
886
    if (actual_key == key) {
885,105✔
887
        return ndx;
871,587✔
888
    }
871,587✔
889
    return realm::npos;
13,518✔
890
}
13,518✔
891

892
std::pair<size_t, Mixed> Dictionary::find_impl(Mixed key) const noexcept
893
{
995,286✔
894
    auto sz = m_keys->size();
995,286✔
895
    Mixed actual;
995,286✔
896
    if (sz && key.is_type(m_key_type)) {
995,286✔
897
        switch (m_key_type) {
962,805✔
898
            case type_String: {
962,805✔
899
                auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
962,805✔
900
                StringData val = key.get<StringData>();
962,805✔
901
                IteratorAdapter help(keys);
962,805✔
902
                auto it = std::lower_bound(help.begin(), help.end(), val);
962,805✔
903
                if (it.index() < sz) {
962,805✔
904
                    actual = *it;
911,319✔
905
                }
911,319✔
906
                return {it.index(), actual};
962,805✔
UNCOV
907
                break;
×
908
            }
×
909
            case type_Int: {
✔
910
                auto keys = static_cast<BPlusTree<Int>*>(m_keys.get());
×
911
                Int val = key.get<Int>();
×
912
                IteratorAdapter help(keys);
×
913
                auto it = std::lower_bound(help.begin(), help.end(), val);
×
914
                if (it.index() < sz) {
×
915
                    actual = *it;
×
916
                }
×
917
                return {it.index(), actual};
×
918
                break;
×
919
            }
×
920
            default:
✔
921
                break;
×
922
        }
32,481✔
923
    }
32,481✔
924

16,197✔
925
    return {sz, actual};
32,481✔
926
}
32,481✔
927

928
Mixed Dictionary::do_get(size_t ndx) const
929
{
949,206✔
930
    Mixed val = m_values->get(ndx);
949,206✔
931

474,444✔
932
    // Filter out potential unresolved links
474,444✔
933
    if (val.is_type(type_TypedLink) && val.get<ObjKey>().is_unresolved()) {
949,206✔
934
        return {};
1,104✔
935
    }
1,104✔
936
    return val;
948,102✔
937
}
948,102✔
938

939
void Dictionary::do_erase(size_t ndx, Mixed key)
940
{
13,488✔
941
    CascadeState cascade_state(CascadeState::Mode::Strong);
13,488✔
942
    bool recurse = clear_backlink(ndx, cascade_state);
13,488✔
943

6,738✔
944
    if (recurse)
13,488✔
945
        _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
102✔
946

6,738✔
947
    if (Replication* repl = get_replication()) {
13,488✔
948
        repl->dictionary_erase(*this, ndx, key);
12,234✔
949
    }
12,234✔
950

6,738✔
951
    m_keys->erase(ndx);
13,488✔
952
    m_values->erase(ndx);
13,488✔
953
    bump_content_version();
13,488✔
954
}
13,488✔
955

956
Mixed Dictionary::do_get_key(size_t ndx) const
957
{
152,328✔
958
    switch (m_key_type) {
152,328✔
959
        case type_String: {
152,328✔
960
            return static_cast<BPlusTree<StringData>*>(m_keys.get())->get(ndx);
152,328✔
UNCOV
961
        }
×
962
        case type_Int: {
✔
963
            return static_cast<BPlusTree<Int>*>(m_keys.get())->get(ndx);
×
964
        }
×
965
        default:
✔
966
            break;
×
967
    }
×
968

UNCOV
969
    return {};
×
970
}
×
971

972
std::pair<Mixed, Mixed> Dictionary::do_get_pair(size_t ndx) const
973
{
93,660✔
974
    return {do_get_key(ndx), do_get(ndx)};
93,660✔
975
}
93,660✔
976

977
bool Dictionary::clear_backlink(size_t ndx, CascadeState& state) const
978
{
24,402✔
979
    auto value = m_values->get(ndx);
24,402✔
980
    if (value.is_type(type_TypedLink)) {
24,402✔
981
        return Base::remove_backlink(m_col_key, value.get_link(), state);
7,836✔
982
    }
7,836✔
983
    if (value.is_type(type_Dictionary)) {
16,566✔
984
        auto key = do_get_key(ndx);
30✔
985
        return get_dictionary(key.get_string())->remove_backlinks(state);
30✔
986
    }
30✔
987
    if (value.is_type(type_List)) {
16,536✔
988
        auto key = do_get_key(ndx);
60✔
989
        return get_list(key.get_string())->remove_backlinks(state);
60✔
990
    }
60✔
991
    return false;
16,476✔
992
}
16,476✔
993

994
void Dictionary::swap_content(Array& fields1, Array& fields2, size_t index1, size_t index2)
UNCOV
995
{
×
996
    std::string buf1, buf2;
×
997

998
    // Swap keys
UNCOV
999
    REALM_ASSERT(m_key_type == type_String);
×
1000
    ArrayString keys(get_alloc());
×
1001
    keys.set_parent(&fields1, 1);
×
1002
    keys.init_from_parent();
×
1003
    buf1 = keys.get(index1);
×
1004

UNCOV
1005
    keys.set_parent(&fields2, 1);
×
1006
    keys.init_from_parent();
×
1007
    buf2 = keys.get(index2);
×
1008
    keys.set(index2, buf1);
×
1009

UNCOV
1010
    keys.set_parent(&fields1, 1);
×
1011
    keys.init_from_parent();
×
1012
    keys.set(index1, buf2);
×
1013

1014
    // Swap values
UNCOV
1015
    ArrayMixed values(get_alloc());
×
1016
    values.set_parent(&fields1, 2);
×
1017
    values.init_from_parent();
×
1018
    Mixed val1 = values.get(index1);
×
1019
    val1.use_buffer(buf1);
×
1020

UNCOV
1021
    values.set_parent(&fields2, 2);
×
1022
    values.init_from_parent();
×
1023
    Mixed val2 = values.get(index2);
×
1024
    val2.use_buffer(buf2);
×
1025
    values.set(index2, val1);
×
1026

UNCOV
1027
    values.set_parent(&fields1, 2);
×
1028
    values.init_from_parent();
×
1029
    values.set(index1, val2);
×
1030
}
×
1031

1032
Mixed Dictionary::find_value(Mixed value) const noexcept
UNCOV
1033
{
×
1034
    size_t ndx = update() ? m_values->find_first(value) : realm::npos;
×
1035
    return (ndx == realm::npos) ? Mixed{} : do_get_key(ndx);
×
1036
}
×
1037

1038
StableIndex Dictionary::build_index(Mixed key) const
1039
{
3,066✔
1040
    auto it = find(key);
3,066✔
1041
    int64_t index = (it != end()) ? m_values->get_key(it.index()) : 0;
3,066✔
1042
    return {index};
3,066✔
1043
}
3,066✔
1044

1045

1046
void Dictionary::verify() const
1047
{
12,177✔
1048
    m_keys->verify();
12,177✔
1049
    m_values->verify();
12,177✔
1050
    REALM_ASSERT(m_keys->size() == m_values->size());
12,177✔
1051
}
12,177✔
1052

1053
void Dictionary::get_key_type()
1054
{
172,443✔
1055
    m_key_type = get_table()->get_dictionary_key_type(m_col_key);
172,443✔
1056
    if (!(m_key_type == type_String || m_key_type == type_Int))
172,443!
UNCOV
1057
        throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary keys can only be strings or integers");
×
1058
}
172,443✔
1059

1060
void Dictionary::migrate()
1061
{
6✔
1062
    // Dummy implementation of legacy dictionary cluster tree
3✔
1063
    class DictionaryClusterTree : public ClusterTree {
6✔
1064
    public:
6✔
1065
        DictionaryClusterTree(ArrayParent* owner, Allocator& alloc, size_t ndx)
6✔
1066
            : ClusterTree(nullptr, alloc, ndx)
6✔
1067
            , m_owner(owner)
6✔
1068
        {
6✔
1069
        }
6✔
1070

3✔
1071
        std::unique_ptr<ClusterNode> get_root_from_parent() final
6✔
1072
        {
6✔
1073
            return create_root_from_parent(m_owner, m_top_position_for_cluster_tree);
6✔
1074
        }
6✔
1075

3✔
1076
    private:
6✔
1077
        ArrayParent* m_owner;
6✔
1078
    };
6✔
1079

3✔
1080
    if (auto dict_ref = Base::get_collection_ref()) {
6✔
1081
        Allocator& alloc = get_alloc();
6✔
1082
        DictionaryClusterTree cluster_tree(this, alloc, 0);
6✔
1083
        if (cluster_tree.init_from_parent()) {
6✔
1084
            // Create an empty dictionary in the old ones place
3✔
1085
            Base::set_collection_ref(0);
6✔
1086
            ensure_created();
6✔
1087

3✔
1088
            ArrayString keys(alloc); // We only support string type keys.
6✔
1089
            ArrayMixed values(alloc);
6✔
1090
            constexpr ColKey key_col(ColKey::Idx{0}, col_type_String, ColumnAttrMask(), 0);
6✔
1091
            constexpr ColKey value_col(ColKey::Idx{1}, col_type_Mixed, ColumnAttrMask(), 0);
6✔
1092
            size_t nb_elements = cluster_tree.size();
6✔
1093
            cluster_tree.traverse([&](const Cluster* cluster) {
6✔
1094
                cluster->init_leaf(key_col, &keys);
6✔
1095
                cluster->init_leaf(value_col, &values);
6✔
1096
                auto sz = cluster->node_size();
6✔
1097
                for (size_t i = 0; i < sz; i++) {
60✔
1098
                    // Just use low level functions to insert elements. All keys must be legal and
27✔
1099
                    // unique and all values must match expected type. Links should just be preserved
27✔
1100
                    // so no need to worry about backlinks.
27✔
1101
                    StringData key = keys.get(i);
54✔
1102
                    auto [ndx, actual_key] = find_impl(key);
54✔
1103
                    REALM_ASSERT(actual_key != key);
54✔
1104
                    static_cast<BPlusTree<StringData>*>(m_keys.get())->insert(ndx, key);
54✔
1105
                    m_values->insert(ndx, values.get(i));
54✔
1106
                }
54✔
1107
                return IteratorControl::AdvanceToNext;
6✔
1108
            });
6✔
1109
            REALM_ASSERT(size() == nb_elements);
6✔
1110
            Array::destroy_deep(to_ref(dict_ref), alloc);
6✔
1111
        }
6✔
UNCOV
1112
        else {
×
1113
            REALM_UNREACHABLE();
UNCOV
1114
        }
×
1115
    }
6✔
1116
}
6✔
1117

1118
template <>
1119
void CollectionBaseImpl<DictionaryBase>::to_json(std::ostream&, JSONOutputMode,
1120
                                                 util::FunctionRef<void(const Mixed&)>) const
UNCOV
1121
{
×
1122
}
×
1123

1124
void Dictionary::to_json(std::ostream& out, JSONOutputMode output_mode,
1125
                         util::FunctionRef<void(const Mixed&)> fn) const
1126
{
438✔
1127
    if (output_mode == output_mode_xjson_plus) {
438✔
1128
        out << "{ \"$dictionary\": ";
156✔
1129
    }
156✔
1130
    out << "{";
438✔
1131

219✔
1132
    auto sz = size();
438✔
1133
    for (size_t i = 0; i < sz; i++) {
966✔
1134
        if (i > 0)
528✔
1135
            out << ",";
126✔
1136
        out << do_get_key(i) << ":";
528✔
1137
        Mixed val = do_get(i);
528✔
1138
        if (val.is_type(type_TypedLink)) {
528✔
1139
            fn(val);
144✔
1140
        }
144✔
1141
        else if (val.is_type(type_Dictionary)) {
384✔
1142
            DummyParent parent(this->get_table(), val.get_ref());
12✔
1143
            Dictionary dict(parent, 0);
12✔
1144
            dict.to_json(out, output_mode, fn);
12✔
1145
        }
12✔
1146
        else if (val.is_type(type_List)) {
372✔
1147
            DummyParent parent(this->get_table(), val.get_ref());
12✔
1148
            Lst<Mixed> list(parent, 0);
12✔
1149
            list.to_json(out, output_mode, fn);
12✔
1150
        }
12✔
1151
        else {
360✔
1152
            val.to_json(out, output_mode);
360✔
1153
        }
360✔
1154
    }
528✔
1155

219✔
1156
    out << "}";
438✔
1157
    if (output_mode == output_mode_xjson_plus) {
438✔
1158
        out << "}";
156✔
1159
    }
156✔
1160
}
438✔
1161

1162
ref_type Dictionary::get_collection_ref(Index index, CollectionType type) const
1163
{
6,522✔
1164
    auto ndx = m_values->find_key(index.get_salt());
6,522✔
1165
    if (ndx != realm::not_found) {
6,522✔
1166
        auto val = m_values->get(ndx);
6,516✔
1167
        if (val.is_type(DataType(int(type)))) {
6,516✔
1168
            return val.get_ref();
6,516✔
1169
        }
6,516✔
UNCOV
1170
        throw realm::IllegalOperation(util::format("Not a %1", type));
×
1171
    }
×
1172
    throw StaleAccessor("This collection is no more");
6✔
1173
}
6✔
1174

1175
bool Dictionary::check_collection_ref(Index index, CollectionType type) const noexcept
1176
{
1,014✔
1177
    auto ndx = m_values->find_key(index.get_salt());
1,014✔
1178
    if (ndx != realm::not_found) {
1,014✔
1179
        return m_values->get(ndx).is_type(DataType(int(type)));
996✔
1180
    }
996✔
1181
    return false;
18✔
1182
}
18✔
1183

1184
void Dictionary::set_collection_ref(Index index, ref_type ref, CollectionType type)
1185
{
1,650✔
1186
    auto ndx = m_values->find_key(index.get_salt());
1,650✔
1187
    if (ndx == realm::not_found) {
1,650✔
UNCOV
1188
        throw StaleAccessor("Collection has been deleted");
×
1189
    }
×
1190
    m_values->set(ndx, Mixed(ref, type));
1,650✔
1191
}
1,650✔
1192

1193
/************************* DictionaryLinkValues *************************/
1194

1195
DictionaryLinkValues::DictionaryLinkValues(const Obj& obj, ColKey col_key)
1196
    : m_source(obj, col_key)
UNCOV
1197
{
×
1198
    REALM_ASSERT_EX(col_key.get_type() == col_type_Link, col_key.get_type());
×
1199
}
×
1200

1201
DictionaryLinkValues::DictionaryLinkValues(const Dictionary& source)
1202
    : m_source(source)
1203
{
3,114✔
1204
    REALM_ASSERT_EX(source.get_value_data_type() == type_Link, source.get_value_data_type());
3,114✔
1205
}
3,114✔
1206

1207
ObjKey DictionaryLinkValues::get_key(size_t ndx) const
1208
{
72✔
1209
    Mixed val = m_source.get_any(ndx);
72✔
1210
    if (val.is_type(type_Link, type_TypedLink)) {
72✔
1211
        return val.get<ObjKey>();
48✔
1212
    }
48✔
1213
    return {};
24✔
1214
}
24✔
1215

1216
Obj DictionaryLinkValues::get_object(size_t row_ndx) const
1217
{
2,400✔
1218
    Mixed val = m_source.get_any(row_ndx);
2,400✔
1219
    if (val.is_type(type_TypedLink)) {
2,400✔
1220
        return get_table()->get_parent_group()->get_object(val.get_link());
2,382✔
1221
    }
2,382✔
1222
    return {};
18✔
1223
}
18✔
1224

1225
} // 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