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

realm / realm-core / 1760

13 Oct 2023 04:18PM UTC coverage: 91.597% (+0.007%) from 91.59%
1760

push

Evergreen

realm-ci
Updated release notes

94264 of 173488 branches covered (0.0%)

230515 of 251661 relevant lines covered (91.6%)

6219245.35 hits per line

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

90.5
/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,251✔
269
    if (size() != other.size())
16,251✔
270
        return false;
×
271
    size_t sz = size();
16,251✔
272
    for (size_t i = 0; i < sz; i++) {
25,830✔
273
        REALM_ASSERT_DEBUG(this->at(i).first == other.at(i).first);
16,383✔
274
        if (this->at(i).second != other.at(i).second)
16,383✔
275
            return false;
6,804✔
276
    }
16,383✔
277
    return true;
12,849✔
278
}
16,251✔
279

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

325
std::ostream& operator<<(std::ostream& o, Table::Type table_type)
326
{
18,765✔
327
    switch (table_type) {
18,765✔
328
        case Table::Type::TopLevel:
18,723✔
329
            return o << "TopLevel";
18,723✔
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
{
21,177✔
391
    m_spec.set_parent(&m_top, top_position_for_spec);
21,177✔
392
    m_index_refs.set_parent(&m_top, top_position_for_search_indexes);
21,177✔
393
    m_opposite_table.set_parent(&m_top, top_position_for_opposite_table);
21,177✔
394
    m_opposite_column.set_parent(&m_top, top_position_for_opposite_column);
21,177✔
395
    m_cookie = cookie_created;
21,177✔
396
}
21,177✔
397

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

247,527✔
402
    Table* invalid_link = nullptr;
504,036✔
403
    ColumnAttrMask attr;
504,036✔
404
    if (nullable || type == type_Mixed)
504,036✔
405
        attr.set(col_attr_Nullable);
110,631✔
406
    ColKey col_key = generate_col_key(ColumnType(type), attr);
504,036✔
407

247,527✔
408
    return do_insert_column(col_key, type, name, invalid_link); // Throws
504,036✔
409
}
504,036✔
410

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

14,655✔
423
    m_has_any_embedded_objects.reset();
29,538✔
424

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

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

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

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

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

14,928✔
467
    m_has_any_embedded_objects.reset();
30,288✔
468

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

14,928✔
473
    return do_insert_column(col_key, type_LinkList, name, &target); // Throws
30,288✔
474
}
30,288✔
475

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

5,172✔
490
    ColumnAttrMask attr;
10,452✔
491
    attr.set(col_attr_Set);
10,452✔
492
    ColKey col_key = generate_col_key(col_type_Link, attr);
10,452✔
493
    return do_insert_column(col_key, type_Link, name, &target); // Throws
10,452✔
494
}
10,452✔
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,670✔
543
    Group* group = get_parent_group();
14,670✔
544
    REALM_ASSERT(group);
14,670✔
545
    cascade_state.m_group = group;
14,670✔
546

6,681✔
547
    do {
18,714✔
548
        cascade_state.send_notifications();
18,714✔
549

8,703✔
550
        for (auto& l : cascade_state.m_to_be_nullified) {
8,727✔
551
            Obj obj = group->get_table(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,714✔
558

8,703✔
559
        auto to_delete = std::move(cascade_state.m_to_be_deleted);
18,714✔
560
        for (auto obj : to_delete) {
16,692✔
561
            auto table = group->get_table(obj.first);
15,963✔
562
            // This might add to the list of objects that should be deleted
7,974✔
563
            REALM_ASSERT(!obj.second.is_unresolved());
15,963✔
564
            table->m_clusters.erase(obj.second, cascade_state);
15,963✔
565
        }
15,963✔
566
        nullify_links(cascade_state);
18,714✔
567
    } while (!cascade_state.m_to_be_deleted.empty() || !cascade_state.m_to_be_nullified.empty());
18,714✔
568
}
14,670✔
569

570
void Table::nullify_links(CascadeState& cascade_state)
571
{
23,304✔
572
    Group* group = get_parent_group();
23,304✔
573
    REALM_ASSERT(group);
23,304✔
574
    for (auto& to_delete : cascade_state.m_to_be_deleted) {
14,964✔
575
        auto table = group->get_table(to_delete.first);
7,914✔
576
        table->m_clusters.nullify_links(to_delete.second, cascade_state);
7,914✔
577
    }
7,914✔
578
}
23,304✔
579

580

581
void Table::remove_column(ColKey col_key)
582
{
16,965✔
583
    check_column(col_key);
16,965✔
584

8,037✔
585
    if (Replication* repl = get_repl())
16,965✔
586
        repl->erase_column(this, col_key); // Throws
519✔
587

8,037✔
588
    if (col_key == m_primary_key_col) {
16,965✔
589
        do_set_primary_key_column(ColKey());
7,179✔
590
    }
7,179✔
591
    else {
9,786✔
592
        REALM_ASSERT_RELEASE(m_primary_key_col.get_index().val != col_key.get_index().val);
9,786✔
593
    }
9,786✔
594

8,037✔
595
    erase_root_column(col_key); // Throws
16,965✔
596
    m_has_any_embedded_objects.reset();
16,965✔
597
}
16,965✔
598

599

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

54✔
604
    auto col_ndx = colkey2spec_ndx(col_key);
123✔
605
    m_spec.rename_column(col_ndx, name); // Throws
123✔
606

54✔
607
    bump_content_version();
123✔
608
    bump_storage_version();
123✔
609

54✔
610
    if (Replication* repl = get_repl())
123✔
611
        repl->rename_column(this, col_key, name); // Throws
123✔
612
}
123✔
613

614

615
TableKey Table::get_key_direct(Allocator& alloc, ref_type top_ref)
616
{
10,239,390✔
617
    // well, not quite "direct", more like "almost direct":
5,623,344✔
618
    Array table_top(alloc);
10,239,390✔
619
    table_top.init_from_ref(top_ref);
10,239,390✔
620
    if (table_top.size() > 3) {
10,239,390✔
621
        RefOrTagged rot = table_top.get_as_ref_or_tagged(top_position_for_key);
10,238,667✔
622
        return TableKey(int32_t(rot.get_as_int()));
10,238,667✔
623
    }
10,238,667✔
624
    else {
723✔
625
        return TableKey();
723✔
626
    }
723✔
627
}
10,239,390✔
628

629

630
void Table::init(ref_type top_ref, ArrayParent* parent, size_t ndx_in_parent, bool is_writable, bool is_frzn)
631
{
5,405,742✔
632
    REALM_ASSERT(!(is_writable && is_frzn));
5,405,742✔
633
    m_is_frozen = is_frzn;
5,405,742✔
634
    m_alloc.set_read_only(!is_writable);
5,405,742✔
635
    // Load from allocated memory
3,140,928✔
636
    m_top.set_parent(parent, ndx_in_parent);
5,405,742✔
637
    m_top.init_from_ref(top_ref);
5,405,742✔
638

3,140,928✔
639
    m_spec.init_from_parent();
5,405,742✔
640

3,140,928✔
641
    while (m_top.size() <= top_position_for_pk_col) {
5,406,702✔
642
        m_top.add(0);
960✔
643
    }
960✔
644

3,140,928✔
645
    if (m_top.get_as_ref(top_position_for_cluster_tree) == 0) {
5,405,742✔
646
        // This is an upgrade - create cluster
48✔
647
        MemRef mem = Cluster::create_empty_cluster(m_top.get_alloc()); // Throws
96✔
648
        m_top.set_as_ref(top_position_for_cluster_tree, mem.get_ref());
96✔
649
    }
96✔
650
    m_clusters.init_from_parent();
5,405,742✔
651

3,140,928✔
652
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_key);
5,405,742✔
653
    if (!rot.is_tagged()) {
5,405,742✔
654
        // Create table key
48✔
655
        rot = RefOrTagged::make_tagged(ndx_in_parent);
96✔
656
        m_top.set(top_position_for_key, rot);
96✔
657
    }
96✔
658
    m_key = TableKey(int32_t(rot.get_as_int()));
5,405,742✔
659

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

3,140,928✔
693
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
5,405,742✔
694
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
4,876,119✔
695

3,140,928✔
696
    if (m_top.size() <= top_position_for_flags) {
5,405,742✔
697
        m_table_type = Type::TopLevel;
702✔
698
    }
702✔
699
    else {
5,405,040✔
700
        uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
5,405,040✔
701
        m_table_type = Type(flags & table_type_mask);
5,405,040✔
702
    }
5,405,040✔
703
    m_has_any_embedded_objects.reset();
5,405,742✔
704

3,140,928✔
705
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
5,405,742✔
706
        // Tombstones exists
467,925✔
707
        if (!m_tombstones) {
880,116✔
708
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
548,388✔
709
        }
548,388✔
710
        m_tombstones->init_from_parent();
880,116✔
711
    }
880,116✔
712
    else {
4,525,626✔
713
        m_tombstones = nullptr;
4,525,626✔
714
    }
4,525,626✔
715
    m_cookie = cookie_initialized;
5,405,742✔
716
}
5,405,742✔
717

718

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

375,009✔
723
    // When the inserted column is a link-type column, we must also add a
375,009✔
724
    // backlink column to the target table.
375,009✔
725

375,009✔
726
    if (target_table) {
760,938✔
727
        auto backlink_col_key = target_table->do_insert_root_column(ColKey{}, col_type_BackLink, ""); // Throws
81,348✔
728
        target_table->check_column(backlink_col_key);
81,348✔
729

40,182✔
730
        set_opposite_column(col_key, target_table->get_key(), backlink_col_key);
81,348✔
731
        target_table->set_opposite_column(backlink_col_key, get_key(), col_key);
81,348✔
732
    }
81,348✔
733

375,009✔
734
    if (Replication* repl = get_repl())
760,938✔
735
        repl->insert_column(this, col_key, type, name, target_table); // Throws
743,274✔
736

375,009✔
737
    return col_key;
760,938✔
738
}
760,938✔
739

740

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

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

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

808
void Table::erase_from_search_indexes(ObjKey key)
809
{
5,029,350✔
810
    // Tombstones do not use index - will crash if we try to erase values
2,515,551✔
811
    if (!key.is_unresolved()) {
5,029,350✔
812
        for (auto&& index : m_index_accessors) {
6,712,401✔
813
            if (index) {
6,712,401✔
814
                index->erase(key);
283,257✔
815
            }
283,257✔
816
        }
6,712,401✔
817
    }
5,015,925✔
818
}
5,029,350✔
819

820
void Table::update_indexes(ObjKey key, const FieldValues& values)
821
{
23,157,303✔
822
    // Tombstones do not use index - will crash if we try to insert values
11,511,711✔
823
    if (key.is_unresolved()) {
23,157,303✔
824
        return;
28,842✔
825
    }
28,842✔
826

11,496,867✔
827
    auto sz = m_index_accessors.size();
23,128,461✔
828
    // values are sorted by column index - there may be values missing
11,496,867✔
829
    auto value = values.begin();
23,128,461✔
830
    for (size_t column_ndx = 0; column_ndx < sz; column_ndx++) {
57,117,939✔
831
        // Check if initial value is provided
16,845,372✔
832
        Mixed init_value;
33,989,562✔
833
        if (value != values.end() && value->col_key.get_index().val == column_ndx) {
33,989,562✔
834
            // Value for this column is provided
284,646✔
835
            init_value = value->value;
588,015✔
836
            ++value;
588,015✔
837
        }
588,015✔
838

16,845,372✔
839
        if (auto&& index = m_index_accessors[column_ndx]) {
33,989,562✔
840
            // There is an index for this column
556,881✔
841
            auto col_key = m_leaf_ndx2colkey[column_ndx];
1,132,692✔
842
            auto type = col_key.get_type();
1,132,692✔
843
            auto attr = col_key.get_attrs();
1,132,692✔
844
            bool nullable = attr.test(col_attr_Nullable);
1,132,692✔
845
            switch (type) {
1,132,692✔
846
                case col_type_Int:
533,694✔
847
                    if (init_value.is_null()) {
533,694✔
848
                        index->insert(key, ArrayIntNull::default_value(nullable));
165,555✔
849
                    }
165,555✔
850
                    else {
368,139✔
851
                        index->insert(key, init_value.get<int64_t>());
368,139✔
852
                    }
368,139✔
853
                    break;
533,694✔
854
                case col_type_Bool:
6,252✔
855
                    if (init_value.is_null()) {
6,252✔
856
                        index->insert(key, ArrayBoolNull::default_value(nullable));
6,216✔
857
                    }
6,216✔
858
                    else {
36✔
859
                        index->insert(key, init_value.get<bool>());
36✔
860
                    }
36✔
861
                    break;
6,252✔
862
                case col_type_String:
481,665✔
863
                    if (init_value.is_null()) {
481,665✔
864
                        index->insert(key, ArrayString::default_value(nullable));
432,873✔
865
                    }
432,873✔
866
                    else {
48,792✔
867
                        index->insert(key, init_value.get<String>());
48,792✔
868
                    }
48,792✔
869
                    break;
481,665✔
870
                case col_type_Timestamp:
6,297✔
871
                    if (init_value.is_null()) {
6,297✔
872
                        index->insert(key, ArrayTimestamp::default_value(nullable));
6,261✔
873
                    }
6,261✔
874
                    else {
36✔
875
                        index->insert(key, init_value.get<Timestamp>());
36✔
876
                    }
36✔
877
                    break;
6,297✔
878
                case col_type_ObjectId:
85,701✔
879
                    if (init_value.is_null()) {
85,701✔
880
                        index->insert(key, ArrayObjectIdNull::default_value(nullable));
6,120✔
881
                    }
6,120✔
882
                    else {
79,581✔
883
                        index->insert(key, init_value.get<ObjectId>());
79,581✔
884
                    }
79,581✔
885
                    break;
85,701✔
886
                case col_type_Mixed:
834✔
887
                    index->insert(key, init_value);
834✔
888
                    break;
834✔
889
                case col_type_UUID:
18,342✔
890
                    if (init_value.is_null()) {
18,342✔
891
                        index->insert(key, ArrayUUIDNull::default_value(nullable));
6,138✔
892
                    }
6,138✔
893
                    else {
12,204✔
894
                        index->insert(key, init_value.get<UUID>());
12,204✔
895
                    }
12,204✔
896
                    break;
18,342✔
897
                default:
✔
898
                    REALM_UNREACHABLE();
×
899
            }
1,132,692✔
900
        }
1,132,692✔
901
    }
33,989,562✔
902
}
23,128,461✔
903

904
void Table::clear_indexes()
905
{
3,555✔
906
    for (auto&& index : m_index_accessors) {
42,975✔
907
        if (index) {
42,975✔
908
            index->clear();
2,265✔
909
        }
2,265✔
910
    }
42,975✔
911
}
3,555✔
912

