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

realm / realm-core / 1707

25 Sep 2023 06:02PM UTC coverage: 91.192% (-0.006%) from 91.198%
1707

push

Evergreen

web-flow
Fixed double delete in CAPITimer and add documentation for platform networking CAPI integration (#6994)

* Fixed double delete in CAPITimer and added individual functions for handling callbacks.
* Added realm_sync_socket_write_complete() fcn and other updates from review
* Don't call handler functions more than once, esp for timers; updated documentation
* Updated some comments
* Updated changelog after release

95848 of 175718 branches covered (0.0%)

20 of 33 new or added lines in 2 files covered. (60.61%)

65 existing lines in 13 files now uncovered.

232403 of 254849 relevant lines covered (91.19%)

6713313.75 hits per line

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

90.34
/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/miscellaneous.hpp>
38
#include <realm/util/serializer.hpp>
39

40
#include <stdexcept>
41

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

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

261

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

265
Replication* Table::g_dummy_replication = nullptr;
266

267
bool TableVersions::operator==(const TableVersions& other) const
268
{
16,191✔
269
    if (size() != other.size())
16,191✔
270
        return false;
×
271
    size_t sz = size();
16,191✔
272
    for (size_t i = 0; i < sz; i++) {
25,722✔
273
        REALM_ASSERT_DEBUG(this->at(i).first == other.at(i).first);
16,323✔
274
        if (this->at(i).second != other.at(i).second)
16,323✔
275
            return false;
6,792✔
276
    }
16,323✔
277
    return true;
12,795✔
278
}
16,191✔
279

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

325
std::ostream& operator<<(std::ostream& o, Table::Type table_type)
326
{
19,074✔
327
    switch (table_type) {
19,074✔
328
        case Table::Type::TopLevel:
19,029✔
329
            return o << "TopLevel";
19,029✔
330
        case Table::Type::Embedded:
6✔
331
            return o << "Embedded";
6✔
332
        case Table::Type::TopLevelAsymmetric:
39✔
333
            return o << "TopLevelAsymmetric";
39✔
334
    }
×
335
    return o << "Invalid table type: " << uint8_t(table_type);
×
336
}
×
337
} // namespace realm
338

339
void LinkChain::add(ColKey ck)
340
{
87,954✔
341
    // Link column can be a single Link, LinkList, or BackLink.
43,977✔
342
    REALM_ASSERT(m_current_table->valid_column(ck));
87,954✔
343
    ColumnType type = ck.get_type();
87,954✔
344
    if (type == col_type_LinkList || type == col_type_Link || type == col_type_BackLink) {
87,954✔
345
        m_current_table = m_current_table->get_opposite_table(ck);
85,389✔
346
    }
85,389✔
347
    else {
2,565✔
348
        // Only last column in link chain is allowed to be non-link
1,284✔
349
        throw LogicError(ErrorCodes::TypeMismatch,
2,565✔
350
                         util::format("Property '%1.%2' is not an object reference",
2,565✔
351
                                      m_current_table->get_class_name(), m_current_table->get_column_name(ck)));
2,565✔
352
    }
2,565✔
353
    m_link_cols.push_back(ck);
85,389✔
354
}
85,389✔
355

356
// -- Table ---------------------------------------------------------------------------------
357

358
Table::Table(Allocator& alloc)
359
    : m_alloc(alloc)
360
    , m_top(m_alloc)
361
    , m_spec(m_alloc)
362
    , m_clusters(this, m_alloc, top_position_for_cluster_tree)
363
    , m_index_refs(m_alloc)
364
    , m_opposite_table(m_alloc)
365
    , m_opposite_column(m_alloc)
366
    , m_repl(&g_dummy_replication)
367
    , m_own_ref(this, alloc.get_instance_version())
368
{
3,552✔
369
    m_spec.set_parent(&m_top, top_position_for_spec);
3,552✔
370
    m_index_refs.set_parent(&m_top, top_position_for_search_indexes);
3,552✔
371
    m_opposite_table.set_parent(&m_top, top_position_for_opposite_table);
3,552✔
372
    m_opposite_column.set_parent(&m_top, top_position_for_opposite_column);
3,552✔
373

1,776✔
374
    ref_type ref = create_empty_table(m_alloc); // Throws
3,552✔
375
    ArrayParent* parent = nullptr;
3,552✔
376
    size_t ndx_in_parent = 0;
3,552✔
377
    init(ref, parent, ndx_in_parent, true, false);
3,552✔
378
}
3,552✔
379

380
Table::Table(Replication* const* repl, Allocator& alloc)
381
    : m_alloc(alloc)
382
    , m_top(m_alloc)
383
    , m_spec(m_alloc)
384
    , m_clusters(this, m_alloc, top_position_for_cluster_tree)
385
    , m_index_refs(m_alloc)
386
    , m_opposite_table(m_alloc)
387
    , m_opposite_column(m_alloc)
388
    , m_repl(repl)
389
    , m_own_ref(this, alloc.get_instance_version())
390
{
30,093✔
391
    m_spec.set_parent(&m_top, top_position_for_spec);
30,093✔
392
    m_index_refs.set_parent(&m_top, top_position_for_search_indexes);
30,093✔
393
    m_opposite_table.set_parent(&m_top, top_position_for_opposite_table);
30,093✔
394
    m_opposite_column.set_parent(&m_top, top_position_for_opposite_column);
30,093✔
395
    m_cookie = cookie_created;
30,093✔
396
}
30,093✔
397

398
ColKey Table::add_column(DataType type, StringData name, bool nullable)
399
{
503,550✔
400
    REALM_ASSERT(!is_link_type(ColumnType(type)));
503,550✔
401

246,966✔
402
    Table* invalid_link = nullptr;
503,550✔
403
    ColumnAttrMask attr;
503,550✔
404
    if (nullable || type == type_Mixed)
503,550✔
405
        attr.set(col_attr_Nullable);
110,688✔
406
    ColKey col_key = generate_col_key(ColumnType(type), attr);
503,550✔
407

246,966✔
408
    return do_insert_column(col_key, type, name, invalid_link); // Throws
503,550✔
409
}
503,550✔
410

411
ColKey Table::add_column(Table& target, StringData name)
412
{
29,379✔
413
    // Both origin and target must be group-level tables, and in the same group.
14,571✔
414
    Group* origin_group = get_parent_group();
29,379✔
415
    Group* target_group = target.get_parent_group();
29,379✔
416
    REALM_ASSERT_RELEASE(origin_group && target_group);
29,379✔
417
    REALM_ASSERT_RELEASE(origin_group == target_group);
29,379✔
418
    // Incoming links from an asymmetric table are not allowed.
14,571✔
419
    if (target.is_asymmetric()) {
29,379✔
420
        throw IllegalOperation("Ephemeral objects not supported");
6✔
421
    }
6✔
422

14,568✔
423
    m_has_any_embedded_objects.reset();
29,373✔
424

14,568✔
425
    ColumnAttrMask attr;
29,373✔
426
    attr.set(col_attr_Nullable);
29,373✔
427
    ColKey col_key = generate_col_key(col_type_Link, attr);
29,373✔
428

14,568✔
429
    auto retval = do_insert_column(col_key, type_Link, name, &target); // Throws
29,373✔
430
    return retval;
29,373✔
431
}
29,373✔
432

433
ColKey Table::add_column_list(DataType type, StringData name, bool nullable)
434
{
80,775✔
435
    Table* invalid_link = nullptr;
80,775✔
436
    ColumnAttrMask attr;
80,775✔
437
    attr.set(col_attr_List);
80,775✔
438
    if (nullable || type == type_Mixed)
80,775✔
439
        attr.set(col_attr_Nullable);
28,896✔
440
    ColKey col_key = generate_col_key(ColumnType(type), attr);
80,775✔
441
    return do_insert_column(col_key, type, name, invalid_link); // Throws
80,775✔
442
}
80,775✔
443

444
ColKey Table::add_column_set(DataType type, StringData name, bool nullable)
445
{
52,509✔
446
    Table* invalid_link = nullptr;
52,509✔
447
    ColumnAttrMask attr;
52,509✔
448
    attr.set(col_attr_Set);
52,509✔
449
    if (nullable || type == type_Mixed)
52,509✔
450
        attr.set(col_attr_Nullable);
21,762✔
451
    ColKey col_key = generate_col_key(ColumnType(type), attr);
52,509✔
452
    return do_insert_column(col_key, type, name, invalid_link); // Throws
52,509✔
453
}
52,509✔
454

455
ColKey Table::add_column_list(Table& target, StringData name)
456
{
30,090✔
457
    // Both origin and target must be group-level tables, and in the same group.
14,817✔
458
    Group* origin_group = get_parent_group();
30,090✔
459
    Group* target_group = target.get_parent_group();
30,090✔
460
    REALM_ASSERT_RELEASE(origin_group && target_group);
30,090✔
461
    REALM_ASSERT_RELEASE(origin_group == target_group);
30,090✔
462
    // Only links to embedded objects are allowed.
14,817✔
463
    if (is_asymmetric() && !target.is_embedded()) {
30,090✔
464
        throw IllegalOperation("List of objects not supported in asymmetric table");
×
465
    }
×
466
    // Incoming links from an asymmetric table are not allowed.
14,817✔
467
    if (target.is_asymmetric()) {
30,090✔
468
        throw IllegalOperation("List of ephemeral objects not supported");
×
469
    }
×
470

14,817✔
471
    m_has_any_embedded_objects.reset();
30,090✔
472

14,817✔
473
    ColumnAttrMask attr;
30,090✔
474
    attr.set(col_attr_List);
30,090✔
475
    ColKey col_key = generate_col_key(col_type_LinkList, attr);
30,090✔
476

14,817✔
477
    return do_insert_column(col_key, type_LinkList, name, &target); // Throws
30,090✔
478
}
30,090✔
479

480
ColKey Table::add_column_set(Table& target, StringData name)
481
{
10,440✔
482
    // Both origin and target must be group-level tables, and in the same group.
5,166✔
483
    Group* origin_group = get_parent_group();
10,440✔
484
    Group* target_group = target.get_parent_group();
10,440✔
485
    REALM_ASSERT_RELEASE(origin_group && target_group);
10,440✔
486
    REALM_ASSERT_RELEASE(origin_group == target_group);
10,440✔
487
    if (target.is_embedded())
10,440✔
488
        throw IllegalOperation("Set of embedded objects not supported");
×
489
    // Outgoing links from an asymmetric table are not allowed.
5,166✔
490
    if (is_asymmetric()) {
10,440✔
491
        throw IllegalOperation("Set of objects not supported in asymmetric table");
×
492
    }
×
493
    // Incoming links from an asymmetric table are not allowed.
5,166✔
494
    if (target.is_asymmetric()) {
10,440✔
495
        throw IllegalOperation("Set of ephemeral objects not supported");
×
496
    }
×
497

5,166✔
498
    ColumnAttrMask attr;
10,440✔
499
    attr.set(col_attr_Set);
10,440✔
500
    ColKey col_key = generate_col_key(col_type_Link, attr);
10,440✔
501
    return do_insert_column(col_key, type_Link, name, &target); // Throws
10,440✔
502
}
10,440✔
503

504
ColKey Table::add_column_link(DataType type, StringData name, Table& target)
505
{
×
506
    REALM_ASSERT(is_link_type(ColumnType(type)));
×
507

508
    if (type == type_LinkList) {
×
509
        return add_column_list(target, name);
×
510
    }
×
511
    else {
×
512
        REALM_ASSERT(type == type_Link);
×
513
        return add_column(target, name);
×
514
    }
×
515
}
×
516

517
ColKey Table::add_column_dictionary(DataType type, StringData name, bool nullable, DataType key_type)
518
{
42,474✔
519
    Table* invalid_link = nullptr;
42,474✔
520
    ColumnAttrMask attr;
42,474✔
521
    REALM_ASSERT(key_type != type_Mixed);
42,474✔
522
    attr.set(col_attr_Dictionary);
42,474✔
523
    if (nullable || type == type_Mixed)
42,474✔
524
        attr.set(col_attr_Nullable);
22,980✔
525
    ColKey col_key = generate_col_key(ColumnType(type), attr);
42,474✔
526
    return do_insert_column(col_key, type, name, invalid_link, key_type); // Throws
42,474✔
527
}
42,474✔
528

529
ColKey Table::add_column_dictionary(Table& target, StringData name, DataType key_type)
530
{
10,932✔
531
    // Both origin and target must be group-level tables, and in the same group.
5,358✔
532
    Group* origin_group = get_parent_group();
10,932✔
533
    Group* target_group = target.get_parent_group();
10,932✔
534
    REALM_ASSERT_RELEASE(origin_group && target_group);
10,932✔
535
    REALM_ASSERT_RELEASE(origin_group == target_group);
10,932✔
536
    // Only links to embedded objects are allowed.
5,358✔
537
    if (is_asymmetric() && !target.is_embedded()) {
10,932✔
538
        throw IllegalOperation("Dictionary of objects not supported in asymmetric table");
×
539
    }
×
540
    // Incoming links from an asymmetric table are not allowed.
5,358✔
541
    if (target.is_asymmetric()) {
10,932✔
542
        throw IllegalOperation("Dictionary of ephemeral objects not supported");
×
543
    }
×
544

5,358✔
545
    ColumnAttrMask attr;
10,932✔
546
    attr.set(col_attr_Dictionary);
10,932✔
547
    attr.set(col_attr_Nullable);
10,932✔
548

5,358✔
549
    ColKey col_key = generate_col_key(ColumnType(col_type_Link), attr);
10,932✔
550
    return do_insert_column(col_key, type_Link, name, &target, key_type); // Throws
10,932✔
551
}
10,932✔
552

553
void Table::remove_recursive(CascadeState& cascade_state)
554
{
14,574✔
555
    Group* group = get_parent_group();
14,574✔
556
    REALM_ASSERT(group);
14,574✔
557
    cascade_state.m_group = group;
14,574✔
558

6,621✔
559
    do {
18,600✔
560
        cascade_state.send_notifications();
18,600✔
561

8,634✔
562
        for (auto& l : cascade_state.m_to_be_nullified) {
8,658✔
563
            Obj obj = group->get_table(l.origin_table)->try_get_object(l.origin_key);
48✔
564
            REALM_ASSERT_DEBUG(obj);
48✔
565
            if (obj) {
48✔
566
                std::move(obj).nullify_link(l.origin_col_key, l.old_target_link);
48✔
567
            }
48✔
568
        }
48✔
569
        cascade_state.m_to_be_nullified.clear();
18,600✔
570

8,634✔
571
        auto to_delete = std::move(cascade_state.m_to_be_deleted);
18,600✔
572
        for (auto obj : to_delete) {
16,587✔
573
            auto table = group->get_table(obj.first);
15,885✔
574
            // This might add to the list of objects that should be deleted
7,932✔
575
            REALM_ASSERT(!obj.second.is_unresolved());
15,885✔
576
            table->m_clusters.erase(obj.second, cascade_state);
15,885✔
577
        }
15,885✔
578
        nullify_links(cascade_state);
18,600✔
579
    } while (!cascade_state.m_to_be_deleted.empty() || !cascade_state.m_to_be_nullified.empty());
18,600✔
580
}
14,574✔
581

582
void Table::nullify_links(CascadeState& cascade_state)
583
{
23,166✔
584
    Group* group = get_parent_group();
23,166✔
585
    REALM_ASSERT(group);
23,166✔
586
    for (auto& to_delete : cascade_state.m_to_be_deleted) {
14,865✔
587
        auto table = group->get_table(to_delete.first);
7,878✔
588
        table->m_clusters.nullify_links(to_delete.second, cascade_state);
7,878✔
589
    }
7,878✔
590
}
23,166✔
591

592

593
void Table::remove_column(ColKey col_key)
594
{
17,577✔
595
    check_column(col_key);
17,577✔
596

9,096✔
597
    if (Replication* repl = get_repl())
17,577✔
598
        repl->erase_column(this, col_key); // Throws
519✔
599

9,096✔
600
    if (col_key == m_primary_key_col) {
17,577✔
601
        do_set_primary_key_column(ColKey());
7,299✔
602
    }
7,299✔
603
    else {
10,278✔
604
        REALM_ASSERT_RELEASE(m_primary_key_col.get_index().val != col_key.get_index().val);
10,278✔
605
    }
10,278✔
606

9,096✔
607
    erase_root_column(col_key); // Throws
17,577✔
608
    m_has_any_embedded_objects.reset();
17,577✔
609
}
17,577✔
610

611

612
void Table::rename_column(ColKey col_key, StringData name)
613
{
90✔
614
    check_column(col_key);
90✔
615

39✔
616
    auto col_ndx = colkey2spec_ndx(col_key);
90✔
617
    m_spec.rename_column(col_ndx, name); // Throws
90✔
618

39✔
619
    bump_content_version();
90✔
620
    bump_storage_version();
90✔
621

39✔
622
    if (Replication* repl = get_repl())
90✔
623
        repl->rename_column(this, col_key, name); // Throws
90✔
624
}
90✔
625

626

627
TableKey Table::get_key_direct(Allocator& alloc, ref_type top_ref)
628
{
9,912,501✔
629
    // well, not quite "direct", more like "almost direct":
5,227,956✔
630
    Array table_top(alloc);
9,912,501✔
631
    table_top.init_from_ref(top_ref);
9,912,501✔
632
    if (table_top.size() > 3) {
9,912,501✔
633
        RefOrTagged rot = table_top.get_as_ref_or_tagged(top_position_for_key);
9,911,694✔
634
        return TableKey(int32_t(rot.get_as_int()));
9,911,694✔
635
    }
9,911,694✔
636
    else {
807✔
637
        return TableKey();
807✔
638
    }
807✔
639
}
9,912,501✔
640

641

642
void Table::init(ref_type top_ref, ArrayParent* parent, size_t ndx_in_parent, bool is_writable, bool is_frzn)
643
{
5,099,904✔
644
    REALM_ASSERT(!(is_writable && is_frzn));
5,099,904✔
645
    m_is_frozen = is_frzn;
5,099,904✔
646
    m_alloc.set_read_only(!is_writable);
5,099,904✔
647
    // Load from allocated memory
2,804,736✔
648
    m_top.set_parent(parent, ndx_in_parent);
5,099,904✔
649
    m_top.init_from_ref(top_ref);
5,099,904✔
650

2,804,736✔
651
    m_spec.init_from_parent();
5,099,904✔
652

2,804,736✔
653
    while (m_top.size() <= top_position_for_pk_col) {
5,100,864✔
654
        m_top.add(0);
960✔
655
    }
960✔
656

2,804,736✔
657
    if (m_top.get_as_ref(top_position_for_cluster_tree) == 0) {
5,099,904✔
658
        // This is an upgrade - create cluster
48✔
659
        MemRef mem = Cluster::create_empty_cluster(m_top.get_alloc()); // Throws
96✔
660
        m_top.set_as_ref(top_position_for_cluster_tree, mem.get_ref());
96✔
661
    }
96✔
662
    m_clusters.init_from_parent();
5,099,904✔
663

2,804,736✔
664
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_key);
5,099,904✔
665
    if (!rot.is_tagged()) {
5,099,904✔
666
        // Create table key
48✔
667
        rot = RefOrTagged::make_tagged(ndx_in_parent);
96✔
668
        m_top.set(top_position_for_key, rot);
96✔
669
    }
96✔
670
    m_key = TableKey(int32_t(rot.get_as_int()));
5,099,904✔
671

2,804,736✔
672
    // index setup relies on column mapping being up to date:
2,804,736✔
673
    build_column_mapping();
5,099,904✔
674
    if (m_top.get_as_ref(top_position_for_search_indexes) == 0) {
5,099,904✔
675
        // This is an upgrade - create the necessary arrays
48✔
676
        bool context_flag = false;
96✔
677
        size_t nb_columns = m_spec.get_column_count();
96✔
678
        MemRef mem = Array::create_array(Array::type_HasRefs, context_flag, nb_columns, 0, m_top.get_alloc());
96✔
679
        m_index_refs.init_from_mem(mem);
96✔
680
        m_index_refs.update_parent();
96✔
681
        mem = Array::create_array(Array::type_Normal, context_flag, nb_columns, TableKey().value, m_top.get_alloc());
96✔
682
        m_opposite_table.init_from_mem(mem);
96✔
683
        m_opposite_table.update_parent();
96✔
684
        mem = Array::create_array(Array::type_Normal, context_flag, nb_columns, ColKey().value, m_top.get_alloc());
96✔
685
        m_opposite_column.init_from_mem(mem);
96✔
686
        m_opposite_column.update_parent();
96✔
687
    }
96✔
688
    else {
5,099,808✔
689
        m_opposite_table.init_from_parent();
5,099,808✔
690
        m_opposite_column.init_from_parent();
5,099,808✔
691
        m_index_refs.init_from_parent();
5,099,808✔
692
        m_index_accessors.resize(m_index_refs.size());
5,099,808✔
693
    }
5,099,808✔
694
    if (!m_top.get_as_ref_or_tagged(top_position_for_column_key).is_tagged()) {
5,099,904✔
695
        m_top.set(top_position_for_column_key, RefOrTagged::make_tagged(0));
96✔
696
    }
96✔
697
    auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
5,099,904✔
698
    if (!rot_version.is_tagged()) {
5,099,904✔
699
        m_top.set(top_position_for_version, RefOrTagged::make_tagged(0));
96✔
700
        m_in_file_version_at_transaction_boundary = 0;
96✔
701
    }
96✔
702
    else
5,099,808✔
703
        m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
5,099,808✔
704

2,804,736✔
705
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
5,099,904✔
706
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
4,571,493✔
707

2,804,736✔
708
    if (m_top.size() <= top_position_for_flags) {
5,099,904✔
709
        m_table_type = Type::TopLevel;
702✔
710
    }
702✔
711
    else {
5,099,202✔
712
        uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
5,099,202✔
713
        m_table_type = Type(flags & table_type_mask);
5,099,202✔
714
    }
5,099,202✔
715
    m_has_any_embedded_objects.reset();
5,099,904✔
716

2,804,736✔
717
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
5,099,904✔
718
        // Tombstones exists
441,078✔
719
        if (!m_tombstones) {
867,816✔
720
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
533,529✔
721
        }
533,529✔
722
        m_tombstones->init_from_parent();
867,816✔
723
    }
867,816✔
724
    else {
4,232,088✔
725
        m_tombstones = nullptr;
4,232,088✔
726
    }
4,232,088✔
727
    m_cookie = cookie_initialized;
5,099,904✔
728
}
5,099,904✔
729

730

731
ColKey Table::do_insert_column(ColKey col_key, DataType type, StringData name, Table* target_table, DataType key_type)
732
{
760,149✔
733
    col_key = do_insert_root_column(col_key, ColumnType(type), name, key_type); // Throws
760,149✔
734

374,733✔
735
    // When the inserted column is a link-type column, we must also add a
374,733✔
736
    // backlink column to the target table.
374,733✔
737

374,733✔
738
    if (target_table) {
760,149✔
739
        auto backlink_col_key = target_table->do_insert_root_column(ColKey{}, col_type_BackLink, ""); // Throws
80,829✔
740
        target_table->check_column(backlink_col_key);
80,829✔
741

39,906✔
742
        set_opposite_column(col_key, target_table->get_key(), backlink_col_key);
80,829✔
743
        target_table->set_opposite_column(backlink_col_key, get_key(), col_key);
80,829✔
744
    }
80,829✔
745

374,733✔
746
    if (Replication* repl = get_repl())
760,149✔
747
        repl->insert_column(this, col_key, type, name, target_table); // Throws
742,488✔
748

374,733✔
749
    return col_key;
760,149✔
750
}
760,149✔
751

752

753
void Table::populate_search_index(ColKey col_key)
754
{
132,510✔
755
    auto col_ndx = col_key.get_index().val;
132,510✔
756
    StringIndex* index = m_index_accessors[col_ndx].get();
132,510✔
757

65,688✔
758
    // Insert ref to index
65,688✔
759
    for (auto o : *this) {
1,324,998✔
760
        ObjKey key = o.get_key();
1,324,998✔
761
        DataType type = get_column_type(col_key);
1,324,998✔
762

662,448✔
763
        if (type == type_Int) {
1,324,998✔
764
            if (is_nullable(col_key)) {
1,214,070✔
765
                Optional<int64_t> value = o.get<Optional<int64_t>>(col_key);
60✔
766
                index->insert(key, value); // Throws
60✔
767
            }
60✔
768
            else {
1,214,010✔
769
                int64_t value = o.get<int64_t>(col_key);
1,214,010✔
770
                index->insert(key, value); // Throws
1,214,010✔
771
            }
1,214,010✔
772
        }
1,214,070✔
773
        else if (type == type_Bool) {
110,928✔
774
            if (is_nullable(col_key)) {
156✔
775
                Optional<bool> value = o.get<Optional<bool>>(col_key);
54✔
776
                index->insert(key, value); // Throws
54✔
777
            }
54✔
778
            else {
102✔
779
                bool value = o.get<bool>(col_key);
102✔
780
                index->insert(key, value); // Throws
102✔
781
            }
102✔
782
        }
156✔
783
        else if (type == type_String) {
110,772✔
784
            StringData value = o.get<StringData>(col_key);
110,562✔
785
            index->insert(key, value); // Throws
110,562✔
786
        }
110,562✔
787
        else if (type == type_Timestamp) {
210✔
788
            Timestamp value = o.get<Timestamp>(col_key);
132✔
789
            index->insert(key, value); // Throws
132✔
790
        }
132✔
791
        else if (type == type_ObjectId) {
78✔
792
            if (is_nullable(col_key)) {
36✔
793
                Optional<ObjectId> value = o.get<Optional<ObjectId>>(col_key);
18✔
794
                index->insert(key, value); // Throws
18✔
795
            }
18✔
796
            else {
18✔
797
                ObjectId value = o.get<ObjectId>(col_key);
18✔
798
                index->insert(key, value); // Throws
18✔
799
            }
18✔
800
        }
36✔
801
        else if (type == type_UUID) {
42✔
802
            if (is_nullable(col_key)) {
36✔
803
                Optional<UUID> value = o.get<Optional<UUID>>(col_key);
18✔
804
                index->insert(key, value); // Throws
18✔
805
            }
18✔
806
            else {
18✔
807
                UUID value = o.get<UUID>(col_key);
18✔
808
                index->insert(key, value); // Throws
18✔
809
            }
18✔
810
        }
36✔
811
        else if (type == type_Mixed) {
6✔
812
            index->insert(key, o.get<Mixed>(col_key));
6✔
813
        }
6✔
UNCOV
814
        else {
×
UNCOV
815
            REALM_ASSERT_RELEASE(false && "Data type does not support search index");
×
UNCOV
816
        }
×
817
    }
1,324,998✔
818
}
132,510✔
819

820
void Table::erase_from_search_indexes(ObjKey key)
821
{
5,028,483✔
822
    // Tombstones do not use index - will crash if we try to erase values
2,514,837✔
823
    if (!key.is_unresolved()) {
5,028,483✔
824
        for (auto&& index : m_index_accessors) {
6,705,777✔
825
            if (index) {
6,705,777✔
826
                index->erase(key);
282,297✔
827
            }
282,297✔
828
        }
6,705,777✔
829
    }
5,014,923✔
830
}
5,028,483✔
831

832
void Table::update_indexes(ObjKey key, const FieldValues& values)
833
{
22,935,570✔
834
    // Tombstones do not use index - will crash if we try to insert values
11,398,710✔
835
    if (key.is_unresolved()) {
22,935,570✔
836
        return;
29,109✔
837
    }
29,109✔
838

11,384,004✔
839
    auto sz = m_index_accessors.size();
22,906,461✔
840
    // values are sorted by column index - there may be values missing
11,384,004✔
841
    auto value = values.begin();
22,906,461✔
842
    for (size_t column_ndx = 0; column_ndx < sz; column_ndx++) {
56,580,390✔
843
        // Check if initial value is provided
16,649,886✔
844
        Mixed init_value;
33,674,049✔
845
        if (value != values.end() && value->col_key.get_index().val == column_ndx) {
33,674,049✔
846
            // Value for this column is provided
282,390✔
847
            init_value = value->value;
586,116✔
848
            ++value;
586,116✔
849
        }
586,116✔
850

16,649,886✔
851
        if (auto&& index = m_index_accessors[column_ndx]) {
33,674,049✔
852
            // There is an index for this column
554,445✔
853
            auto col_key = m_leaf_ndx2colkey[column_ndx];
1,130,376✔
854
            auto type = col_key.get_type();
1,130,376✔
855
            auto attr = col_key.get_attrs();
1,130,376✔
856
            bool nullable = attr.test(col_attr_Nullable);
1,130,376✔
857
            switch (type) {
1,130,376✔
858
                case col_type_Int:
531,738✔
859
                    if (init_value.is_null()) {
531,738✔
860
                        index->insert(key, ArrayIntNull::default_value(nullable));
165,633✔
861
                    }
165,633✔
862
                    else {
366,105✔
863
                        index->insert(key, init_value.get<int64_t>());
366,105✔
864
                    }
366,105✔
865
                    break;
531,738✔
866
                case col_type_Bool:
6,126✔
867
                    if (init_value.is_null()) {
6,126✔
868
                        index->insert(key, ArrayBoolNull::default_value(nullable));
6,090✔
869
                    }
6,090✔
870
                    else {
36✔
871
                        index->insert(key, init_value.get<bool>());
36✔
872
                    }
36✔
873
                    break;
6,126✔
874
                case col_type_String:
481,683✔
875
                    if (init_value.is_null()) {
481,683✔
876
                        index->insert(key, ArrayString::default_value(nullable));
432,690✔
877
                    }
432,690✔
878
                    else {
48,993✔
879
                        index->insert(key, init_value.get<String>());
48,993✔
880
                    }
48,993✔
881
                    break;
481,683✔
882
                case col_type_Timestamp:
6,162✔
883
                    if (init_value.is_null()) {
6,162✔
884
                        index->insert(key, ArrayTimestamp::default_value(nullable));
6,126✔
885
                    }
6,126✔
886
                    else {
36✔
887
                        index->insert(key, init_value.get<Timestamp>());
36✔
888
                    }
36✔
889
                    break;
6,162✔
890
                case col_type_ObjectId:
85,641✔
891
                    if (init_value.is_null()) {
85,641✔
892
                        index->insert(key, ArrayObjectIdNull::default_value(nullable));
6,120✔
893
                    }
6,120✔
894
                    else {
79,521✔
895
                        index->insert(key, init_value.get<ObjectId>());
79,521✔
896
                    }
79,521✔
897
                    break;
85,641✔
898
                case col_type_Mixed:
834✔
899
                    index->insert(key, init_value);
834✔
900
                    break;
834✔
901
                case col_type_UUID:
18,342✔
902
                    if (init_value.is_null()) {
18,342✔
903
                        index->insert(key, ArrayUUIDNull::default_value(nullable));
6,138✔
904
                    }
6,138✔
905
                    else {
12,204✔
906
                        index->insert(key, init_value.get<UUID>());
12,204✔
907
                    }
12,204✔
908
                    break;
18,342✔
909
                default:
✔
910
                    REALM_UNREACHABLE();
×
911
            }
1,130,376✔
912
        }
1,130,376✔
913
    }
33,674,049✔
914
}
22,906,461✔
915

916
void Table::clear_indexes()
917
{
3,519✔
918
    for (auto&& index : m_index_accessors) {
42,924✔
919
        if (index) {
42,924✔
920
            index->clear();
2,262✔
921
        }
2,262✔
922
    }
42,924✔
923
}
3,519✔
924

925
void Table::do_add_search_index(ColKey col_key, IndexType type)
926
{
132,942✔
927
    size_t column_ndx = col_key.get_index().val;
132,942✔
928

65,904✔
929
    // Early-out if already indexed
65,904✔
930
    if (m_index_accessors[column_ndx] != nullptr)
132,942✔
931
        return;
384✔
932

65,712✔
933
    if (!StringIndex::type_supported(DataType(col_key.get_type())) || col_key.is_collection() ||
132,558✔
934
        (type == IndexType::Fulltext && col_key.get_type() != col_type_String)) {
132,531✔
935
        // Not ideal, but this is what we used to throw, so keep throwing that for compatibility reasons, even though
24✔
936
        // it should probably be a type mismatch exception instead.
24✔
937
        throw IllegalOperation(util::format("Index not supported for this property: %1", get_column_name(col_key)));
48✔
938
    }
48✔
939

65,688✔
940
    // m_index_accessors always has the same number of pointers as the number of columns. Columns without search
65,688✔
941
    // index have 0-entries.
65,688✔
942
    REALM_ASSERT(m_index_accessors.size() == m_leaf_ndx2colkey.size());
132,510✔
943
    REALM_ASSERT(m_index_accessors[column_ndx] == nullptr);
132,510✔
944

65,688✔
945
    // Create the index
65,688✔
946
    m_index_accessors[column_ndx] =
132,510✔
947
        std::make_unique<StringIndex>(ClusterColumn(&m_clusters, col_key, type), get_alloc()); // Throws
132,510✔
948
    StringIndex* index = m_index_accessors[column_ndx].get();
132,510✔
949

65,688✔
950
    // Insert ref to index
65,688✔
951
    index->set_parent(&m_index_refs, column_ndx);
132,510✔
952
    m_index_refs.set(column_ndx, index->get_ref()); // Throws
132,510✔
953

65,688✔
954
    populate_search_index(col_key);
132,510✔
955
}
132,510✔
956

957
void Table::add_search_index(ColKey col_key, IndexType type)
958
{
3,846✔
959
    check_column(col_key);
3,846✔
960

1,911✔
961
    // Check spec
1,911✔
962
    auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
3,846✔
963
    auto attr = m_spec.get_column_attr(spec_ndx);
3,846✔
964

1,911✔
965
    if (col_key == m_primary_key_col && type == IndexType::Fulltext)
3,846✔
966
        throw InvalidColumnKey("primary key cannot have a full text index");
6✔
967

1,908✔
968
    switch (type) {
3,840✔
969
        case IndexType::None:
✔
970
            remove_search_index(col_key);
×
971
            return;
×
972
        case IndexType::Fulltext:
54✔
973
            // Early-out if already indexed
27✔
974
            if (attr.test(col_attr_FullText_Indexed)) {
54✔
975
                REALM_ASSERT(search_index_type(col_key) == IndexType::Fulltext);
×
976
                return;
×
977
            }
×
978
            if (attr.test(col_attr_Indexed)) {
54✔
979
                this->remove_search_index(col_key);
×
980
            }
×
981
            break;
54✔
982
        case IndexType::General:
3,786✔
983
            if (attr.test(col_attr_Indexed)) {
3,786✔
984
                REALM_ASSERT(search_index_type(col_key) == IndexType::General);
24✔
985
                return;
24✔
986
            }
24✔
987
            if (attr.test(col_attr_FullText_Indexed)) {
3,762✔
988
                this->remove_search_index(col_key);
×
989
            }
×
990
            break;
3,762✔
991
    }
3,816✔
992

1,896✔
993
    do_add_search_index(col_key, type);
3,816✔
994

1,896✔
995
    // Update spec
1,896✔
996
    attr.set(type == IndexType::Fulltext ? col_attr_FullText_Indexed : col_attr_Indexed);
3,789✔
997
    m_spec.set_column_attr(spec_ndx, attr); // Throws
3,816✔
998
}
3,816✔
999

1000
void Table::remove_search_index(ColKey col_key)
1001
{
7,713✔
1002
    check_column(col_key);
7,713✔
1003
    auto column_ndx = col_key.get_index();
7,713✔
1004

3,918✔
1005
    // Early-out if non-indexed
3,918✔
1006
    if (m_index_accessors[column_ndx.val] == nullptr)
7,713✔
1007
        return;
66✔
1008

3,894✔
1009
    // Destroy and remove the index column
3,894✔
1010
    auto& index = m_index_accessors[column_ndx.val];
7,647✔
1011
    REALM_ASSERT(index != nullptr);
7,647✔
1012
    index->destroy();
7,647✔
1013
    index.reset();
7,647✔
1014

3,894✔
1015
    m_index_refs.set(column_ndx.val, 0);
7,647✔
1016

3,894✔
1017
    // update spec
3,894✔
1018
    auto spec_ndx = leaf_ndx2spec_ndx(column_ndx);
7,647✔
1019
    auto attr = m_spec.get_column_attr(spec_ndx);
7,647✔
1020
    attr.reset(col_attr_Indexed);
7,647✔
1021
    attr.reset(col_attr_FullText_Indexed);
7,647✔
1022
    m_spec.set_column_attr(spec_ndx, attr); // Throws
7,647✔
1023
}
7,647✔
1024

1025
void Table::enumerate_string_column(ColKey col_key)
1026
{
1,296✔
1027
    check_column(col_key);
1,296✔
1028
    size_t column_ndx = colkey2spec_ndx(col_key);
1,296✔
1029
    ColumnType type = col_key.get_type();
1,296✔
1030
    if (type == col_type_String && !col_key.is_collection() && !m_spec.is_string_enum_type(column_ndx)) {
1,296✔
1031
        m_clusters.enumerate_string_column(col_key);
690✔
1032
    }
690✔
1033
}
1,296✔
1034

1035
bool Table::is_enumerated(ColKey col_key) const noexcept
1036
{
58,287✔
1037
    size_t col_ndx = colkey2spec_ndx(col_key);
58,287✔
1038
    return m_spec.is_string_enum_type(col_ndx);
58,287✔
1039
}
58,287✔
1040

1041
size_t Table::get_num_unique_values(ColKey col_key) const
1042
{
138✔
1043
    if (!is_enumerated(col_key))
138✔
1044
        return 0;
84✔
1045

27✔
1046
    ArrayParent* parent;
54✔
1047
    ref_type ref = const_cast<Spec&>(m_spec).get_enumkeys_ref(colkey2spec_ndx(col_key), parent);
54✔
1048
    BPlusTree<StringData> col(get_alloc());
54✔
1049
    col.init_from_ref(ref);
54✔
1050

27✔
1051
    return col.size();
54✔
1052
}
54✔
1053

1054

1055
void Table::erase_root_column(ColKey col_key)
1056
{
17,853✔
1057
    check_column(col_key);
17,853✔
1058
    ColumnType col_type = col_key.get_type();
17,853✔
1059
    if (is_link_type(col_type)) {
17,853✔
1060
        auto target_table = get_opposite_table(col_key);
228✔
1061
        auto target_column = get_opposite_column(col_key);
228✔
1062
        target_table->do_erase_root_column(target_column);
228✔
1063
    }
228✔
1064
    do_erase_root_column(col_key); // Throws
17,853✔
1065
}
17,853✔
1066

1067

1068
ColKey Table::do_insert_root_column(ColKey col_key, ColumnType type, StringData name, DataType key_type)
1069
{
976,632✔
1070
    // if col_key specifies a key, it must be unused
481,911✔
1071
    REALM_ASSERT(!col_key || !valid_column(col_key));
976,632✔
1072

481,911✔
1073
    // locate insertion point: ordinary columns must come before backlink columns
481,911✔
1074
    size_t spec_ndx = (type == col_type_BackLink) ? m_spec.get_column_count() : m_spec.get_public_column_count();
932,277✔
1075

481,911✔
1076
    if (!col_key) {
976,632✔
1077
        col_key = generate_col_key(type, {});
87,693✔
1078
    }
87,693✔
1079

481,911✔
1080
    m_spec.insert_column(spec_ndx, col_key, type, name, col_key.get_attrs().m_value); // Throws
976,632✔
1081
    if (col_key.is_dictionary()) {
976,632✔
1082
        m_spec.set_dictionary_key_type(spec_ndx, key_type);
53,406✔
1083
    }
53,406✔
1084
    auto col_ndx = col_key.get_index().val;
976,632✔
1085
    build_column_mapping();
976,632✔
1086
    REALM_ASSERT(col_ndx <= m_index_refs.size());
976,632✔
1087
    if (col_ndx == m_index_refs.size()) {
976,632✔
1088
        m_index_refs.insert(col_ndx, 0);
976,377✔
1089
    }
976,377✔
1090
    else {
255✔
1091
        m_index_refs.set(col_ndx, 0);
255✔
1092
    }
255✔
1093
    REALM_ASSERT(col_ndx <= m_opposite_table.size());
976,632✔
1094
    if (col_ndx == m_opposite_table.size()) {
976,632✔
1095
        // m_opposite_table and m_opposite_column are always resized together!
481,788✔
1096
        m_opposite_table.insert(col_ndx, TableKey().value);
976,377✔
1097
        m_opposite_column.insert(col_ndx, ColKey().value);
976,377✔
1098
    }
976,377✔
1099
    else {
255✔
1100
        m_opposite_table.set(col_ndx, TableKey().value);
255✔
1101
        m_opposite_column.set(col_ndx, ColKey().value);
255✔
1102
    }
255✔
1103
    refresh_index_accessors();
976,632✔
1104
    m_clusters.insert_column(col_key);
976,632✔
1105
    if (m_tombstones) {
976,632✔
1106
        m_tombstones->insert_column(col_key);
7,299✔
1107
    }
7,299✔
1108

481,911✔
1109
    bump_storage_version();
976,632✔
1110

481,911✔
1111
    return col_key;
976,632✔
1112
}
976,632✔
1113

1114

1115
void Table::do_erase_root_column(ColKey col_key)
1116
{
18,081✔
1117
    size_t col_ndx = col_key.get_index().val;
18,081✔
1118
    // If the column had a source index we have to remove and destroy that as well
9,339✔
1119
    ref_type index_ref = m_index_refs.get_as_ref(col_ndx);
18,081✔
1120
    if (index_ref) {
18,081✔
1121
        Array::destroy_deep(index_ref, m_index_refs.get_alloc());
204✔
1122
        m_index_refs.set(col_ndx, 0);
204✔
1123
        m_index_accessors[col_ndx].reset();
204✔
1124
    }
204✔
1125
    m_opposite_table.set(col_ndx, TableKey().value);
18,081✔
1126
    m_opposite_column.set(col_ndx, ColKey().value);
18,081✔
1127
    m_index_accessors[col_ndx] = nullptr;
18,081✔
1128
    m_clusters.remove_column(col_key);
18,081✔
1129
    if (m_tombstones)
18,081✔
1130
        m_tombstones->remove_column(col_key);
6,474✔
1131
    size_t spec_ndx = colkey2spec_ndx(col_key);
18,081✔
1132
    m_spec.erase_column(spec_ndx);
18,081✔
1133
    m_top.adjust(top_position_for_column_key, 2);
18,081✔
1134

9,339✔
1135
    build_column_mapping();
18,081✔
1136
    while (m_index_accessors.size() > m_leaf_ndx2colkey.size()) {
35,586✔
1137
        REALM_ASSERT(m_index_accessors.back() == nullptr);
17,505✔
1138
        m_index_accessors.pop_back();
17,505✔
1139
    }
17,505✔
1140
    bump_content_version();
18,081✔
1141
    bump_storage_version();
18,081✔
1142
}
18,081✔
1143

1144
Query Table::where(const DictionaryLinkValues& dictionary_of_links) const
1145
{
1,524✔
1146
    return Query(m_own_ref, dictionary_of_links);
1,524✔
1147
}
1,524✔
1148

1149
void Table::set_table_type(Type table_type, bool handle_backlinks)
1150
{
312✔
1151
    if (table_type == m_table_type) {
312✔
1152
        return;
×
1153
    }
×
1154

156✔
1155
    if (m_table_type == Type::TopLevelAsymmetric || table_type == Type::TopLevelAsymmetric) {
312✔
1156
        throw LogicError(ErrorCodes::MigrationFailed, util::format("Cannot change '%1' from %2 to %3",
×
1157
                                                                   get_class_name(), m_table_type, table_type));
×
1158
    }
×
1159

156✔
1160
    REALM_ASSERT_EX(table_type == Type::TopLevel || table_type == Type::Embedded, table_type);
312✔
1161
    set_embedded(table_type == Type::Embedded, handle_backlinks);
312✔
1162
}
312✔
1163

