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

realm / realm-core / 2302

09 May 2024 05:59PM UTC coverage: 90.751% (-0.02%) from 90.769%
2302

push

Evergreen

web-flow
RCORE-2120 Throw useful error messages if baasaas fails to start a container (#7480)

101964 of 180590 branches covered (56.46%)

15 of 43 new or added lines in 1 file covered. (34.88%)

68 existing lines in 8 files now uncovered.

213176 of 234903 relevant lines covered (90.75%)

5732719.53 hits per line

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

90.14
/src/realm/table.cpp
1
/*************************************************************************
2
 *
3
 * Copyright 2016 Realm Inc.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 * http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 *
17
 **************************************************************************/
18

19
#include <realm/table.hpp>
20

21
#include <realm/alloc_slab.hpp>
22
#include <realm/array_binary.hpp>
23
#include <realm/array_bool.hpp>
24
#include <realm/array_decimal128.hpp>
25
#include <realm/array_fixed_bytes.hpp>
26
#include <realm/array_string.hpp>
27
#include <realm/array_timestamp.hpp>
28
#include <realm/db.hpp>
29
#include <realm/dictionary.hpp>
30
#include <realm/exceptions.hpp>
31
#include <realm/impl/destroy_guard.hpp>
32
#include <realm/index_string.hpp>
33
#include <realm/query_conditions_tpl.hpp>
34
#include <realm/replication.hpp>
35
#include <realm/table_view.hpp>
36
#include <realm/util/features.h>
37
#include <realm/util/serializer.hpp>
38

39
#include <stdexcept>
40

41
#ifdef REALM_DEBUG
42
#include <iostream>
43
#include <iomanip>
44
#endif
45

46
/// \page AccessorConsistencyLevels
47
///
48
/// These are the three important levels of consistency of a hierarchy of
49
/// Realm accessors rooted in a common group accessor (tables, columns, rows,
50
/// descriptors, arrays):
51
///
52
/// ### Fully Consistent Accessor Hierarchy (or just "Full Consistency")
53
///
54
/// All attached accessors are in a fully valid state and can be freely used by
55
/// the application. From the point of view of the application, the accessor
56
/// hierarchy remains in this state as long as no library function throws.
57
///
58
/// If a library function throws, and the exception is one that is considered
59
/// part of the API, such as util::File::NotFound, then the accessor hierarchy
60
/// remains fully consistent. In all other cases, such as when a library
61
/// function fails because of memory exhaustion, and it throws std::bad_alloc,
62
/// the application may no longer assume anything beyond minimal consistency.
63
///
64
/// ### Minimally Consistent Accessor Hierarchy (or just "Minimal Consistency")
65
///
66
/// No correspondence between the accessor states and the underlying node
67
/// structure can be assumed, but all parent and child accessor references are
68
/// valid (i.e., not dangling). There are specific additional guarantees, but
69
/// only on some parts of the internal accessors states, and only on some parts
70
/// of the structural state.
71
///
72
/// This level of consistency is guaranteed at all times, and it is also the
73
/// **maximum** that may be assumed by the application after a library function
74
/// fails by throwing an unexpected exception (such as std::bad_alloc). It is
75
/// also the **minimum** level of consistency that is required to be able to
76
/// properly destroy the accessor objects (manually, or as a result of stack
77
/// unwinding).
78
///
79
/// It is supposed to be a library-wide invariant that an accessor hierarchy is
80
/// at least minimally consistent, but so far, only some parts of the library
81
/// conform to it.
82
///
83
/// Note: With proper use, and maintenance of Minimal Consistency, it is
84
/// possible to ensure that no memory is leaked after a group accessor is
85
/// destroyed, even after a library function has failed because of memory
86
/// exhaustion. This is possible because the underlying nodes are allocated in
87
/// the context of the group, and they can all be freed by the group when it is
88
/// destroyed. On the other hand, when working with free-standing tables, each
89
/// underlying node is allocated individually on the heap, so in this case we
90
/// cannot prevent memory leaks, because there is no way of knowing what to free
91
/// when the table accessor is destroyed.
92
///
93
/// ### Structurally Correspondent Accessor Hierarchy (or simply "Structural Correspondence")
94
///
95
/// The structure of the accessor hierarchy is in agreement with the underlying
96
/// node structure, but the refs (references to underlying nodes) are generally
97
/// not valid, and certain other parts of the accessor states are also generally
98
/// not valid. This state of consistency is important mainly during the
99
/// advancing of read transactions (implicit transactions), and is not exposed
100
/// to the application.
101
///
102
///
103
/// Below is a detailed specification of the requirements for Minimal
104
/// Consistency and for Structural Correspondence.
105
///
106
///
107
/// Minimally Consistent Accessor Hierarchy (accessor destruction)
108
/// --------------------------------------------------------------
109
///
110
/// This section defines a level of accessor consistency known as "Minimally
111
/// Consistent Accessor Hierarchy". It applies to a set of accessors rooted in a
112
/// common group. It does not imply any level of correspondance between the
113
/// state of the accessors and the underlying node structure. It enables safe
114
/// destruction of the accessor objects by requiring that the following items
115
/// are valid (the list may not yet be complete):
116
///
117
///  - Every allocated accessor is either a group accessor, or occurs as a
118
///    direct, or an indirect child of a group accessor.
119
///
120
///  - No allocated accessor occurs as a child more than once (for example, no
121
///    doublets are allowed in Group::m_table_accessors).
122
///
123
///  - The 'is_attached' property of array accessors (Array::m_data == 0). For
124
///    example, `Table::m_top` is attached if and only if that table accessor
125
///    was attached to a table with independent dynamic type.
126
///
127
///  - The 'parent' property of array accessors (Array::m_parent), but
128
///    crucially, **not** the `index_in_parent` property.
129
///
130
///  - The list of table accessors in a group accessor
131
///    (Group::m_table_accessors). All non-null pointers refer to existing table
132
///    accessors.
133
///
134
///  - The list of column accessors in a table acccessor (Table::m_cols). All
135
///    non-null pointers refer to existing column accessors.
136
///
137
///  - The 'root_array' property of a column accessor (ColumnBase::m_array). It
138
///    always refers to an existing array accessor. The exact type of that array
139
///    accessor must be determinable from the following properties of itself:
140
///    `is_inner_bptree_node` (Array::m_is_inner_bptree_node), `has_refs`
141
///    (Array::m_has_refs), and `context_flag` (Array::m_context_flag). This
142
///    allows for a column accessor to be properly destroyed.
143
///
144
///  - The map of subtable accessors in a column acccessor
145
///    (SubtableColumnBase:m_subtable_map). All pointers refer to existing
146
///    subtable accessors, but it is not required that the set of subtable
147
///    accessors referenced from a particular parent P conincide with the set of
148
///    subtables accessors specifying P as parent.
149
///
150
///  - The `descriptor` property of a table accesor (Table::m_descriptor). If it
151
///    is not null, then it refers to an existing descriptor accessor.
152
///
153
///  - The map of subdescriptor accessors in a descriptor accessor
154
///    (Descriptor::m_subdesc_map). All non-null pointers refer to existing
155
///    subdescriptor accessors.
156
///
157
///  - The `search_index` property of a column accesor (StringColumn::m_index,
158
///    StringEnumColumn::m_index). When it is non-null, it refers to an existing
159
///    search index accessor.
160
///
161
///
162
/// Structurally Correspondent Accessor Hierarchy (accessor reattachment)
163
/// ---------------------------------------------------------------------
164
///
165
/// This section defines what it means for an accessor hierarchy to be
166
/// "Structurally Correspondent". It applies to a set of accessors rooted in a
167
/// common group. The general idea is that the structure of the accessors must
168
/// match the underlying structure to such an extent that there is never any
169
/// doubt about which underlying node that corresponds with a particular
170
/// accessor. It is assumed that the accessor tree, and the underlying node
171
/// structure are structurally sound individually.
172
///
173
/// With this level of correspondence, it is possible to reattach the accessor
174
/// tree to the underlying node structure (Table::refresh_accessor_tree()).
175
///
176
/// While all the accessors in the tree must be in the attached state (before
177
/// reattachement), they are not required to refer to existing underlying nodes;
178
/// that is, their references **are** allowed to be dangling. Roughly speaking,
179
/// this means that the accessor tree must have been attached to a node
180
/// structure at some earlier point in time.
181
///
182
//
183
/// Requirements at group level:
184
///
185
///  - The number of tables in the underlying group must be equal to the number
186
///    of entries in `Group::m_table_accessors` in the group accessor.
187
///
188
///  - For each table in the underlying group, the corresponding entry in
189
///    `Table::m_table_accessors` (at same index) is either null, or points to a
190
///    table accessor that satisfies all the "requirements for a table".
191
///
192
/// Requirements for a table:
193
///
194
///  - The corresponding underlying table has independent descriptor if, and
195
///    only if `Table::m_top` is attached.
196
///
197
///  - The row index of every row accessor is strictly less than the number of
198
///    rows in the underlying table.
199
///
200
///  - If `Table::m_columns` is unattached (degenerate table), then
201
///    `Table::m_cols` is empty, otherwise the number of columns in the
202
///    underlying table is equal to the number of entries in `Table::m_cols`.
203
///
204
///  - Each entry in `Table::m_cols` is either null, or points to a column
205
///    accessor whose type agrees with the data type (realm::DataType) of the
206
///    corresponding underlying column (at same index).
207
///
208
///  - If a column accessor is of type `StringEnumColumn`, then the
209
///    corresponding underlying column must be an enumerated strings column (the
210
///    reverse is not required).
211
///
212
///  - If a column accessor is equipped with a search index accessor, then the
213
///    corresponding underlying column must be equipped with a search index (the
214
///    reverse is not required).
215
///
216
///  - For each entry in the subtable map of a column accessor there must be an
217
///    underlying subtable at column `i` and row `j`, where `i` is the index of
218
///    the column accessor in `Table::m_cols`, and `j` is the value of
219
///    `SubtableColumnBase::SubtableMap::entry::m_subtable_ndx`. The
220
///    corresponding subtable accessor must satisfy all the "requirements for a
221
///    table" with respect to that underlying subtable.
222
///
223
///  - It the table refers to a descriptor accessor (only possible for tables
224
///    with independent descriptor), then that descriptor accessor must satisfy
225
///    all the "requirements for a descriptor" with respect to the underlying
226
///    spec structure (of this table).
227
///
228
/// Requirements for a descriptor:
229
///
230
///  - For each entry in the subdescriptor map there must be an underlying
231
///    subspec at column `i`, where `i` is the value of
232
///    `Descriptor::subdesc_entry::m_column_ndx`. The corresponding
233
///    subdescriptor accessor must satisfy all the "requirements for a
234
///    descriptor" with respect to that underlying subspec.
235
///
236
/// The 'ndx_in_parent' property of most array accessors is required to be
237
/// valid. The exceptions are:
238
///
239
///  - The top array accessor of root tables (Table::m_top). Root tables are
240
///    tables with independent descriptor.
241
///
242
///  - The columns array accessor of subtables with shared descriptor
243
///    (Table::m_columns).
244
///
245
///  - The top array accessor of spec objects of subtables with shared
246
///    descriptor (Table::m_spec.m_top).
247
///
248
///  - The root array accessor of table level columns
249
///    (*Table::m_cols[]->m_array).
250
///
251
///  - The root array accessor of the subcolumn of unique strings in an
252
///    enumerated string column (*StringEnumColumn::m_keys.m_array).
253
///
254
///  - The root array accessor of search indexes
255
///    (*Table::m_cols[]->m_index->m_array).
256
///
257
/// Note that Structural Correspondence trivially includes Minimal Consistency,
258
/// since the latter it an invariant.
259

260

261
using namespace realm;
262
using namespace realm::util;
263

264
Replication* Table::g_dummy_replication = nullptr;
265

266
bool TableVersions::operator==(const TableVersions& other) const
267
{
19,167✔
268
    if (size() != other.size())
19,167✔
269
        return false;
×
270
    size_t sz = size();
19,167✔
271
    for (size_t i = 0; i < sz; i++) {
30,303✔
272
        REALM_ASSERT_DEBUG(this->at(i).first == other.at(i).first);
19,299✔
273
        if (this->at(i).second != other.at(i).second)
19,299✔
274
            return false;
8,163✔
275
    }
19,299✔
276
    return true;
11,004✔
277
}
19,167✔
278

279
namespace realm {
280
const char* get_data_type_name(DataType type) noexcept
281
{
1,086✔
282
    switch (type) {
1,086✔
283
        case type_Int:
174✔
284
            return "int";
174✔
285
        case type_Bool:
48✔
286
            return "bool";
48✔
287
        case type_Float:
78✔
288
            return "float";
78✔
289
        case type_Double:
108✔
290
            return "double";
108✔
291
        case type_String:
132✔
292
            return "string";
132✔
293
        case type_Binary:
60✔
294
            return "binary";
60✔
295
        case type_Timestamp:
132✔
296
            return "timestamp";
132✔
297
        case type_ObjectId:
78✔
298
            return "objectId";
78✔
299
        case type_Decimal:
60✔
300
            return "decimal128";
60✔
301
        case type_UUID:
138✔
302
            return "uuid";
138✔
303
        case type_Mixed:
6✔
304
            return "mixed";
6✔
305
        case type_Link:
36✔
306
            return "link";
36✔
307
        case type_TypedLink:
✔
308
            return "typedLink";
×
309
        default:
36✔
310
            if (type == type_TypeOfValue)
36✔
311
                return "@type";
24✔
312
#if REALM_ENABLE_GEOSPATIAL
12✔
313
            else if (type == type_Geospatial)
12✔
314
                return "geospatial";
6✔
315
#endif
6✔
316
            else if (type == ColumnTypeTraits<null>::id)
6✔
317
                return "null";
6✔
318
    }
1,086✔
319
    return "unknown";
×
320
}
1,086✔
321

322
std::ostream& operator<<(std::ostream& o, Table::Type table_type)
323
{
65,118✔
324
    switch (table_type) {
65,118✔
325
        case Table::Type::TopLevel:
61,830✔
326
            return o << "TopLevel";
61,830✔
327
        case Table::Type::Embedded:
3,288✔
328
            return o << "Embedded";
3,288✔
329
        case Table::Type::TopLevelAsymmetric:
✔
330
            return o << "TopLevelAsymmetric";
×
331
    }
65,118✔
332
    return o << "Invalid table type: " << uint8_t(table_type);
×
333
}
65,118✔
334
} // namespace realm
335

336
bool LinkChain::add(ColKey ck)
337
{
805,905✔
338
    // Link column can be a single Link, LinkList, or BackLink.
339
    REALM_ASSERT(m_current_table->valid_column(ck));
805,905✔
340
    ColumnType type = ck.get_type();
805,905✔
341
    if (type == col_type_Link || type == col_type_BackLink) {
805,905✔
342
        m_current_table = m_current_table->get_opposite_table(ck);
88,233✔
343
        m_link_cols.push_back(ck);
88,233✔
344
        return true;
88,233✔
345
    }
88,233✔
346
    return false;
717,672✔
347
}
805,905✔
348

349
// -- Table ---------------------------------------------------------------------------------
350

351
Table::Table(Allocator& alloc)
352
    : m_alloc(alloc)
1,776✔
353
    , m_top(m_alloc)
1,776✔
354
    , m_spec(m_alloc)
1,776✔
355
    , m_clusters(this, m_alloc, top_position_for_cluster_tree)
1,776✔
356
    , m_index_refs(m_alloc)
1,776✔
357
    , m_opposite_table(m_alloc)
1,776✔
358
    , m_opposite_column(m_alloc)
1,776✔
359
    , m_repl(&g_dummy_replication)
1,776✔
360
    , m_own_ref(this, alloc.get_instance_version())
1,776✔
361
{
3,552✔
362
    m_spec.set_parent(&m_top, top_position_for_spec);
3,552✔
363
    m_index_refs.set_parent(&m_top, top_position_for_search_indexes);
3,552✔
364
    m_opposite_table.set_parent(&m_top, top_position_for_opposite_table);
3,552✔
365
    m_opposite_column.set_parent(&m_top, top_position_for_opposite_column);
3,552✔
366

367
    ref_type ref = create_empty_table(m_alloc); // Throws
3,552✔
368
    ArrayParent* parent = nullptr;
3,552✔
369
    size_t ndx_in_parent = 0;
3,552✔
370
    init(ref, parent, ndx_in_parent, true, false);
3,552✔
371
}
3,552✔
372

373
Table::Table(Replication* const* repl, Allocator& alloc)
374
    : m_alloc(alloc)
11,151✔
375
    , m_top(m_alloc)
11,151✔
376
    , m_spec(m_alloc)
11,151✔
377
    , m_clusters(this, m_alloc, top_position_for_cluster_tree)
11,151✔
378
    , m_index_refs(m_alloc)
11,151✔
379
    , m_opposite_table(m_alloc)
11,151✔
380
    , m_opposite_column(m_alloc)
11,151✔
381
    , m_repl(repl)
11,151✔
382
    , m_own_ref(this, alloc.get_instance_version())
11,151✔
383
{
21,618✔
384
    m_spec.set_parent(&m_top, top_position_for_spec);
21,618✔
385
    m_index_refs.set_parent(&m_top, top_position_for_search_indexes);
21,618✔
386
    m_opposite_table.set_parent(&m_top, top_position_for_opposite_table);
21,618✔
387
    m_opposite_column.set_parent(&m_top, top_position_for_opposite_column);
21,618✔
388
    m_cookie = cookie_created;
21,618✔
389
}
21,618✔
390

391
ColKey Table::add_column(DataType type, StringData name, bool nullable, std::optional<CollectionType> collection_type,
392
                         DataType key_type)
393
{
465,756✔
394
    REALM_ASSERT(!is_link_type(ColumnType(type)));
465,756✔
395
    if (type == type_TypedLink) {
465,756✔
396
        throw IllegalOperation("TypedLink properties not yet supported");
×
397
    }
×
398

399
    ColumnAttrMask attr;
465,756✔
400
    if (collection_type) {
465,756✔
401
        switch (*collection_type) {
147,801✔
402
            case CollectionType::List:
60,738✔
403
                attr.set(col_attr_List);
60,738✔
404
                break;
60,738✔
405
            case CollectionType::Set:
43,305✔
406
                attr.set(col_attr_Set);
43,305✔
407
                break;
43,305✔
408
            case CollectionType::Dictionary:
43,758✔
409
                attr.set(col_attr_Dictionary);
43,758✔
410
                break;
43,758✔
411
        }
147,801✔
412
    }
147,801✔
413
    if (nullable || type == type_Mixed)
465,756✔
414
        attr.set(col_attr_Nullable);
156,090✔
415
    ColKey col_key = generate_col_key(ColumnType(type), attr);
465,756✔
416

417
    Table* invalid_link = nullptr;
465,756✔
418
    return do_insert_column(col_key, type, name, invalid_link, key_type); // Throws
465,756✔
419
}
465,756✔
420

421
ColKey Table::add_column(Table& target, StringData name, std::optional<CollectionType> collection_type,
422
                         DataType key_type)
423
{
74,094✔
424
    // Both origin and target must be group-level tables, and in the same group.
425
    Group* origin_group = get_parent_group();
74,094✔
426
    Group* target_group = target.get_parent_group();
74,094✔
427
    REALM_ASSERT_RELEASE(origin_group && target_group);
74,094✔
428
    REALM_ASSERT_RELEASE(origin_group == target_group);
74,094✔
429
    // Links to an asymmetric table are not allowed.
430
    if (target.is_asymmetric()) {
74,094✔
431
        throw IllegalOperation("Ephemeral objects not supported");
6✔
432
    }
6✔
433

434
    m_has_any_embedded_objects.reset();
74,088✔
435

436
    DataType data_type = type_Link;
74,088✔
437
    ColumnAttrMask attr;
74,088✔
438
    if (collection_type) {
74,088✔
439
        switch (*collection_type) {
43,350✔
440
            case CollectionType::List:
21,270✔
441
                attr.set(col_attr_List);
21,270✔
442
                break;
21,270✔
443
            case CollectionType::Set:
10,728✔
444
                if (target.is_embedded())
10,728✔
445
                    throw IllegalOperation("Set of embedded objects not supported");
×
446
                attr.set(col_attr_Set);
10,728✔
447
                break;
10,728✔
448
            case CollectionType::Dictionary:
11,352✔
449
                attr.set(col_attr_Dictionary);
11,352✔
450
                attr.set(col_attr_Nullable);
11,352✔
451
                break;
11,352✔
452
        }
43,350✔
453
    }
43,350✔
454
    else {
30,738✔
455
        attr.set(col_attr_Nullable);
30,738✔
456
    }
30,738✔
457
    ColKey col_key = generate_col_key(ColumnType(data_type), attr);
74,088✔
458

459
    return do_insert_column(col_key, data_type, name, &target, key_type); // Throws
74,088✔
460
}
74,088✔
461

462
void Table::remove_recursive(CascadeState& cascade_state)
463
{
19,146✔
464
    Group* group = get_parent_group();
19,146✔
465
    REALM_ASSERT(group);
19,146✔
466
    cascade_state.m_group = group;
19,146✔
467

468
    do {
23,817✔
469
        cascade_state.send_notifications();
23,817✔
470

471
        for (auto& l : cascade_state.m_to_be_nullified) {
23,817✔
472
            Obj obj = group->get_table_unchecked(l.origin_table)->try_get_object(l.origin_key);
48✔
473
            REALM_ASSERT_DEBUG(obj);
48✔
474
            if (obj) {
48✔
475
                std::move(obj).nullify_link(l.origin_col_key, l.old_target_link);
48✔
476
            }
48✔
477
        }
48✔
478
        cascade_state.m_to_be_nullified.clear();
23,817✔
479

480
        auto to_delete = std::move(cascade_state.m_to_be_deleted);
23,817✔
481
        for (auto obj : to_delete) {
23,817✔
482
            auto table = obj.first == m_key ? this : group->get_table_unchecked(obj.first);
17,025✔
483
            // This might add to the list of objects that should be deleted
484
            REALM_ASSERT(!obj.second.is_unresolved());
17,025✔
485
            table->m_clusters.erase(obj.second, cascade_state);
17,025✔
486
        }
17,025✔
487
        nullify_links(cascade_state);
23,817✔
488
    } while (!cascade_state.m_to_be_deleted.empty() || !cascade_state.m_to_be_nullified.empty());
23,817✔
489
}
19,146✔
490

491
void Table::nullify_links(CascadeState& cascade_state)
492
{
29,913✔
493
    Group* group = get_parent_group();
29,913✔
494
    REALM_ASSERT(group);
29,913✔
495
    for (auto& to_delete : cascade_state.m_to_be_deleted) {
29,913✔
496
        auto table = to_delete.first == m_key ? this : group->get_table_unchecked(to_delete.first);
8,421✔
497
        if (!table->is_asymmetric())
8,421✔
498
            table->m_clusters.nullify_incoming_links(to_delete.second, cascade_state);
8,421✔
499
    }
8,421✔
500
}
29,913✔
501

502
CollectionType Table::get_collection_type(ColKey col_key) const
503
{
9,156✔
504
    if (col_key.is_list()) {
9,156✔
505
        return CollectionType::List;
648✔
506
    }
648✔
507
    if (col_key.is_set()) {
8,508✔
508
        return CollectionType::Set;
1,056✔
509
    }
1,056✔
510
    REALM_ASSERT(col_key.is_dictionary());
7,452✔
511
    return CollectionType::Dictionary;
7,452✔
512
}
8,508✔
513

514
void Table::remove_columns()
515
{
2,463✔
516
    for (size_t i = get_column_count(); i > 0; --i) {
7,044✔
517
        ColKey col_key = spec_ndx2colkey(i - 1);
4,581✔
518
        remove_column(col_key);
4,581✔
519
    }
4,581✔
520
}
2,463✔
521

522
void Table::remove_column(ColKey col_key)
523
{
5,271✔
524
    check_column(col_key);
5,271✔
525

526
    if (Replication* repl = get_repl())
5,271✔
527
        repl->erase_column(this, col_key); // Throws
4,212✔
528

529
    if (col_key == m_primary_key_col) {
5,271✔
530
        do_set_primary_key_column(ColKey());
897✔
531
    }
897✔
532
    else {
4,374✔
533
        REALM_ASSERT_RELEASE(m_primary_key_col.get_index().val != col_key.get_index().val);
4,374✔
534
    }
4,374✔
535

536
    erase_root_column(col_key); // Throws
5,271✔
537
    m_has_any_embedded_objects.reset();
5,271✔
538
}
5,271✔
539

540

541
void Table::rename_column(ColKey col_key, StringData name)
542
{
99✔
543
    check_column(col_key);
99✔
544

545
    auto col_ndx = colkey2spec_ndx(col_key);
99✔
546
    m_spec.rename_column(col_ndx, name); // Throws
99✔
547

548
    bump_content_version();
99✔
549
    bump_storage_version();
99✔
550

551
    if (Replication* repl = get_repl())
99✔
552
        repl->rename_column(this, col_key, name); // Throws
99✔
553
}
99✔
554

555

556
TableKey Table::get_key_direct(Allocator& alloc, ref_type top_ref)
557
{
2,547,396✔
558
    // well, not quite "direct", more like "almost direct":
559
    Array table_top(alloc);
2,547,396✔
560
    table_top.init_from_ref(top_ref);
2,547,396✔
561
    if (table_top.size() > 3) {
2,547,414✔
562
        RefOrTagged rot = table_top.get_as_ref_or_tagged(top_position_for_key);
2,546,112✔
563
        return TableKey(int32_t(rot.get_as_int()));
2,546,112✔
564
    }
2,546,112✔
565
    else {
2,147,484,949✔
566
        return TableKey();
2,147,484,949✔
567
    }
2,147,484,949✔
568
}
2,547,396✔
569

570

571
void Table::init(ref_type top_ref, ArrayParent* parent, size_t ndx_in_parent, bool is_writable, bool is_frzn)
572
{
1,958,496✔
573
    REALM_ASSERT(!(is_writable && is_frzn));
1,958,496✔
574
    m_is_frozen = is_frzn;
1,958,496✔
575
    m_alloc.set_read_only(!is_writable);
1,958,496✔
576
    // Load from allocated memory
577
    m_top.set_parent(parent, ndx_in_parent);
1,958,496✔
578
    m_top.init_from_ref(top_ref);
1,958,496✔
579

580
    m_spec.init_from_parent();
1,958,496✔
581

582
    while (m_top.size() <= top_position_for_pk_col) {
1,958,496✔
583
        m_top.add(0);
×
584
    }
×
585

586
    if (m_top.get_as_ref(top_position_for_cluster_tree) == 0) {
1,958,496✔
587
        // This is an upgrade - create cluster
588
        MemRef mem = Cluster::create_empty_cluster(m_top.get_alloc()); // Throws
×
589
        m_top.set_as_ref(top_position_for_cluster_tree, mem.get_ref());
×
590
    }
×
591
    m_clusters.init_from_parent();
1,958,496✔
592

593
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_key);
1,958,496✔
594
    if (!rot.is_tagged()) {
1,958,496✔
595
        // Create table key
596
        rot = RefOrTagged::make_tagged(ndx_in_parent);
×
597
        m_top.set(top_position_for_key, rot);
×
598
    }
×
599
    m_key = TableKey(int32_t(rot.get_as_int()));
1,958,496✔
600

601
    // index setup relies on column mapping being up to date:
602
    build_column_mapping();
1,958,496✔
603
    if (m_top.get_as_ref(top_position_for_search_indexes) == 0) {
1,958,496✔
604
        // This is an upgrade - create the necessary arrays
605
        bool context_flag = false;
×
606
        size_t nb_columns = m_spec.get_column_count();
×
607
        MemRef mem = Array::create_array(Array::type_HasRefs, context_flag, nb_columns, 0, m_top.get_alloc());
×
608
        m_index_refs.init_from_mem(mem);
×
609
        m_index_refs.update_parent();
×
610
        mem = Array::create_array(Array::type_Normal, context_flag, nb_columns, TableKey().value, m_top.get_alloc());
×
611
        m_opposite_table.init_from_mem(mem);
×
612
        m_opposite_table.update_parent();
×
613
        mem = Array::create_array(Array::type_Normal, context_flag, nb_columns, ColKey().value, m_top.get_alloc());
×
614
        m_opposite_column.init_from_mem(mem);
×
615
        m_opposite_column.update_parent();
×
616
    }
×
617
    else {
1,958,496✔
618
        m_opposite_table.init_from_parent();
1,958,496✔
619
        m_opposite_column.init_from_parent();
1,958,496✔
620
        m_index_refs.init_from_parent();
1,958,496✔
621
        m_index_accessors.resize(m_index_refs.size());
1,958,496✔
622
    }
1,958,496✔
623
    if (!m_top.get_as_ref_or_tagged(top_position_for_column_key).is_tagged()) {
1,958,496✔
624
        m_top.set(top_position_for_column_key, RefOrTagged::make_tagged(0));
×
625
    }
×
626
    auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
1,958,496✔
627
    if (!rot_version.is_tagged()) {
1,958,496✔
628
        m_top.set(top_position_for_version, RefOrTagged::make_tagged(0));
×
629
        m_in_file_version_at_transaction_boundary = 0;
×
630
    }
×
631
    else
1,958,496✔
632
        m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
1,958,496✔
633

634
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
1,958,496✔
635
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
1,958,496✔
636

637
    if (m_top.size() <= top_position_for_flags) {
1,958,496✔
638
        m_table_type = Type::TopLevel;
60✔
639
    }
60✔
640
    else {
1,958,436✔
641
        uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
1,958,436✔
642
        m_table_type = Type(flags & table_type_mask);
1,958,436✔
643
    }
1,958,436✔
644
    m_has_any_embedded_objects.reset();
1,958,496✔
645

646
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
1,958,496✔
647
        // Tombstones exists
648
        if (!m_tombstones) {
38,454✔
649
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
30,453✔
650
        }
30,453✔
651
        m_tombstones->init_from_parent();
38,454✔
652
    }
38,454✔
653
    else {
1,920,042✔
654
        m_tombstones = nullptr;
1,920,042✔
655
    }
1,920,042✔
656
    m_cookie = cookie_initialized;
1,958,496✔
657
}
1,958,496✔
658

659

660
ColKey Table::do_insert_column(ColKey col_key, DataType type, StringData name, Table* target_table, DataType key_type)
661
{
539,847✔
662
    col_key = do_insert_root_column(col_key, ColumnType(type), name, key_type); // Throws
539,847✔
663

664
    // When the inserted column is a link-type column, we must also add a
665
    // backlink column to the target table.
666

667
    if (target_table) {
539,847✔
668
        auto backlink_col_key = target_table->do_insert_root_column(ColKey{}, col_type_BackLink, ""); // Throws
74,082✔
669
        target_table->check_column(backlink_col_key);
74,082✔
670

671
        set_opposite_column(col_key, target_table->get_key(), backlink_col_key);
74,082✔
672
        target_table->set_opposite_column(backlink_col_key, get_key(), col_key);
74,082✔
673
    }
74,082✔
674

675
    if (Replication* repl = get_repl())
539,847✔
676
        repl->insert_column(this, col_key, type, name, target_table); // Throws
521,907✔
677

678
    return col_key;
539,847✔
679
}
539,847✔
680

681
template <typename Type>
682
static void do_bulk_insert_index(Table* table, SearchIndex* index, ColKey col_key, Allocator& alloc)
683
{
101,511✔
684
    using LeafType = typename ColumnTypeTraits<Type>::cluster_leaf_type;
101,511✔
685
    LeafType leaf(alloc);
101,511✔
686

687
    auto f = [&col_key, &index, &leaf](const Cluster* cluster) {
106,599✔
688
        cluster->init_leaf(col_key, &leaf);
106,599✔
689
        index->insert_bulk(cluster->get_key_array(), cluster->get_offset(), cluster->node_size(), leaf);
106,599✔
690
        return IteratorControl::AdvanceToNext;
106,599✔
691
    };
106,599✔
692

693
    table->traverse_clusters(f);
101,511✔
694
}
101,511✔
695

696

697
static void do_bulk_insert_index_list(Table* table, SearchIndex* index, ColKey col_key, Allocator& alloc)
698
{
24✔
699
    ArrayInteger leaf(alloc);
24✔
700

701
    auto f = [&col_key, &index, &leaf](const Cluster* cluster) {
258✔
702
        cluster->init_leaf(col_key, &leaf);
258✔
703
        index->insert_bulk_list(cluster->get_key_array(), cluster->get_offset(), cluster->node_size(), leaf);
258✔
704
        return IteratorControl::AdvanceToNext;
258✔
705
    };
258✔
706

707
    table->traverse_clusters(f);
24✔
708
}
24✔
709

710
void Table::populate_search_index(ColKey col_key)
711
{
101,532✔
712
    auto col_ndx = col_key.get_index().val;
101,532✔
713
    SearchIndex* index = m_index_accessors[col_ndx].get();
101,532✔
714
    DataType type = get_column_type(col_key);
101,532✔
715

716
    if (type == type_Int) {
101,532✔
717
        if (is_nullable(col_key)) {
49,359✔
718
            do_bulk_insert_index<Optional<int64_t>>(this, index, col_key, get_alloc());
13,791✔
719
        }
13,791✔
720
        else {
35,568✔
721
            do_bulk_insert_index<int64_t>(this, index, col_key, get_alloc());
35,568✔
722
        }
35,568✔
723
    }
49,359✔
724
    else if (type == type_Bool) {
52,173✔
725
        if (is_nullable(col_key)) {
48✔
726
            do_bulk_insert_index<Optional<bool>>(this, index, col_key, get_alloc());
24✔
727
        }
24✔
728
        else {
24✔
729
            do_bulk_insert_index<bool>(this, index, col_key, get_alloc());
24✔
730
        }
24✔
731
    }
48✔
732
    else if (type == type_String) {
52,125✔
733
        if (col_key.is_list()) {
8,694✔
734
            do_bulk_insert_index_list(this, index, col_key, get_alloc());
24✔
735
        }
24✔
736
        else {
8,670✔
737
            do_bulk_insert_index<StringData>(this, index, col_key, get_alloc());
8,670✔
738
        }
8,670✔
739
    }
8,694✔
740
    else if (type == type_Timestamp) {
43,431✔
741
        do_bulk_insert_index<Timestamp>(this, index, col_key, get_alloc());
96✔
742
    }
96✔
743
    else if (type == type_ObjectId) {
43,335✔
744
        if (is_nullable(col_key)) {
41,745✔
745
            do_bulk_insert_index<Optional<ObjectId>>(this, index, col_key, get_alloc());
996✔
746
        }
996✔
747
        else {
40,749✔
748
            do_bulk_insert_index<ObjectId>(this, index, col_key, get_alloc());
40,749✔
749
        }
40,749✔
750
    }
41,745✔
751
    else if (type == type_UUID) {
1,590✔
752
        if (is_nullable(col_key)) {
684✔
753
            do_bulk_insert_index<Optional<UUID>>(this, index, col_key, get_alloc());
516✔
754
        }
516✔
755
        else {
168✔
756
            do_bulk_insert_index<UUID>(this, index, col_key, get_alloc());
168✔
757
        }
168✔
758
    }
684✔
759
    else if (type == type_Mixed) {
906✔
760
        do_bulk_insert_index<Mixed>(this, index, col_key, get_alloc());
906✔
761
    }
906✔
UNCOV
762
    else {
×
UNCOV
763
        REALM_ASSERT_RELEASE(false && "Data type does not support search index");
×
UNCOV
764
    }
×
765
}
101,532✔
766

767
void Table::erase_from_search_indexes(ObjKey key)
768
{
5,000,373✔
769
    // Tombstones do not use index - will crash if we try to erase values
770
    if (!key.is_unresolved()) {
5,000,373✔
771
        for (auto&& index : m_index_accessors) {
6,668,916✔
772
            if (index) {
6,668,916✔
773
                index->erase(key);
255,174✔
774
            }
255,174✔
775
        }
6,668,916✔
776
    }
4,989,339✔
777
}
5,000,373✔
778

779
void Table::update_indexes(ObjKey key, const FieldValues& values)
780
{
23,464,191✔
781
    // Tombstones do not use index - will crash if we try to insert values
782
    if (key.is_unresolved()) {
23,464,191✔
783
        return;
12,543✔
784
    }
12,543✔
785

786
    auto sz = m_index_accessors.size();
23,451,648✔
787
    // values are sorted by column index - there may be values missing
788
    auto value = values.begin();
23,451,648✔
789
    for (size_t column_ndx = 0; column_ndx < sz; column_ndx++) {
57,854,436✔
790
        // Check if initial value is provided
791
        Mixed init_value;
34,402,779✔
792
        if (value != values.end() && value->col_key.get_index().val == column_ndx) {
34,402,779✔
793
            // Value for this column is provided
794
            init_value = value->value;
810,744✔
795
            ++value;
810,744✔
796
        }
810,744✔
797

798
        if (auto&& index = m_index_accessors[column_ndx]) {
34,402,779✔
799
            // There is an index for this column
800
            auto col_key = m_leaf_ndx2colkey[column_ndx];
1,386,573✔
801
            if (col_key.is_collection())
1,386,573✔
802
                continue;
102✔
803
            auto type = col_key.get_type();
1,386,471✔
804
            auto attr = col_key.get_attrs();
1,386,471✔
805
            bool nullable = attr.test(col_attr_Nullable);
1,386,471✔
806
            switch (type) {
1,386,471✔
807
                case col_type_Int:
479,721✔
808
                    if (init_value.is_null()) {
479,721✔
809
                        index->insert(key, ArrayIntNull::default_value(nullable));
166,755✔
810
                    }
166,755✔
811
                    else {
312,966✔
812
                        index->insert(key, init_value.get<int64_t>());
312,966✔
813
                    }
312,966✔
814
                    break;
479,721✔
815
                case col_type_Bool:
5,985✔
816
                    if (init_value.is_null()) {
5,985✔
817
                        index->insert(key, ArrayBoolNull::default_value(nullable));
5,985✔
818
                    }
5,985✔
819
                    else {
×
820
                        index->insert(key, init_value.get<bool>());
×
821
                    }
×
822
                    break;
5,985✔
823
                case col_type_String:
779,526✔
824
                    if (init_value.is_null()) {
779,526✔
825
                        index->insert(key, ArrayString::default_value(nullable));
432,591✔
826
                    }
432,591✔
827
                    else {
346,935✔
828
                        index->insert(key, init_value.get<String>());
346,935✔
829
                    }
346,935✔
830
                    break;
779,526✔
831
                case col_type_Timestamp:
7,353✔
832
                    if (init_value.is_null()) {
7,353✔
833
                        index->insert(key, ArrayTimestamp::default_value(nullable));
7,353✔
834
                    }
7,353✔
835
                    else {
×
836
                        index->insert(key, init_value.get<Timestamp>());
×
837
                    }
×
838
                    break;
7,353✔
839
                case col_type_ObjectId:
92,127✔
840
                    if (init_value.is_null()) {
92,127✔
841
                        index->insert(key, ArrayObjectIdNull::default_value(nullable));
7,320✔
842
                    }
7,320✔
843
                    else {
84,807✔
844
                        index->insert(key, init_value.get<ObjectId>());
84,807✔
845
                    }
84,807✔
846
                    break;
92,127✔
847
                case col_type_Mixed:
2,286✔
848
                    index->insert(key, init_value);
2,286✔
849
                    break;
2,286✔
850
                case col_type_UUID:
19,542✔
851
                    if (init_value.is_null()) {
19,542✔
852
                        index->insert(key, ArrayUUIDNull::default_value(nullable));
7,338✔
853
                    }
7,338✔
854
                    else {
12,204✔
855
                        index->insert(key, init_value.get<UUID>());
12,204✔
856
                    }
12,204✔
857
                    break;
19,542✔
858
                default:
✔
859
                    REALM_UNREACHABLE();
860
            }
1,386,471✔
861
        }
1,386,471✔
862
    }
34,402,779✔
863
}
23,451,648✔
864

865
void Table::clear_indexes()
866
{
5,994✔
867
    for (auto&& index : m_index_accessors) {
56,913✔
868
        if (index) {
56,913✔
869
            index->clear();
4,716✔
870
        }
4,716✔
871
    }
56,913✔
872
}
5,994✔
873

874
void Table::do_add_search_index(ColKey col_key, IndexType type)
875
{
101,727✔
876
    size_t column_ndx = col_key.get_index().val;
101,727✔
877

878
    // Early-out if already indexed
879
    if (m_index_accessors[column_ndx] != nullptr)
101,727✔
880
        return;
150✔
881

882
    if (!StringIndex::type_supported(DataType(col_key.get_type())) ||
101,577✔
883
        (col_key.is_collection() && !(col_key.is_list() && col_key.get_type() == col_type_String)) ||
101,577✔
884
        (type == IndexType::Fulltext && col_key.get_type() != col_type_String)) {
101,577✔
885
        // Not ideal, but this is what we used to throw, so keep throwing that for compatibility reasons, even though
886
        // it should probably be a type mismatch exception instead.
887
        throw IllegalOperation(util::format("Index not supported for this property: %1", get_column_name(col_key)));
42✔
888
    }
42✔
889

890
    // m_index_accessors always has the same number of pointers as the number of columns. Columns without search
891
    // index have 0-entries.
892
    REALM_ASSERT(m_index_accessors.size() == m_leaf_ndx2colkey.size());
101,535✔
893
    REALM_ASSERT(m_index_accessors[column_ndx] == nullptr);
101,535✔
894

895
    // Create the index
896
    m_index_accessors[column_ndx] =
101,535✔
897
        std::make_unique<StringIndex>(ClusterColumn(&m_clusters, col_key, type), get_alloc()); // Throws
101,535✔
898
    SearchIndex* index = m_index_accessors[column_ndx].get();
101,535✔
899
    // Insert ref to index
900
    index->set_parent(&m_index_refs, column_ndx);
101,535✔
901

902
    m_index_refs.set(column_ndx, index->get_ref()); // Throws
101,535✔
903

904
    populate_search_index(col_key);
101,535✔
905
}
101,535✔
906

907
void Table::add_search_index(ColKey col_key, IndexType type)
908
{
3,960✔
909
    check_column(col_key);
3,960✔
910

911
    // Check spec
912
    auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
3,960✔
913
    auto attr = m_spec.get_column_attr(spec_ndx);
3,960✔
914

915
    if (col_key == m_primary_key_col && type == IndexType::Fulltext)
3,960✔
916
        throw InvalidColumnKey("primary key cannot have a full text index");
6✔
917

918
    switch (type) {
3,954✔
919
        case IndexType::None:
✔
920
            remove_search_index(col_key);
×
921
            return;
×
922
        case IndexType::Fulltext:
54✔
923
            // Early-out if already indexed
924
            if (attr.test(col_attr_FullText_Indexed)) {
54✔
925
                REALM_ASSERT(search_index_type(col_key) == IndexType::Fulltext);
×
926
                return;
×
927
            }
×
928
            if (attr.test(col_attr_Indexed)) {
54✔
929
                this->remove_search_index(col_key);
×
930
            }
×
931
            break;
54✔
932
        case IndexType::General:
3,900✔
933
            if (attr.test(col_attr_Indexed)) {
3,900✔
934
                REALM_ASSERT(search_index_type(col_key) == IndexType::General);
30✔
935
                return;
30✔
936
            }
30✔
937
            if (attr.test(col_attr_FullText_Indexed)) {
3,870✔
938
                this->remove_search_index(col_key);
×
939
            }
×
940
            break;
3,870✔
941
    }
3,954✔
942

943
    do_add_search_index(col_key, type);
3,924✔
944

945
    // Update spec
946
    attr.set(type == IndexType::Fulltext ? col_attr_FullText_Indexed : col_attr_Indexed);
3,924✔
947
    m_spec.set_column_attr(spec_ndx, attr); // Throws
3,924✔
948
}
3,924✔
949

950
void Table::remove_search_index(ColKey col_key)
951
{
1,347✔
952
    check_column(col_key);
1,347✔
953
    auto column_ndx = col_key.get_index();
1,347✔
954

955
    // Early-out if non-indexed
956
    if (m_index_accessors[column_ndx.val] == nullptr)
1,347✔
957
        return;
66✔
958

959
    // Destroy and remove the index column
960
    auto& index = m_index_accessors[column_ndx.val];
1,281✔
961
    REALM_ASSERT(index != nullptr);
1,281✔
962
    index->destroy();
1,281✔
963
    index.reset();
1,281✔
964

965
    m_index_refs.set(column_ndx.val, 0);
1,281✔
966

967
    // update spec
968
    auto spec_ndx = leaf_ndx2spec_ndx(column_ndx);
1,281✔
969
    auto attr = m_spec.get_column_attr(spec_ndx);
1,281✔
970
    attr.reset(col_attr_Indexed);
1,281✔
971
    attr.reset(col_attr_FullText_Indexed);
1,281✔
972
    m_spec.set_column_attr(spec_ndx, attr); // Throws
1,281✔
973
}
1,281✔
974

975
void Table::enumerate_string_column(ColKey col_key)
976
{
1,311✔
977
    check_column(col_key);
1,311✔
978
    size_t column_ndx = colkey2spec_ndx(col_key);
1,311✔
979
    ColumnType type = col_key.get_type();
1,311✔
980
    if (type == col_type_String && !col_key.is_collection() && !m_spec.is_string_enum_type(column_ndx)) {
1,311✔
981
        m_clusters.enumerate_string_column(col_key);
690✔
982
    }
690✔
983
}
1,311✔
984

985
bool Table::is_enumerated(ColKey col_key) const noexcept
986
{
53,634✔
987
    size_t col_ndx = colkey2spec_ndx(col_key);
53,634✔
988
    return m_spec.is_string_enum_type(col_ndx);
53,634✔
989
}
53,634✔
990

991
size_t Table::get_num_unique_values(ColKey col_key) const
992
{
138✔
993
    if (!is_enumerated(col_key))
138✔
994
        return 0;
84✔
995

996
    ArrayParent* parent;
54✔
997
    ref_type ref = const_cast<Spec&>(m_spec).get_enumkeys_ref(colkey2spec_ndx(col_key), parent);
54✔
998
    BPlusTree<StringData> col(get_alloc());
54✔
999
    col.init_from_ref(ref);
54✔
1000

1001
    return col.size();
54✔
1002
}
138✔
1003

1004

1005
void Table::erase_root_column(ColKey col_key)
1006
{
5,547✔
1007
    ColumnType col_type = col_key.get_type();
5,547✔
1008
    if (is_link_type(col_type)) {
5,547✔
1009
        auto target_table = get_opposite_table(col_key);
621✔
1010
        auto target_column = get_opposite_column(col_key);
621✔
1011
        target_table->do_erase_root_column(target_column);
621✔
1012
    }
621✔
1013
    do_erase_root_column(col_key); // Throws
5,547✔
1014
}
5,547✔
1015

1016

1017
ColKey Table::do_insert_root_column(ColKey col_key, ColumnType type, StringData name, DataType key_type)
1018
{
719,463✔
1019
    // if col_key specifies a key, it must be unused
1020
    REALM_ASSERT(!col_key || !valid_column(col_key));
719,463✔
1021

1022
    // locate insertion point: ordinary columns must come before backlink columns
1023
    size_t spec_ndx = (type == col_type_BackLink) ? m_spec.get_column_count() : m_spec.get_public_column_count();
719,463✔
1024

1025
    if (!col_key) {
719,463✔
1026
        col_key = generate_col_key(type, {});
81,840✔
1027
    }
81,840✔
1028

1029
    m_spec.insert_column(spec_ndx, col_key, type, name, col_key.get_attrs().m_value); // Throws
719,463✔
1030
    if (col_key.is_dictionary()) {
719,463✔
1031
        m_spec.set_dictionary_key_type(spec_ndx, key_type);
55,110✔
1032
    }
55,110✔
1033
    auto col_ndx = col_key.get_index().val;
719,463✔
1034
    build_column_mapping();
719,463✔
1035
    REALM_ASSERT(col_ndx <= m_index_refs.size());
719,463✔
1036
    if (col_ndx == m_index_refs.size()) {
719,463✔
1037
        m_index_refs.insert(col_ndx, 0);
719,220✔
1038
    }
719,220✔
1039
    else {
243✔
1040
        m_index_refs.set(col_ndx, 0);
243✔
1041
    }
243✔
1042
    REALM_ASSERT(col_ndx <= m_opposite_table.size());
719,463✔
1043
    if (col_ndx == m_opposite_table.size()) {
719,463✔
1044
        // m_opposite_table and m_opposite_column are always resized together!
1045
        m_opposite_table.insert(col_ndx, TableKey().value);
719,223✔
1046
        m_opposite_column.insert(col_ndx, ColKey().value);
719,223✔
1047
    }
719,223✔
1048
    else {
240✔
1049
        m_opposite_table.set(col_ndx, TableKey().value);
240✔
1050
        m_opposite_column.set(col_ndx, ColKey().value);
240✔
1051
    }
240✔
1052
    refresh_index_accessors();
719,463✔
1053
    m_clusters.insert_column(col_key);
719,463✔
1054
    if (m_tombstones) {
719,463✔
1055
        m_tombstones->insert_column(col_key);
348✔
1056
    }
348✔
1057

1058
    bump_storage_version();
719,463✔
1059

1060
    return col_key;
719,463✔
1061
}
719,463✔
1062

1063

1064
void Table::do_erase_root_column(ColKey col_key)
1065
{
6,168✔
1066
    size_t col_ndx = col_key.get_index().val;
6,168✔
1067
    // If the column had a source index we have to remove and destroy that as well
1068
    ref_type index_ref = m_index_refs.get_as_ref(col_ndx);
6,168✔
1069
    if (index_ref) {
6,168✔
1070
        Array::destroy_deep(index_ref, m_index_refs.get_alloc());
132✔
1071
        m_index_refs.set(col_ndx, 0);
132✔
1072
        m_index_accessors[col_ndx].reset();
132✔
1073
    }
132✔
1074
    m_opposite_table.set(col_ndx, TableKey().value);
6,168✔
1075
    m_opposite_column.set(col_ndx, ColKey().value);
6,168✔
1076
    m_index_accessors[col_ndx] = nullptr;
6,168✔
1077
    m_clusters.remove_column(col_key);
6,168✔
1078
    if (m_tombstones)
6,168✔
1079
        m_tombstones->remove_column(col_key);
414✔
1080
    size_t spec_ndx = colkey2spec_ndx(col_key);
6,168✔
1081
    m_spec.erase_column(spec_ndx);
6,168✔
1082
    m_top.adjust(top_position_for_column_key, 2);
6,168✔
1083

1084
    build_column_mapping();
6,168✔
1085
    while (m_index_accessors.size() > m_leaf_ndx2colkey.size()) {
11,760✔
1086
        REALM_ASSERT(m_index_accessors.back() == nullptr);
5,592✔
1087
        m_index_accessors.pop_back();
5,592✔
1088
    }
5,592✔
1089
    bump_content_version();
6,168✔
1090
    bump_storage_version();
6,168✔
1091
}
6,168✔
1092

1093
Query Table::where(const Dictionary& dict) const
1094
{
12✔
1095
    return Query(m_own_ref, dict.clone_as_obj_list());
12✔
1096
}
12✔
1097

1098
void Table::set_table_type(Type table_type, bool handle_backlinks)
1099
{
312✔
1100
    if (table_type == m_table_type) {
312✔
1101
        return;
×
1102
    }
×
1103

1104
    if (m_table_type == Type::TopLevelAsymmetric || table_type == Type::TopLevelAsymmetric) {
312✔
1105
        throw LogicError(ErrorCodes::MigrationFailed, util::format("Cannot change '%1' from %2 to %3",
×
1106
                                                                   get_class_name(), m_table_type, table_type));
×
1107
    }
×
1108

1109
    REALM_ASSERT_EX(table_type == Type::TopLevel || table_type == Type::Embedded, table_type);
312✔
1110
    set_embedded(table_type == Type::Embedded, handle_backlinks);
312✔
1111
}
312✔
1112

1113
void Table::set_embedded(bool embedded, bool handle_backlinks)
1114
{
312✔
1115
    if (embedded == false) {
312✔
1116
        do_set_table_type(Type::TopLevel);
24✔
1117
        return;
24✔
1118
    }
24✔
1119

1120
    // Embedded objects cannot have a primary key.
1121
    if (get_primary_key_column()) {
288✔
1122
        throw IllegalOperation(
6✔
1123
            util::format("Cannot change '%1' to embedded when using a primary key.", get_class_name()));
6✔
1124
    }
6✔
1125

1126
    if (size() == 0) {
282✔
1127
        do_set_table_type(Type::Embedded);
42✔
1128
        return;
42✔
1129
    }
42✔
1130

1131
    // Check all of the objects for invalid incoming links. Each embedded object
1132
    // must have exactly one incoming link, and it must be from a non-Mixed property.
1133
    // Objects with no incoming links are either deleted or an error (depending
1134
    // on `handle_backlinks`), and objects with multiple incoming links are either
1135
    // cloned for each of the incoming links or an error (again depending on `handle_backlinks`).
1136
    // Incoming links from a Mixed property are always an error, as those can't
1137
    // link to embedded objects
1138
    ArrayInteger leaf(get_alloc());
240✔
1139
    enum class LinkCount : int8_t { None, One, Multiple };
240✔
1140
    std::vector<LinkCount> incoming_link_count;
240✔
1141
    std::vector<ObjKey> orphans;
240✔
1142
    std::vector<ObjKey> multiple_incoming_links;
240✔
1143
    traverse_clusters([&](const Cluster* cluster) {
474✔
1144
        size_t size = cluster->node_size();
474✔
1145
        incoming_link_count.assign(size, LinkCount::None);
474✔
1146

1147
        for_each_backlink_column([&](ColKey col) {
606✔
1148
            cluster->init_leaf(col, &leaf);
606✔
1149
            // Width zero means all the values are zero and there can't be any backlinks
1150
            if (leaf.get_width() == 0) {
606✔
1151
                return IteratorControl::AdvanceToNext;
36✔
1152
            }
36✔
1153

1154
            for (size_t i = 0, size = leaf.size(); i < size; ++i) {
60,816✔
1155
                auto value = leaf.get_as_ref_or_tagged(i);
60,300✔
1156
                if (value.is_ref() && value.get_as_ref() == 0) {
60,300✔
1157
                    // ref of zero means there's no backlinks
1158
                    continue;
59,340✔
1159
                }
59,340✔
1160

1161
                if (value.is_ref()) {
960✔
1162
                    // Any other ref indicates an array of backlinks, which will
1163
                    // always have more than one entry
1164
                    incoming_link_count[i] = LinkCount::Multiple;
78✔
1165
                }
78✔
1166
                else {
882✔
1167
                    // Otherwise it's a tagged ref to the single linking object
1168
                    if (incoming_link_count[i] == LinkCount::None) {
882✔
1169
                        incoming_link_count[i] = LinkCount::One;
792✔
1170
                    }
792✔
1171
                    else if (incoming_link_count[i] == LinkCount::One) {
90✔
1172
                        incoming_link_count[i] = LinkCount::Multiple;
42✔
1173
                    }
42✔
1174
                }
882✔
1175

1176
                auto source_col = get_opposite_column(col);
960✔
1177
                if (source_col.get_type() == col_type_Mixed) {
960✔
1178
                    auto source_table = get_opposite_table(col);
54✔
1179
                    throw IllegalOperation(util::format(
54✔
1180
                        "Cannot convert '%1' to embedded: there is an incoming link from the Mixed property '%2.%3', "
54✔
1181
                        "which does not support linking to embedded objects.",
54✔
1182
                        get_class_name(), source_table->get_class_name(), source_table->get_column_name(source_col)));
54✔
1183
                }
54✔
1184
            }
960✔
1185
            return IteratorControl::AdvanceToNext;
516✔
1186
        });
570✔
1187

1188
        for (size_t i = 0; i < size; ++i) {
60,660✔
1189
            if (incoming_link_count[i] == LinkCount::None) {
60,240✔
1190
                if (!handle_backlinks) {
59,424✔
1191
                    throw IllegalOperation(util::format("Cannot convert '%1' to embedded: at least one object has no "
18✔
1192
                                                        "incoming links and would be deleted.",
18✔
1193
                                                        get_class_name()));
18✔
1194
                }
18✔
1195
                orphans.push_back(cluster->get_real_key(i));
59,406✔
1196
            }
59,406✔
1197
            else if (incoming_link_count[i] == LinkCount::Multiple) {
816✔
1198
                if (!handle_backlinks) {
90✔
1199
                    throw IllegalOperation(util::format(
36✔
1200
                        "Cannot convert '%1' to embedded: at least one object has more than one incoming link.",
36✔
1201
                        get_class_name()));
36✔
1202
                }
36✔
1203
                multiple_incoming_links.push_back(cluster->get_real_key(i));
54✔
1204
            }
54✔
1205
        }
60,240✔
1206

1207
        return IteratorControl::AdvanceToNext;
420✔
1208
    });
474✔
1209

1210
    // orphans and multiple_incoming_links will always be empty if `handle_backlinks = false`
1211
    for (auto key : orphans) {
59,406✔
1212
        remove_object(key);
59,406✔
1213
    }
59,406✔
1214
    for (auto key : multiple_incoming_links) {
240✔
1215
        auto obj = get_object(key);
54✔
1216
        obj.handle_multiple_backlinks_during_schema_migration();
54✔
1217
        obj.remove();
54✔
1218
    }
54✔
1219

1220
    do_set_table_type(Type::Embedded);
240✔
1221
}
240✔
1222

1223
void Table::do_set_table_type(Type table_type)
1224
{
267,126✔
1225
    while (m_top.size() <= top_position_for_flags)
267,126✔
1226
        m_top.add(0);
×
1227

1228
    uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
267,126✔
1229
    // reset bits 0-1
1230
    flags &= ~table_type_mask;
267,126✔
1231
    // set table type
1232
    flags |= static_cast<uint8_t>(table_type);
267,126✔
1233
    m_top.set(top_position_for_flags, RefOrTagged::make_tagged(flags));
267,126✔
1234
    m_table_type = table_type;
267,126✔
1235
}
267,126✔
1236

1237

1238
void Table::detach(LifeCycleCookie cookie) noexcept
1239
{
1,953,897✔
1240
    m_cookie = cookie;
1,953,897✔
1241
    m_alloc.bump_instance_version();
1,953,897✔
1242
}
1,953,897✔
1243

1244
void Table::fully_detach() noexcept
1245
{
1,937,271✔
1246
    m_spec.detach();
1,937,271✔
1247
    m_top.detach();
1,937,271✔
1248
    m_index_refs.detach();
1,937,271✔
1249
    m_opposite_table.detach();
1,937,271✔
1250
    m_opposite_column.detach();
1,937,271✔
1251
    m_index_accessors.clear();
1,937,271✔
1252
}
1,937,271✔
1253

1254

1255
Table::~Table() noexcept
1256
{
3,552✔
1257
    if (m_top.is_attached()) {
3,552✔
1258
        // If destroyed as a standalone table, destroy all memory allocated
1259
        if (m_top.get_parent() == nullptr) {
3,552✔
1260
            m_top.destroy_deep();
3,552✔
1261
        }
3,552✔
1262
        fully_detach();
3,552✔
1263
    }
3,552✔
1264
    else {
×
1265
        REALM_ASSERT(m_index_accessors.size() == 0);
×
1266
    }
×
1267
    m_cookie = cookie_deleted;
3,552✔
1268
}
3,552✔
1269

1270

1271
IndexType Table::search_index_type(ColKey col_key) const noexcept
1272
{
4,819,209✔
1273
    if (m_index_accessors[col_key.get_index().val].get()) {
4,819,209✔
1274
        auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_key.get_index().val]);
1,171,896✔
1275
        bool fulltext = attr.test(col_attr_FullText_Indexed);
1,171,896✔
1276
        return fulltext ? IndexType::Fulltext : IndexType::General;
1,171,896✔
1277
    }
1,171,896✔
1278
    return IndexType::None;
3,647,313✔
1279
}
4,819,209✔
1280

1281

1282
void Table::migrate_sets_and_dictionaries()
1283
{
180✔
1284
    std::vector<ColKey> to_migrate;
180✔
1285
    for (auto col : get_column_keys()) {
570✔
1286
        if (col.is_dictionary() || (col.is_set() && col.get_type() == col_type_Mixed)) {
570✔
1287
            to_migrate.push_back(col);
12✔
1288
        }
12✔
1289
    }
570✔
1290
    if (to_migrate.size()) {
180✔
1291
        for (auto obj : *this) {
6✔
1292
            for (auto col : to_migrate) {
12✔
1293
                if (col.is_set()) {
12✔
1294
                    auto set = obj.get_set<Mixed>(col);
6✔
1295
                    set.migrate();
6✔
1296
                }
6✔
1297
                else if (col.is_dictionary()) {
6✔
1298
                    auto dict = obj.get_dictionary(col);
6✔
1299
                    dict.migrate();
6✔
1300
                }
6✔
1301
            }
12✔
1302
        }
6✔
1303
    }
6✔
1304
}
180✔
1305

1306
void Table::migrate_set_orderings()
1307
{
354✔
1308
    std::vector<ColKey> to_migrate;
354✔
1309
    for (auto col : get_column_keys()) {
918✔
1310
        if (col.is_set() && (col.get_type() == col_type_Mixed || col.get_type() == col_type_String ||
918✔
1311
                             col.get_type() == col_type_Binary)) {
30✔
1312
            to_migrate.push_back(col);
30✔
1313
        }
30✔
1314
    }
918✔
1315
    if (to_migrate.size()) {
354✔
1316
        for (auto obj : *this) {
90✔
1317
            for (auto col : to_migrate) {
102✔
1318
                if (col.get_type() == col_type_Mixed) {
102✔
1319
                    auto set = obj.get_set<Mixed>(col);
12✔
1320
                    set.migration_resort();
12✔
1321
                }
12✔
1322
                else if (col.get_type() == col_type_Binary) {
90✔
1323
                    auto set = obj.get_set<BinaryData>(col);
6✔
1324
                    set.migration_resort();
6✔
1325
                }
6✔
1326
                else {
84✔
1327
                    REALM_ASSERT_3(col.get_type(), ==, col_type_String);
84✔
1328
                    auto set = obj.get_set<String>(col);
84✔
1329
                    set.migration_resort();
84✔
1330
                }
84✔
1331
            }
102✔
1332
        }
90✔
1333
    }
18✔
1334
}
354✔
1335

1336
void Table::migrate_col_keys()
1337
{
354✔
1338
    if (m_spec.migrate_column_keys()) {
354✔
1339
        build_column_mapping();
24✔
1340
    }
24✔
1341

1342
    // Fix also m_opposite_column col_keys
1343
    ColumnType col_type_LinkList(13);
354✔
1344
    auto sz = m_opposite_column.size();
354✔
1345

1346
    for (size_t n = 0; n < sz; n++) {
1,386✔
1347
        ColKey col_key(m_opposite_column.get(n));
1,032✔
1348
        if (col_key.get_type() == col_type_LinkList) {
1,032✔
1349
            auto attrs = col_key.get_attrs();
24✔
1350
            REALM_ASSERT(attrs.test(col_attr_List));
24✔
1351
            ColKey new_key(col_key.get_index(), col_type_Link, attrs, col_key.get_tag());
24✔
1352
            m_opposite_column.set(n, new_key.value);
24✔
1353
        }
24✔
1354
    }
1,032✔
1355
}
354✔
1356

1357
StringData Table::get_name() const noexcept
1358
{
3,098,286✔
1359
    const Array& real_top = m_top;
3,098,286✔
1360
    ArrayParent* parent = real_top.get_parent();
3,098,286✔
1361
    if (!parent)
3,098,286✔
1362
        return StringData("");
54✔
1363
    REALM_ASSERT(dynamic_cast<Group*>(parent));
3,098,232✔
1364
    return static_cast<Group*>(parent)->get_table_name(get_key());
3,098,232✔
1365
}
3,098,286✔
1366

1367
StringData Table::get_class_name() const noexcept
1368
{
672,645✔
1369
    return Group::table_name_to_class_name(get_name());
672,645✔
1370
}
672,645✔
1371

1372
const char* Table::get_state() const noexcept
1373
{
42✔
1374
    switch (m_cookie) {
42✔
1375
        case cookie_created:
✔
1376
            return "created";
×
1377
        case cookie_transaction_ended:
6✔
1378
            return "transaction_ended";
6✔
1379
        case cookie_initialized:
✔
1380
            return "initialised";
×
1381
        case cookie_removed:
36✔
1382
            return "removed";
36✔
1383
        case cookie_void:
✔
1384
            return "void";
×
1385
        case cookie_deleted:
✔
1386
            return "deleted";
×
1387
    }
42✔
1388
    return "";
×
1389
}
42✔
1390

1391

1392
bool Table::is_nullable(ColKey col_key) const
1393
{
751,326✔
1394
    REALM_ASSERT_DEBUG(valid_column(col_key));
751,326✔
1395
    return col_key.get_attrs().test(col_attr_Nullable);
751,326✔
1396
}
751,326✔
1397

1398
bool Table::is_list(ColKey col_key) const
1399
{
27,771✔
1400
    REALM_ASSERT_DEBUG(valid_column(col_key));
27,771✔
1401
    return col_key.get_attrs().test(col_attr_List);
27,771✔
1402
}
27,771✔
1403

1404

1405
ref_type Table::create_empty_table(Allocator& alloc, TableKey key)
1406
{
270,483✔
1407
    Array top(alloc);
270,483✔
1408
    _impl::DeepArrayDestroyGuard dg(&top);
270,483✔
1409
    top.create(Array::type_HasRefs); // Throws
270,483✔
1410
    _impl::DeepArrayRefDestroyGuard dg_2(alloc);
270,483✔
1411

1412
    {
270,483✔
1413
        MemRef mem = Spec::create_empty_spec(alloc); // Throws
270,483✔
1414
        dg_2.reset(mem.get_ref());
270,483✔
1415
        int_fast64_t v(from_ref(mem.get_ref()));
270,483✔
1416
        top.add(v); // Throws
270,483✔
1417
        dg_2.release();
270,483✔
1418
    }
270,483✔
1419
    top.add(0); // Old position for columns
270,483✔
1420
    {
270,483✔
1421
        MemRef mem = Cluster::create_empty_cluster(alloc); // Throws
270,483✔
1422
        dg_2.reset(mem.get_ref());
270,483✔
1423
        int_fast64_t v(from_ref(mem.get_ref()));
270,483✔
1424
        top.add(v); // Throws
270,483✔
1425
        dg_2.release();
270,483✔
1426
    }
270,483✔
1427

1428
    // Table key value
1429
    RefOrTagged rot = RefOrTagged::make_tagged(key.value);
270,483✔
1430
    top.add(rot);
270,483✔
1431

1432
    // Search indexes
1433
    {
270,483✔
1434
        bool context_flag = false;
270,483✔
1435
        MemRef mem = Array::create_empty_array(Array::type_HasRefs, context_flag, alloc); // Throws
270,483✔
1436
        dg_2.reset(mem.get_ref());
270,483✔
1437
        int_fast64_t v(from_ref(mem.get_ref()));
270,483✔
1438
        top.add(v); // Throws
270,483✔
1439
        dg_2.release();
270,483✔
1440
    }
270,483✔
1441
    rot = RefOrTagged::make_tagged(0);
270,483✔
1442
    top.add(rot); // Column key
270,483✔
1443
    top.add(rot); // Version
270,483✔
1444
    dg.release();
270,483✔
1445
    // Opposite keys (table and column)
1446
    {
270,483✔
1447
        bool context_flag = false;
270,483✔
1448
        {
270,483✔
1449
            MemRef mem = Array::create_empty_array(Array::type_Normal, context_flag, alloc); // Throws
270,483✔
1450
            dg_2.reset(mem.get_ref());
270,483✔
1451
            int_fast64_t v(from_ref(mem.get_ref()));
270,483✔
1452
            top.add(v); // Throws
270,483✔
1453
            dg_2.release();
270,483✔
1454
        }
270,483✔
1455
        {
270,483✔
1456
            MemRef mem = Array::create_empty_array(Array::type_Normal, context_flag, alloc); // Throws
270,483✔
1457
            dg_2.reset(mem.get_ref());
270,483✔
1458
            int_fast64_t v(from_ref(mem.get_ref()));
270,483✔
1459
            top.add(v); // Throws
270,483✔
1460
            dg_2.release();
270,483✔
1461
        }
270,483✔
1462
    }
270,483✔
1463
    top.add(0); // Sequence number
270,483✔
1464
    top.add(0); // Collision_map
270,483✔
1465
    top.add(0); // pk col key
270,483✔
1466
    top.add(0); // flags
270,483✔
1467
    top.add(0); // tombstones
270,483✔
1468

1469
    REALM_ASSERT(top.size() == top_array_size);
270,483✔
1470

1471
    return top.get_ref();
270,483✔
1472
}
270,483✔
1473

1474
void Table::ensure_graveyard()
1475
{
12,894✔
1476
    if (!m_tombstones) {
12,894✔
1477
        while (m_top.size() < top_position_for_tombstones)
2,217✔
1478
            m_top.add(0);
×
1479
        REALM_ASSERT(!m_top.get(top_position_for_tombstones));
2,217✔
1480
        MemRef mem = Cluster::create_empty_cluster(m_alloc);
2,217✔
1481
        m_top.set_as_ref(top_position_for_tombstones, mem.get_ref());
2,217✔
1482
        m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
2,217✔
1483
        m_tombstones->init_from_parent();
2,217✔
1484
        for_each_and_every_column([ts = m_tombstones.get()](ColKey col) {
7,617✔
1485
            ts->insert_column(col);
7,617✔
1486
            return IteratorControl::AdvanceToNext;
7,617✔
1487
        });
7,617✔
1488
    }
2,217✔
1489
}
12,894✔
1490

1491
void Table::batch_erase_rows(const KeyColumn& keys)
1492
{
558✔
1493
    size_t num_objs = keys.size();
558✔
1494
    std::vector<ObjKey> vec;
558✔
1495
    vec.reserve(num_objs);
558✔
1496
    for (size_t i = 0; i < num_objs; ++i) {
2,898✔
1497
        ObjKey key = keys.get(i);
2,340✔
1498
        if (key != null_key && is_valid(key)) {
2,340✔
1499
            vec.push_back(key);
2,340✔
1500
        }
2,340✔
1501
    }
2,340✔
1502

1503
    sort(vec.begin(), vec.end());
558✔
1504
    vec.erase(unique(vec.begin(), vec.end()), vec.end());
558✔
1505

1506
    batch_erase_objects(vec);
558✔
1507
}
558✔
1508

1509
void Table::batch_erase_objects(std::vector<ObjKey>& keys)
1510
{
6,834✔
1511
    Group* g = get_parent_group();
6,834✔
1512
    bool maybe_has_incoming_links = g && !is_asymmetric();
6,834✔
1513

1514
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
6,834✔
1515
        CascadeState state(CascadeState::Mode::Strong, g);
6,066✔
1516
        std::for_each(keys.begin(), keys.end(), [this, &state](ObjKey k) {
6,066✔
1517
            state.m_to_be_deleted.emplace_back(m_key, k);
1,755✔
1518
        });
1,755✔
1519
        if (maybe_has_incoming_links)
6,066✔
1520
            nullify_links(state);
6,066✔
1521
        remove_recursive(state);
6,066✔
1522
    }
6,066✔
1523
    else {
768✔
1524
        CascadeState state(CascadeState::Mode::None, g);
768✔
1525
        for (auto k : keys) {
2,512,302✔
1526
            if (maybe_has_incoming_links) {
2,512,302✔
1527
                m_clusters.nullify_incoming_links(k, state);
2,512,224✔
1528
            }
2,512,224✔
1529
            m_clusters.erase(k, state);
2,512,302✔
1530
        }
2,512,302✔
1531
    }
768✔
1532
    keys.clear();
6,834✔
1533
}
6,834✔
1534

1535
void Table::clear()
1536
{
5,994✔
1537
    CascadeState state(CascadeState::Mode::Strong, get_parent_group());
5,994✔
1538
    m_clusters.clear(state);
5,994✔
1539
    free_collision_table();
5,994✔
1540
}
5,994✔
1541

1542

1543
Group* Table::get_parent_group() const noexcept
1544
{
60,532,620✔
1545
    if (!m_top.is_attached())
60,532,620✔
1546
        return 0;                             // Subtable with shared descriptor
×
1547
    ArrayParent* parent = m_top.get_parent(); // ArrayParent guaranteed to be Table::Parent
60,532,620✔
1548
    if (!parent)
60,532,620✔
1549
        return 0; // Free-standing table
25,823,643✔
1550

1551
    return static_cast<Group*>(parent);
34,708,977✔
1552
}
60,532,620✔
1553

1554
inline uint64_t Table::get_sync_file_id() const noexcept
1555
{
39,087,198✔
1556
    Group* g = get_parent_group();
39,087,198✔
1557
    return g ? g->get_sync_file_id() : 0;
39,087,198✔
1558
}
39,087,198✔
1559

1560
size_t Table::get_index_in_group() const noexcept
1561
{
30✔
1562
    if (!m_top.is_attached())
30✔
1563
        return realm::npos;                   // Subtable with shared descriptor
×
1564
    ArrayParent* parent = m_top.get_parent(); // ArrayParent guaranteed to be Table::Parent
30✔
1565
    if (!parent)
30✔
1566
        return realm::npos; // Free-standing table
×
1567
    return m_top.get_ndx_in_parent();
30✔
1568
}
30✔
1569

1570
uint64_t Table::allocate_sequence_number()
1571
{
20,308,740✔
1572
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_sequence_number);
20,308,740✔
1573
    uint64_t sn = rot.is_tagged() ? rot.get_as_int() : 0;
20,308,740✔
1574
    rot = RefOrTagged::make_tagged(sn + 1);
20,308,740✔
1575
    m_top.set(top_position_for_sequence_number, rot);
20,308,740✔
1576

1577
    return sn;
20,308,740✔
1578
}
20,308,740✔
1579

1580
void Table::set_sequence_number(uint64_t seq)
1581
{
×
1582
    m_top.set(top_position_for_sequence_number, RefOrTagged::make_tagged(seq));
×
1583
}
×
1584

1585
void Table::set_collision_map(ref_type ref)
1586
{
×
1587
    m_top.set(top_position_for_collision_map, RefOrTagged::make_ref(ref));
×
1588
}
×
1589

1590
void Table::set_col_key_sequence_number(uint64_t seq)
1591
{
24✔
1592
    m_top.set(top_position_for_column_key, RefOrTagged::make_tagged(seq));
24✔
1593
}
24✔
1594

1595
TableRef Table::get_link_target(ColKey col_key) noexcept
1596
{
273,438✔
1597
    return get_opposite_table(col_key);
273,438✔
1598
}
273,438✔
1599

1600
// count ----------------------------------------------
1601

1602
size_t Table::count_int(ColKey col_key, int64_t value) const
1603
{
12,006✔
1604
    if (auto index = this->get_search_index(col_key)) {
12,006✔
1605
        return index->count(value);
12,000✔
1606
    }
12,000✔
1607

1608
    return where().equal(col_key, value).count();
6✔
1609
}
12,006✔
1610
size_t Table::count_float(ColKey col_key, float value) const
1611
{
6✔
1612
    return where().equal(col_key, value).count();
6✔
1613
}
6✔
1614
size_t Table::count_double(ColKey col_key, double value) const
1615
{
6✔
1616
    return where().equal(col_key, value).count();
6✔
1617
}
6✔
1618
size_t Table::count_decimal(ColKey col_key, Decimal128 value) const
1619
{
18✔
1620
    ArrayDecimal128 leaf(get_alloc());
18✔
1621
    size_t cnt = 0;
18✔
1622
    bool null_value = value.is_null();
18✔
1623
    auto f = [value, &leaf, col_key, null_value, &cnt](const Cluster* cluster) {
18✔
1624
        // direct aggregate on the leaf
1625
        cluster->init_leaf(col_key, &leaf);
18✔
1626
        auto sz = leaf.size();
18✔
1627
        for (size_t i = 0; i < sz; i++) {
1,296✔
1628
            if ((null_value && leaf.is_null(i)) || (leaf.get(i) == value)) {
1,278!
1629
                cnt++;
24✔
1630
            }
24✔
1631
        }
1,278✔
1632
        return IteratorControl::AdvanceToNext;
18✔
1633
    };
18✔
1634

1635
    traverse_clusters(f);
18✔
1636

1637
    return cnt;
18✔
1638
}
18✔
1639
size_t Table::count_string(ColKey col_key, StringData value) const
1640
{
1,476✔
1641
    if (auto index = this->get_search_index(col_key)) {
1,476✔
1642
        return index->count(value);
732✔
1643
    }
732✔
1644
    return where().equal(col_key, value).count();
744✔
1645
}
1,476✔
1646

1647
template <typename T>
1648
void Table::aggregate(QueryStateBase& st, ColKey column_key) const
1649
{
34,881✔
1650
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
34,881✔
1651
    LeafType leaf(get_alloc());
34,881✔
1652

1653
    auto f = [&leaf, column_key, &st](const Cluster* cluster) {
34,902✔
1654
        // direct aggregate on the leaf
1655
        cluster->init_leaf(column_key, &leaf);
34,902✔
1656
        st.m_key_offset = cluster->get_offset();
34,902✔
1657
        st.m_key_values = cluster->get_key_array();
34,902✔
1658
        st.set_payload_column(&leaf);
34,902✔
1659
        bool cont = true;
34,902✔
1660
        size_t sz = leaf.size();
34,902✔
1661
        for (size_t local_index = 0; cont && local_index < sz; local_index++) {
138,654✔
1662
            cont = st.match(local_index);
103,752✔
1663
        }
103,752✔
1664
        return IteratorControl::AdvanceToNext;
34,902✔
1665
    };
34,902✔
1666

1667
    traverse_clusters(f);
34,881✔
1668
}
34,881✔
1669

1670
// This template is also used by the query engine
1671
template void Table::aggregate<int64_t>(QueryStateBase&, ColKey) const;
1672
template void Table::aggregate<std::optional<int64_t>>(QueryStateBase&, ColKey) const;
1673
template void Table::aggregate<float>(QueryStateBase&, ColKey) const;
1674
template void Table::aggregate<double>(QueryStateBase&, ColKey) const;
1675
template void Table::aggregate<Decimal128>(QueryStateBase&, ColKey) const;
1676
template void Table::aggregate<Mixed>(QueryStateBase&, ColKey) const;
1677
template void Table::aggregate<Timestamp>(QueryStateBase&, ColKey) const;
1678

1679
std::optional<Mixed> Table::sum(ColKey col_key) const
1680
{
756✔
1681
    return AggregateHelper<Table>::sum(*this, *this, col_key);
756✔
1682
}
756✔
1683

1684
std::optional<Mixed> Table::avg(ColKey col_key, size_t* value_count) const
1685
{
822✔
1686
    return AggregateHelper<Table>::avg(*this, *this, col_key, value_count);
822✔
1687
}
822✔
1688

1689
std::optional<Mixed> Table::min(ColKey col_key, ObjKey* return_ndx) const
1690
{
1,170✔
1691
    return AggregateHelper<Table>::min(*this, *this, col_key, return_ndx);
1,170✔
1692
}
1,170✔
1693

1694
std::optional<Mixed> Table::max(ColKey col_key, ObjKey* return_ndx) const
1695
{
28,605✔
1696
    return AggregateHelper<Table>::max(*this, *this, col_key, return_ndx);
28,605✔
1697
}
28,605✔
1698

1699

1700
SearchIndex* Table::get_search_index(ColKey col) const noexcept
1701
{
29,647,167✔
1702
    check_column(col);
29,647,167✔
1703
    return m_index_accessors[col.get_index().val].get();
29,647,167✔
1704
}
29,647,167✔
1705

1706
StringIndex* Table::get_string_index(ColKey col) const noexcept
1707
{
689,976✔
1708
    check_column(col);
689,976✔
1709
    return dynamic_cast<StringIndex*>(m_index_accessors[col.get_index().val].get());
689,976✔
1710
}
689,976✔
1711

1712
template <class T>
1713
ObjKey Table::find_first(ColKey col_key, T value) const
1714
{
34,983✔
1715
    check_column(col_key);
34,983✔
1716

1717
    if (!col_key.is_nullable() && value_is_null(value)) {
34,983!
1718
        return {}; // this is a precaution/optimization
6✔
1719
    }
6✔
1720
    // You cannot call GetIndexData on ObjKey
1721
    if constexpr (!std::is_same_v<T, ObjKey>) {
34,977✔
1722
        if (SearchIndex* index = get_search_index(col_key)) {
34,959✔
1723
            return index->find_first(value);
27,111✔
1724
        }
27,111✔
1725
        if (col_key == m_primary_key_col) {
7,848✔
1726
            return find_primary_key(value);
×
1727
        }
×
1728
    }
7,848✔
1729

1730
    ObjKey key;
7,848✔
1731
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
21,288✔
1732
    LeafType leaf(get_alloc());
21,288✔
1733

1734
    auto f = [&key, &col_key, &value, &leaf](const Cluster* cluster) {
22,029✔
1735
        cluster->init_leaf(col_key, &leaf);
9,330✔
1736
        size_t row = leaf.find_first(value, 0, cluster->node_size());
9,330✔
1737
        if (row != realm::npos) {
9,330✔
1738
            key = cluster->get_real_key(row);
7,692✔
1739
            return IteratorControl::Stop;
7,692✔
1740
        }
7,692✔
1741
        return IteratorControl::AdvanceToNext;
1,638✔
1742
    };
9,330✔
1743

1744
    traverse_clusters(f);
21,288✔
1745

1746
    return key;
21,288✔
1747
}
34,971✔
1748

1749
namespace realm {
1750

1751
template <>
1752
ObjKey Table::find_first(ColKey col_key, util::Optional<float> value) const
1753
{
×
1754
    return value ? find_first(col_key, *value) : find_first_null(col_key);
×
1755
}
×
1756

1757
template <>
1758
ObjKey Table::find_first(ColKey col_key, util::Optional<double> value) const
1759
{
×
1760
    return value ? find_first(col_key, *value) : find_first_null(col_key);
×
1761
}
×
1762

1763
template <>
1764
ObjKey Table::find_first(ColKey col_key, null) const
1765
{
×
1766
    return find_first_null(col_key);
×
1767
}
×
1768
} // namespace realm
1769

1770
// Explicitly instantiate the generic case of the template for the types we care about.
1771
template ObjKey Table::find_first(ColKey col_key, bool) const;
1772
template ObjKey Table::find_first(ColKey col_key, int64_t) const;
1773
template ObjKey Table::find_first(ColKey col_key, float) const;
1774
template ObjKey Table::find_first(ColKey col_key, double) const;
1775
template ObjKey Table::find_first(ColKey col_key, Decimal128) const;
1776
template ObjKey Table::find_first(ColKey col_key, ObjectId) const;
1777
template ObjKey Table::find_first(ColKey col_key, ObjKey) const;
1778
template ObjKey Table::find_first(ColKey col_key, util::Optional<bool>) const;
1779
template ObjKey Table::find_first(ColKey col_key, util::Optional<int64_t>) const;
1780
template ObjKey Table::find_first(ColKey col_key, StringData) const;
1781
template ObjKey Table::find_first(ColKey col_key, BinaryData) const;
1782
template ObjKey Table::find_first(ColKey col_key, Mixed) const;
1783
template ObjKey Table::find_first(ColKey col_key, UUID) const;
1784
template ObjKey Table::find_first(ColKey col_key, util::Optional<ObjectId>) const;
1785
template ObjKey Table::find_first(ColKey col_key, util::Optional<UUID>) const;
1786

1787
ObjKey Table::find_first_int(ColKey col_key, int64_t value) const
1788
{
7,698✔
1789
    if (is_nullable(col_key))
7,698✔
1790
        return find_first<util::Optional<int64_t>>(col_key, value);
36✔
1791
    else
7,662✔
1792
        return find_first<int64_t>(col_key, value);
7,662✔
1793
}
7,698✔
1794

1795
ObjKey Table::find_first_bool(ColKey col_key, bool value) const
1796
{
78✔
1797
    if (is_nullable(col_key))
78✔
1798
        return find_first<util::Optional<bool>>(col_key, value);
36✔
1799
    else
42✔
1800
        return find_first<bool>(col_key, value);
42✔
1801
}
78✔
1802

1803
ObjKey Table::find_first_timestamp(ColKey col_key, Timestamp value) const
1804
{
108✔
1805
    return find_first(col_key, value);
108✔
1806
}
108✔
1807

1808
ObjKey Table::find_first_object_id(ColKey col_key, ObjectId value) const
1809
{
6✔
1810
    return find_first(col_key, value);
6✔
1811
}
6✔
1812

1813
ObjKey Table::find_first_float(ColKey col_key, float value) const
1814
{
12✔
1815
    return find_first<Float>(col_key, value);
12✔
1816
}
12✔
1817

1818
ObjKey Table::find_first_double(ColKey col_key, double value) const
1819
{
12✔
1820
    return find_first<Double>(col_key, value);
12✔
1821
}
12✔
1822

1823
ObjKey Table::find_first_decimal(ColKey col_key, Decimal128 value) const
1824
{
×
1825
    return find_first<Decimal128>(col_key, value);
×
1826
}
×
1827

1828
ObjKey Table::find_first_string(ColKey col_key, StringData value) const
1829
{
11,349✔
1830
    return find_first<StringData>(col_key, value);
11,349✔
1831
}
11,349✔
1832

1833
ObjKey Table::find_first_binary(ColKey col_key, BinaryData value) const
1834
{
×
1835
    return find_first<BinaryData>(col_key, value);
×
1836
}
×
1837

1838
ObjKey Table::find_first_null(ColKey col_key) const
1839
{
114✔
1840
    return where().equal(col_key, null{}).find();
114✔
1841
}
114✔
1842

1843
ObjKey Table::find_first_uuid(ColKey col_key, UUID value) const
1844
{
18✔
1845
    return find_first(col_key, value);
18✔
1846
}
18✔
1847

1848
template <class T>
1849
TableView Table::find_all(ColKey col_key, T value)
1850
{
108✔
1851
    return where().equal(col_key, value).find_all();
108✔
1852
}
108✔
1853

1854
TableView Table::find_all_int(ColKey col_key, int64_t value)
1855
{
102✔
1856
    return find_all<int64_t>(col_key, value);
102✔
1857
}
102✔
1858

1859
TableView Table::find_all_int(ColKey col_key, int64_t value) const
1860
{
×
1861
    return const_cast<Table*>(this)->find_all<int64_t>(col_key, value);
×
1862
}
×
1863

1864
TableView Table::find_all_bool(ColKey col_key, bool value)
1865
{
×
1866
    return find_all<bool>(col_key, value);
×
1867
}
×
1868

1869
TableView Table::find_all_bool(ColKey col_key, bool value) const
1870
{
×
1871
    return const_cast<Table*>(this)->find_all<int64_t>(col_key, value);
×
1872
}
×
1873

1874

1875
TableView Table::find_all_float(ColKey col_key, float value)
1876
{
×
1877
    return find_all<float>(col_key, value);
×
1878
}
×
1879

1880
TableView Table::find_all_float(ColKey col_key, float value) const
1881
{
×
1882
    return const_cast<Table*>(this)->find_all<float>(col_key, value);
×
1883
}
×
1884

1885
TableView Table::find_all_double(ColKey col_key, double value)
1886
{
6✔
1887
    return find_all<double>(col_key, value);
6✔
1888
}
6✔
1889

1890
TableView Table::find_all_double(ColKey col_key, double value) const
1891
{
×
1892
    return const_cast<Table*>(this)->find_all<double>(col_key, value);
×
1893
}
×
1894

1895
TableView Table::find_all_string(ColKey col_key, StringData value)
1896
{
282✔
1897
    return where().equal(col_key, value).find_all();
282✔
1898
}
282✔
1899

1900
TableView Table::find_all_string(ColKey col_key, StringData value) const
1901
{
×
1902
    return const_cast<Table*>(this)->find_all_string(col_key, value);
×
1903
}
×
1904

1905
TableView Table::find_all_binary(ColKey, BinaryData)
1906
{
×
1907
    throw Exception(ErrorCodes::IllegalOperation, "Table::find_all_binary not supported");
×
1908
}
×
1909

1910
TableView Table::find_all_binary(ColKey col_key, BinaryData value) const
1911
{
×
1912
    return const_cast<Table*>(this)->find_all_binary(col_key, value);
×
1913
}
×
1914

1915
TableView Table::find_all_null(ColKey col_key)
1916
{
×
1917
    return where().equal(col_key, null{}).find_all();
×
1918
}
×
1919

1920
TableView Table::find_all_null(ColKey col_key) const
1921
{
×
1922
    return const_cast<Table*>(this)->find_all_null(col_key);
×
1923
}
×
1924

1925
TableView Table::find_all_fulltext(ColKey col_key, StringData terms) const
1926
{
6✔
1927
    return where().fulltext(col_key, terms).find_all();
6✔
1928
}
6✔
1929

1930
TableView Table::get_sorted_view(ColKey col_key, bool ascending)
1931
{
72✔
1932
    TableView tv = where().find_all();
72✔
1933
    tv.sort(col_key, ascending);
72✔
1934
    return tv;
72✔
1935
}
72✔
1936

1937
TableView Table::get_sorted_view(ColKey col_key, bool ascending) const
1938
{
6✔
1939
    return const_cast<Table*>(this)->get_sorted_view(col_key, ascending);
6✔
1940
}
6✔
1941

1942
TableView Table::get_sorted_view(SortDescriptor order)
1943
{
126✔
1944
    TableView tv = where().find_all();
126✔
1945
    tv.sort(std::move(order));
126✔
1946
    return tv;
126✔
1947
}
126✔
1948

1949
TableView Table::get_sorted_view(SortDescriptor order) const
1950
{
×
1951
    return const_cast<Table*>(this)->get_sorted_view(std::move(order));
×
1952
}
×
1953

1954
util::Logger* Table::get_logger() const noexcept
1955
{
1,877,649✔
1956
    return *m_repl ? (*m_repl)->get_logger() : nullptr;
1,877,649✔
1957
}
1,877,649✔
1958

1959
// Called after a commit. Table will effectively contain the same as before,
1960
// but now with new refs from the file
1961
void Table::update_from_parent() noexcept
1962
{
702,804✔
1963
    // There is no top for sub-tables sharing spec
1964
    if (m_top.is_attached()) {
702,804✔
1965
        m_top.update_from_parent();
702,801✔
1966
        m_spec.update_from_parent();
702,801✔
1967
        m_clusters.update_from_parent();
702,801✔
1968
        m_index_refs.update_from_parent();
702,801✔
1969
        for (auto&& index : m_index_accessors) {
2,074,989✔
1970
            if (index != nullptr) {
2,074,989✔
1971
                index->update_from_parent();
288,990✔
1972
            }
288,990✔
1973
        }
2,074,989✔
1974

1975
        m_opposite_table.update_from_parent();
702,801✔
1976
        m_opposite_column.update_from_parent();
702,801✔
1977
        if (m_top.size() > top_position_for_flags) {
702,804✔
1978
            uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
702,798✔
1979
            m_table_type = Type(flags & table_type_mask);
702,798✔
1980
        }
702,798✔
1981
        else {
2,147,483,653✔
1982
            m_table_type = Type::TopLevel;
2,147,483,653✔
1983
        }
2,147,483,653✔
1984
        if (m_tombstones)
702,801✔
1985
            m_tombstones->update_from_parent();
3,486✔
1986

1987
        refresh_content_version();
702,801✔
1988
        m_has_any_embedded_objects.reset();
702,801✔
1989
    }
702,801✔
1990
    m_alloc.bump_storage_version();
702,804✔
1991
}
702,804✔
1992

1993
void Table::schema_to_json(std::ostream& out) const
1994
{
12✔
1995
    out << "{";
12✔
1996
    auto name = get_name();
12✔
1997
    out << "\"name\":\"" << name << "\"";
12✔
1998
    if (this->m_primary_key_col) {
12✔
1999
        out << ",";
×
2000
        out << "\"primaryKey\":\"" << this->get_column_name(m_primary_key_col) << "\"";
×
2001
    }
×
2002
    out << ",\"tableType\":\"" << this->get_table_type() << "\"";
12✔
2003
    out << ",\"properties\":[";
12✔
2004
    auto col_keys = get_column_keys();
12✔
2005
    int sz = int(col_keys.size());
12✔
2006
    for (int i = 0; i < sz; ++i) {
54✔
2007
        auto col_key = col_keys[i];
42✔
2008
        name = get_column_name(col_key);
42✔
2009
        auto type = col_key.get_type();
42✔
2010
        out << "{";
42✔
2011
        out << "\"name\":\"" << name << "\"";
42✔
2012
        if (this->is_link_type(type)) {
42✔
2013
            out << ",\"type\":\"object\"";
6✔
2014
            name = this->get_opposite_table(col_key)->get_name();
6✔
2015
            out << ",\"objectType\":\"" << name << "\"";
6✔
2016
        }
6✔
2017
        else {
36✔
2018
            out << ",\"type\":\"" << get_data_type_name(DataType(type)) << "\"";
36✔
2019
        }
36✔
2020
        if (col_key.is_list()) {
42✔
2021
            out << ",\"isArray\":true";
12✔
2022
        }
12✔
2023
        else if (col_key.is_set()) {
30✔
2024
            out << ",\"isSet\":true";
×
2025
        }
×
2026
        else if (col_key.is_dictionary()) {
30✔
2027
            out << ",\"isMap\":true";
6✔
2028
            auto key_type = get_dictionary_key_type(col_key);
6✔
2029
            out << ",\"keyType\":\"" << get_data_type_name(key_type) << "\"";
6✔
2030
        }
6✔
2031
        if (col_key.is_nullable()) {
42✔
2032
            out << ",\"isOptional\":true";
12✔
2033
        }
12✔
2034
        auto index_type = search_index_type(col_key);
42✔
2035
        if (index_type == IndexType::General) {
42✔
2036
            out << ",\"isIndexed\":true";
×
2037
        }
×
2038
        if (index_type == IndexType::Fulltext) {
42✔
2039
            out << ",\"isFulltextIndexed\":true";
×
2040
        }
×
2041
        out << "}";
42✔
2042
        if (i < sz - 1) {
42✔
2043
            out << ",";
30✔
2044
        }
30✔
2045
    }
42✔
2046
    out << "]}";
12✔
2047
}
12✔
2048

2049
bool Table::operator==(const Table& t) const
2050
{
138✔
2051
    if (size() != t.size()) {
138✔
2052
        return false;
12✔
2053
    }
12✔
2054
    // Check columns
2055
    for (auto ck : this->get_column_keys()) {
534✔
2056
        auto name = get_column_name(ck);
534✔
2057
        auto other_ck = t.get_column_key(name);
534✔
2058
        auto attrs = ck.get_attrs();
534✔
2059
        if (search_index_type(ck) != t.search_index_type(other_ck))
534✔
2060
            return false;
×
2061

2062
        if (!other_ck || other_ck.get_attrs() != attrs) {
534✔
2063
            return false;
×
2064
        }
×
2065
    }
534✔
2066
    auto pk_col = get_primary_key_column();
126✔
2067
    for (auto o : *this) {
2,898✔
2068
        Obj other_o;
2,898✔
2069
        if (pk_col) {
2,898✔
2070
            auto pk = o.get_any(pk_col);
90✔
2071
            other_o = t.get_object_with_primary_key(pk);
90✔
2072
        }
90✔
2073
        else {
2,808✔
2074
            other_o = t.get_object(o.get_key());
2,808✔
2075
        }
2,808✔
2076
        if (!(other_o && o == other_o))
2,898✔
2077
            return false;
18✔
2078
    }
2,898✔
2079

2080
    return true;
108✔
2081
}
126✔
2082

2083

2084
void Table::flush_for_commit()
2085
{
1,010,031✔
2086
    if (m_top.is_attached() && m_top.size() >= top_position_for_version) {
1,010,031✔
2087
        if (!m_top.is_read_only()) {
1,010,028✔
2088
            ++m_in_file_version_at_transaction_boundary;
765,075✔
2089
            auto rot_version = RefOrTagged::make_tagged(m_in_file_version_at_transaction_boundary);
765,075✔
2090
            m_top.set(top_position_for_version, rot_version);
765,075✔
2091
        }
765,075✔
2092
    }
1,010,028✔
2093
}
1,010,031✔
2094

2095
void Table::refresh_content_version()
2096
{
1,053,807✔
2097
    REALM_ASSERT(m_top.is_attached());
1,053,807✔
2098
    if (m_top.size() >= top_position_for_version) {
1,053,807✔
2099
        // we have versioning info in the file. Use this to conditionally
2100
        // bump the version counter:
2101
        auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
1,053,465✔
2102
        REALM_ASSERT(rot_version.is_tagged());
1,053,465✔
2103
        if (m_in_file_version_at_transaction_boundary != rot_version.get_as_int()) {
1,053,465✔
2104
            m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
247,248✔
2105
            bump_content_version();
247,248✔
2106
        }
247,248✔
2107
    }
1,053,465✔
2108
    else {
342✔
2109
        // assume the worst:
2110
        bump_content_version();
342✔
2111
    }
342✔
2112
}
1,053,807✔
2113

2114

2115
// Called when Group is moved to another version - either a rollback or an advance.
2116
// The content of the table is potentially different, so make no assumptions.
2117
void Table::refresh_accessor_tree()
2118
{
350,505✔
2119
    REALM_ASSERT(m_cookie == cookie_initialized);
350,505✔
2120
    REALM_ASSERT(m_top.is_attached());
350,505✔
2121
    m_top.init_from_parent();
350,505✔
2122
    m_spec.init_from_parent();
350,505✔
2123
    REALM_ASSERT(m_top.size() > top_position_for_pk_col);
350,505✔
2124
    m_clusters.init_from_parent();
350,505✔
2125
    m_index_refs.init_from_parent();
350,505✔
2126
    m_opposite_table.init_from_parent();
350,505✔
2127
    m_opposite_column.init_from_parent();
350,505✔
2128
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
350,505✔
2129
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
350,505✔
2130
    if (m_top.size() > top_position_for_flags) {
350,601✔
2131
        auto rot_flags = m_top.get_as_ref_or_tagged(top_position_for_flags);
350,601✔
2132
        m_table_type = Type(rot_flags.get_as_int() & table_type_mask);
350,601✔
2133
    }
350,601✔
2134
    else {
4,294,967,294✔
2135
        m_table_type = Type::TopLevel;
4,294,967,294✔
2136
    }
4,294,967,294✔
2137
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
350,625✔
2138
        // Tombstones exists
2139
        if (!m_tombstones) {
2,100✔
2140
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
312✔
2141
        }
312✔
2142
        m_tombstones->init_from_parent();
2,100✔
2143
    }
2,100✔
2144
    else {
348,405✔
2145
        m_tombstones = nullptr;
348,405✔
2146
    }
348,405✔
2147
    refresh_content_version();
350,505✔
2148
    bump_storage_version();
350,505✔
2149
    build_column_mapping();
350,505✔
2150
    refresh_index_accessors();
350,505✔
2151
}
350,505✔
2152

2153
void Table::refresh_index_accessors()
2154
{
3,022,944✔
2155
    // Refresh search index accessors
2156

2157
    // First eliminate any index accessors for eliminated last columns
2158
    size_t col_ndx_end = m_leaf_ndx2colkey.size();
3,022,944✔
2159
    m_index_accessors.resize(col_ndx_end);
3,022,944✔
2160

2161
    // Then eliminate/refresh/create accessors within column range
2162
    // we can not use for_each_column() here, since the columns may have changed
2163
    // and the index accessor vector is not updated correspondingly.
2164
    for (size_t col_ndx = 0; col_ndx < col_ndx_end; col_ndx++) {
16,663,017✔
2165
        ref_type ref = m_index_refs.get_as_ref(col_ndx);
13,640,073✔
2166

2167
        if (ref == 0) {
13,640,073✔
2168
            // accessor drop
2169
            m_index_accessors[col_ndx].reset();
12,731,376✔
2170
        }
12,731,376✔
2171
        else {
908,697✔
2172
            auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_ndx]);
908,697✔
2173
            bool fulltext = attr.test(col_attr_FullText_Indexed);
908,697✔
2174
            auto col_key = m_leaf_ndx2colkey[col_ndx];
908,697✔
2175
            ClusterColumn virtual_col(&m_clusters, col_key, fulltext ? IndexType::Fulltext : IndexType::General);
908,697✔
2176

2177
            if (m_index_accessors[col_ndx]) { // still there, refresh:
908,697✔
2178
                m_index_accessors[col_ndx]->refresh_accessor_tree(virtual_col);
363,414✔
2179
            }
363,414✔
2180
            else { // new index!
545,283✔
2181
                m_index_accessors[col_ndx] =
545,283✔
2182
                    std::make_unique<StringIndex>(ref, &m_index_refs, col_ndx, virtual_col, get_alloc());
545,283✔
2183
            }
545,283✔
2184
        }
908,697✔
2185
    }
13,640,073✔
2186
}
3,022,944✔
2187

2188
bool Table::is_cross_table_link_target() const noexcept
2189
{
1,542✔
2190
    auto is_cross_link = [this](ColKey col_key) {
1,542✔
2191
        auto t = col_key.get_type();
60✔
2192
        // look for a backlink with a different target than ourselves
2193
        return (t == col_type_BackLink && get_opposite_table_key(col_key) != get_key())
60✔
2194
                   ? IteratorControl::Stop
60✔
2195
                   : IteratorControl::AdvanceToNext;
60✔
2196
    };
60✔
2197
    return for_each_backlink_column(is_cross_link);
1,542✔
2198
}
1,542✔
2199

2200
// LCOV_EXCL_START ignore debug functions
2201

2202
void Table::verify() const
2203
{
238,188✔
2204
#ifdef REALM_DEBUG
238,188✔
2205
    if (m_top.is_attached())
238,188✔
2206
        m_top.verify();
238,188✔
2207
    m_spec.verify();
238,188✔
2208
    m_clusters.verify();
238,188✔
2209
    if (nb_unresolved())
238,188✔
2210
        m_tombstones->verify();
30,339✔
2211
#endif
238,188✔
2212
}
238,188✔
2213

2214
#ifdef REALM_DEBUG
2215
MemStats Table::stats() const
2216
{
×
2217
    MemStats mem_stats;
×
2218
    m_top.stats(mem_stats);
×
2219
    return mem_stats;
×
2220
}
×
2221
#endif // LCOV_EXCL_STOP ignore debug functions
2222

2223
Obj Table::create_object(ObjKey key, const FieldValues& values)
2224
{
22,692,096✔
2225
    if (is_embedded())
22,692,096✔
2226
        throw IllegalOperation(util::format("Explicit creation of embedded object not allowed in: %1", get_name()));
48✔
2227
    if (m_primary_key_col)
22,692,048✔
2228
        throw IllegalOperation(util::format("Table has primary key: %1", get_name()));
×
2229
    if (key == null_key) {
22,692,048✔
2230
        GlobalKey object_id = allocate_object_id_squeezed();
19,545,936✔
2231
        key = object_id.get_local_key(get_sync_file_id());
19,545,936✔
2232
        // Check if this key collides with an already existing object
2233
        // This could happen if objects were at some point created with primary keys,
2234
        // but later primary key property was removed from the schema.
2235
        while (m_clusters.is_valid(key)) {
19,545,936✔
2236
            object_id = allocate_object_id_squeezed();
×
2237
            key = object_id.get_local_key(get_sync_file_id());
×
2238
        }
×
2239
        if (auto repl = get_repl())
19,545,936✔
2240
            repl->create_object(this, object_id);
4,296,318✔
2241
    }
19,545,936✔
2242

2243
    REALM_ASSERT(key.value >= 0);
22,692,048✔
2244

2245
    Obj obj = m_clusters.insert(key, values); // repl->set()
22,692,048✔
2246

2247
    return obj;
22,692,048✔
2248
}
22,692,048✔
2249

2250
Obj Table::create_linked_object()
2251
{
42,834✔
2252
    REALM_ASSERT(is_embedded());
42,834✔
2253

2254
    GlobalKey object_id = allocate_object_id_squeezed();
42,834✔
2255
    ObjKey key = object_id.get_local_key(get_sync_file_id());
42,834✔
2256

2257
    REALM_ASSERT(key.value >= 0);
42,834✔
2258

2259
    Obj obj = m_clusters.insert(key, {});
42,834✔
2260

2261
    return obj;
42,834✔
2262
}
42,834✔
2263

2264
Obj Table::create_object(GlobalKey object_id, const FieldValues& values)
2265
{
30✔
2266
    if (is_embedded())
30✔
2267
        throw IllegalOperation(util::format("Explicit creation of embedded object not allowed in: %1", get_name()));
×
2268
    if (m_primary_key_col)
30✔
2269
        throw IllegalOperation(util::format("Table has primary key: %1", get_name()));
×
2270
    ObjKey key = object_id.get_local_key(get_sync_file_id());
30✔
2271

2272
    if (auto repl = get_repl())
30✔
2273
        repl->create_object(this, object_id);
30✔
2274

2275
    try {
30✔
2276
        Obj obj = m_clusters.insert(key, values);
30✔
2277
        // Check if tombstone exists
2278
        if (m_tombstones && m_tombstones->is_valid(key.get_unresolved())) {
30✔
2279
            auto unres_key = key.get_unresolved();
6✔
2280
            // Copy links over
2281
            auto tombstone = m_tombstones->get(unres_key);
6✔
2282
            obj.assign_pk_and_backlinks(tombstone);
6✔
2283
            // If tombstones had no links to it, it may still be alive
2284
            if (m_tombstones->is_valid(unres_key)) {
6✔
2285
                CascadeState state(CascadeState::Mode::None);
6✔
2286
                m_tombstones->erase(unres_key, state);
6✔
2287
            }
6✔
2288
        }
6✔
2289

2290
        return obj;
30✔
2291
    }
30✔
2292
    catch (const KeyAlreadyUsed&) {
30✔
2293
        return m_clusters.get(key);
6✔
2294
    }
6✔
2295
}
30✔
2296

2297
Obj Table::create_object_with_primary_key(const Mixed& primary_key, FieldValues&& field_values, UpdateMode mode,
2298
                                          bool* did_create)
2299
{
803,988✔
2300
    auto primary_key_col = get_primary_key_column();
803,988✔
2301
    if (is_embedded() || !primary_key_col)
803,988✔
2302
        throw InvalidArgument(ErrorCodes::UnexpectedPrimaryKey,
6✔
2303
                              util::format("Table has no primary key: %1", get_name()));
6✔
2304

2305
    DataType type = DataType(primary_key_col.get_type());
803,982✔
2306

2307
    if (primary_key.is_null() && !primary_key_col.is_nullable()) {
803,982✔
2308
        throw InvalidArgument(
6✔
2309
            ErrorCodes::PropertyNotNullable,
6✔
2310
            util::format("Primary key for class %1 cannot be NULL", Group::table_name_to_class_name(get_name())));
6✔
2311
    }
6✔
2312

2313
    if (!(primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) &&
803,976✔
2314
        primary_key.get_type() != type) {
803,976✔
2315
        throw InvalidArgument(ErrorCodes::TypeMismatch, util::format("Wrong primary key type for class %1",
6✔
2316
                                                                     Group::table_name_to_class_name(get_name())));
6✔
2317
    }
6✔
2318

2319
    REALM_ASSERT(type == type_String || type == type_ObjectId || type == type_Int || type == type_UUID);
803,970✔
2320

2321
    if (did_create)
803,970✔
2322
        *did_create = false;
84,420✔
2323

2324
    // Check for existing object
2325
    if (ObjKey key = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key)) {
803,970✔
2326
        if (mode == UpdateMode::never) {
46,926✔
2327
            throw ObjectAlreadyExists(this->get_class_name(), primary_key);
6✔
2328
        }
6✔
2329
        auto obj = m_clusters.get(key);
46,920✔
2330
        for (auto& val : field_values) {
46,920✔
2331
            if (mode == UpdateMode::all || obj.get_any(val.col_key) != val.value) {
12✔
2332
                obj.set_any(val.col_key, val.value, val.is_default);
12✔
2333
            }
12✔
2334
        }
12✔
2335
        return obj;
46,920✔
2336
    }
46,926✔
2337

2338
    ObjKey unres_key;
757,044✔
2339
    if (m_tombstones) {
757,044✔
2340
        // Check for potential tombstone
2341
        GlobalKey object_id{primary_key};
12,444✔
2342
        ObjKey object_key = global_to_local_object_id_hashed(object_id);
12,444✔
2343

2344
        ObjKey key = object_key.get_unresolved();
12,444✔
2345
        if (auto obj = m_tombstones->try_get_obj(key)) {
12,444✔
2346
            auto existing_pk_value = obj.get_any(primary_key_col);
10,827✔
2347

2348
            // If the primary key is the same, the object should be resurrected below
2349
            if (existing_pk_value == primary_key) {
10,827✔
2350
                unres_key = key;
10,821✔
2351
            }
10,821✔
2352
        }
10,827✔
2353
    }
12,444✔
2354

2355
    ObjKey key = get_next_valid_key();
757,044✔
2356

2357
    auto repl = get_repl();
757,044✔
2358
    if (repl) {
757,044✔
2359
        repl->create_object_with_primary_key(this, key, primary_key);
306,282✔
2360
    }
306,282✔
2361
    if (did_create) {
757,044✔
2362
        *did_create = true;
47,058✔
2363
    }
47,058✔
2364

2365
    field_values.insert(primary_key_col, primary_key);
757,044✔
2366
    Obj ret = m_clusters.insert(key, field_values);
757,044✔
2367

2368
    // Check if unresolved exists
2369
    if (unres_key) {
757,044✔
2370
        if (Replication* repl = get_repl()) {
10,821✔
2371
            if (auto logger = repl->would_log(util::Logger::Level::debug)) {
10,731✔
2372
                logger->log(LogCategory::object, util::Logger::Level::debug, "Cancel tombstone on '%1': %2",
36✔
2373
                            get_class_name(), unres_key);
36✔
2374
            }
36✔
2375
        }
10,731✔
2376

2377
        auto tombstone = m_tombstones->get(unres_key);
10,821✔
2378
        ret.assign_pk_and_backlinks(tombstone);
10,821✔
2379
        // If tombstones had no links to it, it may still be alive
2380
        if (m_tombstones->is_valid(unres_key)) {
10,821✔
2381
            CascadeState state(CascadeState::Mode::None);
10,761✔
2382
            m_tombstones->erase(unres_key, state);
10,761✔
2383
        }
10,761✔
2384
    }
10,821✔
2385
    if (is_asymmetric() && repl && repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
757,044✔
2386
        get_parent_group()->m_tables_to_clear.insert(this->m_key);
1,290✔
2387
    }
1,290✔
2388
    return ret;
757,044✔
2389
}
803,970✔
2390

2391
ObjKey Table::find_primary_key(Mixed primary_key) const
2392
{
722,259✔
2393
    auto primary_key_col = get_primary_key_column();
722,259✔
2394
    REALM_ASSERT(primary_key_col);
722,259✔
2395
    DataType type = DataType(primary_key_col.get_type());
722,259✔
2396
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
722,259✔
2397
                 primary_key.get_type() == type);
722,259✔
2398

2399
    if (auto&& index = m_index_accessors[primary_key_col.get_index().val]) {
722,259✔
2400
        return index->find_first(primary_key);
722,238✔
2401
    }
722,238✔
2402

2403
    // This must be file format 11, 20 or 21 as those are the ones we can open in read-only mode
2404
    // so try the old algorithm
2405
    GlobalKey object_id{primary_key};
21✔
2406
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
21✔
2407

2408
    // Check if existing
2409
    if (auto obj = m_clusters.try_get_obj(object_key)) {
21✔
2410
        auto existing_pk_value = obj.get_any(primary_key_col);
×
2411

2412
        if (existing_pk_value == primary_key) {
×
2413
            return object_key;
×
2414
        }
×
2415
    }
×
2416
    return {};
21✔
2417
}
21✔
2418

2419
ObjKey Table::get_objkey_from_primary_key(const Mixed& primary_key)
2420
{
609,036✔
2421
    // Check if existing
2422
    if (auto key = find_primary_key(primary_key)) {
609,036✔
2423
        return key;
597,126✔
2424
    }
597,126✔
2425

2426
    // Object does not exist - create tombstone
2427
    GlobalKey object_id{primary_key};
11,910✔
2428
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
11,910✔
2429
    return get_or_create_tombstone(object_key, m_primary_key_col, primary_key).get_key();
11,910✔
2430
}
609,036✔
2431

2432
ObjKey Table::get_objkey_from_global_key(GlobalKey global_key)
2433
{
18✔
2434
    REALM_ASSERT(!m_primary_key_col);
18✔
2435
    auto object_key = global_key.get_local_key(get_sync_file_id());
18✔
2436

2437
    // Check if existing
2438
    if (m_clusters.is_valid(object_key)) {
18✔
2439
        return object_key;
12✔
2440
    }
12✔
2441

2442
    return get_or_create_tombstone(object_key, {}, {}).get_key();
6✔
2443
}
18✔
2444

2445
ObjKey Table::get_objkey(GlobalKey global_key) const
2446
{
18✔
2447
    ObjKey key;
18✔
2448
    REALM_ASSERT(!m_primary_key_col);
18✔
2449
    uint32_t max = std::numeric_limits<uint32_t>::max();
18✔
2450
    if (global_key.hi() <= max && global_key.lo() <= max) {
18✔
2451
        key = global_key.get_local_key(get_sync_file_id());
6✔
2452
    }
6✔
2453
    if (key && !is_valid(key)) {
18✔
2454
        key = realm::null_key;
6✔
2455
    }
6✔
2456
    return key;
18✔
2457
}
18✔
2458

2459
GlobalKey Table::get_object_id(ObjKey key) const
2460
{
144✔
2461
    auto col = get_primary_key_column();
144✔
2462
    if (col) {
144✔
2463
        const Obj obj = get_object(key);
24✔
2464
        auto val = obj.get_any(col);
24✔
2465
        return {val};
24✔
2466
    }
24✔
2467
    else {
120✔
2468
        return {key, get_sync_file_id()};
120✔
2469
    }
120✔
2470
    return {};
×
2471
}
144✔
2472

2473
Obj Table::get_object_with_primary_key(Mixed primary_key) const
2474
{
81,003✔
2475
    auto primary_key_col = get_primary_key_column();
81,003✔
2476
    REALM_ASSERT(primary_key_col);
81,003✔
2477
    DataType type = DataType(primary_key_col.get_type());
81,003✔
2478
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
81,003✔
2479
                 primary_key.get_type() == type);
81,003✔
2480
    ObjKey k = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key);
81,003✔
2481
    return k ? m_clusters.get(k) : Obj{};
81,003✔
2482
}
81,003✔
2483

2484
Mixed Table::get_primary_key(ObjKey key) const
2485
{
775,632✔
2486
    auto primary_key_col = get_primary_key_column();
775,632✔
2487
    REALM_ASSERT(primary_key_col);
775,632✔
2488
    if (key.is_unresolved()) {
775,632✔
2489
        REALM_ASSERT(m_tombstones);
792✔
2490
        return m_tombstones->get(key).get_any(primary_key_col);
792✔
2491
    }
792✔
2492
    else {
774,840✔
2493
        return m_clusters.get(key).get_any(primary_key_col);
774,840✔
2494
    }
774,840✔
2495
}
775,632✔
2496

2497
GlobalKey Table::allocate_object_id_squeezed()
2498
{
19,590,492✔
2499
    // m_client_file_ident will be zero if we haven't been in contact with
2500
    // the server yet.
2501
    auto peer_id = get_sync_file_id();
19,590,492✔
2502
    auto sequence = allocate_sequence_number();
19,590,492✔
2503
    return GlobalKey{peer_id, sequence};
19,590,492✔
2504
}
19,590,492✔
2505

2506
namespace {
2507

2508
/// Calculate optimistic local ID that may collide with others. It is up to
2509
/// the caller to ensure that collisions are detected and that
2510
/// allocate_local_id_after_collision() is called to obtain a non-colliding
2511
/// ID.
2512
inline ObjKey get_optimistic_local_id_hashed(GlobalKey global_id)
2513
{
25,164✔
2514
#if REALM_EXERCISE_OBJECT_ID_COLLISION
2515
    const uint64_t optimistic_mask = 0xff;
2516
#else
2517
    const uint64_t optimistic_mask = 0x3fffffffffffffff;
25,164✔
2518
#endif
25,164✔
2519
    static_assert(!(optimistic_mask >> 62), "optimistic Object ID mask must leave the 63rd and 64th bit zero");
25,164✔
2520
    return ObjKey{int64_t(global_id.lo() & optimistic_mask)};
25,164✔
2521
}
25,164✔
2522

2523
inline ObjKey make_tagged_local_id_after_hash_collision(uint64_t sequence_number)
2524
{
12✔
2525
    REALM_ASSERT(!(sequence_number >> 62));
12✔
2526
    return ObjKey{int64_t(0x4000000000000000 | sequence_number)};
12✔
2527
}
12✔
2528

2529
} // namespace
2530

2531
ObjKey Table::global_to_local_object_id_hashed(GlobalKey object_id) const
2532
{
25,164✔
2533
    ObjKey optimistic = get_optimistic_local_id_hashed(object_id);
25,164✔
2534

2535
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
25,164✔
2536
        Allocator& alloc = m_top.get_alloc();
24✔
2537
        Array collision_map{alloc};
24✔
2538
        collision_map.init_from_ref(collision_map_ref); // Throws
24✔
2539

2540
        Array hi{alloc};
24✔
2541
        hi.init_from_ref(to_ref(collision_map.get(s_collision_map_hi))); // Throws
24✔
2542

2543
        // Entries are ordered by hi,lo
2544
        size_t found = hi.find_first(object_id.hi());
24✔
2545
        if (found != npos && uint64_t(hi.get(found)) == object_id.hi()) {
24✔
2546
            Array lo{alloc};
24✔
2547
            lo.init_from_ref(to_ref(collision_map.get(s_collision_map_lo))); // Throws
24✔
2548
            size_t candidate = lo.find_first(object_id.lo(), found);
24✔
2549
            if (candidate != npos && uint64_t(hi.get(candidate)) == object_id.hi()) {
24✔
2550
                Array local_id{alloc};
24✔
2551
                local_id.init_from_ref(to_ref(collision_map.get(s_collision_map_local_id))); // Throws
24✔
2552
                return ObjKey{local_id.get(candidate)};
24✔
2553
            }
24✔
2554
        }
24✔
2555
    }
24✔
2556

2557
    return optimistic;
25,140✔
2558
}
25,164✔
2559

2560
ObjKey Table::allocate_local_id_after_hash_collision(GlobalKey incoming_id, GlobalKey colliding_id,
2561
                                                     ObjKey colliding_local_id)
2562
{
12✔
2563
    // Possible optimization: Cache these accessors
2564
    Allocator& alloc = m_top.get_alloc();
12✔
2565
    Array collision_map{alloc};
12✔
2566
    Array hi{alloc};
12✔
2567
    Array lo{alloc};
12✔
2568
    Array local_id{alloc};
12✔
2569

2570
    collision_map.set_parent(&m_top, top_position_for_collision_map);
12✔
2571
    hi.set_parent(&collision_map, s_collision_map_hi);
12✔
2572
    lo.set_parent(&collision_map, s_collision_map_lo);
12✔
2573
    local_id.set_parent(&collision_map, s_collision_map_local_id);
12✔
2574

2575
    ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map));
12✔
2576
    if (collision_map_ref) {
12✔
2577
        collision_map.init_from_parent(); // Throws
×
2578
    }
×
2579
    else {
12✔
2580
        MemRef mem = Array::create_empty_array(Array::type_HasRefs, false, alloc); // Throws
12✔
2581
        collision_map.init_from_mem(mem);                                          // Throws
12✔
2582
        collision_map.update_parent();
12✔
2583

2584
        ref_type lo_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref();       // Throws
12✔
2585
        ref_type hi_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref();       // Throws
12✔
2586
        ref_type local_id_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref(); // Throws
12✔
2587
        collision_map.add(lo_ref);                                                                     // Throws
12✔
2588
        collision_map.add(hi_ref);                                                                     // Throws
12✔
2589
        collision_map.add(local_id_ref);                                                               // Throws
12✔
2590
    }
12✔
2591

2592
    hi.init_from_parent();       // Throws
12✔
2593
    lo.init_from_parent();       // Throws
12✔
2594
    local_id.init_from_parent(); // Throws
12✔
2595

2596
    size_t num_entries = hi.size();
12✔
2597
    REALM_ASSERT(lo.size() == num_entries);
12✔
2598
    REALM_ASSERT(local_id.size() == num_entries);
12✔
2599

2600
    auto lower_bound_object_id = [&](GlobalKey object_id) -> size_t {
24✔
2601
        size_t i = hi.lower_bound_int(int64_t(object_id.hi()));
24✔
2602
        while (i < num_entries && uint64_t(hi.get(i)) == object_id.hi() && uint64_t(lo.get(i)) < object_id.lo())
30✔
2603
            ++i;
6✔
2604
        return i;
24✔
2605
    };
24✔
2606

2607
    auto insert_collision = [&](GlobalKey object_id, ObjKey new_local_id) {
24✔
2608
        size_t i = lower_bound_object_id(object_id);
24✔
2609
        if (i != num_entries) {
24✔
2610
            GlobalKey existing{uint64_t(hi.get(i)), uint64_t(lo.get(i))};
6✔
2611
            if (existing == object_id) {
6✔
2612
                REALM_ASSERT(new_local_id.value == local_id.get(i));
×
2613
                return;
×
2614
            }
×
2615
        }
6✔
2616
        hi.insert(i, int64_t(object_id.hi()));
24✔
2617
        lo.insert(i, int64_t(object_id.lo()));
24✔
2618
        local_id.insert(i, new_local_id.value);
24✔
2619
        ++num_entries;
24✔
2620
    };
24✔
2621

2622
    auto sequence_number_for_local_id = allocate_sequence_number();
12✔
2623
    ObjKey new_local_id = make_tagged_local_id_after_hash_collision(sequence_number_for_local_id);
12✔
2624
    insert_collision(incoming_id, new_local_id);
12✔
2625
    insert_collision(colliding_id, colliding_local_id);
12✔
2626

2627
    return new_local_id;
12✔
2628
}
12✔
2629

2630
Obj Table::get_or_create_tombstone(ObjKey key, ColKey pk_col, Mixed pk_val)
2631
{
12,894✔
2632
    auto unres_key = key.get_unresolved();
12,894✔
2633

2634
    ensure_graveyard();
12,894✔
2635
    auto tombstone = m_tombstones->try_get_obj(unres_key);
12,894✔
2636
    if (tombstone) {
12,894✔
2637
        if (pk_col) {
351✔
2638
            auto existing_pk_value = tombstone.get_any(pk_col);
351✔
2639
            // It may just be the same object
2640
            if (existing_pk_value != pk_val) {
351✔
2641
                // We have a collision - create new ObjKey
2642
                key = allocate_local_id_after_hash_collision({pk_val}, {existing_pk_value}, key);
12✔
2643
                return get_or_create_tombstone(key, pk_col, pk_val);
12✔
2644
            }
12✔
2645
        }
351✔
2646
        return tombstone;
339✔
2647
    }
351✔
2648
    if (Replication* repl = get_repl()) {
12,543✔
2649
        if (auto logger = repl->would_log(util::Logger::Level::debug)) {
12,279✔
2650
            logger->log(LogCategory::object, util::Logger::Level::debug,
576✔
2651
                        "Create tombstone for object '%1' with primary key %2 : %3", get_class_name(), pk_val,
576✔
2652
                        unres_key);
576✔
2653
        }
576✔
2654
    }
12,279✔
2655
    return m_tombstones->insert(unres_key, {{pk_col, pk_val}});
12,543✔
2656
}
12,894✔
2657

2658
void Table::free_local_id_after_hash_collision(ObjKey key)
2659
{
5,000,454✔
2660
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
5,000,454✔
2661
        if (key.is_unresolved()) {
30✔
2662
            // Keys will always be inserted as resolved
2663
            key = key.get_unresolved();
24✔
2664
        }
24✔
2665
        // Possible optimization: Cache these accessors
2666
        Array collision_map{m_alloc};
30✔
2667
        Array local_id{m_alloc};
30✔
2668

2669
        collision_map.set_parent(&m_top, top_position_for_collision_map);
30✔
2670
        local_id.set_parent(&collision_map, s_collision_map_local_id);
30✔
2671
        collision_map.init_from_ref(collision_map_ref);
30✔
2672
        local_id.init_from_parent();
30✔
2673
        auto ndx = local_id.find_first(key.value);
30✔
2674
        if (ndx != realm::npos) {
30✔
2675
            Array hi{m_alloc};
24✔
2676
            Array lo{m_alloc};
24✔
2677

2678
            hi.set_parent(&collision_map, s_collision_map_hi);
24✔
2679
            lo.set_parent(&collision_map, s_collision_map_lo);
24✔
2680
            hi.init_from_parent();
24✔
2681
            lo.init_from_parent();
24✔
2682

2683
            hi.erase(ndx);
24✔
2684
            lo.erase(ndx);
24✔
2685
            local_id.erase(ndx);
24✔
2686
            if (hi.size() == 0) {
24✔
2687
                free_collision_table();
12✔
2688
            }
12✔
2689
        }
24✔
2690
    }
30✔
2691
}
5,000,454✔
2692

2693
void Table::free_collision_table()
2694
{
6,006✔
2695
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
6,006✔
2696
        Array::destroy_deep(collision_map_ref, m_alloc);
12✔
2697
        m_top.set(top_position_for_collision_map, 0);
12✔
2698
    }
12✔
2699
}
6,006✔
2700

2701
void Table::create_objects(size_t number, std::vector<ObjKey>& keys)
2702
{
3,855✔
2703
    while (number--) {
6,323,493✔
2704
        keys.push_back(create_object().get_key());
6,319,638✔
2705
    }
6,319,638✔
2706
}
3,855✔
2707

2708
void Table::create_objects(const std::vector<ObjKey>& keys)
2709
{
630✔
2710
    for (auto k : keys) {
5,616✔
2711
        create_object(k);
5,616✔
2712
    }
5,616✔
2713
}
630✔
2714

2715
void Table::dump_objects()
2716
{
×
2717
    m_clusters.dump_objects();
×
2718
    if (nb_unresolved())
×
2719
        m_tombstones->dump_objects();
×
2720
}
×
2721

2722
void Table::remove_object(ObjKey key)
2723
{
2,463,321✔
2724
    Group* g = get_parent_group();
2,463,321✔
2725

2726
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
2,463,321✔
2727
        CascadeState state(CascadeState::Mode::Strong, g);
3,282✔
2728
        state.m_to_be_deleted.emplace_back(m_key, key);
3,282✔
2729
        m_clusters.nullify_incoming_links(key, state);
3,282✔
2730
        remove_recursive(state);
3,282✔
2731
    }
3,282✔
2732
    else {
2,460,039✔
2733
        CascadeState state(CascadeState::Mode::None, g);
2,460,039✔
2734
        if (g) {
2,460,039✔
2735
            m_clusters.nullify_incoming_links(key, state);
2,378,163✔
2736
        }
2,378,163✔
2737
        m_clusters.erase(key, state);
2,460,039✔
2738
    }
2,460,039✔
2739
}
2,463,321✔
2740

2741
ObjKey Table::invalidate_object(ObjKey key)
2742
{
4,323✔
2743
    if (is_embedded())
4,323✔
2744
        throw IllegalOperation("Deletion of embedded object not allowed");
×
2745
    REALM_ASSERT(!key.is_unresolved());
4,323✔
2746

2747
    Obj tombstone;
4,323✔
2748
    auto obj = get_object(key);
4,323✔
2749
    if (obj.has_backlinks(false)) {
4,323✔
2750
        // If the object has backlinks, we should make a tombstone
2751
        // and make inward links point to it,
2752
        if (auto primary_key_col = get_primary_key_column()) {
978✔
2753
            auto pk = obj.get_any(primary_key_col);
822✔
2754
            GlobalKey object_id{pk};
822✔
2755
            auto unres_key = global_to_local_object_id_hashed(object_id);
822✔
2756
            tombstone = get_or_create_tombstone(unres_key, primary_key_col, pk);
822✔
2757
        }
822✔
2758
        else {
156✔
2759
            tombstone = get_or_create_tombstone(key, {}, {});
156✔
2760
        }
156✔
2761
        tombstone.assign_pk_and_backlinks(obj);
978✔
2762
    }
978✔
2763

2764
    remove_object(key);
4,323✔
2765

2766
    return tombstone.get_key();
4,323✔
2767
}
4,323✔
2768

2769
void Table::remove_object_recursive(ObjKey key)
2770
{
30✔
2771
    size_t table_ndx = get_index_in_group();
30✔
2772
    if (table_ndx != realm::npos) {
30✔
2773
        CascadeState state(CascadeState::Mode::All, get_parent_group());
30✔
2774
        state.m_to_be_deleted.emplace_back(m_key, key);
30✔
2775
        nullify_links(state);
30✔
2776
        remove_recursive(state);
30✔
2777
    }
30✔
2778
    else {
×
2779
        // No links in freestanding table
2780
        CascadeState state(CascadeState::Mode::None);
×
2781
        m_clusters.erase(key, state);
×
2782
    }
×
2783
}
30✔
2784

2785
Table::Iterator Table::begin() const
2786
{
531,783✔
2787
    return Iterator(m_clusters, 0);
531,783✔
2788
}
531,783✔
2789

2790
Table::Iterator Table::end() const
2791
{
10,099,992✔
2792
    return Iterator(m_clusters, size());
10,099,992✔
2793
}
10,099,992✔
2794

2795
TableRef _impl::TableFriend::get_opposite_link_table(const Table& table, ColKey col_key)
2796
{
7,106,520✔
2797
    TableRef ret;
7,106,520✔
2798
    if (col_key) {
7,106,700✔
2799
        return table.get_opposite_table(col_key);
7,106,676✔
2800
    }
7,106,676✔
2801
    return ret;
2,147,483,671✔
2802
}
7,106,520✔
2803

2804
const uint64_t Table::max_num_columns;
2805

2806
void Table::build_column_mapping()
2807
{
3,032,847✔
2808
    // build column mapping from spec
2809
    // TODO: Optimization - Don't rebuild this for every change
2810
    m_spec_ndx2leaf_ndx.clear();
3,032,847✔
2811
    m_leaf_ndx2spec_ndx.clear();
3,032,847✔
2812
    m_leaf_ndx2colkey.clear();
3,032,847✔
2813
    size_t num_spec_cols = m_spec.get_column_count();
3,032,847✔
2814
    m_spec_ndx2leaf_ndx.resize(num_spec_cols);
3,032,847✔
2815
    for (size_t spec_ndx = 0; spec_ndx < num_spec_cols; ++spec_ndx) {
16,633,350✔
2816
        ColKey col_key = m_spec.get_key(spec_ndx);
13,600,503✔
2817
        unsigned leaf_ndx = col_key.get_index().val;
13,600,503✔
2818
        if (leaf_ndx >= m_leaf_ndx2colkey.size()) {
13,600,503✔
2819
            m_leaf_ndx2colkey.resize(leaf_ndx + 1);
13,117,647✔
2820
            m_leaf_ndx2spec_ndx.resize(leaf_ndx + 1, -1);
13,117,647✔
2821
        }
13,117,647✔
2822
        m_spec_ndx2leaf_ndx[spec_ndx] = ColKey::Idx{leaf_ndx};
13,600,503✔
2823
        m_leaf_ndx2spec_ndx[leaf_ndx] = spec_ndx;
13,600,503✔
2824
        m_leaf_ndx2colkey[leaf_ndx] = col_key;
13,600,503✔
2825
    }
13,600,503✔
2826
}
3,032,847✔
2827

2828
ColKey Table::generate_col_key(ColumnType tp, ColumnAttrMask attr)
2829
{
719,466✔
2830
    REALM_ASSERT(!attr.test(col_attr_Indexed));
719,466✔
2831
    REALM_ASSERT(!attr.test(col_attr_Unique)); // Must not be encoded into col_key
719,466✔
2832

2833
    int64_t col_seq_number = m_top.get_as_ref_or_tagged(top_position_for_column_key).get_as_int();
719,466✔
2834
    unsigned upper = unsigned(col_seq_number ^ get_key().value);
719,466✔
2835

2836
    // reuse lowest available leaf ndx:
2837
    unsigned lower = unsigned(m_leaf_ndx2colkey.size());
719,466✔
2838
    // look for an unused entry:
2839
    for (unsigned idx = 0; idx < lower; ++idx) {
5,500,314✔
2840
        if (m_leaf_ndx2colkey[idx] == ColKey()) {
4,780,932✔
2841
            lower = idx;
84✔
2842
            break;
84✔
2843
        }
84✔
2844
    }
4,780,932✔
2845
    return ColKey(ColKey::Idx{lower}, tp, attr, upper);
719,466✔
2846
}
719,466✔
2847

2848
Table::BacklinkOrigin Table::find_backlink_origin(StringData origin_table_name,
2849
                                                  StringData origin_col_name) const noexcept
2850
{
×
2851
    BacklinkOrigin ret;
×
2852
    auto f = [&](ColKey backlink_col_key) {
×
2853
        auto origin_table = get_opposite_table(backlink_col_key);
×
2854
        auto origin_link_col = get_opposite_column(backlink_col_key);
×
2855
        if (origin_table->get_name() == origin_table_name &&
×
2856
            origin_table->get_column_name(origin_link_col) == origin_col_name) {
×
2857
            ret = BacklinkOrigin{{origin_table, origin_link_col}};
×
2858
            return IteratorControl::Stop;
×
2859
        }
×
2860
        return IteratorControl::AdvanceToNext;
×
2861
    };
×
2862
    this->for_each_backlink_column(f);
×
2863
    return ret;
×
2864
}
×
2865

2866
Table::BacklinkOrigin Table::find_backlink_origin(ColKey backlink_col) const noexcept
2867
{
354✔
2868
    try {
354✔
2869
        TableKey linked_table_key = get_opposite_table_key(backlink_col);
354✔
2870
        ColKey linked_column_key = get_opposite_column(backlink_col);
354✔
2871
        if (linked_table_key == m_key) {
354✔
2872
            return {{m_own_ref, linked_column_key}};
18✔
2873
        }
18✔
2874
        else {
336✔
2875
            Group* current_group = get_parent_group();
336✔
2876
            if (current_group) {
336✔
2877
                ConstTableRef linked_table_ref = current_group->get_table(linked_table_key);
336✔
2878
                return {{linked_table_ref, linked_column_key}};
336✔
2879
            }
336✔
2880
        }
336✔
2881
    }
354✔
2882
    catch (...) {
354✔
2883
        // backlink column not found, returning empty optional
2884
    }
×
2885
    return {};
×
2886
}
354✔
2887

2888
std::vector<std::pair<TableKey, ColKey>> Table::get_incoming_link_columns() const noexcept
2889
{
×
2890
    std::vector<std::pair<TableKey, ColKey>> origins;
×
2891
    auto f = [&](ColKey backlink_col_key) {
×
2892
        auto origin_table_key = get_opposite_table_key(backlink_col_key);
×
2893
        auto origin_link_col = get_opposite_column(backlink_col_key);
×
2894
        origins.emplace_back(origin_table_key, origin_link_col);
×
2895
        return IteratorControl::AdvanceToNext;
×
2896
    };
×
2897
    this->for_each_backlink_column(f);
×
2898
    return origins;
×
2899
}
×
2900

2901
ColKey Table::get_primary_key_column() const
2902
{
19,220,679✔
2903
    return m_primary_key_col;
19,220,679✔
2904
}
19,220,679✔
2905

2906
void Table::set_primary_key_column(ColKey col_key)
2907
{
720✔
2908
    if (col_key == m_primary_key_col) {
720✔
2909
        return;
378✔
2910
    }
378✔
2911

2912
    if (Replication* repl = get_repl()) {
342✔
2913
        if (repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
240✔
2914
            throw RuntimeError(
×
2915
                ErrorCodes::BrokenInvariant,
×
2916
                util::format("Cannot change primary key property in '%1' when realm is synchronized", get_name()));
×
2917
        }
×
2918
    }
240✔
2919

2920
    REALM_ASSERT_RELEASE(col_key.value >= 0); // Just to be sure. We have an issue where value seems to be -1
342✔
2921

2922
    if (col_key) {
342✔
2923
        check_column(col_key);
222✔
2924
        validate_column_is_unique(col_key);
222✔
2925
        do_set_primary_key_column(col_key);
222✔
2926
    }
222✔
2927
    else {
120✔
2928
        do_set_primary_key_column(col_key);
120✔
2929
    }
120✔
2930
}
342✔
2931

2932

2933
void Table::do_set_primary_key_column(ColKey col_key)
2934
{
98,724✔
2935
    if (col_key) {
98,724✔
2936
        auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
97,701✔
2937
        auto attr = m_spec.get_column_attr(spec_ndx);
97,701✔
2938
        if (attr.test(col_attr_FullText_Indexed)) {
97,701✔
2939
            throw InvalidColumnKey("primary key cannot have a full text index");
6✔
2940
        }
6✔
2941
    }
97,701✔
2942

2943
    if (m_primary_key_col) {
98,718✔
2944
        // If the search index has not been set explicitly on current pk col, we remove it again
2945
        auto spec_ndx = leaf_ndx2spec_ndx(m_primary_key_col.get_index());
1,047✔
2946
        auto attr = m_spec.get_column_attr(spec_ndx);
1,047✔
2947
        if (!attr.test(col_attr_Indexed)) {
1,047✔
2948
            remove_search_index(m_primary_key_col);
1,035✔
2949
        }
1,035✔
2950
    }
1,047✔
2951

2952
    if (col_key) {
98,718✔
2953
        m_top.set(top_position_for_pk_col, RefOrTagged::make_tagged(col_key.value));
97,695✔
2954
        do_add_search_index(col_key, IndexType::General);
97,695✔
2955
    }
97,695✔
2956
    else {
1,023✔
2957
        m_top.set(top_position_for_pk_col, 0);
1,023✔
2958
    }
1,023✔
2959

2960
    m_primary_key_col = col_key;
98,718✔
2961
}
98,718✔
2962

2963
bool Table::contains_unique_values(ColKey col) const
2964
{
834✔
2965
    if (search_index_type(col) == IndexType::General) {
834✔
2966
        auto search_index = get_search_index(col);
744✔
2967
        return !search_index->has_duplicate_values();
744✔
2968
    }
744✔
2969
    else {
90✔
2970
        TableView tv = where().find_all();
90✔
2971
        tv.distinct(col);
90✔
2972
        return tv.size() == size();
90✔
2973
    }
90✔
2974
}
834✔
2975

2976
void Table::validate_column_is_unique(ColKey col) const
2977
{
834✔
2978
    if (!contains_unique_values(col)) {
834✔
2979
        throw MigrationFailed(util::format("Primary key property '%1.%2' has duplicate values after migration.",
30✔
2980
                                           get_class_name(), get_column_name(col)));
30✔
2981
    }
30✔
2982
}
834✔
2983

2984
void Table::validate_primary_column()
2985
{
1,812✔
2986
    if (ColKey col = get_primary_key_column()) {
1,812✔
2987
        validate_column_is_unique(col);
612✔
2988
    }
612✔
2989
}
1,812✔
2990

2991
ObjKey Table::get_next_valid_key()
2992
{
757,035✔
2993
    ObjKey key;
757,035✔
2994
    do {
757,041✔
2995
        key = ObjKey(allocate_sequence_number());
757,041✔
2996
    } while (m_clusters.is_valid(key));
757,041✔
2997

2998
    return key;
757,035✔
2999
}
757,035✔
3000

3001
namespace {
3002
template <class T>
3003
typename util::RemoveOptional<T>::type remove_optional(T val)
3004
{
88,149✔
3005
    return val;
88,149✔
3006
}
88,149✔
3007
template <>
3008
int64_t remove_optional<Optional<int64_t>>(Optional<int64_t> val)
3009
{
5,475✔
3010
    return *val;
5,475✔
3011
}
5,475✔
3012
template <>
3013
bool remove_optional<Optional<bool>>(Optional<bool> val)
3014
{
11,484✔
3015
    return *val;
11,484✔
3016
}
11,484✔
3017
template <>
3018
ObjectId remove_optional<Optional<ObjectId>>(Optional<ObjectId> val)
3019
{
5,529✔
3020
    return *val;
5,529✔
3021
}
5,529✔
3022
template <>
3023
UUID remove_optional<Optional<UUID>>(Optional<UUID> val)
3024
{
6,060✔
3025
    return *val;
6,060✔
3026
}
6,060✔
3027
} // namespace
3028

3029
template <class F, class T>
3030
void Table::change_nullability(ColKey key_from, ColKey key_to, bool throw_on_null)
3031
{
162✔
3032
    Allocator& allocator = this->get_alloc();
162✔
3033
    bool from_nullability = is_nullable(key_from);
162✔
3034
    auto func = [&](Cluster* cluster) {
162✔
3035
        size_t sz = cluster->node_size();
162✔
3036

3037
        typename ColumnTypeTraits<F>::cluster_leaf_type from_arr(allocator);
162✔
3038
        typename ColumnTypeTraits<T>::cluster_leaf_type to_arr(allocator);
162✔
3039
        cluster->init_leaf(key_from, &from_arr);
162✔
3040
        cluster->init_leaf(key_to, &to_arr);
162✔
3041

3042
        for (size_t i = 0; i < sz; i++) {
1,512✔
3043
            if (from_nullability && from_arr.is_null(i)) {
1,356!
3044
                if (throw_on_null) {
75!
3045
                    throw RuntimeError(ErrorCodes::BrokenInvariant,
6✔
3046
                                       util::format("Objects in '%1' has null value(s) in property '%2'", get_name(),
6✔
3047
                                                    get_column_name(key_from)));
6✔
3048
                }
6✔
3049
                else {
69✔
3050
                    to_arr.set(i, ColumnTypeTraits<T>::cluster_leaf_type::default_value(false));
69✔
3051
                }
69✔
3052
            }
75✔
3053
            else {
1,281✔
3054
                auto v = remove_optional(from_arr.get(i));
1,281✔
3055
                to_arr.set(i, v);
1,281✔
3056
            }
1,281✔
3057
        }
1,356✔
3058
    };
162✔
3059

3060
    m_clusters.update(func);
162✔
3061
}
162✔
3062

3063
template <class F, class T>
3064
void Table::change_nullability_list(ColKey key_from, ColKey key_to, bool throw_on_null)
3065
{
120✔
3066
    Allocator& allocator = this->get_alloc();
120✔
3067
    bool from_nullability = is_nullable(key_from);
120✔
3068
    auto func = [&](Cluster* cluster) {
120✔
3069
        size_t sz = cluster->node_size();
120✔
3070

3071
        ArrayInteger from_arr(allocator);
120✔
3072
        ArrayInteger to_arr(allocator);
120✔
3073
        cluster->init_leaf(key_from, &from_arr);
120✔
3074
        cluster->init_leaf(key_to, &to_arr);
120✔
3075

3076
        for (size_t i = 0; i < sz; i++) {
360✔
3077
            ref_type ref_from = to_ref(from_arr.get(i));
240✔
3078
            ref_type ref_to = to_ref(to_arr.get(i));
240✔
3079
            REALM_ASSERT(!ref_to);
240✔
3080

3081
            if (ref_from) {
240✔
3082
                BPlusTree<F> from_list(allocator);
120✔
3083
                BPlusTree<T> to_list(allocator);
120✔
3084
                from_list.init_from_ref(ref_from);
120✔
3085
                to_list.create();
120✔
3086
                size_t n = from_list.size();
120✔
3087
                for (size_t j = 0; j < n; j++) {
120,120✔
3088
                    auto v = from_list.get(j);
120,000✔
3089
                    if (!from_nullability || aggregate_operations::valid_for_agg(v)) {
120,000✔
3090
                        to_list.add(remove_optional(v));
115,416✔
3091
                    }
115,416✔
3092
                    else {
4,584✔
3093
                        if (throw_on_null) {
4,584!
3094
                            throw RuntimeError(ErrorCodes::BrokenInvariant,
×
3095
                                               util::format("Objects in '%1' has null value(s) in list property '%2'",
×
3096
                                                            get_name(), get_column_name(key_from)));
×
3097
                        }
×
3098
                        else {
4,584✔
3099
                            to_list.add(ColumnTypeTraits<T>::cluster_leaf_type::default_value(false));
4,584✔
3100
                        }
4,584✔
3101
                    }
4,584✔
3102
                }
120,000✔
3103
                to_arr.set(i, from_ref(to_list.get_ref()));
120✔
3104
            }
120✔
3105
        }
240✔
3106
    };
120✔
3107

3108
    m_clusters.update(func);
120✔
3109
}
120✔
3110

3111
void Table::convert_column(ColKey from, ColKey to, bool throw_on_null)
3112
{
282✔
3113
    realm::DataType type_id = get_column_type(from);
282✔
3114
    bool _is_list = is_list(from);
282✔
3115
    if (_is_list) {
282✔
3116
        switch (type_id) {
120✔
3117
            case type_Int:
12✔
3118
                if (is_nullable(from)) {
12✔
3119
                    change_nullability_list<Optional<int64_t>, int64_t>(from, to, throw_on_null);
6✔
3120
                }
6✔
3121
                else {
6✔
3122
                    change_nullability_list<int64_t, Optional<int64_t>>(from, to, throw_on_null);
6✔
3123
                }
6✔
3124
                break;
12✔
3125
            case type_Float:
12✔
3126
                change_nullability_list<float, float>(from, to, throw_on_null);
12✔
3127
                break;
12✔
3128
            case type_Double:
12✔
3129
                change_nullability_list<double, double>(from, to, throw_on_null);
12✔
3130
                break;
12✔
3131
            case type_Bool:
12✔
3132
                change_nullability_list<Optional<bool>, Optional<bool>>(from, to, throw_on_null);
12✔
3133
                break;
12✔
3134
            case type_String:
12✔
3135
                change_nullability_list<StringData, StringData>(from, to, throw_on_null);
12✔
3136
                break;
12✔
3137
            case type_Binary:
12✔
3138
                change_nullability_list<BinaryData, BinaryData>(from, to, throw_on_null);
12✔
3139
                break;
12✔
3140
            case type_Timestamp:
12✔
3141
                change_nullability_list<Timestamp, Timestamp>(from, to, throw_on_null);
12✔
3142
                break;
12✔
3143
            case type_ObjectId:
12✔
3144
                if (is_nullable(from)) {
12✔
3145
                    change_nullability_list<Optional<ObjectId>, ObjectId>(from, to, throw_on_null);
6✔
3146
                }
6✔
3147
                else {
6✔
3148
                    change_nullability_list<ObjectId, Optional<ObjectId>>(from, to, throw_on_null);
6✔
3149
                }
6✔
3150
                break;
12✔
3151
            case type_Decimal:
12✔
3152
                change_nullability_list<Decimal128, Decimal128>(from, to, throw_on_null);
12✔
3153
                break;
12✔
3154
            case type_UUID:
12✔
3155
                if (is_nullable(from)) {
12✔
3156
                    change_nullability_list<Optional<UUID>, UUID>(from, to, throw_on_null);
6✔
3157
                }
6✔
3158
                else {
6✔
3159
                    change_nullability_list<UUID, Optional<UUID>>(from, to, throw_on_null);
6✔
3160
                }
6✔
3161
                break;
12✔
3162
            case type_Link:
✔
3163
            case type_TypedLink:
✔
3164
                // Can't have lists of these types
3165
            case type_Mixed:
✔
3166
                // These types are no longer supported at all
3167
                REALM_UNREACHABLE();
3168
                break;
×
3169
        }
120✔
3170
    }
120✔
3171
    else {
162✔
3172
        switch (type_id) {
162✔
3173
            case type_Int:
36✔
3174
                if (is_nullable(from)) {
36✔
3175
                    change_nullability<Optional<int64_t>, int64_t>(from, to, throw_on_null);
6✔
3176
                }
6✔
3177
                else {
30✔
3178
                    change_nullability<int64_t, Optional<int64_t>>(from, to, throw_on_null);
30✔
3179
                }
30✔
3180
                break;
36✔
3181
            case type_Float:
12✔
3182
                change_nullability<float, float>(from, to, throw_on_null);
12✔
3183
                break;
12✔
3184
            case type_Double:
12✔
3185
                change_nullability<double, double>(from, to, throw_on_null);
12✔
3186
                break;
12✔
3187
            case type_Bool:
12✔
3188
                change_nullability<Optional<bool>, Optional<bool>>(from, to, throw_on_null);
12✔
3189
                break;
12✔
3190
            case type_String:
30✔
3191
                change_nullability<StringData, StringData>(from, to, throw_on_null);
30✔
3192
                break;
30✔
3193
            case type_Binary:
12✔
3194
                change_nullability<BinaryData, BinaryData>(from, to, throw_on_null);
12✔
3195
                break;
12✔
3196
            case type_Timestamp:
12✔
3197
                change_nullability<Timestamp, Timestamp>(from, to, throw_on_null);
12✔
3198
                break;
12✔
3199
            case type_ObjectId:
12✔
3200
                if (is_nullable(from)) {
12✔
3201
                    change_nullability<Optional<ObjectId>, ObjectId>(from, to, throw_on_null);
6✔
3202
                }
6✔
3203
                else {
6✔
3204
                    change_nullability<ObjectId, Optional<ObjectId>>(from, to, throw_on_null);
6✔
3205
                }
6✔
3206
                break;
12✔
3207
            case type_Decimal:
12✔
3208
                change_nullability<Decimal128, Decimal128>(from, to, throw_on_null);
12✔
3209
                break;
12✔
3210
            case type_UUID:
12✔
3211
                if (is_nullable(from)) {
12✔
3212
                    change_nullability<Optional<UUID>, UUID>(from, to, throw_on_null);
6✔
3213
                }
6✔
3214
                else {
6✔
3215
                    change_nullability<UUID, Optional<UUID>>(from, to, throw_on_null);
6✔
3216
                }
6✔
3217
                break;
12✔
3218
            case type_TypedLink:
✔
3219
            case type_Link:
✔
3220
                // Always nullable, so can't convert
3221
            case type_Mixed:
✔
3222
                // These types are no longer supported at all
3223
                REALM_UNREACHABLE();
3224
                break;
×
3225
        }
162✔
3226
    }
162✔
3227
}
282✔
3228

3229

3230
ColKey Table::set_nullability(ColKey col_key, bool nullable, bool throw_on_null)
3231
{
522✔
3232
    if (col_key.is_nullable() == nullable)
522✔
3233
        return col_key;
240✔
3234

3235
    check_column(col_key);
282✔
3236

3237
    auto index_type = search_index_type(col_key);
282✔
3238
    std::string column_name(get_column_name(col_key));
282✔
3239
    auto type = col_key.get_type();
282✔
3240
    auto attr = col_key.get_attrs();
282✔
3241
    bool is_pk_col = (col_key == m_primary_key_col);
282✔
3242
    if (nullable) {
282✔
3243
        attr.set(col_attr_Nullable);
150✔
3244
    }
150✔
3245
    else {
132✔
3246
        attr.reset(col_attr_Nullable);
132✔
3247
    }
132✔
3248

3249
    ColKey new_col = generate_col_key(type, attr);
282✔
3250
    do_insert_root_column(new_col, type, "__temporary");
282✔
3251

3252
    try {
282✔
3253
        convert_column(col_key, new_col, throw_on_null);
282✔
3254
    }
282✔
3255
    catch (...) {
282✔
3256
        // remove any partially filled column
3257
        remove_column(new_col);
6✔
3258
        throw;
6✔
3259
    }
6✔
3260

3261
    if (is_pk_col) {
276✔
3262
        // If we go from non nullable to nullable, no values change,
3263
        // so it is safe to preserve the pk column. Otherwise it is not
3264
        // safe as a null entry might have been converted to default value.
3265
        do_set_primary_key_column(nullable ? new_col : ColKey{});
12✔
3266
    }
12✔
3267

3268
    erase_root_column(col_key);
276✔
3269
    m_spec.rename_column(colkey2spec_ndx(new_col), column_name);
276✔
3270

3271
    if (index_type != IndexType::None)
276✔
3272
        do_add_search_index(new_col, index_type);
30✔
3273

3274
    return new_col;
276✔
3275
}
282✔
3276

3277
bool Table::has_any_embedded_objects()
3278
{
2,470,098✔
3279
    if (!m_has_any_embedded_objects) {
2,470,098✔
3280
        m_has_any_embedded_objects = false;
25,188✔
3281
        for_each_public_column([&](ColKey col_key) {
60,135✔
3282
            auto target_table_key = get_opposite_table_key(col_key);
60,135✔
3283
            if (target_table_key && is_link_type(col_key.get_type())) {
60,135✔
3284
                auto target_table = get_parent_group()->get_table_unchecked(target_table_key);
11,430✔
3285
                if (target_table->is_embedded()) {
11,430✔
3286
                    m_has_any_embedded_objects = true;
9,300✔
3287
                    return IteratorControl::Stop; // early out
9,300✔
3288
                }
9,300✔
3289
            }
11,430✔
3290
            return IteratorControl::AdvanceToNext;
50,835✔
3291
        });
60,135✔
3292
    }
25,188✔
3293
    return *m_has_any_embedded_objects;
2,470,098✔
3294
}
2,470,098✔
3295

3296
void Table::set_opposite_column(ColKey col_key, TableKey opposite_table, ColKey opposite_column)
3297
{
155,922✔
3298
    m_opposite_table.set(col_key.get_index().val, opposite_table.value);
155,922✔
3299
    m_opposite_column.set(col_key.get_index().val, opposite_column.value);
155,922✔
3300
}
155,922✔
3301

3302
ColKey Table::find_backlink_column(ColKey origin_col_key, TableKey origin_table) const
3303
{
47,580✔
3304
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
163,305✔
3305
        if (m_opposite_column.get(i) == origin_col_key.value && m_opposite_table.get(i) == origin_table.value) {
155,547✔
3306
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
39,822✔
3307
        }
39,822✔
3308
    }
155,547✔
3309

3310
    return {};
7,758✔
3311
}
47,580✔
3312

3313
ColKey Table::find_or_add_backlink_column(ColKey origin_col_key, TableKey origin_table)
3314
{
47,508✔
3315
    ColKey backlink_col_key = find_backlink_column(origin_col_key, origin_table);
47,508✔
3316

3317
    if (!backlink_col_key) {
47,508✔
3318
        backlink_col_key = do_insert_root_column(ColKey{}, col_type_BackLink, "");
7,758✔
3319
        set_opposite_column(backlink_col_key, origin_table, origin_col_key);
7,758✔
3320

3321
        if (Replication* repl = get_repl())
7,758✔
3322
            repl->typed_link_change(get_parent_group()->get_table_unchecked(origin_table), origin_col_key,
7,452✔
3323
                                    m_key); // Throws
7,452✔
3324
    }
7,758✔
3325

3326
    return backlink_col_key;
47,508✔
3327
}
47,508✔
3328

3329
TableKey Table::get_opposite_table_key(ColKey col_key) const
3330
{
14,466,681✔
3331
    return TableKey(int32_t(m_opposite_table.get(col_key.get_index().val)));
14,466,681✔
3332
}
14,466,681✔
3333

3334
bool Table::links_to_self(ColKey col_key) const
3335
{
66,924✔
3336
    return get_opposite_table_key(col_key) == m_key;
66,924✔
3337
}
66,924✔
3338

3339
TableRef Table::get_opposite_table(ColKey col_key) const
3340
{
7,814,592✔
3341
    if (auto k = get_opposite_table_key(col_key)) {
7,814,592✔
3342
        return get_parent_group()->get_table(k);
7,756,185✔
3343
    }
7,756,185✔
3344
    return {};
58,407✔
3345
}
7,814,592✔
3346

3347
ColKey Table::get_opposite_column(ColKey col_key) const
3348
{
16,294,239✔
3349
    return ColKey(m_opposite_column.get(col_key.get_index().val));
16,294,239✔
3350
}
16,294,239✔
3351

3352
ColKey Table::find_opposite_column(ColKey col_key) const
3353
{
×
3354
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
×
3355
        if (m_opposite_column.get(i) == col_key.value) {
×
3356
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
×
3357
        }
×
3358
    }
×
3359
    return ColKey();
×
3360
}
×
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