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

realm / realm-core / github_pull_request_281750

30 Oct 2023 03:37PM UTC coverage: 90.528% (-1.0%) from 91.571%
github_pull_request_281750

Pull #6073

Evergreen

jedelbo
Log free space and history sizes when opening file
Pull Request #6073: Merge next-major

95488 of 175952 branches covered (0.0%)

8973 of 12277 new or added lines in 149 files covered. (73.09%)

622 existing lines in 51 files now uncovered.

233503 of 257934 relevant lines covered (90.53%)

6533720.56 hits per line

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

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

76
Dictionary::~Dictionary() = default;
186,474✔
77

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

2,853✔
82
    if (this != &other) {
5,706✔
83
        // Back to scratch
2,853✔
84
        m_dictionary_top.reset();
5,706✔
85
        reset_content_version();
5,706✔
86
    }
5,706✔
87

2,853✔
88
    return *this;
5,706✔
89
}
5,706✔
90

91
size_t Dictionary::size() const
92
{
365,034✔
93
    if (!update())
365,034✔
94
        return 0;
40,896✔
95

161,874✔
96
    return m_values->size();
324,138✔
97
}
324,138✔
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,226✔
106
    return DataType(m_col_key.get_type());
14,226✔
107
}
14,226✔
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
{
14,205✔
116
    // Note: `size()` calls `update_if_needed()`.
7,101✔
117
    auto current_size = size();
14,205✔
118
    CollectionBase::validate_index("get_any()", ndx, current_size);
14,205✔
119
    return do_get(ndx);
14,205✔
120
}
14,205✔
121

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

130
Mixed Dictionary::get_key(size_t ndx) const
131
{
45,798✔
132
    // Note: `size()` calls `update_if_needed()`.
22,881✔
133
    CollectionBase::validate_index("get_key()", ndx, size());
45,798✔
134
    return do_get_key(ndx);
45,798✔
135
}
45,798✔
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
{
35,712✔
144
    if (update()) {
35,712✔
145
        return do_find_key(key);
27,876✔
146
    }
27,876✔
147

3,918✔
148
    return realm::npos;
7,836✔
149
}
7,836✔
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,589✔
163
            }
38,589✔
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) {
35,835✔
356
        return ascending ? values[i1] < values[i2] : values[i2] < values[i1];
35,193✔
357
    });
35,835✔
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: {
✔
NEW
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,242✔
425
    Table& t = *get_target_table();
4,242✔
426
    auto o = t.is_embedded() ? t.create_linked_object() : t.create_object();
4,242✔
427
    insert(key, o.get_key());
4,242✔
428
    return o;
4,242✔
429
}
4,242✔
430

431
void Dictionary::insert_collection(const PathElement& path_elem, CollectionType dict_or_list)
432
{
330✔
433
    check_level();
330✔
434
    ensure_created();
330✔
435
    m_values->ensure_keys();
330✔
436
    auto [it, inserted] = insert(path_elem.get_key(), Mixed(0, dict_or_list));
330✔
437
    int64_t key = generate_key(size());
330✔
438
    while (m_values->find_key(key) != realm::not_found) {
333✔
439
        key++;
3✔
440
    }
3✔
441
    m_values->set_key(it.index(), key);
330✔
442
}
330✔
443

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

454
SetMixedPtr Dictionary::get_set(const PathElement& path_elem) const
455
{
36✔
456
    update();
36✔
457
    auto weak = const_cast<Dictionary*>(this)->weak_from_this();
36✔
458
    auto shared = weak.expired() ? std::make_shared<Dictionary>(*this) : weak.lock();
36✔
459
    auto ret = std::make_shared<Set<Mixed>>(m_obj_mem, m_col_key);
36✔
460
    ret->set_owner(shared, build_index(path_elem.get_key()));
36✔
461
    return ret;
36✔
462
}
36✔
463

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

474
Mixed Dictionary::get(Mixed key) const
475
{
13,245✔
476
    if (auto opt_val = try_get(key)) {
13,245✔
477
        return *opt_val;
13,221✔
478
    }
13,221✔
479
    throw KeyNotFound("Dictionary::get");
24✔
480
}
24✔
481

482
util::Optional<Mixed> Dictionary::try_get(Mixed key) const
483
{
839,241✔
484
    if (update()) {
839,241✔
485
        auto ndx = do_find_key(key);
838,269✔
486
        if (ndx != realm::npos) {
838,269✔
487
            return do_get(ndx);
836,097✔
488
        }
836,097✔
489
    }
3,144✔
490
    return {};
3,144✔
491
}
3,144✔
492

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

501
Dictionary::Iterator Dictionary::end() const
502
{
80,217✔
503
    return Iterator(this, size());
80,217✔
504
}
80,217✔
505

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

