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

realm / realm-core / 2123

12 Mar 2024 11:18PM UTC coverage: 91.833% (+0.05%) from 91.787%
2123

push

Evergreen

web-flow
RCORE-1928 Use baasaas for baas integration tests in CI (#7423)

94732 of 174812 branches covered (54.19%)

201 of 288 new or added lines in 4 files covered. (69.79%)

62 existing lines in 11 files now uncovered.

242847 of 264443 relevant lines covered (91.83%)

5989046.65 hits per line

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

85.09
/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,289✔
35
    if (key.is_type(type_String)) {
122,289✔
36
        auto str = key.get_string();
122,289✔
37
        if (str.size()) {
122,289✔
38
            if (str[0] == '$')
122,229✔
39
                throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not start with '$'");
12✔
40
            if (memchr(str.data(), '.', str.size()))
122,217✔
41
                throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not contain '.'");
12✔
42
        }
122,217✔
43
    }
122,289✔
44
}
122,289✔
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,605✔
55
    if (!(col_key.is_dictionary() || col_key.get_type() == col_type_Mixed)) {
172,605✔
56
        throw InvalidArgument(ErrorCodes::TypeMismatch, "Property not a dictionary");
×
57
    }
×
58
}
172,605✔
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,903✔
64
    set_alloc(alloc);
27,903✔
65
    REALM_ASSERT(ref);
27,903✔
66
    m_dictionary_top.reset(new Array(alloc));
27,903✔
67
    m_dictionary_top->init_from_ref(ref);
27,903✔
68
    m_keys.reset(new BPlusTree<StringData>(alloc));
27,903✔
69
    m_values.reset(new BPlusTreeMixed(alloc));
27,903✔
70
    m_keys->set_parent(m_dictionary_top.get(), 0);
27,903✔
71
    m_values->set_parent(m_dictionary_top.get(), 1);
27,903✔
72
    m_keys->init_from_parent();
27,903✔
73
    m_values->init_from_parent();
27,903✔
74
}
27,903✔
75

76
Dictionary::~Dictionary() = default;
208,350✔
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
{
396,279✔
93
    if (!update())
396,279✔
94
        return 0;
41,808✔
95

176,922✔
96
    return m_values->size();
354,471✔
97
}
354,471✔
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,235✔
106
    return DataType(m_col_key.get_type());
14,235✔
107
}
14,235✔
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,574✔
163
            }
38,574✔
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,153✔
356
        return ascending ? values[i1] < values[i2] : values[i2] < values[i1];
35,511✔
357
    });
36,153✔
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
        int64_t key = generate_key(size());
1,392✔
445
        while (m_values->find_key(key) != realm::not_found) {
1,392✔
UNCOV
446
            key++;
×
UNCOV
447
        }
×
448
        m_values->set_key(it.index(), key);
1,392✔
449
    }
1,392✔
450
}
1,530✔
451

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

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

472
Mixed Dictionary::get(Mixed key) const
473
{
15,051✔
474
    if (auto opt_val = try_get(key)) {
15,051✔
475
        return *opt_val;
15,027✔
476
    }
15,027✔
477
    throw KeyNotFound("Dictionary::get");
24✔
478
}
24✔
479

480
util::Optional<Mixed> Dictionary::try_get(Mixed key) const
481
{
842,925✔
482
    if (update()) {
842,925✔
483
        auto ndx = do_find_key(key);
841,929✔
484
        if (ndx != realm::npos) {
841,929✔
485
            return do_get(ndx);
838,593✔
486
        }
838,593✔
487
    }
4,332✔
488
    return {};
4,332✔
489
}
4,332✔
490

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

499
Dictionary::Iterator Dictionary::end() const
500
{
84,951✔
501
    return Iterator(this, size());
84,951✔
502
}
84,951✔
503

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

55,011✔
533
    validate_key_value(key);
110,265✔
534
    ensure_created();
110,265✔
535

55,011✔
536
    ObjLink new_link;