913
void Table::do_add_search_index(ColKey col_key, IndexType type)
914
{
132,921✔
915
    size_t column_ndx = col_key.get_index().val;
132,921✔
916

65,844✔
917
    // Early-out if already indexed
65,844✔
918
    if (m_index_accessors[column_ndx] != nullptr)
132,921✔
919
        return;
384✔
920

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

65,628✔
928
    // m_index_accessors always has the same number of pointers as the number of columns. Columns without search
65,628✔
929
    // index have 0-entries.
65,628✔
930
    REALM_ASSERT(m_index_accessors.size() == m_leaf_ndx2colkey.size());
132,489✔
931
    REALM_ASSERT(m_index_accessors[column_ndx] == nullptr);
132,489✔
932

65,628✔
933
    // Create the index
65,628✔
934
    m_index_accessors[column_ndx] =
132,489✔
935
        std::make_unique<StringIndex>(ClusterColumn(&m_clusters, col_key, type), get_alloc()); // Throws
132,489✔
936
    StringIndex* index = m_index_accessors[column_ndx].get();
132,489✔
937

65,628✔
938
    // Insert ref to index
65,628✔
939
    index->set_parent(&m_index_refs, column_ndx);
132,489✔
940
    m_index_refs.set(column_ndx, index->get_ref()); // Throws
132,489✔
941

65,628✔
942
    populate_search_index(col_key);
132,489✔
943
}
132,489✔
944

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

1,935✔
949
    // Check spec
1,935✔
950
    auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
3,903✔
951
    auto attr = m_spec.get_column_attr(spec_ndx);
3,903✔
952

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

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

1,920✔
981
    do_add_search_index(col_key, type);
3,873✔
982

1,920✔
983
    // Update spec
1,920✔
984
    attr.set(type == IndexType::Fulltext ? col_attr_FullText_Indexed : col_attr_Indexed);
3,846✔
985
    m_spec.set_column_attr(spec_ndx, attr); // Throws
3,873✔
986
}
3,873✔
987

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

3,582✔
993
    // Early-out if non-indexed
3,582✔
994
    if (m_index_accessors[column_ndx.val] == nullptr)
7,632✔
995
        return;
60✔
996

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

3,555✔
1003
    m_index_refs.set(column_ndx.val, 0);
7,572✔
1004

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

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

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

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

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

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

1042

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

1055

1056
ColKey Table::do_insert_root_column(ColKey col_key, ColumnType type, StringData name, DataType key_type)
1057
{
977,928✔
1058
    // if col_key specifies a key, it must be unused
482,409✔
1059
    REALM_ASSERT(!col_key || !valid_column(col_key));
977,928✔
1060

482,409✔
1061
    // locate insertion point: ordinary columns must come before backlink columns
482,409✔
1062
    size_t spec_ndx = (type == col_type_BackLink) ? m_spec.get_column_count() : m_spec.get_public_column_count();
933,294✔
1063

482,409✔
1064
    if (!col_key) {
977,928✔
1065
        col_key = generate_col_key(type, {});
88,284✔
1066
    }
88,284✔
1067

482,409✔
1068
    m_spec.insert_column(spec_ndx, col_key, type, name, col_key.get_attrs().m_value); // Throws
977,928✔
1069
    if (col_key.is_dictionary()) {
977,928✔
1070
        m_spec.set_dictionary_key_type(spec_ndx, key_type);
53,562✔
1071
    }
53,562✔
1072
    auto col_ndx = col_key.get_index().val;
977,928✔
1073
    build_column_mapping();
977,928✔
1074
    REALM_ASSERT(col_ndx <= m_index_refs.size());
977,928✔
1075
    if (col_ndx == m_index_refs.size()) {
977,928✔
1076
        m_index_refs.insert(col_ndx, 0);
977,652✔
1077
    }
977,652✔
1078
    else {
276✔
1079
        m_index_refs.set(col_ndx, 0);
276✔
1080
    }
276✔
1081
    REALM_ASSERT(col_ndx <= m_opposite_table.size());
977,928✔
1082
    if (col_ndx == m_opposite_table.size()) {
977,928✔
1083
        // m_opposite_table and m_opposite_column are always resized together!
482,265✔
1084
        m_opposite_table.insert(col_ndx, TableKey().value);
977,649✔
1085
        m_opposite_column.insert(col_ndx, ColKey().value);
977,649✔
1086
    }
977,649✔
1087
    else {
279✔
1088
        m_opposite_table.set(col_ndx, TableKey().value);
279✔
1089
        m_opposite_column.set(col_ndx, ColKey().value);
279✔
1090
    }
279✔
1091
    refresh_index_accessors();
977,928✔
1092
    m_clusters.insert_column(col_key);
977,928✔
1093
    if (m_tombstones) {
977,928✔
1094
        m_tombstones->insert_column(col_key);
6,825✔
1095
    }
6,825✔
1096

482,409✔
1097
    bump_storage_version();
977,928✔
1098

482,409✔
1099
    return col_key;
977,928✔
1100
}
977,928✔
1101

1102

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

8,295✔
1123
    build_column_mapping();
17,478✔
1124
    while (m_index_accessors.size() > m_leaf_ndx2colkey.size()) {
34,368✔
1125
        REALM_ASSERT(m_index_accessors.back() == nullptr);
16,890✔
1126
        m_index_accessors.pop_back();
16,890✔
1127
    }
16,890✔
1128
    bump_content_version();
17,478✔
1129
    bump_storage_version();
17,478✔
1130
}
17,478✔
1131

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1276

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

1283
void Table::fully_detach() noexcept
1284
{
5,384,811✔
1285
    m_spec.detach();
5,384,811✔
1286
    m_top.detach();
5,384,811✔
1287
    m_index_refs.detach();
5,384,811✔
1288
    m_opposite_table.detach();
5,384,811✔
1289
    m_opposite_column.detach();
5,384,811✔
1290
    m_index_accessors.clear();
5,384,811✔
1291
}
5,384,811✔
1292

1293

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

1309

1310
IndexType Table::search_index_type(ColKey col_key) const noexcept
1311
{
8,115,600✔
1312
    if (auto index = m_index_accessors[col_key.get_index().val].get()) {
8,115,600✔
1313
        return index->is_fulltext_index() ? IndexType::Fulltext : IndexType::General;
1,159,032✔
1314
    }
1,159,242✔
1315
    return IndexType::None;
6,956,358✔
1316
}
6,956,358✔
1317

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

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

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

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

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

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

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

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

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

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

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

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

1463
namespace {
1464

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

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

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

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

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

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

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

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

1522
    using Array::set_parent;
1523

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

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

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

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

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

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

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

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

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

1665
} // namespace
1666

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

78✔
1831
    /*************************** Create objects ******************************/
78✔
1832

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2060

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

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

2073

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

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

168,060✔
2097
    // Table key value
168,060✔
2098
    RefOrTagged rot = RefOrTagged::make_tagged(key.value);
338,781✔
2099
    top.add(rot);
338,781✔
2100

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

168,060✔
2138
    REALM_ASSERT(top.size() == top_array_size);
338,781✔
2139

168,060✔
2140
    return top.get_ref();
338,781✔
2141
}
338,781✔
2142

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

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

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

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

2178
void Table::batch_erase_objects(std::vector<ObjKey>& keys)
2179
{
5,325✔
2180
    Group* g = get_parent_group();
5,325✔
2181

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

2202
void Table::clear()
2203
{
3,555✔
2204
    CascadeState state(CascadeState::Mode::Strong, get_parent_group());
3,555✔
2205
    m_clusters.clear(state);
3,555✔
2206
    free_collision_table();
3,555✔
2207
}
3,555✔
2208

2209

2210
Group* Table::get_parent_group() const noexcept
2211
{
60,167,175✔
2212
    if (!m_top.is_attached())
60,167,175✔
2213
        return 0;                             // Subtable with shared descriptor
×
2214
    ArrayParent* parent = m_top.get_parent(); // ArrayParent guaranteed to be Table::Parent
60,167,175✔
2215
    if (!parent)
60,167,175✔
2216
        return 0; // Free-standing table
25,856,964✔
2217

16,985,496✔
2218
    return static_cast<Group*>(parent);
34,310,211✔
2219
}
34,310,211✔
2220

2221
inline uint64_t Table::get_sync_file_id() const noexcept
2222
{
38,921,751✔
2223
    Group* g = get_parent_group();
38,921,751✔
2224
    return g ? g->get_sync_file_id() : 0;
32,301,984✔
2225
}
38,921,751✔
2226

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

2237
uint64_t Table::allocate_sequence_number()
2238
{
19,982,652✔
2239
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_sequence_number);
19,982,652✔
2240
    uint64_t sn = rot.is_tagged() ? rot.get_as_int() : 0;
19,853,097✔
2241
    rot = RefOrTagged::make_tagged(sn + 1);
19,982,652✔
2242
    m_top.set(top_position_for_sequence_number, rot);
19,982,652✔
2243

9,928,068✔
2244
    return sn;
19,982,652✔
2245
}
19,982,652✔
2246

2247
void Table::set_sequence_number(uint64_t seq)
2248
{
156✔
2249
    m_top.set(top_position_for_sequence_number, RefOrTagged::make_tagged(seq));
156✔
2250
}
156✔
2251

2252
void Table::set_collision_map(ref_type ref)
2253
{
×
2254
    m_top.set(top_position_for_collision_map, RefOrTagged::make_ref(ref));
×
2255
}
×
2256

2257
TableRef Table::get_link_target(ColKey col_key) noexcept
2258
{
309,627✔
2259
    return get_opposite_table(col_key);
309,627✔
2260
}
309,627✔
2261

2262
// count ----------------------------------------------
2263

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

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

9✔
2297
    traverse_clusters(f);
18✔
2298

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

2309
template <typename T>
2310
void Table::aggregate(QueryStateBase& st, ColKey column_key) const
2311
{
27,759✔
2312
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
27,759✔
2313
    LeafType leaf(get_alloc());
27,759✔
2314

13,896✔
2315
    auto f = [&leaf, column_key, &st](const Cluster* cluster) {
27,777✔
2316
        // direct aggregate on the leaf
13,905✔
2317
        cluster->init_leaf(column_key, &leaf);
27,777✔
2318
        st.m_key_offset = cluster->get_offset();
27,777✔
2319
        st.m_key_values = cluster->get_key_array();
27,777✔
2320

13,905✔
2321
        bool cont = true;
27,777✔
2322
        size_t sz = leaf.size();
27,777✔
2323
        for (size_t local_index = 0; cont && local_index < sz; local_index++) {
120,414✔
2324
            auto v = leaf.get(local_index);
92,637✔
2325
            cont = st.match(local_index, v);
92,637✔
2326
        }
92,637✔
2327
        return IteratorControl::AdvanceToNext;
27,777✔
2328
    };
27,777✔
2329

13,896✔
2330
    traverse_clusters(f);
27,759✔
2331
}
27,759✔
2332

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

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

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

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

2357
std::optional<Mixed> Table::max(ColKey col_key, ObjKey* return_ndx) const
2358
{
21,483✔
2359
    return AggregateHelper<Table>::max(*this, *this, col_key, return_ndx);
21,483✔
2360
}
21,483✔
2361

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

17,565✔
2367
    if (!col_key.is_nullable() && value_is_null(value)) {
35,154!
2368
        return {}; // this is a precaution/optimization
6✔
2369
    }
6✔
2370
    // You cannot call GetIndexData on ObjKey
17,562✔
2371
    if constexpr (!std::is_same_v<T, ObjKey>) {
35,148✔
2372
        if (StringIndex* index = get_search_index(col_key)) {
35,130!
2373
            return index->find_first(value);
27,282✔
2374
        }
27,282✔
2375
        if (col_key == m_primary_key_col) {
7,848!
2376
            return find_primary_key(value);
×
2377
        }
×
2378
    }
7,848✔
2379

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

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

3,924✔
2394
    traverse_clusters(f);
7,848✔
2395

3,924✔
2396
    return key;
7,848✔
2397
}
7,848✔
2398

2399
namespace realm {
2400

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2524

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2604
util::Logger* Table::get_logger() const noexcept
2605
{
1,785,030✔
2606
    return *m_repl ? (*m_repl)->get_logger() : nullptr;
2,148,377,407✔
2607
}
1,785,030✔
2608

2609
// Called after a commit. Table will effectively contain the same as before,
2610
// but now with new refs from the file
2611
void Table::update_from_parent() noexcept
2612
{
811,155✔
2613
    // There is no top for sub-tables sharing spec
403,845✔
2614
    if (m_top.is_attached()) {
811,155✔
2615
        m_top.update_from_parent();
811,155✔
2616
        m_spec.update_from_parent();
811,155✔
2617
        m_clusters.update_from_parent();
811,155✔
2618
        m_index_refs.update_from_parent();
811,155✔
2619
        for (auto&& index : m_index_accessors) {
2,649,606✔
2620
            if (index != nullptr) {
2,649,606✔
2621
                index->update_from_parent();
272,916✔
2622
            }
272,916✔
2623
        }
2,649,606✔
2624

403,845✔
2625
        m_opposite_table.update_from_parent();
811,155✔
2626
        m_opposite_column.update_from_parent();
811,155✔
2627
        if (m_top.size() > top_position_for_flags) {
811,155✔
2628
            uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
809,319✔
2629
            m_table_type = Type(flags & table_type_mask);
809,319✔
2630
        }
809,319✔
2631
        else {
1,836✔
2632
            m_table_type = Type::TopLevel;
1,836✔
2633
        }
1,836✔
2634
        if (m_tombstones)
811,155✔
2635
            m_tombstones->update_from_parent();
1,278✔
2636

403,845✔
2637
        refresh_content_version();
811,155✔
2638
        m_has_any_embedded_objects.reset();
811,155✔
2639
    }
811,155✔
2640
    m_alloc.bump_storage_version();
811,155✔
2641
}
811,155✔
2642

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

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

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

150✔
2722
    out << "]";
300✔
2723
}
300✔
2724

2725

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

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

63✔
2757
    return true;
117✔
2758
}
126✔
2759

2760

2761
void Table::flush_for_commit()
2762
{
4,008,195✔
2763
    if (m_top.is_attached() && m_top.size() >= top_position_for_version) {
4,008,201✔
2764
        if (!m_top.is_read_only()) {
4,008,189✔
2765
            ++m_in_file_version_at_transaction_boundary;
1,242,540✔
2766
            auto rot_version = RefOrTagged::make_tagged(m_in_file_version_at_transaction_boundary);
1,242,540✔
2767
            m_top.set(top_position_for_version, rot_version);
1,242,540✔
2768
        }
1,242,540✔
2769
    }
4,008,189✔
2770
}
4,008,195✔
2771