51,771✔
535
    validate_key_value(key);
103,740✔
536
    ensure_created();
103,740✔
537

51,771✔
538
    ObjLink new_link;
103,740✔
539
    if (value.is_type(type_TypedLink)) {
103,740✔
540
        new_link = value.get<ObjLink>();
7,212✔
541
        if (!new_link.is_unresolved())
7,212✔
542
            my_table->get_parent_group()->validate(new_link);
7,116✔
543
    }
7,212✔
544
    else if (value.is_type(type_Link)) {
96,528✔
545
        auto target_table = my_table->get_opposite_table(m_col_key);
12,156✔
546
        auto key = value.get<ObjKey>();
12,156✔
547
        if (!key.is_unresolved() && !target_table->is_valid(key)) {
12,156✔
548
            throw InvalidArgument(ErrorCodes::KeyNotFound, "Target object not found");
6✔
549
        }
6✔
550
        new_link = ObjLink(target_table->get_key(), key);
12,150✔
551
        value = Mixed(new_link);
12,150✔
552
    }
12,150✔
553

51,771✔
554
    if (!m_dictionary_top) {
103,737✔
555
        throw StaleAccessor("Stale dictionary");
×
556
    }
×
557

51,768✔
558
    bool old_entry = false;
103,734✔
559
    auto [ndx, actual_key] = find_impl(key);
103,734✔
560
    if (actual_key != key) {
103,734✔
561
        // key does not already exist
47,148✔
562
        switch (m_key_type) {
94,494✔
563
            case type_String:
94,494✔
564
                static_cast<BPlusTree<StringData>*>(m_keys.get())->insert(ndx, key.get_string());
94,494✔
565
                break;
94,494✔
566
            case type_Int:
✔
567
                static_cast<BPlusTree<Int>*>(m_keys.get())->insert(ndx, key.get_int());
×
568
                break;
×
569
            default:
✔
570
                break;
×
571
        }
94,494✔
572
        m_values->insert(ndx, value);
94,494✔
573
    }
94,494✔
574
    else {
9,240✔
575
        old_entry = true;
9,240✔
576
    }
9,240✔
577

51,768✔
578
    if (Replication* repl = get_replication()) {
103,734✔
579
        if (old_entry) {
91,368✔
580
            repl->dictionary_set(*this, ndx, key, value);
7,992✔
581
        }
7,992✔
582
        else {
83,376✔
583
            repl->dictionary_insert(*this, ndx, key, value);
83,376✔
584
        }
83,376✔
585
    }
91,368✔
586

51,768✔
587
    bump_content_version();
103,734✔
588

51,768✔
589
    ObjLink old_link;
103,734✔
590
    if (old_entry) {
103,734✔
591
        Mixed old_value = m_values->get(ndx);
9,192✔
592
        if (old_value.is_type(type_TypedLink)) {
9,192✔
593
            old_link = old_value.get<ObjLink>();
594✔
594
        }
594✔
595
        m_values->set(ndx, value);
9,192✔
596
    }
9,192✔
597

51,768✔
598
    if (new_link != old_link) {
103,734✔
599
        CascadeState cascade_state(CascadeState::Mode::Strong);
19,398✔
600
        bool recurse = Base::replace_backlink(m_col_key, old_link, new_link, cascade_state);
19,398✔
601
        if (recurse)
19,398✔
602
            _impl::TableFriend::remove_recursive(*my_table, cascade_state); // Throws
288✔
603
    }
19,398✔
604

51,768✔
605
    return {Iterator(this, ndx), !old_entry};
103,734✔
606
}
103,734✔
607

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

406,398✔
616
    return *ret;
812,796✔
617
}
812,796✔
618

619
Obj Dictionary::get_object(StringData key)
620
{
12,069✔
621
    if (auto val = try_get(key)) {
12,069✔
622
        if ((*val).is_type(type_TypedLink)) {
8,967✔
623
            return get_table()->get_parent_group()->get_object((*val).get_link());
8,847✔
624
        }
8,847✔
625
    }
3,222✔
626
    return {};
3,222✔
627
}
3,222✔
628

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

634
Dictionary::Iterator Dictionary::find(Mixed key) const noexcept
635
{
31,548✔
636
    auto ndx = find_any_key(key);
31,548✔
637
    if (ndx != realm::npos) {
31,548✔
638
        return Iterator(this, ndx);
16,590✔
639
    }
16,590✔
640
    return end();
14,958✔
641
}
14,958✔
642

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

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