110,265✔
537
    if (value.is_type(type_TypedLink)) {
110,265✔
538
        new_link = value.get<ObjLink>();
8,160✔
539
        if (!new_link.is_unresolved())
8,160✔
540
            my_table->get_parent_group()->validate(new_link);
7,920✔
541
    }
8,160✔
542
    else if (value.is_type(type_Link)) {
102,105✔
543
        auto target_table = my_table->get_opposite_table(m_col_key);
12,990✔
544
        auto key = value.get<ObjKey>();
12,990✔
545
        if (!key.is_unresolved() && !target_table->is_valid(key)) {
12,990✔
546
            throw InvalidArgument(ErrorCodes::KeyNotFound, "Target object not found");
6✔
547
        }
6✔
548
        new_link = ObjLink(target_table->get_key(), key);
12,984✔
549
        value = Mixed(new_link);
12,984✔
550
    }
12,984✔
551

55,011✔
552
    if (!m_dictionary_top) {
110,262✔
553
        throw StaleAccessor("Stale dictionary");
×
554
    }
×
555

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

55,008✔
576
    if (Replication* repl = get_replication()) {
110,259✔
577
        if (old_entry) {
96,615✔
578
            repl->dictionary_set(*this, ndx, key, value);
8,592✔
579
        }
8,592✔
580
        else {
88,023✔
581
            repl->dictionary_insert(*this, ndx, key, value);
88,023✔
582
        }
88,023✔
583
    }
96,615✔
584

55,008✔
585
    bump_content_version();
110,259✔
586

55,008✔
587
    ObjLink old_link;
110,259✔
588
    if (old_entry) {
110,259✔
589
        Mixed old_value = m_values->get(ndx);
9,792✔
590
        if (old_value.is_type(type_TypedLink)) {
9,792✔
591
            old_link = old_value.get<ObjLink>();
768✔
592
        }
768✔
593
        m_values->set(ndx, value);
9,792✔
594
    }
9,792✔
595

55,008✔
596
    if (new_link != old_link) {
110,259✔
597
        CascadeState cascade_state(CascadeState::Mode::Strong);
21,192✔
598
        bool recurse = Base::replace_backlink(m_col_key, old_link, new_link, cascade_state);
21,192✔
599
        if (recurse)
21,192✔
600
            _impl::TableFriend::remove_recursive(*my_table, cascade_state); // Throws
294✔
601
    }
21,192✔
602

55,008✔
603
    return {Iterator(this, ndx), !old_entry};
110,259✔
604
}
110,259✔
605

606
const Mixed Dictionary::operator[](Mixed key)
607
{
812,802✔
608
    auto ret = try_get(key);
812,802✔
609
    if (!ret) {
812,802✔
610
        ret = Mixed{};
6✔
611
        insert(key, Mixed{});
6✔
612
    }
6✔
613

406,401✔
614
    return *ret;
812,802✔
615
}
812,802✔
616

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

627
bool Dictionary::contains(Mixed key) const noexcept
628
{
3,072✔
629
    return find_any_key(key) != realm::npos;
3,072✔
630
}
3,072✔
631

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

641
void Dictionary::add_index(Path& path, const Index& index) const
642
{
1,008✔
643
    auto ndx = m_values->find_key(index.get_salt());
1,008✔
644
    auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
1,008✔
645
    path.emplace_back(keys->get(ndx));
1,008✔
646
}
1,008✔
647

648
size_t Dictionary::find_index(const Index& index) const
649
{
306✔
650
    update();
306✔
651
    return m_values->find_key(index.get_salt());
306✔
652
}
306✔
653

