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

realm / realm-core / 1787

28 Oct 2023 12:35PM UTC coverage: 91.591% (+0.009%) from 91.582%
1787

push

Evergreen

web-flow
Improve configurations for sanitized builds (#6911)

* Refactor sanitizer flags for different build types:

** Enable address sanitizer for msvc
** Allow to build with sanitizer for diffent optimized build (also Debug)
** Make RelASAN, RelTSAN, RelUSAN, RelUSAN just shortcuts for half-optimized builds

* Fix usage of moved object for fuzz tester
* Check asan/tsan on macos x64/arm64
* Check asan with msvc 2019
* Remove Jenkins sanitized builders replaced by evergreen configs
* Work-around stack-use-after-scope with msvc2019 and mpark
* Fix crash on check with staled ColKeys
* fix a buffer overrun in a test
* fix a race in async_open_realm test util
* Add some logger related test fixes
* Work around catch2 limmitation with not thread safe asserts and TSAN races
* Run multiprocesses tests under sanitizers
* add assert for an error reported by undefined sanitizer
* Workaround uv scheduler main thread only constraint for callbacks called from non main thread and requesting a realm

---------

Co-authored-by: James Stone <james.stone@mongodb.com>

94356 of 173648 branches covered (0.0%)

54 of 63 new or added lines in 15 files covered. (85.71%)

2202 existing lines in 52 files now uncovered.

230692 of 251872 relevant lines covered (91.59%)

7167285.55 hits per line

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

90.61
/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
{
19,191✔
327
    switch (table_type) {
19,191✔
328
        case Table::Type::TopLevel:
19,149✔
329
            return o << "TopLevel";
19,149✔
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,951✔
341
    // Link column can be a single Link, LinkList, or BackLink.
43,974✔
342
    REALM_ASSERT(m_current_table->valid_column(ck));
87,951✔
343
    ColumnType type = ck.get_type();
87,951✔
344
    if (type == col_type_LinkList || type == col_type_Link || type == col_type_BackLink) {
87,951✔
345
        m_current_table = m_current_table->get_opposite_table(ck);
85,389✔
346
    }
85,389✔
347
    else {
2,562✔
348
        // Only last column in link chain is allowed to be non-link
1,281✔
349
        throw LogicError(ErrorCodes::TypeMismatch,
2,562✔
350
                         util::format("Property '%1.%2' is not an object reference",
2,562✔
351
                                      m_current_table->get_class_name(), m_current_table->get_column_name(ck)));
2,562✔
352
    }
2,562✔
353
    m_link_cols.push_back(ck);
85,389✔
354
}
85,389✔
355

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

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

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

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

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

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

248,121✔
408
    return do_insert_column(col_key, type, name, invalid_link); // Throws
505,161✔
409
}
505,161✔
410

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

14,661✔
423
    m_has_any_embedded_objects.reset();
29,544✔
424

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

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

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

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

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

14,934✔
467
    m_has_any_embedded_objects.reset();
30,309✔
468

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

14,934✔
473
    return do_insert_column(col_key, type_LinkList, name, &target); // Throws
30,309✔
474
}
30,309✔
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,079✔
543
    Group* group = get_parent_group();
14,079✔
544
    REALM_ASSERT(group);
14,079✔
545
    cascade_state.m_group = group;
14,079✔
546

6,375✔
547
    do {
18,099✔
548
        cascade_state.send_notifications();
18,099✔
549

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

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

570
void Table::nullify_links(CascadeState& cascade_state)
571
{
22,698✔
572
    Group* group = get_parent_group();
22,698✔
573
    REALM_ASSERT(group);
22,698✔
574
    for (auto& to_delete : cascade_state.m_to_be_deleted) {
14,634✔
575
        auto table = to_delete.first == m_key ? this : group->get_table_unchecked(to_delete.first);
6,948✔
576
        if (!table->is_asymmetric())
7,881✔
577
            table->m_clusters.nullify_incoming_links(to_delete.second, cascade_state);
7,881✔
578
    }
7,881✔
579
}
22,698✔
580

581

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

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

8,487✔
589
    if (col_key == m_primary_key_col) {
17,628✔
590
        do_set_primary_key_column(ColKey());
7,584✔
591
    }
7,584✔
592
    else {
10,044✔
593
        REALM_ASSERT_RELEASE(m_primary_key_col.get_index().val != col_key.get_index().val);
10,044✔
594
    }
10,044✔
595

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

600

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

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

57✔
608
    bump_content_version();
99✔
609
    bump_storage_version();
99✔
610

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

615

616
TableKey Table::get_key_direct(Allocator& alloc, ref_type top_ref)
617
{
10,094,406✔
618
    // well, not quite "direct", more like "almost direct":
5,412,231✔
619
    Array table_top(alloc);
10,094,406✔
620
    table_top.init_from_ref(top_ref);
10,094,406✔
621
    if (table_top.size() > 3) {
10,094,682✔
622
        RefOrTagged rot = table_top.get_as_ref_or_tagged(top_position_for_key);
10,094,682✔
623
        return TableKey(int32_t(rot.get_as_int()));
10,094,682✔
624
    }
10,094,682✔
625
    else {
4,294,967,294✔
626
        return TableKey();
4,294,967,294✔
627
    }
4,294,967,294✔
628
}
10,094,406✔
629

630

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

2,967,411✔
640
    m_spec.init_from_parent();
5,262,396✔
641

2,967,411✔
642
    while (m_top.size() <= top_position_for_pk_col) {
5,263,356✔
643
        m_top.add(0);
960✔
644
    }
960✔
645

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

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

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

2,967,411✔
694
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
5,262,396✔
695
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
4,728,021✔
696

2,967,411✔
697
    if (m_top.size() <= top_position_for_flags) {
5,262,396✔
698
        m_table_type = Type::TopLevel;
702✔
699
    }
702✔
700
    else {
5,261,694✔
701
        uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
5,261,694✔
702
        m_table_type = Type(flags & table_type_mask);
5,261,694✔
703
    }
5,261,694✔
704
    m_has_any_embedded_objects.reset();
5,262,396✔
705

2,967,411✔
706
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
5,262,396✔
707
        // Tombstones exists
439,176✔
708
        if (!m_tombstones) {
847,674✔
709
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
524,130✔
710
        }
524,130✔
711
        m_tombstones->init_from_parent();
847,674✔
712
    }