656
UpdateStatus Dictionary::update_if_needed_with_status() const
657
{
1,333,662✔
658
    auto status = Base::get_update_status();
1,333,662✔
659
    switch (status) {
1,333,662✔
660
        case UpdateStatus::Detached: {
6✔
661
            m_dictionary_top.reset();
6✔
662
            return UpdateStatus::Detached;
6✔
663
        }
×
664
        case UpdateStatus::NoChange: {
1,202,268✔
665
            if (m_dictionary_top && m_dictionary_top->is_attached()) {
1,202,268✔
666
                return UpdateStatus::NoChange;
1,167,381✔
667
            }
1,167,381✔
668
            // The tree has not been initialized yet for this accessor, so
17,259✔
669
            // perform lazy initialization by treating it as an update.
17,259✔
670
            [[fallthrough]];
34,887✔
671
        }
34,887✔
672
        case UpdateStatus::Updated: {
166,275✔
673
            // Try to initialize. If the dictionary is not initialized
82,629✔
674
            // the function will return false;
82,629✔
675
            bool attached = init_from_parent(false);
166,275✔
676
            Base::update_content_version();
166,275✔
677
            return attached ? UpdateStatus::Updated : UpdateStatus::Detached;
136,014✔
678
        }
×
679
    }
×
680
    REALM_UNREACHABLE();
×
681
}
×
682

683
void Dictionary::ensure_created()
684
{
104,052✔
685
    if (Base::should_update() || !(m_dictionary_top && m_dictionary_top->is_attached())) {
104,052✔
686
        // When allow_create is true, init_from_parent will always succeed
24,117✔
687
        // In case of errors, an exception is thrown.
24,117✔
688
        constexpr bool allow_create = true;
48,252✔
689
        init_from_parent(allow_create); // Throws
48,252✔
690
        Base::update_content_version();
48,252✔
691
    }
48,252✔
692
}
104,052✔
693

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

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

5,454✔
705
    do_erase(ndx, key);
10,980✔
706

5,454✔
707
    return true;
10,980✔
708
}
10,980✔
709

710

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

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

1,191✔
723
    do_erase(pos, do_get_key(pos));
2,382✔
724
    if (pos < size())
2,382✔
725
        pos++;
402✔
726
    return {this, pos};
2,382✔
727
}
2,382✔
728

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

147✔
734
    if (Replication* repl = get_replication()) {
294✔
735
        auto key = do_get_key(ndx);
276✔
736
        repl->dictionary_set(*this, ndx, key, Mixed());
276✔
737
    }
276✔
738

147✔
739
    m_values->set(ndx, Mixed());
294✔
740
}
294✔
741

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

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

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

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

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

1,176✔
829
        // Just destroy the whole cluster
1,176✔
830
        m_dictionary_top->destroy_deep();
2,352✔
831
        m_dictionary_top.reset();
2,352✔
832

1,176✔
833
        update_child_ref(0, 0);
2,352✔
834

1,176✔
835
        if (recurse)
2,352✔
836
            _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
6✔
837
    }
2,352✔
838
}
2,586✔
839

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

106,746✔
865
        if (ref) {
214,527✔
866
            m_dictionary_top->init_from_ref(ref);
127,731✔
867
            m_keys->init_from_parent();
127,731✔
868
            m_values->init_from_parent();
127,731✔
869
        }
127,731✔
870
        else {
86,796✔
871
            // dictionary detached
42,936✔
872
            if (!allow_create) {
86,796✔
873
                m_dictionary_top.reset();
59,664✔
874
                return false;
59,664✔
875
            }
59,664✔
876

13,524✔
877
            // Create dictionary
13,524✔
878
            m_dictionary_top->create(Array::type_HasRefs, false, 2, 0);
27,132✔
879
            m_values->create();
27,132✔
880
            m_keys->create();
27,132✔
881
            m_dictionary_top->update_parent();
27,132✔
882
        }
27,132✔
883

106,746✔
884
        return true;
184,275✔
885
    }
36✔
886
    catch (...) {
36✔
887
        m_dictionary_top.reset();
36✔
888
        throw;
36✔
889
    }
36✔
890
}
214,527✔
891

892
size_t Dictionary::do_find_key(Mixed key) const noexcept
893
{
878,343✔
894
    auto [ndx, actual_key] = find_impl(key);
878,343✔
895
    if (actual_key == key) {
878,343✔
896
        return ndx;
866,181✔
897
    }
866,181✔
898
    return realm::npos;
12,162✔
899
}
12,162✔
900

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

14,082✔
934
    return {sz, actual};
28,251✔
935
}
28,251✔
936

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

470,067✔
941
    // Filter out potential unresolved links
470,067✔
942
    if (val.is_type(type_TypedLink) && val.get<ObjKey>().is_unresolved()) {
940,512✔
943
        return {};
690✔
944
    }
690✔
945
    return val;
939,822✔
946
}
939,822✔
947

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

6,639✔
953
    if (recurse)
13,350✔
954
        _impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
102✔
955