1164
void Table::set_embedded(bool embedded, bool handle_backlinks)
1165
{
312✔
1166
    if (embedded == false) {
312✔
1167
        do_set_table_type(Type::TopLevel);
24✔
1168
        return;
24✔
1169
    }
24✔
1170

144✔
1171
    // Embedded objects cannot have a primary key.
144✔
1172
    if (get_primary_key_column()) {
288✔
1173
        throw IllegalOperation(
6✔
1174
            util::format("Cannot change '%1' to embedded when using a primary key.", get_class_name()));
6✔
1175
    }
6✔
1176

141✔
1177
    if (size() == 0) {
282✔
1178
        do_set_table_type(Type::Embedded);
42✔
1179
        return;
42✔
1180
    }
42✔
1181

120✔
1182
    // Check all of the objects for invalid incoming links. Each embedded object
120✔
1183
    // must have exactly one incoming link, and it must be from a non-Mixed property.
120✔
1184
    // Objects with no incoming links are either deleted or an error (depending
120✔
1185
    // on `handle_backlinks`), and objects with multiple incoming links are either
120✔
1186
    // cloned for each of the incoming links or an error (again depending on `handle_backlinks`).
120✔
1187
    // Incoming links from a Mixed property are always an error, as those can't
120✔
1188
    // link to embedded objects
120✔
1189
    ArrayInteger leaf(get_alloc());
240✔
1190
    enum class LinkCount : int8_t { None, One, Multiple };
240✔
1191
    std::vector<LinkCount> incoming_link_count;
240✔
1192
    std::vector<ObjKey> orphans;
240✔
1193
    std::vector<ObjKey> multiple_incoming_links;
240✔
1194
    traverse_clusters([&](const Cluster* cluster) {
474✔
1195
        size_t size = cluster->node_size();
474✔
1196
        incoming_link_count.assign(size, LinkCount::None);
474✔
1197

237✔
1198
        for_each_backlink_column([&](ColKey col) {
606✔
1199
            cluster->init_leaf(col, &leaf);
606✔
1200
            // Width zero means all the values are zero and there can't be any backlinks
303✔
1201
            if (leaf.get_width() == 0) {
606✔
1202
                return IteratorControl::AdvanceToNext;
36✔
1203
            }
36✔
1204

285✔
1205
            for (size_t i = 0, size = leaf.size(); i < size; ++i) {
60,816✔
1206
                auto value = leaf.get_as_ref_or_tagged(i);
60,300✔
1207
                if (value.is_ref() && value.get_as_ref() == 0) {
60,300✔
1208
                    // ref of zero means there's no backlinks
29,670✔
1209
                    continue;
59,340✔
1210
                }
59,340✔
1211

480✔
1212
                if (value.is_ref()) {
960✔
1213
                    // Any other ref indicates an array of backlinks, which will
39✔
1214
                    // always have more than one entry
39✔
1215
                    incoming_link_count[i] = LinkCount::Multiple;
78✔
1216
                }
78✔
1217
                else {
882✔
1218
                    // Otherwise it's a tagged ref to the single linking object
441✔
1219
                    if (incoming_link_count[i] == LinkCount::None) {
882✔
1220
                        incoming_link_count[i] = LinkCount::One;
792✔
1221
                    }
792✔
1222
                    else if (incoming_link_count[i] == LinkCount::One) {
90✔
1223
                        incoming_link_count[i] = LinkCount::Multiple;
42✔
1224
                    }
42✔
1225
                }
882✔
1226

480✔
1227
                auto source_col = get_opposite_column(col);
960✔
1228
                if (source_col.get_type() == col_type_Mixed) {
960✔
1229
                    auto source_table = get_opposite_table(col);
54✔
1230
                    throw IllegalOperation(util::format(
54✔
1231
                        "Cannot convert '%1' to embedded: there is an incoming link from the Mixed property '%2.%3', "
54✔
1232
                        "which does not support linking to embedded objects.",
54✔
1233
                        get_class_name(), source_table->get_class_name(), source_table->get_column_name(source_col)));
54✔
1234
                }
54✔
1235
            }
960✔
1236
            return IteratorControl::AdvanceToNext;
543✔
1237
        });
570✔
1238

237✔
1239
        for (size_t i = 0; i < size; ++i) {
60,660✔
1240
            if (incoming_link_count[i] == LinkCount::None) {
60,240✔
1241
                if (!handle_backlinks) {
59,424✔
1242
                    throw IllegalOperation(util::format("Cannot convert '%1' to embedded: at least one object has no "
18✔
1243
                                                        "incoming links and would be deleted.",
18✔
1244
                                                        get_class_name()));
18✔
1245
                }
18✔
1246
                orphans.push_back(cluster->get_real_key(i));
59,406✔
1247
            }
59,406✔
1248
            else if (incoming_link_count[i] == LinkCount::Multiple) {
816✔
1249
                if (!handle_backlinks) {
90✔
1250
                    throw IllegalOperation(util::format(
36✔
1251
                        "Cannot convert '%1' to embedded: at least one object has more than one incoming link.",
36✔
1252
                        get_class_name()));
36✔
1253
                }
36✔
1254
                multiple_incoming_links.push_back(cluster->get_real_key(i));
54✔
1255
            }
54✔
1256
        }
60,240✔
1257

237✔
1258
        return IteratorControl::AdvanceToNext;
447✔
1259
    });
474✔
1260

120✔
1261
    // orphans and multiple_incoming_links will always be empty if `handle_backlinks = false`
120✔
1262
    for (auto key : orphans) {
59,406✔
1263
        remove_object(key);
59,406✔
1264
    }
59,406✔
1265
    for (auto key : multiple_incoming_links) {
147✔
1266
        auto obj = get_object(key);
54✔
1267
        obj.handle_multiple_backlinks_during_schema_migration();
54✔
1268
        obj.remove();
54✔
1269
    }
54✔
1270

120✔
1271
    do_set_table_type(Type::Embedded);
240✔
1272
}
240✔
1273

1274
void Table::do_set_table_type(Type table_type)
1275
{
335,295✔
1276
    while (m_top.size() <= top_position_for_flags)
335,295✔
1277
        m_top.add(0);
×
1278

166,383✔
1279
    uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
335,295✔
1280
    // reset bits 0-1
166,383✔
1281
    flags &= ~table_type_mask;
335,295✔
1282
    // set table type
166,383✔
1283
    flags |= static_cast<uint8_t>(table_type);
335,295✔
1284
    m_top.set(top_position_for_flags, RefOrTagged::make_tagged(flags));
335,295✔
1285
    m_table_type = table_type;
335,295✔
1286
}
335,295✔
1287

1288

1289
void Table::detach(LifeCycleCookie cookie) noexcept
1290
{
5,088,627✔
1291
    m_cookie = cookie;
5,088,627✔
1292
    m_alloc.bump_instance_version();
5,088,627✔
1293
}
5,088,627✔
1294

1295
void Table::fully_detach() noexcept
1296
{
5,070,297✔
1297
    m_spec.detach();
5,070,297✔
1298
    m_top.detach();
5,070,297✔
1299
    m_index_refs.detach();
5,070,297✔
1300
    m_opposite_table.detach();
5,070,297✔
1301
    m_opposite_column.detach();
5,070,297✔
1302
    m_index_accessors.clear();
5,070,297✔
1303
}
5,070,297✔
1304

1305

1306
Table::~Table() noexcept
1307
{
3,552✔
1308
    if (m_top.is_attached()) {
3,552✔
1309
        // If destroyed as a standalone table, destroy all memory allocated
1,776✔
1310
        if (m_top.get_parent() == nullptr) {
3,552✔
1311
            m_top.destroy_deep();
3,552✔
1312
        }
3,552✔
1313
        fully_detach();
3,552✔
1314
    }
3,552✔
1315
    else {
×
1316
        REALM_ASSERT(m_index_accessors.size() == 0);
×
1317
    }
×
1318
    m_cookie = cookie_deleted;
3,552✔
1319
}
3,552✔
1320

1321

1322
IndexType Table::search_index_type(ColKey col_key) const noexcept
1323
{
8,013,030✔
1324
    if (auto index = m_index_accessors[col_key.get_index().val].get()) {
8,013,030✔
1325
        return index->is_fulltext_index() ? IndexType::Fulltext : IndexType::General;
1,165,884✔
1326
    }
1,166,094✔
1327
    return IndexType::None;
6,846,936✔
1328
}
6,846,936✔
1329

1330
void Table::migrate_column_info()
1331
{
336✔
1332
    bool changes = false;
336✔
1333
    TableKey tk = (get_name() == "pk") ? TableKey(0) : get_key();
309✔
1334
    changes |= m_spec.convert_column_attributes();
336✔
1335
    changes |= m_spec.convert_column_keys(tk);
336✔
1336

168✔
1337
    if (changes) {
336✔
1338
        build_column_mapping();
60✔
1339
    }
60✔
1340
}
336✔
1341

1342
bool Table::verify_column_keys()
1343
{
282✔
1344
    size_t nb_public_columns = m_spec.get_public_column_count();
282✔
1345
    size_t nb_columns = m_spec.get_column_count();
282✔
1346
    bool modified = false;
282✔
1347

141✔
1348
    auto check = [&]() {
288✔
1349
        for (size_t spec_ndx = nb_public_columns; spec_ndx < nb_columns; spec_ndx++) {
426✔
1350
            if (m_spec.get_column_type(spec_ndx) == col_type_BackLink) {
144✔
1351
                auto col_key = m_spec.get_key(spec_ndx);
144✔
1352
                // This function checks for a specific error in the m_keys array where the
72✔
1353
                // backlink column keys are wrong. It can be detected by trying to find the
72✔
1354
                // corresponding origin table. If the error exists some of the results will
72✔
1355
                // give null TableKeys back.
72✔
1356
                if (!get_opposite_table_key(col_key))
144✔
1357
                    return false;
6✔
1358
                auto t = get_opposite_table(col_key);
138✔
1359
                auto c = get_opposite_column(col_key);
138✔
1360
                if (!t->valid_column(c))
138✔
1361
                    return false;
×
1362
                if (t->get_opposite_column(c) != col_key) {
138✔
1363
                    t->set_opposite_column(c, get_key(), col_key);
12✔
1364
                }
12✔
1365
            }
138✔
1366
        }
144✔
1367
        return true;
285✔
1368
    };
288✔
1369

141✔
1370
    if (!check()) {
282✔
1371
        m_spec.fix_column_keys(get_key());
6✔
1372
        build_column_mapping();
6✔
1373
        refresh_index_accessors();
6✔
1374
        REALM_ASSERT_RELEASE(check());
6✔
1375
        modified = true;
6✔
1376
    }
6✔
1377
    return modified;
282✔
1378
}
282✔
1379

1380
// Delete the indexes stored in the columns array and create corresponding
1381
// entries in m_index_accessors array. This also has the effect that the columns
1382
// array after this step does not have extra entries for certain columns
1383
void Table::migrate_indexes(ColKey pk_col_key)
1384
{
336✔
1385
    if (ref_type top_ref = m_top.get_as_ref(top_position_for_columns)) {
336✔
1386
        Array col_refs(m_alloc);
246✔
1387
        col_refs.set_parent(&m_top, top_position_for_columns);
246✔
1388
        col_refs.init_from_ref(top_ref);
246✔
1389
        auto col_count = m_spec.get_column_count();
246✔
1390
        size_t col_ndx = 0;
246✔
1391

123✔
1392
        // If col_refs.size() equals col_count, there are no indexes to migrate
123✔
1393
        while (col_ndx < col_count && col_refs.size() > col_count) {
468✔
1394
            if (m_spec.get_column_attr(col_ndx).test(col_attr_Indexed) && !m_index_refs.get(col_ndx)) {
222✔
1395
                // Simply delete entry. This will have the effect that we will not have to take
72✔
1396
                // extra entries into account
72✔
1397
                auto old_index_ref = to_ref(col_refs.get(col_ndx + 1));
144✔
1398
                col_refs.erase(col_ndx + 1);
144✔
1399
                if (old_index_ref) {
144✔
1400
                    // It should not be possible for old_index_ref to be 0, but we have seen some error
72✔
1401
                    // reports on freeing a null ref, so just to be sure ...
72✔
1402
                    Array::destroy_deep(old_index_ref, m_alloc);
144✔
1403
                }
144✔
1404

72✔
1405
                // Primary key columns does not need an index
72✔
1406
                if (m_leaf_ndx2colkey[col_ndx] != pk_col_key) {
144✔
1407
                    // Otherwise create new index. Will be updated when objects are created
45✔
1408
                    m_index_accessors[col_ndx] = std::make_unique<StringIndex>(
90✔
1409
                        ClusterColumn(&m_clusters, m_spec.get_key(col_ndx), IndexType::General),
90✔
1410
                        get_alloc()); // Throws
90✔
1411
                    auto index = m_index_accessors[col_ndx].get();
90✔
1412
                    index->set_parent(&m_index_refs, col_ndx);
90✔
1413
                    m_index_refs.set(col_ndx, index->get_ref());
90✔
1414
                }
90✔
1415
            }
144✔
1416
            col_ndx++;
222✔
1417
        };
222✔
1418
    }
246✔
1419
}
336✔
1420

1421
// Move information held in the subspec area into the structures managed by Table
1422
// This is information about origin/target tables in relation to links
1423
// This information is now held in "opposite" arrays directly in Table structure
1424
// At the same time the backlink columns are destroyed
1425
// If there is no subspec, this stage is done
1426
void Table::migrate_subspec()
1427
{
282✔
1428
    if (!m_spec.has_subspec())
282✔
1429
        return;
210✔
1430

36✔
1431
    ref_type top_ref = m_top.get_as_ref(top_position_for_columns);
72✔
1432
    Array col_refs(m_alloc);
72✔
1433
    col_refs.set_parent(&m_top, top_position_for_columns);
72✔
1434
    col_refs.init_from_ref(top_ref);
72✔
1435
    Group* group = get_parent_group();
72✔
1436

36✔
1437
    for (size_t col_ndx = 0; col_ndx < m_spec.get_column_count(); col_ndx++) {
516✔
1438
        ColumnType col_type = m_spec.get_column_type(col_ndx);
444✔
1439

222✔
1440
        if (is_link_type(col_type)) {
444✔
1441
            auto target_key = m_spec.get_opposite_link_table_key(col_ndx);
72✔
1442
            auto target_table = group->get_table(target_key);
72✔
1443
            Spec& target_spec = _impl::TableFriend::get_spec(*target_table);
72✔
1444
            // The target table spec may already be migrated.
36✔
1445
            // If it has, the new functions should be used.
36✔
1446
            ColKey backlink_col_key = target_spec.has_subspec()
72✔
1447
                                          ? target_spec.find_backlink_column(m_key, col_ndx)
72✔
1448
                                          : target_table->find_opposite_column(m_spec.get_key(col_ndx));
36✔
1449
            REALM_ASSERT(backlink_col_key.get_type() == col_type_BackLink);
72✔
1450
            if (m_opposite_table.get(col_ndx) != target_key.value) {
72✔
1451
                m_opposite_table.set(col_ndx, target_key.value);
72✔
1452
            }
72✔
1453
            if (m_opposite_column.get(col_ndx) != backlink_col_key.value) {
72✔
1454
                m_opposite_column.set(col_ndx, backlink_col_key.value);
72✔
1455
            }
72✔
1456
        }
72✔
1457
        else if (col_type == col_type_BackLink) {
372✔
1458
            auto origin_key = m_spec.get_opposite_link_table_key(col_ndx);
72✔
1459
            size_t origin_col_ndx = m_spec.get_origin_column_ndx(col_ndx);
72✔
1460
            auto origin_table = group->get_table(origin_key);
72✔
1461
            Spec& origin_spec = _impl::TableFriend::get_spec(*origin_table);
72✔
1462
            ColKey origin_col_key = origin_spec.get_key(origin_col_ndx);
72✔
1463
            REALM_ASSERT(is_link_type(origin_col_key.get_type()));
72✔
1464
            if (m_opposite_table.get(col_ndx) != origin_key.value) {
72✔
1465
                m_opposite_table.set(col_ndx, origin_key.value);
72✔
1466
            }
72✔
1467
            if (m_opposite_column.get(col_ndx) != origin_col_key.value) {
72✔
1468
                m_opposite_column.set(col_ndx, origin_col_key.value);
72✔
1469
            }
72✔
1470
        }
72✔
1471
    };
444✔
1472
    m_spec.destroy_subspec();
72✔
1473
}
72✔
1474

1475
namespace {
1476

1477
class LegacyStringColumn : public BPlusTree<StringData> {
1478
public:
1479
    LegacyStringColumn(Allocator& alloc, Spec* spec, size_t col_ndx, bool nullable)
1480
        : BPlusTree(alloc)
1481
        , m_spec(spec)
1482
        , m_col_ndx(col_ndx)
1483
        , m_nullable(nullable)
1484
    {
300✔
1485
    }
300✔
1486

1487
    std::unique_ptr<BPlusTreeLeaf> init_leaf_node(ref_type ref) override
1488
    {
300✔
1489
        auto leaf = std::make_unique<LeafNode>(this);
300✔
1490
        leaf->ArrayString::set_spec(m_spec, m_col_ndx);
300✔
1491
        leaf->set_nullability(m_nullable);
300✔
1492
        leaf->init_from_ref(ref);
300✔
1493
        return leaf;
300✔
1494
    }
300✔
1495

1496
    StringData get_legacy(size_t n) const
1497
    {
6,648✔
1498
        if (m_cached_leaf_begin <= n && n < m_cached_leaf_end) {
6,648!
1499
            return m_leaf_cache.get_legacy(n - m_cached_leaf_begin);
×
1500
        }
×
1501
        else {
6,648✔
1502
            StringData value;
6,648✔
1503

3,324✔
1504
            auto func = [&value](BPlusTreeNode* node, size_t ndx) {
6,648✔
1505
                auto leaf = static_cast<LeafNode*>(node);
6,648✔
1506
                value = leaf->get_legacy(ndx);
6,648✔
1507
            };
6,648✔
1508

3,324✔
1509
            m_root->bptree_access(n, func);
6,648✔
1510

3,324✔
1511
            return value;
6,648✔
1512
        }
6,648✔
1513
    }
6,648✔
1514

1515
private:
1516
    Spec* m_spec;
1517
    size_t m_col_ndx;
1518
    bool m_nullable;
1519
};
1520

1521
// We need an accessor that can read old Timestamp columns.
1522
// The new BPlusTree<Timestamp> uses a different layout
1523
class LegacyTS : private Array {
1524
public:
1525
    explicit LegacyTS(Allocator& allocator)
1526
        : Array(allocator)
1527
        , m_seconds(allocator)
1528
        , m_nanoseconds(allocator)
1529
    {
18✔
1530
        m_seconds.set_parent(this, 0);
18✔
1531
        m_nanoseconds.set_parent(this, 1);
18✔
1532
    }
18✔
1533

1534
    using Array::set_parent;
1535

1536
    void init_from_parent()
1537
    {
18✔
1538
        Array::init_from_parent();
18✔
1539
        m_seconds.init_from_parent();
18✔
1540
        m_nanoseconds.init_from_parent();
18✔
1541
    }
18✔
1542

1543
    size_t size() const
1544
    {
18✔
1545
        return m_seconds.size();
18✔
1546
    }
18✔
1547

1548
    Timestamp get(size_t ndx) const
1549
    {
3,078✔
1550
        util::Optional<int64_t> seconds = m_seconds.get(ndx);
3,078✔
1551
        return seconds ? Timestamp(*seconds, int32_t(m_nanoseconds.get(ndx))) : Timestamp{};
3,060✔
1552
    }
3,078✔
1553

1554
private:
1555
    BPlusTree<util::Optional<Int>> m_seconds;
1556
    BPlusTree<Int> m_nanoseconds;
1557
};
1558

1559
// Function that can retrieve a single value from the old columns
1560
Mixed get_val_from_column(size_t ndx, ColumnType col_type, bool nullable, BPlusTreeBase* accessor)
1561
{
28,200✔
1562
    switch (col_type) {
28,200✔
1563
        case col_type_Int:
6,612✔
1564
            if (nullable) {
6,612✔
1565
                auto val = static_cast<BPlusTree<util::Optional<Int>>*>(accessor)->get(ndx);
3,150✔
1566
                return Mixed{val};
3,150✔
1567
            }
3,150✔
1568
            else {
3,462✔
1569
                return Mixed{static_cast<BPlusTree<Int>*>(accessor)->get(ndx)};
3,462✔
1570
            }
3,462✔
1571
        case col_type_Bool:
6,084✔
1572
            if (nullable) {
6,084✔
1573
                auto val = static_cast<BPlusTree<util::Optional<Int>>*>(accessor)->get(ndx);
3,042✔
1574
                return val ? Mixed{bool(*val)} : Mixed{};
2,292✔
1575
            }
3,042✔
1576
            else {
3,042✔
1577
                return Mixed{bool(static_cast<BPlusTree<Int>*>(accessor)->get(ndx))};
3,042✔
1578
            }
3,042✔
1579
        case col_type_Float:
3,042✔
1580
            return Mixed{static_cast<BPlusTree<float>*>(accessor)->get(ndx)};
3,042✔
1581
        case col_type_Double:
3,042✔
1582
            return Mixed{static_cast<BPlusTree<double>*>(accessor)->get(ndx)};
3,042✔
1583
        case col_type_String: {
6,378✔
1584
            auto str = static_cast<LegacyStringColumn*>(accessor)->get_legacy(ndx);
6,378✔
1585
            // This is a workaround for a bug where the length could be -1
3,189✔
1586
            // Seen when upgrading very old file.
3,189✔
1587
            if (str.size() == size_t(-1)) {
6,378✔
1588
                return Mixed("");
×
1589
            }
×
1590
            return Mixed{str};
6,378✔
1591
        }
6,378✔
1592
        case col_type_Binary:
4,710✔
1593
            return Mixed{static_cast<BPlusTree<Binary>*>(accessor)->get(ndx)};
3,042✔
1594
        default:
3,189✔
1595
            REALM_UNREACHABLE();
×
1596
    }
28,200✔
1597
}
28,200✔
1598

1599
template <class T>
1600
void copy_list(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1601
{
6,012✔
1602
    if (sub_table_ref) {
6,012!
1603
        // Actual list is in the columns array position 0
36✔
1604
        Array cols(alloc);
72✔
1605
        cols.init_from_ref(sub_table_ref);
72✔
1606
        ref_type list_ref = cols.get_as_ref(0);
72✔
1607
        BPlusTree<T> from_list(alloc);
72✔
1608
        from_list.init_from_ref(list_ref);
72✔
1609
        size_t list_size = from_list.size();
72✔
1610
        auto l = obj.get_list<T>(col);
72✔
1611
        for (size_t j = 0; j < list_size; j++) {
1,740!
1612
            l.add(from_list.get(j));
1,668✔
1613
        }
1,668✔
1614
    }
72✔
1615
}
6,012✔
1616

1617
template <>
1618
void copy_list<util::Optional<Bool>>(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1619
{
×
1620
    if (sub_table_ref) {
×
1621
        // Actual list is in the columns array position 0
1622
        Array cols(alloc);
×
1623
        cols.init_from_ref(sub_table_ref);
×
1624
        BPlusTree<util::Optional<Int>> from_list(alloc);
×
1625
        from_list.set_parent(&cols, 0);
×
1626
        from_list.init_from_parent();
×
1627
        size_t list_size = from_list.size();
×
1628
        auto l = obj.get_list<util::Optional<Bool>>(col);
×
1629
        for (size_t j = 0; j < list_size; j++) {
×
1630
            util::Optional<Bool> val;
×
1631
            auto int_val = from_list.get(j);
×
1632
            if (int_val) {
×
1633
                val = (*int_val != 0);
×
1634
            }
×
1635
            l.add(val);
×
1636
        }
×
1637
    }
×
1638
}
×
1639

1640
template <>
1641
void copy_list<String>(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1642
{
276✔
1643
    if (sub_table_ref) {
276✔
1644
        // Actual list is in the columns array position 0
63✔
1645
        bool nullable = col.get_attrs().test(col_attr_Nullable);
126✔
1646
        Array cols(alloc);
126✔
1647
        cols.init_from_ref(sub_table_ref);
126✔
1648
        LegacyStringColumn from_list(alloc, nullptr, 0, nullable); // List of strings cannot be enumerated
126✔
1649
        from_list.set_parent(&cols, 0);
126✔
1650
        from_list.init_from_parent();
126✔
1651
        size_t list_size = from_list.size();
126✔
1652
        auto l = obj.get_list<String>(col);
126✔
1653
        for (size_t j = 0; j < list_size; j++) {
396✔
1654
            l.add(from_list.get_legacy(j));
270✔
1655
        }
270✔
1656
    }
126✔
1657
}
276✔
1658

1659
template <>
1660
void copy_list<Timestamp>(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1661
{
×
1662
    if (sub_table_ref) {
×
1663
        // Actual list is in the columns array position 0
1664
        Array cols(alloc);
×
1665
        cols.init_from_ref(sub_table_ref);
×
1666
        LegacyTS from_list(alloc);
×
1667
        from_list.set_parent(&cols, 0);
×
1668
        from_list.init_from_parent();
×
1669
        size_t list_size = from_list.size();
×
1670
        auto l = obj.get_list<Timestamp>(col);
×
1671
        for (size_t j = 0; j < list_size; j++) {
×
1672
            l.add(from_list.get(j));
×
1673
        }
×
1674
    }
×
1675
}
×
1676

1677
} // namespace
1678

1679
void Table::create_columns()
1680
{
336✔
1681
    size_t cnt;
336✔
1682
    auto get_column_cnt = [&cnt](const Cluster* cluster) {
336✔
1683
        cnt = cluster->nb_columns();
336✔
1684
        return IteratorControl::Stop;
336✔
1685
    };
336✔
1686
    traverse_clusters(get_column_cnt);
336✔
1687

168✔
1688
    size_t column_count = m_spec.get_column_count();
336✔
1689
    if (cnt != column_count) {
336✔
1690
        for (size_t col_ndx = 0; col_ndx < column_count; col_ndx++) {
846✔
1691
            m_clusters.insert_column(m_spec.get_key(col_ndx));
672✔
1692
        }
672✔
1693
    }
174✔
1694
}
336✔
1695

1696
bool Table::migrate_objects()
1697
{
336✔
1698
    size_t nb_public_columns = m_spec.get_public_column_count();
336✔
1699
    size_t nb_columns = m_spec.get_column_count();
336✔
1700
    if (!nb_columns) {
336✔
1701
        // No columns - this means no objects
12✔
1702
        return true;
24✔
1703
    }
24✔
1704

156✔
1705
    ref_type top_ref = m_top.get_as_ref(top_position_for_columns);
312✔
1706
    if (!top_ref) {
312✔
1707
        // Has already been done
45✔
1708
        return true;
90✔
1709
    }
90✔
1710
    Array col_refs(m_alloc);
222✔
1711
    col_refs.set_parent(&m_top, top_position_for_columns);
222✔
1712
    col_refs.init_from_ref(top_ref);
222✔
1713

111✔
1714
    /************************ Create column accessors ************************/
111✔
1715

111✔
1716
    std::map<ColKey, std::unique_ptr<BPlusTreeBase>> column_accessors;
222✔
1717
    std::map<ColKey, std::unique_ptr<LegacyTS>> ts_accessors;
222✔
1718
    std::map<ColKey, std::unique_ptr<BPlusTree<int64_t>>> list_accessors;
222✔
1719
    std::vector<size_t> cols_to_destroy;
222✔
1720
    bool has_link_columns = false;
222✔
1721

111✔
1722
    // helper function to determine the number of objects in the table
111✔
1723
    size_t number_of_objects = (nb_columns == 0) ? 0 : size_t(-1);
222✔
1724
    auto update_size = [&number_of_objects](size_t s) {
792✔
1725
        if (number_of_objects == size_t(-1)) {
792✔
1726
            number_of_objects = s;
222✔
1727
        }
222✔
1728
        else {
570✔
1729
            REALM_ASSERT(s == number_of_objects);
570✔
1730
        }
570✔
1731
    };
792✔
1732

111✔
1733
    for (size_t col_ndx = 0; col_ndx < nb_columns; col_ndx++) {
1,062✔
1734
        if (col_ndx < nb_public_columns && m_spec.get_column_name(col_ndx) == "!ROW_INDEX") {
840✔
1735
            // If this column has been added, we can break here
1736
            break;
×
1737
        }
×
1738

420✔
1739
        ColKey col_key = m_spec.get_key(col_ndx);
840✔
1740
        ColumnAttrMask attr = m_spec.get_column_attr(col_ndx);
840✔
1741
        ColumnType col_type = m_spec.get_column_type(col_ndx);
840✔
1742
        bool nullable = attr.test(col_attr_Nullable);
840✔
1743
        std::unique_ptr<BPlusTreeBase> acc;
840✔
1744
        std::unique_ptr<LegacyTS> ts_acc;
840✔
1745
        std::unique_ptr<BPlusTree<int64_t>> list_acc;
840✔
1746

420✔
1747
        if (!(col_ndx < col_refs.size())) {
840✔
1748
            throw RuntimeError(ErrorCodes::BrokenInvariant,
×
1749
                               util::format("Objects in '%1' corrupted by previous upgrade attempt", get_name()));
×
1750
        }
×
1751

420✔
1752
        if (!col_refs.get(col_ndx)) {
840✔
1753
            // This column has been migrated
24✔
1754
            continue;
48✔
1755
        }
48✔
1756

396✔
1757
        if (attr.test(col_attr_List) && col_type != col_type_LinkList) {
792✔
1758
            list_acc = std::make_unique<BPlusTree<int64_t>>(m_alloc);
60✔
1759
        }
60✔
1760
        else {
732✔
1761
            switch (col_type) {
732✔
1762
                case col_type_Int:
300✔
1763
                case col_type_Bool:
312✔
1764
                    if (nullable) {
312✔
1765
                        acc = std::make_unique<BPlusTree<util::Optional<Int>>>(m_alloc);
60✔
1766
                    }
60✔
1767
                    else {
252✔
1768
                        acc = std::make_unique<BPlusTree<Int>>(m_alloc);
252✔
1769
                    }
252✔
1770
                    break;
312✔
1771
                case col_type_Float:
162✔
1772
                    acc = std::make_unique<BPlusTree<float>>(m_alloc);
12✔
1773
                    break;
12✔
1774
                case col_type_Double:
162✔
1775
                    acc = std::make_unique<BPlusTree<double>>(m_alloc);
12✔
1776
                    break;
12✔
1777
                case col_type_String:
243✔
1778
                    acc = std::make_unique<LegacyStringColumn>(m_alloc, &m_spec, col_ndx, nullable);
174✔
1779
                    break;
174✔
1780
                case col_type_Binary:
162✔
1781
                    acc = std::make_unique<BPlusTree<Binary>>(m_alloc);
12✔
1782
                    break;
12✔
1783
                case col_type_Timestamp: {
165✔
1784
                    ts_acc = std::make_unique<LegacyTS>(m_alloc);
18✔
1785
                    break;
18✔
1786
                }
300✔
1787
                case col_type_Link:
186✔
1788
                case col_type_LinkList: {
120✔
1789
                    BPlusTree<int64_t> arr(m_alloc);
120✔
1790
                    arr.set_parent(&col_refs, col_ndx);
120✔
1791
                    arr.init_from_parent();
120✔
1792
                    update_size(arr.size());
120✔
1793
                    has_link_columns = true;
120✔
1794
                    break;
120✔
1795
                }
90✔
1796
                case col_type_BackLink: {
96✔
1797
                    BPlusTree<int64_t> arr(m_alloc);
72✔
1798
                    arr.set_parent(&col_refs, col_ndx);
72✔
1799
                    arr.init_from_parent();
72✔
1800
                    update_size(arr.size());
72✔
1801
                    cols_to_destroy.push_back(col_ndx);
72✔
1802
                    break;
72✔
1803
                }
90✔
1804
                default:
60✔
1805
                    break;
×
1806
            }
792✔
1807
        }
792✔
1808

396✔
1809
        if (acc) {
792✔
1810
            acc->set_parent(&col_refs, col_ndx);
522✔
1811
            acc->init_from_parent();
522✔
1812
            update_size(acc->size());
522✔
1813
            column_accessors.emplace(col_key, std::move(acc));
522✔
1814
            cols_to_destroy.push_back(col_ndx);
522✔
1815
        }
522✔
1816
        if (ts_acc) {
792✔
1817
            ts_acc->set_parent(&col_refs, col_ndx);
18✔
1818
            ts_acc->init_from_parent();
18✔
1819
            update_size(ts_acc->size());
18✔
1820
            ts_accessors.emplace(col_key, std::move(ts_acc));
18✔
1821
            cols_to_destroy.push_back(col_ndx);
18✔
1822
        }
18✔
1823
        if (list_acc) {
792✔
1824
            list_acc->set_parent(&col_refs, col_ndx);
60✔
1825
            list_acc->init_from_parent();
60✔
1826
            update_size(list_acc->size());
60✔
1827
            list_accessors.emplace(col_key, std::move(list_acc));
60✔
1828
            cols_to_destroy.push_back(col_ndx);
60✔
1829
        }
60✔
1830
    }
792✔
1831

111✔
1832
    REALM_ASSERT(number_of_objects != size_t(-1));
222✔
1833

111✔
1834
    if (m_clusters.size() == number_of_objects) {
222✔
1835
        // We have migrated all objects
33✔
1836
        return !has_link_columns;
66✔
1837
    }
66✔
1838

78✔
1839
    // !OID column must not be present. Such columns are only present in syncked
78✔
1840
    // realms, which we cannot upgrade.
78✔
1841
    REALM_ASSERT(nb_public_columns == 0 || m_spec.get_column_name(0) != "!OID");
156✔
1842

78✔
1843
    /*************************** Create objects ******************************/
78✔
1844

78✔
1845
    for (size_t row_ndx = 0; row_ndx < number_of_objects; row_ndx++) {
3,654✔
1846
        // Build a vector of values obtained from the old columns
1,749✔
1847
        FieldValues init_values;
3,498✔
1848
        for (auto& it : column_accessors) {
28,200✔
1849
            auto col_key = it.first;
28,200✔
1850
            auto col_type = col_key.get_type();
28,200✔
1851
            auto nullable = col_key.get_attrs().test(col_attr_Nullable);
28,200✔
1852
            auto val = get_val_from_column(row_ndx, col_type, nullable, it.second.get());
28,200✔
1853
            init_values.insert(col_key, val);
28,200✔
1854
        }
28,200✔
1855
        for (auto& it : ts_accessors) {
3,288✔
1856
            init_values.insert(it.first, Mixed(it.second->get(row_ndx)));
3,078✔
1857
        }
3,078✔
1858

1,749✔
1859
        // Create object with the initial values
1,749✔
1860
        Obj obj = m_clusters.insert(ObjKey(row_ndx), init_values);
3,498✔
1861

1,749✔
1862
        // Then update possible list types
1,749✔
1863
        for (auto& it : list_accessors) {
6,288✔
1864
            switch (it.first.get_type()) {
6,288✔
1865
                case col_type_Int: {
6,012✔
1866
                    if (it.first.get_attrs().test(col_attr_Nullable)) {
6,012✔
1867
                        copy_list<util::Optional<int64_t>>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
3,006✔
1868
                    }
3,006✔
1869
                    else {
3,006✔
1870
                        copy_list<int64_t>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
3,006✔
1871
                    }
3,006✔
1872
                    break;
6,012✔
1873
                }
×
1874
                case col_type_Bool:
✔
1875
                    if (it.first.get_attrs().test(col_attr_Nullable)) {
×
1876
                        copy_list<util::Optional<Bool>>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
×
1877
                    }
×
1878
                    else {
×
1879
                        copy_list<Bool>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
×
1880
                    }
×
1881
                    break;
×
1882
                case col_type_Float:
✔
1883
                    copy_list<float>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
×
1884
                    break;
×
1885
                case col_type_Double:
✔
1886
                    copy_list<double>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
×
1887
                    break;
×
1888
                case col_type_String:
276✔
1889
                    copy_list<String>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
276✔
1890
                    break;
276✔
1891
                case col_type_Binary:
✔
1892
                    copy_list<Binary>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
×
1893
                    break;
×
1894
                case col_type_Timestamp: {
✔
1895
                    copy_list<Timestamp>(to_ref(it.second->get(row_ndx)), obj, it.first, m_alloc);
×
1896
                    break;
×
1897
                }
×
1898
                default:
✔
1899
                    break;
×
1900
            }
6,288✔
1901
        }
6,288✔
1902
    }
3,498✔
1903

78✔
1904
    // Destroy values in the old columns that has been copied.
78✔
1905
    // This frees up space in the file
78✔
1906
    for (auto ndx : cols_to_destroy) {
516✔
1907
        Array::destroy_deep(to_ref(col_refs.get(ndx)), m_alloc);
516✔
1908
        col_refs.set(ndx, 0);
516✔
1909
    }
516✔
1910

78✔
1911
    // We need to be sure that the stored 'next sequence number' is bigger than
78✔
1912
    // the biggest ObjKey currently used.
78✔
1913
    this->set_sequence_number(uint64_t(number_of_objects));
156✔
1914

78✔
1915
#if 0
1916
    if (fastrand(100) < 20) {
1917
        throw std::runtime_error("Upgrade interrupted"); // Can be used for testing
1918
    }
1919
#endif
1920
    return !has_link_columns;
156✔
1921
}
156✔
1922

1923
void Table::migrate_links()
1924
{
60✔
1925
    ref_type top_ref = m_top.get_as_ref(top_position_for_columns);
60✔
1926
    if (!top_ref) {
60✔
1927
        // All objects migrated
1928
        return;
×
1929
    }
×
1930

30✔
1931
    Array col_refs(m_alloc);
60✔
1932
    col_refs.set_parent(&m_top, top_position_for_columns);
60✔
1933
    col_refs.init_from_ref(top_ref);
60✔
1934

30✔
1935
    // Cache column accessors and other information
30✔
1936
    size_t nb_columns = m_spec.get_public_column_count();
60✔
1937
    std::vector<std::unique_ptr<BPlusTree<Int>>> link_column_accessors(nb_columns);
60✔
1938
    std::vector<ColKey> col_keys(nb_columns);
60✔
1939
    std::vector<ColumnType> col_types(nb_columns);
60✔
1940
    std::vector<Table*> target_tables(nb_columns);
60✔
1941
    std::vector<ColKey> opposite_orig_row_ndx_col(nb_columns);
60✔
1942
    for (size_t col_ndx = 0; col_ndx < nb_columns; col_ndx++) {
414✔
1943
        ColumnType col_type = m_spec.get_column_type(col_ndx);
354✔
1944

177✔
1945
        if (is_link_type(col_type)) {
354✔
1946
            link_column_accessors[col_ndx] = std::make_unique<BPlusTree<int64_t>>(m_alloc);
120✔
1947
            link_column_accessors[col_ndx]->set_parent(&col_refs, col_ndx);
120✔
1948
            link_column_accessors[col_ndx]->init_from_parent();
120✔
1949
            col_keys[col_ndx] = m_spec.get_key(col_ndx);
120✔
1950
            col_types[col_ndx] = col_type;
120✔
1951
            target_tables[col_ndx] = get_opposite_table(col_keys[col_ndx]).unchecked_ptr();
120✔
1952
            opposite_orig_row_ndx_col[col_ndx] = target_tables[col_ndx]->get_column_key("!ROW_INDEX");
120✔
1953
        }
120✔
1954
    }
354✔
1955

30✔
1956
    auto orig_row_ndx_col_key = get_column_key("!ROW_INDEX");
60✔
1957
    for (auto obj : *this) {
3,186✔
1958
        for (size_t col_ndx = 0; col_ndx < nb_columns; col_ndx++) {
46,314✔
1959
            if (col_keys[col_ndx]) {
43,128✔
1960
                // If no !ROW_INDEX column is found, the original row index number is
3,186✔
1961
                // equal to the ObjKey value
3,186✔
1962
                size_t orig_row_ndx =
6,372✔
1963
                    size_t(orig_row_ndx_col_key ? obj.get<Int>(orig_row_ndx_col_key) : obj.get_key().value);
6,372✔
1964
                // Get original link value
3,186✔
1965
                int64_t link_val = link_column_accessors[col_ndx]->get(orig_row_ndx);
6,372✔
1966

3,186✔
1967
                Table* target_table = target_tables[col_ndx];
6,372✔
1968
                ColKey search_col = opposite_orig_row_ndx_col[col_ndx];
6,372✔
1969
                auto get_target_key = [target_table, search_col](int64_t orig_link_val) -> ObjKey {
3,444✔
1970
                    if (search_col)
516✔
1971
                        return target_table->find_first_int(search_col, orig_link_val);
36✔
1972
                    else
480✔
1973
                        return ObjKey(orig_link_val);
480✔
1974
                };
516✔
1975

3,186✔
1976
                if (link_val) {
6,372✔
1977
                    if (col_types[col_ndx] == col_type_Link) {
240✔
1978
                        obj.set(col_keys[col_ndx], get_target_key(link_val - 1));
138✔
1979
                    }
138✔
1980
                    else {
102✔
1981
                        auto ll = obj.get_linklist(col_keys[col_ndx]);
102✔
1982
                        BPlusTree<Int> links(m_alloc);
102✔
1983
                        links.init_from_ref(ref_type(link_val));
102✔
1984
                        size_t nb_links = links.size();
102✔
1985
                        for (size_t j = 0; j < nb_links; j++) {
480✔
1986
                            ll.add(get_target_key(links.get(j)));
378✔
1987
                        }
378✔
1988
                    }
102✔
1989
                }
240✔
1990
            }
6,372✔
1991
        }
43,128✔
1992
    }
3,186✔
1993
}
60✔
1994

1995
void Table::finalize_migration(ColKey pk_col_key)
1996
{
282✔
1997
    if (ref_type ref = m_top.get_as_ref(top_position_for_columns)) {
282✔
1998
        Array::destroy_deep(ref, m_alloc);
234✔
1999
        m_top.set(top_position_for_columns, 0);
234✔
2000
    }
234✔
2001

141✔
2002
    if (auto orig_row_ndx_col = get_column_key("!ROW_INDEX")) {
282✔
2003
        remove_column(orig_row_ndx_col);
18✔
2004
    }
18✔
2005

141✔
2006
    if (auto oid_col = get_column_key("!OID")) {
282✔
2007
        remove_column(oid_col);
×
2008
    }
×
2009

141✔
2010
    REALM_ASSERT_RELEASE(!pk_col_key || valid_column(pk_col_key));
282✔
2011
    do_set_primary_key_column(pk_col_key);
282✔
2012
}
282✔
2013

2014
void Table::migrate_sets_and_dictionaries()
2015
{
180✔
2016
    std::vector<ColKey> to_migrate;
180✔
2017
    for (auto col : get_column_keys()) {
570✔
2018
        if (col.is_dictionary() || (col.is_set() && col.get_type() == col_type_Mixed)) {
570✔
2019
            to_migrate.push_back(col);
12✔
2020
        }
12✔
2021
    }
570✔
2022
    if (to_migrate.size()) {
180✔
2023
        for (auto obj : *this) {
6✔
2024
            for (auto col : to_migrate) {
12✔
2025
                if (col.is_set()) {
12✔
2026
                    auto set = obj.get_set<Mixed>(col);
6✔
2027
                    set.migrate();
6✔
2028
                }
6✔
2029
                else if (col.is_dictionary()) {
6✔
2030
                    auto dict = obj.get_dictionary(col);
6✔
2031
                    dict.migrate();
6✔
2032
                }
6✔
2033
            }
12✔
2034
        }
6✔
2035
    }
6✔
2036
}
180✔
2037

2038
StringData Table::get_name() const noexcept
2039
{
2,914,854✔
2040
    const Array& real_top = m_top;
2,914,854✔
2041
    ArrayParent* parent = real_top.get_parent();
2,914,854✔
2042
    if (!parent)
2,914,854✔
2043
        return StringData("");
48✔
2044
    REALM_ASSERT(dynamic_cast<Group*>(parent));
2,914,806✔
2045
    return static_cast<Group*>(parent)->get_table_name(get_key());
2,914,806✔
2046
}
2,914,806✔
2047

2048
StringData Table::get_class_name() const noexcept
2049
{
14,958✔
2050
    return Group::table_name_to_class_name(get_name());
14,958✔
2051
}
14,958✔
2052

2053
const char* Table::get_state() const noexcept
2054
{
42✔
2055
    switch (m_cookie) {
42✔
2056
        case cookie_created:
✔
2057
            return "created";
×
2058
        case cookie_transaction_ended:
6✔
2059
            return "transaction_ended";
6✔
2060
        case cookie_initialized:
✔
2061
            return "initialised";
×
2062
        case cookie_removed:
36✔
2063
            return "removed";
36✔
2064
        case cookie_void:
✔
2065
            return "void";
×
2066
        case cookie_deleted:
✔
2067
            return "deleted";
×
2068
    }
×
2069
    return "";
×
2070
}
×
2071

2072

2073
bool Table::is_nullable(ColKey col_key) const
2074
{
2,018,649✔
2075
    REALM_ASSERT_DEBUG(valid_column(col_key));
2,018,649✔
2076
    return col_key.get_attrs().test(col_attr_Nullable);
2,018,649✔
2077
}
2,018,649✔
2078

2079
bool Table::is_list(ColKey col_key) const
2080
{
173,493✔
2081
    REALM_ASSERT_DEBUG(valid_column(col_key));
173,493✔
2082
    return col_key.get_attrs().test(col_attr_List);
173,493✔
2083
}
173,493✔
2084

2085

2086
ref_type Table::create_empty_table(Allocator& alloc, TableKey key)
2087
{
338,652✔
2088
    Array top(alloc);
338,652✔
2089
    _impl::DeepArrayDestroyGuard dg(&top);
338,652✔
2090
    top.create(Array::type_HasRefs); // Throws
338,652✔
2091
    _impl::DeepArrayRefDestroyGuard dg_2(alloc);
338,652✔
2092

168,060✔
2093
    {
338,652✔
2094
        MemRef mem = Spec::create_empty_spec(alloc); // Throws
338,652✔
2095
        dg_2.reset(mem.get_ref());
338,652✔
2096
        int_fast64_t v(from_ref(mem.get_ref()));
338,652✔
2097
        top.add(v); // Throws
338,652✔
2098
        dg_2.release();
338,652✔
2099
    }
338,652✔
2100
    top.add(0); // Old position for columns
338,652✔
2101
    {
338,652✔
2102
        MemRef mem = Cluster::create_empty_cluster(alloc); // Throws
338,652✔
2103
        dg_2.reset(mem.get_ref());
338,652✔
2104
        int_fast64_t v(from_ref(mem.get_ref()));
338,652✔
2105
        top.add(v); // Throws
338,652✔
2106
        dg_2.release();
338,652✔
2107
    }
338,652✔
2108

168,060✔
2109
    // Table key value
168,060✔
2110
    RefOrTagged rot = RefOrTagged::make_tagged(key.value);
338,652✔
2111
    top.add(rot);
338,652✔
2112

168,060✔
2113
    // Search indexes
168,060✔
2114
    {
338,652✔
2115
        bool context_flag = false;
338,652✔
2116
        MemRef mem = Array::create_empty_array(Array::type_HasRefs, context_flag, alloc); // Throws
338,652✔
2117
        dg_2.reset(mem.get_ref());
338,652✔
2118
        int_fast64_t v(from_ref(mem.get_ref()));
338,652✔
2119
        top.add(v); // Throws
338,652✔
2120
        dg_2.release();
338,652✔
2121
    }
338,652✔
2122
    rot = RefOrTagged::make_tagged(0);
338,652✔
2123
    top.add(rot); // Column key
338,652✔
2124
    top.add(rot); // Version
338,652✔
2125
    dg.release();
338,652✔
2126
    // Opposite keys (table and column)
168,060✔
2127
    {
338,652✔
2128
        bool context_flag = false;
338,652✔
2129
        {
338,652✔
2130
            MemRef mem = Array::create_empty_array(Array::type_Normal, context_flag, alloc); // Throws
338,652✔
2131
            dg_2.reset(mem.get_ref());
338,652✔
2132
            int_fast64_t v(from_ref(mem.get_ref()));
338,652✔
2133
            top.add(v); // Throws
338,652✔
2134
            dg_2.release();
338,652✔
2135
        }
338,652✔
2136
        {
338,652✔
2137
            MemRef mem = Array::create_empty_array(Array::type_Normal, context_flag, alloc); // Throws
338,652✔
2138
            dg_2.reset(mem.get_ref());
338,652✔
2139
            int_fast64_t v(from_ref(mem.get_ref()));
338,652✔
2140
            top.add(v); // Throws
338,652✔
2141
            dg_2.release();
338,652✔
2142
        }
338,652✔
2143
    }
338,652✔
2144
    top.add(0); // Sequence number
338,652✔
2145
    top.add(0); // Collision_map
338,652✔
2146
    top.add(0); // pk col key
338,652✔
2147
    top.add(0); // flags
338,652✔
2148
    top.add(0); // tombstones
338,652✔
2149

168,060✔
2150
    REALM_ASSERT(top.size() == top_array_size);
338,652✔
2151

168,060✔
2152
    return top.get_ref();
338,652✔
2153
}
338,652✔
2154

2155
void Table::ensure_graveyard()
2156
{
32,001✔
2157
    if (!m_tombstones) {
32,001✔
2158
        while (m_top.size() < top_position_for_tombstones)
10,080✔
2159
            m_top.add(0);
×
2160
        REALM_ASSERT(!m_top.get(top_position_for_tombstones));
10,080✔
2161
        MemRef mem = Cluster::create_empty_cluster(m_alloc);
10,080✔
2162
        m_top.set_as_ref(top_position_for_tombstones, mem.get_ref());
10,080✔
2163
        m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
10,080✔
2164
        m_tombstones->init_from_parent();
10,080✔
2165
        for_each_and_every_column([ts = m_tombstones.get()](ColKey col) {
24,423✔
2166
            ts->insert_column(col);
24,423✔
2167
            return IteratorControl::AdvanceToNext;
24,423✔
2168
        });
24,423✔
2169
    }
10,080✔
2170
}
32,001✔
2171

2172
void Table::batch_erase_rows(const KeyColumn& keys)
2173
{
5,301✔
2174
    Group* g = get_parent_group();
5,301✔
2175

2,652✔
2176
    size_t num_objs = keys.size();
5,301✔
2177
    std::vector<ObjKey> vec;
5,301✔
2178
    vec.reserve(num_objs);
5,301✔
2179
    for (size_t i = 0; i < num_objs; ++i) {
2,519,373✔
2180
        ObjKey key = keys.get(i);
2,514,072✔
2181
        if (key != null_key && is_valid(key)) {
2,514,072✔
2182
            vec.push_back(key);
2,514,066✔
2183
        }
2,514,066✔
2184
    }
2,514,072✔
2185
    sort(vec.begin(), vec.end());
5,301✔
2186
    vec.erase(unique(vec.begin(), vec.end()), vec.end());
5,301✔
2187

2,652✔
2188
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
5,301✔
2189
        CascadeState state(CascadeState::Mode::Strong, g);
4,533✔
2190
        std::for_each(vec.begin(), vec.end(), [this, &state](ObjKey k) {
3,147✔
2191
            state.m_to_be_deleted.emplace_back(m_key, k);
1,758✔
2192
        });
1,758✔
2193
        nullify_links(state);
4,533✔
2194
        remove_recursive(state);
4,533✔
2195
    }
4,533✔
2196
    else {
768✔
2197
        CascadeState state(CascadeState::Mode::None, g);
768✔
2198
        for (auto k : vec) {
2,512,302✔
2199
            if (g) {
2,512,302✔
2200
                m_clusters.nullify_links(k, state);
2,512,224✔
2201
            }
2,512,224✔
2202
            m_clusters.erase(k, state);
2,512,302✔
2203
        }
2,512,302✔
2204
    }
768✔
2205
}
5,301✔
2206

2207

2208
void Table::clear()
2209
{
3,519✔
2210
    CascadeState state(CascadeState::Mode::Strong, get_parent_group());
3,519✔
2211
    m_clusters.clear(state);
3,519✔
2212
    free_collision_table();
3,519✔
2213
}
3,519✔
2214

2215

2216
Group* Table::get_parent_group() const noexcept
2217
{
59,595,882✔
2218
    if (!m_top.is_attached())
59,595,882✔
2219
        return 0;                             // Subtable with shared descriptor
×
2220
    ArrayParent* parent = m_top.get_parent(); // ArrayParent guaranteed to be Table::Parent
59,595,882✔
2221
    if (!parent)
59,595,882✔
2222
        return 0; // Free-standing table
25,501,884✔
2223

16,758,750✔
2224
    return static_cast<Group*>(parent);
34,093,998✔
2225
}
34,093,998✔
2226

2227
inline uint64_t Table::get_sync_file_id() const noexcept
2228
{
38,471,286✔
2229
    Group* g = get_parent_group();
38,471,286✔
2230
    return g ? g->get_sync_file_id() : 0;
31,855,521✔
2231
}
38,471,286✔
2232

2233
size_t Table::get_index_in_group() const noexcept
2234
{
33✔
2235
    if (!m_top.is_attached())
33✔
2236
        return realm::npos;                   // Subtable with shared descriptor
×
2237
    ArrayParent* parent = m_top.get_parent(); // ArrayParent guaranteed to be Table::Parent
33✔
2238
    if (!parent)
33✔
2239
        return realm::npos; // Free-standing table
×
2240
    return m_top.get_ndx_in_parent();
33✔
2241
}
33✔
2242

2243
uint64_t Table::allocate_sequence_number()
2244
{
19,772,751✔
2245
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_sequence_number);
19,772,751✔
2246
    uint64_t sn = rot.is_tagged() ? rot.get_as_int() : 0;
19,643,160✔
2247
    rot = RefOrTagged::make_tagged(sn + 1);
19,772,751✔
2248
    m_top.set(top_position_for_sequence_number, rot);
19,772,751✔
2249

9,823,935✔
2250
    return sn;
19,772,751✔
2251
}
19,772,751✔
2252

2253
void Table::set_sequence_number(uint64_t seq)
2254
{
156✔
2255
    m_top.set(top_position_for_sequence_number, RefOrTagged::make_tagged(seq));
156✔
2256
}
156✔
2257

2258
void Table::set_collision_map(ref_type ref)
2259
{
×
2260
    m_top.set(top_position_for_collision_map, RefOrTagged::make_ref(ref));
×
2261
}
×
2262

2263
TableRef Table::get_link_target(ColKey col_key) noexcept
2264
{
308,589✔
2265
    return get_opposite_table(col_key);
308,589✔
2266
}
308,589✔
2267

2268
// count ----------------------------------------------
2269

2270
size_t Table::count_int(ColKey col_key, int64_t value) const
2271
{
12,006✔
2272
    if (auto index = this->get_search_index(col_key)) {
12,006✔
2273
        return index->count(value);
12,000✔
2274
    }
12,000✔
2275

3✔
2276
    return where().equal(col_key, value).count();
6✔
2277
}
6✔
2278
size_t Table::count_float(ColKey col_key, float value) const
2279
{
6✔
2280
    return where().equal(col_key, value).count();
6✔
2281
}
6✔
2282
size_t Table::count_double(ColKey col_key, double value) const
2283
{
6✔
2284
    return where().equal(col_key, value).count();
6✔
2285
}
6✔
2286
size_t Table::count_decimal(ColKey col_key, Decimal128 value) const
2287
{
18✔
2288
    ArrayDecimal128 leaf(get_alloc());
18✔
2289
    size_t cnt = 0;
18✔
2290
    bool null_value = value.is_null();
18✔
2291
    auto f = [value, &leaf, col_key, null_value, &cnt](const Cluster* cluster) {
18✔
2292
        // direct aggregate on the leaf
9✔
2293
        cluster->init_leaf(col_key, &leaf);
18✔
2294
        auto sz = leaf.size();
18✔
2295
        for (size_t i = 0; i < sz; i++) {
1,296✔
2296
            if ((null_value && leaf.is_null(i)) || (leaf.get(i) == value)) {
1,278!
2297
                cnt++;
24✔
2298
            }
24✔
2299
        }
1,278✔
2300
        return IteratorControl::AdvanceToNext;
18✔
2301
    };
18✔
2302

9✔
2303
    traverse_clusters(f);
18✔
2304

9✔
2305
    return cnt;
18✔
2306
}
18✔
2307
size_t Table::count_string(ColKey col_key, StringData value) const
2308
{
1,476✔
2309
    if (auto index = this->get_search_index(col_key)) {
1,476✔
2310
        return index->count(value);
732✔
2311
    }
732✔
2312
    return where().equal(col_key, value).count();
744✔
2313
}
744✔
2314

2315
template <typename T>
2316
void Table::aggregate(QueryStateBase& st, ColKey column_key) const
2317
{
27,570✔
2318
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
27,570✔
2319
    LeafType leaf(get_alloc());
27,570✔
2320

13,803✔
2321
    auto f = [&leaf, column_key, &st](const Cluster* cluster) {
27,588✔
2322
        // direct aggregate on the leaf
13,812✔
2323
        cluster->init_leaf(column_key, &leaf);
27,588✔
2324
        st.m_key_offset = cluster->get_offset();
27,588✔
2325
        st.m_key_values = cluster->get_key_array();
27,588✔
2326

13,812✔
2327
        bool cont = true;
27,588✔
2328
        size_t sz = leaf.size();
27,588✔
2329
        for (size_t local_index = 0; cont && local_index < sz; local_index++) {
122,721✔
2330
            auto v = leaf.get(local_index);
95,133✔
2331
            cont = st.match(local_index, v);
95,133✔
2332
        }
95,133✔
2333
        return IteratorControl::AdvanceToNext;
27,588✔
2334
    };
27,588✔
2335

13,803✔
2336
    traverse_clusters(f);
27,570✔
2337
}
27,570✔
2338

2339
// This template is also used by the query engine
2340
template void Table::aggregate<int64_t>(QueryStateBase&, ColKey) const;
2341
template void Table::aggregate<std::optional<int64_t>>(QueryStateBase&, ColKey) const;
2342
template void Table::aggregate<float>(QueryStateBase&, ColKey) const;
2343
template void Table::aggregate<double>(QueryStateBase&, ColKey) const;
2344
template void Table::aggregate<Decimal128>(QueryStateBase&, ColKey) const;
2345
template void Table::aggregate<Mixed>(QueryStateBase&, ColKey) const;
2346
template void Table::aggregate<Timestamp>(QueryStateBase&, ColKey) const;
2347

2348
std::optional<Mixed> Table::sum(ColKey col_key) const
2349
{
756✔
2350
    return AggregateHelper<Table>::sum(*this, *this, col_key);
756✔
2351
}
756✔
2352

2353
std::optional<Mixed> Table::avg(ColKey col_key, size_t* value_count) const
2354
{
822✔
2355
    return AggregateHelper<Table>::avg(*this, *this, col_key, value_count);
822✔
2356
}
822✔
2357

2358
std::optional<Mixed> Table::min(ColKey col_key, ObjKey* return_ndx) const
2359
{
1,170✔
2360
    return AggregateHelper<Table>::min(*this, *this, col_key, return_ndx);
1,170✔
2361
}
1,170✔
2362

2363
std::optional<Mixed> Table::max(ColKey col_key, ObjKey* return_ndx) const
2364
{
21,294✔
2365
    return AggregateHelper<Table>::max(*this, *this, col_key, return_ndx);
21,294✔
2366
}
21,294✔
2367

2368
template <class T>
2369
ObjKey Table::find_first(ColKey col_key, T value) const
2370
{
34,833✔
2371
    check_column(col_key);
34,833✔
2372

17,394✔
2373
    if (!col_key.is_nullable() && value_is_null(value)) {
34,833!
2374
        return {}; // this is a precaution/optimization
6✔
2375
    }
6✔
2376
    // You cannot call GetIndexData on ObjKey
17,391✔
2377
    if constexpr (!std::is_same_v<T, ObjKey>) {
34,827✔
2378
        if (StringIndex* index = get_search_index(col_key)) {
34,809!
2379
            return index->find_first(value);
26,961✔
2380
        }
26,961✔
2381
        if (col_key == m_primary_key_col) {
7,848!
2382
            return find_primary_key(value);
×
2383
        }
×
2384
    }
7,848✔
2385

3,924✔
2386
    ObjKey key;
7,848✔
2387
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
7,848✔
2388
    LeafType leaf(get_alloc());
7,848✔
2389

3,924✔
2390
    auto f = [&key, &col_key, &value, &leaf](const Cluster* cluster) {
9,330✔
2391
        cluster->init_leaf(col_key, &leaf);
9,330✔
2392
        size_t row = leaf.find_first(value, 0, cluster->node_size());
9,330✔
2393
        if (row != realm::npos) {
9,330!
2394
            key = cluster->get_real_key(row);
7,704✔
2395
            return IteratorControl::Stop;
7,704✔
2396
        }
7,704✔
2397
        return IteratorControl::AdvanceToNext;
1,626✔
2398
    };
1,626✔
2399

3,924✔
2400
    traverse_clusters(f);
7,848✔
2401

3,924✔
2402
    return key;
7,848✔
2403
}
7,848✔
2404

2405
namespace realm {
2406

2407
template <>
2408
ObjKey Table::find_first(ColKey col_key, util::Optional<float> value) const
2409
{
×
2410
    return value ? find_first(col_key, *value) : find_first_null(col_key);
×
2411
}
×
2412

2413
template <>
2414
ObjKey Table::find_first(ColKey col_key, util::Optional<double> value) const
2415
{
×
2416
    return value ? find_first(col_key, *value) : find_first_null(col_key);
×
2417
}
×
2418

2419
template <>
2420
ObjKey Table::find_first(ColKey col_key, null) const
2421
{
×
2422
    return find_first_null(col_key);
×
2423
}
×
2424
} // namespace realm
2425

2426
// Explicitly instantiate the generic case of the template for the types we care about.
2427
template ObjKey Table::find_first(ColKey col_key, bool) const;
2428
template ObjKey Table::find_first(ColKey col_key, int64_t) const;
2429
template ObjKey Table::find_first(ColKey col_key, float) const;
2430
template ObjKey Table::find_first(ColKey col_key, double) const;
2431
template ObjKey Table::find_first(ColKey col_key, Decimal128) const;
2432
template ObjKey Table::find_first(ColKey col_key, ObjectId) const;
2433
template ObjKey Table::find_first(ColKey col_key, ObjKey) const;
2434
template ObjKey Table::find_first(ColKey col_key, util::Optional<bool>) const;
2435
template ObjKey Table::find_first(ColKey col_key, util::Optional<int64_t>) const;
2436
template ObjKey Table::find_first(ColKey col_key, StringData) const;
2437
template ObjKey Table::find_first(ColKey col_key, BinaryData) const;
2438
template ObjKey Table::find_first(ColKey col_key, Mixed) const;
2439
template ObjKey Table::find_first(ColKey col_key, UUID) const;
2440
template ObjKey Table::find_first(ColKey col_key, util::Optional<ObjectId>) const;
2441
template ObjKey Table::find_first(ColKey col_key, util::Optional<UUID>) const;
2442

2443
ObjKey Table::find_first_int(ColKey col_key, int64_t value) const
2444
{
7,740✔
2445
    if (is_nullable(col_key))
7,740✔
2446
        return find_first<util::Optional<int64_t>>(col_key, value);
36✔
2447
    else
7,704✔
2448
        return find_first<int64_t>(col_key, value);
7,704✔
2449
}
7,740✔
2450

2451
ObjKey Table::find_first_bool(ColKey col_key, bool value) const
2452
{
78✔
2453
    if (is_nullable(col_key))
78✔
2454
        return find_first<util::Optional<bool>>(col_key, value);
36✔
2455
    else
42✔
2456
        return find_first<bool>(col_key, value);
42✔
2457
}
78✔
2458

2459
ObjKey Table::find_first_timestamp(ColKey col_key, Timestamp value) const
2460
{
108✔
2461
    return find_first(col_key, value);
108✔
2462
}
108✔
2463

2464
ObjKey Table::find_first_object_id(ColKey col_key, ObjectId value) const
2465
{
6✔
2466
    return find_first(col_key, value);
6✔
2467
}
6✔
2468

2469
ObjKey Table::find_first_float(ColKey col_key, float value) const
2470
{
12✔
2471
    return find_first<Float>(col_key, value);
12✔
2472
}
12✔
2473

2474
ObjKey Table::find_first_double(ColKey col_key, double value) const
2475
{
12✔
2476
    return find_first<Double>(col_key, value);
12✔
2477
}
12✔
2478

2479
ObjKey Table::find_first_decimal(ColKey col_key, Decimal128 value) const
2480
{
×
2481
    return find_first<Decimal128>(col_key, value);
×
2482
}
×
2483

2484
ObjKey Table::find_first_string(ColKey col_key, StringData value) const
2485
{
11,433✔
2486
    return find_first<StringData>(col_key, value);
11,433✔
2487
}
11,433✔
2488

2489
ObjKey Table::find_first_binary(ColKey col_key, BinaryData value) const
2490
{
×
2491
    return find_first<BinaryData>(col_key, value);
×
2492
}
×
2493

2494
ObjKey Table::find_first_null(ColKey col_key) const
2495
{
114✔
2496
    return where().equal(col_key, null{}).find();
114✔
2497
}
114✔
2498

2499
ObjKey Table::find_first_uuid(ColKey col_key, UUID value) const
2500
{
18✔
2501
    return find_first(col_key, value);
18✔
2502
}
18✔
2503

2504
template <class T>
2505
TableView Table::find_all(ColKey col_key, T value)
2506
{
102✔
2507
    return where().equal(col_key, value).find_all();
102✔
2508
}
102✔
2509

2510
TableView Table::find_all_int(ColKey col_key, int64_t value)
2511
{
96✔
2512
    return find_all<int64_t>(col_key, value);
96✔
2513
}
96✔
2514

2515
TableView Table::find_all_int(ColKey col_key, int64_t value) const
2516
{
×
2517
    return const_cast<Table*>(this)->find_all<int64_t>(col_key, value);
×
2518
}
×
2519

2520
TableView Table::find_all_bool(ColKey col_key, bool value)
2521
{
×
2522
    return find_all<bool>(col_key, value);
×
2523
}
×
2524

2525
TableView Table::find_all_bool(ColKey col_key, bool value) const
2526
{
×
2527
    return const_cast<Table*>(this)->find_all<int64_t>(col_key, value);
×
2528
}
×
2529

2530

2531
TableView Table::find_all_float(ColKey col_key, float value)
2532
{
×
2533
    return find_all<float>(col_key, value);
×
2534
}
×
2535

2536
TableView Table::find_all_float(ColKey col_key, float value) const
2537
{
×
2538
    return const_cast<Table*>(this)->find_all<float>(col_key, value);
×
2539
}
×
2540

2541
TableView Table::find_all_double(ColKey col_key, double value)
2542
{
6✔
2543
    return find_all<double>(col_key, value);
6✔
2544
}
6✔
2545

2546
TableView Table::find_all_double(ColKey col_key, double value) const
2547
{
×
2548
    return const_cast<Table*>(this)->find_all<double>(col_key, value);
×
2549
}
×
2550

2551
TableView Table::find_all_string(ColKey col_key, StringData value)
2552
{
282✔
2553
    return where().equal(col_key, value).find_all();
282✔
2554
}
282✔
2555

2556
TableView Table::find_all_string(ColKey col_key, StringData value) const
2557
{
×
2558
    return const_cast<Table*>(this)->find_all_string(col_key, value);
×
2559
}
×
2560

2561
TableView Table::find_all_binary(ColKey, BinaryData)
2562
{
×
2563
    throw Exception(ErrorCodes::IllegalOperation, "Table::find_all_binary not supported");
×
2564
}
×
2565

2566
TableView Table::find_all_binary(ColKey col_key, BinaryData value) const
2567
{
×
2568
    return const_cast<Table*>(this)->find_all_binary(col_key, value);
×
2569
}
×
2570

2571
TableView Table::find_all_null(ColKey col_key)
2572
{
×
2573
    return where().equal(col_key, null{}).find_all();
×
2574
}
×
2575

2576
TableView Table::find_all_null(ColKey col_key) const
2577
{
×
2578
    return const_cast<Table*>(this)->find_all_null(col_key);
×
2579
}
×
2580

2581
TableView Table::find_all_fulltext(ColKey col_key, StringData terms) const
2582
{
6✔
2583
    return where().fulltext(col_key, terms).find_all();
6✔
2584
}
6✔
2585

2586
TableView Table::get_sorted_view(ColKey col_key, bool ascending)
2587
{
72✔
2588
    TableView tv = where().find_all();
72✔
2589
    tv.sort(col_key, ascending);
72✔
2590
    return tv;
72✔
2591
}
72✔
2592

2593
TableView Table::get_sorted_view(ColKey col_key, bool ascending) const
2594
{
6✔
2595
    return const_cast<Table*>(this)->get_sorted_view(col_key, ascending);
6✔
2596
}
6✔
2597

2598
TableView Table::get_sorted_view(SortDescriptor order)
2599
{
126✔
2600
    TableView tv = where().find_all();
126✔
2601
    tv.sort(std::move(order));
126✔
2602
    return tv;
126✔
2603
}
126✔
2604

2605
TableView Table::get_sorted_view(SortDescriptor order) const
2606
{
×
2607
    return const_cast<Table*>(this)->get_sorted_view(std::move(order));
×
2608
}
×
2609

2610
util::Logger* Table::get_logger() const noexcept
2611
{
1,917,909✔
2612
    return *m_repl ? (*m_repl)->get_logger() : nullptr;
1,825,518✔
2613
}
1,917,909✔
2614

2615
// Called after a commit. Table will effectively contain the same as before,
2616
// but now with new refs from the file
2617
void Table::update_from_parent() noexcept
2618
{
810,213✔
2619
    // There is no top for sub-tables sharing spec
403,239✔
2620
    if (m_top.is_attached()) {
810,213✔
2621
        m_top.update_from_parent();
810,207✔
2622
        m_spec.update_from_parent();
810,207✔
2623
        m_clusters.update_from_parent();
810,207✔
2624
        m_index_refs.update_from_parent();
810,207✔
2625
        for (auto&& index : m_index_accessors) {
2,638,617✔
2626
            if (index != nullptr) {
2,638,617✔
2627
                index->update_from_parent();
272,199✔
2628
            }
272,199✔
2629
        }
2,638,617✔
2630

403,236✔
2631
        m_opposite_table.update_from_parent();
810,207✔
2632
        m_opposite_column.update_from_parent();
810,207✔
2633
        if (m_top.size() > top_position_for_flags) {
810,207✔
2634
            uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
808,374✔
2635
            m_table_type = Type(flags & table_type_mask);
808,374✔
2636
        }
808,374✔
2637
        else {
1,833✔
2638
            m_table_type = Type::TopLevel;
1,833✔
2639
        }
1,833✔
2640
        if (m_tombstones)
810,207✔
2641
            m_tombstones->update_from_parent();
1,278✔
2642

403,236✔
2643
        refresh_content_version();
810,207✔
2644
        m_has_any_embedded_objects.reset();
810,207✔
2645
    }
810,207✔
2646
    m_alloc.bump_storage_version();
810,213✔
2647
}
810,213✔
2648

2649
void Table::schema_to_json(std::ostream& out, const std::map<std::string, std::string>& renames) const
2650
{
12✔
2651
    out << "{";
12✔
2652
    auto name = get_name();
12✔
2653
    if (renames.count(name))
12✔
2654
        name = renames.at(name);
×
2655
    out << "\"name\":\"" << name << "\"";
12✔
2656
    if (this->m_primary_key_col) {
12✔
2657
        out << ",";
×
2658
        out << "\"primaryKey\":\"" << this->get_column_name(m_primary_key_col) << "\"";
×
2659
    }
×
2660
    out << ",\"tableType\":\"" << this->get_table_type() << "\"";
12✔
2661
    out << ",\"properties\":[";
12✔
2662
    auto col_keys = get_column_keys();
12✔
2663
    int sz = int(col_keys.size());
12✔
2664
    for (int i = 0; i < sz; ++i) {
48✔
2665
        auto col_key = col_keys[i];
36✔
2666
        name = get_column_name(col_key);
36✔
2667
        auto type = col_key.get_type();
36✔
2668
        if (renames.count(name))
36✔
2669
            name = renames.at(name);
×
2670
        out << "{";
36✔
2671
        out << "\"name\":\"" << name << "\"";
36✔
2672
        if (this->is_link_type(type)) {
36✔
2673
            out << ",\"type\":\"object\"";
6✔
2674
            name = this->get_opposite_table(col_key)->get_name();
6✔
2675
            if (renames.count(name))
6✔
2676
                name = renames.at(name);
×
2677
            out << ",\"objectType\":\"" << name << "\"";
6✔
2678
        }
6✔
2679
        else {
30✔
2680
            out << ",\"type\":\"" << get_data_type_name(DataType(type)) << "\"";
30✔
2681
        }
30✔
2682
        if (col_key.is_list()) {
36✔
2683
            out << ",\"isArray\":true";
12✔
2684
        }
12✔
2685
        else if (col_key.is_set()) {
24✔
2686
            out << ",\"isSet\":true";
×
2687
        }
×
2688
        else if (col_key.is_dictionary()) {
24✔
2689
            out << ",\"isMap\":true";
×
2690
            auto key_type = get_dictionary_key_type(col_key);
×
2691
            out << ",\"keyType\":\"" << get_data_type_name(key_type) << "\"";
×
2692
        }
×
2693
        if (col_key.is_nullable()) {
36✔
2694
            out << ",\"isOptional\":true";
6✔
2695
        }
6✔
2696
        auto index_type = search_index_type(col_key);
36✔
2697
        if (index_type == IndexType::General) {
36✔
2698
            out << ",\"isIndexed\":true";
×
2699
        }
×
2700
        if (index_type == IndexType::Fulltext) {
36✔
2701
            out << ",\"isFulltextIndexed\":true";
×
2702
        }
×
2703
        out << "}";
36✔
2704
        if (i < sz - 1) {
36✔
2705
            out << ",";
24✔
2706
        }
24✔
2707
    }
36✔
2708
    out << "]}";
12✔
2709
}
12✔
2710

2711
void Table::to_json(std::ostream& out, size_t link_depth, const std::map<std::string, std::string>& renames,
2712
                    JSONOutputMode output_mode) const
2713
{
300✔
2714
    // Represent table as list of objects
150✔
2715
    out << "[";
300✔
2716
    bool first = true;
300✔
2717

150✔
2718
    for (auto& obj : *this) {
4,050✔
2719
        if (first) {
4,050✔
2720
            first = false;
294✔
2721
        }
294✔
2722
        else {
3,756✔
2723
            out << ",";
3,756✔
2724
        }
3,756✔
2725
        obj.to_json(out, link_depth, renames, output_mode);
4,050✔
2726
    }
4,050✔
2727

150✔
2728
    out << "]";
300✔
2729
}
300✔
2730

2731

2732
bool Table::operator==(const Table& t) const
2733
{
138✔
2734
    if (size() != t.size()) {
138✔
2735
        return false;
12✔
2736
    }
12✔
2737
    // Check columns
63✔
2738
    for (auto ck : this->get_column_keys()) {
522✔
2739
        auto name = get_column_name(ck);
522✔
2740
        auto other_ck = t.get_column_key(name);
522✔
2741
        auto attrs = ck.get_attrs();
522✔
2742
        if (search_index_type(ck) != t.search_index_type(other_ck))
522✔
2743
            return false;
×
2744

261✔
2745
        if (!other_ck || other_ck.get_attrs() != attrs) {
522✔
2746
            return false;
×
2747
        }
×
2748
    }
522✔
2749
    auto pk_col = get_primary_key_column();
126✔
2750
    for (auto o : *this) {
2,898✔
2751
        Obj other_o;
2,898✔
2752
        if (pk_col) {
2,898✔
2753
            auto pk = o.get_any(pk_col);
90✔
2754
            other_o = t.get_object_with_primary_key(pk);
90✔
2755
        }
90✔
2756
        else {
2,808✔
2757
            other_o = t.get_object(o.get_key());
2,808✔
2758
        }
2,808✔
2759
        if (!(other_o && o == other_o))
2,898✔
2760
            return false;
18✔
2761
    }
2,898✔
2762

63✔
2763
    return true;
117✔
2764
}
126✔
2765

2766

2767
void Table::flush_for_commit()
2768
{
3,978,381✔
2769
    if (m_top.is_attached() && m_top.size() >= top_position_for_version) {
3,978,381✔
2770
        if (!m_top.is_read_only()) {
3,978,363✔
2771
            ++m_in_file_version_at_transaction_boundary;
1,239,657✔
2772
            auto rot_version = RefOrTagged::make_tagged(m_in_file_version_at_transaction_boundary);
1,239,657✔
2773
            m_top.set(top_position_for_version, rot_version);
1,239,657✔
2774
        }
1,239,657✔
2775
    }
3,978,363✔
2776
}
3,978,381✔
2777

2778
void Table::refresh_content_version()
2779
{
1,172,256✔
2780
    REALM_ASSERT(m_top.is_attached());
1,172,256✔
2781
    if (m_top.size() >= top_position_for_version) {
1,172,256✔
2782
        // we have versioning info in the file. Use this to conditionally
622,356✔
2783
        // bump the version counter:
622,356✔
2784
        auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
1,172,112✔
2785
        REALM_ASSERT(rot_version.is_tagged());
1,172,112✔
2786
        if (m_in_file_version_at_transaction_boundary != rot_version.get_as_int()) {
1,172,112✔
2787
            m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
230,103✔
2788
            bump_content_version();
230,103✔
2789
        }
230,103✔
2790
    }
1,172,112✔
2791
    else {
144✔
2792
        // assume the worst:
129✔
2793
        bump_content_version();
144✔
2794
    }
144✔
2795
}
1,172,256✔
2796

2797

2798
// Called when Group is moved to another version - either a rollback or an advance.
2799
// The content of the table is potentially different, so make no assumptions.
2800
void Table::refresh_accessor_tree()
2801
{
362,139✔
2802
    REALM_ASSERT(m_cookie == cookie_initialized);
362,139✔
2803
    REALM_ASSERT(m_top.is_attached());
362,139✔
2804
    m_top.init_from_parent();
362,139✔
2805
    m_spec.init_from_parent();
362,139✔
2806
    REALM_ASSERT(m_top.size() > top_position_for_pk_col);
362,139✔
2807
    m_clusters.init_from_parent();
362,139✔
2808
    m_index_refs.init_from_parent();
362,139✔
2809
    m_opposite_table.init_from_parent();
362,139✔
2810
    m_opposite_column.init_from_parent();
362,139✔
2811
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
362,139✔
2812
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
307,932✔
2813
    if (m_top.size() > top_position_for_flags) {
362,139✔
2814
        auto rot_flags = m_top.get_as_ref_or_tagged(top_position_for_flags);
362,034✔
2815
        m_table_type = Type(rot_flags.get_as_int() & table_type_mask);
362,034✔
2816
    }
362,034✔
2817
    else {
105✔
2818
        m_table_type = Type::TopLevel;
105✔
2819
    }
105✔
2820
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
362,139✔
2821
        // Tombstones exists
354✔
2822
        if (!m_tombstones) {
708✔
2823
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
240✔
2824
        }
240✔
2825
        m_tombstones->init_from_parent();
708✔
2826
    }
708✔
2827
    else {
361,431✔
2828
        m_tombstones = nullptr;
361,431✔
2829
    }
361,431✔
2830
    refresh_content_version();
362,139✔
2831
    bump_storage_version();
362,139✔
2832
    build_column_mapping();
362,139✔
2833
    refresh_index_accessors();
362,139✔
2834
}
362,139✔
2835

2836
void Table::refresh_index_accessors()
2837
{
6,430,851✔
2838
    // Refresh search index accessors
3,499,986✔
2839

3,499,986✔
2840
    // First eliminate any index accessors for eliminated last columns
3,499,986✔
2841
    size_t col_ndx_end = m_leaf_ndx2colkey.size();
6,430,851✔
2842
    m_index_accessors.resize(col_ndx_end);
6,430,851✔
2843

3,499,986✔
2844
    // Then eliminate/refresh/create accessors within column range
3,499,986✔
2845
    // we can not use for_each_column() here, since the columns may have changed
3,499,986✔
2846
    // and the index accessor vector is not updated correspondingly.
3,499,986✔
2847
    for (size_t col_ndx = 0; col_ndx < col_ndx_end; col_ndx++) {
28,083,153✔
2848
        ref_type ref = m_index_refs.get_as_ref(col_ndx);
21,652,302✔
2849

11,281,482✔
2850
        if (ref == 0) {
21,652,302✔
2851
            // accessor drop
9,306,108✔
2852
            m_index_accessors[col_ndx].reset();
17,668,032✔
2853
        }
17,668,032✔
2854
        else {
3,984,270✔
2855
            auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_ndx]);
3,984,270✔
2856
            bool fulltext = attr.test(col_attr_FullText_Indexed);
3,984,270✔
2857
            auto col_key = m_leaf_ndx2colkey[col_ndx];
3,984,270✔
2858
            ClusterColumn virtual_col(&m_clusters, col_key, fulltext ? IndexType::Fulltext : IndexType::General);
3,984,255✔
2859

1,975,374✔
2860
            if (m_index_accessors[col_ndx]) { // still there, refresh:
3,984,270✔
2861
                m_index_accessors[col_ndx]->refresh_accessor_tree(virtual_col);
472,878✔
2862
            }
472,878✔
2863
            else { // new index!
3,511,392✔
2864
                m_index_accessors[col_ndx] =
3,511,392✔
2865
                    std::make_unique<StringIndex>(ref, &m_index_refs, col_ndx, virtual_col, get_alloc());
3,511,392✔
2866
            }
3,511,392✔
2867
        }
3,984,270✔
2868
    }