847,674✔
713
    else {
4,414,722✔
714
        m_tombstones = nullptr;
4,414,722✔
715
    }
4,414,722✔
716
    m_cookie = cookie_initialized;
5,262,396✔
717
}
5,262,396✔
718

719

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

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

375,813✔
727
    if (target_table) {
761,829✔
728
        auto backlink_col_key = target_table->do_insert_root_column(ColKey{}, col_type_BackLink, ""); // Throws
81,375✔
729
        target_table->check_column(backlink_col_key);
81,375✔
730

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

375,813✔
735
    if (Replication* repl = get_repl())
761,829✔
736
        repl->insert_column(this, col_key, type, name, target_table); // Throws
744,165✔
737

375,813✔
738
    return col_key;
761,829✔
739
}
761,829✔
740

741

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

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

662,538✔
752
        if (type == type_Int) {
1,325,523✔
753
            if (is_nullable(col_key)) {
1,214,058✔
754
                Optional<int64_t> value = o.get<Optional<int64_t>>(col_key);
60✔
755
                index->insert(key, value); // Throws
60✔
756
            }
60✔
757
            else {
1,213,998✔
758
                int64_t value = o.get<int64_t>(col_key);
1,213,998✔
759
                index->insert(key, value); // Throws
1,213,998✔
760
            }
1,213,998✔
761
        }
1,214,058✔
762
        else if (type == type_Bool) {
111,465✔
763
            if (is_nullable(col_key)) {
690✔
764
                Optional<bool> value = o.get<Optional<bool>>(col_key);
588✔
765
                index->insert(key, value); // Throws
588✔
766
            }
588✔
767
            else {
102✔
768
                bool value = o.get<bool>(col_key);
102✔
769
                index->insert(key, value); // Throws
102✔
770
            }
102✔
771
        }
690✔
772
        else if (type == type_String) {
110,775✔
773
            StringData value = o.get<StringData>(col_key);
110,613✔
774
            index->insert(key, value); // Throws
110,613✔
775
        }
110,613✔
776
        else if (type == type_Timestamp) {
165✔
777
            Timestamp value = o.get<Timestamp>(col_key);
132✔
778
            index->insert(key, value); // Throws
132✔
779
        }
132✔
780
        else if (type == type_ObjectId) {
2,147,483,680✔
781
            if (is_nullable(col_key)) {
36✔
782
                Optional<ObjectId> value = o.get<Optional<ObjectId>>(col_key);
18✔
783
                index->insert(key, value); // Throws
18✔
784
            }
18✔
785
            else {
18✔
786
                ObjectId value = o.get<ObjectId>(col_key);
18✔
787
                index->insert(key, value); // Throws
18✔
788
            }
18✔
789
        }
36✔
790
        else if (type == type_UUID) {
2,147,483,665✔
791
            if (is_nullable(col_key)) {
36✔
792
                Optional<UUID> value = o.get<Optional<UUID>>(col_key);
18✔
793
                index->insert(key, value); // Throws
18✔
794
            }
18✔
795
            else {
18✔
796
                UUID value = o.get<UUID>(col_key);
18✔
797
                index->insert(key, value); // Throws
18✔
798
            }
18✔
799
        }
36✔
800
        else if (type == type_Mixed) {
4,294,967,294✔
801
            index->insert(key, o.get<Mixed>(col_key));
6✔
802
        }
6✔
803
        else {
4,294,967,294✔
804
            REALM_ASSERT_RELEASE(false && "Data type does not support search index");
4,294,967,294✔
805
        }
4,294,967,294✔
806
    }
1,325,523✔
807
}
132,990✔
808

809
void Table::erase_from_search_indexes(ObjKey key)
810
{
5,028,369✔
811
    // Tombstones do not use index - will crash if we try to erase values
2,514,753✔
812
    if (!key.is_unresolved()) {
5,028,369✔
813
        for (auto&& index : m_index_accessors) {
6,701,835✔
814
            if (index) {
6,701,835✔
815
                index->erase(key);
282,321✔
816
            }
282,321✔
817
        }
6,701,835✔
818
    }
5,014,908✔
819
}
5,028,369✔
820

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