654
UpdateStatus Dictionary::update_if_needed_with_status() const
655
{
1,396,719✔
656
    auto status = Base::get_update_status();
1,396,719✔
657
    switch (status) {
1,396,719✔
658
        case UpdateStatus::Detached: {
6✔
659
            m_dictionary_top.reset();
6✔
660
            return UpdateStatus::Detached;
6✔
661
        }
×
662
        case UpdateStatus::NoChange: {
1,248,225✔
663
            if (m_dictionary_top && m_dictionary_top->is_attached()) {
1,248,225✔
664
                return UpdateStatus::NoChange;
1,212,435✔
665
            }
1,212,435✔
666
            // The tree has not been initialized yet for this accessor, so
17,667✔
667
            // perform lazy initialization by treating it as an update.
17,667✔
668
            [[fallthrough]];
35,790✔
669
        }
35,790✔
670
        case UpdateStatus::Updated: {
184,278✔
671
            // Try to initialize. If the dictionary is not initialized
91,533✔
672
            // the function will return false;
91,533✔
673
            bool attached = init_from_parent(false);
184,278✔
674
            Base::update_content_version();
184,278✔
675
            CollectionParent::m_parent_version++;
184,278✔
676
            return attached ? UpdateStatus::Updated : UpdateStatus::Detached;
153,345✔
677
        }
×
678
    }
×
679
    REALM_UNREACHABLE();
680
}
×
681

682
void Dictionary::ensure_created()
683
{
111,777✔
684
    if (Base::should_update() || !(m_dictionary_top && m_dictionary_top->is_attached())) {
111,777✔
685
        // When allow_create is true, init_from_parent will always succeed
27,069✔
686
        // In case of errors, an exception is thrown.
27,069✔
687
        constexpr bool allow_create = true;
54,201✔
688
        init_from_parent(allow_create); // Throws
54,201✔
689
        CollectionParent::m_parent_version++;
54,201✔
690
        Base::update_content_version();
54,201✔
691
    }
54,201✔
692
}
111,777✔
693

694
bool Dictionary::try_erase(Mixed key)
695
{
12,030✔
696
    validate_key_value(key);
12,030✔
697
    if (!update())
12,030✔
698
        return false;
×
699

6,000✔
700
    auto ndx = do_find_key(key);
12,030✔
701
    if (ndx == realm::npos) {
12,030✔
702
        return false;
1,230✔
703
    }
1,230✔
704

5,385✔
705
    do_erase(ndx, key);
10,800✔
706

5,385✔
707
    return true;
10,800✔
708
}
10,800✔
709

710
void Dictionary::erase(Mixed key)
711
{
10,920✔
712
    if (!try_erase(key)) {
10,920✔
713
        throw KeyNotFound(util::format("Cannot remove key %1 from dictionary: key not found", key));
618✔
714
    }
618✔
715
}
10,920✔
716

717
auto Dictionary::erase(Iterator it) -> Iterator
718
{
2,616✔
719
    auto pos = it.m_ndx;
2,616✔
720
    CollectionBase::validate_index("erase()", pos, size());
2,616✔
721

1,308✔
722
    do_erase(pos, do_get_key(pos));
2,616✔
723
    if (pos < size())
2,616✔
724
        pos++;
480✔
725
    return {this, pos};
2,616✔
726
}
2,616✔
727

728
void Dictionary::nullify(size_t ndx)
729
{
726✔
730
    REALM_ASSERT(m_dictionary_top);
726✔
731
    REALM_ASSERT(ndx != realm::npos);
726✔
732

363✔
733
    if (Replication* repl = get_replication()) {
726✔
734
        auto key = do_get_key(ndx);
708✔
735
        repl->dictionary_set(*this, ndx, key, Mixed());
708✔
736
    }
708✔
737

363✔
738
    m_values->set(ndx, Mixed());
726✔
739
}
726✔
740

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

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

802
bool Dictionary::remove_backlinks(CascadeState& state) const
803
{
3,054✔
804
    size_t sz = size();
3,054✔
805
    bool recurse = false;
3,054✔
806
    for (size_t ndx = 0; ndx < sz; ndx++) {
13,968✔
807
        if (clear_backlink(ndx, state)) {
10,914✔
808
            recurse = true;
369✔
809
        }
369✔
810
    }
10,914✔
811
    return recurse;
3,054✔
812
}
3,054✔
813

814
size_t Dictionary::find_first(Mixed value) const
815
{
46,596✔
816
    return update() ? m_values->find_first(value) : realm::not_found;
46,596✔
817
}
46,596✔
818

819
void Dictionary::clear()
820
{
2,724✔
821
    if (size() > 0) {
2,724✔
822
        if (Replication* repl = get_replication()) {
2,490✔
823
            repl->dictionary_clear(*this);
2,478✔
824
        }
2,478✔
825
        CascadeState cascade_state(CascadeState::Mode::Strong);
2,490✔
826
        bool recurse = remove_backlinks(cascade_state);
2,490✔
827

1,245✔
828
        // Just destroy the whole cluster
1,245✔
829
        m_dictionary_top->destroy_deep();
2,490✔
830
        m_dictionary_top.reset();
2,490✔
831

1,245✔
832
        update_child_ref(0, 0);
2,490✔
833

1,245✔
834
        if (recurse)
2,490✔
835
            _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
6✔
836
    }
2,490✔
837
}
2,724✔
838

839
bool Dictionary::init_from_parent(bool allow_create) const
840
{
238,479✔
841
    try {
238,479✔
842
        auto ref = Base::get_collection_ref();
238,479✔
843
        if ((ref || allow_create) && !m_dictionary_top) {
238,479✔
844
            Allocator& alloc = get_alloc();
145,812✔
845
            m_dictionary_top.reset(new Array(alloc));
145,812✔
846
            m_dictionary_top->set_parent(const_cast<Dictionary*>(this), 0);
145,812✔
847
            switch (m_key_type) {
145,812✔
848
                case type_String: {
145,812✔
849
                    m_keys.reset(new BPlusTree<StringData>(alloc));
145,812✔
850
                    break;
145,812✔
851
                }
×
852
                case type_Int: {
✔
853
                    m_keys.reset(new BPlusTree<Int>(alloc));
×
854
                    break;
×
855
                }
×
856
                default:
✔
857
                    break;
×
858
            }
145,812✔
859
            m_keys->set_parent(m_dictionary_top.get(), 0);
145,812✔
860
            m_values.reset(new BPlusTreeMixed(alloc));
145,812✔
861
            m_values->set_parent(m_dictionary_top.get(), 1);
145,812✔
862
        }
145,812✔
863

118,602✔
864
        if (ref) {
238,479✔
865
            m_dictionary_top->init_from_ref(ref);
146,895✔
866
            m_keys->init_from_parent();
146,895✔
867
            m_values->init_from_parent();
146,895✔
868
        }
146,895✔
869
        else {
91,584✔
870
            // dictionary detached
45,330✔
871
            if (!allow_create) {
91,584✔
872
                m_dictionary_top.reset();
61,008✔
873
                return false;
61,008✔
874
            }
61,008✔
875

15,246✔
876
            // Create dictionary
15,246✔
877
            m_dictionary_top->create(Array::type_HasRefs, false, 2, 0);
30,576✔
878
            m_values->create();
30,576✔
879
            m_keys->create();
30,576✔
880
            m_dictionary_top->update_parent();
30,576✔
881
        }
30,576✔
882

118,602✔
883
        return true;
207,555✔
884
    }
30✔
885
    catch (...) {
30✔
886
        m_dictionary_top.reset();
30✔
887
        throw;
30✔
888
    }
30✔
889
}
238,479✔
890

891
size_t Dictionary::do_find_key(Mixed key) const noexcept
892
{
884,937✔
893
    auto [ndx, actual_key] = find_impl(key);
884,937✔
894
    if (actual_key == key) {
884,937✔
895
        return ndx;
871,419✔
896
    }
871,419✔
897
    return realm::npos;
13,518✔
898
}
13,518✔
899

900
std::pair<size_t, Mixed> Dictionary::find_impl(Mixed key) const noexcept
901
{
995,196✔
902
    auto sz = m_keys->size();
995,196✔
903
    Mixed actual;
995,196✔
904
    if (sz && key.is_type(m_key_type)) {
995,196✔
905
        switch (m_key_type) {
962,715✔
906
            case type_String: {
962,715✔
907
                auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
962,715✔
908
                StringData val = key.get<StringData>();
962,715✔
909
                IteratorAdapter help(keys);
962,715✔
910
                auto it = std::lower_bound(help.begin(), help.end(), val);
962,715✔
911
                if (it.index() < sz) {
962,715✔
912
                    actual = *it;
911,205✔
913
                }
911,205✔
914
                return {it.index(), actual};
962,715✔
915
                break;
×
916
            }
×
917
            case type_Int: {
✔
918
                auto keys = static_cast<BPlusTree<Int>*>(m_keys.get());
×
919
                Int val = key.get<Int>();
×
920
                IteratorAdapter help(keys);
×
921
                auto it = std::lower_bound(help.begin(), help.end(), val);
×
922
                if (it.index() < sz) {
×
923
                    actual = *it;
×
924
                }
×
925
                return {it.index(), actual};
×
926
                break;
×
927
            }
×
928
            default:
✔
929
                break;
×
930
        }
32,481✔
931
    }
32,481✔
932

16,200✔
933
    return {sz, actual};
32,481✔
934
}
32,481✔
935

936
Mixed Dictionary::do_get(size_t ndx) const
937
{
949,122✔
938
    Mixed val = m_values->get(ndx);
949,122✔
939

474,393✔
940
    // Filter out potential unresolved links
474,393✔
941
    if (val.is_type(type_TypedLink) && val.get<ObjKey>().is_unresolved()) {
949,122✔
942
        return {};
1,104✔
943
    }
1,104✔
944
    return val;
948,018✔
945
}
948,018✔
946

947
void Dictionary::do_erase(size_t ndx, Mixed key)
948
{
13,404✔
949
    CascadeState cascade_state(CascadeState::Mode::Strong);
13,404✔
950
    bool recurse = clear_backlink(ndx, cascade_state);
13,404✔
951

6,687✔
952
    if (recurse)
13,404✔
953
        _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
102✔
954

6,687✔
955
    if (Replication* repl = get_replication()) {
13,404✔
956
        repl->dictionary_erase(*this, ndx, key);
12,150✔
957
    }
12,150✔
958

6,687✔
959
    m_keys->erase(ndx);
13,404✔
960
    m_values->erase(ndx);
13,404✔
961
    bump_content_version();
13,404✔
962
}
13,404✔
963

964
Mixed Dictionary::do_get_key(size_t ndx) const
965
{
152,328✔
966
    switch (m_key_type) {
152,328✔
967
        case type_String: {
152,328✔
968
            return static_cast<BPlusTree<StringData>*>(m_keys.get())->get(ndx);
152,328✔
969
        }
×
970
        case type_Int: {
✔
971
            return static_cast<BPlusTree<Int>*>(m_keys.get())->get(ndx);
×
972
        }
×
973
        default:
✔
974
            break;
×
975
    }
×
976

977
    return {};
×
978
}
×
979

980
std::pair<Mixed, Mixed> Dictionary::do_get_pair(size_t ndx) const
981
{
93,660✔
982
    return {do_get_key(ndx), do_get(ndx)};
93,660✔
983
}
93,660✔
984

985
bool Dictionary::clear_backlink(size_t ndx, CascadeState& state) const
986
{
24,318✔
987
    auto value = m_values->get(ndx);
24,318✔
988
    if (value.is_type(type_TypedLink)) {
24,318✔
989
        return Base::remove_backlink(m_col_key, value.get_link(), state);
7,836✔
990
    }
7,836✔
991
    if (value.is_type(type_Dictionary)) {
16,482✔
992
        auto key = do_get_key(ndx);
30✔
993
        return get_dictionary(key.get_string())->remove_backlinks(state);
30✔
994
    }
30✔
995
    if (value.is_type(type_List)) {
16,452✔
996
        auto key = do_get_key(ndx);
60✔
997
        return get_list(key.get_string())->remove_backlinks(state);
60✔
998
    }
60✔
999
    return false;
16,392✔
1000
}
16,392✔
1001

1002
void Dictionary::swap_content(Array& fields1, Array& fields2, size_t index1, size_t index2)
1003
{
×
1004
    std::string buf1, buf2;
×
1005

1006
    // Swap keys
1007
    REALM_ASSERT(m_key_type == type_String);
×
1008
    ArrayString keys(get_alloc());
×
1009
    keys.set_parent(&fields1, 1);
×
1010
    keys.init_from_parent();
×
1011
    buf1 = keys.get(index1);
×
1012

1013
    keys.set_parent(&fields2, 1);
×
1014
    keys.init_from_parent();
×
1015
    buf2 = keys.get(index2);
×
1016
    keys.set(index2, buf1);
×
1017

1018
    keys.set_parent(&fields1, 1);
×
1019
    keys.init_from_parent();
×
1020
    keys.set(index1, buf2);
×
1021

1022
    // Swap values
1023
    ArrayMixed values(get_alloc());
×
1024
    values.set_parent(&fields1, 2);
×
1025
    values.init_from_parent();
×
1026
    Mixed val1 = values.get(index1);
×
1027
    val1.use_buffer(buf1);
×
1028

1029
    values.set_parent(&fields2, 2);
×
1030
    values.init_from_parent();
×
1031
    Mixed val2 = values.get(index2);
×
1032
    val2.use_buffer(buf2);
×
1033
    values.set(index2, val1);
×
1034

1035
    values.set_parent(&fields1, 2);
×
1036
    values.init_from_parent();
×
1037
    values.set(index1, val2);
×
1038
}
×
1039

1040
Mixed Dictionary::find_value(Mixed value) const noexcept
1041
{
×
1042
    size_t ndx = update() ? m_values->find_first(value) : realm::npos;
×
1043
    return (ndx == realm::npos) ? Mixed{} : do_get_key(ndx);
×
1044
}
×
1045

1046
StableIndex Dictionary::build_index(Mixed key) const
1047
{
3,066✔
1048
    auto it = find(key);
3,066✔
1049
    int64_t index = (it != end()) ? m_values->get_key(it.index()) : 0;
3,066✔
1050
    return {index};
3,066✔
1051
}
3,066✔
1052

1053

1054
void Dictionary::verify() const
1055
{
12,171✔
1056
    m_keys->verify();
12,171✔
1057
    m_values->verify();
12,171✔
1058
    REALM_ASSERT(m_keys->size() == m_values->size());
12,171✔
1059
}
12,171✔
1060

1061
void Dictionary::get_key_type()
1062
{
172,605✔
1063
    m_key_type = get_table()->get_dictionary_key_type(m_col_key);
172,605✔
1064
    if (!(m_key_type == type_String || m_key_type == type_Int))
172,605!
1065
        throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary keys can only be strings or integers");
×
1066
}
172,605✔
1067

1068
void Dictionary::migrate()
1069
{
6✔
1070
    // Dummy implementation of legacy dictionary cluster tree
3✔
1071
    class DictionaryClusterTree : public ClusterTree {
6✔
1072
    public:
6✔
1073
        DictionaryClusterTree(ArrayParent* owner, Allocator& alloc, size_t ndx)
6✔
1074
            : ClusterTree(nullptr, alloc, ndx)
6✔
1075
            , m_owner(owner)
6✔
1076
        {
6✔
1077
        }
6✔
1078

3✔
1079
        std::unique_ptr<ClusterNode> get_root_from_parent() final
6✔
1080
        {
6✔
1081
            return create_root_from_parent(m_owner, m_top_position_for_cluster_tree);
6✔
1082
        }
6✔
1083

3✔
1084
    private:
6✔
1085
        ArrayParent* m_owner;
6✔
1086
    };
6✔
1087

3✔
1088
    if (auto dict_ref = Base::get_collection_ref()) {
6✔
1089
        Allocator& alloc = get_alloc();
6✔
1090
        DictionaryClusterTree cluster_tree(this, alloc, 0);
6✔
1091
        if (cluster_tree.init_from_parent()) {
6✔
1092
            // Create an empty dictionary in the old ones place
3✔
1093
            Base::set_collection_ref(0);
6✔
1094
            ensure_created();
6✔
1095

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

1126
template <>
1127
void CollectionBaseImpl<DictionaryBase>::to_json(std::ostream&, JSONOutputMode,
1128
                                                 util::FunctionRef<void(const Mixed&)>) const
1129
{
×
1130
}
×
1131

1132
void Dictionary::to_json(std::ostream& out, JSONOutputMode output_mode,
1133
                         util::FunctionRef<void(const Mixed&)> fn) const
1134
{
438✔
1135
    if (output_mode == output_mode_xjson_plus) {
438✔
1136
        out << "{ \"$dictionary\": ";
156✔
1137
    }
156✔
1138
    out << "{";
438✔
1139

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

219✔
1164
    out << "}";
438✔
1165
    if (output_mode == output_mode_xjson_plus) {
438✔
1166
        out << "}";
156✔
1167
    }
156✔
1168
}
438✔
1169

1170
ref_type Dictionary::get_collection_ref(Index index, CollectionType type) const
1171
{
5,502✔
1172
    auto ndx = m_values->find_key(index.get_salt());
5,502✔
1173
    if (ndx != realm::not_found) {
5,502✔
1174
        auto val = m_values->get(ndx);
5,496✔
1175
        if (val.is_type(DataType(int(type)))) {
5,496✔
1176
            return val.get_ref();
5,496✔
1177
        }
5,496✔
1178
        throw realm::IllegalOperation(util::format("Not a %1", type));
×
1179
    }
×
1180
    throw StaleAccessor("This collection is no more");
6✔
1181
    return 0;
3✔
1182
}
6✔
1183

1184
bool Dictionary::check_collection_ref(Index index, CollectionType type) const noexcept
1185
{
1,014✔
1186
    auto ndx = m_values->find_key(index.get_salt());
1,014✔
1187
    if (ndx != realm::not_found) {
1,014✔
1188
        return m_values->get(ndx).is_type(DataType(int(type)));
996✔
1189
    }
996✔
1190
    return false;
18✔
1191
}
18✔
1192

1193
void Dictionary::set_collection_ref(Index index, ref_type ref, CollectionType type)
1194
{
1,650✔
1195
    auto ndx = m_values->find_key(index.get_salt());
1,650✔
1196
    if (ndx == realm::not_found) {
1,650✔
1197
        throw StaleAccessor("Collection has been deleted");
×
1198
    }
×
1199
    m_values->set(ndx, Mixed(ref, type));
1,650✔
1200
}
1,650✔
1201

1202
bool Dictionary::update_if_needed() const
1203
{
2,244✔
1204
    auto status = update_if_needed_with_status();
2,244✔
1205
    if (status == UpdateStatus::Detached) {
2,244✔
1206
        throw StaleAccessor("CollectionList no longer exists");
×
1207
    }
×
1208
    return status == UpdateStatus::Updated;
2,244✔
1209
}
2,244✔
1210

1211
/************************* DictionaryLinkValues *************************/
1212

1213
DictionaryLinkValues::DictionaryLinkValues(const Obj& obj, ColKey col_key)
1214
    : m_source(obj, col_key)
1215
{
×
1216
    REALM_ASSERT_EX(col_key.get_type() == col_type_Link, col_key.get_type());
×
1217
}
×
1218

1219
DictionaryLinkValues::DictionaryLinkValues(const Dictionary& source)
1220
    : m_source(source)
1221
{
3,114✔
1222
    REALM_ASSERT_EX(source.get_value_data_type() == type_Link, source.get_value_data_type());
3,114✔
1223
}
3,114✔
1224

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

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

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