21,652,302✔
2869
}
6,430,851✔
2870

2871
bool Table::is_cross_table_link_target() const noexcept
2872
{
7,593✔
2873
    auto is_cross_link = [this](ColKey col_key) {
3,918✔
2874
        auto t = col_key.get_type();
66✔
2875
        // look for a backlink with a different target than ourselves
24✔
2876
        return (t == col_type_BackLink && get_opposite_table_key(col_key) != get_key())
66✔
2877
                   ? IteratorControl::Stop
36✔
2878
                   : IteratorControl::AdvanceToNext;
54✔
2879
    };
66✔
2880
    return for_each_backlink_column(is_cross_link);
7,593✔
2881
}
7,593✔
2882

2883
// LCOV_EXCL_START ignore debug functions
2884

2885
void Table::verify() const
2886
{
2,963,778✔
2887
#ifdef REALM_DEBUG
2,963,778✔
2888
    if (m_top.is_attached())
2,963,778✔
2889
        m_top.verify();
2,963,775✔
2890
    m_spec.verify();
2,963,778✔
2891
    m_clusters.verify();
2,963,778✔
2892
    if (nb_unresolved())
2,963,778✔
2893
        m_tombstones->verify();
794,730✔
2894
#endif
2,963,778✔
2895
}
2,963,778✔
2896

2897
#ifdef REALM_DEBUG
2898
MemStats Table::stats() const
2899
{
×
2900
    MemStats mem_stats;
×
2901
    m_top.stats(mem_stats);
×
2902
    return mem_stats;
×
2903
}
×
2904
#endif // LCOV_EXCL_STOP ignore debug functions
2905

2906
Obj Table::create_object(ObjKey key, const FieldValues& values)
2907
{
22,439,583✔
2908
    if (is_embedded())
22,439,583✔
2909
        throw IllegalOperation(util::format("Explicit creation of embedded object not allowed in: %1", get_name()));
48✔
2910
    if (m_primary_key_col)
22,439,535✔
2911
        throw IllegalOperation(util::format("Table has primary key: %1", get_name()));
×
2912
    if (key == null_key) {
22,439,535✔
2913
        GlobalKey object_id = allocate_object_id_squeezed();
19,279,356✔
2914
        key = object_id.get_local_key(get_sync_file_id());
19,279,356✔
2915
        // Check if this key collides with an already existing object
9,604,452✔
2916
        // This could happen if objects were at some point created with primary keys,
9,604,452✔
2917
        // but later primary key property was removed from the schema.
9,604,452✔
2918
        while (m_clusters.is_valid(key)) {
19,279,356✔
2919
            object_id = allocate_object_id_squeezed();
×
2920
            key = object_id.get_local_key(get_sync_file_id());
×
2921
        }
×
2922
        if (auto repl = get_repl())
19,279,356✔
2923
            repl->create_object(this, object_id);
4,297,896✔
2924
    }
19,279,356✔
2925

11,186,400✔
2926
    REALM_ASSERT(key.value >= 0);
22,439,535✔
2927

11,186,400✔
2928
    Obj obj = m_clusters.insert(key, values); // repl->set()
22,439,535✔
2929

11,186,400✔
2930
    return obj;
22,439,535✔
2931
}
22,439,535✔
2932

2933
Obj Table::create_linked_object()
2934
{
39,636✔
2935
    REALM_ASSERT(is_embedded());
39,636✔
2936

19,725✔
2937
    GlobalKey object_id = allocate_object_id_squeezed();
39,636✔
2938
    ObjKey key = object_id.get_local_key(get_sync_file_id());
39,636✔
2939

19,725✔
2940
    REALM_ASSERT(key.value >= 0);
39,636✔
2941

19,725✔
2942
    Obj obj = m_clusters.insert(key, {});
39,636✔
2943

19,725✔
2944
    return obj;
39,636✔
2945
}
39,636✔
2946

2947
Obj Table::create_object(GlobalKey object_id, const FieldValues& values)
2948
{
30✔
2949
    if (is_embedded())
30✔
2950
        throw IllegalOperation(util::format("Explicit creation of embedded object not allowed in: %1", get_name()));
×
2951
    if (m_primary_key_col)
30✔
2952
        throw IllegalOperation(util::format("Table has primary key: %1", get_name()));
×
2953
    ObjKey key = object_id.get_local_key(get_sync_file_id());
30✔
2954

15✔
2955
    if (auto repl = get_repl())
30✔
2956
        repl->create_object(this, object_id);
30✔
2957

15✔
2958
    try {
30✔
2959
        Obj obj = m_clusters.insert(key, values);
30✔
2960
        // Check if tombstone exists
15✔
2961
        if (m_tombstones && m_tombstones->is_valid(key.get_unresolved())) {
30✔
2962
            auto unres_key = key.get_unresolved();
6✔
2963
            // Copy links over
3✔
2964
            auto tombstone = m_tombstones->get(unres_key);
6✔
2965
            obj.assign_pk_and_backlinks(tombstone);
6✔
2966
            // If tombstones had no links to it, it may still be alive
3✔
2967
            if (m_tombstones->is_valid(unres_key)) {
6✔
2968
                CascadeState state(CascadeState::Mode::None);
6✔
2969
                m_tombstones->erase(unres_key, state);
6✔
2970
            }
6✔
2971
        }
6✔
2972

15✔
2973
        return obj;
30✔
2974
    }
30✔
2975
    catch (const KeyAlreadyUsed&) {
6✔
2976
        return m_clusters.get(key);
6✔
2977
    }
6✔
2978
}
30✔
2979

2980
Obj Table::create_object_with_primary_key(const Mixed& primary_key, FieldValues&& field_values, UpdateMode mode,
2981
                                          bool* did_create)
2982
{
588,198✔
2983
    auto primary_key_col = get_primary_key_column();
588,198✔
2984
    if (is_embedded() || !primary_key_col)
588,198✔
2985
        throw InvalidArgument(ErrorCodes::UnexpectedPrimaryKey,
6✔
2986
                              util::format("Table has no primary key: %1", get_name()));
6✔
2987

282,846✔
2988
    DataType type = DataType(primary_key_col.get_type());
588,192✔
2989

282,846✔
2990
    if (primary_key.is_null() && !primary_key_col.is_nullable()) {
588,192✔
2991
        throw InvalidArgument(
6✔
2992
            ErrorCodes::PropertyNotNullable,
6✔
2993
            util::format("Primary key for class %1 cannot be NULL", Group::table_name_to_class_name(get_name())));
6✔
2994
    }
6✔
2995

282,843✔
2996
    if (!(primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) &&
588,186✔
2997
        primary_key.get_type() != type) {
587,967✔
2998
        throw InvalidArgument(ErrorCodes::TypeMismatch, util::format("Wrong primary key type for class %1",
6✔
2999
                                                                     Group::table_name_to_class_name(get_name())));
6✔
3000
    }
6✔
3001

282,840✔
3002
    REALM_ASSERT(type == type_String || type == type_ObjectId || type == type_Int || type == type_UUID);
588,180✔
3003

282,840✔
3004
    if (did_create)
588,180✔
3005
        *did_create = false;
74,325✔
3006

282,840✔
3007
    // Check for existing object
282,840✔
3008
    if (ObjKey key = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key)) {
588,180✔
3009
        if (mode == UpdateMode::never) {
83,076✔
3010
            throw ObjectAlreadyExists(this->get_class_name(), primary_key);
6✔
3011
        }
6✔
3012
        auto obj = m_clusters.get(key);
83,070✔
3013
        for (auto& val : field_values) {
40,959✔
3014
            if (mode == UpdateMode::all || obj.get_any(val.col_key) != val.value) {
12✔
3015
                obj.set_any(val.col_key, val.value, val.is_default);
12✔
3016
            }
12✔
3017
        }
12✔
3018
        return obj;
83,070✔
3019
    }
83,070✔
3020

241,884✔
3021
    ObjKey unres_key;
505,104✔
3022
    if (m_tombstones) {
505,104✔
3023
        // Check for potential tombstone
21,585✔
3024
        GlobalKey object_id{primary_key};
40,989✔
3025
        ObjKey object_key = global_to_local_object_id_hashed(object_id);
40,989✔
3026

21,585✔
3027
        ObjKey key = object_key.get_unresolved();
40,989✔
3028
        if (auto obj = m_tombstones->try_get_obj(key)) {
40,989✔
3029
            auto existing_pk_value = obj.get_any(primary_key_col);
13,497✔
3030

6,918✔
3031
            // If the primary key is the same, the object should be resurrected below
6,918✔
3032
            if (existing_pk_value == primary_key) {
13,497✔
3033
                unres_key = key;
13,491✔
3034
            }
13,491✔
3035
        }
13,497✔
3036
    }
40,989✔
3037

241,884✔
3038
    ObjKey key = get_next_valid_key();
505,104✔
3039

241,884✔
3040
    auto repl = get_repl();
505,104✔
3041
    if (repl) {
505,104✔
3042
        repl->create_object_with_primary_key(this, key, primary_key);
444,012✔
3043
    }
444,012✔
3044
    if (did_create) {
505,104✔
3045
        *did_create = true;
36,261✔
3046
    }
36,261✔
3047

241,884✔
3048
    field_values.insert(primary_key_col, primary_key);
505,104✔
3049
    Obj ret = m_clusters.insert(key, field_values);
505,104✔
3050

241,884✔
3051
    // Check if unresolved exists
241,884✔
3052
    if (unres_key) {
505,104✔
3053
        auto tombstone = m_tombstones->get(unres_key);
13,491✔
3054
        ret.assign_pk_and_backlinks(tombstone);
13,491✔
3055
        // If tombstones had no links to it, it may still be alive
6,915✔
3056
        if (m_tombstones->is_valid(unres_key)) {
13,491✔
3057
            CascadeState state(CascadeState::Mode::None);
4,335✔
3058
            m_tombstones->erase(unres_key, state);
4,335✔
3059
        }
4,335✔
3060
    }
13,491✔
3061
    if (is_asymmetric() && repl && repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
505,104✔
3062
        get_parent_group()->m_objects_to_delete.emplace_back(this->m_key, ret.get_key());
1,266✔
3063
    }
1,266✔
3064
    return ret;
505,104✔
3065
}
505,104✔
3066

3067
ObjKey Table::find_primary_key(Mixed primary_key) const
3068
{
921,288✔
3069
    auto primary_key_col = get_primary_key_column();
921,288✔
3070
    REALM_ASSERT(primary_key_col);
921,288✔
3071
    DataType type = DataType(primary_key_col.get_type());
921,288✔
3072
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
921,288✔
3073
                 primary_key.get_type() == type);
921,288✔
3074

460,206✔
3075
    if (auto&& index = m_index_accessors[primary_key_col.get_index().val]) {
921,300✔
3076
        return index->find_first(primary_key);
921,261✔
3077
    }
921,261✔
3078

39✔
3079
    // This must be file format 11, 20 or 21 as those are the ones we can open in read-only mode
39✔
3080
    // so try the old algorithm
39✔
3081
    GlobalKey object_id{primary_key};
2,147,483,686✔
3082
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
2,147,483,686✔
3083

39✔
3084
    // Check if existing
39✔
3085
    if (auto obj = m_clusters.try_get_obj(object_key)) {
2,147,483,686✔
3086
        auto existing_pk_value = obj.get_any(primary_key_col);
×
3087

3088
        if (existing_pk_value == primary_key) {
×
3089
            return object_key;
×
3090
        }
×
3091
    }
2,147,483,686✔
3092
    return {};
2,147,483,686✔
3093
}
2,147,483,686✔
3094

3095
ObjKey Table::get_objkey_from_primary_key(const Mixed& primary_key)
3096
{
749,676✔
3097
    // Check if existing
375,246✔
3098
    if (auto key = find_primary_key(primary_key)) {
749,676✔
3099
        return key;
718,215✔
3100
    }
718,215✔
3101

15,984✔
3102
    // Object does not exist - create tombstone
15,984✔
3103
    GlobalKey object_id{primary_key};
31,461✔
3104
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
31,461✔
3105
    return get_or_create_tombstone(object_key, m_primary_key_col, primary_key).get_key();
31,461✔
3106
}
31,461✔
3107

3108
ObjKey Table::get_objkey_from_global_key(GlobalKey global_key)
3109
{
18✔
3110
    REALM_ASSERT(!m_primary_key_col);
18✔
3111
    auto object_key = global_key.get_local_key(get_sync_file_id());
18✔
3112

9✔
3113
    // Check if existing
9✔
3114
    if (m_clusters.is_valid(object_key)) {
18✔
3115
        return object_key;
12✔
3116
    }
12✔
3117

3✔
3118
    return get_or_create_tombstone(object_key, {}, {}).get_key();
6✔
3119
}
6✔
3120

3121
ObjKey Table::get_objkey(GlobalKey global_key) const
3122
{
18✔
3123
    ObjKey key;
18✔
3124
    REALM_ASSERT(!m_primary_key_col);
18✔
3125
    uint32_t max = std::numeric_limits<uint32_t>::max();
18✔
3126
    if (global_key.hi() <= max && global_key.lo() <= max) {
18✔
3127
        key = global_key.get_local_key(get_sync_file_id());
6✔
3128
    }
6✔
3129
    if (key && !is_valid(key)) {
18✔
3130
        key = realm::null_key;
6✔
3131
    }
6✔
3132
    return key;
18✔
3133
}
18✔
3134

3135
GlobalKey Table::get_object_id(ObjKey key) const
3136
{
144✔
3137
    auto col = get_primary_key_column();
144✔
3138
    if (col) {
144✔
3139
        const Obj obj = get_object(key);
24✔
3140
        auto val = obj.get_any(col);
24✔
3141
        return {val};
24✔
3142
    }
24✔
3143
    else {
120✔
3144
        return {key, get_sync_file_id()};
120✔
3145
    }
120✔
3146
    return {};
×
3147
}
×
3148

3149
Obj Table::get_object_with_primary_key(Mixed primary_key) const
3150
{
62,574✔
3151
    auto primary_key_col = get_primary_key_column();
62,574✔
3152
    REALM_ASSERT(primary_key_col);
62,574✔
3153
    DataType type = DataType(primary_key_col.get_type());
62,574✔
3154
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
62,574✔
3155
                 primary_key.get_type() == type);
62,574✔
3156
    return m_clusters.get(m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key));
62,574✔
3157
}
62,574✔
3158

3159
Mixed Table::get_primary_key(ObjKey key) const
3160
{
616,320✔
3161
    auto primary_key_col = get_primary_key_column();
616,320✔
3162
    REALM_ASSERT(primary_key_col);
616,320✔
3163
    if (key.is_unresolved()) {
616,320✔
3164
        REALM_ASSERT(m_tombstones);
72✔
3165
        return m_tombstones->get(key).get_any(primary_key_col);
72✔
3166
    }
72✔
3167
    else {
616,248✔
3168
        return m_clusters.get(key).get_any(primary_key_col);
616,248✔
3169
    }
616,248✔
3170
}
616,320✔
3171

3172
GlobalKey Table::allocate_object_id_squeezed()
3173
{
19,319,736✔
3174
    // m_client_file_ident will be zero if we haven't been in contact with
9,624,522✔
3175
    // the server yet.
9,624,522✔
3176
    auto peer_id = get_sync_file_id();
19,319,736✔
3177
    auto sequence = allocate_sequence_number();
19,319,736✔
3178
    return GlobalKey{peer_id, sequence};
19,319,736✔
3179
}
19,319,736✔
3180

3181
namespace {
3182

3183
/// Calculate optimistic local ID that may collide with others. It is up to
3184
/// the caller to ensure that collisions are detected and that
3185
/// allocate_local_id_after_collision() is called to obtain a non-colliding
3186
/// ID.
3187
inline ObjKey get_optimistic_local_id_hashed(GlobalKey global_id)
3188
{
72,816✔
3189
#if REALM_EXERCISE_OBJECT_ID_COLLISION
3190
    const uint64_t optimistic_mask = 0xff;
3191
#else
3192
    const uint64_t optimistic_mask = 0x3fffffffffffffff;
72,816✔
3193
#endif
72,816✔
3194
    static_assert(!(optimistic_mask >> 62), "optimistic Object ID mask must leave the 63rd and 64th bit zero");
72,816✔
3195
    return ObjKey{int64_t(global_id.lo() & optimistic_mask)};
72,816✔
3196
}
72,816✔
3197

3198
inline ObjKey make_tagged_local_id_after_hash_collision(uint64_t sequence_number)
3199
{
12✔
3200
    REALM_ASSERT(!(sequence_number >> 62));
12✔
3201
    return ObjKey{int64_t(0x4000000000000000 | sequence_number)};
12✔
3202
}
12✔
3203

3204
} // namespace
3205

3206
ObjKey Table::global_to_local_object_id_hashed(GlobalKey object_id) const
3207
{
72,816✔
3208
    ObjKey optimistic = get_optimistic_local_id_hashed(object_id);
72,816✔
3209

37,749✔
3210
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
72,816✔
3211
        Allocator& alloc = m_top.get_alloc();
24✔
3212
        Array collision_map{alloc};
24✔
3213
        collision_map.init_from_ref(collision_map_ref); // Throws
24✔
3214

12✔
3215
        Array hi{alloc};
24✔
3216
        hi.init_from_ref(to_ref(collision_map.get(s_collision_map_hi))); // Throws
24✔
3217

12✔
3218
        // Entries are ordered by hi,lo
12✔
3219
        size_t found = hi.find_first(object_id.hi());
24✔
3220
        if (found != npos && uint64_t(hi.get(found)) == object_id.hi()) {
24✔
3221
            Array lo{alloc};
24✔
3222
            lo.init_from_ref(to_ref(collision_map.get(s_collision_map_lo))); // Throws
24✔
3223
            size_t candidate = lo.find_first(object_id.lo(), found);
24✔
3224
            if (candidate != npos && uint64_t(hi.get(candidate)) == object_id.hi()) {
24✔
3225
                Array local_id{alloc};
24✔
3226
                local_id.init_from_ref(to_ref(collision_map.get(s_collision_map_local_id))); // Throws
24✔
3227
                return ObjKey{local_id.get(candidate)};
24✔
3228
            }
24✔
3229
        }
72,792✔
3230
    }
24✔
3231

37,737✔
3232
    return optimistic;
72,792✔
3233
}
72,792✔
3234

3235
ObjKey Table::allocate_local_id_after_hash_collision(GlobalKey incoming_id, GlobalKey colliding_id,
3236
                                                     ObjKey colliding_local_id)
3237
{
12✔
3238
    // Possible optimization: Cache these accessors
6✔
3239
    Allocator& alloc = m_top.get_alloc();
12✔
3240
    Array collision_map{alloc};
12✔
3241
    Array hi{alloc};
12✔
3242
    Array lo{alloc};
12✔
3243
    Array local_id{alloc};
12✔
3244

6✔
3245
    collision_map.set_parent(&m_top, top_position_for_collision_map);
12✔
3246
    hi.set_parent(&collision_map, s_collision_map_hi);
12✔
3247
    lo.set_parent(&collision_map, s_collision_map_lo);
12✔
3248
    local_id.set_parent(&collision_map, s_collision_map_local_id);
12✔
3249

6✔
3250
    ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map));
12✔
3251
    if (collision_map_ref) {
12✔
3252
        collision_map.init_from_parent(); // Throws
×
3253
    }
×
3254
    else {
12✔
3255
        MemRef mem = Array::create_empty_array(Array::type_HasRefs, false, alloc); // Throws
12✔
3256
        collision_map.init_from_mem(mem);                                          // Throws
12✔
3257
        collision_map.update_parent();
12✔
3258

6✔
3259
        ref_type lo_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref();       // Throws
12✔
3260
        ref_type hi_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref();       // Throws
12✔
3261
        ref_type local_id_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref(); // Throws
12✔
3262
        collision_map.add(lo_ref);                                                                     // Throws
12✔
3263
        collision_map.add(hi_ref);                                                                     // Throws
12✔
3264
        collision_map.add(local_id_ref);                                                               // Throws
12✔
3265
    }
12✔
3266

6✔
3267
    hi.init_from_parent();       // Throws
12✔
3268
    lo.init_from_parent();       // Throws
12✔
3269
    local_id.init_from_parent(); // Throws
12✔
3270

6✔
3271
    size_t num_entries = hi.size();
12✔
3272
    REALM_ASSERT(lo.size() == num_entries);
12✔
3273
    REALM_ASSERT(local_id.size() == num_entries);
12✔
3274

6✔
3275
    auto lower_bound_object_id = [&](GlobalKey object_id) -> size_t {
24✔
3276
        size_t i = hi.lower_bound_int(int64_t(object_id.hi()));
24✔
3277
        while (i < num_entries && uint64_t(hi.get(i)) == object_id.hi() && uint64_t(lo.get(i)) < object_id.lo())
30✔
3278
            ++i;
6✔
3279
        return i;
24✔
3280
    };
24✔
3281

6✔
3282
    auto insert_collision = [&](GlobalKey object_id, ObjKey new_local_id) {
24✔
3283
        size_t i = lower_bound_object_id(object_id);
24✔
3284
        if (i != num_entries) {
24✔
3285
            GlobalKey existing{uint64_t(hi.get(i)), uint64_t(lo.get(i))};
6✔
3286
            if (existing == object_id) {
6✔
3287
                REALM_ASSERT(new_local_id.value == local_id.get(i));
×
3288
                return;
×
3289
            }
×
3290
        }
24✔
3291
        hi.insert(i, int64_t(object_id.hi()));
24✔
3292
        lo.insert(i, int64_t(object_id.lo()));
24✔
3293
        local_id.insert(i, new_local_id.value);
24✔
3294
        ++num_entries;
24✔
3295
    };
24✔
3296

6✔
3297
    auto sequence_number_for_local_id = allocate_sequence_number();
12✔
3298
    ObjKey new_local_id = make_tagged_local_id_after_hash_collision(sequence_number_for_local_id);
12✔
3299
    insert_collision(incoming_id, new_local_id);
12✔
3300
    insert_collision(colliding_id, colliding_local_id);
12✔
3301

6✔
3302
    return new_local_id;
12✔
3303
}
12✔
3304

3305
Obj Table::get_or_create_tombstone(ObjKey key, ColKey pk_col, Mixed pk_val)
3306
{
32,001✔
3307
    auto unres_key = key.get_unresolved();
32,001✔
3308

16,251✔
3309
    ensure_graveyard();
32,001✔
3310
    auto tombstone = m_tombstones->try_get_obj(unres_key);
32,001✔
3311
    if (tombstone) {
32,001✔
3312
        if (pk_col) {
2,892✔
3313
            auto existing_pk_value = tombstone.get_any(pk_col);
2,892✔
3314
            // It may just be the same object
1,545✔
3315
            if (existing_pk_value != pk_val) {
2,892✔
3316
                // We have a collision - create new ObjKey
6✔
3317
                key = allocate_local_id_after_hash_collision({pk_val}, {existing_pk_value}, key);
12✔
3318
                return get_or_create_tombstone(key, pk_col, pk_val);
12✔
3319
            }
12✔
3320
        }
2,880✔
3321
        return tombstone;
2,880✔
3322
    }
2,880✔
3323
    return m_tombstones->insert(unres_key, {{pk_col, pk_val}});
29,109✔
3324
}
29,109✔
3325

3326
void Table::free_local_id_after_hash_collision(ObjKey key)
3327
{
5,028,486✔
3328
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
5,028,486✔
3329
        if (key.is_unresolved()) {
30✔
3330
            // Keys will always be inserted as resolved
12✔
3331
            key = key.get_unresolved();
24✔
3332
        }
24✔
3333
        // Possible optimization: Cache these accessors
15✔
3334
        Array collision_map{m_alloc};
30✔
3335
        Array local_id{m_alloc};
30✔
3336

15✔
3337
        collision_map.set_parent(&m_top, top_position_for_collision_map);
30✔
3338
        local_id.set_parent(&collision_map, s_collision_map_local_id);
30✔
3339
        collision_map.init_from_ref(collision_map_ref);
30✔
3340
        local_id.init_from_parent();
30✔
3341
        auto ndx = local_id.find_first(key.value);
30✔
3342
        if (ndx != realm::npos) {
30✔
3343
            Array hi{m_alloc};
24✔
3344
            Array lo{m_alloc};
24✔
3345

12✔
3346
            hi.set_parent(&collision_map, s_collision_map_hi);
24✔
3347
            lo.set_parent(&collision_map, s_collision_map_lo);
24✔
3348
            hi.init_from_parent();
24✔
3349
            lo.init_from_parent();
24✔
3350

12✔
3351
            hi.erase(ndx);
24✔
3352
            lo.erase(ndx);
24✔
3353
            local_id.erase(ndx);
24✔
3354
            if (hi.size() == 0) {
24✔
3355
                free_collision_table();
12✔
3356
            }
12✔
3357
        }
24✔
3358
    }
30✔
3359
}
5,028,486✔
3360

3361
void Table::free_collision_table()
3362
{
3,531✔
3363
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
3,531✔
3364
        Array::destroy_deep(collision_map_ref, m_alloc);
12✔
3365
        m_top.set(top_position_for_collision_map, 0);
12✔
3366
    }
12✔
3367
}
3,531✔
3368

3369
void Table::create_objects(size_t number, std::vector<ObjKey>& keys)
3370
{
3,837✔
3371
    while (number--) {
6,321,990✔
3372
        keys.push_back(create_object().get_key());
6,318,153✔
3373
    }
6,318,153✔
3374
}
3,837✔
3375

3376
void Table::create_objects(const std::vector<ObjKey>& keys)
3377
{
630✔
3378
    for (auto k : keys) {
5,616✔
3379
        create_object(k);
5,616✔
3380
    }
5,616✔
3381
}
630✔
3382

3383
void Table::dump_objects()
3384
{
×
3385
    m_clusters.dump_objects();
×
3386
    if (nb_unresolved())
×
3387
        m_tombstones->dump_objects();
×
3388
}
×
3389

3390
void Table::remove_object(ObjKey key)
3391
{
2,490,480✔
3392
    Group* g = get_parent_group();
2,490,480✔
3393

1,245,666✔
3394
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
2,490,480✔
3395
        CascadeState state(CascadeState::Mode::Strong, g);
3,732✔
3396
        state.m_to_be_deleted.emplace_back(m_key, key);
3,732✔
3397
        m_clusters.nullify_links(key, state);
3,732✔
3398
        remove_recursive(state);
3,732✔
3399
    }
3,732✔
3400
    else {
2,486,748✔
3401
        CascadeState state(CascadeState::Mode::None, g);
2,486,748✔
3402
        if (g) {
2,486,748✔
3403
            m_clusters.nullify_links(key, state);
2,404,878✔
3404
        }
2,404,878✔
3405
        m_clusters.erase(key, state);
2,486,748✔
3406
    }
2,486,748✔
3407
}
2,490,480✔
3408

3409
ObjKey Table::invalidate_object(ObjKey key)
3410
{
63,852✔
3411
    if (is_embedded())
63,852✔
3412
        throw IllegalOperation("Deletion of embedded object not allowed");
×
3413
    REALM_ASSERT(!key.is_unresolved());
63,852✔
3414

32,124✔
3415
    Obj tombstone;
63,852✔
3416
    auto obj = get_object(key);
63,852✔
3417
    if (obj.has_backlinks(false)) {
63,852✔
3418
        // If the object has backlinks, we should make a tombstone
267✔
3419
        // and make inward links point to it,
267✔
3420
        if (auto primary_key_col = get_primary_key_column()) {
534✔
3421
            auto pk = obj.get_any(primary_key_col);
378✔
3422
            GlobalKey object_id{pk};
378✔
3423
            auto unres_key = global_to_local_object_id_hashed(object_id);
378✔
3424
            tombstone = get_or_create_tombstone(unres_key, primary_key_col, pk);
378✔
3425
        }
378✔
3426
        else {
156✔
3427
            tombstone = get_or_create_tombstone(key, {}, {});
156✔
3428
        }
156✔
3429
        tombstone.assign_pk_and_backlinks(obj);
534✔
3430
    }
534✔
3431

32,124✔
3432
    remove_object(key);
63,852✔
3433

32,124✔
3434
    return tombstone.get_key();
63,852✔
3435
}
63,852✔
3436

3437
void Table::remove_object_recursive(ObjKey key)
3438
{
33✔
3439
    size_t table_ndx = get_index_in_group();
33✔
3440
    if (table_ndx != realm::npos) {
33✔
3441
        CascadeState state(CascadeState::Mode::All, get_parent_group());
33✔
3442
        state.m_to_be_deleted.emplace_back(m_key, key);
33✔
3443
        nullify_links(state);
33✔
3444
        remove_recursive(state);
33✔
3445
    }
33✔
3446
    else {
×
3447
        // No links in freestanding table
3448
        CascadeState state(CascadeState::Mode::None);
×
3449
        m_clusters.erase(key, state);
×
3450
    }
×
3451
}
33✔
3452

3453
Table::Iterator Table::begin() const
3454
{
672,996✔
3455
    return Iterator(m_clusters, 0);
672,996✔
3456
}
672,996✔
3457

3458
Table::Iterator Table::end() const
3459
{
9,921,189✔
3460
    return Iterator(m_clusters, size());
9,921,189✔
3461
}
9,921,189✔
3462

3463
TableRef _impl::TableFriend::get_opposite_link_table(const Table& table, ColKey col_key)
3464
{
7,083,486✔
3465
    TableRef ret;
7,083,486✔
3466
    if (col_key) {
7,084,389✔
3467
        return table.get_opposite_table(col_key);
7,084,389✔
3468
    }
7,084,389✔
3469
    return ret;
4,294,967,294✔
3470
}
4,294,967,294✔
3471

3472
const uint64_t Table::max_num_columns;
3473

3474
void Table::build_column_mapping()
3475
{
6,453,591✔
3476
    // build column mapping from spec
3,512,256✔
3477
    // TODO: Optimization - Don't rebuild this for every change
3,512,256✔
3478
    m_spec_ndx2leaf_ndx.clear();
6,453,591✔
3479
    m_leaf_ndx2spec_ndx.clear();
6,453,591✔
3480
    m_leaf_ndx2colkey.clear();
6,453,591✔
3481
    size_t num_spec_cols = m_spec.get_column_count();
6,453,591✔
3482
    m_spec_ndx2leaf_ndx.resize(num_spec_cols);
6,453,591✔
3483
    for (size_t spec_ndx = 0; spec_ndx < num_spec_cols; ++spec_ndx) {
28,074,351✔
3484
        ColKey col_key = m_spec.get_key(spec_ndx);
21,620,760✔
3485
        unsigned leaf_ndx = col_key.get_index().val;
21,620,760✔
3486
        if (leaf_ndx >= m_leaf_ndx2colkey.size()) {
21,620,760✔
3487
            m_leaf_ndx2colkey.resize(leaf_ndx + 1);
21,154,188✔
3488
            m_leaf_ndx2spec_ndx.resize(leaf_ndx + 1, -1);
21,154,188✔
3489
        }
21,154,188✔
3490
        m_spec_ndx2leaf_ndx[spec_ndx] = ColKey::Idx{leaf_ndx};
21,620,760✔
3491
        m_leaf_ndx2spec_ndx[leaf_ndx] = spec_ndx;
21,620,760✔
3492
        m_leaf_ndx2colkey[leaf_ndx] = col_key;
21,620,760✔
3493
    }
21,620,760✔
3494
}
6,453,591✔
3495

3496
ColKey Table::generate_col_key(ColumnType tp, ColumnAttrMask attr)
3497
{
976,629✔
3498
    REALM_ASSERT(!attr.test(col_attr_Indexed));
976,629✔
3499
    REALM_ASSERT(!attr.test(col_attr_Unique)); // Must not be encoded into col_key
976,629✔
3500

481,911✔
3501
    int64_t col_seq_number = m_top.get_as_ref_or_tagged(top_position_for_column_key).get_as_int();
976,629✔
3502
    unsigned upper = unsigned(col_seq_number ^ get_key().value);
976,629✔
3503

481,911✔
3504
    // reuse lowest available leaf ndx:
481,911✔
3505
    unsigned lower = unsigned(m_leaf_ndx2colkey.size());
976,629✔
3506
    // look for an unused entry:
481,911✔
3507
    for (unsigned idx = 0; idx < lower; ++idx) {
6,238,494✔
3508
        if (m_leaf_ndx2colkey[idx] == ColKey()) {
5,261,952✔
3509
            lower = idx;
87✔
3510
            break;
87✔
3511
        }
87✔
3512
    }
5,261,952✔
3513
    return ColKey(ColKey::Idx{lower}, tp, attr, upper);
976,629✔
3514
}
976,629✔
3515

3516
Table::BacklinkOrigin Table::find_backlink_origin(StringData origin_table_name,
3517
                                                  StringData origin_col_name) const noexcept
3518
{
×
3519
    BacklinkOrigin ret;
×
3520
    auto f = [&](ColKey backlink_col_key) {
×
3521
        auto origin_table = get_opposite_table(backlink_col_key);
×
3522
        auto origin_link_col = get_opposite_column(backlink_col_key);
×
3523
        if (origin_table->get_name() == origin_table_name &&
×
3524
            origin_table->get_column_name(origin_link_col) == origin_col_name) {
×
3525
            ret = BacklinkOrigin{{origin_table, origin_link_col}};
×
3526
            return IteratorControl::Stop;
×
3527
        }
×
3528
        return IteratorControl::AdvanceToNext;
×
3529
    };
×
3530
    this->for_each_backlink_column(f);
×
3531
    return ret;
×
3532
}
×
3533