11,580,483✔
828
    auto sz = m_index_accessors.size();
23,229,156✔
829
    // values are sorted by column index - there may be values missing
11,580,483✔
830
    auto value = values.begin();
23,229,156✔
831
    for (size_t column_ndx = 0; column_ndx < sz; column_ndx++) {
57,424,413✔
832
        // Check if initial value is provided
16,967,058✔
833
        Mixed init_value;
34,195,344✔
834
        if (value != values.end() && value->col_key.get_index().val == column_ndx) {
34,195,344✔
835
            // Value for this column is provided
283,020✔
836
            init_value = value->value;
588,465✔
837
            ++value;
588,465✔
838
        }
588,465✔
839

16,967,058✔
840
        if (auto&& index = m_index_accessors[column_ndx]) {
34,195,344✔
841
            // There is an index for this column
555,027✔
842
            auto col_key = m_leaf_ndx2colkey[column_ndx];
1,132,758✔
843
            auto type = col_key.get_type();
1,132,758✔
844
            auto attr = col_key.get_attrs();
1,132,758✔
845
            bool nullable = attr.test(col_attr_Nullable);
1,132,758✔
846
            switch (type) {
1,132,758✔
847
                case col_type_Int:
534,897✔
848
                    if (init_value.is_null()) {
534,897✔
849
                        index->insert(key, ArrayIntNull::default_value(nullable));
165,621✔
850
                    }
165,621✔
851
                    else {
369,276✔
852
                        index->insert(key, init_value.get<int64_t>());
369,276✔
853
                    }
369,276✔
854
                    break;
534,897✔
855
                case col_type_Bool:
6,084✔
856
                    if (init_value.is_null()) {
6,084✔
857
                        index->insert(key, ArrayBoolNull::default_value(nullable));
6,048✔
858
                    }
6,048✔
859
                    else {
36✔
860
                        index->insert(key, init_value.get<bool>());
36✔
861
                    }
36✔
862
                    break;
6,084✔
863
                case col_type_String:
480,702✔
864
                    if (init_value.is_null()) {
480,702✔
865
                        index->insert(key, ArrayString::default_value(nullable));
432,597✔
866
                    }
432,597✔
867
                    else {
48,105✔
868
                        index->insert(key, init_value.get<String>());
48,105✔
869
                    }
48,105✔
870
                    break;
480,702✔
871
                case col_type_Timestamp:
6,315✔
872
                    if (init_value.is_null()) {
6,315✔
873
                        index->insert(key, ArrayTimestamp::default_value(nullable));
6,279✔
874
                    }
6,279✔
875
                    else {
36✔
876
                        index->insert(key, init_value.get<Timestamp>());
36✔
877
                    }
36✔
878
                    break;
6,315✔
879
                case col_type_ObjectId:
85,692✔
880
                    if (init_value.is_null()) {
85,692✔
881
                        index->insert(key, ArrayObjectIdNull::default_value(nullable));
6,120✔
882
                    }
6,120✔
883
                    else {
79,572✔
884
                        index->insert(key, init_value.get<ObjectId>());
79,572✔
885
                    }
79,572✔
886
                    break;
85,692✔
887
                case col_type_Mixed:
834✔
888
                    index->insert(key, init_value);
834✔
889
                    break;
834✔
890
                case col_type_UUID:
18,342✔
891
                    if (init_value.is_null()) {
18,342✔
892
                        index->insert(key, ArrayUUIDNull::default_value(nullable));
6,138✔
893
                    }
6,138✔
894
                    else {
12,204✔
895
                        index->insert(key, init_value.get<UUID>());
12,204✔
896
                    }
12,204✔
897
                    break;
18,342✔
898
                default:
✔
899
                    REALM_UNREACHABLE();
×
900
            }
1,132,758✔
901
        }
1,132,758✔
902
    }
34,195,344✔
903
}
23,229,156✔
904

905
void Table::clear_indexes()
906
{
4,215✔
907
    for (auto&& index : m_index_accessors) {
48,231✔
908
        if (index) {
48,231✔
909
            index->clear();
2,940✔
910
        }
2,940✔
911
    }
48,231✔
912
}
4,215✔
913

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

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

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

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

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

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

65,787✔
943
    populate_search_index(col_key);
132,990✔
944
}
132,990✔
945

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

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

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

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

1,935✔
982
    do_add_search_index(col_key, type);
3,846✔
983

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

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

3,861✔
994
    // Early-out if non-indexed
3,861✔
995
    if (m_index_accessors[column_ndx.val] == nullptr)
8,022✔
996
        return;
63✔
997

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

3,828✔
1004
    m_index_refs.set(column_ndx.val, 0);
7,959✔
1005

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

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

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

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

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

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

1043

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

1056

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

483,375✔
1062
    // locate insertion point: ordinary columns must come before backlink columns
483,375✔
1063
    size_t spec_ndx = (type == col_type_BackLink) ? m_spec.get_column_count() : m_spec.get_public_column_count();
934,731✔
1064

483,375✔
1065
    if (!col_key) {
979,380✔
1066
        col_key = generate_col_key(type, {});
88,311✔
1067
    }
88,311✔
1068

483,375✔
1069
    m_spec.insert_column(spec_ndx, col_key, type, name, col_key.get_attrs().m_value); // Throws
979,380✔
1070
    if (col_key.is_dictionary()) {
979,380✔
1071
        m_spec.set_dictionary_key_type(spec_ndx, key_type);
53,562✔
1072
    }
53,562✔
1073
    auto col_ndx = col_key.get_index().val;
979,380✔
1074
    build_column_mapping();
979,380✔
1075
    REALM_ASSERT(col_ndx <= m_index_refs.size());
979,380✔
1076
    if (col_ndx == m_index_refs.size()) {
979,380✔
1077
        m_index_refs.insert(col_ndx, 0);
979,125✔
1078
    }
979,125✔
1079
    else {
255✔
1080
        m_index_refs.set(col_ndx, 0);
255✔
1081
    }
255✔
1082
    REALM_ASSERT(col_ndx <= m_opposite_table.size());
979,380✔
1083
    if (col_ndx == m_opposite_table.size()) {
979,380✔
1084
        // m_opposite_table and m_opposite_column are always resized together!
483,243✔
1085
        m_opposite_table.insert(col_ndx, TableKey().value);
979,119✔
1086
        m_opposite_column.insert(col_ndx, ColKey().value);
979,119✔
1087
    }
979,119✔
1088
    else {
261✔
1089
        m_opposite_table.set(col_ndx, TableKey().value);
261✔
1090
        m_opposite_column.set(col_ndx, ColKey().value);
261✔
1091
    }
261✔
1092
    refresh_index_accessors();
979,380✔
1093
    m_clusters.insert_column(col_key);
979,380✔
1094
    if (m_tombstones) {
979,380✔
1095
        m_tombstones->insert_column(col_key);
7,089✔
1096
    }
7,089✔
1097

483,375✔
1098
    bump_storage_version();
979,380✔
1099

483,375✔
1100
    return col_key;
979,380✔
1101
}
979,380✔
1102

1103

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

8,739✔
1124
    build_column_mapping();
18,135✔
1125
    while (m_index_accessors.size() > m_leaf_ndx2colkey.size()) {
35,691✔
1126
        REALM_ASSERT(m_index_accessors.back() == nullptr);
17,556✔
1127
        m_index_accessors.pop_back();
17,556✔
1128
    }
17,556✔
1129
    bump_content_version();
18,135✔
1130
    bump_storage_version();
18,135✔
1131
}
18,135✔
1132

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1277

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

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

1294

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

1310

1311
IndexType Table::search_index_type(ColKey col_key) const noexcept
1312
{
7,894,881✔
1313
    if (auto index = m_index_accessors[col_key.get_index().val].get()) {
7,894,881✔
1314
        return index->is_fulltext_index() ? IndexType::Fulltext : IndexType::General;
1,159,176✔
1315
    }
1,159,386✔
1316
    return IndexType::None;
6,735,495✔
1317
}
6,735,495✔
1318

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

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

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

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

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

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

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

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

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

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

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

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

1464
namespace {
1465

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

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

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

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

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

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

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

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

1523
    using Array::set_parent;
1524

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

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

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

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

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

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

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

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

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

1666
} // namespace
1667

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2061

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

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

2074

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

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

168,228✔
2098
    // Table key value
168,228✔
2099
    RefOrTagged rot = RefOrTagged::make_tagged(key.value);
339,363✔
2100
    top.add(rot);
339,363✔
2101

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

168,228✔
2139
    REALM_ASSERT(top.size() == top_array_size);
339,363✔
2140

168,228✔
2141
    return top.get_ref();
339,363✔
2142
}
339,363✔
2143

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

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

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

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

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

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

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

2212

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

17,135,778✔
2221
    return static_cast<Group*>(parent);
34,406,730✔
2222
}
34,406,730✔
2223

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

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

2240
uint64_t Table::allocate_sequence_number()
2241
{
20,086,227✔
2242
    RefOrTagged rot = m_top.get_as_ref_or_tagged(top_position_for_sequence_number);
20,086,227✔
2243
    uint64_t sn = rot.is_tagged() ? rot.get_as_int() : 0;
19,959,825✔
2244
    rot = RefOrTagged::make_tagged(sn + 1);
20,086,227✔
2245
    m_top.set(top_position_for_sequence_number, rot);
20,086,227✔
2246

10,015,680✔
2247
    return sn;
20,086,227✔
2248
}
20,086,227✔
2249

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

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

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

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

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

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

9✔
2300
    traverse_clusters(f);
18✔
2301

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

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

13,929✔
2318
    auto f = [&leaf, column_key, &st](const Cluster* cluster) {
27,834✔
2319
        // direct aggregate on the leaf
13,938✔
2320
        cluster->init_leaf(column_key, &leaf);
27,834✔
2321
        st.m_key_offset = cluster->get_offset();
27,834✔
2322
        st.m_key_values = cluster->get_key_array();
27,834✔
2323

13,938✔
2324
        bool cont = true;
27,834✔
2325
        size_t sz = leaf.size();
27,834✔
2326
        for (size_t local_index = 0; cont && local_index < sz; local_index++) {
121,068✔
2327
            auto v = leaf.get(local_index);
93,234✔
2328
            cont = st.match(local_index, v);
93,234✔
2329
        }
93,234✔
2330
        return IteratorControl::AdvanceToNext;
27,834✔
2331
    };
27,834✔
2332

13,929✔
2333
    traverse_clusters(f);
27,816✔
2334
}
27,816✔
2335

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

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

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

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

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

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

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

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

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

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

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

2402
namespace realm {
2403

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2527

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2607
util::Logger* Table::get_logger() const noexcept
2608
{
1,777,296✔
2609
    return *m_repl ? (*m_repl)->get_logger() : nullptr;
2,148,357,595✔
2610
}
1,777,296✔
2611

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

403,179✔
2628
        m_opposite_table.update_from_parent();
810,798✔
2629
        m_opposite_column.update_from_parent();
810,798✔
2630
        if (m_top.size() > top_position_for_flags) {
810,798✔
2631
            uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
808,959✔
2632
            m_table_type = Type(flags & table_type_mask);
808,959✔
2633
        }
808,959✔
2634
        else {
1,839✔
2635
            m_table_type = Type::TopLevel;
1,839✔
2636
        }
1,839✔
2637
        if (m_tombstones)
810,798✔
2638
            m_tombstones->update_from_parent();
1,278✔
2639

403,179✔
2640
        refresh_content_version();
810,798✔
2641
        m_has_any_embedded_objects.reset();
810,798✔
2642
    }
810,798✔
2643
    m_alloc.bump_storage_version();
810,795✔
2644
}
810,795✔
2645

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

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

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

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

2728

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

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

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

2763

2764
void Table::flush_for_commit()
2765
{
4,000,698✔
2766
    if (m_top.is_attached() && m_top.size() >= top_position_for_version) {
4,000,698✔
2767
        if (!m_top.is_read_only()) {
4,000,659✔
2768
            ++m_in_file_version_at_transaction_boundary;
1,238,721✔
2769
            auto rot_version = RefOrTagged::make_tagged(m_in_file_version_at_transaction_boundary);
1,238,721✔
2770
            m_top.set(top_position_for_version, rot_version);
1,238,721✔
2771
        }
1,238,721✔
2772
    }
4,000,659✔
2773
}
4,000,698✔
2774

2775
void Table::refresh_content_version()
2776
{
1,167,192✔
2777
    REALM_ASSERT(m_top.is_attached());
1,167,192✔
2778
    if (m_top.size() >= top_position_for_version) {
1,167,192✔
2779
        // we have versioning info in the file. Use this to conditionally
617,496✔
2780
        // bump the version counter:
617,496✔
2781
        auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
1,167,003✔
2782
        REALM_ASSERT(rot_version.is_tagged());
1,167,003✔
2783
        if (m_in_file_version_at_transaction_boundary != rot_version.get_as_int()) {
1,167,003✔
2784
            m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
224,490✔
2785
            bump_content_version();
224,490✔
2786
        }
224,490✔
2787
    }
1,167,003✔
2788
    else {
189✔
2789
        // assume the worst:
168✔
2790
        bump_content_version();
189✔
2791
    }
189✔
2792
}
1,167,192✔
2793

2794

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

2833
void Table::refresh_index_accessors()
2834
{
6,587,388✔
2835
    // Refresh search index accessors
3,656,343✔
2836

3,656,343✔
2837
    // First eliminate any index accessors for eliminated last columns
3,656,343✔
2838
    size_t col_ndx_end = m_leaf_ndx2colkey.size();
6,587,388✔
2839
    m_index_accessors.resize(col_ndx_end);
6,587,388✔
2840

3,656,343✔
2841
    // Then eliminate/refresh/create accessors within column range
3,656,343✔
2842
    // we can not use for_each_column() here, since the columns may have changed
3,656,343✔
2843
    // and the index accessor vector is not updated correspondingly.
3,656,343✔
2844
    for (size_t col_ndx = 0; col_ndx < col_ndx_end; col_ndx++) {
28,460,142✔
2845
        ref_type ref = m_index_refs.get_as_ref(col_ndx);
21,872,754✔
2846

11,632,665✔
2847
        if (ref == 0) {
21,872,754✔
2848
            // accessor drop
9,605,802✔
2849
            m_index_accessors[col_ndx].reset();
17,842,476✔
2850
        }
17,842,476✔
2851
        else {
4,030,278✔
2852
            auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_ndx]);
4,030,278✔
2853
            bool fulltext = attr.test(col_attr_FullText_Indexed);
4,030,278✔
2854
            auto col_key = m_leaf_ndx2colkey[col_ndx];
4,030,278✔
2855
            ClusterColumn virtual_col(&m_clusters, col_key, fulltext ? IndexType::Fulltext : IndexType::General);
4,030,263✔
2856

2,026,863✔
2857
            if (m_index_accessors[col_ndx]) { // still there, refresh:
4,030,278✔
2858
                m_index_accessors[col_ndx]->refresh_accessor_tree(virtual_col);
474,405✔
2859
            }
474,405✔
2860
            else { // new index!
3,555,873✔
2861
                m_index_accessors[col_ndx] =
3,555,873✔
2862
                    std::make_unique<StringIndex>(ref, &m_index_refs, col_ndx, virtual_col, get_alloc());
3,555,873✔
2863
            }
3,555,873✔
2864
        }
4,030,278✔
2865
    }
21,872,754✔
2866
}
6,587,388✔
2867

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

2880
// LCOV_EXCL_START ignore debug functions
2881

2882
void Table::verify() const
2883
{
2,985,660✔
2884
#ifdef REALM_DEBUG
2,985,660✔
2885
    if (m_top.is_attached())
2,985,660✔
2886
        m_top.verify();
2,985,660✔
2887
    m_spec.verify();
2,985,660✔
2888
    m_clusters.verify();
2,985,660✔
2889
    if (nb_unresolved())
2,985,660✔
2890
        m_tombstones->verify();
767,856✔
2891
#endif
2,985,660✔
2892
}
2,985,660✔
2893

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

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

11,369,808✔
2923
    REALM_ASSERT(key.value >= 0);
22,746,636✔
2924

11,369,808✔
2925
    Obj obj = m_clusters.insert(key, values); // repl->set()
22,746,636✔
2926

11,369,808✔
2927
    return obj;
22,746,636✔
2928
}
22,746,636✔
2929

2930
Obj Table::create_linked_object()
2931
{
39,702✔
2932
    REALM_ASSERT(is_embedded());
39,702✔
2933

19,758✔
2934
    GlobalKey object_id = allocate_object_id_squeezed();
39,702✔
2935
    ObjKey key = object_id.get_local_key(get_sync_file_id());
39,702✔
2936

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

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

19,758✔
2941
    return obj;
39,702✔
2942
}
39,702✔
2943

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

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

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

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

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

283,782✔
2985
    DataType type = DataType(primary_key_col.get_type());
590,514✔
2986

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

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

283,776✔
2999
    REALM_ASSERT(type == type_String || type == type_ObjectId || type == type_Int || type == type_UUID);
590,502✔
3000

283,776✔
3001
    if (did_create)
590,502✔
3002
        *did_create = false;
74,409✔
3003

283,776✔
3004
    // Check for existing object
283,776✔
3005
    if (ObjKey key = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key)) {
590,502✔
3006
        if (mode == UpdateMode::never) {
83,061✔
3007
            throw ObjectAlreadyExists(this->get_class_name(), primary_key);
6✔
3008
        }
6✔
3009
        auto obj = m_clusters.get(key);
83,055✔
3010
        for (auto& val : field_values) {
41,271✔
3011
            if (mode == UpdateMode::all || obj.get_any(val.col_key) != val.value) {
12✔
3012
                obj.set_any(val.col_key, val.value, val.is_default);
12✔
3013
            }
12✔
3014
        }
12✔
3015
        return obj;
83,055✔
3016
    }
83,055✔
3017

242,508✔
3018
    ObjKey unres_key;
507,441✔
3019
    if (m_tombstones) {
507,441✔
3020
        // Check for potential tombstone
20,751✔
3021
        GlobalKey object_id{primary_key};
40,683✔
3022
        ObjKey object_key = global_to_local_object_id_hashed(object_id);
40,683✔
3023

20,751✔
3024
        ObjKey key = object_key.get_unresolved();
40,683✔
3025
        if (auto obj = m_tombstones->try_get_obj(key)) {
40,683✔
3026
            auto existing_pk_value = obj.get_any(primary_key_col);
13,377✔
3027

6,846✔
3028
            // If the primary key is the same, the object should be resurrected below
6,846✔
3029
            if (existing_pk_value == primary_key) {
13,377✔
3030
                unres_key = key;
13,371✔
3031
            }
13,371✔
3032
        }
13,377✔
3033
    }
40,683✔
3034

242,508✔
3035
    ObjKey key = get_next_valid_key();
507,441✔
3036

242,508✔
3037
    auto repl = get_repl();
507,441✔
3038
    if (repl) {
507,441✔
3039
        repl->create_object_with_primary_key(this, key, primary_key);
446,355✔
3040
    }
446,355✔
3041
    if (did_create) {
507,441✔
3042
        *did_create = true;
36,345✔
3043
    }
36,345✔
3044

242,508✔
3045
    field_values.insert(primary_key_col, primary_key);
507,441✔
3046
    Obj ret = m_clusters.insert(key, field_values);
507,441✔
3047

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

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

462,435✔
3072
    if (auto&& index = m_index_accessors[primary_key_col.get_index().val]) {
919,164✔
3073
        return index->find_first(primary_key);
918,777✔
3074
    }
918,777✔
3075

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

351✔
3081
    // Check if existing
351✔
3082
    if (auto obj = m_clusters.try_get_obj(object_key)) {
387✔
3083
        auto existing_pk_value = obj.get_any(primary_key_col);
×
3084

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

3092
ObjKey Table::get_objkey_from_primary_key(const Mixed& primary_key)
3093
{
747,090✔
3094
    // Check if existing
375,933✔
3095
    if (auto key = find_primary_key(primary_key)) {
747,090✔
3096
        return key;
715,164✔
3097
    }
715,164✔
3098

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

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

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

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

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

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

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

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

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

3179
namespace {
3180

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

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

3202
} // namespace
3203

3204
ObjKey Table::global_to_local_object_id_hashed(GlobalKey object_id) const
3205
{
72,699✔
3206
    ObjKey optimistic = get_optimistic_local_id_hashed(object_id);
72,699✔
3207

37,101✔
3208
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
72,699✔
3209
        Allocator& alloc = m_top.get_alloc();
24✔
3210
        Array collision_map{alloc};
24✔
3211
        collision_map.init_from_ref(collision_map_ref); // Throws
24✔
3212

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

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

37,089✔
3230
    return optimistic;
72,675✔
3231
}
72,675✔
3232

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

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

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

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

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

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

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

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

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

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

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

16,437✔
3307
    ensure_graveyard();
32,190✔
3308
    auto tombstone = m_tombstones->try_get_obj(unres_key);
32,190✔
3309
    if (tombstone) {
32,190✔
3310
        if (pk_col) {
3,201✔
3311
            auto existing_pk_value = tombstone.get_any(pk_col);
3,201✔
3312
            // It may just be the same object
1,650✔
3313
            if (existing_pk_value != pk_val) {
3,201✔
3314
                // We have a collision - create new ObjKey
6✔
3315
                key = allocate_local_id_after_hash_collision({pk_val}, {existing_pk_value}, key);
12✔
3316
                return get_or_create_tombstone(key, pk_col, pk_val);
12✔
3317
            }
12✔
3318
        }
3,189✔
3319
        return tombstone;
3,189✔
3320
    }
3,189✔
3321
    return m_tombstones->insert(unres_key, {{pk_col, pk_val}});
28,989✔
3322
}
28,989✔
3323

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

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

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

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

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

3367
void Table::create_objects(size_t number, std::vector<ObjKey>& keys)
3368
{
3,867✔
3369
    while (number--) {
6,325,650✔
3370
        keys.push_back(create_object().get_key());
6,321,783✔
3371
    }
6,321,783✔
3372
}
3,867✔
3373

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

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

3388
void Table::remove_object(ObjKey key)
3389
{
2,490,519✔
3390
    Group* g = get_parent_group();
2,490,519✔
3391

1,245,630✔
3392
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
2,490,519✔
3393
        CascadeState state(CascadeState::Mode::Strong, g);
2,502✔
3394
        state.m_to_be_deleted.emplace_back(m_key, key);
2,502✔
3395
        m_clusters.nullify_incoming_links(key, state);
2,502✔
3396
        remove_recursive(state);
2,502✔
3397
    }
2,502✔
3398
    else {
2,488,017✔
3399
        CascadeState state(CascadeState::Mode::None, g);
2,488,017✔
3400
        if (g) {
2,488,017✔
3401
            m_clusters.nullify_incoming_links(key, state);
2,406,114✔
3402
        }
2,406,114✔
3403
        m_clusters.erase(key, state);
2,488,017✔
3404
    }
2,488,017✔
3405
}
2,490,519✔
3406

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

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

32,643✔
3430
    remove_object(key);
64,599✔
3431

32,643✔
3432
    return tombstone.get_key();
64,599✔
3433
}
64,599✔
3434

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

3451
Table::Iterator Table::begin() const
3452
{
837,309✔
3453
    return Iterator(m_clusters, 0);
837,309✔
3454
}
837,309✔
3455

3456
Table::Iterator Table::end() const
3457
{
9,269,406✔
3458
    return Iterator(m_clusters, size());
9,269,406✔
3459
}
9,269,406✔
3460

3461
TableRef _impl::TableFriend::get_opposite_link_table(const Table& table, ColKey col_key)
3462
{
7,081,047✔
3463
    TableRef ret;
7,081,047✔
3464
    if (col_key) {
7,081,362✔
3465
        return table.get_opposite_table(col_key);
7,081,134✔
3466
    }
7,081,134✔
3467
    return ret;
2,147,483,875✔
3468
}
2,147,483,875✔
3469

3470
const uint64_t Table::max_num_columns;
3471

3472
void Table::build_column_mapping()
3473
{
6,610,095✔
3474
    // build column mapping from spec
3,667,878✔
3475
    // TODO: Optimization - Don't rebuild this for every change
3,667,878✔
3476
    m_spec_ndx2leaf_ndx.clear();
6,610,095✔
3477
    m_leaf_ndx2spec_ndx.clear();
6,610,095✔
3478
    m_leaf_ndx2colkey.clear();
6,610,095✔
3479
    size_t num_spec_cols = m_spec.get_column_count();
6,610,095✔
3480
    m_spec_ndx2leaf_ndx.resize(num_spec_cols);
6,610,095✔
3481
    for (size_t spec_ndx = 0; spec_ndx < num_spec_cols; ++spec_ndx) {
28,448,085✔
3482
        ColKey col_key = m_spec.get_key(spec_ndx);
21,837,990✔
3483
        unsigned leaf_ndx = col_key.get_index().val;
21,837,990✔
3484
        if (leaf_ndx >= m_leaf_ndx2colkey.size()) {
21,837,990✔
3485
            m_leaf_ndx2colkey.resize(leaf_ndx + 1);
21,366,441✔
3486
            m_leaf_ndx2spec_ndx.resize(leaf_ndx + 1, -1);
21,366,441✔
3487
        }
21,366,441✔
3488
        m_spec_ndx2leaf_ndx[spec_ndx] = ColKey::Idx{leaf_ndx};
21,837,990✔
3489
        m_leaf_ndx2spec_ndx[leaf_ndx] = spec_ndx;
21,837,990✔
3490
        m_leaf_ndx2colkey[leaf_ndx] = col_key;
21,837,990✔
3491
    }
21,837,990✔
3492
}
6,610,095✔
3493

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

483,369✔
3499
    int64_t col_seq_number = m_top.get_as_ref_or_tagged(top_position_for_column_key).get_as_int();
979,374✔
3500
    unsigned upper = unsigned(col_seq_number ^ get_key().value);
979,374✔
3501

483,369✔
3502
    // reuse lowest available leaf ndx:
483,369✔
3503
    unsigned lower = unsigned(m_leaf_ndx2colkey.size());
979,374✔
3504
    // look for an unused entry:
483,369✔
3505
    for (unsigned idx = 0; idx < lower; ++idx) {
6,246,945✔
3506
        if (m_leaf_ndx2colkey[idx] == ColKey()) {
5,267,658✔
3507
            lower = idx;
87✔
3508
            break;
87✔
3509
        }
87✔
3510
    }
5,267,658✔
3511
    return ColKey(ColKey::Idx{lower}, tp, attr, upper);
979,374✔
3512
}
979,374✔
3513

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

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

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

3567
ColKey Table::get_primary_key_column() const
3568
{
19,779,423✔
3569
    return m_primary_key_col;
19,779,423✔
3570
}
19,779,423✔
3571

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

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

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

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

3598

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

67,689✔
3609
    if (m_primary_key_col) {
137,148✔
3610
        // If the search index has not been set explicitly on current pk col, we remove it again
3,702✔
3611
        auto spec_ndx = leaf_ndx2spec_ndx(m_primary_key_col.get_index());
7,734✔
3612
        auto attr = m_spec.get_column_attr(spec_ndx);
7,734✔
3613
        if (!attr.test(col_attr_Indexed)) {
7,734✔
3614
            remove_search_index(m_primary_key_col);
7,722✔
3615
        }
7,722✔
3616
    }
7,734✔
3617

67,689✔
3618
    if (col_key) {
137,148✔
3619
        m_top.set(top_position_for_pk_col, RefOrTagged::make_tagged(col_key.value));
129,318✔
3620
        do_add_search_index(col_key, IndexType::General);
129,318✔
3621
    }
129,318✔
3622
    else {
7,830✔
3623
        m_top.set(top_position_for_pk_col, 0);
7,830✔
3624
    }
7,830✔
3625

67,689✔
3626
    m_primary_key_col = col_key;
137,148✔
3627
}
137,148✔
3628

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

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

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

3657
ObjKey Table::get_next_valid_key()
3658
{
507,444✔
3659
    ObjKey key;
507,444✔
3660
    do {
507,450✔
3661
        key = ObjKey(allocate_sequence_number());
507,450✔
3662
    } while (m_clusters.is_valid(key));
507,450✔
3663

242,511✔
3664
    return key;
507,444✔
3665
}
507,444✔
3666

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

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

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

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

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

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

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

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

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

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

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

3898

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

141✔
3904
    check_column(col_key);
282✔
3905

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

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

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

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

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

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

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

3946
bool Table::has_any_embedded_objects()
3947
{
2,495,799✔
3948
    if (!m_has_any_embedded_objects) {
2,495,799✔
3949
        m_has_any_embedded_objects = false;
110,898✔
3950
        for_each_public_column([&](ColKey col_key) {
222,216✔
3951
            auto target_table_key = get_opposite_table_key(col_key);
222,216✔
3952
            if (target_table_key && is_link_type(col_key.get_type())) {
222,216✔
3953
                auto target_table = get_parent_group()->get_table_unchecked(target_table_key);
9,141✔
3954
                if (target_table->is_embedded()) {
9,141✔
3955
                    m_has_any_embedded_objects = true;
7,017✔
3956
                    return IteratorControl::Stop; // early out
7,017✔
3957
                }
7,017✔
3958
            }
215,199✔
3959
            return IteratorControl::AdvanceToNext;
215,199✔
3960
        });
215,199✔
3961
    }
110,898✔
3962
    return *m_has_any_embedded_objects;
2,495,799✔
3963
}
2,495,799✔
3964

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

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

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

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

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

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

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

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

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

4008
TableRef Table::get_opposite_table(ColKey col_key) const
4009
{
7,710,156✔
4010
    if (auto k = get_opposite_table_key(col_key)) {
7,710,156✔
4011
        return get_parent_group()->get_table(k);
7,655,844✔
4012
    }
7,655,844✔
4013
    return {};
54,312✔
4014
}
54,312✔
4015

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

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