6,639✔
956
    if (Replication* repl = get_replication()) {
13,350✔
957
        repl->dictionary_erase(*this, ndx, key);
12,126✔
958
    }
12,126✔
959

6,639✔
960
    m_keys->erase(ndx);
13,350✔
961
    m_values->erase(ndx);
13,350✔
962
    bump_content_version();
13,350✔
963
}
13,350✔
964

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

978
    return {};
×
979
}
×
980

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

986
bool Dictionary::clear_backlink(size_t ndx, CascadeState& state) const
987
{
23,898✔
988
    auto value = m_values->get(ndx);
23,898✔
989
    if (value.is_type(type_TypedLink)) {
23,898✔
990
        return Base::remove_backlink(m_col_key, value.get_link(), state);
7,674✔
991
    }
7,674✔
992
    if (value.is_type(type_Dictionary)) {
16,224✔
993
        auto key = do_get_key(ndx);
12✔
994
        return get_dictionary(key.get_string())->remove_backlinks(state);
12✔
995
    }
12✔
996
    if (value.is_type(type_List)) {
16,212✔
997
        auto key = do_get_key(ndx);
24✔
998
        return get_list(key.get_string())->remove_backlinks(state);
24✔
999
    }
24✔
1000
    return false;
16,188✔
1001
}
16,188✔
1002

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

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

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

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

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

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

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

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

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

1054

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

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

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

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

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

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

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

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

1133
void Dictionary::to_json(std::ostream& out, size_t link_depth, JSONOutputMode output_mode,
1134
                         util::FunctionRef<void(const Mixed&)> fn) const
1135
{
504✔
1136
    auto [open_str, close_str] = get_open_close_strings(link_depth, output_mode);
504✔
1137

252✔
1138
    out << open_str;
504✔
1139
    out << "{";
504✔
1140

252✔
1141
    auto sz = size();
504✔
1142
    for (size_t i = 0; i < sz; i++) {
1,152✔
1143
        if (i > 0)
648✔
1144
            out << ",";
198✔
1145
        out << do_get_key(i) << ":";
648✔
1146
        Mixed val = do_get(i);
648✔
1147
        if (val.is_type(type_TypedLink)) {
648✔
1148
            fn(val);
210✔
1149
        }
210✔
1150
        else if (val.is_type(type_Dictionary)) {
438✔
1151
            DummyParent parent(this->get_table(), val.get_ref());
12✔
1152
            Dictionary dict(parent, 0);
12✔
1153
            dict.to_json(out, link_depth, output_mode, fn);
12✔
1154
        }
12✔
1155
        else if (val.is_type(type_List)) {
426✔
1156
            DummyParent parent(this->get_table(), val.get_ref());
12✔
1157
            Lst<Mixed> list(parent, 0);
12✔
1158
            list.to_json(out, link_depth, output_mode, fn);
12✔
1159
        }
12✔
1160
        else if (val.is_type(type_Set)) {
414✔
1161
            DummyParent parent(this->get_table(), val.get_ref());
12✔
1162
            Set<Mixed> set(parent, 0);
12✔
1163
            set.to_json(out, link_depth, output_mode, fn);
12✔
1164
        }
12✔
1165
        else {
402✔
1166
            val.to_json(out, output_mode);
402✔
1167
        }
402✔
1168
    }
648✔
1169

252✔
1170
    out << "}";
504✔
1171
    out << close_str;
504✔
1172
}
504✔
1173

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

1188
bool Dictionary::check_collection_ref(Index index, CollectionType type) const noexcept
1189
{
510✔
1190
    auto ndx = m_values->find_key(index.get_salt());
510✔
1191
    if (ndx != realm::not_found) {
510✔
1192
        return m_values->get(ndx).is_type(DataType(int(type)));
480✔
1193
    }
480✔
1194
    return false;
30✔
1195
}
30✔
1196

1197
void Dictionary::set_collection_ref(Index index, ref_type ref, CollectionType type)
1198
{
234✔
1199
    auto ndx = m_values->find_key(index.get_salt());
234✔
1200
    if (ndx == realm::not_found) {
234✔
NEW
1201
        throw StaleAccessor("Collection has been deleted");
×
NEW
1202
    }
×
1203
    m_values->set(ndx, Mixed(ref, type));
234✔
1204
}
234✔
1205

1206
bool Dictionary::update_if_needed() const
1207
{
516✔
1208
    auto status = update_if_needed_with_status();
516✔
1209
    if (status == UpdateStatus::Detached) {
516✔
NEW
1210
        throw StaleAccessor("CollectionList no longer exists");
×
NEW
1211
    }
×
1212
    return status == UpdateStatus::Updated;
516✔
1213
}
516✔
1214

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

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

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

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

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

1247
} // namespace realm
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc