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

realm / realm-core / 1840

14 Nov 2023 02:09PM UTC coverage: 91.683% (+0.006%) from 91.677%
1840

push

Evergreen

web-flow
Merge pull request #7130 from realm/release/13.23.4

Release/13.23.4

92152 of 168858 branches covered (0.0%)

0 of 2 new or added lines in 1 file covered. (0.0%)

56 existing lines in 11 files now uncovered.

231161 of 252132 relevant lines covered (91.68%)

6512704.45 hits per line

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

90.63
/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,494✔
269
    if (size() != other.size())
16,494✔
270
        return false;
×
271
    size_t sz = size();
16,494✔
272
    for (size_t i = 0; i < sz; i++) {
26,310✔
273
        REALM_ASSERT_DEBUG(this->at(i).first == other.at(i).first);
16,626✔
274
        if (this->at(i).second != other.at(i).second)
16,626✔
275
            return false;
6,810✔
276
    }
16,626✔
277
    return true;
13,089✔
278
}
16,494✔
279

280
namespace realm {
281
const char* get_data_type_name(DataType type) noexcept
282
{
649,041✔
283
    switch (type) {
649,041✔
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,146✔
327
    switch (table_type) {
19,146✔
328
        case Table::Type::TopLevel:
19,104✔
329
            return o << "TopLevel";
19,104✔
330
        case Table::Type::Embedded:
6✔
331
            return o << "Embedded";
6✔
332
        case Table::Type::TopLevelAsymmetric:
36✔
333
            return o << "TopLevelAsymmetric";
36✔
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,281✔
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,558✔
369
    m_spec.set_parent(&m_top, top_position_for_spec);
3,558✔
370
    m_index_refs.set_parent(&m_top, top_position_for_search_indexes);
3,558✔
371
    m_opposite_table.set_parent(&m_top, top_position_for_opposite_table);
3,558✔
372
    m_opposite_column.set_parent(&m_top, top_position_for_opposite_column);
3,558✔
373

1,779✔
374
    ref_type ref = create_empty_table(m_alloc); // Throws
3,558✔
375
    ArrayParent* parent = nullptr;
3,558✔
376
    size_t ndx_in_parent = 0;
3,558✔
377
    init(ref, parent, ndx_in_parent, true, false);
3,558✔
378
}
3,558✔
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
{
29,637✔
391
    m_spec.set_parent(&m_top, top_position_for_spec);
29,637✔
392
    m_index_refs.set_parent(&m_top, top_position_for_search_indexes);
29,637✔
393
    m_opposite_table.set_parent(&m_top, top_position_for_opposite_table);
29,637✔
394
    m_opposite_column.set_parent(&m_top, top_position_for_opposite_column);
29,637✔
395
    m_cookie = cookie_created;
29,637✔
396
}
29,637✔
397

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

248,568✔
402
    Table* invalid_link = nullptr;
506,874✔
403
    ColumnAttrMask attr;
506,874✔
404
    if (nullable || type == type_Mixed)
506,874✔
405
        attr.set(col_attr_Nullable);
110,808✔
406
    ColKey col_key = generate_col_key(ColumnType(type), attr);
506,874✔
407

248,568✔
408
    return do_insert_column(col_key, type, name, invalid_link); // Throws
506,874✔
409
}
506,874✔
410

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

14,697✔
423
    m_has_any_embedded_objects.reset();
29,604✔
424

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

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

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

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

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

15,018✔
467
    m_has_any_embedded_objects.reset();
30,471✔
468

15,018✔
469
    ColumnAttrMask attr;
30,471✔
470
    attr.set(col_attr_List);
30,471✔
471
    ColKey col_key = generate_col_key(col_type_LinkList, attr);
30,471✔
472

15,018✔
473
    return do_insert_column(col_key, type_LinkList, name, &target); // Throws
30,471✔
474
}
30,471✔
475

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

5,184✔
490
    ColumnAttrMask attr;
10,476✔
491
    attr.set(col_attr_Set);
10,476✔
492
    ColKey col_key = generate_col_key(col_type_Link, attr);
10,476✔
493
    return do_insert_column(col_key, type_Link, name, &target); // Throws
10,476✔
494
}
10,476✔
495

496
ColKey Table::add_column_link(DataType type, StringData name, Table& target)
497
{
×
498
    REALM_ASSERT(is_link_type(ColumnType(type)));
×
499

500
    if (type == type_LinkList) {
×
501
        return add_column_list(target, name);
×
502
    }
×
503
    else {
×
504
        REALM_ASSERT(type == type_Link);
×
505
        return add_column(target, name);
×
506
    }
×
507
}
×
508

509
ColKey Table::add_column_dictionary(DataType type, StringData name, bool nullable, DataType key_type)
510
{
42,486✔
511
    Table* invalid_link = nullptr;
42,486✔
512
    ColumnAttrMask attr;
42,486✔
513
    REALM_ASSERT(key_type != type_Mixed);
42,486✔
514
    attr.set(col_attr_Dictionary);
42,486✔
515
    if (nullable || type == type_Mixed)
42,486✔
516
        attr.set(col_attr_Nullable);
22,992✔
517
    ColKey col_key = generate_col_key(ColumnType(type), attr);
42,486✔
518
    return do_insert_column(col_key, type, name, invalid_link, key_type); // Throws
42,486✔
519
}
42,486✔
520

521
ColKey Table::add_column_dictionary(Table& target, StringData name, DataType key_type)
522
{
11,076✔
523
    // Both origin and target must be group-level tables, and in the same group.
5,430✔
524
    Group* origin_group = get_parent_group();
11,076✔
525
    Group* target_group = target.get_parent_group();
11,076✔
526
    REALM_ASSERT_RELEASE(origin_group && target_group);
11,076✔
527
    REALM_ASSERT_RELEASE(origin_group == target_group);
11,076✔
528
    // Incoming links from an asymmetric table are not allowed.
5,430✔
529
    if (target.is_asymmetric()) {
11,076✔
530
        throw IllegalOperation("Dictionary of ephemeral objects not supported");
×
531
    }
×
532

5,430✔
533
    ColumnAttrMask attr;
11,076✔
534
    attr.set(col_attr_Dictionary);
11,076✔
535
    attr.set(col_attr_Nullable);
11,076✔
536

5,430✔
537
    ColKey col_key = generate_col_key(ColumnType(col_type_Link), attr);
11,076✔
538
    return do_insert_column(col_key, type_Link, name, &target, key_type); // Throws
11,076✔
539
}
11,076✔
540

541
void Table::remove_recursive(CascadeState& cascade_state)
542
{
14,622✔
543
    Group* group = get_parent_group();
14,622✔
544
    REALM_ASSERT(group);
14,622✔
545
    cascade_state.m_group = group;
14,622✔
546

6,648✔
547
    do {
18,729✔
548
        cascade_state.send_notifications();
18,729✔
549

8,700✔
550
        for (auto& l : cascade_state.m_to_be_nullified) {
8,724✔
551
            Obj obj = group->get_table_unchecked(l.origin_table)->try_get_object(l.origin_key);
48✔
552
            REALM_ASSERT_DEBUG(obj);
48✔
553
            if (obj) {
48✔
554
                std::move(obj).nullify_link(l.origin_col_key, l.old_target_link);
48✔
555
            }
48✔
556
        }
48✔
557
        cascade_state.m_to_be_nullified.clear();
18,729✔
558

8,700✔
559
        auto to_delete = std::move(cascade_state.m_to_be_deleted);
18,729✔
560
        for (auto obj : to_delete) {
16,254✔
561
            auto table = obj.first == m_key ? this : group->get_table_unchecked(obj.first);
12,654✔
562
            // This might add to the list of objects that should be deleted
7,518✔
563
            REALM_ASSERT(!obj.second.is_unresolved());
15,072✔
564
            table->m_clusters.erase(obj.second, cascade_state);
15,072✔
565
        }
15,072✔
566
        nullify_links(cascade_state);
18,729✔
567
    } while (!cascade_state.m_to_be_deleted.empty() || !cascade_state.m_to_be_nullified.empty());
18,729✔
568
}
14,622✔
569

570
void Table::nullify_links(CascadeState& cascade_state)
571
{
23,562✔
572
    Group* group = get_parent_group();
23,562✔
573
    REALM_ASSERT(group);
23,562✔
574
    for (auto& to_delete : cascade_state.m_to_be_deleted) {
15,135✔
575
        auto table = to_delete.first == m_key ? this : group->get_table_unchecked(to_delete.first);
7,074✔
576
        if (!table->is_asymmetric())
8,019✔
577
            table->m_clusters.nullify_incoming_links(to_delete.second, cascade_state);
8,019✔
578
    }
8,019✔
579
}
23,562✔
580

581

582
void Table::remove_column(ColKey col_key)
583
{
17,247✔
584
    check_column(col_key);
17,247✔
585

8,478✔
586
    if (Replication* repl = get_repl())
17,247✔
587
        repl->erase_column(this, col_key); // Throws
516✔
588

8,478✔
589
    if (col_key == m_primary_key_col) {
17,247✔
590
        do_set_primary_key_column(ColKey());
7,479✔
591
    }
7,479✔
592
    else {
9,768✔
593
        REALM_ASSERT_RELEASE(m_primary_key_col.get_index().val != col_key.get_index().val);
9,768✔
594
    }
9,768✔
595

8,478✔
596
    erase_root_column(col_key); // Throws
17,247✔
597
    m_has_any_embedded_objects.reset();
17,247✔
598
}
17,247✔
599

600

601
void Table::rename_column(ColKey col_key, StringData name)
602
{
93✔
603
    check_column(col_key);
93✔
604

48✔
605
    auto col_ndx = colkey2spec_ndx(col_key);
93✔
606
    m_spec.rename_column(col_ndx, name); // Throws
93✔
607

48✔
608
    bump_content_version();
93✔
609
    bump_storage_version();
93✔
610

48✔
611
    if (Replication* repl = get_repl())
93✔
612
        repl->rename_column(this, col_key, name); // Throws
93✔
613
}
93✔
614

615

616
TableKey Table::get_key_direct(Allocator& alloc, ref_type top_ref)
617
{
9,736,680✔
618
    // well, not quite "direct", more like "almost direct":
5,155,248✔
619
    Array table_top(alloc);
9,736,680✔
620
    table_top.init_from_ref(top_ref);
9,736,680✔
621
    if (table_top.size() > 3) {
9,736,893✔
622
        RefOrTagged rot = table_top.get_as_ref_or_tagged(top_position_for_key);
9,736,758✔
623
        return TableKey(int32_t(rot.get_as_int()));
9,736,758✔
624
    }
9,736,758✔
625
    else {
2,147,483,782✔
626
        return TableKey();
2,147,483,782✔
627
    }
2,147,483,782✔
628
}
9,736,680✔
629

630

631
void Table::init(ref_type top_ref, ArrayParent* parent, size_t ndx_in_parent, bool is_writable, bool is_frzn)
632
{
4,978,998✔
633
    REALM_ASSERT(!(is_writable && is_frzn));
4,978,998✔
634
    m_is_frozen = is_frzn;
4,978,998✔
635
    m_alloc.set_read_only(!is_writable);
4,978,998✔
636
    // Load from allocated memory
2,712,825✔
637
    m_top.set_parent(parent, ndx_in_parent);
4,978,998✔
638
    m_top.init_from_ref(top_ref);
4,978,998✔
639

2,712,825✔
640
    m_spec.init_from_parent();
4,978,998✔
641

2,712,825✔
642
    while (m_top.size() <= top_position_for_pk_col) {
4,979,958✔
643
        m_top.add(0);
960✔
644
    }
960✔
645

2,712,825✔
646
    if (m_top.get_as_ref(top_position_for_cluster_tree) == 0) {
4,978,998✔
647
        // This is an upgrade - create cluster
48✔
648
        MemRef mem = Cluster::create_empty_cluster(m_top.get_alloc()); // Throws
96✔
649
        m_top.set_as_ref(top_position_for_cluster_tree, mem.get_ref());
96✔
650
    }
96✔
651
    m_clusters.init_from_parent();
4,978,998✔
652

2,712,825✔
653
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_key);
4,978,998✔
654
    if (!rot.is_tagged()) {
4,978,998✔
655
        // Create table key
48✔
656
        rot = RefOrTagged::make_tagged(ndx_in_parent);
96✔
657
        m_top.set(top_position_for_key, rot);
96✔
658
    }
96✔
659
    m_key = TableKey(int32_t(rot.get_as_int()));
4,978,998✔
660

2,712,825✔
661
    // index setup relies on column mapping being up to date:
2,712,825✔
662
    build_column_mapping();
4,978,998✔
663
    if (m_top.get_as_ref(top_position_for_search_indexes) == 0) {
4,978,998✔
664
        // This is an upgrade - create the necessary arrays
48✔
665
        bool context_flag = false;
96✔
666
        size_t nb_columns = m_spec.get_column_count();
96✔
667
        MemRef mem = Array::create_array(Array::type_HasRefs, context_flag, nb_columns, 0, m_top.get_alloc());
96✔
668
        m_index_refs.init_from_mem(mem);
96✔
669
        m_index_refs.update_parent();
96✔
670
        mem = Array::create_array(Array::type_Normal, context_flag, nb_columns, TableKey().value, m_top.get_alloc());
96✔
671
        m_opposite_table.init_from_mem(mem);
96✔
672
        m_opposite_table.update_parent();
96✔
673
        mem = Array::create_array(Array::type_Normal, context_flag, nb_columns, ColKey().value, m_top.get_alloc());
96✔
674
        m_opposite_column.init_from_mem(mem);
96✔
675
        m_opposite_column.update_parent();
96✔
676
    }
96✔
677
    else {
4,978,902✔
678
        m_opposite_table.init_from_parent();
4,978,902✔
679
        m_opposite_column.init_from_parent();
4,978,902✔
680
        m_index_refs.init_from_parent();
4,978,902✔
681
        m_index_accessors.resize(m_index_refs.size());
4,978,902✔
682
    }
4,978,902✔
683
    if (!m_top.get_as_ref_or_tagged(top_position_for_column_key).is_tagged()) {
4,978,998✔
684
        m_top.set(top_position_for_column_key, RefOrTagged::make_tagged(0));
96✔
685
    }
96✔
686
    auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
4,978,998✔
687
    if (!rot_version.is_tagged()) {
4,978,998✔
688
        m_top.set(top_position_for_version, RefOrTagged::make_tagged(0));
96✔
689
        m_in_file_version_at_transaction_boundary = 0;
96✔
690
    }
96✔
691
    else
4,978,902✔
692
        m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
4,978,902✔
693

2,712,825✔
694
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
4,978,998✔
695
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
4,447,539✔
696

2,712,825✔
697
    if (m_top.size() <= top_position_for_flags) {
4,978,998✔
698
        m_table_type = Type::TopLevel;
702✔
699
    }
702✔
700
    else {
4,978,296✔
701
        uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
4,978,296✔
702
        m_table_type = Type(flags & table_type_mask);
4,978,296✔
703
    }
4,978,296✔
704
    m_has_any_embedded_objects.reset();
4,978,998✔
705

2,712,825✔
706
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
4,978,998✔
707
        // Tombstones exists
411,159✔
708
        if (!m_tombstones) {
814,398✔
709
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
511,281✔
710
        }
511,281✔
711
        m_tombstones->init_from_parent();
814,398✔
712
    }
814,398✔
713
    else {
4,164,600✔
714
        m_tombstones = nullptr;
4,164,600✔
715
    }
4,164,600✔
716
    m_cookie = cookie_initialized;
4,978,998✔
717
}
4,978,998✔
718

719

720
ColKey Table::do_insert_column(ColKey col_key, DataType type, StringData name, Table* target_table, DataType key_type)
721
{
763,911✔
722
    col_key = do_insert_root_column(col_key, ColumnType(type), name, key_type); // Throws
763,911✔
723

376,290✔
724
    // When the inserted column is a link-type column, we must also add a
376,290✔
725
    // backlink column to the target table.
376,290✔
726

376,290✔
727
    if (target_table) {
763,911✔
728
        auto backlink_col_key = target_table->do_insert_root_column(ColKey{}, col_type_BackLink, ""); // Throws
81,621✔
729
        target_table->check_column(backlink_col_key);
81,621✔
730

40,326✔
731
        set_opposite_column(col_key, target_table->get_key(), backlink_col_key);
81,621✔
732
        target_table->set_opposite_column(backlink_col_key, get_key(), col_key);
81,621✔
733
    }
81,621✔
734

376,290✔
735
    if (Replication* repl = get_repl())
763,911✔
736
        repl->insert_column(this, col_key, type, name, target_table); // Throws
746,253✔
737

376,290✔
738
    return col_key;
763,911✔
739
}
763,911✔
740

741

742
void Table::populate_search_index(ColKey col_key)
743
{
133,629✔
744
    auto col_ndx = col_key.get_index().val;
133,629✔
745
    StringIndex* index = m_index_accessors[col_ndx].get();
133,629✔
746

66,216✔
747
    // Insert ref to index
66,216✔
748
    for (auto o : *this) {
1,325,145✔
749
        ObjKey key = o.get_key();
1,325,145✔
750
        DataType type = get_column_type(col_key);
1,325,145✔
751

662,442✔
752
        if (type == type_Int) {
1,325,145✔
753
            if (is_nullable(col_key)) {
1,214,070✔
754
                Optional<int64_t> value = o.get<Optional<int64_t>>(col_key);
60✔
755
                index->insert(key, value); // Throws
60✔
756
            }
60✔
757
            else {
1,214,010✔
758
                int64_t value = o.get<int64_t>(col_key);
1,214,010✔
759
                index->insert(key, value); // Throws
1,214,010✔
760
            }
1,214,010✔
761
        }
1,214,070✔
762
        else if (type == type_Bool) {
111,075✔
763
            if (is_nullable(col_key)) {
156✔
764
                Optional<bool> value = o.get<Optional<bool>>(col_key);
54✔
765
                index->insert(key, value); // Throws
54✔
766
            }
54✔
767
            else {
102✔
768
                bool value = o.get<bool>(col_key);
102✔
769
                index->insert(key, value); // Throws
102✔
770
            }
102✔
771
        }
156✔
772
        else if (type == type_String) {
110,919✔
773
            StringData value = o.get<StringData>(col_key);
110,709✔
774
            index->insert(key, value); // Throws
110,709✔
775
        }
110,709✔
776
        else if (type == type_Timestamp) {
210✔
777
            Timestamp value = o.get<Timestamp>(col_key);
132✔
778
            index->insert(key, value); // Throws
132✔
779
        }
132✔
780
        else if (type == type_ObjectId) {
78✔
781
            if (is_nullable(col_key)) {
36✔
782
                Optional<ObjectId> value = o.get<Optional<ObjectId>>(col_key);
18✔
783
                index->insert(key, value); // Throws
18✔
784
            }
18✔
785
            else {
18✔
786
                ObjectId value = o.get<ObjectId>(col_key);
18✔
787
                index->insert(key, value); // Throws
18✔
788
            }
18✔
789
        }
36✔
790
        else if (type == type_UUID) {
42✔
791
            if (is_nullable(col_key)) {
36✔
792
                Optional<UUID> value = o.get<Optional<UUID>>(col_key);
18✔
793
                index->insert(key, value); // Throws
18✔
794
            }
18✔
795
            else {
18✔
796
                UUID value = o.get<UUID>(col_key);
18✔
797
                index->insert(key, value); // Throws
18✔
798
            }
18✔
799
        }
36✔
800
        else if (type == type_Mixed) {
6✔
801
            index->insert(key, o.get<Mixed>(col_key));
6✔
802
        }
6✔
UNCOV
803
        else {
×
UNCOV
804
            REALM_ASSERT_RELEASE(false && "Data type does not support search index");
×
UNCOV
805
        }
×
806
    }
1,325,145✔
807
}
133,629✔
808

809
void Table::erase_from_search_indexes(ObjKey key)
810
{
5,027,316✔
811
    // Tombstones do not use index - will crash if we try to erase values
2,513,217✔
812
    if (!key.is_unresolved()) {
5,027,316✔
813
        for (auto&& index : m_index_accessors) {
6,700,818✔
814
            if (index) {
6,700,818✔
815
                index->erase(key);
281,013✔
816
            }
281,013✔
817
        }
6,700,818✔
818
    }
5,013,837✔
819
}
5,027,316✔
820

821
void Table::update_indexes(ObjKey key, const FieldValues& values)
822
{
23,302,356✔
823
    // Tombstones do not use index - will crash if we try to insert values
11,619,072✔
824
    if (key.is_unresolved()) {
23,302,356✔
825
        return;
28,332✔
826
    }
28,332✔
827

11,605,065✔
828
    auto sz = m_index_accessors.size();
23,274,024✔
829
    // values are sorted by column index - there may be values missing
11,605,065✔
830
    auto value = values.begin();
23,274,024✔
831
    for (size_t column_ndx = 0; column_ndx < sz; column_ndx++) {
57,565,011✔
832
        // Check if initial value is provided
17,050,260✔
833
        Mixed init_value;
34,291,059✔
834
        if (value != values.end() && value->col_key.get_index().val == column_ndx) {
34,291,059✔
835
            // Value for this column is provided
282,831✔
836
            init_value = value->value;
587,301✔
837
            ++value;
587,301✔
838
        }
587,301✔
839

17,050,260✔
840
        if (auto&& index = m_index_accessors[column_ndx]) {
34,291,059✔
841
            // There is an index for this column
554,793✔
842
            auto col_key = m_leaf_ndx2colkey[column_ndx];
1,131,345✔
843
            auto type = col_key.get_type();
1,131,345✔
844
            auto attr = col_key.get_attrs();
1,131,345✔
845
            bool nullable = attr.test(col_attr_Nullable);
1,131,345✔
846
            switch (type) {
1,131,345✔
847
                case col_type_Int:
534,843✔
848
                    if (init_value.is_null()) {
534,843✔
849
                        index->insert(key, ArrayIntNull::default_value(nullable));
165,588✔
850
                    }
165,588✔
851
                    else {
369,255✔
852
                        index->insert(key, init_value.get<int64_t>());
369,255✔
853
                    }
369,255✔
854
                    break;
534,843✔
855
                case col_type_Bool:
6,024✔
856
                    if (init_value.is_null()) {
6,024✔
857
                        index->insert(key, ArrayBoolNull::default_value(nullable));
5,988✔
858
                    }
5,988✔
859
                    else {
36✔
860
                        index->insert(key, init_value.get<bool>());
36✔
861
                    }
36✔
862
                    break;
6,024✔
863
                case col_type_String:
479,415✔
864
                    if (init_value.is_null()) {
479,415✔
865
                        index->insert(key, ArrayString::default_value(nullable));
432,819✔
866
                    }
432,819✔
867
                    else {
46,596✔
868
                        index->insert(key, init_value.get<String>());
46,596✔
869
                    }
46,596✔
870
                    break;
479,415✔
871
                case col_type_Timestamp:
6,267✔
872
                    if (init_value.is_null()) {
6,267✔
873
                        index->insert(key, ArrayTimestamp::default_value(nullable));
6,231✔
874
                    }
6,231✔
875
                    else {
36✔
876
                        index->insert(key, init_value.get<Timestamp>());
36✔
877
                    }
36✔
878
                    break;
6,267✔
879
                case col_type_ObjectId:
85,794✔
880
                    if (init_value.is_null()) {
85,794✔
881
                        index->insert(key, ArrayObjectIdNull::default_value(nullable));
6,120✔
882
                    }
6,120✔
883
                    else {
79,674✔
884
                        index->insert(key, init_value.get<ObjectId>());
79,674✔
885
                    }
79,674✔
886
                    break;
85,794✔
887
                case col_type_Mixed:
834✔
888
                    index->insert(key, init_value);
834✔
889
                    break;
834✔
890
                case col_type_UUID:
18,342✔
891
                    if (init_value.is_null()) {
18,342✔
892
                        index->insert(key, ArrayUUIDNull::default_value(nullable));
6,138✔
893
                    }
6,138✔
894
                    else {
12,204✔
895
                        index->insert(key, init_value.get<UUID>());
12,204✔
896
                    }
12,204✔
897
                    break;
18,342✔
898
                default:
✔
899
                    REALM_UNREACHABLE();
900
            }
1,131,345✔
901
        }
1,131,345✔
902
    }
34,291,059✔
903
}
23,274,024✔
904

905
void Table::clear_indexes()
906
{
4,290✔
907
    for (auto&& index : m_index_accessors) {
48,570✔
908
        if (index) {
48,570✔
909
            index->clear();
3,024✔
910
        }
3,024✔
911
    }
48,570✔
912
}
4,290✔
913

914
void Table::do_add_search_index(ColKey col_key, IndexType type)
915
{
134,061✔
916
    size_t column_ndx = col_key.get_index().val;
134,061✔
917

66,435✔
918
    // Early-out if already indexed
66,435✔
919
    if (m_index_accessors[column_ndx] != nullptr)
134,061✔
920
        return;
384✔
921

66,243✔
922
    if (!StringIndex::type_supported(DataType(col_key.get_type())) || col_key.is_collection() ||
133,677✔
923
        (type == IndexType::Fulltext && col_key.get_type() != col_type_String)) {
133,653✔
924
        // Not ideal, but this is what we used to throw, so keep throwing that for compatibility reasons, even though
24✔
925
        // it should probably be a type mismatch exception instead.
24✔
926
        throw IllegalOperation(util::format("Index not supported for this property: %1", get_column_name(col_key)));
48✔
927
    }
48✔
928

66,219✔
929
    // m_index_accessors always has the same number of pointers as the number of columns. Columns without search
66,219✔
930
    // index have 0-entries.
66,219✔
931
    REALM_ASSERT(m_index_accessors.size() == m_leaf_ndx2colkey.size());
133,629✔
932
    REALM_ASSERT(m_index_accessors[column_ndx] == nullptr);
133,629✔
933

66,219✔
934
    // Create the index
66,219✔
935
    m_index_accessors[column_ndx] =
133,629✔
936
        std::make_unique<StringIndex>(ClusterColumn(&m_clusters, col_key, type), get_alloc()); // Throws
133,629✔
937
    StringIndex* index = m_index_accessors[column_ndx].get();
133,629✔
938

66,219✔
939
    // Insert ref to index
66,219✔
940
    index->set_parent(&m_index_refs, column_ndx);
133,629✔
941
    m_index_refs.set(column_ndx, index->get_ref()); // Throws
133,629✔
942

66,219✔
943
    populate_search_index(col_key);
133,629✔
944
}
133,629✔
945

946
void Table::add_search_index(ColKey col_key, IndexType type)
947
{
3,888✔
948
    check_column(col_key);
3,888✔
949

1,926✔
950
    // Check spec
1,926✔
951
    auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
3,888✔
952
    auto attr = m_spec.get_column_attr(spec_ndx);
3,888✔
953

1,926✔
954
    if (col_key == m_primary_key_col && type == IndexType::Fulltext)
3,888✔
955
        throw InvalidColumnKey("primary key cannot have a full text index");
6✔
956

1,923✔
957
    switch (type) {
3,882✔
958
        case IndexType::None:
✔
959
            remove_search_index(col_key);
×
960
            return;
×
961
        case IndexType::Fulltext:
54✔
962
            // Early-out if already indexed
27✔
963
            if (attr.test(col_attr_FullText_Indexed)) {
54✔
964
                REALM_ASSERT(search_index_type(col_key) == IndexType::Fulltext);
×
965
                return;
×
966
            }
×
967
            if (attr.test(col_attr_Indexed)) {
54✔
968
                this->remove_search_index(col_key);
×
969
            }
×
970
            break;
54✔
971
        case IndexType::General:
3,828✔
972
            if (attr.test(col_attr_Indexed)) {
3,828✔
973
                REALM_ASSERT(search_index_type(col_key) == IndexType::General);
24✔
974
                return;
24✔
975
            }
24✔
976
            if (attr.test(col_attr_FullText_Indexed)) {
3,804✔
977
                this->remove_search_index(col_key);
×
978
            }
×
979
            break;
3,804✔
980
    }
3,858✔
981

1,911✔
982
    do_add_search_index(col_key, type);
3,858✔
983

1,911✔
984
    // Update spec
1,911✔
985
    attr.set(type == IndexType::Fulltext ? col_attr_FullText_Indexed : col_attr_Indexed);
3,831✔
986
    m_spec.set_column_attr(spec_ndx, attr); // Throws
3,858✔
987
}
3,858✔
988

989
void Table::remove_search_index(ColKey col_key)
990
{
7,935✔
991
    check_column(col_key);
7,935✔
992
    auto column_ndx = col_key.get_index();
7,935✔
993

3,882✔
994
    // Early-out if non-indexed
3,882✔
995
    if (m_index_accessors[column_ndx.val] == nullptr)
7,935✔
996
        return;
69✔
997

3,849✔
998
    // Destroy and remove the index column
3,849✔
999
    auto& index = m_index_accessors[column_ndx.val];
7,866✔
1000
    REALM_ASSERT(index != nullptr);
7,866✔
1001
    index->destroy();
7,866✔
1002
    index.reset();
7,866✔
1003

3,849✔
1004
    m_index_refs.set(column_ndx.val, 0);
7,866✔
1005

3,849✔
1006
    // update spec
3,849✔
1007
    auto spec_ndx = leaf_ndx2spec_ndx(column_ndx);
7,866✔
1008
    auto attr = m_spec.get_column_attr(spec_ndx);
7,866✔
1009
    attr.reset(col_attr_Indexed);
7,866✔
1010
    attr.reset(col_attr_FullText_Indexed);
7,866✔
1011
    m_spec.set_column_attr(spec_ndx, attr); // Throws
7,866✔
1012
}
7,866✔
1013

1014
void Table::enumerate_string_column(ColKey col_key)
1015
{
1,296✔
1016
    check_column(col_key);
1,296✔
1017
    size_t column_ndx = colkey2spec_ndx(col_key);
1,296✔
1018
    ColumnType type = col_key.get_type();
1,296✔
1019
    if (type == col_type_String && !col_key.is_collection() && !m_spec.is_string_enum_type(column_ndx)) {
1,296✔
1020
        m_clusters.enumerate_string_column(col_key);
690✔
1021
    }
690✔
1022
}
1,296✔
1023

1024
bool Table::is_enumerated(ColKey col_key) const noexcept
1025
{
58,443✔
1026
    size_t col_ndx = colkey2spec_ndx(col_key);
58,443✔
1027
    return m_spec.is_string_enum_type(col_ndx);
58,443✔
1028
}
58,443✔
1029

1030
size_t Table::get_num_unique_values(ColKey col_key) const
1031
{
138✔
1032
    if (!is_enumerated(col_key))
138✔
1033
        return 0;
84✔
1034

27✔
1035
    ArrayParent* parent;
54✔
1036
    ref_type ref = const_cast<Spec&>(m_spec).get_enumkeys_ref(colkey2spec_ndx(col_key), parent);
54✔
1037
    BPlusTree<StringData> col(get_alloc());
54✔
1038
    col.init_from_ref(ref);
54✔
1039

27✔
1040
    return col.size();
54✔
1041
}
54✔
1042

1043

1044
void Table::erase_root_column(ColKey col_key)
1045
{
17,523✔
1046
    check_column(col_key);
17,523✔
1047
    ColumnType col_type = col_key.get_type();
17,523✔
1048
    if (is_link_type(col_type)) {
17,523✔
1049
        auto target_table = get_opposite_table(col_key);
207✔
1050
        auto target_column = get_opposite_column(col_key);
207✔
1051
        target_table->do_erase_root_column(target_column);
207✔
1052
    }
207✔
1053
    do_erase_root_column(col_key); // Throws
17,523✔
1054
}
17,523✔
1055

1056

1057
ColKey Table::do_insert_root_column(ColKey col_key, ColumnType type, StringData name, DataType key_type)
1058
{
982,338✔
1059
    // if col_key specifies a key, it must be unused
484,440✔
1060
    REALM_ASSERT(!col_key || !valid_column(col_key));
982,338✔
1061

484,440✔
1062
    // locate insertion point: ordinary columns must come before backlink columns
484,440✔
1063
    size_t spec_ndx = (type == col_type_BackLink) ? m_spec.get_column_count() : m_spec.get_public_column_count();
937,575✔
1064

484,440✔
1065
    if (!col_key) {
982,338✔
1066
        col_key = generate_col_key(type, {});
88,557✔
1067
    }
88,557✔
1068

484,440✔
1069
    m_spec.insert_column(spec_ndx, col_key, type, name, col_key.get_attrs().m_value); // Throws
982,338✔
1070
    if (col_key.is_dictionary()) {
982,338✔
1071
        m_spec.set_dictionary_key_type(spec_ndx, key_type);
53,562✔
1072
    }
53,562✔
1073
    auto col_ndx = col_key.get_index().val;
982,338✔
1074
    build_column_mapping();
982,338✔
1075
    REALM_ASSERT(col_ndx <= m_index_refs.size());
982,338✔
1076
    if (col_ndx == m_index_refs.size()) {
982,338✔
1077
        m_index_refs.insert(col_ndx, 0);
982,080✔
1078
    }
982,080✔
1079
    else {
258✔
1080
        m_index_refs.set(col_ndx, 0);
258✔
1081
    }
258✔
1082
    REALM_ASSERT(col_ndx <= m_opposite_table.size());
982,338✔
1083
    if (col_ndx == m_opposite_table.size()) {
982,338✔
1084
        // m_opposite_table and m_opposite_column are always resized together!
484,305✔
1085
        m_opposite_table.insert(col_ndx, TableKey().value);
982,074✔
1086
        m_opposite_column.insert(col_ndx, ColKey().value);
982,074✔
1087
    }
982,074✔
1088
    else {
264✔
1089
        m_opposite_table.set(col_ndx, TableKey().value);
264✔
1090
        m_opposite_column.set(col_ndx, ColKey().value);
264✔
1091
    }
264✔
1092
    refresh_index_accessors();
982,338✔
1093
    m_clusters.insert_column(col_key);
982,338✔
1094
    if (m_tombstones) {
982,338✔
1095
        m_tombstones->insert_column(col_key);
6,522✔
1096
    }
6,522✔
1097

484,440✔
1098
    bump_storage_version();
982,338✔
1099

484,440✔
1100
    return col_key;
982,338✔
1101
}
982,338✔
1102

1103

1104
void Table::do_erase_root_column(ColKey col_key)
1105
{
17,730✔
1106
    size_t col_ndx = col_key.get_index().val;
17,730✔
1107
    // If the column had a source index we have to remove and destroy that as well
8,721✔
1108
    ref_type index_ref = m_index_refs.get_as_ref(col_ndx);
17,730✔
1109
    if (index_ref) {
17,730✔
1110
        Array::destroy_deep(index_ref, m_index_refs.get_alloc());
207✔
1111
        m_index_refs.set(col_ndx, 0);
207✔
1112
        m_index_accessors[col_ndx].reset();
207✔
1113
    }
207✔
1114
    m_opposite_table.set(col_ndx, TableKey().value);
17,730✔
1115
    m_opposite_column.set(col_ndx, ColKey().value);
17,730✔
1116
    m_index_accessors[col_ndx] = nullptr;
17,730✔
1117
    m_clusters.remove_column(col_key);
17,730✔
1118
    if (m_tombstones)
17,730✔
1119
        m_tombstones->remove_column(col_key);
5,655✔
1120
    size_t spec_ndx = colkey2spec_ndx(col_key);
17,730✔
1121
    m_spec.erase_column(spec_ndx);
17,730✔
1122
    m_top.adjust(top_position_for_column_key, 2);
17,730✔
1123

8,721✔
1124
    build_column_mapping();
17,730✔
1125
    while (m_index_accessors.size() > m_leaf_ndx2colkey.size()) {
34,887✔
1126
        REALM_ASSERT(m_index_accessors.back() == nullptr);
17,157✔
1127
        m_index_accessors.pop_back();
17,157✔
1128
    }
17,157✔
1129
    bump_content_version();
17,730✔
1130
    bump_storage_version();
17,730✔
1131
}
17,730✔
1132

1133
Query Table::where(const DictionaryLinkValues& dictionary_of_links) const
1134
{
1,524✔
1135
    return Query(m_own_ref, dictionary_of_links);
1,524✔
1136
}
1,524✔
1137

1138
void Table::set_table_type(Type table_type, bool handle_backlinks)
1139
{
312✔
1140
    if (table_type == m_table_type) {
312✔
1141
        return;
×
1142
    }
×
1143

156✔
1144
    if (m_table_type == Type::TopLevelAsymmetric || table_type == Type::TopLevelAsymmetric) {
312✔
1145
        throw LogicError(ErrorCodes::MigrationFailed, util::format("Cannot change '%1' from %2 to %3",
×
1146
                                                                   get_class_name(), m_table_type, table_type));
×
1147
    }
×
1148

156✔
1149
    REALM_ASSERT_EX(table_type == Type::TopLevel || table_type == Type::Embedded, table_type);
312✔
1150
    set_embedded(table_type == Type::Embedded, handle_backlinks);
312✔
1151
}
312✔
1152

1153
void Table::set_embedded(bool embedded, bool handle_backlinks)
1154
{
312✔
1155
    if (embedded == false) {
312✔
1156
        do_set_table_type(Type::TopLevel);
24✔
1157
        return;
24✔
1158
    }
24✔
1159

144✔
1160
    // Embedded objects cannot have a primary key.
144✔
1161
    if (get_primary_key_column()) {
288✔
1162
        throw IllegalOperation(
6✔
1163
            util::format("Cannot change '%1' to embedded when using a primary key.", get_class_name()));
6✔
1164
    }
6✔
1165

141✔
1166
    if (size() == 0) {
282✔
1167
        do_set_table_type(Type::Embedded);
42✔
1168
        return;
42✔
1169
    }
42✔
1170

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

237✔
1187
        for_each_backlink_column([&](ColKey col) {
606✔
1188
            cluster->init_leaf(col, &leaf);
606✔
1189
            // Width zero means all the values are zero and there can't be any backlinks
303✔
1190
            if (leaf.get_width() == 0) {
606✔
1191
                return IteratorControl::AdvanceToNext;
36✔
1192
            }
36✔
1193

285✔
1194
            for (size_t i = 0, size = leaf.size(); i < size; ++i) {
60,816✔
1195
                auto value = leaf.get_as_ref_or_tagged(i);
60,300✔
1196
                if (value.is_ref() && value.get_as_ref() == 0) {
60,300✔
1197
                    // ref of zero means there's no backlinks
29,670✔
1198
                    continue;
59,340✔
1199
                }
59,340✔
1200

480✔
1201
                if (value.is_ref()) {
960✔
1202
                    // Any other ref indicates an array of backlinks, which will
39✔
1203
                    // always have more than one entry
39✔
1204
                    incoming_link_count[i] = LinkCount::Multiple;
78✔
1205
                }
78✔
1206
                else {
882✔
1207
                    // Otherwise it's a tagged ref to the single linking object
441✔
1208
                    if (incoming_link_count[i] == LinkCount::None) {
882✔
1209
                        incoming_link_count[i] = LinkCount::One;
792✔
1210
                    }
792✔
1211
                    else if (incoming_link_count[i] == LinkCount::One) {
90✔
1212
                        incoming_link_count[i] = LinkCount::Multiple;
42✔
1213
                    }
42✔
1214
                }
882✔
1215

480✔
1216
                auto source_col = get_opposite_column(col);
960✔
1217
                if (source_col.get_type() == col_type_Mixed) {
960✔
1218
                    auto source_table = get_opposite_table(col);
54✔
1219
                    throw IllegalOperation(util::format(
54✔
1220
                        "Cannot convert '%1' to embedded: there is an incoming link from the Mixed property '%2.%3', "
54✔
1221
                        "which does not support linking to embedded objects.",
54✔
1222
                        get_class_name(), source_table->get_class_name(), source_table->get_column_name(source_col)));
54✔
1223
                }
54✔
1224
            }
960✔
1225
            return IteratorControl::AdvanceToNext;
543✔
1226
        });
570✔
1227

237✔
1228
        for (size_t i = 0; i < size; ++i) {
60,660✔
1229
            if (incoming_link_count[i] == LinkCount::None) {
60,240✔
1230
                if (!handle_backlinks) {
59,424✔
1231
                    throw IllegalOperation(util::format("Cannot convert '%1' to embedded: at least one object has no "
18✔
1232
                                                        "incoming links and would be deleted.",
18✔
1233
                                                        get_class_name()));
18✔
1234
                }
18✔
1235
                orphans.push_back(cluster->get_real_key(i));
59,406✔
1236
            }
59,406✔
1237
            else if (incoming_link_count[i] == LinkCount::Multiple) {
816✔
1238
                if (!handle_backlinks) {
90✔
1239
                    throw IllegalOperation(util::format(
36✔
1240
                        "Cannot convert '%1' to embedded: at least one object has more than one incoming link.",
36✔
1241
                        get_class_name()));
36✔
1242
                }
36✔
1243
                multiple_incoming_links.push_back(cluster->get_real_key(i));
54✔
1244
            }
54✔
1245
        }
60,240✔
1246

237✔
1247
        return IteratorControl::AdvanceToNext;
447✔
1248
    });
474✔
1249

120✔
1250
    // orphans and multiple_incoming_links will always be empty if `handle_backlinks = false`
120✔
1251
    for (auto key : orphans) {
59,406✔
1252
        remove_object(key);
59,406✔
1253
    }
59,406✔
1254
    for (auto key : multiple_incoming_links) {
147✔
1255
        auto obj = get_object(key);
54✔
1256
        obj.handle_multiple_backlinks_during_schema_migration();
54✔
1257
        obj.remove();
54✔
1258
    }
54✔
1259

120✔
1260
    do_set_table_type(Type::Embedded);
240✔
1261
}
240✔
1262

1263
void Table::do_set_table_type(Type table_type)
1264
{
336,975✔
1265
    while (m_top.size() <= top_position_for_flags)
336,975✔
1266
        m_top.add(0);
×
1267

167,181✔
1268
    uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
336,975✔
1269
    // reset bits 0-1
167,181✔
1270
    flags &= ~table_type_mask;
336,975✔
1271
    // set table type
167,181✔
1272
    flags |= static_cast<uint8_t>(table_type);
336,975✔
1273
    m_top.set(top_position_for_flags, RefOrTagged::make_tagged(flags));
336,975✔
1274
    m_table_type = table_type;
336,975✔
1275
}
336,975✔
1276

1277

1278
void Table::detach(LifeCycleCookie cookie) noexcept
1279
{
4,969,428✔
1280
    m_cookie = cookie;
4,969,428✔
1281
    m_alloc.bump_instance_version();
4,969,428✔
1282
}
4,969,428✔
1283

1284
void Table::fully_detach() noexcept
1285
{
4,949,493✔
1286
    m_spec.detach();
4,949,493✔
1287
    m_top.detach();
4,949,493✔
1288
    m_index_refs.detach();
4,949,493✔
1289
    m_opposite_table.detach();
4,949,493✔
1290
    m_opposite_column.detach();
4,949,493✔
1291
    m_index_accessors.clear();
4,949,493✔
1292
}
4,949,493✔
1293

1294

1295
Table::~Table() noexcept
1296
{
3,558✔
1297
    if (m_top.is_attached()) {
3,558✔
1298
        // If destroyed as a standalone table, destroy all memory allocated
1,779✔
1299
        if (m_top.get_parent() == nullptr) {
3,558✔
1300
            m_top.destroy_deep();
3,558✔
1301
        }
3,558✔
1302
        fully_detach();
3,558✔
1303
    }
3,558✔
1304
    else {
×
1305
        REALM_ASSERT(m_index_accessors.size() == 0);
×
1306
    }
×
1307
    m_cookie = cookie_deleted;
3,558✔
1308
}
3,558✔
1309

1310

1311
IndexType Table::search_index_type(ColKey col_key) const noexcept
1312
{
8,063,970✔
1313
    if (auto index = m_index_accessors[col_key.get_index().val].get()) {
8,063,970✔
1314
        return index->is_fulltext_index() ? IndexType::Fulltext : IndexType::General;
1,160,445✔
1315
    }
1,160,655✔
1316
    return IndexType::None;
6,903,315✔
1317
}
6,903,315✔
1318

1319
void Table::migrate_column_info()
1320
{
336✔
1321
    bool changes = false;
336✔
1322
    TableKey tk = (get_name() == "pk") ? TableKey(0) : get_key();
309✔
1323
    changes |= m_spec.convert_column_attributes();
336✔
1324
    changes |= m_spec.convert_column_keys(tk);
336✔
1325

168✔
1326
    if (changes) {
336✔
1327
        build_column_mapping();
60✔
1328
    }
60✔
1329
}
336✔
1330

1331
bool Table::verify_column_keys()
1332
{
282✔
1333
    size_t nb_public_columns = m_spec.get_public_column_count();
282✔
1334
    size_t nb_columns = m_spec.get_column_count();
282✔
1335
    bool modified = false;
282✔
1336

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

141✔
1359
    if (!check()) {
282✔
1360
        m_spec.fix_column_keys(get_key());
6✔
1361
        build_column_mapping();
6✔
1362
        refresh_index_accessors();
6✔
1363
        REALM_ASSERT_RELEASE(check());
6✔
1364
        modified = true;
6✔
1365
    }
6✔
1366
    return modified;
282✔
1367
}
282✔
1368

1369
// Delete the indexes stored in the columns array and create corresponding
1370
// entries in m_index_accessors array. This also has the effect that the columns
1371
// array after this step does not have extra entries for certain columns
1372
void Table::migrate_indexes(ColKey pk_col_key)
1373
{
336✔
1374
    if (ref_type top_ref = m_top.get_as_ref(top_position_for_columns)) {
336✔
1375
        Array col_refs(m_alloc);
246✔
1376
        col_refs.set_parent(&m_top, top_position_for_columns);
246✔
1377
        col_refs.init_from_ref(top_ref);
246✔
1378
        auto col_count = m_spec.get_column_count();
246✔
1379
        size_t col_ndx = 0;
246✔
1380

123✔
1381
        // If col_refs.size() equals col_count, there are no indexes to migrate
123✔
1382
        while (col_ndx < col_count && col_refs.size() > col_count) {
468✔
1383
            if (m_spec.get_column_attr(col_ndx).test(col_attr_Indexed) && !m_index_refs.get(col_ndx)) {
222✔
1384
                // Simply delete entry. This will have the effect that we will not have to take
72✔
1385
                // extra entries into account
72✔
1386
                auto old_index_ref = to_ref(col_refs.get(col_ndx + 1));
144✔
1387
                col_refs.erase(col_ndx + 1);
144✔
1388
                if (old_index_ref) {
144✔
1389
                    // It should not be possible for old_index_ref to be 0, but we have seen some error
72✔
1390
                    // reports on freeing a null ref, so just to be sure ...
72✔
1391
                    Array::destroy_deep(old_index_ref, m_alloc);
144✔
1392
                }
144✔
1393

72✔
1394
                // Primary key columns does not need an index
72✔
1395
                if (m_leaf_ndx2colkey[col_ndx] != pk_col_key) {
144✔
1396
                    // Otherwise create new index. Will be updated when objects are created
45✔
1397
                    m_index_accessors[col_ndx] = std::make_unique<StringIndex>(
90✔
1398
                        ClusterColumn(&m_clusters, m_spec.get_key(col_ndx), IndexType::General),
90✔
1399
                        get_alloc()); // Throws
90✔
1400
                    auto index = m_index_accessors[col_ndx].get();
90✔
1401
                    index->set_parent(&m_index_refs, col_ndx);
90✔
1402
                    m_index_refs.set(col_ndx, index->get_ref());
90✔
1403
                }
90✔
1404
            }
144✔
1405
            col_ndx++;
222✔
1406
        };
222✔
1407
    }
246✔
1408
}
336✔
1409