2772
void Table::refresh_content_version()
2773
{
1,143,468✔
2774
    REALM_ASSERT(m_top.is_attached());
1,143,468✔
2775
    if (m_top.size() >= top_position_for_version) {
1,143,468✔
2776
        // we have versioning info in the file. Use this to conditionally
593,631✔
2777
        // bump the version counter:
593,631✔
2778
        auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
1,143,213✔
2779
        REALM_ASSERT(rot_version.is_tagged());
1,143,213✔
2780
        if (m_in_file_version_at_transaction_boundary != rot_version.get_as_int()) {
1,143,213✔
2781
            m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
201,507✔
2782
            bump_content_version();
201,507✔
2783
        }
201,507✔
2784
    }
1,143,213✔
2785
    else {
255✔
2786
        // assume the worst:
246✔
2787
        bump_content_version();
255✔
2788
    }
255✔
2789
}
1,143,468✔
2790

2791

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

2830
void Table::refresh_index_accessors()
2831
{
6,707,244✔
2832
    // Refresh search index accessors
3,806,508✔
2833

3,806,508✔
2834
    // First eliminate any index accessors for eliminated last columns
3,806,508✔
2835
    size_t col_ndx_end = m_leaf_ndx2colkey.size();
6,707,244✔
2836
    m_index_accessors.resize(col_ndx_end);
6,707,244✔
2837

3,806,508✔
2838
    // Then eliminate/refresh/create accessors within column range
3,806,508✔
2839
    // we can not use for_each_column() here, since the columns may have changed
3,806,508✔
2840
    // and the index accessor vector is not updated correspondingly.
3,806,508✔
2841
    for (size_t col_ndx = 0; col_ndx < col_ndx_end; col_ndx++) {
28,866,474✔
2842
        ref_type ref = m_index_refs.get_as_ref(col_ndx);
22,159,230✔
2843

11,862,801✔
2844
        if (ref == 0) {
22,159,230✔
2845
            // accessor drop
9,818,508✔
2846
            m_index_accessors[col_ndx].reset();
18,137,091✔
2847
        }
18,137,091✔
2848
        else {
4,022,139✔
2849
            auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_ndx]);
4,022,139✔
2850
            bool fulltext = attr.test(col_attr_FullText_Indexed);
4,022,139✔
2851
            auto col_key = m_leaf_ndx2colkey[col_ndx];
4,022,139✔
2852
            ClusterColumn virtual_col(&m_clusters, col_key, fulltext ? IndexType::Fulltext : IndexType::General);
4,022,124✔
2853

2,044,293✔
2854
            if (m_index_accessors[col_ndx]) { // still there, refresh:
4,022,139✔
2855
                m_index_accessors[col_ndx]->refresh_accessor_tree(virtual_col);
473,703✔
2856
            }
473,703✔
2857
            else { // new index!
3,548,436✔
2858
                m_index_accessors[col_ndx] =
3,548,436✔
2859
                    std::make_unique<StringIndex>(ref, &m_index_refs, col_ndx, virtual_col, get_alloc());
3,548,436✔
2860
            }
3,548,436✔
2861
        }
4,022,139✔
2862
    }
22,159,230✔
2863
}
6,707,244✔
2864

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

2877
// LCOV_EXCL_START ignore debug functions
2878

2879
void Table::verify() const
2880
{
2,993,430✔
2881
#ifdef REALM_DEBUG
2,993,430✔
2882
    if (m_top.is_attached())
2,993,430✔
2883
        m_top.verify();
2,993,424✔
2884
    m_spec.verify();
2,993,430✔
2885
    m_clusters.verify();
2,993,430✔
2886
    if (nb_unresolved())
2,993,430✔
2887
        m_tombstones->verify();
795,789✔
2888
#endif
2,993,430✔
2889
}
2,993,430✔
2890

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

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

11,274,744✔
2920
    REALM_ASSERT(key.value >= 0);
22,643,751✔
2921

11,274,744✔
2922
    Obj obj = m_clusters.insert(key, values); // repl->set()
22,643,751✔
2923

11,274,744✔
2924
    return obj;
22,643,751✔
2925
}
22,643,751✔
2926

2927
Obj Table::create_linked_object()
2928
{
39,702✔
2929
    REALM_ASSERT(is_embedded());
39,702✔
2930

19,758✔
2931
    GlobalKey object_id = allocate_object_id_squeezed();
39,702✔
2932
    ObjKey key = object_id.get_local_key(get_sync_file_id());
39,702✔
2933

19,758✔
2934
    REALM_ASSERT(key.value >= 0);
39,702✔
2935

19,758✔
2936
    Obj obj = m_clusters.insert(key, {});
39,702✔
2937

19,758✔
2938
    return obj;
39,702✔
2939
}
39,702✔
2940

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

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

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

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

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

286,038✔
2982
    DataType type = DataType(primary_key_col.get_type());
589,290✔
2983

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

286,035✔
2990
    if (!(primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) &&
589,284✔
2991
        primary_key.get_type() != type) {
589,068✔
2992
        throw InvalidArgument(ErrorCodes::TypeMismatch, util::format("Wrong primary key type for class %1",
6✔
2993
                                                                     Group::table_name_to_class_name(get_name())));
6✔
2994
    }
6✔
2995

286,032✔
2996
    REALM_ASSERT(type == type_String || type == type_ObjectId || type == type_Int || type == type_UUID);
589,278✔
2997

286,032✔
2998
    if (did_create)
589,278✔
2999
        *did_create = false;
74,409✔
3000

286,032✔
3001
    // Check for existing object
286,032✔
3002
    if (ObjKey key = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key)) {
589,278✔
3003
        if (mode == UpdateMode::never) {
82,266✔
3004
            throw ObjectAlreadyExists(this->get_class_name(), primary_key);
6✔
3005
        }
6✔
3006
        auto obj = m_clusters.get(key);
82,260✔
3007
        for (auto& val : field_values) {
41,898✔
3008
            if (mode == UpdateMode::all || obj.get_any(val.col_key) != val.value) {
12✔
3009
                obj.set_any(val.col_key, val.value, val.is_default);
12✔
3010
            }
12✔
3011
        }
12✔
3012
        return obj;
82,260✔
3013
    }
82,260✔
3014

244,137✔
3015
    ObjKey unres_key;
507,012✔
3016
    if (m_tombstones) {
507,012✔
3017
        // Check for potential tombstone
20,988✔
3018
        GlobalKey object_id{primary_key};
40,866✔
3019
        ObjKey object_key = global_to_local_object_id_hashed(object_id);
40,866✔
3020

20,988✔
3021
        ObjKey key = object_key.get_unresolved();
40,866✔
3022
        if (auto obj = m_tombstones->try_get_obj(key)) {
40,866✔
3023
            auto existing_pk_value = obj.get_any(primary_key_col);
13,362✔
3024

6,828✔
3025
            // If the primary key is the same, the object should be resurrected below
6,828✔
3026
            if (existing_pk_value == primary_key) {
13,362✔
3027
                unres_key = key;
13,356✔
3028
            }
13,356✔
3029
        }
13,362✔
3030
    }
40,866✔
3031

244,137✔
3032
    ObjKey key = get_next_valid_key();
507,012✔
3033

244,137✔
3034
    auto repl = get_repl();
507,012✔
3035
    if (repl) {
507,012✔
3036
        repl->create_object_with_primary_key(this, key, primary_key);
445,917✔
3037
    }
445,917✔
3038
    if (did_create) {
507,012✔
3039
        *did_create = true;
36,345✔
3040
    }
36,345✔
3041

244,137✔
3042
    field_values.insert(primary_key_col, primary_key);
507,012✔
3043
    Obj ret = m_clusters.insert(key, field_values);
507,012✔
3044

244,137✔
3045
    // Check if unresolved exists
244,137✔
3046
    if (unres_key) {
507,012✔
3047
        auto tombstone = m_tombstones->get(unres_key);
13,356✔
3048
        ret.assign_pk_and_backlinks(tombstone);
13,356✔
3049
        // If tombstones had no links to it, it may still be alive
6,825✔
3050
        if (m_tombstones->is_valid(unres_key)) {
13,356✔
3051
            CascadeState state(CascadeState::Mode::None);
4,200✔
3052
            m_tombstones->erase(unres_key, state);
4,200✔
3053
        }
4,200✔
3054
    }
13,356✔
3055
    if (is_asymmetric() && repl && repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
507,012✔
3056
        get_parent_group()->m_objects_to_delete.emplace_back(this->m_key, ret.get_key());
1,284✔
3057
    }
1,284✔
3058
    return ret;
507,012✔
3059
}
507,012✔
3060

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

464,493✔
3069
    if (auto&& index = m_index_accessors[primary_key_col.get_index().val]) {
923,832✔
3070
        return index->find_first(primary_key);
923,790✔
3071
    }
923,790✔
3072

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

33✔
3078
    // Check if existing
33✔
3079
    if (auto obj = m_clusters.try_get_obj(object_key)) {
42✔
3080
        auto existing_pk_value = obj.get_any(primary_key_col);
×
3081

3082
        if (existing_pk_value == primary_key) {
×
3083
            return object_key;
×
3084
        }
×
3085
    }
42✔
3086
    return {};
42✔
3087
}
42✔
3088

3089
ObjKey Table::get_objkey_from_primary_key(const Mixed& primary_key)
3090
{
752,430✔
3091
    // Check if existing
376,905✔
3092
    if (auto key = find_primary_key(primary_key)) {
752,430✔
3093
        return key;
721,008✔
3094
    }
721,008✔
3095

16,125✔
3096
    // Object does not exist - create tombstone
16,125✔
3097
    GlobalKey object_id{primary_key};
31,422✔
3098
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
31,422✔
3099
    return get_or_create_tombstone(object_key, m_primary_key_col, primary_key).get_key();
31,422✔
3100
}
31,422✔
3101

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

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

3✔
3112
    return get_or_create_tombstone(object_key, {}, {}).get_key();
6✔
3113
}
6✔
3114

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

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

3143
Obj Table::get_object_with_primary_key(Mixed primary_key) const
3144
{
62,754✔
3145
    auto primary_key_col = get_primary_key_column();
62,754✔
3146
    REALM_ASSERT(primary_key_col);
62,754✔
3147
    DataType type = DataType(primary_key_col.get_type());
62,754✔
3148
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
62,754✔
3149
                 primary_key.get_type() == type);
62,754✔
3150
    return m_clusters.get(m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key));
62,754✔
3151
}
62,754✔
3152

3153
Mixed Table::get_primary_key(ObjKey key) const
3154
{
617,115✔
3155
    auto primary_key_col = get_primary_key_column();
617,115✔
3156
    REALM_ASSERT(primary_key_col);
617,115✔
3157
    if (key.is_unresolved()) {
617,115✔
3158
        REALM_ASSERT(m_tombstones);
72✔
3159
        return m_tombstones->get(key).get_any(primary_key_col);
72✔
3160
    }
72✔
3161
    else {
617,043✔
3162
        return m_clusters.get(key).get_any(primary_key_col);
617,043✔
3163
    }
617,043✔
3164
}
617,115✔
3165

3166
GlobalKey Table::allocate_object_id_squeezed()
3167
{
19,527,846✔
3168
    // m_client_file_ident will be zero if we haven't been in contact with
9,713,688✔
3169
    // the server yet.
9,713,688✔
3170
    auto peer_id = get_sync_file_id();
19,527,846✔
3171
    auto sequence = allocate_sequence_number();
19,527,846✔
3172
    return GlobalKey{peer_id, sequence};
19,527,846✔
3173
}
19,527,846✔
3174

3175
namespace {
3176

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

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

3198
} // namespace
3199

3200
ObjKey Table::global_to_local_object_id_hashed(GlobalKey object_id) const
3201
{
72,660✔
3202
    ObjKey optimistic = get_optimistic_local_id_hashed(object_id);
72,660✔
3203

37,299✔
3204
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
72,660✔
3205
        Allocator& alloc = m_top.get_alloc();
24✔
3206
        Array collision_map{alloc};
24✔
3207
        collision_map.init_from_ref(collision_map_ref); // Throws
24✔
3208

12✔
3209
        Array hi{alloc};
24✔
3210
        hi.init_from_ref(to_ref(collision_map.get(s_collision_map_hi))); // Throws
24✔
3211

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

37,287✔
3226
    return optimistic;
72,636✔
3227
}
72,636✔
3228

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

6✔
3239
    collision_map.set_parent(&m_top, top_position_for_collision_map);
12✔
3240
    hi.set_parent(&collision_map, s_collision_map_hi);
12✔
3241
    lo.set_parent(&collision_map, s_collision_map_lo);
12✔
3242
    local_id.set_parent(&collision_map, s_collision_map_local_id);
12✔
3243

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

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

6✔
3261
    hi.init_from_parent();       // Throws
12✔
3262
    lo.init_from_parent();       // Throws
12✔
3263
    local_id.init_from_parent(); // Throws
12✔
3264

6✔
3265
    size_t num_entries = hi.size();
12✔
3266
    REALM_ASSERT(lo.size() == num_entries);
12✔
3267
    REALM_ASSERT(local_id.size() == num_entries);
12✔
3268

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

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

6✔
3291
    auto sequence_number_for_local_id = allocate_sequence_number();
12✔
3292
    ObjKey new_local_id = make_tagged_local_id_after_hash_collision(sequence_number_for_local_id);
12✔
3293
    insert_collision(incoming_id, new_local_id);
12✔
3294
    insert_collision(colliding_id, colliding_local_id);
12✔
3295

6✔
3296
    return new_local_id;
12✔
3297
}
12✔
3298

3299
Obj Table::get_or_create_tombstone(ObjKey key, ColKey pk_col, Mixed pk_val)
3300
{
31,968✔
3301
    auto unres_key = key.get_unresolved();
31,968✔
3302

16,398✔
3303
    ensure_graveyard();
31,968✔
3304
    auto tombstone = m_tombstones->try_get_obj(unres_key);
31,968✔
3305
    if (tombstone) {
31,968✔
3306
        if (pk_col) {
3,126✔
3307
            auto existing_pk_value = tombstone.get_any(pk_col);
3,126✔
3308
            // It may just be the same object
1,554✔
3309
            if (existing_pk_value != pk_val) {
3,126✔
3310
                // We have a collision - create new ObjKey
6✔
3311
                key = allocate_local_id_after_hash_collision({pk_val}, {existing_pk_value}, key);
12✔
3312
                return get_or_create_tombstone(key, pk_col, pk_val);
12✔
3313
            }
12✔
3314
        }
3,114✔
3315
        return tombstone;
3,114✔
3316
    }
3,114✔
3317
    return m_tombstones->insert(unres_key, {{pk_col, pk_val}});
28,842✔
3318
}
28,842✔
3319

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

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

12✔
3340
            hi.set_parent(&collision_map, s_collision_map_hi);
24✔
3341
            lo.set_parent(&collision_map, s_collision_map_lo);
24✔
3342
            hi.init_from_parent();
24✔
3343
            lo.init_from_parent();
24✔
3344

12✔
3345
            hi.erase(ndx);
24✔
3346
            lo.erase(ndx);
24✔
3347
            local_id.erase(ndx);
24✔
3348
            if (hi.size() == 0) {
24✔
3349
                free_collision_table();
12✔
3350
            }
12✔
3351
        }
24✔
3352
    }
30✔
3353
}
5,029,377✔
3354

3355
void Table::free_collision_table()
3356
{
3,567✔
3357
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
3,567✔
3358
        Array::destroy_deep(collision_map_ref, m_alloc);
12✔
3359
        m_top.set(top_position_for_collision_map, 0);
12✔
3360
    }
12✔
3361
}
3,567✔
3362

3363
void Table::create_objects(size_t number, std::vector<ObjKey>& keys)
3364
{
3,840✔
3365
    while (number--) {
6,321,252✔
3366
        keys.push_back(create_object().get_key());
6,317,412✔
3367
    }
6,317,412✔
3368
}
3,840✔
3369

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

3377
void Table::dump_objects()
3378
{
×
3379
    m_clusters.dump_objects();
×
3380
    if (nb_unresolved())
×
3381
        m_tombstones->dump_objects();
×
3382
}
×
3383

3384
void Table::remove_object(ObjKey key)
3385
{
2,491,467✔
3386
    Group* g = get_parent_group();
2,491,467✔
3387

1,246,473✔
3388
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
2,491,467✔
3389
        CascadeState state(CascadeState::Mode::Strong, g);
3,762✔
3390
        state.m_to_be_deleted.emplace_back(m_key, key);
3,762✔
3391
        m_clusters.nullify_links(key, state);
3,762✔
3392
        remove_recursive(state);
3,762✔
3393
    }
3,762✔
3394
    else {
2,487,705✔
3395
        CascadeState state(CascadeState::Mode::None, g);
2,487,705✔
3396
        if (g) {
2,487,705✔
3397
            m_clusters.nullify_links(key, state);
2,405,793✔
3398
        }
2,405,793✔
3399
        m_clusters.erase(key, state);
2,487,705✔
3400
    }
2,487,705✔
3401
}
2,491,467✔
3402

3403
ObjKey Table::invalidate_object(ObjKey key)
3404
{
64,854✔
3405
    if (is_embedded())
64,854✔
3406
        throw IllegalOperation("Deletion of embedded object not allowed");
×
3407
    REALM_ASSERT(!key.is_unresolved());
64,854✔
3408

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

33,159✔
3426
    remove_object(key);
64,854✔
3427

33,159✔
3428
    return tombstone.get_key();
64,854✔
3429
}
64,854✔
3430

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

3447
Table::Iterator Table::begin() const
3448
{
661,341✔
3449
    return Iterator(m_clusters, 0);
661,341✔
3450
}
661,341✔
3451

3452
Table::Iterator Table::end() const
3453
{
9,678,861✔
3454
    return Iterator(m_clusters, size());
9,678,861✔
3455
}
9,678,861✔
3456

3457
TableRef _impl::TableFriend::get_opposite_link_table(const Table& table, ColKey col_key)
3458
{
7,087,233✔
3459
    TableRef ret;
7,087,233✔
3460
    if (col_key) {
7,087,434✔
3461
        return table.get_opposite_table(col_key);
7,087,434✔
3462
    }
7,087,434✔
3463
    return ret;
4,294,967,294✔
3464
}
4,294,967,294✔
3465

3466
const uint64_t Table::max_num_columns;
3467

3468
void Table::build_column_mapping()
3469
{
6,730,302✔
3470
    // build column mapping from spec
3,818,571✔
3471
    // TODO: Optimization - Don't rebuild this for every change
3,818,571✔
3472
    m_spec_ndx2leaf_ndx.clear();
6,730,302✔
3473
    m_leaf_ndx2spec_ndx.clear();
6,730,302✔
3474
    m_leaf_ndx2colkey.clear();
6,730,302✔
3475
    size_t num_spec_cols = m_spec.get_column_count();
6,730,302✔
3476
    m_spec_ndx2leaf_ndx.resize(num_spec_cols);
6,730,302✔
3477
    for (size_t spec_ndx = 0; spec_ndx < num_spec_cols; ++spec_ndx) {
28,857,744✔
3478
        ColKey col_key = m_spec.get_key(spec_ndx);
22,127,442✔
3479
        unsigned leaf_ndx = col_key.get_index().val;
22,127,442✔
3480
        if (leaf_ndx >= m_leaf_ndx2colkey.size()) {
22,127,442✔
3481
            m_leaf_ndx2colkey.resize(leaf_ndx + 1);
21,661,068✔
3482
            m_leaf_ndx2spec_ndx.resize(leaf_ndx + 1, -1);
21,661,068✔
3483
        }
21,661,068✔
3484
        m_spec_ndx2leaf_ndx[spec_ndx] = ColKey::Idx{leaf_ndx};
22,127,442✔
3485
        m_leaf_ndx2spec_ndx[leaf_ndx] = spec_ndx;
22,127,442✔
3486
        m_leaf_ndx2colkey[leaf_ndx] = col_key;
22,127,442✔
3487
    }
22,127,442✔
3488
}
6,730,302✔
3489

3490
ColKey Table::generate_col_key(ColumnType tp, ColumnAttrMask attr)
3491
{
977,928✔
3492
    REALM_ASSERT(!attr.test(col_attr_Indexed));
977,928✔
3493
    REALM_ASSERT(!attr.test(col_attr_Unique)); // Must not be encoded into col_key
977,928✔
3494

482,409✔
3495
    int64_t col_seq_number = m_top.get_as_ref_or_tagged(top_position_for_column_key).get_as_int();
977,928✔
3496
    unsigned upper = unsigned(col_seq_number ^ get_key().value);
977,928✔
3497

482,409✔
3498
    // reuse lowest available leaf ndx:
482,409✔
3499
    unsigned lower = unsigned(m_leaf_ndx2colkey.size());
977,928✔
3500
    // look for an unused entry:
482,409✔
3501
    for (unsigned idx = 0; idx < lower; ++idx) {
6,242,901✔
3502
        if (m_leaf_ndx2colkey[idx] == ColKey()) {
5,265,075✔
3503
            lower = idx;
102✔
3504
            break;
102✔
3505
        }
102✔
3506
    }
5,265,075✔
3507
    return ColKey(ColKey::Idx{lower}, tp, attr, upper);
977,928✔
3508
}
977,928✔
3509

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

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

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

3563
ColKey Table::get_primary_key_column() const
3564
{
19,800,816✔
3565
    return m_primary_key_col;
19,800,816✔
3566
}
19,800,816✔
3567

3568
void Table::set_primary_key_column(ColKey col_key)
3569
{
720✔
3570
    if (col_key == m_primary_key_col) {
720✔
3571
        return;
378✔
3572
    }
378✔
3573

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

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

171✔
3584
    if (col_key) {
342✔
3585
        check_column(col_key);
222✔
3586
        validate_column_is_unique(col_key);
222✔
3587
        do_set_primary_key_column(col_key);
222✔
3588
    }
222✔
3589
    else {
120✔
3590
        do_set_primary_key_column(col_key);
120✔
3591
    }
120✔
3592
}
342✔
3593

3594

3595
void Table::do_set_primary_key_column(ColKey col_key)
3596
{
136,218✔
3597
    if (col_key) {
136,218✔
3598
        auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
128,796✔
3599
        auto attr = m_spec.get_column_attr(spec_ndx);
128,796✔
3600
        if (attr.test(col_attr_FullText_Indexed)) {
128,796✔
3601
            throw InvalidColumnKey("primary key cannot have a full text index");
6✔
3602
        }
6✔
3603
    }
136,212✔
3604

67,287✔
3605
    if (m_primary_key_col) {
136,212✔
3606
        // If the search index has not been set explicitly on current pk col, we remove it again
3,447✔
3607
        auto spec_ndx = leaf_ndx2spec_ndx(m_primary_key_col.get_index());
7,329✔
3608
        auto attr = m_spec.get_column_attr(spec_ndx);
7,329✔
3609
        if (!attr.test(col_attr_Indexed)) {
7,329✔
3610
            remove_search_index(m_primary_key_col);
7,317✔
3611
        }
7,317✔
3612
    }
7,329✔
3613

67,287✔
3614
    if (col_key) {
136,212✔
3615
        m_top.set(top_position_for_pk_col, RefOrTagged::make_tagged(col_key.value));
128,790✔
3616
        do_add_search_index(col_key, IndexType::General);
128,790✔
3617
    }
128,790✔
3618
    else {
7,422✔
3619
        m_top.set(top_position_for_pk_col, 0);
7,422✔
3620
    }
7,422✔
3621

67,287✔
3622
    m_primary_key_col = col_key;
136,212✔
3623
}
136,212✔
3624

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

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

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

3653
ObjKey Table::get_next_valid_key()
3654
{
507,012✔
3655
    ObjKey key;
507,012✔
3656
    do {
507,018✔
3657
        key = ObjKey(allocate_sequence_number());
507,018✔
3658
    } while (m_clusters.is_valid(key));
507,018✔
3659

244,137✔
3660
    return key;
507,012✔
3661
}
507,012✔
3662

3663
namespace {
3664
template <class T>
3665
typename util::RemoveOptional<T>::type remove_optional(T val)
3666
{
87,966✔
3667
    return val;
87,966✔
3668
}
87,966✔
3669
template <>
3670
int64_t remove_optional<Optional<int64_t>>(Optional<int64_t> val)
3671
{
5,415✔
3672
    return *val;
5,415✔
3673
}
5,415✔
3674
template <>
3675
bool remove_optional<Optional<bool>>(Optional<bool> val)
3676
{
11,484✔
3677
    return *val;
11,484✔
3678
}
11,484✔
3679
template <>
3680
ObjectId remove_optional<Optional<ObjectId>>(Optional<ObjectId> val)
3681
{
5,457✔
3682
    return *val;
5,457✔
3683
}
5,457✔
3684
template <>
3685
UUID remove_optional<Optional<UUID>>(Optional<UUID> val)
3686
{
6,060✔
3687
    return *val;
6,060✔
3688
}
6,060✔
3689
} // namespace
3690

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

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

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

81✔
3722
    m_clusters.update(func);
162✔
3723
}
162✔
3724

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

60✔
3733
        ArrayInteger from_arr(allocator);
120✔
3734
        ArrayInteger to_arr(allocator);
120✔
3735
        cluster->init_leaf(key_from, &from_arr);
120✔
3736
        cluster->init_leaf(key_to, &to_arr);
120✔
3737

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

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

60✔
3770
    m_clusters.update(func);
120✔
3771
}
120✔
3772

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

3894

3895
ColKey Table::set_nullability(ColKey col_key, bool nullable, bool throw_on_null)
3896
{
522✔
3897
    if (col_key.is_nullable() == nullable)
522✔
3898
        return col_key;
240✔
3899

141✔
3900
    check_column(col_key);
282✔
3901

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

141✔
3914
    ColKey new_col = generate_col_key(type, attr);
282✔
3915
    do_insert_root_column(new_col, type, "__temporary");
282✔
3916

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

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

138✔
3933
    erase_root_column(col_key);
276✔
3934
    m_spec.rename_column(colkey2spec_ndx(new_col), column_name);
276✔
3935

138✔
3936
    if (index_type != IndexType::None)
276✔
3937
        do_add_search_index(new_col, index_type);
30✔
3938

138✔
3939
    return new_col;
276✔
3940
}
276✔
3941

3942
bool Table::has_any_embedded_objects()
3943
{
2,496,762✔
3944
    if (!m_has_any_embedded_objects) {
2,496,762✔
3945
        m_has_any_embedded_objects = false;
111,381✔
3946
        for_each_public_column([&](ColKey col_key) {
224,823✔
3947
            auto target_table_key = get_opposite_table_key(col_key);
224,823✔
3948
            if (target_table_key && is_link_type(col_key.get_type())) {
224,823✔
3949
                auto target_table = get_parent_group()->get_table(target_table_key);
9,795✔
3950
                if (target_table->is_embedded()) {
9,795✔
3951
                    m_has_any_embedded_objects = true;
7,674✔
3952
                    return IteratorControl::Stop; // early out
7,674✔
3953
                }
7,674✔
3954
            }
217,149✔
3955
            return IteratorControl::AdvanceToNext;
217,149✔
3956
        });
217,149✔
3957
    }
111,381✔
3958
    return *m_has_any_embedded_objects;
2,496,762✔
3959
}
2,496,762✔
3960

3961
void Table::set_opposite_column(ColKey col_key, TableKey opposite_table, ColKey opposite_column)
3962
{
169,644✔
3963
    m_opposite_table.set(col_key.get_index().val, opposite_table.value);
169,644✔
3964
    m_opposite_column.set(col_key.get_index().val, opposite_column.value);
169,644✔
3965
}
169,644✔
3966

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

20,709✔
3975
    return {};
24,177✔
3976
}
41,652✔
3977

3978
ColKey Table::find_or_add_backlink_column(ColKey origin_col_key, TableKey origin_table)
3979
{
41,004✔
3980
    ColKey backlink_col_key = find_backlink_column(origin_col_key, origin_table);
41,004✔
3981

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

3,468✔
3986
        if (Replication* repl = get_repl())
6,936✔
3987
            repl->typed_link_change(get_parent_group()->get_table(origin_table).unchecked_ptr(), origin_col_key,
6,606✔
3988
                                    m_key); // Throws
6,606✔
3989
    }
6,936✔
3990

20,385✔
3991
    return backlink_col_key;
41,004✔
3992
}
41,004✔
3993

3994
TableKey Table::get_opposite_table_key(ColKey col_key) const
3995
{
14,503,599✔
3996
    return TableKey(int32_t(m_opposite_table.get(col_key.get_index().val)));
14,503,599✔
3997
}
14,503,599✔
3998

3999
bool Table::links_to_self(ColKey col_key) const
4000
{
52,995✔
4001
    return get_opposite_table_key(col_key) == m_key;
52,995✔
4002
}
52,995✔
4003

4004
TableRef Table::get_opposite_table(ColKey col_key) const
4005
{
7,716,675✔
4006
    if (auto k = get_opposite_table_key(col_key)) {
7,716,675✔
4007
        return get_parent_group()->get_table(k);
7,663,428✔
4008
    }
7,663,428✔
4009
    return {};
53,247✔
4010
}
53,247✔
4011

4012
ColKey Table::get_opposite_column(ColKey col_key) const
4013
{
7,055,595✔
4014
    return ColKey(m_opposite_column.get(col_key.get_index().val));
7,055,595✔
4015
}
7,055,595✔
4016

4017
ColKey Table::find_opposite_column(ColKey col_key) const
4018
{
×
4019
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
×
4020
        if (m_opposite_column.get(i) == col_key.value) {
×
4021
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
×
4022
        }
×
4023
    }
×
4024
    return ColKey();
×
4025
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc