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

realm / realm-core / github_pull_request_312964

19 Feb 2025 07:31PM UTC coverage: 90.814% (-0.3%) from 91.119%
github_pull_request_312964

Pull #8071

Evergreen

web-flow
Bump serialize-javascript and mocha

Bumps [serialize-javascript](https://github.com/yahoo/serialize-javascript) to 6.0.2 and updates ancestor dependency [mocha](https://github.com/mochajs/mocha). These dependencies need to be updated together.


Updates `serialize-javascript` from 6.0.0 to 6.0.2
- [Release notes](https://github.com/yahoo/serialize-javascript/releases)
- [Commits](https://github.com/yahoo/serialize-javascript/compare/v6.0.0...v6.0.2)

Updates `mocha` from 10.2.0 to 10.8.2
- [Release notes](https://github.com/mochajs/mocha/releases)
- [Changelog](https://github.com/mochajs/mocha/blob/main/CHANGELOG.md)
- [Commits](https://github.com/mochajs/mocha/compare/v10.2.0...v10.8.2)

---
updated-dependencies:
- dependency-name: serialize-javascript
  dependency-type: indirect
- dependency-name: mocha
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #8071: Bump serialize-javascript and mocha

96552 of 179126 branches covered (53.9%)

212672 of 234185 relevant lines covered (90.81%)

3115802.0 hits per line

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

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

19
#include <realm/table.hpp>
20

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

39
#include <stdexcept>
40

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

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

260

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

264
Replication* Table::g_dummy_replication = nullptr;
265

266
bool TableVersions::operator==(const TableVersions& other) const
267
{
11,310✔
268
    if (size() != other.size())
11,310✔
269
        return false;
×
270
    size_t sz = size();
11,310✔
271
    for (size_t i = 0; i < sz; i++) {
18,633✔
272
        REALM_ASSERT_DEBUG(this->at(i).first == other.at(i).first);
11,376✔
273
        if (this->at(i).second != other.at(i).second)
11,376✔
274
            return false;
4,053✔
275
    }
11,376✔
276
    return true;
7,257✔
277
}
11,310✔
278

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

322
std::ostream& operator<<(std::ostream& o, Table::Type table_type)
323
{
27,405✔
324
    switch (table_type) {
27,405✔
325
        case Table::Type::TopLevel:
25,803✔
326
            return o << "TopLevel";
25,803✔
327
        case Table::Type::Embedded:
1,602✔
328
            return o << "Embedded";
1,602✔
329
        case Table::Type::TopLevelAsymmetric:
✔
330
            return o << "TopLevelAsymmetric";
×
331
    }
27,405✔
332
    return o << "Invalid table type: " << uint8_t(table_type);
×
333
}
27,405✔
334
} // namespace realm
335

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

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

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

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

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

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

399
    ColumnAttrMask attr;
256,416✔
400
    if (collection_type) {
256,416✔
401
        switch (*collection_type) {
75,315✔
402
            case CollectionType::List:
31,038✔
403
                attr.set(col_attr_List);
31,038✔
404
                break;
31,038✔
405
            case CollectionType::Set:
21,687✔
406
                attr.set(col_attr_Set);
21,687✔
407
                break;
21,687✔
408
            case CollectionType::Dictionary:
22,590✔
409
                attr.set(col_attr_Dictionary);
22,590✔
410
                break;
22,590✔
411
        }
75,315✔
412
    }
75,315✔
413
    if (nullable || type == type_Mixed)
256,416✔
414
        attr.set(col_attr_Nullable);
79,329✔
415
    ColKey col_key = generate_col_key(ColumnType(type), attr);
256,416✔
416

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

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

434
    m_has_any_embedded_objects.reset();
37,314✔
435

436
    DataType data_type = type_Link;
37,314✔
437
    ColumnAttrMask attr;
37,314✔
438
    if (collection_type) {
37,314✔
439
        switch (*collection_type) {
21,831✔
440
            case CollectionType::List:
10,935✔
441
                attr.set(col_attr_List);
10,935✔
442
                break;
10,935✔
443
            case CollectionType::Set:
5,316✔
444
                if (target.is_embedded())
5,316✔
445
                    throw IllegalOperation("Set of embedded objects not supported");
×
446
                attr.set(col_attr_Set);
5,316✔
447
                break;
5,316✔
448
            case CollectionType::Dictionary:
5,580✔
449
                attr.set(col_attr_Dictionary);
5,580✔
450
                attr.set(col_attr_Nullable);
5,580✔
451
                break;
5,580✔
452
        }
21,831✔
453
    }
21,831✔
454
    else {
15,483✔
455
        attr.set(col_attr_Nullable);
15,483✔
456
    }
15,483✔
457
    ColKey col_key = generate_col_key(ColumnType(data_type), attr);
37,314✔
458

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

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

468
    do {
125,352✔
469
        cascade_state.send_notifications();
125,352✔
470

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

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

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

502
CollectionType Table::get_collection_type(ColKey col_key) const
503
{
4,578✔
504
    if (col_key.is_list()) {
4,578✔
505
        return CollectionType::List;
324✔
506
    }
324✔
507
    if (col_key.is_set()) {
4,254✔
508
        return CollectionType::Set;
528✔
509
    }
528✔
510
    REALM_ASSERT(col_key.is_dictionary());
3,726✔
511
    return CollectionType::Dictionary;
3,726✔
512
}
4,254✔
513

514
void Table::remove_columns()
515
{
1,257✔
516
    for (size_t i = get_column_count(); i > 0; --i) {
3,675✔
517
        ColKey col_key = spec_ndx2colkey(i - 1);
2,418✔
518
        remove_column(col_key);
2,418✔
519
    }
2,418✔
520
}
1,257✔
521

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

526
    if (Replication* repl = get_repl())
2,766✔
527
        repl->erase_column(this, col_key); // Throws
2,121✔
528

529
    if (col_key == m_primary_key_col) {
2,766✔
530
        do_set_primary_key_column(ColKey());
471✔
531
    }
471✔
532
    else {
2,295✔
533
        REALM_ASSERT_RELEASE(m_primary_key_col.get_index().val != col_key.get_index().val);
2,295✔
534
    }
2,295✔
535

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

540

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

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

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

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

555

556
TableKey Table::get_key_direct(Allocator& alloc, ref_type top_ref)
557
{
1,670,481✔
558
    // well, not quite "direct", more like "almost direct":
559
    Array table_top(alloc);
1,670,481✔
560
    table_top.init_from_ref(top_ref);
1,670,481✔
561
    if (table_top.size() > 3) {
1,670,481✔
562
        RefOrTagged rot = table_top.get_as_ref_or_tagged(top_position_for_key);
1,668,777✔
563
        return TableKey(int32_t(rot.get_as_int()));
1,668,777✔
564
    }
1,668,777✔
565
    else {
1,704✔
566
        return TableKey();
1,704✔
567
    }
1,704✔
568
}
1,670,481✔
569

570

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

580
    m_spec.init_from_parent();
1,409,205✔
581

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

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

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

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

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

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

646
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
1,409,205✔
647
        // Tombstones exists
648
        if (!m_tombstones) {
19,896✔
649
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
13,896✔
650
        }
13,896✔
651
        m_tombstones->init_from_parent();
19,896✔
652
    }
19,896✔
653
    else {
1,389,309✔
654
        m_tombstones = nullptr;
1,389,309✔
655
    }
1,389,309✔
656
    m_cookie = cookie_initialized;
1,409,205✔
657
}
1,409,205✔
658

659

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

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

667
    if (target_table) {
293,730✔
668
        auto backlink_col_key = target_table->do_insert_root_column(ColKey{}, col_type_BackLink, ""); // Throws
37,311✔
669
        target_table->check_column(backlink_col_key);
37,311✔
670

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

675
    if (Replication* repl = get_repl())
293,730✔
676
        repl->insert_column(this, col_key, type, name, target_table); // Throws
284,655✔
677

678
    return col_key;
293,730✔
679
}
293,730✔
680

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

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

693
    table->traverse_clusters(f);
45,570✔
694
}
45,570✔
695

696

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

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

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

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

716
    if (type == type_Int) {
45,582✔
717
        if (is_nullable(col_key)) {
24,975✔
718
            do_bulk_insert_index<Optional<int64_t>>(this, index, col_key, get_alloc());
6,909✔
719
        }
6,909✔
720
        else {
18,066✔
721
            do_bulk_insert_index<int64_t>(this, index, col_key, get_alloc());
18,066✔
722
        }
18,066✔
723
    }
24,975✔
724
    else if (type == type_Bool) {
20,607✔
725
        if (is_nullable(col_key)) {
24✔
726
            do_bulk_insert_index<Optional<bool>>(this, index, col_key, get_alloc());
12✔
727
        }
12✔
728
        else {
12✔
729
            do_bulk_insert_index<bool>(this, index, col_key, get_alloc());
12✔
730
        }
12✔
731
    }
24✔
732
    else if (type == type_String) {
20,583✔
733
        if (col_key.is_list()) {
4,041✔
734
            do_bulk_insert_index_list(this, index, col_key, get_alloc());
12✔
735
        }
12✔
736
        else {
4,029✔
737
            do_bulk_insert_index<StringData>(this, index, col_key, get_alloc());
4,029✔
738
        }
4,029✔
739
    }
4,041✔
740
    else if (type == type_Timestamp) {
16,542✔
741
        do_bulk_insert_index<Timestamp>(this, index, col_key, get_alloc());
48✔
742
    }
48✔
743
    else if (type == type_ObjectId) {
16,494✔
744
        if (is_nullable(col_key)) {
15,678✔
745
            do_bulk_insert_index<Optional<ObjectId>>(this, index, col_key, get_alloc());
507✔
746
        }
507✔
747
        else {
15,171✔
748
            do_bulk_insert_index<ObjectId>(this, index, col_key, get_alloc());
15,171✔
749
        }
15,171✔
750
    }
15,678✔
751
    else if (type == type_UUID) {
816✔
752
        if (is_nullable(col_key)) {
351✔
753
            do_bulk_insert_index<Optional<UUID>>(this, index, col_key, get_alloc());
264✔
754
        }
264✔
755
        else {
87✔
756
            do_bulk_insert_index<UUID>(this, index, col_key, get_alloc());
87✔
757
        }
87✔
758
    }
351✔
759
    else if (type == type_Mixed) {
465✔
760
        do_bulk_insert_index<Mixed>(this, index, col_key, get_alloc());
465✔
761
    }
465✔
762
    else {
×
763
        REALM_ASSERT_RELEASE(false && "Data type does not support search index");
×
764
    }
×
765
}
45,582✔
766

767
void Table::erase_from_search_indexes(ObjKey key)
768
{
2,661,558✔
769
    // Tombstones do not use index - will crash if we try to erase values
770
    if (!key.is_unresolved()) {
2,661,558✔
771
        for (auto&& index : m_index_accessors) {
3,646,956✔
772
            if (index) {
3,646,956✔
773
                index->erase(key);
272,454✔
774
            }
272,454✔
775
        }
3,646,956✔
776
    }
2,641,746✔
777
}
2,661,558✔
778

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

786
    auto sz = m_index_accessors.size();
11,833,683✔
787
    // values are sorted by column index - there may be values missing
788
    auto value = values.begin();
11,833,683✔
789
    for (size_t column_ndx = 0; column_ndx < sz; column_ndx++) {
29,512,836✔
790
        // Check if initial value is provided
791
        Mixed init_value;
17,679,156✔
792
        if (value != values.end() && value->col_key.get_index().val == column_ndx) {
17,679,156✔
793
            // Value for this column is provided
794
            init_value = value->value;
475,161✔
795
            ++value;
475,161✔
796
        }
475,161✔
797

798
        if (auto&& index = m_index_accessors[column_ndx]) {
17,679,156✔
799
            // There is an index for this column
800
            auto col_key = m_leaf_ndx2colkey[column_ndx];
745,476✔
801
            if (col_key.is_collection())
745,476✔
802
                continue;
51✔
803
            auto type = col_key.get_type();
745,425✔
804
            auto attr = col_key.get_attrs();
745,425✔
805
            bool nullable = attr.test(col_attr_Nullable);
745,425✔
806
            switch (type) {
745,425✔
807
                case col_type_Int:
232,167✔
808
                    if (init_value.is_null()) {
232,167✔
809
                        index->insert(key, ArrayIntNull::default_value(nullable));
84,093✔
810
                    }
84,093✔
811
                    else {
148,074✔
812
                        index->insert(key, init_value.get<int64_t>());
148,074✔
813
                    }
148,074✔
814
                    break;
232,167✔
815
                case col_type_Bool:
2,997✔
816
                    if (init_value.is_null()) {
2,997✔
817
                        index->insert(key, ArrayBoolNull::default_value(nullable));
2,997✔
818
                    }
2,997✔
819
                    else {
×
820
                        index->insert(key, init_value.get<bool>());
×
821
                    }
×
822
                    break;
2,997✔
823
                case col_type_String:
436,881✔
824
                    if (init_value.is_null()) {
436,881✔
825
                        index->insert(key, ArrayString::default_value(nullable));
216,252✔
826
                    }
216,252✔
827
                    else {
220,629✔
828
                        index->insert(key, init_value.get<String>());
220,629✔
829
                    }
220,629✔
830
                    break;
436,881✔
831
                case col_type_Timestamp:
3,726✔
832
                    if (init_value.is_null()) {
3,726✔
833
                        index->insert(key, ArrayTimestamp::default_value(nullable));
3,726✔
834
                    }
3,726✔
835
                    else {
×
836
                        index->insert(key, init_value.get<Timestamp>());
×
837
                    }
×
838
                    break;
3,726✔
839
                case col_type_ObjectId:
58,263✔
840
                    if (init_value.is_null()) {
58,263✔
841
                        index->insert(key, ArrayObjectIdNull::default_value(nullable));
3,660✔
842
                    }
3,660✔
843
                    else {
54,603✔
844
                        index->insert(key, init_value.get<ObjectId>());
54,603✔
845
                    }
54,603✔
846
                    break;
58,263✔
847
                case col_type_Mixed:
1,143✔
848
                    index->insert(key, init_value);
1,143✔
849
                    break;
1,143✔
850
                case col_type_UUID:
9,774✔
851
                    if (init_value.is_null()) {
9,774✔
852
                        index->insert(key, ArrayUUIDNull::default_value(nullable));
3,669✔
853
                    }
3,669✔
854
                    else {
6,105✔
855
                        index->insert(key, init_value.get<UUID>());
6,105✔
856
                    }
6,105✔
857
                    break;
9,774✔
858
                default:
✔
859
                    REALM_UNREACHABLE();
860
            }
745,425✔
861
        }
745,425✔
862
    }
17,679,156✔
863
}
11,833,683✔
864

865
void Table::clear_indexes()
866
{
8,433✔
867
    for (auto&& index : m_index_accessors) {
46,815✔
868
        if (index) {
46,815✔
869
            index->clear();
1,692✔
870
        }
1,692✔
871
    }
46,815✔
872
}
8,433✔
873

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

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

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

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

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

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

904
    populate_search_index(col_key);
45,579✔
905
}
45,579✔
906

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

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

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

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

943
    do_add_search_index(col_key, type);
1,989✔
944

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

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

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

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

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

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

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

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

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

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

1001
    return col.size();
27✔
1002
}
69✔
1003

1004

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

1016

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

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

1025
    if (!col_key) {
378,642✔
1026
        col_key = generate_col_key(type, {});
41,235✔
1027
    }
41,235✔
1028

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

1058
    bump_storage_version();
378,642✔
1059

1060
    return col_key;
378,642✔
1061
}
378,642✔
1062

1063

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

1084
    build_column_mapping();
3,210✔
1085
    while (m_index_accessors.size() > m_leaf_ndx2colkey.size()) {
6,126✔
1086
        REALM_ASSERT(m_index_accessors.back() == nullptr);
2,916✔
1087
        m_index_accessors.pop_back();
2,916✔
1088
    }
2,916✔
1089
    bump_content_version();
3,210✔
1090
    bump_storage_version();
3,210✔
1091
}
3,210✔
1092

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

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

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

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

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

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

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

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

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

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

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

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

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

1207
        return IteratorControl::AdvanceToNext;
210✔
1208
    });
237✔
1209

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

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

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

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

1237

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

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

1254

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

1270

1271
IndexType Table::search_index_type(ColKey col_key) const noexcept
1272
{
1,940,943✔
1273
    if (m_index_accessors[col_key.get_index().val].get()) {
1,940,943✔
1274
        auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_key.get_index().val]);
457,425✔
1275
        bool fulltext = attr.test(col_attr_FullText_Indexed);
457,425✔
1276
        return fulltext ? IndexType::Fulltext : IndexType::General;
457,425✔
1277
    }
457,425✔
1278
    return IndexType::None;
1,483,518✔
1279
}
1,940,943✔
1280

1281

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

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

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

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

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

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

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

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

1391

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

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

1404

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

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

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

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

1469
    REALM_ASSERT(top.size() == top_array_size);
136,656✔
1470

1471
    return top.get_ref();
136,656✔
1472
}
136,656✔
1473

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

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

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

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

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

1514
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
5,175✔
1515
        CascadeState state(CascadeState::Mode::Strong, g);
4,791✔
1516
        std::for_each(keys.begin(), keys.end(), [this, &state](ObjKey k) {
4,791✔
1517
            state.m_to_be_deleted.emplace_back(m_key, k);
1,038✔
1518
        });
1,038✔
1519
        if (maybe_has_incoming_links)
4,791✔
1520
            nullify_links(state);
4,791✔
1521
        remove_recursive(state);
4,791✔
1522
    }
4,791✔
1523
    else {
384✔
1524
        CascadeState state(CascadeState::Mode::None, g);
384✔
1525
        for (auto k : keys) {
1,256,151✔
1526
            if (maybe_has_incoming_links) {
1,256,151✔
1527
                m_clusters.nullify_incoming_links(k, state);
1,256,112✔
1528
            }
1,256,112✔
1529
            m_clusters.erase(k, state);
1,256,151✔
1530
        }
1,256,151✔
1531
    }
384✔
1532
    keys.clear();
5,175✔
1533
}
5,175✔
1534

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

1542

1543
Group* Table::get_parent_group() const noexcept
1544
{
31,429,227✔
1545
    if (!m_top.is_attached())
31,429,227✔
1546
        return 0;                             // Subtable with shared descriptor
×
1547
    ArrayParent* parent = m_top.get_parent(); // ArrayParent guaranteed to be Table::Parent
31,429,227✔
1548
    if (!parent)
31,429,227✔
1549
        return 0; // Free-standing table
13,070,706✔
1550

1551
    return static_cast<Group*>(parent);
18,358,521✔
1552
}
31,429,227✔
1553

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

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

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

1577
    return sn;
10,297,734✔
1578
}
10,297,734✔
1579

1580
void Table::set_col_key_sequence_number(uint64_t seq)
1581
{
12✔
1582
    m_top.set(top_position_for_column_key, RefOrTagged::make_tagged(seq));
12✔
1583
}
12✔
1584

1585
TableRef Table::get_link_target(ColKey col_key) noexcept
1586
{
124,770✔
1587
    return get_opposite_table(col_key);
124,770✔
1588
}
124,770✔
1589

1590
// count ----------------------------------------------
1591

1592
size_t Table::count_int(ColKey col_key, int64_t value) const
1593
{
6,003✔
1594
    if (auto index = this->get_search_index(col_key)) {
6,003✔
1595
        return index->count(value);
6,000✔
1596
    }
6,000✔
1597

1598
    return where().equal(col_key, value).count();
3✔
1599
}
6,003✔
1600
size_t Table::count_float(ColKey col_key, float value) const
1601
{
3✔
1602
    return where().equal(col_key, value).count();
3✔
1603
}
3✔
1604
size_t Table::count_double(ColKey col_key, double value) const
1605
{
3✔
1606
    return where().equal(col_key, value).count();
3✔
1607
}
3✔
1608
size_t Table::count_decimal(ColKey col_key, Decimal128 value) const
1609
{
9✔
1610
    ArrayDecimal128 leaf(get_alloc());
9✔
1611
    size_t cnt = 0;
9✔
1612
    bool null_value = value.is_null();
9✔
1613
    auto f = [value, &leaf, col_key, null_value, &cnt](const Cluster* cluster) {
9✔
1614
        // direct aggregate on the leaf
1615
        cluster->init_leaf(col_key, &leaf);
9✔
1616
        auto sz = leaf.size();
9✔
1617
        for (size_t i = 0; i < sz; i++) {
648✔
1618
            if ((null_value && leaf.is_null(i)) || (leaf.get(i) == value)) {
639!
1619
                cnt++;
12✔
1620
            }
12✔
1621
        }
639✔
1622
        return IteratorControl::AdvanceToNext;
9✔
1623
    };
9✔
1624

1625
    traverse_clusters(f);
9✔
1626

1627
    return cnt;
9✔
1628
}
9✔
1629
size_t Table::count_string(ColKey col_key, StringData value) const
1630
{
738✔
1631
    if (auto index = this->get_search_index(col_key)) {
738✔
1632
        return index->count(value);
366✔
1633
    }
366✔
1634
    return where().equal(col_key, value).count();
372✔
1635
}
738✔
1636

1637
template <typename T>
1638
void Table::aggregate(QueryStateBase& st, ColKey column_key) const
1639
{
18,381✔
1640
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
18,381✔
1641
    LeafType leaf(get_alloc());
18,381✔
1642

1643
    auto f = [&leaf, column_key, &st](const Cluster* cluster) {
18,390✔
1644
        // direct aggregate on the leaf
1645
        cluster->init_leaf(column_key, &leaf);
18,390✔
1646
        st.m_key_offset = cluster->get_offset();
18,390✔
1647
        st.m_key_values = cluster->get_key_array();
18,390✔
1648
        st.set_payload_column(&leaf);
18,390✔
1649
        bool cont = true;
18,390✔
1650
        size_t sz = leaf.size();
18,390✔
1651
        for (size_t local_index = 0; cont && local_index < sz; local_index++) {
65,673✔
1652
            cont = st.match(local_index);
47,283✔
1653
        }
47,283✔
1654
        return IteratorControl::AdvanceToNext;
18,390✔
1655
    };
18,390✔
1656

1657
    traverse_clusters(f);
18,381✔
1658
}
18,381✔
1659

1660
// This template is also used by the query engine
1661
template void Table::aggregate<int64_t>(QueryStateBase&, ColKey) const;
1662
template void Table::aggregate<std::optional<int64_t>>(QueryStateBase&, ColKey) const;
1663
template void Table::aggregate<float>(QueryStateBase&, ColKey) const;
1664
template void Table::aggregate<double>(QueryStateBase&, ColKey) const;
1665
template void Table::aggregate<Decimal128>(QueryStateBase&, ColKey) const;
1666
template void Table::aggregate<Mixed>(QueryStateBase&, ColKey) const;
1667
template void Table::aggregate<Timestamp>(QueryStateBase&, ColKey) const;
1668

1669
std::optional<Mixed> Table::sum(ColKey col_key) const
1670
{
378✔
1671
    return AggregateHelper<Table>::sum(*this, *this, col_key);
378✔
1672
}
378✔
1673

1674
std::optional<Mixed> Table::avg(ColKey col_key, size_t* value_count) const
1675
{
411✔
1676
    return AggregateHelper<Table>::avg(*this, *this, col_key, value_count);
411✔
1677
}
411✔
1678

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

1684
std::optional<Mixed> Table::max(ColKey col_key, ObjKey* return_ndx) const
1685
{
15,240✔
1686
    return AggregateHelper<Table>::max(*this, *this, col_key, return_ndx);
15,240✔
1687
}
15,240✔
1688

1689

1690
SearchIndex* Table::get_search_index(ColKey col) const noexcept
1691
{
15,048,927✔
1692
    check_column(col);
15,048,927✔
1693
    return m_index_accessors[col.get_index().val].get();
15,048,927✔
1694
}
15,048,927✔
1695

1696
StringIndex* Table::get_string_index(ColKey col) const noexcept
1697
{
375,852✔
1698
    check_column(col);
375,852✔
1699
    return dynamic_cast<StringIndex*>(m_index_accessors[col.get_index().val].get());
375,852✔
1700
}
375,852✔
1701

1702
template <class T>
1703
ObjKey Table::find_first(ColKey col_key, T value) const
1704
{
17,670✔
1705
    check_column(col_key);
17,670✔
1706

1707
    if (!col_key.is_nullable() && value_is_null(value)) {
17,670!
1708
        return {}; // this is a precaution/optimization
3✔
1709
    }
3✔
1710
    // You cannot call GetIndexData on ObjKey
1711
    if constexpr (!std::is_same_v<T, ObjKey>) {
17,667✔
1712
        if (SearchIndex* index = get_search_index(col_key)) {
17,658!
1713
            return index->find_first(value);
13,734✔
1714
        }
13,734✔
1715
        if (col_key == m_primary_key_col) {
3,924!
1716
            return find_primary_key(value);
×
1717
        }
×
1718
    }
3,924✔
1719

1720
    ObjKey key;
3,924✔
1721
    using LeafType = typename ColumnTypeTraits<T>::cluster_leaf_type;
17,667✔
1722
    LeafType leaf(get_alloc());
17,667✔
1723

1724
    auto f = [&key, &col_key, &value, &leaf](const Cluster* cluster) {
17,667✔
1725
        cluster->init_leaf(col_key, &leaf);
4,665✔
1726
        size_t row = leaf.find_first(value, 0, cluster->node_size());
4,665✔
1727
        if (row != realm::npos) {
4,665!
1728
            key = cluster->get_real_key(row);
3,846✔
1729
            return IteratorControl::Stop;
3,846✔
1730
        }
3,846✔
1731
        return IteratorControl::AdvanceToNext;
819✔
1732
    };
4,665✔
1733

1734
    traverse_clusters(f);
17,667✔
1735

1736
    return key;
17,667✔
1737
}
17,670✔
1738

1739
namespace realm {
1740

1741
template <>
1742
ObjKey Table::find_first(ColKey col_key, util::Optional<float> value) const
1743
{
×
1744
    return value ? find_first(col_key, *value) : find_first_null(col_key);
×
1745
}
×
1746

1747
template <>
1748
ObjKey Table::find_first(ColKey col_key, util::Optional<double> value) const
1749
{
×
1750
    return value ? find_first(col_key, *value) : find_first_null(col_key);
×
1751
}
×
1752

1753
template <>
1754
ObjKey Table::find_first(ColKey col_key, null) const
1755
{
×
1756
    return find_first_null(col_key);
×
1757
}
×
1758
} // namespace realm
1759

1760
// Explicitly instantiate the generic case of the template for the types we care about.
1761
template ObjKey Table::find_first(ColKey col_key, bool) const;
1762
template ObjKey Table::find_first(ColKey col_key, int64_t) const;
1763
template ObjKey Table::find_first(ColKey col_key, float) const;
1764
template ObjKey Table::find_first(ColKey col_key, double) const;
1765
template ObjKey Table::find_first(ColKey col_key, Decimal128) const;
1766
template ObjKey Table::find_first(ColKey col_key, ObjectId) const;
1767
template ObjKey Table::find_first(ColKey col_key, ObjKey) const;
1768
template ObjKey Table::find_first(ColKey col_key, util::Optional<bool>) const;
1769
template ObjKey Table::find_first(ColKey col_key, util::Optional<int64_t>) const;
1770
template ObjKey Table::find_first(ColKey col_key, StringData) const;
1771
template ObjKey Table::find_first(ColKey col_key, BinaryData) const;
1772
template ObjKey Table::find_first(ColKey col_key, Mixed) const;
1773
template ObjKey Table::find_first(ColKey col_key, UUID) const;
1774
template ObjKey Table::find_first(ColKey col_key, util::Optional<ObjectId>) const;
1775
template ObjKey Table::find_first(ColKey col_key, util::Optional<UUID>) const;
1776

1777
ObjKey Table::find_first_int(ColKey col_key, int64_t value) const
1778
{
3,849✔
1779
    if (is_nullable(col_key))
3,849✔
1780
        return find_first<util::Optional<int64_t>>(col_key, value);
18✔
1781
    else
3,831✔
1782
        return find_first<int64_t>(col_key, value);
3,831✔
1783
}
3,849✔
1784

1785
ObjKey Table::find_first_bool(ColKey col_key, bool value) const
1786
{
39✔
1787
    if (is_nullable(col_key))
39✔
1788
        return find_first<util::Optional<bool>>(col_key, value);
18✔
1789
    else
21✔
1790
        return find_first<bool>(col_key, value);
21✔
1791
}
39✔
1792

1793
ObjKey Table::find_first_timestamp(ColKey col_key, Timestamp value) const
1794
{
54✔
1795
    return find_first(col_key, value);
54✔
1796
}
54✔
1797

1798
ObjKey Table::find_first_object_id(ColKey col_key, ObjectId value) const
1799
{
3✔
1800
    return find_first(col_key, value);
3✔
1801
}
3✔
1802

1803
ObjKey Table::find_first_float(ColKey col_key, float value) const
1804
{
6✔
1805
    return find_first<Float>(col_key, value);
6✔
1806
}
6✔
1807

1808
ObjKey Table::find_first_double(ColKey col_key, double value) const
1809
{
6✔
1810
    return find_first<Double>(col_key, value);
6✔
1811
}
6✔
1812

1813
ObjKey Table::find_first_decimal(ColKey col_key, Decimal128 value) const
1814
{
×
1815
    return find_first<Decimal128>(col_key, value);
×
1816
}
×
1817

1818
ObjKey Table::find_first_string(ColKey col_key, StringData value) const
1819
{
5,778✔
1820
    return find_first<StringData>(col_key, value);
5,778✔
1821
}
5,778✔
1822

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

1828
ObjKey Table::find_first_null(ColKey col_key) const
1829
{
57✔
1830
    return where().equal(col_key, null{}).find();
57✔
1831
}
57✔
1832

1833
ObjKey Table::find_first_uuid(ColKey col_key, UUID value) const
1834
{
9✔
1835
    return find_first(col_key, value);
9✔
1836
}
9✔
1837

1838
template <class T>
1839
TableView Table::find_all(ColKey col_key, T value)
1840
{
54✔
1841
    return where().equal(col_key, value).find_all();
54✔
1842
}
54✔
1843

1844
TableView Table::find_all_int(ColKey col_key, int64_t value)
1845
{
51✔
1846
    return find_all<int64_t>(col_key, value);
51✔
1847
}
51✔
1848

1849
TableView Table::find_all_int(ColKey col_key, int64_t value) const
1850
{
×
1851
    return const_cast<Table*>(this)->find_all<int64_t>(col_key, value);
×
1852
}
×
1853

1854
TableView Table::find_all_bool(ColKey col_key, bool value)
1855
{
×
1856
    return find_all<bool>(col_key, value);
×
1857
}
×
1858

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

1864

1865
TableView Table::find_all_float(ColKey col_key, float value)
1866
{
×
1867
    return find_all<float>(col_key, value);
×
1868
}
×
1869

1870
TableView Table::find_all_float(ColKey col_key, float value) const
1871
{
×
1872
    return const_cast<Table*>(this)->find_all<float>(col_key, value);
×
1873
}
×
1874

1875
TableView Table::find_all_double(ColKey col_key, double value)
1876
{
3✔
1877
    return find_all<double>(col_key, value);
3✔
1878
}
3✔
1879

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

1885
TableView Table::find_all_string(ColKey col_key, StringData value)
1886
{
141✔
1887
    return where().equal(col_key, value).find_all();
141✔
1888
}
141✔
1889

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

1895
TableView Table::find_all_binary(ColKey, BinaryData)
1896
{
×
1897
    throw Exception(ErrorCodes::IllegalOperation, "Table::find_all_binary not supported");
×
1898
}
×
1899

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

1905
TableView Table::find_all_null(ColKey col_key)
1906
{
×
1907
    return where().equal(col_key, null{}).find_all();
×
1908
}
×
1909

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

1915
TableView Table::find_all_fulltext(ColKey col_key, StringData terms) const
1916
{
3✔
1917
    return where().fulltext(col_key, terms).find_all();
3✔
1918
}
3✔
1919

1920
TableView Table::get_sorted_view(ColKey col_key, bool ascending)
1921
{
36✔
1922
    TableView tv = where().find_all();
36✔
1923
    tv.sort(col_key, ascending);
36✔
1924
    return tv;
36✔
1925
}
36✔
1926

1927
TableView Table::get_sorted_view(ColKey col_key, bool ascending) const
1928
{
3✔
1929
    return const_cast<Table*>(this)->get_sorted_view(col_key, ascending);
3✔
1930
}
3✔
1931

1932
TableView Table::get_sorted_view(SortDescriptor order)
1933
{
63✔
1934
    TableView tv = where().find_all();
63✔
1935
    tv.sort(std::move(order));
63✔
1936
    return tv;
63✔
1937
}
63✔
1938

1939
TableView Table::get_sorted_view(SortDescriptor order) const
1940
{
×
1941
    return const_cast<Table*>(this)->get_sorted_view(std::move(order));
×
1942
}
×
1943

1944
util::Logger* Table::get_logger() const noexcept
1945
{
963,522✔
1946
    return *m_repl ? (*m_repl)->get_logger() : nullptr;
963,522✔
1947
}
963,522✔
1948

1949
// Called after a commit. Table will effectively contain the same as before,
1950
// but now with new refs from the file
1951
void Table::update_from_parent() noexcept
1952
{
354,840✔
1953
    // There is no top for sub-tables sharing spec
1954
    if (m_top.is_attached()) {
354,840✔
1955
        m_top.init_from_parent();
354,840✔
1956
        m_spec.init_from_parent();
354,840✔
1957
        m_clusters.update_from_parent();
354,840✔
1958
        m_index_refs.init_from_parent();
354,840✔
1959
        for (auto&& index : m_index_accessors) {
1,067,145✔
1960
            if (index != nullptr) {
1,067,145✔
1961
                index->update_from_parent();
135,633✔
1962
            }
135,633✔
1963
        }
1,067,145✔
1964

1965
        m_opposite_table.init_from_parent();
354,840✔
1966
        m_opposite_column.init_from_parent();
354,840✔
1967
        if (m_top.size() > top_position_for_flags) {
354,840✔
1968
            uint64_t flags = m_top.get_as_ref_or_tagged(top_position_for_flags).get_as_int();
354,825✔
1969
            m_table_type = Type(flags & table_type_mask);
354,825✔
1970
        }
354,825✔
1971
        else {
15✔
1972
            m_table_type = Type::TopLevel;
15✔
1973
        }
15✔
1974
        if (m_tombstones)
354,840✔
1975
            m_tombstones->update_from_parent();
2,061✔
1976

1977
        refresh_content_version();
354,840✔
1978
        m_has_any_embedded_objects.reset();
354,840✔
1979
    }
354,840✔
1980
    m_alloc.bump_storage_version();
354,840✔
1981
}
354,840✔
1982

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

2039
bool Table::operator==(const Table& t) const
2040
{
69✔
2041
    if (size() != t.size()) {
69✔
2042
        return false;
6✔
2043
    }
6✔
2044
    // Check columns
2045
    for (auto ck : this->get_column_keys()) {
267✔
2046
        auto name = get_column_name(ck);
267✔
2047
        auto other_ck = t.get_column_key(name);
267✔
2048
        auto attrs = ck.get_attrs();
267✔
2049
        if (search_index_type(ck) != t.search_index_type(other_ck))
267✔
2050
            return false;
×
2051

2052
        if (!other_ck || other_ck.get_attrs() != attrs) {
267✔
2053
            return false;
×
2054
        }
×
2055
    }
267✔
2056
    auto pk_col = get_primary_key_column();
63✔
2057
    for (auto o : *this) {
1,449✔
2058
        Obj other_o;
1,449✔
2059
        if (pk_col) {
1,449✔
2060
            auto pk = o.get_any(pk_col);
45✔
2061
            other_o = t.get_object_with_primary_key(pk);
45✔
2062
        }
45✔
2063
        else {
1,404✔
2064
            other_o = t.get_object(o.get_key());
1,404✔
2065
        }
1,404✔
2066
        if (!(other_o && o == other_o))
1,449✔
2067
            return false;
9✔
2068
    }
1,449✔
2069

2070
    return true;
54✔
2071
}
63✔
2072

2073

2074
void Table::flush_for_commit()
2075
{
520,377✔
2076
    if (m_top.is_attached() && m_top.size() >= top_position_for_version) {
520,383✔
2077
        if (!m_top.is_read_only()) {
520,383✔
2078
            ++m_in_file_version_at_transaction_boundary;
395,580✔
2079
            auto rot_version = RefOrTagged::make_tagged(m_in_file_version_at_transaction_boundary);
395,580✔
2080
            m_top.set(top_position_for_version, rot_version);
395,580✔
2081
        }
395,580✔
2082
    }
520,383✔
2083
}
520,377✔
2084

2085
void Table::refresh_content_version()
2086
{
557,631✔
2087
    REALM_ASSERT(m_top.is_attached());
557,631✔
2088
    if (m_top.size() >= top_position_for_version) {
557,631✔
2089
        // we have versioning info in the file. Use this to conditionally
2090
        // bump the version counter:
2091
        auto rot_version = m_top.get_as_ref_or_tagged(top_position_for_version);
557,481✔
2092
        REALM_ASSERT(rot_version.is_tagged());
557,481✔
2093
        if (m_in_file_version_at_transaction_boundary != rot_version.get_as_int()) {
557,481✔
2094
            m_in_file_version_at_transaction_boundary = rot_version.get_as_int();
147,684✔
2095
            bump_content_version();
147,684✔
2096
        }
147,684✔
2097
    }
557,481✔
2098
    else {
150✔
2099
        // assume the worst:
2100
        bump_content_version();
150✔
2101
    }
150✔
2102
}
557,631✔
2103

2104

2105
// Called when Group is moved to another version - either a rollback or an advance.
2106
// The content of the table is potentially different, so make no assumptions.
2107
void Table::refresh_accessor_tree()
2108
{
202,503✔
2109
    REALM_ASSERT(m_cookie == cookie_initialized);
202,503✔
2110
    REALM_ASSERT(m_top.is_attached());
202,503✔
2111
    m_top.init_from_parent();
202,503✔
2112
    m_spec.init_from_parent();
202,503✔
2113
    REALM_ASSERT(m_top.size() > top_position_for_pk_col);
202,503✔
2114
    m_clusters.init_from_parent();
202,503✔
2115
    m_index_refs.init_from_parent();
202,503✔
2116
    m_opposite_table.init_from_parent();
202,503✔
2117
    m_opposite_column.init_from_parent();
202,503✔
2118
    auto rot_pk_key = m_top.get_as_ref_or_tagged(top_position_for_pk_col);
202,503✔
2119
    m_primary_key_col = rot_pk_key.is_tagged() ? ColKey(rot_pk_key.get_as_int()) : ColKey();
202,503✔
2120
    if (m_top.size() > top_position_for_flags) {
202,605✔
2121
        auto rot_flags = m_top.get_as_ref_or_tagged(top_position_for_flags);
202,605✔
2122
        m_table_type = Type(rot_flags.get_as_int() & table_type_mask);
202,605✔
2123
    }
202,605✔
2124
    else {
2,147,483,647✔
2125
        m_table_type = Type::TopLevel;
2,147,483,647✔
2126
    }
2,147,483,647✔
2127
    if (m_top.size() > top_position_for_tombstones && m_top.get_as_ref(top_position_for_tombstones)) {
202,527✔
2128
        // Tombstones exists
2129
        if (!m_tombstones) {
1,206✔
2130
            m_tombstones = std::make_unique<ClusterTree>(this, m_alloc, size_t(top_position_for_tombstones));
237✔
2131
        }
237✔
2132
        m_tombstones->init_from_parent();
1,206✔
2133
    }
1,206✔
2134
    else {
201,297✔
2135
        m_tombstones = nullptr;
201,297✔
2136
    }
201,297✔
2137
    refresh_content_version();
202,503✔
2138
    bump_storage_version();
202,503✔
2139
    build_column_mapping();
202,503✔
2140
    refresh_index_accessors();
202,503✔
2141
}
202,503✔
2142

2143
void Table::refresh_index_accessors()
2144
{
1,984,908✔
2145
    // Refresh search index accessors
2146

2147
    // First eliminate any index accessors for eliminated last columns
2148
    size_t col_ndx_end = m_leaf_ndx2colkey.size();
1,984,908✔
2149
    m_index_accessors.resize(col_ndx_end);
1,984,908✔
2150

2151
    // Then eliminate/refresh/create accessors within column range
2152
    // we can not use for_each_column() here, since the columns may have changed
2153
    // and the index accessor vector is not updated correspondingly.
2154
    for (size_t col_ndx = 0; col_ndx < col_ndx_end; col_ndx++) {
9,716,463✔
2155
        ref_type ref = m_index_refs.get_as_ref(col_ndx);
7,731,555✔
2156

2157
        if (ref == 0) {
7,731,555✔
2158
            // accessor drop
2159
            m_index_accessors[col_ndx].reset();
7,266,540✔
2160
        }
7,266,540✔
2161
        else {
465,015✔
2162
            auto attr = m_spec.get_column_attr(m_leaf_ndx2spec_ndx[col_ndx]);
465,015✔
2163
            bool fulltext = attr.test(col_attr_FullText_Indexed);
465,015✔
2164
            auto col_key = m_leaf_ndx2colkey[col_ndx];
465,015✔
2165
            ClusterColumn virtual_col(&m_clusters, col_key, fulltext ? IndexType::Fulltext : IndexType::General);
465,015✔
2166

2167
            if (m_index_accessors[col_ndx]) { // still there, refresh:
465,015✔
2168
                m_index_accessors[col_ndx]->refresh_accessor_tree(virtual_col);
166,899✔
2169
            }
166,899✔
2170
            else { // new index!
298,116✔
2171
                m_index_accessors[col_ndx] =
298,116✔
2172
                    std::make_unique<StringIndex>(ref, &m_index_refs, col_ndx, virtual_col, get_alloc());
298,116✔
2173
            }
298,116✔
2174
        }
465,015✔
2175
    }
7,731,555✔
2176
}
1,984,908✔
2177

2178
bool Table::is_cross_table_link_target() const noexcept
2179
{
795✔
2180
    auto is_cross_link = [this](ColKey col_key) {
795✔
2181
        auto t = col_key.get_type();
30✔
2182
        // look for a backlink with a different target than ourselves
2183
        return (t == col_type_BackLink && get_opposite_table_key(col_key) != get_key())
30✔
2184
                   ? IteratorControl::Stop
30✔
2185
                   : IteratorControl::AdvanceToNext;
30✔
2186
    };
30✔
2187
    return for_each_backlink_column(is_cross_link);
795✔
2188
}
795✔
2189

2190
// LCOV_EXCL_START ignore debug functions
2191

2192
void Table::verify() const
2193
{
121,842✔
2194
#ifdef REALM_DEBUG
121,842✔
2195
    if (m_top.is_attached())
121,842✔
2196
        m_top.verify();
121,842✔
2197
    m_spec.verify();
121,842✔
2198
    m_clusters.verify();
121,842✔
2199
    if (nb_unresolved())
121,842✔
2200
        m_tombstones->verify();
17,640✔
2201
#endif
121,842✔
2202
}
121,842✔
2203

2204
#ifdef REALM_DEBUG
2205
MemStats Table::stats() const
2206
{
×
2207
    MemStats mem_stats;
×
2208
    m_top.stats(mem_stats);
×
2209
    return mem_stats;
×
2210
}
×
2211
#endif // LCOV_EXCL_STOP ignore debug functions
2212

2213
Obj Table::create_object(ObjKey key, const FieldValues& values)
2214
{
11,440,251✔
2215
    if (is_embedded())
11,440,251✔
2216
        throw IllegalOperation(util::format("Explicit creation of embedded object not allowed in: %1", get_name()));
24✔
2217
    if (m_primary_key_col)
11,440,227✔
2218
        throw IllegalOperation(util::format("Table has primary key: %1", get_name()));
×
2219
    if (key == null_key) {
11,440,227✔
2220
        GlobalKey object_id = allocate_object_id_squeezed();
9,866,712✔
2221
        key = object_id.get_local_key(get_sync_file_id());
9,866,712✔
2222
        // Check if this key collides with an already existing object
2223
        // This could happen if objects were at some point created with primary keys,
2224
        // but later primary key property was removed from the schema.
2225
        while (m_clusters.is_valid(key)) {
9,866,712✔
2226
            object_id = allocate_object_id_squeezed();
×
2227
            key = object_id.get_local_key(get_sync_file_id());
×
2228
        }
×
2229
        if (auto repl = get_repl())
9,866,712✔
2230
            repl->create_object(this, object_id);
2,155,635✔
2231
    }
9,866,712✔
2232

2233
    REALM_ASSERT(key.value >= 0);
11,440,227✔
2234

2235
    Obj obj = m_clusters.insert(key, values); // repl->set()
11,440,227✔
2236

2237
    return obj;
11,440,227✔
2238
}
11,440,227✔
2239

2240
Obj Table::create_linked_object()
2241
{
23,886✔
2242
    REALM_ASSERT(is_embedded());
23,886✔
2243

2244
    GlobalKey object_id = allocate_object_id_squeezed();
23,886✔
2245
    ObjKey key = object_id.get_local_key(get_sync_file_id());
23,886✔
2246
    REALM_ASSERT(key.value >= 0);
23,886✔
2247

2248
    if (auto repl = get_repl())
23,886✔
2249
        repl->create_linked_object(this, key);
23,229✔
2250

2251
    Obj obj = m_clusters.insert(key, {});
23,886✔
2252

2253
    return obj;
23,886✔
2254
}
23,886✔
2255

2256
Obj Table::create_object(GlobalKey object_id, const FieldValues& values)
2257
{
15✔
2258
    if (is_embedded())
15✔
2259
        throw IllegalOperation(util::format("Explicit creation of embedded object not allowed in: %1", get_name()));
×
2260
    if (m_primary_key_col)
15✔
2261
        throw IllegalOperation(util::format("Table has primary key: %1", get_name()));
×
2262
    ObjKey key = object_id.get_local_key(get_sync_file_id());
15✔
2263

2264
    if (auto repl = get_repl())
15✔
2265
        repl->create_object(this, object_id);
15✔
2266

2267
    try {
15✔
2268
        Obj obj = m_clusters.insert(key, values);
15✔
2269
        // Check if tombstone exists
2270
        if (m_tombstones && m_tombstones->is_valid(key.get_unresolved())) {
15✔
2271
            auto unres_key = key.get_unresolved();
3✔
2272
            // Copy links over
2273
            auto tombstone = m_tombstones->get(unres_key);
3✔
2274
            obj.assign_pk_and_backlinks(tombstone);
3✔
2275
            // If tombstones had no links to it, it may still be alive
2276
            if (m_tombstones->is_valid(unres_key)) {
3✔
2277
                CascadeState state(CascadeState::Mode::None);
3✔
2278
                m_tombstones->erase(unres_key, state);
3✔
2279
            }
3✔
2280
        }
3✔
2281

2282
        return obj;
15✔
2283
    }
15✔
2284
    catch (const KeyAlreadyUsed&) {
15✔
2285
        return m_clusters.get(key);
3✔
2286
    }
3✔
2287
}
15✔
2288

2289
Obj Table::create_object_with_primary_key(const Mixed& primary_key, FieldValues&& field_values, UpdateMode mode,
2290
                                          bool* did_create)
2291
{
518,586✔
2292
    auto primary_key_col = get_primary_key_column();
518,586✔
2293
    if (is_embedded() || !primary_key_col)
518,586✔
2294
        throw InvalidArgument(ErrorCodes::UnexpectedPrimaryKey,
3✔
2295
                              util::format("Table has no primary key: %1", get_name()));
3✔
2296

2297
    DataType type = DataType(primary_key_col.get_type());
518,583✔
2298

2299
    if (primary_key.is_null() && !primary_key_col.is_nullable()) {
518,583✔
2300
        throw InvalidArgument(
3✔
2301
            ErrorCodes::PropertyNotNullable,
3✔
2302
            util::format("Primary key for class %1 cannot be NULL", Group::table_name_to_class_name(get_name())));
3✔
2303
    }
3✔
2304

2305
    if (!(primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) &&
518,580✔
2306
        primary_key.get_type() != type) {
518,580✔
2307
        throw InvalidArgument(ErrorCodes::TypeMismatch, util::format("Wrong primary key type for class %1",
3✔
2308
                                                                     Group::table_name_to_class_name(get_name())));
3✔
2309
    }
3✔
2310

2311
    REALM_ASSERT(type == type_String || type == type_ObjectId || type == type_Int || type == type_UUID);
518,577✔
2312

2313
    if (did_create)
518,577✔
2314
        *did_create = false;
48,690✔
2315

2316
    // Check for existing object
2317
    if (ObjKey key = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key)) {
518,577✔
2318
        if (mode == UpdateMode::never) {
88,452✔
2319
            throw ObjectAlreadyExists(this->get_class_name(), primary_key);
3✔
2320
        }
3✔
2321
        auto obj = m_clusters.get(key);
88,449✔
2322
        for (auto& val : field_values) {
88,449✔
2323
            if (mode == UpdateMode::all || obj.get_any(val.col_key) != val.value) {
6✔
2324
                obj.set_any(val.col_key, val.value, val.is_default);
6✔
2325
            }
6✔
2326
        }
6✔
2327
        return obj;
88,449✔
2328
    }
88,452✔
2329

2330
    ObjKey unres_key;
430,125✔
2331
    if (m_tombstones) {
430,125✔
2332
        // Check for potential tombstone
2333
        GlobalKey object_id{primary_key};
23,175✔
2334
        ObjKey object_key = global_to_local_object_id_hashed(object_id);
23,175✔
2335

2336
        ObjKey key = object_key.get_unresolved();
23,175✔
2337
        if (auto obj = m_tombstones->try_get_obj(key)) {
23,175✔
2338
            auto existing_pk_value = obj.get_any(primary_key_col);
19,695✔
2339

2340
            // If the primary key is the same, the object should be resurrected below
2341
            if (existing_pk_value == primary_key) {
19,695✔
2342
                unres_key = key;
19,692✔
2343
            }
19,692✔
2344
        }
19,695✔
2345
    }
23,175✔
2346

2347
    ObjKey key = get_next_valid_key();
430,125✔
2348

2349
    auto repl = get_repl();
430,125✔
2350
    if (repl) {
430,125✔
2351
        repl->create_object_with_primary_key(this, key, primary_key);
157,302✔
2352
    }
157,302✔
2353
    if (did_create) {
430,125✔
2354
        *did_create = true;
28,323✔
2355
    }
28,323✔
2356

2357
    field_values.insert(primary_key_col, primary_key);
430,125✔
2358
    Obj ret = m_clusters.insert(key, field_values);
430,125✔
2359

2360
    // Check if unresolved exists
2361
    if (unres_key) {
430,125✔
2362
        if (Replication* repl = get_repl()) {
19,692✔
2363
            if (auto logger = repl->would_log(util::Logger::Level::debug)) {
19,647✔
2364
                logger->log(LogCategory::object, util::Logger::Level::debug, "Cancel tombstone on '%1': %2",
18✔
2365
                            get_class_name(), unres_key);
18✔
2366
            }
18✔
2367
        }
19,647✔
2368

2369
        auto tombstone = m_tombstones->get(unres_key);
19,692✔
2370
        ret.assign_pk_and_backlinks(tombstone);
19,692✔
2371
        // If tombstones had no links to it, it may still be alive
2372
        if (m_tombstones->is_valid(unres_key)) {
19,692✔
2373
            CascadeState state(CascadeState::Mode::None);
19,662✔
2374
            m_tombstones->erase(unres_key, state);
19,662✔
2375
        }
19,662✔
2376
    }
19,692✔
2377
    if (is_asymmetric() && repl && repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
430,125✔
2378
        get_parent_group()->m_tables_to_clear.insert(this->m_key);
645✔
2379
    }
645✔
2380
    return ret;
430,125✔
2381
}
518,577✔
2382

2383
ObjKey Table::find_primary_key(Mixed primary_key) const
2384
{
380,472✔
2385
    auto primary_key_col = get_primary_key_column();
380,472✔
2386
    REALM_ASSERT(primary_key_col);
380,472✔
2387
    DataType type = DataType(primary_key_col.get_type());
380,472✔
2388
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
380,472✔
2389
                 primary_key.get_type() == type);
380,472✔
2390

2391
    if (auto&& index = m_index_accessors[primary_key_col.get_index().val]) {
380,472✔
2392
        return index->find_first(primary_key);
380,430✔
2393
    }
380,430✔
2394

2395
    // This must be file format 11, 20 or 21 as those are the ones we can open in read-only mode
2396
    // so try the old algorithm
2397
    GlobalKey object_id{primary_key};
42✔
2398
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
42✔
2399

2400
    // Check if existing
2401
    if (auto obj = m_clusters.try_get_obj(object_key)) {
42✔
2402
        auto existing_pk_value = obj.get_any(primary_key_col);
×
2403

2404
        if (existing_pk_value == primary_key) {
×
2405
            return object_key;
×
2406
        }
×
2407
    }
×
2408
    return {};
42✔
2409
}
42✔
2410

2411
ObjKey Table::get_objkey_from_primary_key(const Mixed& primary_key)
2412
{
322,518✔
2413
    // Check if existing
2414
    if (auto key = find_primary_key(primary_key)) {
322,518✔
2415
        return key;
302,250✔
2416
    }
302,250✔
2417

2418
    // Object does not exist - create tombstone
2419
    GlobalKey object_id{primary_key};
20,268✔
2420
    ObjKey object_key = global_to_local_object_id_hashed(object_id);
20,268✔
2421
    return get_or_create_tombstone(object_key, m_primary_key_col, primary_key).get_key();
20,268✔
2422
}
322,518✔
2423

2424
ObjKey Table::get_objkey_from_global_key(GlobalKey global_key)
2425
{
9✔
2426
    REALM_ASSERT(!m_primary_key_col);
9✔
2427
    auto object_key = global_key.get_local_key(get_sync_file_id());
9✔
2428

2429
    // Check if existing
2430
    if (m_clusters.is_valid(object_key)) {
9✔
2431
        return object_key;
6✔
2432
    }
6✔
2433

2434
    return get_or_create_tombstone(object_key, {}, {}).get_key();
3✔
2435
}
9✔
2436

2437
ObjKey Table::get_objkey(GlobalKey global_key) const
2438
{
9✔
2439
    ObjKey key;
9✔
2440
    REALM_ASSERT(!m_primary_key_col);
9✔
2441
    uint32_t max = std::numeric_limits<uint32_t>::max();
9✔
2442
    if (global_key.hi() <= max && global_key.lo() <= max) {
9✔
2443
        key = global_key.get_local_key(get_sync_file_id());
3✔
2444
    }
3✔
2445
    if (key && !is_valid(key)) {
9✔
2446
        key = realm::null_key;
3✔
2447
    }
3✔
2448
    return key;
9✔
2449
}
9✔
2450

2451
GlobalKey Table::get_object_id(ObjKey key) const
2452
{
72✔
2453
    auto col = get_primary_key_column();
72✔
2454
    if (col) {
72✔
2455
        const Obj obj = get_object(key);
12✔
2456
        auto val = obj.get_any(col);
12✔
2457
        return {val};
12✔
2458
    }
12✔
2459
    else {
60✔
2460
        return {key, get_sync_file_id()};
60✔
2461
    }
60✔
2462
    return {};
×
2463
}
72✔
2464

2465
Obj Table::get_object_with_primary_key(Mixed primary_key) const
2466
{
59,094✔
2467
    auto primary_key_col = get_primary_key_column();
59,094✔
2468
    REALM_ASSERT(primary_key_col);
59,094✔
2469
    DataType type = DataType(primary_key_col.get_type());
59,094✔
2470
    REALM_ASSERT((primary_key.is_null() && primary_key_col.get_attrs().test(col_attr_Nullable)) ||
59,094✔
2471
                 primary_key.get_type() == type);
59,094✔
2472
    ObjKey k = m_index_accessors[primary_key_col.get_index().val]->find_first(primary_key);
59,094✔
2473
    return k ? m_clusters.get(k) : Obj{};
59,094✔
2474
}
59,094✔
2475

2476
Mixed Table::get_primary_key(ObjKey key) const
2477
{
380,805✔
2478
    auto primary_key_col = get_primary_key_column();
380,805✔
2479
    REALM_ASSERT(primary_key_col);
380,805✔
2480
    if (key.is_unresolved()) {
380,805✔
2481
        REALM_ASSERT(m_tombstones);
396✔
2482
        return m_tombstones->get(key).get_any(primary_key_col);
396✔
2483
    }
396✔
2484
    else {
380,409✔
2485
        return m_clusters.get(key).get_any(primary_key_col);
380,409✔
2486
    }
380,409✔
2487
}
380,805✔
2488

2489
GlobalKey Table::allocate_object_id_squeezed()
2490
{
9,889,377✔
2491
    // m_client_file_ident will be zero if we haven't been in contact with
2492
    // the server yet.
2493
    auto peer_id = get_sync_file_id();
9,889,377✔
2494
    auto sequence = allocate_sequence_number();
9,889,377✔
2495
    return GlobalKey{peer_id, sequence};
9,889,377✔
2496
}
9,889,377✔
2497

2498
namespace {
2499

2500
/// Calculate optimistic local ID that may collide with others. It is up to
2501
/// the caller to ensure that collisions are detected and that
2502
/// allocate_local_id_after_collision() is called to obtain a non-colliding
2503
/// ID.
2504
inline ObjKey get_optimistic_local_id_hashed(GlobalKey global_id)
2505
{
43,851✔
2506
#if REALM_EXERCISE_OBJECT_ID_COLLISION
2507
    const uint64_t optimistic_mask = 0xff;
2508
#else
2509
    const uint64_t optimistic_mask = 0x3fffffffffffffff;
43,851✔
2510
#endif
43,851✔
2511
    static_assert(!(optimistic_mask >> 62), "optimistic Object ID mask must leave the 63rd and 64th bit zero");
43,851✔
2512
    return ObjKey{int64_t(global_id.lo() & optimistic_mask)};
43,851✔
2513
}
43,851✔
2514

2515
inline ObjKey make_tagged_local_id_after_hash_collision(uint64_t sequence_number)
2516
{
6✔
2517
    REALM_ASSERT(!(sequence_number >> 62));
6✔
2518
    return ObjKey{int64_t(0x4000000000000000 | sequence_number)};
6✔
2519
}
6✔
2520

2521
} // namespace
2522

2523
ObjKey Table::global_to_local_object_id_hashed(GlobalKey object_id) const
2524
{
43,851✔
2525
    ObjKey optimistic = get_optimistic_local_id_hashed(object_id);
43,851✔
2526

2527
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
43,851✔
2528
        Allocator& alloc = m_top.get_alloc();
12✔
2529
        Array collision_map{alloc};
12✔
2530
        collision_map.init_from_ref(collision_map_ref); // Throws
12✔
2531

2532
        Array hi{alloc};
12✔
2533
        hi.init_from_ref(to_ref(collision_map.get(s_collision_map_hi))); // Throws
12✔
2534

2535
        // Entries are ordered by hi,lo
2536
        size_t found = hi.find_first(object_id.hi());
12✔
2537
        if (found != npos && uint64_t(hi.get(found)) == object_id.hi()) {
12✔
2538
            Array lo{alloc};
12✔
2539
            lo.init_from_ref(to_ref(collision_map.get(s_collision_map_lo))); // Throws
12✔
2540
            size_t candidate = lo.find_first(object_id.lo(), found);
12✔
2541
            if (candidate != npos && uint64_t(hi.get(candidate)) == object_id.hi()) {
12✔
2542
                Array local_id{alloc};
12✔
2543
                local_id.init_from_ref(to_ref(collision_map.get(s_collision_map_local_id))); // Throws
12✔
2544
                return ObjKey{local_id.get(candidate)};
12✔
2545
            }
12✔
2546
        }
12✔
2547
    }
12✔
2548

2549
    return optimistic;
43,839✔
2550
}
43,851✔
2551

2552
ObjKey Table::allocate_local_id_after_hash_collision(GlobalKey incoming_id, GlobalKey colliding_id,
2553
                                                     ObjKey colliding_local_id)
2554
{
6✔
2555
    // Possible optimization: Cache these accessors
2556
    Allocator& alloc = m_top.get_alloc();
6✔
2557
    Array collision_map{alloc};
6✔
2558
    Array hi{alloc};
6✔
2559
    Array lo{alloc};
6✔
2560
    Array local_id{alloc};
6✔
2561

2562
    collision_map.set_parent(&m_top, top_position_for_collision_map);
6✔
2563
    hi.set_parent(&collision_map, s_collision_map_hi);
6✔
2564
    lo.set_parent(&collision_map, s_collision_map_lo);
6✔
2565
    local_id.set_parent(&collision_map, s_collision_map_local_id);
6✔
2566

2567
    ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map));
6✔
2568
    if (collision_map_ref) {
6✔
2569
        collision_map.init_from_parent(); // Throws
×
2570
    }
×
2571
    else {
6✔
2572
        MemRef mem = Array::create_empty_array(Array::type_HasRefs, false, alloc); // Throws
6✔
2573
        collision_map.init_from_mem(mem);                                          // Throws
6✔
2574
        collision_map.update_parent();
6✔
2575

2576
        ref_type lo_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref();       // Throws
6✔
2577
        ref_type hi_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref();       // Throws
6✔
2578
        ref_type local_id_ref = Array::create_array(Array::type_Normal, false, 0, 0, alloc).get_ref(); // Throws
6✔
2579
        collision_map.add(lo_ref);                                                                     // Throws
6✔
2580
        collision_map.add(hi_ref);                                                                     // Throws
6✔
2581
        collision_map.add(local_id_ref);                                                               // Throws
6✔
2582
    }
6✔
2583

2584
    hi.init_from_parent();       // Throws
6✔
2585
    lo.init_from_parent();       // Throws
6✔
2586
    local_id.init_from_parent(); // Throws
6✔
2587

2588
    size_t num_entries = hi.size();
6✔
2589
    REALM_ASSERT(lo.size() == num_entries);
6✔
2590
    REALM_ASSERT(local_id.size() == num_entries);
6✔
2591

2592
    auto lower_bound_object_id = [&](GlobalKey object_id) -> size_t {
12✔
2593
        size_t i = hi.lower_bound_int(int64_t(object_id.hi()));
12✔
2594
        while (i < num_entries && uint64_t(hi.get(i)) == object_id.hi() && uint64_t(lo.get(i)) < object_id.lo())
15✔
2595
            ++i;
3✔
2596
        return i;
12✔
2597
    };
12✔
2598

2599
    auto insert_collision = [&](GlobalKey object_id, ObjKey new_local_id) {
12✔
2600
        size_t i = lower_bound_object_id(object_id);
12✔
2601
        if (i != num_entries) {
12✔
2602
            GlobalKey existing{uint64_t(hi.get(i)), uint64_t(lo.get(i))};
3✔
2603
            if (existing == object_id) {
3✔
2604
                REALM_ASSERT(new_local_id.value == local_id.get(i));
×
2605
                return;
×
2606
            }
×
2607
        }
3✔
2608
        hi.insert(i, int64_t(object_id.hi()));
12✔
2609
        lo.insert(i, int64_t(object_id.lo()));
12✔
2610
        local_id.insert(i, new_local_id.value);
12✔
2611
        ++num_entries;
12✔
2612
    };
12✔
2613

2614
    auto sequence_number_for_local_id = allocate_sequence_number();
6✔
2615
    ObjKey new_local_id = make_tagged_local_id_after_hash_collision(sequence_number_for_local_id);
6✔
2616
    insert_collision(incoming_id, new_local_id);
6✔
2617
    insert_collision(colliding_id, colliding_local_id);
6✔
2618

2619
    return new_local_id;
6✔
2620
}
6✔
2621

2622
Obj Table::get_or_create_tombstone(ObjKey key, ColKey pk_col, Mixed pk_val)
2623
{
20,763✔
2624
    auto unres_key = key.get_unresolved();
20,763✔
2625

2626
    ensure_graveyard();
20,763✔
2627
    auto tombstone = m_tombstones->try_get_obj(unres_key);
20,763✔
2628
    if (tombstone) {
20,763✔
2629
        if (pk_col) {
213✔
2630
            auto existing_pk_value = tombstone.get_any(pk_col);
213✔
2631
            // It may just be the same object
2632
            if (existing_pk_value != pk_val) {
213✔
2633
                // We have a collision - create new ObjKey
2634
                key = allocate_local_id_after_hash_collision({pk_val}, {existing_pk_value}, key);
6✔
2635
                return get_or_create_tombstone(key, pk_col, pk_val);
6✔
2636
            }
6✔
2637
        }
213✔
2638
        return tombstone;
207✔
2639
    }
213✔
2640
    if (Replication* repl = get_repl()) {
20,550✔
2641
        if (auto logger = repl->would_log(util::Logger::Level::debug)) {
20,415✔
2642
            logger->log(LogCategory::object, util::Logger::Level::debug,
288✔
2643
                        "Create tombstone for object '%1' with primary key %2 : %3", get_class_name(), pk_val,
288✔
2644
                        unres_key);
288✔
2645
        }
288✔
2646
    }
20,415✔
2647
    return m_tombstones->insert(unres_key, {{pk_col, pk_val}});
20,550✔
2648
}
20,763✔
2649

2650
void Table::free_local_id_after_hash_collision(ObjKey key)
2651
{
2,661,621✔
2652
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
2,661,621✔
2653
        if (key.is_unresolved()) {
15✔
2654
            // Keys will always be inserted as resolved
2655
            key = key.get_unresolved();
12✔
2656
        }
12✔
2657
        // Possible optimization: Cache these accessors
2658
        Array collision_map{m_alloc};
15✔
2659
        Array local_id{m_alloc};
15✔
2660

2661
        collision_map.set_parent(&m_top, top_position_for_collision_map);
15✔
2662
        local_id.set_parent(&collision_map, s_collision_map_local_id);
15✔
2663
        collision_map.init_from_ref(collision_map_ref);
15✔
2664
        local_id.init_from_parent();
15✔
2665
        auto ndx = local_id.find_first(key.value);
15✔
2666
        if (ndx != realm::npos) {
15✔
2667
            Array hi{m_alloc};
12✔
2668
            Array lo{m_alloc};
12✔
2669

2670
            hi.set_parent(&collision_map, s_collision_map_hi);
12✔
2671
            lo.set_parent(&collision_map, s_collision_map_lo);
12✔
2672
            hi.init_from_parent();
12✔
2673
            lo.init_from_parent();
12✔
2674

2675
            hi.erase(ndx);
12✔
2676
            lo.erase(ndx);
12✔
2677
            local_id.erase(ndx);
12✔
2678
            if (hi.size() == 0) {
12✔
2679
                free_collision_table();
6✔
2680
            }
6✔
2681
        }
12✔
2682
    }
15✔
2683
}
2,661,621✔
2684

2685
void Table::free_collision_table()
2686
{
8,439✔
2687
    if (ref_type collision_map_ref = to_ref(m_top.get(top_position_for_collision_map))) {
8,439✔
2688
        Array::destroy_deep(collision_map_ref, m_alloc);
6✔
2689
        m_top.set(top_position_for_collision_map, 0);
6✔
2690
    }
6✔
2691
}
8,439✔
2692

2693
void Table::create_objects(size_t number, std::vector<ObjKey>& keys)
2694
{
1,944✔
2695
    while (number--) {
3,163,728✔
2696
        keys.push_back(create_object().get_key());
3,161,784✔
2697
    }
3,161,784✔
2698
}
1,944✔
2699

2700
void Table::create_objects(const std::vector<ObjKey>& keys)
2701
{
315✔
2702
    for (auto k : keys) {
2,808✔
2703
        create_object(k);
2,808✔
2704
    }
2,808✔
2705
}
315✔
2706

2707
void Table::dump_objects()
2708
{
×
2709
    m_clusters.dump_objects();
×
2710
    if (nb_unresolved())
×
2711
        m_tombstones->dump_objects();
×
2712
}
×
2713

2714
void Table::remove_object(ObjKey key)
2715
{
1,271,325✔
2716
    Group* g = get_parent_group();
1,271,325✔
2717

2718
    if (has_any_embedded_objects() || (g && g->has_cascade_notification_handler())) {
1,271,325✔
2719
        CascadeState state(CascadeState::Mode::Strong, g);
1,995✔
2720
        state.m_to_be_deleted.emplace_back(m_key, key);
1,995✔
2721
        m_clusters.nullify_incoming_links(key, state);
1,995✔
2722
        remove_recursive(state);
1,995✔
2723
    }
1,995✔
2724
    else {
1,269,330✔
2725
        CascadeState state(CascadeState::Mode::None, g);
1,269,330✔
2726
        if (g) {
1,269,330✔
2727
            m_clusters.nullify_incoming_links(key, state);
1,228,419✔
2728
        }
1,228,419✔
2729
        m_clusters.erase(key, state);
1,269,330✔
2730
    }
1,269,330✔
2731
}
1,271,325✔
2732

2733
ObjKey Table::invalidate_object(ObjKey key)
2734
{
4,413✔
2735
    if (is_embedded())
4,413✔
2736
        throw IllegalOperation("Deletion of embedded object not allowed");
×
2737
    REALM_ASSERT(!key.is_unresolved());
4,413✔
2738

2739
    Obj tombstone;
4,413✔
2740
    auto obj = get_object(key);
4,413✔
2741
    if (obj.has_backlinks(false)) {
4,413✔
2742
        // If the object has backlinks, we should make a tombstone
2743
        // and make inward links point to it,
2744
        if (auto primary_key_col = get_primary_key_column()) {
492✔
2745
            auto pk = obj.get_any(primary_key_col);
414✔
2746
            GlobalKey object_id{pk};
414✔
2747
            auto unres_key = global_to_local_object_id_hashed(object_id);
414✔
2748
            tombstone = get_or_create_tombstone(unres_key, primary_key_col, pk);
414✔
2749
        }
414✔
2750
        else {
78✔
2751
            tombstone = get_or_create_tombstone(key, {}, {});
78✔
2752
        }
78✔
2753
        tombstone.assign_pk_and_backlinks(obj);
492✔
2754
    }
492✔
2755

2756
    remove_object(key);
4,413✔
2757

2758
    return tombstone.get_key();
4,413✔
2759
}
4,413✔
2760

2761
void Table::remove_object_recursive(ObjKey key)
2762
{
84,024✔
2763
    size_t table_ndx = get_index_in_group();
84,024✔
2764
    if (table_ndx != realm::npos) {
84,024✔
2765
        CascadeState state(CascadeState::Mode::All, get_parent_group());
84,024✔
2766
        state.m_to_be_deleted.emplace_back(m_key, key);
84,024✔
2767
        nullify_links(state);
84,024✔
2768
        remove_recursive(state);
84,024✔
2769
    }
84,024✔
2770
    else {
×
2771
        // No links in freestanding table
2772
        CascadeState state(CascadeState::Mode::None);
×
2773
        m_clusters.erase(key, state);
×
2774
    }
×
2775
}
84,024✔
2776

2777
Table::Iterator Table::begin() const
2778
{
274,392✔
2779
    return Iterator(m_clusters, 0);
274,392✔
2780
}
274,392✔
2781

2782
Table::Iterator Table::end() const
2783
{
4,707,189✔
2784
    return Iterator(m_clusters, size());
4,707,189✔
2785
}
4,707,189✔
2786

2787
TableRef _impl::TableFriend::get_opposite_link_table(const Table& table, ColKey col_key)
2788
{
3,585,249✔
2789
    TableRef ret;
3,585,249✔
2790
    if (col_key) {
3,585,249✔
2791
        return table.get_opposite_table(col_key);
3,585,231✔
2792
    }
3,585,231✔
2793
    return ret;
18✔
2794
}
3,585,249✔
2795

2796
const uint64_t Table::max_num_columns;
2797

2798
void Table::build_column_mapping()
2799
{
1,986,462✔
2800
    // build column mapping from spec
2801
    // TODO: Optimization - Don't rebuild this for every change
2802
    m_spec_ndx2leaf_ndx.clear();
1,986,462✔
2803
    m_leaf_ndx2spec_ndx.clear();
1,986,462✔
2804
    m_leaf_ndx2colkey.clear();
1,986,462✔
2805
    size_t num_spec_cols = m_spec.get_column_count();
1,986,462✔
2806
    m_spec_ndx2leaf_ndx.resize(num_spec_cols);
1,986,462✔
2807
    for (size_t spec_ndx = 0; spec_ndx < num_spec_cols; ++spec_ndx) {
9,694,767✔
2808
        ColKey col_key = m_spec.get_key(spec_ndx);
7,708,305✔
2809
        unsigned leaf_ndx = col_key.get_index().val;
7,708,305✔
2810
        if (leaf_ndx >= m_leaf_ndx2colkey.size()) {
7,708,305✔
2811
            m_leaf_ndx2colkey.resize(leaf_ndx + 1);
7,457,904✔
2812
            m_leaf_ndx2spec_ndx.resize(leaf_ndx + 1, -1);
7,457,904✔
2813
        }
7,457,904✔
2814
        m_spec_ndx2leaf_ndx[spec_ndx] = ColKey::Idx{leaf_ndx};
7,708,305✔
2815
        m_leaf_ndx2spec_ndx[leaf_ndx] = spec_ndx;
7,708,305✔
2816
        m_leaf_ndx2colkey[leaf_ndx] = col_key;
7,708,305✔
2817
    }
7,708,305✔
2818
}
1,986,462✔
2819

2820
ColKey Table::generate_col_key(ColumnType tp, ColumnAttrMask attr)
2821
{
378,642✔
2822
    REALM_ASSERT(!attr.test(col_attr_Indexed));
378,642✔
2823
    REALM_ASSERT(!attr.test(col_attr_Unique)); // Must not be encoded into col_key
378,642✔
2824

2825
    int64_t col_seq_number = m_top.get_as_ref_or_tagged(top_position_for_column_key).get_as_int();
378,642✔
2826
    unsigned upper = unsigned(col_seq_number ^ get_key().value);
378,642✔
2827

2828
    // reuse lowest available leaf ndx:
2829
    unsigned lower = unsigned(m_leaf_ndx2colkey.size());
378,642✔
2830
    // look for an unused entry:
2831
    for (unsigned idx = 0; idx < lower; ++idx) {
2,811,120✔
2832
        if (m_leaf_ndx2colkey[idx] == ColKey()) {
2,432,529✔
2833
            lower = idx;
51✔
2834
            break;
51✔
2835
        }
51✔
2836
    }
2,432,529✔
2837
    return ColKey(ColKey::Idx{lower}, tp, attr, upper);
378,642✔
2838
}
378,642✔
2839

2840
Table::BacklinkOrigin Table::find_backlink_origin(StringData origin_table_name,
2841
                                                  StringData origin_col_name) const noexcept
2842
{
×
2843
    BacklinkOrigin ret;
×
2844
    auto f = [&](ColKey backlink_col_key) {
×
2845
        auto origin_table = get_opposite_table(backlink_col_key);
×
2846
        auto origin_link_col = get_opposite_column(backlink_col_key);
×
2847
        if (origin_table->get_name() == origin_table_name &&
×
2848
            origin_table->get_column_name(origin_link_col) == origin_col_name) {
×
2849
            ret = BacklinkOrigin{{origin_table, origin_link_col}};
×
2850
            return IteratorControl::Stop;
×
2851
        }
×
2852
        return IteratorControl::AdvanceToNext;
×
2853
    };
×
2854
    this->for_each_backlink_column(f);
×
2855
    return ret;
×
2856
}
×
2857

2858
Table::BacklinkOrigin Table::find_backlink_origin(ColKey backlink_col) const noexcept
2859
{
177✔
2860
    try {
177✔
2861
        TableKey linked_table_key = get_opposite_table_key(backlink_col);
177✔
2862
        ColKey linked_column_key = get_opposite_column(backlink_col);
177✔
2863
        if (linked_table_key == m_key) {
177✔
2864
            return {{m_own_ref, linked_column_key}};
9✔
2865
        }
9✔
2866
        else {
168✔
2867
            Group* current_group = get_parent_group();
168✔
2868
            if (current_group) {
168✔
2869
                ConstTableRef linked_table_ref = current_group->get_table(linked_table_key);
168✔
2870
                return {{linked_table_ref, linked_column_key}};
168✔
2871
            }
168✔
2872
        }
168✔
2873
    }
177✔
2874
    catch (...) {
177✔
2875
        // backlink column not found, returning empty optional
2876
    }
×
2877
    return {};
×
2878
}
177✔
2879

2880
std::vector<std::pair<TableKey, ColKey>> Table::get_incoming_link_columns() const noexcept
2881
{
×
2882
    std::vector<std::pair<TableKey, ColKey>> origins;
×
2883
    auto f = [&](ColKey backlink_col_key) {
×
2884
        auto origin_table_key = get_opposite_table_key(backlink_col_key);
×
2885
        auto origin_link_col = get_opposite_column(backlink_col_key);
×
2886
        origins.emplace_back(origin_table_key, origin_link_col);
×
2887
        return IteratorControl::AdvanceToNext;
×
2888
    };
×
2889
    this->for_each_backlink_column(f);
×
2890
    return origins;
×
2891
}
×
2892

2893
ColKey Table::get_primary_key_column() const
2894
{
9,896,529✔
2895
    return m_primary_key_col;
9,896,529✔
2896
}
9,896,529✔
2897

2898
void Table::set_primary_key_column(ColKey col_key)
2899
{
366✔
2900
    if (col_key == m_primary_key_col) {
366✔
2901
        return;
189✔
2902
    }
189✔
2903

2904
    if (Replication* repl = get_repl()) {
177✔
2905
        if (repl->get_history_type() == Replication::HistoryType::hist_SyncClient) {
126✔
2906
            throw RuntimeError(
×
2907
                ErrorCodes::BrokenInvariant,
×
2908
                util::format("Cannot change primary key property in '%1' when realm is synchronized", get_name()));
×
2909
        }
×
2910
    }
126✔
2911

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

2914
    if (col_key) {
177✔
2915
        check_column(col_key);
117✔
2916
        validate_column_is_unique(col_key);
117✔
2917
        do_set_primary_key_column(col_key);
117✔
2918
    }
117✔
2919
    else {
60✔
2920
        do_set_primary_key_column(col_key);
60✔
2921
    }
60✔
2922
}
177✔
2923

2924

2925
void Table::do_set_primary_key_column(ColKey col_key)
2926
{
44,175✔
2927
    if (col_key) {
44,175✔
2928
        auto spec_ndx = leaf_ndx2spec_ndx(col_key.get_index());
43,644✔
2929
        auto attr = m_spec.get_column_attr(spec_ndx);
43,644✔
2930
        if (attr.test(col_attr_FullText_Indexed)) {
43,644✔
2931
            throw InvalidColumnKey("primary key cannot have a full text index");
3✔
2932
        }
3✔
2933
    }
43,644✔
2934

2935
    if (m_primary_key_col) {
44,172✔
2936
        // If the search index has not been set explicitly on current pk col, we remove it again
2937
        auto spec_ndx = leaf_ndx2spec_ndx(m_primary_key_col.get_index());
546✔
2938
        auto attr = m_spec.get_column_attr(spec_ndx);
546✔
2939
        if (!attr.test(col_attr_Indexed)) {
546✔
2940
            remove_search_index(m_primary_key_col);
540✔
2941
        }
540✔
2942
    }
546✔
2943

2944
    if (col_key) {
44,172✔
2945
        m_top.set(top_position_for_pk_col, RefOrTagged::make_tagged(col_key.value));
43,641✔
2946
        do_add_search_index(col_key, IndexType::General);
43,641✔
2947
    }
43,641✔
2948
    else {
531✔
2949
        m_top.set(top_position_for_pk_col, 0);
531✔
2950
    }
531✔
2951

2952
    m_primary_key_col = col_key;
44,172✔
2953
}
44,172✔
2954

2955
bool Table::contains_unique_values(ColKey col) const
2956
{
426✔
2957
    if (search_index_type(col) == IndexType::General) {
426✔
2958
        auto search_index = get_search_index(col);
381✔
2959
        return !search_index->has_duplicate_values();
381✔
2960
    }
381✔
2961
    else {
45✔
2962
        TableView tv = where().find_all();
45✔
2963
        tv.distinct(col);
45✔
2964
        return tv.size() == size();
45✔
2965
    }
45✔
2966
}
426✔
2967

2968
void Table::validate_column_is_unique(ColKey col) const
2969
{
426✔
2970
    if (!contains_unique_values(col)) {
426✔
2971
        throw MigrationFailed(util::format("Primary key property '%1.%2' has duplicate values after migration.",
15✔
2972
                                           get_class_name(), get_column_name(col)));
15✔
2973
    }
15✔
2974
}
426✔
2975

2976
void Table::validate_primary_column()
2977
{
912✔
2978
    if (ColKey col = get_primary_key_column()) {
912✔
2979
        validate_column_is_unique(col);
309✔
2980
    }
309✔
2981
}
912✔
2982