1410
// Move information held in the subspec area into the structures managed by Table
1411
// This is information about origin/target tables in relation to links
1412
// This information is now held in "opposite" arrays directly in Table structure
1413
// At the same time the backlink columns are destroyed
1414
// If there is no subspec, this stage is done
1415
void Table::migrate_subspec()
1416
{
282✔
1417
    if (!m_spec.has_subspec())
282✔
1418
        return;
210✔
1419

36✔
1420
    ref_type top_ref = m_top.get_as_ref(top_position_for_columns);
72✔
1421
    Array col_refs(m_alloc);
72✔
1422
    col_refs.set_parent(&m_top, top_position_for_columns);
72✔
1423
    col_refs.init_from_ref(top_ref);
72✔
1424
    Group* group = get_parent_group();
72✔
1425

36✔
1426
    for (size_t col_ndx = 0; col_ndx < m_spec.get_column_count(); col_ndx++) {
516✔
1427
        ColumnType col_type = m_spec.get_column_type(col_ndx);
444✔
1428

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

1464
namespace {
1465

1466
class LegacyStringColumn : public BPlusTree<StringData> {
1467
public:
1468
    LegacyStringColumn(Allocator& alloc, Spec* spec, size_t col_ndx, bool nullable)
1469
        : BPlusTree(alloc)
1470
        , m_spec(spec)
1471
        , m_col_ndx(col_ndx)
1472
        , m_nullable(nullable)
1473
    {
300✔
1474
    }
300✔
1475

1476
    std::unique_ptr<BPlusTreeLeaf> init_leaf_node(ref_type ref) override
1477
    {
300✔
1478
        auto leaf = std::make_unique<LeafNode>(this);
300✔
1479
        leaf->ArrayString::set_spec(m_spec, m_col_ndx);
300✔
1480
        leaf->set_nullability(m_nullable);
300✔
1481
        leaf->init_from_ref(ref);
300✔
1482
        return leaf;
300✔
1483
    }
300✔
1484

1485
    StringData get_legacy(size_t n) const
1486
    {
6,648✔
1487
        if (m_cached_leaf_begin <= n && n < m_cached_leaf_end) {
6,648!
1488
            return m_leaf_cache.get_legacy(n - m_cached_leaf_begin);
×
1489
        }
×
1490
        else {
6,648✔
1491
            StringData value;
6,648✔
1492

3,324✔
1493
            auto func = [&value](BPlusTreeNode* node, size_t ndx) {
6,648✔
1494
                auto leaf = static_cast<LeafNode*>(node);
6,648✔
1495
                value = leaf->get_legacy(ndx);
6,648✔
1496
            };
6,648✔
1497

3,324✔
1498
            m_root->bptree_access(n, func);
6,648✔
1499

3,324✔
1500
            return value;
6,648✔
1501
        }
6,648✔
1502
    }
6,648✔
1503

1504
private:
1505
    Spec* m_spec;
1506
    size_t m_col_ndx;
1507
    bool m_nullable;
1508
};
1509

1510
// We need an accessor that can read old Timestamp columns.
1511
// The new BPlusTree<Timestamp> uses a different layout
1512
class LegacyTS : private Array {
1513
public:
1514
    explicit LegacyTS(Allocator& allocator)
1515
        : Array(allocator)
1516
        , m_seconds(allocator)
1517
        , m_nanoseconds(allocator)
1518
    {
18✔
1519
        m_seconds.set_parent(this, 0);
18✔
1520
        m_nanoseconds.set_parent(this, 1);
18✔
1521
    }
18✔
1522

1523
    using Array::set_parent;
1524

1525
    void init_from_parent()
1526
    {
18✔
1527
        Array::init_from_parent();
18✔
1528
        m_seconds.init_from_parent();
18✔
1529
        m_nanoseconds.init_from_parent();
18✔
1530
    }
18✔
1531

1532
    size_t size() const
1533
    {
18✔
1534
        return m_seconds.size();
18✔
1535
    }
18✔
1536

1537
    Timestamp get(size_t ndx) const
1538
    {
3,078✔
1539
        util::Optional<int64_t> seconds = m_seconds.get(ndx);
3,078✔
1540
        return seconds ? Timestamp(*seconds, int32_t(m_nanoseconds.get(ndx))) : Timestamp{};
3,060✔
1541
    }
3,078✔
1542

1543
private:
1544
    BPlusTree<util::Optional<Int>> m_seconds;
1545
    BPlusTree<Int> m_nanoseconds;
1546
};
1547

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

1588
template <class T>
1589
void copy_list(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1590
{
6,012✔
1591
    if (sub_table_ref) {
6,012!
1592
        // Actual list is in the columns array position 0
36✔
1593
        Array cols(alloc);
72✔
1594
        cols.init_from_ref(sub_table_ref);
72✔
1595
        ref_type list_ref = cols.get_as_ref(0);
72✔
1596
        BPlusTree<T> from_list(alloc);
72✔
1597
        from_list.init_from_ref(list_ref);
72✔
1598
        size_t list_size = from_list.size();
72✔
1599
        auto l = obj.get_list<T>(col);
72✔
1600
        for (size_t j = 0; j < list_size; j++) {
1,740!
1601
            l.add(from_list.get(j));
1,668✔
1602
        }
1,668✔
1603
    }
72✔
1604
}
6,012✔
1605

1606
template <>
1607
void copy_list<util::Optional<Bool>>(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1608
{
×
1609
    if (sub_table_ref) {
×
1610
        // Actual list is in the columns array position 0
1611
        Array cols(alloc);
×
1612
        cols.init_from_ref(sub_table_ref);
×
1613
        BPlusTree<util::Optional<Int>> from_list(alloc);
×
1614
        from_list.set_parent(&cols, 0);
×
1615
        from_list.init_from_parent();
×
1616
        size_t list_size = from_list.size();
×
1617
        auto l = obj.get_list<util::Optional<Bool>>(col);
×
1618
        for (size_t j = 0; j < list_size; j++) {
×
1619
            util::Optional<Bool> val;
×
1620
            auto int_val = from_list.get(j);
×
1621
            if (int_val) {
×
1622
                val = (*int_val != 0);
×
1623
            }
×
1624
            l.add(val);
×
1625
        }
×
1626
    }
×
1627
}
×
1628

1629
template <>
1630
void copy_list<String>(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1631
{
276✔
1632
    if (sub_table_ref) {
276✔
1633
        // Actual list is in the columns array position 0
63✔
1634
        bool nullable = col.get_attrs().test(col_attr_Nullable);
126✔
1635
        Array cols(alloc);
126✔
1636
        cols.init_from_ref(sub_table_ref);
126✔
1637
        LegacyStringColumn from_list(alloc, nullptr, 0, nullable); // List of strings cannot be enumerated
126✔
1638
        from_list.set_parent(&cols, 0);
126✔
1639
        from_list.init_from_parent();
126✔
1640
        size_t list_size = from_list.size();
126✔
1641
        auto l = obj.get_list<String>(col);
126✔
1642
        for (size_t j = 0; j < list_size; j++) {
396✔
1643
            l.add(from_list.get_legacy(j));
270✔
1644
        }
270✔
1645
    }
126✔
1646
}
276✔
1647

1648
template <>
1649
void copy_list<Timestamp>(ref_type sub_table_ref, Obj& obj, ColKey col, Allocator& alloc)
1650
{
×
1651
    if (sub_table_ref) {
×
1652
        // Actual list is in the columns array position 0
1653
        Array cols(alloc);
×
1654
        cols.init_from_ref(sub_table_ref);
×
1655
        LegacyTS from_list(alloc);
×
1656
        from_list.set_parent(&cols, 0);
×
1657
        from_list.init_from_parent();
×
1658
        size_t list_size = from_list.size();
×
1659
        auto l = obj.get_list<Timestamp>(col);
×
1660
        for (size_t j = 0; j < list_size; j++) {
×
1661
            l.add(from_list.get(j));
×
1662
        }
×
1663
    }
×
1664
}
×
1665

1666
} // namespace
1667

1668
void Table::create_columns()
1669
{
336✔
1670
    size_t cnt;
336✔
1671
    auto get_column_cnt = [&cnt](const Cluster* cluster) {
336✔
1672
        cnt = cluster->nb_columns();
336✔
1673
        return IteratorControl::Stop;
336✔
1674
    };
336✔
1675
    traverse_clusters(get_column_cnt);
336✔
1676

168✔
1677
    size_t column_count = m_spec.get_column_count();
336✔
1678
    if (cnt != column_count) {
336✔
1679
        for (size_t col_ndx = 0; col_ndx < column_count; col_ndx++) {
846✔
1680
            m_clusters.insert_column(m_spec.get_key(col_ndx));
672✔
1681
        }
672✔
1682
    }
174✔
1683
}
336✔
1684

1685
bool Table::migrate_objects()
1686
{
336✔
1687
    size_t nb_public_columns = m_spec.get_public_column_count();
336✔
1688
    size_t nb_columns = m_spec.get_column_count();
336✔
1689
    if (!nb_columns) {
336✔
1690
        // No columns - this means no objects
12✔
1691
        return true;
24✔
1692
    }
24✔
1693

156✔
1694
    ref_type top_ref = m_top.get_as_ref(top_position_for_columns);
312✔
1695
    if (!top_ref) {
312✔
1696
        // Has already been done
45✔
1697
        return true;
90✔
1698
    }
90✔
1699
    Array col_refs(m_alloc);
222✔
1700
    col_refs.set_parent(&m_top, top_position_for_columns);
222✔
1701
    col_refs.init_from_ref(top_ref);
222✔
1702

111✔
1703
    /************************ Create column accessors ************************/
111✔
1704

111✔
1705
    std::map<ColKey, std::unique_ptr<BPlusTreeBase>> column_accessors;
222✔
1706
    std::map<ColKey, std::unique_ptr<LegacyTS>> ts_accessors;
222✔
1707
    std::map<ColKey, std::unique_ptr<BPlusTree<int64_t>>> list_accessors;
222✔
1708
    std::vector<size_t> cols_to_destroy;
222✔
1709
    bool has_link_columns = false;
222✔
1710

111✔
1711
    // helper function to determine the number of objects in the table
111✔
1712
    size_t number_of_objects = (nb_columns == 0) ? 0 : size_t(-1);
222✔
1713
    auto update_size = [&number_of_objects](size_t s) {
792✔
1714
        if (number_of_objects == size_t(-1)) {
792✔
1715
            number_of_objects = s;
222✔
1716
        }
222✔
1717
        else {
570✔
1718
            REALM_ASSERT(s == number_of_objects);
570✔
1719
        }
570✔
1720
    };
792✔
1721

111✔
1722
    for (size_t col_ndx = 0; col_ndx < nb_columns; col_ndx++) {
1,062✔
1723
        if (col_ndx < nb_public_columns && m_spec.get_column_name(col_ndx) == "!ROW_INDEX") {
840✔
1724
            // If this column has been added, we can break here
1725
            break;
×
1726
        }
×
1727

420✔
1728
        ColKey col_key = m_spec.get_key(col_ndx);
840✔
1729
        ColumnAttrMask attr = m_spec.get_column_attr(col_ndx);
840✔
1730
        ColumnType col_type = m_spec.get_column_type(col_ndx);
840✔
1731
        bool nullable = attr.test(col_attr_Nullable);
840✔
1732
        std::unique_ptr<BPlusTreeBase> acc;
840✔
1733
        std::unique_ptr<LegacyTS> ts_acc;
840✔
1734
        std::unique_ptr<BPlusTree<int64_t>> list_acc;
840✔
1735

420✔
1736
        if (!(col_ndx < col_refs.size())) {
840✔
1737
            throw RuntimeError(ErrorCodes::BrokenInvariant,
×
1738
                               util::format("Objects in '%1' corrupted by previous upgrade attempt", get_name()));
×
1739
        }
×
1740

420✔
1741
        if (!col_refs.get(col_ndx)) {
840✔
1742
            // This column has been migrated
24✔
1743
            continue;
48✔
1744
        }
48✔
1745

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

396✔
1798
        if (acc) {
792✔
1799
            acc->set_parent(&col_refs, col_ndx);
522✔
1800
            acc->init_from_parent();
522✔
1801
            update_size(acc->size());
522✔
1802
            column_accessors.emplace(col_key, std::move(acc));
522✔
1803
            cols_to_destroy.push_back(col_ndx);
522✔
1804
        }
522✔
1805
        if (ts_acc) {
792✔
1806
            ts_acc->set_parent(&col_refs, col_ndx);
18✔
1807
            ts_acc->init_from_parent();
18✔
1808
            update_size(ts_acc->size());
18✔
1809
            ts_accessors.emplace(col_key, std::move(ts_acc));
18✔
1810
            cols_to_destroy.push_back(col_ndx);
18✔
1811
        }
18✔
1812
        if (list_acc) {
792✔
1813
            list_acc->set_parent(&col_refs, col_ndx);
60✔
1814
            list_acc->init_from_parent();
60✔
1815
            update_size(list_acc->size());
60✔
1816
            list_accessors.emplace(col_key, std::move(list_acc));
60✔
1817
            cols_to_destroy.push_back(col_ndx);
60✔
1818
        }
60✔
1819
    }
792✔
1820

111✔
1821
    REALM_ASSERT(number_of_objects != size_t(-1));
222✔
1822

111✔
1823
    if (m_clusters.size() == number_of_objects) {
222✔
1824
        // We have migrated all objects
33✔
1825
        return !has_link_columns;
66✔
1826
    }
66✔
1827

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

78✔
1832
    /*************************** Create objects ******************************/
78✔
1833

78✔
1834
    for (size_t row_ndx = 0; row_ndx < number_of_objects; row_ndx++) {
3,654✔
1835
        // Build a vector of values obtained from the old columns
1,749✔
1836
        FieldValues init_values;
3,498✔
1837
        for (auto& it : column_accessors) {
28,200✔
1838
            auto col_key = it.first;
28,200✔
1839
            auto col_type = col_key.get_type();
28,200✔
1840
            auto nullable = col_key.get_attrs().test(col_attr_Nullable);
28,200✔
1841
            auto val = get_val_from_column(row_ndx, col_type, nullable, it.second.get());
28,200✔
1842
            init_values.insert(col_key, val);
28,200✔
1843
        }
28,200✔
1844
        for (auto& it : ts_accessors) {
3,288✔
1845
            init_values.insert(it.first, Mixed(it.second->get(row_ndx)));
3,078✔
1846
        }
3,078✔
1847

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

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

78✔
1893
    // Destroy values in the old columns that has been copied.
78✔
1894
    // This frees up space in the file
78✔
1895
    for (auto ndx : cols_to_destroy) {
516✔
1896
        Array::destroy_deep(to_ref(col_refs.get(ndx)), m_alloc);
516✔
1897
        col_refs.set(ndx, 0);
516✔
1898
    }
516✔
1899

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

78✔
1904
#if 0
1905
    if (fastrand(100) < 20) {
1906
        throw std::runtime_error("Upgrade interrupted"); // Can be used for testing
1907
    }
1908
#endif
1909
    return !has_link_columns;
156✔
1910
}
156✔
1911

1912
void Table::migrate_links()
1913
{
60✔
1914
    ref_type top_ref = m_top.get_as_ref(top_position_for_columns);
60✔
1915
    if (!top_ref) {
60✔
1916
        // All objects migrated
1917
        return;
×
1918
    }
×
1919

30✔
1920
    Array col_refs(m_alloc);
60✔
1921
    col_refs.set_parent(&m_top, top_position_for_columns);
60✔
1922
    col_refs.init_from_ref(top_ref);
60✔
1923

30✔
1924
    // Cache column accessors and other information
30✔
1925
    size_t nb_columns = m_spec.get_public_column_count();
60✔
1926
    std::vector<std::unique_ptr<BPlusTree<Int>>> link_column_accessors(nb_columns);
60✔
1927
    std::vector<ColKey> col_keys(nb_columns);
60✔
1928
    std::vector<ColumnType> col_types(nb_columns);
60✔
1929
    std::vector<Table*> target_tables(nb_columns);
60✔
1930
    std::vector<ColKey> opposite_orig_row_ndx_col(nb_columns);
60✔
1931
    for (size_t col_ndx = 0; col_ndx < nb_columns; col_ndx++) {
414✔
1932
        ColumnType col_type = m_spec.get_column_type(col_ndx);
354✔
1933

177✔
1934
        if (is_link_type(col_type)) {
354✔
1935
            link_column_accessors[col_ndx] = std::make_unique<BPlusTree<int64_t>>(m_alloc);
120✔
1936
            link_column_accessors[col_ndx]->set_parent(&col_refs, col_ndx);
120✔
1937
            link_column_accessors[col_ndx]->init_from_parent();
120✔
1938
            col_keys[col_ndx] = m_spec.get_key(col_ndx);
120✔
1939
            col_types[col_ndx] = col_type;
120✔
1940
            target_tables[col_ndx] = get_opposite_table(col_keys[col_ndx]).unchecked_ptr();
120✔
1941
            opposite_orig_row_ndx_col[col_ndx] = target_tables[col_ndx]->get_column_key("!ROW_INDEX");
120✔
1942
        }
120✔
1943
    }
354✔
1944

30✔
1945
    auto orig_row_ndx_col_key = get_column_key("!ROW_INDEX");
60✔
1946
    for (auto obj : *this) {
3,186✔
1947
        for (size_t col_ndx = 0; col_ndx < nb_columns; col_ndx++) {
46,314✔
1948
            if (col_keys[col_ndx]) {
43,128✔
1949
                // If no !ROW_INDEX column is found, the original row index number is
3,186✔
1950
                // equal to the ObjKey value
3,186✔
1951
                size_t orig_row_ndx =
6,372✔
1952
                    size_t(orig_row_ndx_col_key ? obj.get<Int>(orig_row_ndx_col_key) : obj.get_key().value);
6,372✔
1953
                // Get original link value
3,186✔
1954
                int64_t link_val = link_column_accessors[col_ndx]->get(orig_row_ndx);
6,372✔
1955

3,186✔
1956
                Table* target_table = target_tables[col_ndx];
6,372✔
1957
                ColKey search_col = opposite_orig_row_ndx_col[col_ndx];
6,372✔
1958
                auto get_target_key = [target_table, search_col](int64_t orig_link_val) -> ObjKey {
3,444✔
1959
                    if (search_col)
516✔
1960
                        return target_table->find_first_int(search_col, orig_link_val);
36✔
1961
                    else
480✔
1962
                        return ObjKey(orig_link_val);
480✔
1963
                };
516✔
1964

3,186✔
1965
                if (link_val) {
6,372✔
1966
                    if (col_types[col_ndx] == col_type_Link) {
240✔
1967
                        obj.set(col_keys[col_ndx], get_target_key(link_val - 1));
138✔
1968
                    }
138✔
1969
                    else {
102✔
1970
                        auto ll = obj.get_linklist(col_keys[col_ndx]);
102✔
1971
                        BPlusTree<Int> links(m_alloc);
102✔
1972
                        links.init_from_ref(ref_type(link_val));
102✔
1973
                        size_t nb_links = links.size();
102✔
1974
                        for (size_t j = 0; j < nb_links; j++) {
480✔
1975
                            ll.add(get_target_key(links.get(j)));
378✔
1976
                        }
378✔
1977
                    }
102✔
1978
                }
240✔
1979
            }
6,372✔
1980
        }
43,128✔
1981
    }
3,186✔
1982
}
60✔
1983

1984
void Table::finalize_migration(ColKey pk_col_key)
1985
{
282✔
1986
    if (ref_type ref = m_top.get_as_ref(top_position_for_columns)) {
282✔
1987
        Array::destroy_deep(ref, m_alloc);
234✔
1988
        m_top.set(top_position_for_columns, 0);
234✔
1989
    }
234✔
1990

141✔
1991
    if (auto orig_row_ndx_col = get_column_key("!ROW_INDEX")) {
282✔
1992
        remove_column(orig_row_ndx_col);
18✔
1993
    }
18✔
1994

141✔
1995
    if (auto oid_col = get_column_key("!OID")) {
282✔
1996
        remove_column(oid_col);
×
1997
    }
×
1998

141✔
1999
    REALM_ASSERT_RELEASE(!pk_col_key || valid_column(pk_col_key));
282✔
2000
    do_set_primary_key_column(pk_col_key);
282✔
2001
}
282✔
2002

2003
void Table::migrate_sets_and_dictionaries()
2004
{
180✔
2005
    std::vector<ColKey> to_migrate;
180✔
2006
    for (auto col : get_column_keys()) {
570✔
2007
        if (col.is_dictionary() || (col.is_set() && col.get_type() == col_type_Mixed)) {
570✔
2008
            to_migrate.push_back(col);
12✔
2009
        }
12✔
2010
    }
570✔
2011
    if (to_migrate.size()) {
180✔
2012
        for (auto obj : *this) {
6✔
2013
            for (auto col : to_migrate) {
12✔
2014
                if (col.is_set()) {
12✔
2015
                    auto set = obj.get_set<Mixed>(col);
6✔
2016
                    set.migrate();
6✔
2017
                }
6✔
2018
                else if (col.is_dictionary()) {
6✔
2019
                    auto dict = obj.get_dictionary(col);
6✔
2020
                    dict.migrate();
6✔
2021
                }
6✔
2022
            }
12✔
2023
        }
6✔
2024
    }
6✔
2025
}
180✔
2026

2027
StringData Table::get_name() const noexcept
2028
{
2,919,033✔
2029
    const Array& real_top = m_top;
2,919,033✔
2030
    ArrayParent* parent = real_top.get_parent();
2,919,033✔
2031
    if (!parent)
2,919,033✔
2032
        return StringData("");
51✔
2033
    REALM_ASSERT(dynamic_cast<Group*>(parent));
2,918,982✔
2034
    return static_cast<Group*>(parent)->get_table_name(get_key());
2,918,982✔
2035
}
2,918,982✔
2036

2037
StringData Table::get_class_name() const noexcept
2038
{
14,952✔
2039
    return Group::table_name_to_class_name(get_name());
14,952✔
2040
}
14,952✔
2041

2042
const char* Table::get_state() const noexcept
2043
{
42✔
2044
    switch (m_cookie) {
42✔
2045
        case cookie_created:
✔
2046
            return "created";
×
2047
        case cookie_transaction_ended:
6✔
2048
            return "transaction_ended";
6✔
2049
        case cookie_initialized:
✔
2050
            return "initialised";
×
2051
        case cookie_removed:
36✔
2052
            return "removed";
36✔
2053
        case cookie_void:
✔
2054
            return "void";
×
2055
        case cookie_deleted:
✔
2056
            return "deleted";
×
2057
    }
×
2058
    return "";
×
2059
}
×
2060

2061

2062
bool Table::is_nullable(ColKey col_key) const
2063
{
2,017,893✔
2064
    REALM_ASSERT_DEBUG(valid_column(col_key));
2,017,893✔
2065
    return col_key.get_attrs().test(col_attr_Nullable);
2,017,893✔
2066
}
2,017,893✔
2067

2068
bool Table::is_list(ColKey col_key) const
2069
{
172,671✔
2070
    REALM_ASSERT_DEBUG(valid_column(col_key));
172,671✔
2071
    return col_key.get_attrs().test(col_attr_List);
172,671✔
2072
}
172,671✔
2073

2074

2075
ref_type Table::create_empty_table(Allocator& alloc, TableKey key)
2076
{
340,329✔
2077
    Array top(alloc);
340,329✔
2078
    _impl::DeepArrayDestroyGuard dg(&top);
340,329✔
2079
    top.create(Array::type_HasRefs); // Throws
340,329✔
2080
    _impl::DeepArrayRefDestroyGuard dg_2(alloc);
340,329✔
2081

168,855✔
2082
    {
340,329✔
2083
        MemRef mem = Spec::create_empty_spec(alloc); // Throws
340,329✔
2084
        dg_2.reset(mem.get_ref());
340,329✔
2085
        int_fast64_t v(from_ref(mem.get_ref()));
340,329✔
2086
        top.add(v); // Throws
340,329✔
2087
        dg_2.release();
340,329✔
2088
    }
340,329✔
2089
    top.add(0); // Old position for columns
340,329✔
2090
    {
340,329✔
2091
        MemRef mem = Cluster::create_empty_cluster(alloc); // Throws
340,329✔
2092
        dg_2.reset(mem.get_ref());
340,329✔
2093
        int_fast64_t v(from_ref(mem.get_ref()));
340,329✔
2094
        top.add(v); // Throws
340,329✔
2095
        dg_2.release();
340,329✔
2096
    }
340,329✔
2097

168,855✔
2098
    // Table key value
168,855✔
2099
    RefOrTagged rot = RefOrTagged::make_tagged(key.value);
340,329✔
2100
    top.add(rot);
340,329✔
2101

168,855✔
2102
    // Search indexes
168,855✔
2103
    {
340,329✔
2104
        bool context_flag = false;
340,329✔
2105
        MemRef mem = Array::create_empty_array(Array::type_HasRefs, context_flag, alloc); // Throws
340,329✔
2106
        dg_2.reset(mem.get_ref());
340,329✔
2107
        int_fast64_t v(from_ref(mem.get_ref()));
340,329✔
2108
        top.add(v); // Throws
340,329✔
2109
        dg_2.release();
340,329✔
2110
    }
340,329✔
2111
    rot = RefOrTagged::make_tagged(0);
340,329✔
2112
    top.add(rot); // Column key
340,329✔
2113
    top.add(rot); // Version
340,329✔
2114
    dg.release();
340,329✔
2115
    // Opposite keys (table and column)
168,855✔
2116
    {
340,329✔
2117
        bool context_flag = false;
340,329✔
2118
        {
340,329✔
2119
            MemRef mem = Array::create_empty_array(Array::type_Normal, context_flag, alloc); // Throws
340,329✔
2120
            dg_2.reset(mem.get_ref());
340,329✔
2121
            int_fast64_t v(from_ref(mem.get_ref()));
340,329✔
2122
            top.add(v); // Throws
340,329✔
2123
            dg_2.release();
340,329✔
2124
        }
340,329✔
2125
        {
340,329✔
2126
            MemRef mem = Array::create_empty_array(Array::type_Normal, context_flag, alloc); // Throws
340,329✔
2127
            dg_2.reset(mem.get_ref());
340,329✔
2128
            int_fast64_t v(from_ref(mem.get_ref()));
340,329✔
2129
            top.add(v); // Throws
340,329✔
2130
            dg_2.release();
340,329✔
2131
        }
340,329✔
2132
    }
340,329✔
2133
    top.add(0); // Sequence number
340,329✔
2134
    top.add(0); // Collision_map
340,329✔
2135
    top.add(0); // pk col key
340,329✔
2136
    top.add(0); // flags
340,329✔
2137
    top.add(0); // tombstones
340,329✔
2138

168,855✔
2139
    REALM_ASSERT(top.size() == top_array_size);
340,329✔
2140

168,855✔
2141
    return top.get_ref();
340,329✔
2142
}
340,329✔
2143

2144
void Table::ensure_graveyard()
2145
{
31,386✔
2146
    if (!m_tombstones) {
31,386✔
2147
        while (m_top.size() < top_position_for_tombstones)
9,861✔
2148
            m_top.add(0);
×
2149
        REALM_ASSERT(!m_top.get(top_position_for_tombstones));
9,861✔
2150
        MemRef mem = Cluster::create_empty_cluster(m_alloc);
9,861✔
2151
        m_top.set_as_ref(top_position_for_tombstones, mem.get_ref());
9,861✔
2152
        m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
9,861✔
2153
        m_tombstones->init_from_parent();
9,861✔
2154
        for_each_and_every_column([ts = m_tombstones.get()](ColKey col) {
24,252✔
2155
            ts->insert_column(col);
24,252✔
2156
            return IteratorControl::AdvanceToNext;
24,252✔
2157
        });
24,252✔
2158
    }
9,861✔
2159
}
31,386✔
2160

2161
void Table::batch_erase_rows(const KeyColumn& keys)
2162
{
558✔
2163
    size_t num_objs = keys.size();
558✔
2164
    std::vector<ObjKey> vec;
558✔
2165
    vec.reserve(num_objs);
558✔
2166
    for (size_t i = 0; i < num_objs; ++i) {
2,898✔
2167
        ObjKey key = keys.get(i);
2,340✔
2168
        if (key != null_key && is_valid(key)) {
2,340✔
2169
            vec.push_back(key);
2,340✔
2170
        }
2,340✔
2171
    }
2,340✔
2172

279✔
2173
    sort(vec.begin(), vec.end());
558✔
2174
    vec.erase(unique(vec.begin(), vec.end()), vec.end());
558✔
2175

279✔
2176
    batch_erase_objects(vec);
558✔
2177
}
558✔
2178

2179
void Table::batch_erase_objects(std::vector<ObjKey>& keys)
2180
{
5,562✔
2181
    Group* g = get_parent_group();
5,562✔
2182
    bool maybe_has_incoming_links = g && !is_asymmetric();
5,562✔
2183

2,781✔
2184
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
5,562✔
2185
        CascadeState state(CascadeState::Mode::Strong, g);
4,794✔
2186
        std::for_each(keys.begin(), keys.end(), [this, &state](ObjKey k) {
3,285✔
2187
            state.m_to_be_deleted.emplace_back(m_key, k);
1,776✔
2188
        });
1,776✔
2189
        if (maybe_has_incoming_links)
4,794✔
2190
            nullify_links(state);
4,794✔
2191
        remove_recursive(state);
4,794✔
2192
    }
4,794✔
2193
    else {
768✔
2194
        CascadeState state(CascadeState::Mode::None, g);
768✔
2195
        for (auto k : keys) {
2,512,302✔
2196
            if (maybe_has_incoming_links) {
2,512,302✔
2197
                m_clusters.nullify_incoming_links(k, state);
2,512,224✔
2198
            }
2,512,224✔
2199
            m_clusters.erase(k, state);
2,512,302✔
2200
        }
2,512,302✔
2201
    }
768✔
2202
    keys.clear();
5,562✔
2203
}
5,562✔
2204

2205
void Table::clear()
2206
{
4,290✔
2207
    CascadeState state(CascadeState::Mode::Strong, get_parent_group());
4,290✔
2208
    m_clusters.clear(state);
4,290✔
2209
    free_collision_table();
4,290✔
2210
}
4,290✔
2211

2212

2213
Group* Table::get_parent_group() const noexcept
2214
{
60,962,643✔
2215
    if (!m_top.is_attached())
60,962,643✔
2216
        return 0;                             // Subtable with shared descriptor
×
2217
    ArrayParent* parent = m_top.get_parent(); // ArrayParent guaranteed to be Table::Parent
60,962,643✔
2218
    if (!parent)
60,962,643✔
2219
        return 0; // Free-standing table
26,142,513✔
2220

17,602,308✔
2221
    return static_cast<Group*>(parent);
34,820,130✔
2222
}
34,820,130✔
2223

2224
inline uint64_t Table::get_sync_file_id() const noexcept
2225
{
39,201,627✔
2226
    Group* g = get_parent_group();
39,201,627✔
2227
    return g ? g->get_sync_file_id() : 0;
32,573,064✔
2228
}
39,201,627✔
2229

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

2240
uint64_t Table::allocate_sequence_number()
2241
{
20,128,122✔
2242
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_sequence_number);
20,128,122✔
2243
    uint64_t sn = rot.is_tagged() ? rot.get_as_int() : 0;
20,001,819✔
2244
    rot = RefOrTagged::make_tagged(sn + 1);
20,128,122✔
2245
    m_top.set(top_position_for_sequence_number, rot);
20,128,122✔
2246

10,033,506✔
2247
    return sn;
20,128,122✔
2248
}
20,128,122✔
2249

2250
void Table::set_sequence_number(uint64_t seq)
2251
{
156✔
2252
    m_top.set(top_position_for_sequence_number, RefOrTagged::make_tagged(seq));
156✔
2253
}
156✔
2254

2255
void Table::set_collision_map(ref_type ref)
2256
{
×
2257
    m_top.set(top_position_for_collision_map, RefOrTagged::make_ref(ref));
×
2258
}
×
2259

2260
TableRef Table::get_link_target(ColKey col_key) noexcept
2261
{
310,377✔
2262
    return get_opposite_table(col_key);
310,377✔
2263
}
310,377✔
2264

2265
// count ----------------------------------------------
2266

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

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

9✔
2300
    traverse_clusters(f);
18✔
2301

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

2312
template <typename T>
2313
void Table::aggregate(QueryStateBase& st, ColKey column_key) const
2314
{
28,521✔
2315
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
28,521✔
2316
    LeafType leaf(get_alloc());
28,521✔
2317

14,250✔
2318
    auto f = [&leaf, column_key, &st](const Cluster* cluster) {
28,539✔
2319
        // direct aggregate on the leaf
14,259✔
2320
        cluster->init_leaf(column_key, &leaf);
28,539✔
2321
        st.m_key_offset = cluster->get_offset();
28,539✔
2322
        st.m_key_values = cluster->get_key_array();
28,539✔
2323
        st.set_payload_column(&leaf);
28,539✔
2324
        bool cont = true;
28,539✔
2325
        size_t sz = leaf.size();
28,539✔
2326
        for (size_t local_index = 0; cont && local_index < sz; local_index++) {
122,343✔
2327
            cont = st.match(local_index);
93,804✔
2328
        }
93,804✔
2329
        return IteratorControl::AdvanceToNext;
28,539✔
2330
    };
28,539✔
2331

14,250✔
2332
    traverse_clusters(f);
28,521✔
2333
}
28,521✔
2334

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

2344
std::optional<Mixed> Table::sum(ColKey col_key) const
2345
{
756✔
2346
    return AggregateHelper<Table>::sum(*this, *this, col_key);
756✔
2347
}
756✔
2348

2349
std::optional<Mixed> Table::avg(ColKey col_key, size_t* value_count) const
2350
{
822✔
2351
    return AggregateHelper<Table>::avg(*this, *this, col_key, value_count);
822✔
2352
}
822✔
2353

2354
std::optional<Mixed> Table::min(ColKey col_key, ObjKey* return_ndx) const
2355
{
1,170✔
2356
    return AggregateHelper<Table>::min(*this, *this, col_key, return_ndx);
1,170✔
2357
}
1,170✔
2358

2359
std::optional<Mixed> Table::max(ColKey col_key, ObjKey* return_ndx) const
2360
{
22,245✔
2361
    return AggregateHelper<Table>::max(*this, *this, col_key, return_ndx);
22,245✔
2362
}
22,245✔
2363

2364
template <class T>
2365
ObjKey Table::find_first(ColKey col_key, T value) const
2366
{
35,142✔
2367
    check_column(col_key);
35,142✔
2368

17,457✔
2369
    if (!col_key.is_nullable() && value_is_null(value)) {
35,142!
2370
        return {}; // this is a precaution/optimization
6✔
2371
    }
6✔
2372
    // You cannot call GetIndexData on ObjKey
17,454✔
2373
    if constexpr (!std::is_same_v<T, ObjKey>) {
35,136✔
2374
        if (StringIndex* index = get_search_index(col_key)) {
35,118!
2375
            return index->find_first(value);
27,270✔
2376
        }
27,270✔
2377
        if (col_key == m_primary_key_col) {
7,848!
2378
            return find_primary_key(value);
×
2379
        }
×
2380
    }
7,848✔
2381

3,924✔
2382
    ObjKey key;
7,848✔
2383
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
7,848✔
2384
    LeafType leaf(get_alloc());
7,848✔
2385

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

3,924✔
2396
    traverse_clusters(f);
7,848✔
2397

3,924✔
2398
    return key;
7,848✔
2399
}
7,848✔
2400

2401
namespace realm {
2402

2403
template <>
2404
ObjKey Table::find_first(ColKey col_key, util::Optional<float> value) const
2405
{
×
2406
    return value ? find_first(col_key, *value) : find_first_null(col_key);
×
2407
}
×
2408

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

2415
template <>
2416
ObjKey Table::find_first(ColKey col_key, null) const
2417
{
×
2418
    return find_first_null(col_key);
×
2419
}
×
2420
} // namespace realm
2421

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

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

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

2455
ObjKey Table::find_first_timestamp(ColKey col_key, Timestamp value) const
2456
{
108✔
2457
    return find_first(col_key, value);
108✔
2458
}
108✔
2459

2460
ObjKey Table::find_first_object_id(ColKey col_key, ObjectId value) const
2461
{
6✔
2462
    return find_first(col_key, value);
6✔
2463
}
6✔
2464

2465
ObjKey Table::find_first_float(ColKey col_key, float value) const
2466
{
12✔
2467
    return find_first<Float>(col_key, value);
12✔
2468
}
12✔
2469

2470
ObjKey Table::find_first_double(ColKey col_key, double value) const
2471
{
12✔
2472
    return find_first<Double>(col_key, value);
12✔
2473
}
12✔
2474

2475
ObjKey Table::find_first_decimal(ColKey col_key, Decimal128 value) const
2476
{
×
2477
    return find_first<Decimal128>(col_key, value);
×
2478
}
×
2479

2480
ObjKey Table::find_first_string(ColKey col_key, StringData value) const
2481
{
11,742✔
2482
    return find_first<StringData>(col_key, value);
11,742✔
2483
}
11,742✔
2484

2485
ObjKey Table::find_first_binary(ColKey col_key, BinaryData value) const
2486
{
×
2487
    return find_first<BinaryData>(col_key, value);
×
2488
}
×
2489

2490
ObjKey Table::find_first_null(ColKey col_key) const
2491
{
114✔
2492
    return where().equal(col_key, null{}).find();
114✔
2493
}
114✔
2494

2495
ObjKey Table::find_first_uuid(ColKey col_key, UUID value) const
2496
{
18✔
2497
    return find_first(col_key, value);
18✔
2498
}
18✔
2499

2500
template <class T>
2501
TableView Table::find_all(ColKey col_key, T value)
2502
{
102✔
2503
    return where().equal(col_key, value).find_all();
102✔
2504
}
102✔
2505

2506
TableView Table::find_all_int(ColKey col_key, int64_t value)
2507
{
96✔
2508
    return find_all<int64_t>(col_key, value);
96✔
2509
}
96✔
2510

2511
TableView Table::find_all_int(ColKey col_key, int64_t value) const
2512
{
×
2513
    return const_cast<Table*>(this)->find_all<int64_t>(col_key, value);
×
2514
}
×
2515

2516
TableView Table::find_all_bool(ColKey col_key, bool value)
2517
{
×
2518
    return find_all<bool>(col_key, value);
×
2519
}
×
2520

2521
TableView Table::find_all_bool(ColKey col_key, bool value) const
2522
{
×
2523
    return const_cast<Table*>(this)->find_all<int64_t>(col_key, value);
×
2524
}
×
2525

2526

2527
TableView Table::find_all_float(ColKey col_key, float value)
2528
{
×
2529
    return find_all<float>(col_key, value);
×
2530
}
×
2531

2532
TableView Table::find_all_float(ColKey col_key, float value) const
2533
{
×
2534
    return const_cast<Table*>(this)->find_all<float>(col_key, value);
×
2535
}
×
2536

2537
TableView Table::find_all_double(ColKey col_key, double value)
2538
{
6✔
2539
    return find_all<double>(col_key, value);
6✔
2540
}
6✔
2541

2542
TableView Table::find_all_double(ColKey col_key, double value) const
2543
{
×
2544
    return const_cast<Table*>(this)->find_all<double>(col_key, value);
×
2545
}
×
2546

2547
TableView Table::find_all_string(ColKey col_key, StringData value)
2548
{
282✔
2549
    return where().equal(col_key, value).find_all();
282✔
2550
}
282✔
2551

2552
TableView Table::find_all_string(ColKey col_key, StringData value) const
2553
{
×
2554
    return const_cast<Table*>(this)->find_all_string(col_key, value);
×
2555
}
×
2556

2557
TableView Table::find_all_binary(ColKey, BinaryData)
2558
{
×
2559
    throw Exception(ErrorCodes::IllegalOperation, "Table::find_all_binary not supported");
×
2560
}
×
2561

2562
TableView Table::find_all_binary(ColKey col_key, BinaryData value) const
2563
{
×
2564
    return const_cast<Table*>(this)->find_all_binary(col_key, value);
×
2565
}
×
2566

2567
TableView Table::find_all_null(ColKey col_key)
2568
{
×
2569
    return where().equal(col_key, null{}).find_all();
×
2570
}
×
2571

2572
TableView Table::find_all_null(ColKey col_key) const
2573
{
×
2574
    return const_cast<Table*>(this)->find_all_null(col_key);
×
2575
}
×
2576

2577
TableView Table::find_all_fulltext(ColKey col_key, StringData terms) const
2578
{
6✔
2579
    return where().fulltext(col_key, terms).find_all();
6✔
2580
}
6✔
2581

2582
TableView Table::get_sorted_view(ColKey col_key, bool ascending)
2583
{
72✔
2584
    TableView tv = where().find_all();
72✔
2585
    tv.sort(col_key, ascending);
72✔
2586
    return tv;
72✔
2587
}
72✔
2588

2589
TableView Table::get_sorted_view(ColKey col_key, bool ascending) const
2590
{
6✔
2591
    return const_cast<Table*>(this)->get_sorted_view(col_key, ascending);
6✔
2592
}
6✔
2593

2594
TableView Table::get_sorted_view(SortDescriptor order)
2595
{
126✔
2596
    TableView tv = where().find_all();
126✔
2597
    tv.sort(std::move(order));
126✔
2598
    return tv;
126✔
2599
}
126✔
2600

2601
TableView Table::get_sorted_view(SortDescriptor order) const
2602
{
×
2603
    return const_cast<Table*>(this)->get_sorted_view(std::move(order));
×
2604
}
×
2605

2606
util::Logger* Table::get_logger() const noexcept
2607
{
1,826,604✔
2608
    return *m_repl ? (*m_repl)->get_logger() : nullptr;
1,734,216✔
2609
}
1,826,604✔
2610

2611
// Called after a commit. Table will effectively contain the same as before,
2612
// but now with new refs from the file
2613
void Table::update_from_parent() noexcept
2614
{
814,425✔
2615
    // There is no top for sub-tables sharing spec
404,349✔
2616
    if (m_top.is_attached()) {
814,434✔
2617
        m_top.update_from_parent();
814,434✔
2618
        m_spec.update_from_parent();
814,434✔
2619
        m_clusters.update_from_parent();
814,434✔
2620
        m_index_refs.update_from_parent();
814,434✔
2621
        for (auto&& index : m_index_accessors) {
2,665,251✔
2622
            if (index != nullptr) {
2,665,251✔
2623
                index->update_from_parent();
274,548✔
2624
            }
274,548✔
2625
        }
2,665,251✔
2626

404,358✔
2627
        m_opposite_table.update_from_parent();
814,434✔
2628
        m_opposite_column.update_from_parent();
814,434✔
2629
        if (m_top.size() > top_position_for_flags) {
814,434✔
2630
            uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
812,601✔
2631
            m_table_type = Type(flags & table_type_mask);
812,601✔
2632
        }
812,601✔
2633
        else {
1,833✔
2634
            m_table_type = Type::TopLevel;
1,833✔
2635
        }
1,833✔
2636
        if (m_tombstones)
814,434✔
2637
            m_tombstones->update_from_parent();
1,314✔
2638

404,358✔
2639
        refresh_content_version();
814,434✔
2640
        m_has_any_embedded_objects.reset();
814,434✔
2641
    }
814,434✔
2642
    m_alloc.bump_storage_version();
814,425✔
2643
}
814,425✔
2644

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

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

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

150✔
2724
    out << "]";
300✔
2725
}
300✔
2726

2727

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

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

63✔
2759
    return true;
117✔
2760
}
126✔
2761

2762

2763
void Table::flush_for_commit()
2764
{
3,969,177✔
2765
    if (m_top.is_attached() && m_top.size() >= top_position_for_version) {
3,969,180✔
2766
        if (!m_top.is_read_only()) {
3,969,147✔
2767
            ++m_in_file_version_at_transaction_boundary;
1,239,828✔
2768
            auto rot_version = RefOrTagged::make_tagged(m_in_file_version_at_transaction_boundary);
1,239,828✔
2769
            m_top.set(top_position_for_version, rot_version);
1,239,828✔
2770
        }
1,239,828✔
2771
    }
3,969,147✔
2772
}
3,969,177✔
2773

2774
void Table::refresh_content_version()
2775
{
1,157,184✔
2776
    REALM_ASSERT(m_top.is_attached());
1,157,184✔
2777
    if (m_top.size() >= top_position_for_version) {
1,157,184✔
2778
        // we have versioning info in the file. Use this to conditionally
612,753✔
2779
        // bump the version counter:
612,753✔
2780
        auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
1,156,920✔
2781
        REALM_ASSERT(rot_version.is_tagged());
1,156,920✔
2782
        if (m_in_file_version_at_transaction_boundary != rot_version.get_as_int()) {
1,156,920✔
2783
            m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
227,637✔
2784
            bump_content_version();
227,637✔
2785
        }
227,637✔
2786
    }
1,156,920✔
2787
    else {
264✔
2788
        // assume the worst:
213✔
2789
        bump_content_version();
264✔
2790
    }
264✔
2791
}
1,157,184✔
2792

2793

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

2832
void Table::refresh_index_accessors()
2833
{
6,296,397✔
2834
    // Refresh search index accessors
3,400,014✔
2835

3,400,014✔
2836
    // First eliminate any index accessors for eliminated last columns
3,400,014✔
2837
    size_t col_ndx_end = m_leaf_ndx2colkey.size();
6,296,397✔
2838
    m_index_accessors.resize(col_ndx_end);
6,296,397✔
2839

3,400,014✔
2840
    // Then eliminate/refresh/create accessors within column range
3,400,014✔
2841
    // we can not use for_each_column() here, since the columns may have changed
3,400,014✔
2842
    // and the index accessor vector is not updated correspondingly.
3,400,014✔
2843
    for (size_t col_ndx = 0; col_ndx < col_ndx_end; col_ndx++) {
27,557,193✔
2844
        ref_type ref = m_index_refs.get_as_ref(col_ndx);
21,260,796✔
2845

11,012,157✔
2846
        if (ref == 0) {
21,260,796✔
2847
            // accessor drop
9,008,052✔
2848
            m_index_accessors[col_ndx].reset();
17,284,038✔
2849
        }
17,284,038✔
2850
        else {
3,976,758✔
2851
            auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_ndx]);
3,976,758✔
2852
            bool fulltext = attr.test(col_attr_FullText_Indexed);
3,976,758✔
2853
            auto col_key = m_leaf_ndx2colkey[col_ndx];
3,976,758✔
2854
            ClusterColumn virtual_col(&m_clusters, col_key, fulltext ? IndexType::Fulltext : IndexType::General);
3,976,743✔
2855

2,004,105✔
2856
            if (m_index_accessors[col_ndx]) { // still there, refresh:
3,976,758✔
2857
                m_index_accessors[col_ndx]->refresh_accessor_tree(virtual_col);
463,749✔
2858
            }
463,749✔
2859
            else { // new index!
3,513,009✔
2860
                m_index_accessors[col_ndx] =
3,513,009✔
2861
                    std::make_unique<StringIndex>(ref, &m_index_refs, col_ndx, virtual_col, get_alloc());
3,513,009✔
2862
            }
3,513,009✔
2863
        }
3,976,758✔
2864
    }
21,260,796✔
2865
}
6,296,397✔
2866

2867
bool Table::is_cross_table_link_target() const noexcept
2868
{
7,758✔
2869
    auto is_cross_link = [this](ColKey col_key) {
3,828✔
2870
        auto t = col_key.get_type();
48✔
2871
        // look for a backlink with a different target than ourselves
24✔
2872
        return (t == col_type_BackLink && get_opposite_table_key(col_key) != get_key())
48✔
2873
                   ? IteratorControl::Stop
33✔
2874
                   : IteratorControl::AdvanceToNext;
39✔
2875
    };
48✔
2876
    return for_each_backlink_column(is_cross_link);
7,758✔
2877
}
7,758✔
2878

2879
// LCOV_EXCL_START ignore debug functions
2880

2881
void Table::verify() const
2882
{
2,949,261✔
2883
#ifdef REALM_DEBUG
2,949,261✔
2884
    if (m_top.is_attached())
2,949,261✔
2885
        m_top.verify();
2,949,264✔
2886
    m_spec.verify();
2,949,261✔
2887
    m_clusters.verify();
2,949,261✔
2888
    if (nb_unresolved())
2,949,261✔
2889
        m_tombstones->verify();
730,350✔
2890
#endif
2,949,261✔
2891
}
2,949,261✔
2892

2893
#ifdef REALM_DEBUG
2894
MemStats Table::stats() const
2895
{
×
2896
    MemStats mem_stats;
×
2897
    m_top.stats(mem_stats);
×
2898
    return mem_stats;
×
2899
}
×
2900
#endif // LCOV_EXCL_STOP ignore debug functions
2901

2902
Obj Table::create_object(ObjKey key, const FieldValues& values)
2903
{
22,787,010✔
2904
    if (is_embedded())
22,787,010✔
2905
        throw IllegalOperation(util::format("Explicit creation of embedded object not allowed in: %1", get_name()));
48✔
2906
    if (m_primary_key_col)
22,786,962✔
2907
        throw IllegalOperation(util::format("Table has primary key: %1", get_name()));
×
2908
    if (key == null_key) {
22,786,962✔
2909
        GlobalKey object_id = allocate_object_id_squeezed();
19,630,380✔
2910
        key = object_id.get_local_key(get_sync_file_id());
19,630,380✔
2911
        // Check if this key collides with an already existing object
9,807,522✔
2912
        // This could happen if objects were at some point created with primary keys,
9,807,522✔
2913
        // but later primary key property was removed from the schema.
9,807,522✔
2914
        while (m_clusters.is_valid(key)) {
19,630,380✔
2915
            object_id = allocate_object_id_squeezed();
×
2916
            key = object_id.get_local_key(get_sync_file_id());
×
2917
        }
×
2918
        if (auto repl = get_repl())
19,630,380✔
2919
            repl->create_object(this, object_id);
4,313,172✔
2920
    }
19,630,380✔
2921

11,384,247✔
2922
    REALM_ASSERT(key.value >= 0);
22,786,962✔
2923

11,384,247✔
2924
    Obj obj = m_clusters.insert(key, values); // repl->set()
22,786,962✔
2925

11,384,247✔
2926
    return obj;
22,786,962✔
2927
}
22,786,962✔
2928

2929
Obj Table::create_linked_object()
2930
{
40,161✔
2931
    REALM_ASSERT(is_embedded());
40,161✔
2932

19,986✔
2933
    GlobalKey object_id = allocate_object_id_squeezed();
40,161✔
2934
    ObjKey key = object_id.get_local_key(get_sync_file_id());
40,161✔
2935

19,986✔
2936
    REALM_ASSERT(key.value >= 0);
40,161✔
2937

19,986✔
2938
    Obj obj = m_clusters.insert(key, {});
40,161✔
2939

19,986✔
2940
    return obj;
40,161✔
2941
}
40,161✔
2942

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

15✔
2951
    if (auto repl = get_repl())
30✔
2952
        repl->create_object(this, object_id);
30✔
2953

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

15✔
2969
        return obj;
30✔
2970
    }
30✔
2971
    catch (const KeyAlreadyUsed&) {
6✔
2972
        return m_clusters.get(key);
6✔
2973
    }
6✔
2974
}
30✔
2975

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

283,068✔
2984
    DataType type = DataType(primary_key_col.get_type());
589,050✔
2985

283,068✔
2986
    if (primary_key.is_null() && !primary_key_col.is_nullable()) {
589,050✔
2987
        throw InvalidArgument(
6✔
2988
            ErrorCodes::PropertyNotNullable,
6✔
2989
            util::format("Primary key for class %1 cannot be NULL", Group::table_name_to_class_name(get_name())));
6✔
2990
    }
6✔
2991

283,065✔
2992
    if (!(primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) &&
589,044✔
2993
        primary_key.get_type() != type) {
588,804✔
2994
        throw InvalidArgument(ErrorCodes::TypeMismatch, util::format("Wrong primary key type for class %1",
6✔
2995
                                                                     Group::table_name_to_class_name(get_name())));
6✔
2996
    }
6✔
2997

283,062✔
2998
    REALM_ASSERT(type == type_String || type == type_ObjectId || type == type_Int || type == type_UUID);
589,038✔
2999

283,062✔
3000
    if (did_create)
589,038✔
3001
        *did_create = false;
74,904✔
3002

283,062✔
3003
    // Check for existing object
283,062✔
3004
    if (ObjKey key = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key)) {
589,038✔
3005
        if (mode == UpdateMode::never) {
82,998✔
3006
            throw ObjectAlreadyExists(this->get_class_name(), primary_key);
6✔
3007
        }
6✔
3008
        auto obj = m_clusters.get(key);
82,992✔
3009
        for (auto& val : field_values) {
40,866✔
3010
            if (mode == UpdateMode::all || obj.get_any(val.col_key) != val.value) {
12✔
3011
                obj.set_any(val.col_key, val.value, val.is_default);
12✔
3012
            }
12✔
3013
        }
12✔
3014
        return obj;
82,992✔
3015
    }
82,992✔
3016

242,199✔
3017
    ObjKey unres_key;
506,040✔
3018
    if (m_tombstones) {
506,040✔
3019
        // Check for potential tombstone
19,020✔
3020
        GlobalKey object_id{primary_key};
38,244✔
3021
        ObjKey object_key = global_to_local_object_id_hashed(object_id);
38,244✔
3022

19,020✔
3023
        ObjKey key = object_key.get_unresolved();
38,244✔
3024
        if (auto obj = m_tombstones->try_get_obj(key)) {
38,244✔
3025
            auto existing_pk_value = obj.get_any(primary_key_col);
13,413✔
3026

6,630✔
3027
            // If the primary key is the same, the object should be resurrected below
6,630✔
3028
            if (existing_pk_value == primary_key) {
13,413✔
3029
                unres_key = key;
13,407✔
3030
            }
13,407✔
3031
        }
13,413✔
3032
    }
38,244✔
3033

242,199✔
3034
    ObjKey key = get_next_valid_key();
506,040✔
3035

242,199✔
3036
    auto repl = get_repl();
506,040✔
3037
    if (repl) {
506,040✔
3038
        repl->create_object_with_primary_key(this, key, primary_key);
444,924✔
3039
    }
444,924✔
3040
    if (did_create) {
506,040✔
3041
        *did_create = true;
36,579✔
3042
    }
36,579✔
3043

242,199✔
3044
    field_values.insert(primary_key_col, primary_key);
506,040✔
3045
    Obj ret = m_clusters.insert(key, field_values);
506,040✔
3046

242,199✔
3047
    // Check if unresolved exists
242,199✔
3048
    if (unres_key) {
506,040✔
3049
        auto tombstone = m_tombstones->get(unres_key);
13,407✔
3050
        ret.assign_pk_and_backlinks(tombstone);
13,407✔
3051
        // If tombstones had no links to it, it may still be alive
6,627✔
3052
        if (m_tombstones->is_valid(unres_key)) {
13,407✔
3053
            CascadeState state(CascadeState::Mode::None);
4,251✔
3054
            m_tombstones->erase(unres_key, state);
4,251✔
3055
        }
4,251✔
3056
    }
13,407✔
3057
    if (is_asymmetric() && repl && repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
506,040✔
3058
        get_parent_group()->m_tables_to_clear.insert(this->m_key);
1,290✔
3059
    }
1,290✔
3060
    return ret;
506,040✔
3061
}
506,040✔
3062

3063
ObjKey Table::find_primary_key(Mixed primary_key) const
3064
{
920,985✔
3065
    auto primary_key_col = get_primary_key_column();
920,985✔
3066
    REALM_ASSERT(primary_key_col);
920,985✔
3067
    DataType type = DataType(primary_key_col.get_type());
920,985✔
3068
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
920,985✔
3069
                 primary_key.get_type() == type);
920,985✔
3070

464,256✔
3071
    if (auto&& index = m_index_accessors[primary_key_col.get_index().val]) {
920,985✔
3072
        return index->find_first(primary_key);
920,979✔
3073
    }
920,979✔
3074

6✔
3075
    // This must be file format 11, 20 or 21 as those are the ones we can open in read-only mode
6✔
3076
    // so try the old algorithm
6✔
3077
    GlobalKey object_id{primary_key};
6✔
3078
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
6✔
3079

6✔
3080
    // Check if existing
6✔
3081
    if (auto obj = m_clusters.try_get_obj(object_key)) {
6!
3082
        auto existing_pk_value = obj.get_any(primary_key_col);
×
3083

3084
        if (existing_pk_value == primary_key) {
×
3085
            return object_key;
×
3086
        }
×
3087
    }
6✔
3088
    return {};
6✔
3089
}
6✔
3090

3091
ObjKey Table::get_objkey_from_primary_key(const Mixed& primary_key)
3092
{
749,475✔
3093
    // Check if existing
377,064✔
3094
    if (auto key = find_primary_key(primary_key)) {
749,475✔
3095
        return key;
718,632✔
3096
    }
718,632✔
3097

15,105✔
3098
    // Object does not exist - create tombstone
15,105✔
3099
    GlobalKey object_id{primary_key};
30,843✔
3100
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
30,843✔
3101
    return get_or_create_tombstone(object_key, m_primary_key_col, primary_key).get_key();
30,843✔
3102
}
30,843✔
3103

3104
ObjKey Table::get_objkey_from_global_key(GlobalKey global_key)
3105
{
18✔
3106
    REALM_ASSERT(!m_primary_key_col);
18✔
3107
    auto object_key = global_key.get_local_key(get_sync_file_id());
18✔
3108

9✔
3109
    // Check if existing
9✔
3110
    if (m_clusters.is_valid(object_key)) {
18✔
3111
        return object_key;
12✔
3112
    }
12✔
3113

3✔
3114
    return get_or_create_tombstone(object_key, {}, {}).get_key();
6✔
3115
}
6✔
3116

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

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

3145
Obj Table::get_object_with_primary_key(Mixed primary_key) const
3146
{
58,968✔
3147
    auto primary_key_col = get_primary_key_column();
58,968✔
3148
    REALM_ASSERT(primary_key_col);
58,968✔
3149
    DataType type = DataType(primary_key_col.get_type());
58,968✔
3150
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
58,968✔
3151
                 primary_key.get_type() == type);
58,968✔
3152
    ObjKey k = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key);
58,968✔
3153
    return k ? m_clusters.get(k) : Obj{};
58,959✔
3154
}
58,968✔
3155

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

3169
GlobalKey Table::allocate_object_id_squeezed()
3170
{
19,670,919✔
3171
    // m_client_file_ident will be zero if we haven't been in contact with
9,827,343✔
3172
    // the server yet.
9,827,343✔
3173
    auto peer_id = get_sync_file_id();
19,670,919✔
3174
    auto sequence = allocate_sequence_number();
19,670,919✔
3175
    return GlobalKey{peer_id, sequence};
19,670,919✔
3176
}
19,670,919✔
3177

3178
namespace {
3179

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

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

3201
} // namespace
3202

3203
ObjKey Table::global_to_local_object_id_hashed(GlobalKey object_id) const
3204
{
69,456✔
3205
    ObjKey optimistic = get_optimistic_local_id_hashed(object_id);
69,456✔
3206

34,314✔
3207
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
69,456✔
3208
        Allocator& alloc = m_top.get_alloc();
24✔
3209
        Array collision_map{alloc};
24✔
3210
        collision_map.init_from_ref(collision_map_ref); // Throws
24✔
3211

12✔
3212
        Array hi{alloc};
24✔
3213
        hi.init_from_ref(to_ref(collision_map.get(s_collision_map_hi))); // Throws
24✔
3214

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

34,302✔
3229
    return optimistic;
69,432✔
3230
}
69,432✔
3231

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

6✔
3242
    collision_map.set_parent(&m_top, top_position_for_collision_map);
12✔
3243
    hi.set_parent(&collision_map, s_collision_map_hi);
12✔
3244
    lo.set_parent(&collision_map, s_collision_map_lo);
12✔
3245
    local_id.set_parent(&collision_map, s_collision_map_local_id);
12✔
3246

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

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

6✔
3264
    hi.init_from_parent();       // Throws
12✔
3265
    lo.init_from_parent();       // Throws
12✔
3266
    local_id.init_from_parent(); // Throws
12✔
3267

6✔
3268
    size_t num_entries = hi.size();
12✔
3269
    REALM_ASSERT(lo.size() == num_entries);
12✔
3270
    REALM_ASSERT(local_id.size() == num_entries);
12✔
3271

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

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

6✔
3294
    auto sequence_number_for_local_id = allocate_sequence_number();
12✔
3295
    ObjKey new_local_id = make_tagged_local_id_after_hash_collision(sequence_number_for_local_id);
12✔
3296
    insert_collision(incoming_id, new_local_id);
12✔
3297
    insert_collision(colliding_id, colliding_local_id);
12✔
3298

6✔
3299
    return new_local_id;
12✔
3300
}
12✔
3301

3302
Obj Table::get_or_create_tombstone(ObjKey key, ColKey pk_col, Mixed pk_val)
3303
{
31,386✔
3304
    auto unres_key = key.get_unresolved();
31,386✔
3305

15,381✔
3306
    ensure_graveyard();
31,386✔
3307
    auto tombstone = m_tombstones->try_get_obj(unres_key);
31,386✔
3308
    if (tombstone) {
31,386✔
3309
        if (pk_col) {
3,054✔
3310
            auto existing_pk_value = tombstone.get_any(pk_col);
3,054✔
3311
            // It may just be the same object
1,374✔
3312
            if (existing_pk_value != pk_val) {
3,054✔
3313
                // We have a collision - create new ObjKey
6✔
3314
                key = allocate_local_id_after_hash_collision({pk_val}, {existing_pk_value}, key);
12✔
3315
                return get_or_create_tombstone(key, pk_col, pk_val);
12✔
3316
            }
12✔
3317
        }
3,042✔
3318
        return tombstone;
3,042✔
3319
    }
3,042✔
3320
    return m_tombstones->insert(unres_key, {{pk_col, pk_val}});
28,332✔
3321
}
28,332✔
3322

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

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

12✔
3343
            hi.set_parent(&collision_map, s_collision_map_hi);
24✔
3344
            lo.set_parent(&collision_map, s_collision_map_lo);
24✔
3345
            hi.init_from_parent();
24✔
3346
            lo.init_from_parent();
24✔
3347

12✔
3348
            hi.erase(ndx);
24✔
3349
            lo.erase(ndx);
24✔
3350
            local_id.erase(ndx);
24✔
3351
            if (hi.size() == 0) {
24✔
3352
                free_collision_table();
12✔
3353
            }
12✔
3354
        }
24✔
3355
    }
30✔
3356
}
5,027,379✔
3357

3358
void Table::free_collision_table()
3359
{
4,302✔
3360
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
4,302✔
3361
        Array::destroy_deep(collision_map_ref, m_alloc);
12✔
3362
        m_top.set(top_position_for_collision_map, 0);
12✔
3363
    }
12✔
3364
}
4,302✔
3365

3366
void Table::create_objects(size_t number, std::vector<ObjKey>& keys)
3367
{
3,858✔
3368
    while (number--) {
6,323,832✔
3369
        keys.push_back(create_object().get_key());
6,319,974✔
3370
    }
6,319,974✔
3371
}
3,858✔
3372

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

3380
void Table::dump_objects()
3381
{
×
3382
    m_clusters.dump_objects();
×
3383
    if (nb_unresolved())
×
3384
        m_tombstones->dump_objects();
×
3385
}
×
3386

3387
void Table::remove_object(ObjKey key)
3388
{
2,489,217✔
3389
    Group* g = get_parent_group();
2,489,217✔
3390

1,244,217✔
3391
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
2,489,217✔
3392
        CascadeState state(CascadeState::Mode::Strong, g);
2,625✔
3393
        state.m_to_be_deleted.emplace_back(m_key, key);
2,625✔
3394
        m_clusters.nullify_incoming_links(key, state);
2,625✔
3395
        remove_recursive(state);
2,625✔
3396
    }
2,625✔
3397
    else {
2,486,592✔
3398
        CascadeState state(CascadeState::Mode::None, g);
2,486,592✔
3399
        if (g) {
2,486,592✔
3400
            m_clusters.nullify_incoming_links(key, state);
2,404,596✔
3401
        }
2,404,596✔
3402
        m_clusters.erase(key, state);
2,486,592✔
3403
    }
2,486,592✔
3404
}
2,489,217✔
3405

3406
ObjKey Table::invalidate_object(ObjKey key)
3407
{
63,672✔
3408
    if (is_embedded())
63,672✔
3409
        throw IllegalOperation("Deletion of embedded object not allowed");
×
3410
    REALM_ASSERT(!key.is_unresolved());
63,672✔
3411

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

31,611✔
3429
    remove_object(key);
63,672✔
3430

31,611✔
3431
    return tombstone.get_key();
63,672✔
3432
}
63,672✔
3433

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

3450
Table::Iterator Table::begin() const
3451
{
1,002,162✔
3452
    return Iterator(m_clusters, 0);
1,002,162✔
3453
}
1,002,162✔
3454

3455
Table::Iterator Table::end() const
3456
{
9,487,998✔
3457
    return Iterator(m_clusters, size());
9,487,998✔
3458
}
9,487,998✔
3459

3460
TableRef _impl::TableFriend::get_opposite_link_table(const Table& table, ColKey col_key)
3461
{
7,088,367✔
3462
    TableRef ret;
7,088,367✔
3463
    if (col_key) {
7,089,312✔
3464
        return table.get_opposite_table(col_key);
7,089,312✔
3465
    }
7,089,312✔
3466
    return ret;
4,294,967,294✔
3467
}
4,294,967,294✔
3468

3469
const uint64_t Table::max_num_columns;
3470

3471
void Table::build_column_mapping()
3472
{
6,318,441✔
3473
    // build column mapping from spec
3,411,228✔
3474
    // TODO: Optimization - Don't rebuild this for every change
3,411,228✔
3475
    m_spec_ndx2leaf_ndx.clear();
6,318,441✔
3476
    m_leaf_ndx2spec_ndx.clear();
6,318,441✔
3477
    m_leaf_ndx2colkey.clear();
6,318,441✔
3478
    size_t num_spec_cols = m_spec.get_column_count();
6,318,441✔
3479
    m_spec_ndx2leaf_ndx.resize(num_spec_cols);
6,318,441✔
3480
    for (size_t spec_ndx = 0; spec_ndx < num_spec_cols; ++spec_ndx) {
27,543,975✔
3481
        ColKey col_key = m_spec.get_key(spec_ndx);
21,225,534✔
3482
        unsigned leaf_ndx = col_key.get_index().val;
21,225,534✔
3483
        if (leaf_ndx >= m_leaf_ndx2colkey.size()) {
21,225,534✔
3484
            m_leaf_ndx2colkey.resize(leaf_ndx + 1);
20,757,639✔
3485
            m_leaf_ndx2spec_ndx.resize(leaf_ndx + 1, -1);
20,757,639✔
3486
        }
20,757,639✔
3487
        m_spec_ndx2leaf_ndx[spec_ndx] = ColKey::Idx{leaf_ndx};
21,225,534✔
3488
        m_leaf_ndx2spec_ndx[leaf_ndx] = spec_ndx;
21,225,534✔
3489
        m_leaf_ndx2colkey[leaf_ndx] = col_key;
21,225,534✔
3490
    }
21,225,534✔
3491
}
6,318,441✔
3492

3493
ColKey Table::generate_col_key(ColumnType tp, ColumnAttrMask attr)
3494
{
982,344✔
3495
    REALM_ASSERT(!attr.test(col_attr_Indexed));
982,344✔
3496
    REALM_ASSERT(!attr.test(col_attr_Unique)); // Must not be encoded into col_key
982,344✔
3497

484,446✔
3498
    int64_t col_seq_number = m_top.get_as_ref_or_tagged(top_position_for_column_key).get_as_int();
982,344✔
3499
    unsigned upper = unsigned(col_seq_number ^ get_key().value);
982,344✔
3500

484,446✔
3501
    // reuse lowest available leaf ndx:
484,446✔
3502
    unsigned lower = unsigned(m_leaf_ndx2colkey.size());
982,344✔
3503
    // look for an unused entry:
484,446✔
3504
    for (unsigned idx = 0; idx < lower; ++idx) {
6,255,924✔
3505
        if (m_leaf_ndx2colkey[idx] == ColKey()) {
5,273,667✔
3506
            lower = idx;
87✔
3507
            break;
87✔
3508
        }
87✔
3509
    }
5,273,667✔
3510
    return ColKey(ColKey::Idx{lower}, tp, attr, upper);
982,344✔
3511
}
982,344✔
3512

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

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

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

3566
ColKey Table::get_primary_key_column() const
3567
{
19,793,616✔
3568
    return m_primary_key_col;
19,793,616✔
3569
}
19,793,616✔
3570

3571
void Table::set_primary_key_column(ColKey col_key)
3572
{
720✔
3573
    if (col_key == m_primary_key_col) {
720✔
3574
        return;
378✔
3575
    }
378✔
3576

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

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

171✔
3587
    if (col_key) {
342✔
3588
        check_column(col_key);
222✔
3589
        validate_column_is_unique(col_key);
222✔
3590
        do_set_primary_key_column(col_key);
222✔
3591
    }
222✔
3592
    else {
120✔
3593
        do_set_primary_key_column(col_key);
120✔
3594
    }
120✔
3595
}
342✔
3596

3597

3598
void Table::do_set_primary_key_column(ColKey col_key)
3599
{
137,676✔
3600
    if (col_key) {
137,676✔
3601
        auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
129,951✔
3602
        auto attr = m_spec.get_column_attr(spec_ndx);
129,951✔
3603
        if (attr.test(col_attr_FullText_Indexed)) {
129,951✔
3604
            throw InvalidColumnKey("primary key cannot have a full text index");
6✔
3605
        }
6✔
3606
    }
137,670✔
3607

68,190✔
3608
    if (m_primary_key_col) {
137,670✔
3609
        // If the search index has not been set explicitly on current pk col, we remove it again
3,747✔
3610
        auto spec_ndx = leaf_ndx2spec_ndx(m_primary_key_col.get_index());
7,629✔
3611
        auto attr = m_spec.get_column_attr(spec_ndx);
7,629✔
3612
        if (!attr.test(col_attr_Indexed)) {
7,629✔
3613
            remove_search_index(m_primary_key_col);
7,617✔
3614
        }
7,617✔
3615
    }
7,629✔
3616

68,190✔
3617
    if (col_key) {
137,670✔
3618
        m_top.set(top_position_for_pk_col, RefOrTagged::make_tagged(col_key.value));
129,945✔
3619
        do_add_search_index(col_key, IndexType::General);
129,945✔
3620
    }
129,945✔
3621
    else {
7,725✔
3622
        m_top.set(top_position_for_pk_col, 0);
7,725✔
3623
    }
7,725✔
3624

68,190✔
3625
    m_primary_key_col = col_key;
137,670✔
3626
}
137,670✔
3627

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

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

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

3656
ObjKey Table::get_next_valid_key()
3657
{
506,040✔
3658
    ObjKey key;
506,040✔
3659
    do {
506,046✔
3660
        key = ObjKey(allocate_sequence_number());
506,046✔
3661
    } while (m_clusters.is_valid(key));
506,046✔
3662

242,202✔
3663
    return key;
506,040✔
3664
}
506,040✔
3665

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

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

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

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

81✔
3725
    m_clusters.update(func);
162✔
3726
}
162✔
3727

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

60✔
3736
        ArrayInteger from_arr(allocator);
120✔
3737
        ArrayInteger to_arr(allocator);
120✔
3738
        cluster->init_leaf(key_from, &from_arr);
120✔
3739
        cluster->init_leaf(key_to, &to_arr);
120✔
3740

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

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

60✔
3773
    m_clusters.update(func);
120✔
3774
}
120✔
3775

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

3897

3898
ColKey Table::set_nullability(ColKey col_key, bool nullable, bool throw_on_null)
3899
{
522✔
3900
    if (col_key.is_nullable() == nullable)
522✔
3901
        return col_key;
240✔
3902

141✔
3903
    check_column(col_key);
282✔
3904

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

141✔
3917
    ColKey new_col = generate_col_key(type, attr);
282✔
3918
    do_insert_root_column(new_col, type, "__temporary");
282✔
3919

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

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

138✔
3936
    erase_root_column(col_key);
276✔
3937
    m_spec.rename_column(colkey2spec_ndx(new_col), column_name);
276✔
3938

138✔
3939
    if (index_type != IndexType::None)
276✔
3940
        do_add_search_index(new_col, index_type);
30✔
3941

138✔
3942
    return new_col;
276✔
3943
}
276✔
3944

3945
bool Table::has_any_embedded_objects()
3946
{
2,494,749✔
3947
    if (!m_has_any_embedded_objects) {
2,494,749✔
3948
        m_has_any_embedded_objects = false;
109,971✔
3949
        for_each_public_column([&](ColKey col_key) {
220,344✔
3950
            auto target_table_key = get_opposite_table_key(col_key);
220,344✔
3951
            if (target_table_key && is_link_type(col_key.get_type())) {
220,344✔
3952
                auto target_table = get_parent_group()->get_table_unchecked(target_table_key);
9,489✔
3953
                if (target_table->is_embedded()) {
9,489✔
3954
                    m_has_any_embedded_objects = true;
7,371✔
3955
                    return IteratorControl::Stop; // early out
7,371✔
3956
                }
7,371✔
3957
            }
212,973✔
3958
            return IteratorControl::AdvanceToNext;
212,973✔
3959
        });
212,973✔
3960
    }
109,971✔
3961
    return *m_has_any_embedded_objects;
2,494,749✔
3962
}
2,494,749✔
3963

3964
void Table::set_opposite_column(ColKey col_key, TableKey opposite_table, ColKey opposite_column)
3965
{
170,190✔
3966
    m_opposite_table.set(col_key.get_index().val, opposite_table.value);
170,190✔
3967
    m_opposite_column.set(col_key.get_index().val, opposite_column.value);
170,190✔
3968
}
170,190✔
3969

3970
ColKey Table::find_backlink_column(ColKey origin_col_key, TableKey origin_table) const
3971
{
41,652✔
3972
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
145,365✔
3973
        if (m_opposite_column.get(i) == origin_col_key.value && m_opposite_table.get(i) == origin_table.value) {
138,429✔
3974
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
34,716✔
3975
        }
34,716✔
3976
    }
138,429✔
3977

20,709✔
3978
    return {};
24,177✔
3979
}
41,652✔
3980

3981
ColKey Table::find_or_add_backlink_column(ColKey origin_col_key, TableKey origin_table)
3982
{
41,004✔
3983
    ColKey backlink_col_key = find_backlink_column(origin_col_key, origin_table);
41,004✔
3984

20,385✔
3985
    if (!backlink_col_key) {
41,004✔
3986
        backlink_col_key = do_insert_root_column(ColKey{}, col_type_BackLink, "");
6,936✔
3987
        set_opposite_column(backlink_col_key, origin_table, origin_col_key);
6,936✔
3988

3,468✔
3989
        if (Replication* repl = get_repl())
6,936✔
3990
            repl->typed_link_change(get_parent_group()->get_table_unchecked(origin_table), origin_col_key,
6,606✔
3991
                                    m_key); // Throws
6,606✔
3992
    }
6,936✔
3993

20,385✔
3994
    return backlink_col_key;
41,004✔
3995
}
41,004✔
3996

3997
TableKey Table::get_opposite_table_key(ColKey col_key) const
3998
{
14,501,103✔
3999
    return TableKey(int32_t(m_opposite_table.get(col_key.get_index().val)));
14,501,103✔
4000
}
14,501,103✔
4001

4002
bool Table::links_to_self(ColKey col_key) const
4003
{
58,584✔
4004
    return get_opposite_table_key(col_key) == m_key;
58,584✔
4005
}
58,584✔
4006

4007
TableRef Table::get_opposite_table(ColKey col_key) const
4008
{
7,718,376✔
4009
    if (auto k = get_opposite_table_key(col_key)) {
7,718,376✔
4010
        return get_parent_group()->get_table(k);
7,665,207✔
4011
    }
7,665,207✔
4012
    return {};
53,169✔
4013
}
53,169✔
4014

4015
ColKey Table::get_opposite_column(ColKey col_key) const
4016
{
7,052,610✔
4017
    return ColKey(m_opposite_column.get(col_key.get_index().val));
7,052,610✔
4018
}
7,052,610✔
4019

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

© 2026 Coveralls, Inc