3534
Table::BacklinkOrigin Table::find_backlink_origin(ColKey backlink_col) const noexcept
3535
{
360✔
3536
    try {
360✔
3537
        TableKey linked_table_key = get_opposite_table_key(backlink_col);
360✔
3538
        ColKey linked_column_key = get_opposite_column(backlink_col);
360✔
3539
        if (linked_table_key == m_key) {
360✔
3540
            return {{m_own_ref, linked_column_key}};
24✔
3541
        }
24✔
3542
        else {
336✔
3543
            Group* current_group = get_parent_group();
336✔
3544
            if (current_group) {
336✔
3545
                ConstTableRef linked_table_ref = current_group->get_table(linked_table_key);
336✔
3546
                return {{linked_table_ref, linked_column_key}};
336✔
3547
            }
336✔
3548
        }
×
3549
    }
360✔
3550
    catch (...) {
×
3551
        // backlink column not found, returning empty optional
3552
    }
×
3553
    return {};
180✔
3554
}
360✔
3555

3556
std::vector<std::pair<TableKey, ColKey>> Table::get_incoming_link_columns() const noexcept
3557
{
×
3558
    std::vector<std::pair<TableKey, ColKey>> origins;
×
3559
    auto f = [&](ColKey backlink_col_key) {
×
3560
        auto origin_table_key = get_opposite_table_key(backlink_col_key);
×
3561
        auto origin_link_col = get_opposite_column(backlink_col_key);
×
3562
        origins.emplace_back(origin_table_key, origin_link_col);
×
3563
        return IteratorControl::AdvanceToNext;
×
3564
    };
×
3565
    this->for_each_backlink_column(f);
×
3566
    return origins;
×
3567
}
×
3568

3569
ColKey Table::get_primary_key_column() const
3570
{
19,775,214✔
3571
    return m_primary_key_col;
19,775,214✔
3572
}
19,775,214✔
3573

3574
void Table::set_primary_key_column(ColKey col_key)
3575
{
720✔
3576
    if (col_key == m_primary_key_col) {
720✔
3577
        return;
378✔
3578
    }
378✔
3579

171✔
3580
    if (Replication* repl = get_repl()) {
342✔
3581
        if (repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
240✔
3582
            throw RuntimeError(
×
3583
                ErrorCodes::BrokenInvariant,
×
3584
                util::format("Cannot change primary key property in '%1' when realm is synchronized", get_name()));
×
3585
        }
×
3586
    }
342✔
3587

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

171✔
3590
    if (col_key) {
342✔
3591
        check_column(col_key);
222✔
3592
        validate_column_is_unique(col_key);
222✔
3593
        do_set_primary_key_column(col_key);
222✔
3594
    }
222✔
3595
    else {
120✔
3596
        do_set_primary_key_column(col_key);
120✔
3597
    }
120✔
3598
}
342✔
3599

3600

3601
void Table::do_set_primary_key_column(ColKey col_key)
3602
{
136,416✔
3603
    if (col_key) {
136,416✔
3604
        auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
128,871✔
3605
        auto attr = m_spec.get_column_attr(spec_ndx);
128,871✔
3606
        if (attr.test(col_attr_FullText_Indexed)) {
128,871✔
3607
            throw InvalidColumnKey("primary key cannot have a full text index");
6✔
3608
        }
6✔
3609
    }
136,410✔
3610

67,734✔
3611
    if (m_primary_key_col) {
136,410✔
3612
        // If the search index has not been set explicitly on current pk col, we remove it again
3,807✔
3613
        auto spec_ndx = leaf_ndx2spec_ndx(m_primary_key_col.get_index());
7,449✔
3614
        auto attr = m_spec.get_column_attr(spec_ndx);
7,449✔
3615
        if (!attr.test(col_attr_Indexed)) {
7,449✔
3616
            remove_search_index(m_primary_key_col);
7,437✔
3617
        }
7,437✔
3618
    }
7,449✔
3619

67,734✔
3620
    if (col_key) {
136,410✔
3621
        m_top.set(top_position_for_pk_col, RefOrTagged::make_tagged(col_key.value));
128,865✔
3622
        do_add_search_index(col_key, IndexType::General);
128,865✔
3623
    }
128,865✔
3624
    else {
7,545✔
3625
        m_top.set(top_position_for_pk_col, 0);
7,545✔
3626
    }
7,545✔
3627

67,734✔
3628
    m_primary_key_col = col_key;
136,410✔
3629
}
136,410✔
3630

3631
bool Table::contains_unique_values(ColKey col) const
3632
{
834✔
3633
    if (search_index_type(col) == IndexType::General) {
834✔
3634
        auto search_index = get_search_index(col);
744✔
3635
        return !search_index->has_duplicate_values();
744✔
3636
    }
744✔
3637
    else {
90✔
3638
        TableView tv = where().find_all();
90✔
3639
        tv.distinct(col);
90✔
3640
        return tv.size() == size();
90✔
3641
    }
90✔
3642
}
834✔
3643

3644
void Table::validate_column_is_unique(ColKey col) const
3645
{
834✔
3646
    if (!contains_unique_values(col)) {
834✔
3647
        throw MigrationFailed(util::format("Primary key property '%1.%2' has duplicate values after migration.",
30✔
3648
                                           get_class_name(), get_column_name(col)));
30✔
3649
    }
30✔
3650
}
834✔
3651

3652
void Table::validate_primary_column()
3653
{
1,812✔
3654
    if (ColKey col = get_primary_key_column()) {
1,812✔
3655
        validate_column_is_unique(col);
612✔
3656
    }
612✔
3657
}
1,812✔
3658

3659
ObjKey Table::get_next_valid_key()
3660
{
505,104✔
3661
    ObjKey key;
505,104✔
3662
    do {
505,110✔
3663
        key = ObjKey(allocate_sequence_number());
505,110✔
3664
    } while (m_clusters.is_valid(key));
505,110✔
3665

241,884✔
3666
    return key;
505,104✔
3667
}
505,104✔
3668

3669
namespace {
3670
template <class T>
3671
typename util::RemoveOptional<T>::type remove_optional(T val)
3672
{
88,068✔
3673
    return val;
88,068✔
3674
}
88,068✔
3675
template <>
3676
int64_t remove_optional<Optional<int64_t>>(Optional<int64_t> val)
3677
{
5,499✔
3678
    return *val;
5,499✔
3679
}
5,499✔
3680
template <>
3681
bool remove_optional<Optional<bool>>(Optional<bool> val)
3682
{
11,466✔
3683
    return *val;
11,466✔
3684
}
11,466✔
3685
template <>
3686
ObjectId remove_optional<Optional<ObjectId>>(Optional<ObjectId> val)
3687
{
5,484✔
3688
    return *val;
5,484✔
3689
}
5,484✔
3690
template <>
3691
UUID remove_optional<Optional<UUID>>(Optional<UUID> val)
3692
{
6,060✔
3693
    return *val;
6,060✔
3694
}
6,060✔
3695
} // namespace
3696

3697
template <class F, class T>
3698
void Table::change_nullability(ColKey key_from, ColKey key_to, bool throw_on_null)
3699
{
162✔
3700
    Allocator& allocator = this->get_alloc();
162✔
3701
    bool from_nullability = is_nullable(key_from);
162✔
3702
    auto func = [&](Cluster* cluster) {
162✔
3703
        size_t sz = cluster->node_size();
162✔
3704

81✔
3705
        typename ColumnTypeTraits<F>::cluster_leaf_type from_arr(allocator);
162✔
3706
        typename ColumnTypeTraits<T>::cluster_leaf_type to_arr(allocator);
162✔
3707
        cluster->init_leaf(key_from, &from_arr);
162✔
3708
        cluster->init_leaf(key_to, &to_arr);
162✔
3709

81✔
3710
        for (size_t i = 0; i < sz; i++) {
1,512✔
3711
            if (from_nullability && from_arr.is_null(i)) {
1,356!
3712
                if (throw_on_null) {
57!
3713
                    throw RuntimeError(ErrorCodes::BrokenInvariant,
6✔
3714
                                       util::format("Objects in '%1' has null value(s) in property '%2'", get_name(),
6✔
3715
                                                    get_column_name(key_from)));
6✔
3716
                }
6✔
3717
                else {
51✔
3718
                    to_arr.set(i, ColumnTypeTraits<T>::cluster_leaf_type::default_value(false));
51✔
3719
                }
51✔
3720
            }
57✔
3721
            else {
1,299✔
3722
                auto v = remove_optional(from_arr.get(i));
1,299✔
3723
                to_arr.set(i, v);
1,299✔
3724
            }
1,299✔
3725
        }
1,356✔
3726
    };
162✔
3727

81✔
3728
    m_clusters.update(func);
162✔
3729
}
162✔
3730

3731
template <class F, class T>
3732
void Table::change_nullability_list(ColKey key_from, ColKey key_to, bool throw_on_null)
3733
{
120✔
3734
    Allocator& allocator = this->get_alloc();
120✔
3735
    bool from_nullability = is_nullable(key_from);
120✔
3736
    auto func = [&](Cluster* cluster) {
120✔
3737
        size_t sz = cluster->node_size();
120✔
3738

60✔
3739
        ArrayInteger from_arr(allocator);
120✔
3740
        ArrayInteger to_arr(allocator);
120✔
3741
        cluster->init_leaf(key_from, &from_arr);
120✔
3742
        cluster->init_leaf(key_to, &to_arr);
120✔
3743

60✔
3744
        for (size_t i = 0; i < sz; i++) {
360✔
3745
            ref_type ref_from = to_ref(from_arr.get(i));
240✔
3746
            ref_type ref_to = to_ref(to_arr.get(i));
240✔
3747
            REALM_ASSERT(!ref_to);
240✔
3748

120✔
3749
            if (ref_from) {
240✔
3750
                BPlusTree<F> from_list(allocator);
120✔
3751
                BPlusTree<T> to_list(allocator);
120✔
3752
                from_list.init_from_ref(ref_from);
120✔
3753
                to_list.create();
120✔
3754
                size_t n = from_list.size();
120✔
3755
                for (size_t j = 0; j < n; j++) {
120,120✔
3756
                    auto v = from_list.get(j);
120,000✔
3757
                    if (!from_nullability || aggregate_operations::valid_for_agg(v)) {
120,000!
3758
                        to_list.add(remove_optional(v));
115,278✔
3759
                    }
115,278✔
3760
                    else {
4,722✔
3761
                        if (throw_on_null) {
4,722!
3762
                            throw RuntimeError(ErrorCodes::BrokenInvariant,
×
3763
                                               util::format("Objects in '%1' has null value(s) in list property '%2'",
×
3764
                                                            get_name(), get_column_name(key_from)));
×
3765
                        }
×
3766
                        else {
4,722✔
3767
                            to_list.add(ColumnTypeTraits<T>::cluster_leaf_type::default_value(false));
4,722✔
3768
                        }
4,722✔
3769
                    }
4,722✔
3770
                }
120,000✔
3771
                to_arr.set(i, from_ref(to_list.get_ref()));
120✔
3772
            }
120✔
3773
        }
240✔
3774
    };
120✔
3775

60✔
3776
    m_clusters.update(func);
120✔
3777
}
120✔
3778

3779
void Table::convert_column(ColKey from, ColKey to, bool throw_on_null)
3780
{
282✔
3781
    realm::DataType type_id = get_column_type(from);
282✔
3782
    bool _is_list = is_list(from);
282✔
3783
    if (_is_list) {
282✔
3784
        switch (type_id) {
120✔
3785
            case type_Int:
12✔
3786
                if (is_nullable(from)) {
12✔
3787
                    change_nullability_list<Optional<int64_t>, int64_t>(from, to, throw_on_null);
6✔
3788
                }
6✔
3789
                else {
6✔
3790
                    change_nullability_list<int64_t, Optional<int64_t>>(from, to, throw_on_null);
6✔
3791
                }
6✔
3792
                break;
12✔
3793
            case type_Float:
12✔
3794
                change_nullability_list<float, float>(from, to, throw_on_null);
12✔
3795
                break;
12✔
3796
            case type_Double:
12✔
3797
                change_nullability_list<double, double>(from, to, throw_on_null);
12✔
3798
                break;
12✔
3799
            case type_Bool:
12✔
3800
                change_nullability_list<Optional<bool>, Optional<bool>>(from, to, throw_on_null);
12✔
3801
                break;
12✔
3802
            case type_String:
12✔
3803
                change_nullability_list<StringData, StringData>(from, to, throw_on_null);
12✔
3804
                break;
12✔
3805
            case type_Binary:
12✔
3806
                change_nullability_list<BinaryData, BinaryData>(from, to, throw_on_null);
12✔
3807
                break;
12✔
3808
            case type_Timestamp:
12✔
3809
                change_nullability_list<Timestamp, Timestamp>(from, to, throw_on_null);
12✔
3810
                break;
12✔
3811
            case type_ObjectId:
12✔
3812
                if (is_nullable(from)) {
12✔
3813
                    change_nullability_list<Optional<ObjectId>, ObjectId>(from, to, throw_on_null);
6✔
3814
                }
6✔
3815
                else {
6✔
3816
                    change_nullability_list<ObjectId, Optional<ObjectId>>(from, to, throw_on_null);
6✔
3817
                }
6✔
3818
                break;
12✔
3819
            case type_Decimal:
12✔
3820
                change_nullability_list<Decimal128, Decimal128>(from, to, throw_on_null);
12✔
3821
                break;
12✔
3822
            case type_UUID:
12✔
3823
                if (is_nullable(from)) {
12✔
3824
                    change_nullability_list<Optional<UUID>, UUID>(from, to, throw_on_null);
6✔
3825
                }
6✔
3826
                else {
6✔
3827
                    change_nullability_list<UUID, Optional<UUID>>(from, to, throw_on_null);
6✔
3828
                }
6✔
3829
                break;
12✔
3830
            case type_Link:
✔
3831
            case type_TypedLink:
✔
3832
            case type_LinkList:
✔
3833
                // Can't have lists of these types
3834
            case type_Mixed:
✔
3835
                // These types are no longer supported at all
3836
                REALM_UNREACHABLE();
×
3837
                break;
×
3838
        }
162✔
3839
    }
162✔
3840
    else {
162✔
3841
        switch (type_id) {
162✔
3842
            case type_Int:
36✔
3843
                if (is_nullable(from)) {
36✔
3844
                    change_nullability<Optional<int64_t>, int64_t>(from, to, throw_on_null);
6✔
3845
                }
6✔
3846
                else {
30✔
3847
                    change_nullability<int64_t, Optional<int64_t>>(from, to, throw_on_null);
30✔
3848
                }
30✔
3849
                break;
36✔
3850
            case type_Float:
12✔
3851
                change_nullability<float, float>(from, to, throw_on_null);
12✔
3852
                break;
12✔
3853
            case type_Double:
12✔
3854
                change_nullability<double, double>(from, to, throw_on_null);
12✔
3855
                break;
12✔
3856
            case type_Bool:
12✔
3857
                change_nullability<Optional<bool>, Optional<bool>>(from, to, throw_on_null);
12✔
3858
                break;
12✔
3859
            case type_String:
30✔
3860
                change_nullability<StringData, StringData>(from, to, throw_on_null);
30✔
3861
                break;
30✔
3862
            case type_Binary:
12✔
3863
                change_nullability<BinaryData, BinaryData>(from, to, throw_on_null);
12✔
3864
                break;
12✔
3865
            case type_Timestamp:
12✔
3866
                change_nullability<Timestamp, Timestamp>(from, to, throw_on_null);
12✔
3867
                break;
12✔
3868
            case type_ObjectId:
12✔
3869
                if (is_nullable(from)) {
12✔
3870
                    change_nullability<Optional<ObjectId>, ObjectId>(from, to, throw_on_null);
6✔
3871
                }
6✔
3872
                else {
6✔
3873
                    change_nullability<ObjectId, Optional<ObjectId>>(from, to, throw_on_null);
6✔
3874
                }
6✔
3875
                break;
12✔
3876
            case type_Decimal:
12✔
3877
                change_nullability<Decimal128, Decimal128>(from, to, throw_on_null);
12✔
3878
                break;
12✔
3879
            case type_UUID:
12✔
3880
                if (is_nullable(from)) {
12✔
3881
                    change_nullability<Optional<UUID>, UUID>(from, to, throw_on_null);
6✔
3882
                }
6✔
3883
                else {
6✔
3884
                    change_nullability<UUID, Optional<UUID>>(from, to, throw_on_null);
6✔
3885
                }
6✔
3886
                break;
12✔
3887
            case type_TypedLink:
✔
3888
            case type_Link:
✔
3889
                // Always nullable, so can't convert
3890
            case type_LinkList:
✔
3891
                // Never nullable, so can't convert
3892
            case type_Mixed:
✔
3893
                // These types are no longer supported at all
3894
                REALM_UNREACHABLE();
×
3895
                break;
×
3896
        }
162✔
3897
    }
162✔
3898
}
282✔
3899

3900

3901
ColKey Table::set_nullability(ColKey col_key, bool nullable, bool throw_on_null)
3902
{
522✔
3903
    if (col_key.is_nullable() == nullable)
522✔
3904
        return col_key;
240✔
3905

141✔
3906
    check_column(col_key);
282✔
3907

141✔
3908
    auto index_type = search_index_type(col_key);
282✔
3909
    std::string column_name(get_column_name(col_key));
282✔
3910
    auto type = col_key.get_type();
282✔
3911
    auto attr = col_key.get_attrs();
282✔
3912
    bool is_pk_col = (col_key == m_primary_key_col);
282✔
3913
    if (nullable) {
282✔
3914
        attr.set(col_attr_Nullable);
150✔
3915
    }
150✔
3916
    else {
132✔
3917
        attr.reset(col_attr_Nullable);
132✔
3918
    }
132✔
3919

141✔
3920
    ColKey new_col = generate_col_key(type, attr);
282✔
3921
    do_insert_root_column(new_col, type, "__temporary");
282✔
3922

141✔
3923
    try {
282✔
3924
        convert_column(col_key, new_col, throw_on_null);
282✔
3925
    }
282✔
3926
    catch (...) {
144✔
3927
        // remove any partially filled column
3✔
3928
        remove_column(new_col);
6✔
3929
        throw;
6✔
3930
    }
6✔
3931

138✔
3932
    if (is_pk_col) {
276✔
3933
        // If we go from non nullable to nullable, no values change,
6✔
3934
        // so it is safe to preserve the pk column. Otherwise it is not
6✔
3935
        // safe as a null entry might have been converted to default value.
6✔
3936
        do_set_primary_key_column(nullable ? new_col : ColKey{});
9✔
3937
    }
12✔
3938

138✔
3939
    erase_root_column(col_key);
276✔
3940
    m_spec.rename_column(colkey2spec_ndx(new_col), column_name);
276✔
3941

138✔
3942
    if (index_type != IndexType::None)
276✔
3943
        do_add_search_index(new_col, index_type);
30✔
3944

138✔
3945
    return new_col;
276✔
3946
}
276✔
3947

3948
bool Table::has_any_embedded_objects()
3949
{
2,495,775✔
3950
    if (!m_has_any_embedded_objects) {
2,495,775✔
3951
        m_has_any_embedded_objects = false;
110,556✔
3952
        for_each_public_column([&](ColKey col_key) {
224,880✔
3953
            auto target_table_key = get_opposite_table_key(col_key);
224,880✔
3954
            if (target_table_key && is_link_type(col_key.get_type())) {
224,880✔
3955
                auto target_table = get_parent_group()->get_table(target_table_key);
9,744✔
3956
                if (target_table->is_embedded()) {
9,744✔
3957
                    m_has_any_embedded_objects = true;
7,623✔
3958
                    return IteratorControl::Stop; // early out
7,623✔
3959
                }
7,623✔
3960
            }
217,257✔
3961
            return IteratorControl::AdvanceToNext;
217,257✔
3962
        });
217,257✔
3963
    }
110,556✔
3964
    return *m_has_any_embedded_objects;
2,495,775✔
3965
}
2,495,775✔
3966

3967
void Table::set_opposite_column(ColKey col_key, TableKey opposite_table, ColKey opposite_column)
3968
{
168,528✔
3969
    m_opposite_table.set(col_key.get_index().val, opposite_table.value);
168,528✔
3970
    m_opposite_column.set(col_key.get_index().val, opposite_column.value);
168,528✔
3971
}
168,528✔
3972

3973
ColKey Table::find_backlink_column(ColKey origin_col_key, TableKey origin_table) const
3974
{
41,520✔
3975
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
144,633✔
3976
        if (m_opposite_column.get(i) == origin_col_key.value && m_opposite_table.get(i) == origin_table.value) {
137,769✔
3977
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
34,656✔
3978
        }
34,656✔
3979
    }
137,769✔
3980

20,643✔
3981
    return {};
24,075✔
3982
}
41,520✔
3983

3984
ColKey Table::find_or_add_backlink_column(ColKey origin_col_key, TableKey origin_table)
3985
{
40,872✔
3986
    ColKey backlink_col_key = find_backlink_column(origin_col_key, origin_table);
40,872✔
3987

20,319✔
3988
    if (!backlink_col_key) {
40,872✔
3989
        backlink_col_key = do_insert_root_column(ColKey{}, col_type_BackLink, "");
6,864✔
3990
        set_opposite_column(backlink_col_key, origin_table, origin_col_key);
6,864✔
3991

3,432✔
3992
        if (Replication* repl = get_repl())
6,864✔
3993
            repl->typed_link_change(get_parent_group()->get_table(origin_table).unchecked_ptr(), origin_col_key,
6,534✔
3994
                                    m_key); // Throws
6,534✔
3995
    }
6,864✔
3996

20,319✔
3997
    return backlink_col_key;
40,872✔
3998
}
40,872✔
3999

4000
TableKey Table::get_opposite_table_key(ColKey col_key) const
4001
{
14,488,302✔
4002
    return TableKey(int32_t(m_opposite_table.get(col_key.get_index().val)));
14,488,302✔
4003
}
14,488,302✔
4004

4005
bool Table::links_to_self(ColKey col_key) const
4006
{
52,944✔
4007
    return get_opposite_table_key(col_key) == m_key;
52,944✔
4008
}
52,944✔
4009

4010
TableRef Table::get_opposite_table(ColKey col_key) const
4011
{
7,711,941✔
4012
    if (auto k = get_opposite_table_key(col_key)) {
7,711,941✔
4013
        return get_parent_group()->get_table(k);
7,659,546✔
4014
    }
7,659,546✔
4015
    return {};
52,395✔
4016
}
52,395✔
4017

4018
ColKey Table::get_opposite_column(ColKey col_key) const
4019
{
7,049,157✔
4020
    return ColKey(m_opposite_column.get(col_key.get_index().val));
7,049,157✔
4021
}
7,049,157✔
4022

4023
ColKey Table::find_opposite_column(ColKey col_key) const
4024
{
×
4025
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
×
4026
        if (m_opposite_column.get(i) == col_key.value) {
×
4027
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
×
4028
        }
×
4029
    }
×
4030
    return ColKey();
×
4031
}
×
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