2983
ObjKey Table::get_next_valid_key()
2984
{
430,101✔
2985
    ObjKey key;
430,101✔
2986
    do {
430,104✔
2987
        key = ObjKey(allocate_sequence_number());
430,104✔
2988
    } while (m_clusters.is_valid(key));
430,104✔
2989

2990
    return key;
430,101✔
2991
}
430,101✔
2992

2993
namespace {
2994
template <class T>
2995
typename util::RemoveOptional<T>::type remove_optional(T val)
2996
{
43,932✔
2997
    return val;
43,932✔
2998
}
43,932✔
2999
template <>
3000
int64_t remove_optional<Optional<int64_t>>(Optional<int64_t> val)
3001
{
2,724✔
3002
    return *val;
2,724✔
3003
}
2,724✔
3004
template <>
3005
bool remove_optional<Optional<bool>>(Optional<bool> val)
3006
{
5,781✔
3007
    return *val;
5,781✔
3008
}
5,781✔
3009
template <>
3010
ObjectId remove_optional<Optional<ObjectId>>(Optional<ObjectId> val)
3011
{
2,757✔
3012
    return *val;
2,757✔
3013
}
2,757✔
3014
template <>
3015
UUID remove_optional<Optional<UUID>>(Optional<UUID> val)
3016
{
3,030✔
3017
    return *val;
3,030✔
3018
}
3,030✔
3019
} // namespace
3020

3021
template <class F, class T>
3022
void Table::change_nullability(ColKey key_from, ColKey key_to, bool throw_on_null)
3023
{
81✔
3024
    Allocator& allocator = this->get_alloc();
81✔
3025
    bool from_nullability = is_nullable(key_from);
81✔
3026
    auto func = [&](Cluster* cluster) {
81✔
3027
        size_t sz = cluster->node_size();
81✔
3028

3029
        typename ColumnTypeTraits<F>::cluster_leaf_type from_arr(allocator);
81✔
3030
        typename ColumnTypeTraits<T>::cluster_leaf_type to_arr(allocator);
81✔
3031
        cluster->init_leaf(key_from, &from_arr);
81✔
3032
        cluster->init_leaf(key_to, &to_arr);
81✔
3033

3034
        for (size_t i = 0; i < sz; i++) {
756✔
3035
            if (from_nullability && from_arr.is_null(i)) {
678!
3036
                if (throw_on_null) {
21!
3037
                    throw RuntimeError(ErrorCodes::BrokenInvariant,
3✔
3038
                                       util::format("Objects in '%1' has null value(s) in property '%2'", get_name(),
3✔
3039
                                                    get_column_name(key_from)));
3✔
3040
                }
3✔
3041
                else {
18✔
3042
                    to_arr.set(i, ColumnTypeTraits<T>::cluster_leaf_type::default_value(false));
18✔
3043
                }
18✔
3044
            }
21✔
3045
            else {
657✔
3046
                auto v = remove_optional(from_arr.get(i));
657✔
3047
                to_arr.set(i, v);
657✔
3048
            }
657✔
3049
        }
678✔
3050
    };
81✔
3051

3052
    m_clusters.update(func);
81✔
3053
}
81✔
3054

3055
template <class F, class T>
3056
void Table::change_nullability_list(ColKey key_from, ColKey key_to, bool throw_on_null)
3057
{
60✔
3058
    Allocator& allocator = this->get_alloc();
60✔
3059
    bool from_nullability = is_nullable(key_from);
60✔
3060
    auto func = [&](Cluster* cluster) {
60✔
3061
        size_t sz = cluster->node_size();
60✔
3062

3063
        ArrayInteger from_arr(allocator);
60✔
3064
        ArrayInteger to_arr(allocator);
60✔
3065
        cluster->init_leaf(key_from, &from_arr);
60✔
3066
        cluster->init_leaf(key_to, &to_arr);
60✔
3067

3068
        for (size_t i = 0; i < sz; i++) {
180✔
3069
            ref_type ref_from = to_ref(from_arr.get(i));
120✔
3070
            ref_type ref_to = to_ref(to_arr.get(i));
120✔
3071
            REALM_ASSERT(!ref_to);
120✔
3072

3073
            if (ref_from) {
120✔
3074
                BPlusTree<F> from_list(allocator);
60✔
3075
                BPlusTree<T> to_list(allocator);
60✔
3076
                from_list.init_from_ref(ref_from);
60✔
3077
                to_list.create();
60✔
3078
                size_t n = from_list.size();
60✔
3079
                for (size_t j = 0; j < n; j++) {
60,060✔
3080
                    auto v = from_list.get(j);
60,000✔
3081
                    if (!from_nullability || aggregate_operations::valid_for_agg(v)) {
60,000!
3082
                        to_list.add(remove_optional(v));
57,567✔
3083
                    }
57,567✔
3084
                    else {
2,433✔
3085
                        if (throw_on_null) {
2,433!
3086
                            throw RuntimeError(ErrorCodes::BrokenInvariant,
×
3087
                                               util::format("Objects in '%1' has null value(s) in list property '%2'",
×
3088
                                                            get_name(), get_column_name(key_from)));
×
3089
                        }
×
3090
                        else {
2,433✔
3091
                            to_list.add(ColumnTypeTraits<T>::cluster_leaf_type::default_value(false));
2,433✔
3092
                        }
2,433✔
3093
                    }
2,433✔
3094
                }
60,000✔
3095
                to_arr.set(i, from_ref(to_list.get_ref()));
60✔
3096
            }
60✔
3097
        }
120✔
3098
    };
60✔
3099

3100
    m_clusters.update(func);
60✔
3101
}
60✔
3102

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

3221

3222
ColKey Table::set_nullability(ColKey col_key, bool nullable, bool throw_on_null)
3223
{
261✔
3224
    if (col_key.is_nullable() == nullable)
261✔
3225
        return col_key;
120✔
3226

3227
    check_column(col_key);
141✔
3228

3229
    auto index_type = search_index_type(col_key);
141✔
3230
    std::string column_name(get_column_name(col_key));
141✔
3231
    auto type = col_key.get_type();
141✔
3232
    auto attr = col_key.get_attrs();
141✔
3233
    bool is_pk_col = (col_key == m_primary_key_col);
141✔
3234
    if (nullable) {
141✔
3235
        attr.set(col_attr_Nullable);
75✔
3236
    }
75✔
3237
    else {
66✔
3238
        attr.reset(col_attr_Nullable);
66✔
3239
    }
66✔
3240

3241
    ColKey new_col = generate_col_key(type, attr);
141✔
3242
    do_insert_root_column(new_col, type, "__temporary");
141✔
3243

3244
    try {
141✔
3245
        convert_column(col_key, new_col, throw_on_null);
141✔
3246
    }
141✔
3247
    catch (...) {
141✔
3248
        // remove any partially filled column
3249
        remove_column(new_col);
3✔
3250
        throw;
3✔
3251
    }
3✔
3252

3253
    if (is_pk_col) {
138✔
3254
        // If we go from non nullable to nullable, no values change,
3255
        // so it is safe to preserve the pk column. Otherwise it is not
3256
        // safe as a null entry might have been converted to default value.
3257
        do_set_primary_key_column(nullable ? new_col : ColKey{});
6✔
3258
    }
6✔
3259

3260
    erase_root_column(col_key);
138✔
3261
    m_spec.rename_column(colkey2spec_ndx(new_col), column_name);
138✔
3262

3263
    if (index_type != IndexType::None)
138✔
3264
        do_add_search_index(new_col, index_type);
15✔
3265

3266
    return new_col;
138✔
3267
}
141✔
3268

3269
bool Table::has_any_embedded_objects()
3270
{
1,276,491✔
3271
    if (!m_has_any_embedded_objects) {
1,276,491✔
3272
        m_has_any_embedded_objects = false;
14,664✔
3273
        for_each_public_column([&](ColKey col_key) {
35,553✔
3274
            auto target_table_key = get_opposite_table_key(col_key);
35,553✔
3275
            if (target_table_key && is_link_type(col_key.get_type())) {
35,553✔
3276
                auto target_table = get_parent_group()->get_table_unchecked(target_table_key);
7,809✔
3277
                if (target_table->is_embedded()) {
7,809✔
3278
                    m_has_any_embedded_objects = true;
6,762✔
3279
                    return IteratorControl::Stop; // early out
6,762✔
3280
                }
6,762✔
3281
            }
7,809✔
3282
            return IteratorControl::AdvanceToNext;
28,791✔
3283
        });
35,553✔
3284
    }
14,664✔
3285
    return *m_has_any_embedded_objects;
1,276,491✔
3286
}
1,276,491✔
3287

3288
void Table::set_opposite_column(ColKey col_key, TableKey opposite_table, ColKey opposite_column)
3289
{
78,546✔
3290
    m_opposite_table.set(col_key.get_index().val, opposite_table.value);
78,546✔
3291
    m_opposite_column.set(col_key.get_index().val, opposite_column.value);
78,546✔
3292
}
78,546✔
3293

3294
ColKey Table::find_backlink_column(ColKey origin_col_key, TableKey origin_table) const
3295
{
311,742✔
3296
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
657,243✔
3297
        if (m_opposite_column.get(i) == origin_col_key.value && m_opposite_table.get(i) == origin_table.value) {
653,307✔
3298
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
307,806✔
3299
        }
307,806✔
3300
    }
653,307✔
3301

3302
    return {};
3,936✔
3303
}
311,742✔
3304

3305
ColKey Table::find_or_add_backlink_column(ColKey origin_col_key, TableKey origin_table)
3306
{
311,718✔
3307
    ColKey backlink_col_key = find_backlink_column(origin_col_key, origin_table);
311,718✔
3308

3309
    if (!backlink_col_key) {
311,718✔
3310
        backlink_col_key = do_insert_root_column(ColKey{}, col_type_BackLink, "");
3,924✔
3311
        set_opposite_column(backlink_col_key, origin_table, origin_col_key);
3,924✔
3312

3313
        if (Replication* repl = get_repl())
3,924✔
3314
            repl->typed_link_change(get_parent_group()->get_table_unchecked(origin_table), origin_col_key,
3,726✔
3315
                                    m_key); // Throws
3,726✔
3316
    }
3,924✔
3317

3318
    return backlink_col_key;
311,718✔
3319
}
311,718✔
3320

3321
TableKey Table::get_opposite_table_key(ColKey col_key) const
3322
{
7,369,089✔
3323
    return TableKey(int32_t(m_opposite_table.get(col_key.get_index().val)));
7,369,089✔
3324
}
7,369,089✔
3325

3326
bool Table::links_to_self(ColKey col_key) const
3327
{
51,837✔
3328
    return get_opposite_table_key(col_key) == m_key;
51,837✔
3329
}
51,837✔
3330

3331
TableRef Table::get_opposite_table(ColKey col_key) const
3332
{
3,994,206✔
3333
    if (auto k = get_opposite_table_key(col_key)) {
3,994,206✔
3334
        return get_parent_group()->get_table(k);
3,963,519✔
3335
    }
3,963,519✔
3336
    return {};
30,687✔
3337
}
3,994,206✔
3338

3339
ColKey Table::get_opposite_column(ColKey col_key) const
3340
{
8,219,139✔
3341
    return ColKey(m_opposite_column.get(col_key.get_index().val));
8,219,139✔
3342
}
8,219,139✔
3343

3344
ColKey Table::find_opposite_column(ColKey col_key) const
3345
{
×
3346
    for (size_t i = 0; i < m_opposite_column.size(); i++) {
×
3347
        if (m_opposite_column.get(i) == col_key.value) {
×
3348
            return m_spec.get_key(m_leaf_ndx2spec_ndx[i]);
×
3349
        }
×
3350
    }
×
3351
    return ColKey();
×
3352
}
×
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