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

realm / realm-core / nicola.cabiddu_1042

27 Sep 2023 06:04PM UTC coverage: 91.085% (-1.8%) from 92.915%
nicola.cabiddu_1042

Pull #6766

Evergreen

nicola-cab
Fix logic for dictionaries
Pull Request #6766: Client Reset for collections in mixed / nested collections

97276 of 178892 branches covered (0.0%)

1994 of 2029 new or added lines in 7 files covered. (98.28%)

4556 existing lines in 112 files now uncovered.

237059 of 260260 relevant lines covered (91.09%)

6321099.55 hits per line

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

85.47
/src/realm/parser/driver.cpp
1
/*************************************************************************
2
 *
3
 * Copyright 2021 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/parser/driver.hpp"
20
#include "realm/parser/keypath_mapping.hpp"
21
#include "realm/parser/query_parser.hpp"
22
#include "realm/sort_descriptor.hpp"
23
#include "realm/decimal128.hpp"
24
#include "realm/uuid.hpp"
25
#include "realm/util/base64.hpp"
26
#include "realm/util/overload.hpp"
27

28
#define YY_NO_UNISTD_H 1
29
#define YY_NO_INPUT 1
30
#include "realm/parser/generated/query_flex.hpp"
31

32
#include <external/mpark/variant.hpp>
33
#include <stdexcept>
34

35
using namespace realm;
36
using namespace std::string_literals;
37

38
// Whether to generate parser debug traces.
39
static bool trace_parsing = false;
40
// Whether to generate scanner debug traces.
41
static bool trace_scanning = false;
42

43
namespace {
44

45
const char* agg_op_type_to_str(query_parser::AggrNode::Type type)
46
{
256✔
47
    switch (type) {
256✔
48
        case realm::query_parser::AggrNode::MAX:
60✔
49
            return ".@max";
60✔
50
        case realm::query_parser::AggrNode::MIN:
68✔
51
            return ".@min";
68✔
52
        case realm::query_parser::AggrNode::SUM:
64✔
53
            return ".@sum";
64✔
54
        case realm::query_parser::AggrNode::AVG:
64✔
55
            return ".@avg";
64✔
56
    }
×
57
    return "";
×
58
}
×
59

60
const char* expression_cmp_type_to_str(util::Optional<ExpressionComparisonType> type)
61
{
44✔
62
    if (type) {
44✔
63
        switch (*type) {
44✔
64
            case ExpressionComparisonType::Any:
16✔
65
                return "ANY";
16✔
66
            case ExpressionComparisonType::All:
12✔
67
                return "ALL";
12✔
68
            case ExpressionComparisonType::None:
16✔
69
                return "NONE";
16✔
70
        }
×
71
    }
×
72
    return "";
×
73
}
×
74

75
std::string print_pretty_objlink(const ObjLink& link, const Group* g)
76
{
8✔
77
    REALM_ASSERT(g);
8✔
78
    if (link.is_null()) {
8✔
79
        return "NULL";
×
80
    }
×
81
    try {
8✔
82
        auto table = g->get_table(link.get_table_key());
8✔
83
        if (!table) {
8✔
84
            return "link to an invalid table";
×
85
        }
×
86
        auto obj = table->get_object(link.get_obj_key());
8✔
87
        Mixed pk = obj.get_primary_key();
8✔
88
        return util::format("'%1' with primary key '%2'", table->get_class_name(), util::serializer::print_value(pk));
8✔
89
    }
8✔
90
    catch (...) {
×
91
        return "invalid link";
×
92
    }
×
93
}
8✔
94

95
bool is_length_suffix(const std::string& s)
96
{
1,704✔
97
    return s.size() == 6 && (s[0] == 'l' || s[0] == 'L') && (s[1] == 'e' || s[1] == 'E') &&
1,704!
98
           (s[2] == 'n' || s[2] == 'N') && (s[3] == 'g' || s[3] == 'G') && (s[4] == 't' || s[4] == 'T') &&
1,696!
99
           (s[5] == 'h' || s[5] == 'H');
1,696!
100
}
1,704✔
101

102
template <typename T>
103
inline bool try_parse_specials(std::string str, T& ret)
104
{
8✔
105
    if constexpr (realm::is_any<T, float, double>::value || std::numeric_limits<T>::is_iec559) {
8✔
106
        std::transform(str.begin(), str.end(), str.begin(), toLowerAscii);
×
107
        if (std::numeric_limits<T>::has_quiet_NaN && (str == "nan" || str == "+nan")) {
×
108
            ret = std::numeric_limits<T>::quiet_NaN();
×
109
            return true;
×
110
        }
×
111
        else if (std::numeric_limits<T>::has_quiet_NaN && (str == "-nan")) {
×
112
            ret = -std::numeric_limits<T>::quiet_NaN();
×
113
            return true;
×
114
        }
×
115
        else if (std::numeric_limits<T>::has_infinity &&
×
116
                 (str == "+infinity" || str == "infinity" || str == "+inf" || str == "inf")) {
×
117
            ret = std::numeric_limits<T>::infinity();
×
118
            return true;
×
119
        }
×
120
        else if (std::numeric_limits<T>::has_infinity && (str == "-infinity" || str == "-inf")) {
×
121
            ret = -std::numeric_limits<T>::infinity();
×
122
            return true;
×
123
        }
×
124
    }
×
125
    return false;
×
126
}
×
127

128
template <typename T>
129
inline const char* get_type_name()
130
{
131
    return "unknown";
132
}
133
template <>
134
inline const char* get_type_name<int64_t>()
135
{
8✔
136
    return "number";
8✔
137
}
8✔
138
template <>
139
inline const char* get_type_name<float>()
140
{
×
141
    return "floating point number";
×
142
}
×
143
template <>
144
inline const char* get_type_name<double>()
145
{
×
146
    return "floating point number";
×
147
}
×
148

149
template <typename T>
150
inline T string_to(const std::string& s)
151
{
408✔
152
    std::istringstream iss(s);
408✔
153
    iss.imbue(std::locale::classic());
408✔
154
    T value;
408✔
155
    iss >> value;
408✔
156
    if (iss.fail()) {
408!
157
        if (!try_parse_specials(s, value)) {
8!
158
            throw InvalidQueryArgError(util::format("Cannot convert '%1' to a %2", s, get_type_name<T>()));
8✔
159
        }
8✔
160
    }
400✔
161
    return value;
400✔
162
}
400✔
163

164
class MixedArguments : public query_parser::Arguments {
165
public:
166
    using Arg = mpark::variant<Mixed, std::vector<Mixed>>;
167

168
    MixedArguments(const std::vector<Mixed>& args)
169
        : Arguments(args.size())
170
        , m_args([](const std::vector<Mixed>& args) -> std::vector<Arg> {
1,692✔
171
            std::vector<Arg> ret;
1,692✔
172
            ret.reserve(args.size());
1,692✔
173
            for (const Mixed& m : args) {
15,160✔
174
                ret.push_back(m);
15,160✔
175
            }
15,160✔
176
            return ret;
1,692✔
177
        }(args))
1,692✔
178
    {
1,692✔
179
    }
1,692✔
180
    MixedArguments(const std::vector<Arg>& args)
181
        : Arguments(args.size())
182
        , m_args(args)
183
    {
11,668✔
184
    }
11,668✔
185
    bool bool_for_argument(size_t n) final
186
    {
×
187
        return mixed_for_argument(n).get<bool>();
×
188
    }
×
189
    long long long_for_argument(size_t n) final
190
    {
364✔
191
        return mixed_for_argument(n).get<int64_t>();
364✔
192
    }
364✔
193
    float float_for_argument(size_t n) final
194
    {
×
195
        return mixed_for_argument(n).get<float>();
×
196
    }
×
197
    double double_for_argument(size_t n) final
198
    {
156✔
199
        return mixed_for_argument(n).get<double>();
156✔
200
    }
156✔
201
    StringData string_for_argument(size_t n) final
202
    {
36✔
203
        return mixed_for_argument(n).get<StringData>();
36✔
204
    }
36✔
205
    BinaryData binary_for_argument(size_t n) final
206
    {
×
207
        return mixed_for_argument(n).get<BinaryData>();
×
208
    }
×
209
    Timestamp timestamp_for_argument(size_t n) final
210
    {
×
211
        return mixed_for_argument(n).get<Timestamp>();
×
212
    }
×
213
    ObjectId objectid_for_argument(size_t n) final
214
    {
428,088✔
215
        return mixed_for_argument(n).get<ObjectId>();
428,088✔
216
    }
428,088✔
217
    UUID uuid_for_argument(size_t n) final
218
    {
12✔
219
        return mixed_for_argument(n).get<UUID>();
12✔
220
    }
12✔
221
    Decimal128 decimal128_for_argument(size_t n) final
222
    {
72✔
223
        return mixed_for_argument(n).get<Decimal128>();
72✔
224
    }
72✔
225
    ObjKey object_index_for_argument(size_t n) final
226
    {
×
227
        return mixed_for_argument(n).get<ObjKey>();
×
228
    }
×
229
    ObjLink objlink_for_argument(size_t n) final
230
    {
×
231
        return mixed_for_argument(n).get<ObjLink>();
×
232
    }
×
233
#if REALM_ENABLE_GEOSPATIAL
234
    Geospatial geospatial_for_argument(size_t n) final
235
    {
16✔
236
        return mixed_for_argument(n).get<Geospatial>();
16✔
237
    }
16✔
238
#endif
239
    std::vector<Mixed> list_for_argument(size_t n) final
240
    {
100✔
241
        Arguments::verify_ndx(n);
100✔
242
        return mpark::get<std::vector<Mixed>>(m_args[n]);
100✔
243
    }
100✔
244
    bool is_argument_null(size_t n) final
245
    {
428,924✔
246
        Arguments::verify_ndx(n);
428,924✔
247
        return visit(util::overload{
428,924✔
248
                         [](const Mixed& m) {
428,868✔
249
                             return m.is_null();
428,812✔
250
                         },
428,812✔
251
                         [](const std::vector<Mixed>&) {
214,512✔
252
                             return false;
100✔
253
                         },
100✔
254
                     },
428,924✔
255
                     m_args[n]);
428,924✔
256
    }
428,924✔
257
    bool is_argument_list(size_t n) final
258
    {
1,286,320✔
259
        Arguments::verify_ndx(n);
1,286,320✔
260
        static_assert(std::is_same_v<mpark::variant_alternative_t<1, Arg>, std::vector<Mixed>>);
1,286,320✔
261
        return m_args[n].index() == 1;
1,286,320✔
262
    }
1,286,320✔
263
    DataType type_for_argument(size_t n)
264
    {
428,760✔
265
        return mixed_for_argument(n).get_type();
428,760✔
266
    }
428,760✔
267

268
private:
269
    const Mixed& mixed_for_argument(size_t n)
270
    {
857,504✔
271
        Arguments::verify_ndx(n);
857,504✔
272
        if (is_argument_list(n)) {
857,504✔
273
            throw InvalidQueryArgError(
×
274
                util::format("Request for scalar argument at index %1 but a list was provided", n));
×
275
        }
×
276

428,752✔
277
        return mpark::get<Mixed>(m_args[n]);
857,504✔
278
    }
857,504✔
279

280
    const std::vector<Arg> m_args;
281
};
282

283
Timestamp get_timestamp_if_valid(int64_t seconds, int32_t nanoseconds)
284
{
596✔
285
    const bool both_non_negative = seconds >= 0 && nanoseconds >= 0;
596✔
286
    const bool both_non_positive = seconds <= 0 && nanoseconds <= 0;
596✔
287
    if (both_non_negative || both_non_positive) {
596✔
288
        return Timestamp(seconds, nanoseconds);
580✔
289
    }
580✔
290
    throw SyntaxError("Invalid timestamp format");
16✔
291
}
16✔
292

293
} // namespace
294

295
namespace realm {
296

297
namespace query_parser {
298

299
std::string_view string_for_op(CompareType op)
300
{
2,616✔
301
    switch (op) {
2,616✔
302
        case CompareType::EQUAL:
164✔
303
            return "=";
164✔
304
        case CompareType::NOT_EQUAL:
40✔
305
            return "!=";
40✔
306
        case CompareType::GREATER:
✔
307
            return ">";
×
308
        case CompareType::LESS:
✔
309
            return "<";
×
310
        case CompareType::GREATER_EQUAL:
✔
311
            return ">=";
×
312
        case CompareType::LESS_EQUAL:
✔
313
            return "<=";
×
314
        case CompareType::BEGINSWITH:
520✔
315
            return "beginswith";
520✔
316
        case CompareType::ENDSWITH:
512✔
317
            return "endswith";
512✔
318
        case CompareType::CONTAINS:
864✔
319
            return "contains";
864✔
320
        case CompareType::LIKE:
480✔
321
            return "like";
480✔
322
        case CompareType::IN:
8✔
323
            return "in";
8✔
324
        case CompareType::TEXT:
28✔
325
            return "text";
28✔
326
    }
×
327
    return ""; // appease MSVC warnings
×
328
}
×
329

330
NoArguments ParserDriver::s_default_args;
331
query_parser::KeyPathMapping ParserDriver::s_default_mapping;
332

333
ParserNode::~ParserNode() = default;
2,385,440✔
334

335
QueryNode::~QueryNode() = default;
905,312✔
336

337
Query NotNode::visit(ParserDriver* drv)
338
{
912✔
339
    Query q = drv->m_base_table->where();
912✔
340
    q.Not();
912✔
341
    q.and_query(query->visit(drv));
912✔
342
    return {q};
912✔
343
}
912✔
344

345
Query OrNode::visit(ParserDriver* drv)
346
{
556✔
347
    Query q(drv->m_base_table);
556✔
348
    q.group();
556✔
349
    for (auto it : children) {
430,460✔
350
        q.Or();
430,460✔
351
        q.and_query(it->visit(drv));
430,460✔
352
    }
430,460✔
353
    q.end_group();
556✔
354

278✔
355
    return q;
556✔
356
}
556✔
357

358
Query AndNode::visit(ParserDriver* drv)
359
{
708✔
360
    Query q(drv->m_base_table);
708✔
361
    for (auto it : children) {
1,592✔
362
        q.and_query(it->visit(drv));
1,592✔
363
    }
1,592✔
364
    return q;
708✔
365
}
708✔
366

367
static void verify_only_string_types(DataType type, std::string_view op_string)
368
{
2,616✔
369
    if (type != type_String && type != type_Binary && type != type_Mixed) {
2,616✔
370
        throw InvalidQueryError(util::format(
348✔
371
            "Unsupported comparison operator '%1' against type '%2', right side must be a string or binary type",
348✔
372
            op_string, get_data_type_name(type)));
348✔
373
    }
348✔
374
}
2,616✔
375

376
std::unique_ptr<Subexpr> OperationNode::visit(ParserDriver* drv, DataType type)
377
{
1,056✔
378
    std::unique_ptr<Subexpr> left;
1,056✔
379
    std::unique_ptr<Subexpr> right;
1,056✔
380

528✔
381
    const bool left_is_constant = m_left->is_constant();
1,056✔
382
    const bool right_is_constant = m_right->is_constant();
1,056✔
383
    const bool produces_multiple_values = m_left->is_list() || m_right->is_list();
1,056✔
384

528✔
385
    if (left_is_constant && right_is_constant && !produces_multiple_values) {
1,056✔
386
        right = m_right->visit(drv, type);
48✔
387
        left = m_left->visit(drv, type);
48✔
388
        auto v_left = left->get_mixed();
48✔
389
        auto v_right = right->get_mixed();
48✔
390
        Mixed result;
48✔
391
        switch (m_op) {
48✔
392
            case '+':
28✔
393
                result = v_left + v_right;
28✔
394
                break;
28✔
395
            case '-':
✔
396
                result = v_left - v_right;
×
397
                break;
×
398
            case '*':
20✔
399
                result = v_left * v_right;
20✔
400
                break;
20✔
401
            case '/':
✔
402
                result = v_left / v_right;
×
403
                break;
×
404
            default:
✔
405
                break;
×
406
        }
48✔
407
        return std::make_unique<Value<Mixed>>(result);
48✔
408
    }
48✔
409

504✔
410
    if (right_is_constant) {
1,008✔
411
        // Take left first - it cannot be a constant
208✔
412
        left = m_left->visit(drv);
416✔
413

208✔
414
        right = m_right->visit(drv, left->get_type());
416✔
415
    }
416✔
416
    else {
592✔
417
        right = m_right->visit(drv);
592✔
418
        if (left_is_constant) {
592✔
419
            left = m_left->visit(drv, right->get_type());
152✔
420
        }
152✔
421
        else {
440✔
422
            left = m_left->visit(drv);
440✔
423
        }
440✔
424
    }
592✔
425
    if (!Mixed::is_numeric(left->get_type(), right->get_type())) {
1,008✔
426
        util::serializer::SerialisationState state;
16✔
427
        std::string op(&m_op, 1);
16✔
428
        throw InvalidQueryArgError(util::format("Cannot perform '%1' operation on '%2' and '%3'", op,
16✔
429
                                                left->description(state), right->description(state)));
16✔
430
    }
16✔
431

496✔
432
    switch (m_op) {
992✔
433
        case '+':
400✔
434
            return std::make_unique<Operator<Plus>>(std::move(left), std::move(right));
400✔
435
        case '-':
136✔
436
            return std::make_unique<Operator<Minus>>(std::move(left), std::move(right));
136✔
437
        case '*':
260✔
438
            return std::make_unique<Operator<Mul>>(std::move(left), std::move(right));
260✔
439
        case '/':
196✔
440
            return std::make_unique<Operator<Div>>(std::move(left), std::move(right));
196✔
441
        default:
✔
442
            break;
×
443
    }
×
444
    return {};
×
445
}
×
446

447
Query EqualityNode::visit(ParserDriver* drv)
448
{
464,036✔
449
    auto [left, right] = drv->cmp(values);
464,036✔
450

232,016✔
451
    auto left_type = left->get_type();
464,036✔
452
    auto right_type = right->get_type();
464,036✔
453

232,016✔
454
    auto handle_typed_links = [drv](std::unique_ptr<Subexpr>& list, std::unique_ptr<Subexpr>& expr, DataType& type) {
232,206✔
455
        if (auto link_column = dynamic_cast<const Columns<Link>*>(list.get())) {
380✔
456
            // Change all TypedLink values to ObjKey values
190✔
457
            auto value = dynamic_cast<ValueBase*>(expr.get());
380✔
458
            auto left_dest_table_key = link_column->link_map().get_target_table()->get_key();
380✔
459
            auto sz = value->size();
380✔
460
            auto obj_keys = std::make_unique<Value<ObjKey>>();
380✔
461
            obj_keys->init(expr->has_multiple_values(), sz);
380✔
462
            obj_keys->set_comparison_type(expr->get_comparison_type());
380✔
463
            for (size_t i = 0; i < sz; i++) {
764✔
464
                auto val = value->get(i);
396✔
465
                // i'th entry is already NULL
198✔
466
                if (!val.is_null()) {
396✔
467
                    TableKey right_table_key;
196✔
468
                    ObjKey right_obj_key;
196✔
469
                    if (val.is_type(type_Link)) {
196✔
470
                        right_table_key = left_dest_table_key;
20✔
471
                        right_obj_key = val.get<ObjKey>();
20✔
472
                    }
20✔
473
                    else if (val.is_type(type_TypedLink)) {
176✔
474
                        right_table_key = val.get_link().get_table_key();
172✔
475
                        right_obj_key = val.get_link().get_obj_key();
172✔
476
                    }
172✔
477
                    else {
4✔
478
                        const char* target_type = get_data_type_name(val.get_type());
4✔
479
                        throw InvalidQueryError(
4✔
480
                            util::format("Unsupported comparison between '%1' and type '%2'",
4✔
481
                                         link_column->link_map().description(drv->m_serializer_state), target_type));
4✔
482
                    }
4✔
483
                    if (left_dest_table_key == right_table_key) {
192✔
484
                        obj_keys->set(i, right_obj_key);
184✔
485
                    }
184✔
486
                    else {
8✔
487
                        const Group* g = drv->m_base_table->get_parent_group();
8✔
488
                        throw InvalidQueryArgError(
8✔
489
                            util::format("The relationship '%1' which links to type '%2' cannot be compared to "
8✔
490
                                         "an argument of type %3",
8✔
491
                                         link_column->link_map().description(drv->m_serializer_state),
8✔
492
                                         link_column->link_map().get_target_table()->get_class_name(),
8✔
493
                                         print_pretty_objlink(ObjLink(right_table_key, right_obj_key), g)));
8✔
494
                    }
8✔
495
                }
192✔
496
            }
396✔
497
            expr = std::move(obj_keys);
374✔
498
            type = type_Link;
368✔
499
        }
368✔
500
    };
380✔
501

232,016✔
502
    if (left_type == type_Link && right->has_constant_evaluation()) {
464,036✔
503
        handle_typed_links(left, right, right_type);
368✔
504
    }
368✔
505
    if (right_type == type_Link && left->has_constant_evaluation()) {
464,036✔
506
        handle_typed_links(right, left, left_type);
12✔
507
    }
12✔
508

232,016✔
509
    if (left_type.is_valid() && right_type.is_valid() && !Mixed::data_types_are_comparable(left_type, right_type)) {
464,036✔
510
        throw InvalidQueryError(util::format("Unsupported comparison between type '%1' and type '%2'",
152✔
511
                                             get_data_type_name(left_type), get_data_type_name(right_type)));
152✔
512
    }
152✔
513
    if (left_type == type_TypeOfValue || right_type == type_TypeOfValue) {
463,884✔
514
        if (left_type != right_type) {
512✔
515
            throw InvalidQueryArgError(
12✔
516
                util::format("Unsupported comparison between @type and raw value: '%1' and '%2'",
12✔
517
                             get_data_type_name(left_type), get_data_type_name(right_type)));
12✔
518
        }
12✔
519
    }
463,872✔
520

231,934✔
521
    if (op == CompareType::IN) {
463,872✔
522
        Subexpr* r = right.get();
656✔
523
        if (!r->has_multiple_values()) {
656✔
524
            throw InvalidQueryArgError("The keypath following 'IN' must contain a list. Found '" +
8✔
525
                                       r->description(drv->m_serializer_state) + "'");
8✔
526
        }
8✔
527
    }
463,864✔
528

231,930✔
529
    if (left_type == type_Link && left_type == right_type && right->has_constant_evaluation()) {
463,864✔
530
        if (auto link_column = dynamic_cast<const Columns<Link>*>(left.get())) {
356✔
531
            if (link_column->link_map().get_nb_hops() == 1 &&
356✔
532
                link_column->get_comparison_type().value_or(ExpressionComparisonType::Any) ==
328✔
533
                    ExpressionComparisonType::Any) {
292✔
534
                REALM_ASSERT(dynamic_cast<const Value<ObjKey>*>(right.get()));
284✔
535
                auto link_values = static_cast<const Value<ObjKey>*>(right.get());
284✔
536
                // We can use a LinksToNode based query
142✔
537
                std::vector<ObjKey> values;
284✔
538
                values.reserve(link_values->size());
284✔
539
                for (auto val : *link_values) {
300✔
540
                    values.emplace_back(val.is_null() ? ObjKey() : val.get<ObjKey>());
234✔
541
                }
300✔
542
                if (op == CompareType::EQUAL) {
284✔
543
                    return drv->m_base_table->where().links_to(link_column->link_map().get_first_column_key(),
184✔
544
                                                               values);
184✔
545
                }
184✔
546
                else if (op == CompareType::NOT_EQUAL) {
100✔
547
                    return drv->m_base_table->where().not_links_to(link_column->link_map().get_first_column_key(),
96✔
548
                                                                   values);
96✔
549
                }
96✔
550
            }
463,508✔
551
        }
356✔
552
    }
463,508✔
553
    else if (right->has_single_value() && (left_type == right_type || left_type == type_Mixed)) {
463,508✔
554
        Mixed val = right->get_mixed();
457,238✔
555
        const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
457,238✔
556
        if (prop && !prop->links_exist() && !prop->has_path()) {
457,238✔
557
            auto col_key = prop->column_key();
443,552✔
558
            if (val.is_null()) {
443,552✔
559
                switch (op) {
188✔
560
                    case CompareType::EQUAL:
132✔
561
                    case CompareType::IN:
132✔
562
                        return drv->m_base_table->where().equal(col_key, realm::null());
132✔
563
                    case CompareType::NOT_EQUAL:
94✔
564
                        return drv->m_base_table->where().not_equal(col_key, realm::null());
56✔
565
                    default:
66✔
566
                        break;
×
567
                }
443,364✔
568
            }
443,364✔
569
            switch (left->get_type()) {
443,364✔
570
                case type_Int:
9,768✔
571
                    return drv->simple_query(op, col_key, val.get_int());
9,768✔
572
                case type_Bool:
132✔
573
                    return drv->simple_query(op, col_key, val.get_bool());
132✔
574
                case type_String:
2,392✔
575
                    return drv->simple_query(op, col_key, val.get_string(), case_sensitive);
2,392✔
576
                case type_Binary:
1,416✔
577
                    return drv->simple_query(op, col_key, val.get_binary(), case_sensitive);
1,416✔
578
                case type_Timestamp:
140✔
579
                    return drv->simple_query(op, col_key, val.get<Timestamp>());
140✔
580
                case type_Float:
52✔
581
                    return drv->simple_query(op, col_key, val.get_float());
52✔
582
                case type_Double:
100✔
583
                    return drv->simple_query(op, col_key, val.get_double());
100✔
584
                case type_Decimal:
696✔
585
                    return drv->simple_query(op, col_key, val.get<Decimal128>());
696✔
586
                case type_ObjectId:
428,384✔
587
                    return drv->simple_query(op, col_key, val.get<ObjectId>());
428,384✔
588
                case type_UUID:
164✔
589
                    return drv->simple_query(op, col_key, val.get<UUID>());
164✔
590
                case type_Mixed:
116✔
591
                    return drv->simple_query(op, col_key, val, case_sensitive);
116✔
592
                default:
✔
593
                    break;
×
594
            }
20,032✔
595
        }
20,032✔
596
    }
457,238✔
597
    if (case_sensitive) {
20,032✔
598
        switch (op) {
19,384✔
599
            case CompareType::EQUAL:
16,488✔
600
            case CompareType::IN:
16,808✔
601
                return Query(std::unique_ptr<Expression>(new Compare<Equal>(std::move(left), std::move(right))));
16,808✔
602
            case CompareType::NOT_EQUAL:
9,692✔
603
                return Query(std::unique_ptr<Expression>(new Compare<NotEqual>(std::move(left), std::move(right))));
2,576✔
604
            default:
8,404✔
605
                break;
×
606
        }
648✔
607
    }
648✔
608
    else {
648✔
609
        verify_only_string_types(right_type, util::format("%1%2", string_for_op(op), "[c]"));
648✔
610
        switch (op) {
648✔
611
            case CompareType::EQUAL:
108✔
612
            case CompareType::IN:
112✔
613
                return Query(std::unique_ptr<Expression>(new Compare<EqualIns>(std::move(left), std::move(right))));
112✔
614
            case CompareType::NOT_EQUAL:
76✔
615
                return Query(
40✔
616
                    std::unique_ptr<Expression>(new Compare<NotEqualIns>(std::move(left), std::move(right))));
40✔
617
            default:
56✔
618
                break;
×
619
        }
×
620
    }
×
621
    return {};
×
622
}
×
623

624
Query BetweenNode::visit(ParserDriver* drv)
625
{
92✔
626
    if (limits->elements.size() != 2) {
92✔
627
        throw InvalidQueryError("Operator 'BETWEEN' requires list with 2 elements.");
8✔
628
    }
8✔
629

42✔
630
    if (dynamic_cast<ColumnListBase*>(prop->visit(drv, type_Int).get())) {
84✔
631
        // It's a list!
8✔
632
        util::Optional<ExpressionComparisonType> cmp_type = dynamic_cast<PropertyNode*>(prop)->comp_type;
16✔
633
        if (cmp_type.value_or(ExpressionComparisonType::Any) != ExpressionComparisonType::All) {
16✔
634
            throw InvalidQueryError("Only 'ALL' supported for operator 'BETWEEN' when applied to lists.");
12✔
635
        }
12✔
636
    }
72✔
637

36✔
638
    auto& min(limits->elements.at(0));
72✔
639
    auto& max(limits->elements.at(1));
72✔
640
    RelationalNode cmp1(prop, CompareType::GREATER_EQUAL, min);
72✔
641
    RelationalNode cmp2(prop, CompareType::LESS_EQUAL, max);
72✔
642

36✔
643
    Query q(drv->m_base_table);
72✔
644
    q.and_query(cmp1.visit(drv));
72✔
645
    q.and_query(cmp2.visit(drv));
72✔
646

36✔
647
    return q;
72✔
648
}
72✔
649

650
Query RelationalNode::visit(ParserDriver* drv)
651
{
5,160✔
652
    auto [left, right] = drv->cmp(values);
5,160✔
653

2,580✔
654
    auto left_type = left->get_type();
5,160✔
655
    auto right_type = right->get_type();
5,160✔
656
    const bool right_type_is_null = right->has_single_value() && right->get_mixed().is_null();
5,160✔
657
    const bool left_type_is_null = left->has_single_value() && left->get_mixed().is_null();
5,160✔
658
    REALM_ASSERT(!(left_type_is_null && right_type_is_null));
5,160!
659

2,580✔
660
    if (left_type == type_Link || left_type == type_TypeOfValue) {
5,160✔
661
        throw InvalidQueryError(util::format(
×
662
            "Unsupported operator %1 in query. Only equal (==) and not equal (!=) are supported for this type.",
×
663
            string_for_op(op)));
×
664
    }
×
665

2,580✔
666
    if (!(left_type_is_null || right_type_is_null) && (!left_type.is_valid() || !right_type.is_valid() ||
5,160✔
667
                                                       !Mixed::data_types_are_comparable(left_type, right_type))) {
4,664✔
668
        throw InvalidQueryError(util::format("Unsupported comparison between type '%1' and type '%2'",
36✔
669
                                             get_data_type_name(left_type), get_data_type_name(right_type)));
36✔
670
    }
36✔
671

2,562✔
672
    const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
5,124✔
673
    if (prop && !prop->links_exist() && !prop->has_path() && right->has_single_value() &&
5,124✔
674
        (left_type == right_type || left_type == type_Mixed)) {
3,438✔
675
        auto col_key = prop->column_key();
1,464✔
676
        switch (left->get_type()) {
1,464✔
677
            case type_Int:
692✔
678
                return drv->simple_query(op, col_key, right->get_mixed().get_int());
692✔
679
            case type_Bool:
✔
680
                break;
×
681
            case type_String:
✔
682
                break;
×
683
            case type_Binary:
✔
684
                break;
×
685
            case type_Timestamp:
48✔
686
                return drv->simple_query(op, col_key, right->get_mixed().get<Timestamp>());
48✔
687
            case type_Float:
68✔
688
                return drv->simple_query(op, col_key, right->get_mixed().get_float());
68✔
689
                break;
×
690
            case type_Double:
144✔
691
                return drv->simple_query(op, col_key, right->get_mixed().get_double());
144✔
692
                break;
×
693
            case type_Decimal:
16✔
694
                return drv->simple_query(op, col_key, right->get_mixed().get<Decimal128>());
16✔
695
                break;
×
696
            case type_ObjectId:
288✔
697
                return drv->simple_query(op, col_key, right->get_mixed().get<ObjectId>());
288✔
698
                break;
×
699
            case type_UUID:
128✔
700
                return drv->simple_query(op, col_key, right->get_mixed().get<UUID>());
128✔
701
                break;
×
702
            case type_Mixed:
80✔
703
                return drv->simple_query(op, col_key, right->get_mixed());
80✔
704
                break;
×
705
            default:
✔
706
                break;
×
707
        }
3,660✔
708
    }
3,660✔
709
    switch (op) {
3,660✔
710
        case CompareType::GREATER:
2,260✔
711
            return Query(std::unique_ptr<Expression>(new Compare<Greater>(std::move(left), std::move(right))));
2,260✔
712
        case CompareType::LESS:
284✔
713
            return Query(std::unique_ptr<Expression>(new Compare<Less>(std::move(left), std::move(right))));
284✔
714
        case CompareType::GREATER_EQUAL:
540✔
715
            return Query(std::unique_ptr<Expression>(new Compare<GreaterEqual>(std::move(left), std::move(right))));
540✔
716
        case CompareType::LESS_EQUAL:
172✔
717
            return Query(std::unique_ptr<Expression>(new Compare<LessEqual>(std::move(left), std::move(right))));
172✔
718
        default:
✔
719
            break;
×
720
    }
×
721
    return {};
×
722
}
×
723

724
Query StringOpsNode::visit(ParserDriver* drv)
725
{
2,420✔
726
    auto [left, right] = drv->cmp(values);
2,420✔
727

1,210✔
728
    auto left_type = left->get_type();
2,420✔
729
    auto right_type = right->get_type();
2,420✔
730
    const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
2,420✔
731

1,210✔
732
    verify_only_string_types(right_type, string_for_op(op));
2,420✔
733

1,210✔
734
    if (prop && !prop->links_exist() && right->has_single_value() &&
2,420✔
735
        (left_type == right_type || left_type == type_Mixed)) {
1,478✔
736
        auto col_key = prop->column_key();
536✔
737
        if (right_type == type_String) {
536✔
738
            StringData val = right->get_mixed().get_string();
320✔
739

160✔
740
            switch (op) {
320✔
741
                case CompareType::BEGINSWITH:
56✔
742
                    return drv->m_base_table->where().begins_with(col_key, val, case_sensitive);
56✔
743
                case CompareType::ENDSWITH:
64✔
744
                    return drv->m_base_table->where().ends_with(col_key, val, case_sensitive);
64✔
745
                case CompareType::CONTAINS:
120✔
746
                    return drv->m_base_table->where().contains(col_key, val, case_sensitive);
120✔
747
                case CompareType::LIKE:
56✔
748
                    return drv->m_base_table->where().like(col_key, val, case_sensitive);
56✔
749
                case CompareType::TEXT:
24✔
750
                    return drv->m_base_table->where().fulltext(col_key, val);
24✔
751
                case CompareType::IN:
✔
752
                case CompareType::EQUAL:
✔
753
                case CompareType::NOT_EQUAL:
✔
754
                case CompareType::GREATER:
✔
755
                case CompareType::LESS:
✔
756
                case CompareType::GREATER_EQUAL:
✔
757
                case CompareType::LESS_EQUAL:
✔
758
                    break;
×
759
            }
216✔
760
        }
216✔
761
        else if (right_type == type_Binary) {
216✔
762
            BinaryData val = right->get_mixed().get_binary();
216✔
763

108✔
764
            switch (op) {
216✔
765
                case CompareType::BEGINSWITH:
48✔
766
                    return drv->m_base_table->where().begins_with(col_key, val, case_sensitive);
48✔
767
                case CompareType::ENDSWITH:
56✔
768
                    return drv->m_base_table->where().ends_with(col_key, val, case_sensitive);
56✔
769
                case CompareType::CONTAINS:
72✔
770
                    return drv->m_base_table->where().contains(col_key, val, case_sensitive);
72✔
771
                case CompareType::LIKE:
40✔
772
                    return drv->m_base_table->where().like(col_key, val, case_sensitive);
40✔
773
                case CompareType::TEXT:
✔
774
                case CompareType::IN:
✔
775
                case CompareType::EQUAL:
✔
776
                case CompareType::NOT_EQUAL:
✔
777
                case CompareType::GREATER:
✔
778
                case CompareType::LESS:
✔
779
                case CompareType::GREATER_EQUAL:
✔
780
                case CompareType::LESS_EQUAL:
✔
781
                    break;
×
782
            }
1,884✔
783
        }
1,884✔
784
    }
536✔
785

942✔
786
    if (case_sensitive) {
1,884✔
787
        switch (op) {
724✔
788
            case CompareType::BEGINSWITH:
144✔
789
                return Query(std::unique_ptr<Expression>(new Compare<BeginsWith>(std::move(right), std::move(left))));
144✔
790
            case CompareType::ENDSWITH:
152✔
791
                return Query(std::unique_ptr<Expression>(new Compare<EndsWith>(std::move(right), std::move(left))));
152✔
792
            case CompareType::CONTAINS:
272✔
793
                return Query(std::unique_ptr<Expression>(new Compare<Contains>(std::move(right), std::move(left))));
272✔
794
            case CompareType::LIKE:
152✔
795
                return Query(std::unique_ptr<Expression>(new Compare<Like>(std::move(right), std::move(left))));
152✔
796
            case CompareType::TEXT: {
4✔
797
                StringData val = right->get_mixed().get_string();
4✔
798
                auto string_prop = dynamic_cast<Columns<StringData>*>(left.get());
4✔
799
                return string_prop->fulltext(val);
4✔
800
            }
×
801
            case CompareType::IN:
✔
802
            case CompareType::EQUAL:
✔
803
            case CompareType::NOT_EQUAL:
✔
804
            case CompareType::GREATER:
✔
805
            case CompareType::LESS:
✔
806
            case CompareType::GREATER_EQUAL:
✔
807
            case CompareType::LESS_EQUAL:
✔
808
                break;
×
809
        }
1,160✔
810
    }
1,160✔
811
    else {
1,160✔
812
        switch (op) {
1,160✔
813
            case CompareType::BEGINSWITH:
200✔
814
                return Query(
200✔
815
                    std::unique_ptr<Expression>(new Compare<BeginsWithIns>(std::move(right), std::move(left))));
200✔
816
            case CompareType::ENDSWITH:
168✔
817
                return Query(
168✔
818
                    std::unique_ptr<Expression>(new Compare<EndsWithIns>(std::move(right), std::move(left))));
168✔
819
            case CompareType::CONTAINS:
328✔
820
                return Query(
328✔
821
                    std::unique_ptr<Expression>(new Compare<ContainsIns>(std::move(right), std::move(left))));
328✔
822
            case CompareType::LIKE:
160✔
823
                return Query(std::unique_ptr<Expression>(new Compare<LikeIns>(std::move(right), std::move(left))));
160✔
824
            case CompareType::IN:
✔
825
            case CompareType::EQUAL:
✔
826
            case CompareType::NOT_EQUAL:
✔
827
            case CompareType::GREATER:
✔
828
            case CompareType::LESS:
✔
829
            case CompareType::GREATER_EQUAL:
✔
830
            case CompareType::LESS_EQUAL:
✔
831
            case CompareType::TEXT:
✔
832
                break;
×
833
        }
×
834
    }
×
835
    return {};
×
836
}
×
837

838
#if REALM_ENABLE_GEOSPATIAL
839
Query GeoWithinNode::visit(ParserDriver* drv)
840
{
176✔
841
    auto left = prop->visit(drv);
176✔
842
    auto left_type = left->get_type();
176✔
843
    if (left_type != type_Link) {
176✔
844
        throw InvalidQueryError(util::format("The left hand side of 'geoWithin' must be a link to geoJSON formatted "
4✔
845
                                             "data. But the provided type is '%1'",
4✔
846
                                             get_data_type_name(left_type)));
4✔
847
    }
4✔
848
    auto link_column = dynamic_cast<const Columns<Link>*>(left.get());
172✔
849

86✔
850
    if (geo) {
172✔
851
        auto right = geo->visit(drv, type_Int);
124✔
852
        auto geo_value = dynamic_cast<const ConstantGeospatialValue*>(right.get());
124✔
853
        return link_column->geo_within(geo_value->get_mixed().get<Geospatial>());
124✔
854
    }
124✔
855

24✔
856
    REALM_ASSERT_3(argument.size(), >, 1);
48✔
857
    REALM_ASSERT_3(argument[0], ==, '$');
48✔
858
    size_t arg_no = size_t(strtol(argument.substr(1).c_str(), nullptr, 10));
48✔
859
    auto right_type = drv->m_args.is_argument_null(arg_no) ? DataType(-1) : drv->m_args.type_for_argument(arg_no);
46✔
860

24✔
861
    Geospatial geo_from_argument;
48✔
862
    if (right_type == type_Geospatial) {
48✔
863
        geo_from_argument = drv->m_args.geospatial_for_argument(arg_no);
16✔
864
    }
16✔
865
    else if (right_type == type_String) {
32✔
866
        // This is a "hack" to allow users to pass in geospatial objects
10✔
867
        // serialized as a string instead of as a native type. This is because
10✔
868
        // the CAPI doesn't have support for marshalling polygons (of variable length)
10✔
869
        // yet and that project was deprioritized to geospatial phase 2. This should be
10✔
870
        // removed once SDKs are all using the binding generator.
10✔
871
        std::string str_val = drv->m_args.string_for_argument(arg_no);
20✔
872
        const std::string simulated_prefix = "simulated GEOWITHIN ";
20✔
873
        str_val = simulated_prefix + str_val;
20✔
874
        ParserDriver sub_driver;
20✔
875
        try {
20✔
876
            sub_driver.parse(str_val);
20✔
877
        }
20✔
878
        catch (const std::exception& ex) {
14✔
879
            std::string doctored_err = ex.what();
8✔
880
            size_t prefix_location = doctored_err.find(simulated_prefix);
8✔
881
            if (prefix_location != std::string::npos) {
8✔
882
                doctored_err.erase(prefix_location, simulated_prefix.size());
8✔
883
            }
8✔
884
            throw InvalidQueryError(util::format(
8✔
885
                "Invalid syntax in serialized geospatial object at argument %1: '%2'", arg_no, doctored_err));
8✔
886
        }
8✔
887
        GeoWithinNode* node = dynamic_cast<GeoWithinNode*>(sub_driver.result);
12✔
888
        REALM_ASSERT(node);
12✔
889
        if (node->geo) {
12✔
890
            if (node->geo->m_geo.get_type() != Geospatial::Type::Invalid) {
12✔
891
                geo_from_argument = node->geo->m_geo;
4✔
892
            }
4✔
893
            else {
8✔
894
                geo_from_argument = GeoPolygon{node->geo->m_points};
8✔
895
            }
8✔
896
        }
12✔
897
    }
12✔
898
    else {
12✔
899
        throw InvalidQueryError(util::format("The right hand side of 'geoWithin' must be a geospatial constant "
12✔
900
                                             "value. But the provided type is '%1'",
12✔
901
                                             get_data_type_name(right_type)));
12✔
902
    }
12✔
903

14✔
904
    if (geo_from_argument.get_type() == Geospatial::Type::Invalid) {
28✔
905
        throw InvalidQueryError(util::format(
4✔
906
            "The right hand side of 'geoWithin' must be a valid Geospatial value, got '%1'", geo_from_argument));
4✔
907
    }
4✔
908
    Status geo_status = geo_from_argument.is_valid();
24✔
909
    if (!geo_status.is_ok()) {
24✔
910
        throw InvalidQueryError(
×
911
            util::format("The Geospatial query argument region is invalid: '%1'", geo_status.reason()));
×
912
    }
×
913
    return link_column->geo_within(geo_from_argument);
24✔
914
}
24✔
915
#endif
916

917
Query TrueOrFalseNode::visit(ParserDriver* drv)
918
{
612✔
919
    Query q = drv->m_base_table->where();
612✔
920
    if (true_or_false) {
612✔
921
        q.and_query(std::unique_ptr<realm::Expression>(new TrueExpression));
460✔
922
    }
460✔
923
    else {
152✔
924
        q.and_query(std::unique_ptr<realm::Expression>(new FalseExpression));
152✔
925
    }
152✔
926
    return q;
612✔
927
}
612✔
928

929
std::unique_ptr<Subexpr> PropertyNode::visit(ParserDriver* drv, DataType)
930
{
474,476✔
931
    if (path->path_elems.back().is_key() && path->path_elems.back().get_key() == "@links") {
474,476✔
932
        identifier = "@links";
304✔
933
        // This is a backlink aggregate query
152✔
934
        path->path_elems.pop_back();
304✔
935
        auto link_chain = path->visit(drv, comp_type);
304✔
936
        auto sub = link_chain.get_backlink_count<Int>();
304✔
937
        return sub.clone();
304✔
938
    }
304✔
939
    m_link_chain = path->visit(drv, comp_type);
474,172✔
940
    if (!path->at_end()) {
474,172✔
941
        if (!path->current_path_elem->is_key()) {
472,460✔
942
            throw InvalidQueryError(util::format("[%1] not expected", *path->current_path_elem));
4✔
943
        }
4✔
944
        identifier = path->current_path_elem->get_key();
472,456✔
945
    }
472,456✔
946
    std::unique_ptr<Subexpr> subexpr{drv->column(m_link_chain, path)};
474,170✔
947

237,074✔
948
    Path indexes;
474,168✔
949
    while (!path->at_end()) {
477,912✔
950
        indexes.emplace_back(std::move(*(path->current_path_elem++)));
3,744✔
951
    }
3,744✔
952

237,074✔
953
    if (!indexes.empty()) {
474,168✔
954
        auto ok = false;
3,480✔
955
        const PathElement& first_index = indexes.front();
3,480✔
956
        if (indexes.size() > 1 && subexpr->get_type() != type_Mixed) {
3,480✔
UNCOV
957
            throw InvalidQueryError("Only Property of type 'any' can have nested collections");
×
958
        }
×
959
        if (auto mixed = dynamic_cast<Columns<Mixed>*>(subexpr.get())) {
3,480✔
960
            ok = true;
128✔
961
            mixed->path(indexes);
128✔
962
        }
128✔
963
        else if (auto dict = dynamic_cast<Columns<Dictionary>*>(subexpr.get())) {
3,352✔
964
            if (first_index.is_key()) {
224✔
965
                ok = true;
180✔
966
                auto trailing = first_index.get_key();
180✔
967
                if (trailing == "@values") {
180✔
968
                }
4✔
969
                else if (trailing == "@keys") {
176✔
970
                    subexpr = std::make_unique<ColumnDictionaryKeys>(*dict);
44✔
971
                }
44✔
972
                else {
132✔
973
                    dict->path(indexes);
132✔
974
                }
132✔
975
            }
180✔
976
            else if (first_index.is_all()) {
44✔
977
                ok = true;
36✔
978
                dict->path(indexes);
36✔
979
            }
36✔
980
        }
224✔
981
        else if (auto coll = dynamic_cast<Columns<Lst<Mixed>>*>(subexpr.get())) {
3,128✔
982
            ok = coll->indexes(indexes);
40✔
983
        }
40✔
984
        else if (auto coll = dynamic_cast<ColumnListBase*>(subexpr.get())) {
3,088✔
985
            if (indexes.size() == 1) {
3,080✔
986
                ok = coll->index(first_index);
3,080✔
987
            }
3,080✔
988
        }
3,080✔
989

1,740✔
990
        if (!ok) {
3,480✔
991
            if (first_index.is_key()) {
1,744✔
992
                auto trailing = first_index.get_key();
1,704✔
993
                if (!post_op && is_length_suffix(trailing)) {
1,704✔
994
                    // If 'length' is the operator, the last id in the path must be the name
844✔
995
                    // of a list property
844✔
996
                    path->path_elems.pop_back();
1,688✔
997
                    const std::string& prop = path->path_elems.back().get_key();
1,688✔
998
                    std::unique_ptr<Subexpr> subexpr{path->visit(drv, comp_type).column(prop)};
1,688✔
999
                    if (auto list = dynamic_cast<ColumnListBase*>(subexpr.get())) {
1,688✔
1000
                        if (auto length_expr = list->get_element_length())
1,688✔
1001
                            return length_expr;
1,624✔
1002
                    }
80✔
1003
                }
1,688✔
1004
                throw InvalidQueryError(util::format("Property '%1.%2' has no property '%3'",
80✔
1005
                                                     m_link_chain.get_current_table()->get_class_name(), identifier,
80✔
1006
                                                     trailing));
80✔
1007
            }
80✔
1008
            else {
40✔
1009
                throw InvalidQueryError(util::format("Property '%1.%2' does not support index '%3'",
40✔
1010
                                                     m_link_chain.get_current_table()->get_class_name(), identifier,
40✔
1011
                                                     first_index));
40✔
1012
            }
40✔
1013
        }
472,424✔
1014
    }
3,480✔
1015
    if (post_op) {
472,424✔
1016
        return post_op->visit(drv, subexpr.get());
4,012✔
1017
    }
4,012✔
1018
    return subexpr;
468,412✔
1019
}
468,412✔
1020

1021
std::unique_ptr<Subexpr> SubqueryNode::visit(ParserDriver* drv, DataType)
1022
{
304✔
1023
    if (variable_name.size() < 2 || variable_name[0] != '$') {
304✔
1024
        throw SyntaxError(util::format("The subquery variable '%1' is invalid. The variable must start with "
4✔
1025
                                       "'$' and cannot be empty; for example '$x'.",
4✔
1026
                                       variable_name));
4✔
1027
    }
4✔
1028
    LinkChain lc = prop->path->visit(drv, prop->comp_type);
300✔
1029

150✔
1030
    ColKey col_key;
300✔
1031
    std::string identifier;
300✔
1032
    if (!prop->path->at_end()) {
300✔
1033
        identifier = prop->path->next_identifier();
8✔
1034
        col_key = lc.get_current_table()->get_column_key(identifier);
8✔
1035
    }
8✔
1036
    else {
292✔
1037
        identifier = prop->path->last_identifier();
292✔
1038
        col_key = lc.get_current_col();
292✔
1039
    }
292✔
1040

150✔
1041
    auto col_type = col_key.get_type();
300✔
1042
    if (col_key.is_list() && col_type != col_type_LinkList) {
300✔
1043
        throw InvalidQueryError(
4✔
1044
            util::format("A subquery can not operate on a list of primitive values (property '%1')", identifier));
4✔
1045
    }
4✔
1046
    if (col_type != col_type_LinkList && col_type != col_type_BackLink) {
296✔
1047
        throw InvalidQueryError(util::format("A subquery must operate on a list property, but '%1' is type '%2'",
8✔
1048
                                             identifier, realm::get_data_type_name(DataType(col_type))));
8✔
1049
    }
8✔
1050

144✔
1051
    TableRef previous_table = drv->m_base_table;
288✔
1052
    drv->m_base_table = lc.get_current_table().cast_away_const();
288✔
1053
    bool did_add = drv->m_mapping.add_mapping(drv->m_base_table, variable_name, "");
288✔
1054
    if (!did_add) {
288✔
1055
        throw InvalidQueryError(util::format("Unable to create a subquery expression with variable '%1' since an "
4✔
1056
                                             "identical variable already exists in this context",
4✔
1057
                                             variable_name));
4✔
1058
    }
4✔
1059
    Query sub = subquery->visit(drv);
284✔
1060
    drv->m_mapping.remove_mapping(drv->m_base_table, variable_name);
284✔
1061
    drv->m_base_table = previous_table;
284✔
1062

142✔
1063
    return lc.subquery(sub);
284✔
1064
}
284✔
1065

1066
std::unique_ptr<Subexpr> PostOpNode::visit(ParserDriver*, Subexpr* subexpr)
1067
{
4,012✔
1068
    if (op_type == PostOpNode::SIZE) {
4,012✔
1069
        if (auto s = dynamic_cast<Columns<Link>*>(subexpr)) {
3,428✔
1070
            return s->count().clone();
344✔
1071
        }
344✔
1072
        if (auto s = dynamic_cast<ColumnListBase*>(subexpr)) {
3,084✔
1073
            return s->size().clone();
2,896✔
1074
        }
2,896✔
1075
        if (auto s = dynamic_cast<Columns<StringData>*>(subexpr)) {
188✔
1076
            return s->size().clone();
128✔
1077
        }
128✔
1078
        if (auto s = dynamic_cast<Columns<BinaryData>*>(subexpr)) {
60✔
1079
            return s->size().clone();
48✔
1080
        }
48✔
1081
    }
584✔
1082
    else if (op_type == PostOpNode::TYPE) {
584✔
1083
        if (auto s = dynamic_cast<Columns<Mixed>*>(subexpr)) {
584✔
1084
            return s->type_of_value().clone();
452✔
1085
        }
452✔
1086
        if (auto s = dynamic_cast<ColumnsCollection<Mixed>*>(subexpr)) {
132✔
1087
            return s->type_of_value().clone();
112✔
1088
        }
112✔
1089
        if (auto s = dynamic_cast<ObjPropertyBase*>(subexpr)) {
20✔
1090
            return Value<TypeOfValue>(TypeOfValue(s->column_key())).clone();
8✔
1091
        }
8✔
1092
        if (dynamic_cast<Columns<Link>*>(subexpr)) {
12✔
1093
            return Value<TypeOfValue>(TypeOfValue(TypeOfValue::Attribute::ObjectLink)).clone();
12✔
1094
        }
12✔
1095
    }
12✔
1096

6✔
1097
    if (subexpr) {
12✔
1098
        throw InvalidQueryError(util::format("Operation '%1' is not supported on property of type '%2'", op_name,
12✔
1099
                                             get_data_type_name(DataType(subexpr->get_type()))));
12✔
1100
    }
12✔
UNCOV
1101
    REALM_UNREACHABLE();
×
UNCOV
1102
    return {};
×
UNCOV
1103
}
×
1104

1105
std::unique_ptr<Subexpr> LinkAggrNode::visit(ParserDriver* drv, DataType)
1106
{
784✔
1107
    auto subexpr = property->visit(drv);
784✔
1108
    auto link_prop = dynamic_cast<Columns<Link>*>(subexpr.get());
784✔
1109
    if (!link_prop) {
784✔
1110
        throw InvalidQueryError(util::format("Operation '%1' cannot apply to property '%2' because it is not a list",
40✔
1111
                                             agg_op_type_to_str(type), property->get_identifier()));
40✔
1112
    }
40✔
1113
    const LinkChain& link_chain = property->link_chain();
744✔
1114
    prop_name = drv->translate(link_chain, prop_name);
744✔
1115
    auto col_key = link_chain.get_current_table()->get_column_key(prop_name);
744✔
1116

372✔
1117
    switch (col_key.get_type()) {
744✔
1118
        case col_type_Int:
64✔
1119
            subexpr = link_prop->column<Int>(col_key).clone();
64✔
1120
            break;
64✔
1121
        case col_type_Float:
128✔
1122
            subexpr = link_prop->column<float>(col_key).clone();
128✔
1123
            break;
128✔
1124
        case col_type_Double:
344✔
1125
            subexpr = link_prop->column<double>(col_key).clone();
344✔
1126
            break;
344✔
1127
        case col_type_Decimal:
96✔
1128
            subexpr = link_prop->column<Decimal>(col_key).clone();
96✔
1129
            break;
96✔
1130
        case col_type_Timestamp:
56✔
1131
            subexpr = link_prop->column<Timestamp>(col_key).clone();
56✔
1132
            break;
56✔
1133
        default:
48✔
1134
            throw InvalidQueryError(util::format("collection aggregate not supported for type '%1'",
48✔
1135
                                                 get_data_type_name(DataType(col_key.get_type()))));
48✔
1136
    }
688✔
1137
    return aggregate(subexpr.get());
688✔
1138
}
688✔
1139

1140
std::unique_ptr<Subexpr> ListAggrNode::visit(ParserDriver* drv, DataType)
1141
{
2,728✔
1142
    auto subexpr = property->visit(drv);
2,728✔
1143
    return aggregate(subexpr.get());
2,728✔
1144
}
2,728✔
1145

1146
std::unique_ptr<Subexpr> AggrNode::aggregate(Subexpr* subexpr)
1147
{
3,416✔
1148
    std::unique_ptr<Subexpr> agg;
3,416✔
1149
    if (auto list_prop = dynamic_cast<ColumnListBase*>(subexpr)) {
3,416✔
1150
        switch (type) {
2,696✔
1151
            case MAX:
628✔
1152
                agg = list_prop->max_of();
628✔
1153
                break;
628✔
1154
            case MIN:
604✔
1155
                agg = list_prop->min_of();
604✔
1156
                break;
604✔
1157
            case SUM:
796✔
1158
                agg = list_prop->sum_of();
796✔
1159
                break;
796✔
1160
            case AVG:
668✔
1161
                agg = list_prop->avg_of();
668✔
1162
                break;
668✔
1163
        }
720✔
1164
    }
720✔
1165
    else if (auto prop = dynamic_cast<SubColumnBase*>(subexpr)) {
720✔
1166
        switch (type) {
688✔
1167
            case MAX:
200✔
1168
                agg = prop->max_of();
200✔
1169
                break;
200✔
1170
            case MIN:
192✔
1171
                agg = prop->min_of();
192✔
1172
                break;
192✔
1173
            case SUM:
132✔
1174
                agg = prop->sum_of();
132✔
1175
                break;
132✔
1176
            case AVG:
164✔
1177
                agg = prop->avg_of();
164✔
1178
                break;
164✔
1179
        }
3,416✔
1180
    }
3,416✔
1181
    if (!agg) {
3,416✔
1182
        throw InvalidQueryError(
216✔
1183
            util::format("Cannot use aggregate '%1' for this type of property", agg_op_type_to_str(type)));
216✔
1184
    }
216✔
1185

1,600✔
1186
    return agg;
3,200✔
1187
}
3,200✔
1188

1189
void ConstantNode::decode_b64(util::FunctionRef<void(StringData)> callback)
1190
{
1,432✔
1191
    const size_t encoded_size = text.size() - 5;
1,432✔
1192
    size_t buffer_size = util::base64_decoded_size(encoded_size);
1,432✔
1193
    std::string decode_buffer(buffer_size, char(0));
1,432✔
1194
    StringData window(text.c_str() + 4, encoded_size);
1,432✔
1195
    util::Optional<size_t> decoded_size = util::base64_decode(window, decode_buffer.data(), buffer_size);
1,432✔
1196
    if (!decoded_size) {
1,432✔
UNCOV
1197
        throw SyntaxError("Invalid base64 value");
×
UNCOV
1198
    }
×
1199
    REALM_ASSERT_DEBUG_EX(*decoded_size <= encoded_size, *decoded_size, encoded_size);
1,432✔
1200
    decode_buffer.resize(*decoded_size); // truncate
1,432✔
1201
    callback(StringData(decode_buffer.data(), decode_buffer.size()));
1,432✔
1202
}
1,432✔
1203

1204
std::unique_ptr<Subexpr> ConstantNode::visit(ParserDriver* drv, DataType hint)
1205
{
471,168✔
1206
    std::unique_ptr<Subexpr> ret;
471,168✔
1207
    std::string explain_value_message = text;
471,168✔
1208
    if (target_table.length()) {
471,168✔
1209
        const Group* g = drv->m_base_table->get_parent_group();
104✔
1210
        TableKey table_key;
104✔
1211
        ObjKey obj_key;
104✔
1212
        auto table = g->get_table(target_table);
104✔
1213
        if (!table) {
104✔
1214
            // Perhaps class prefix is missing
4✔
1215
            Group::TableNameBuffer buffer;
8✔
1216
            table = g->get_table(Group::class_name_to_table_name(target_table, buffer));
8✔
1217
        }
8✔
1218
        if (!table) {
104✔
UNCOV
1219
            throw InvalidQueryError(util::format("Unknown object type '%1'", target_table));
×
UNCOV
1220
        }
×
1221
        table_key = table->get_key();
104✔
1222
        target_table = "";
104✔
1223
        auto pk_val_node = visit(drv, hint); // call recursively
104✔
1224
        auto pk_val = pk_val_node->get_mixed();
104✔
1225
        obj_key = table->find_primary_key(pk_val);
104✔
1226
        return std::make_unique<Value<ObjLink>>(ObjLink(table_key, ObjKey(obj_key)));
104✔
1227
    }
104✔
1228
    switch (type) {
471,064✔
1229
        case Type::NUMBER: {
22,200✔
1230
            if (hint == type_Decimal) {
22,200✔
1231
                ret = std::make_unique<Value<Decimal128>>(Decimal128(text));
716✔
1232
            }
716✔
1233
            else {
21,484✔
1234
                ret = std::make_unique<Value<int64_t>>(strtoll(text.c_str(), nullptr, 0));
21,484✔
1235
            }
21,484✔
1236
            break;
22,200✔
1237
        }
×
1238
        case Type::FLOAT: {
2,108✔
1239
            if (hint == type_Float || text[text.size() - 1] == 'f') {
2,108✔
1240
                ret = std::make_unique<Value<float>>(strtof(text.c_str(), nullptr));
104✔
1241
            }
104✔
1242
            else if (hint == type_Decimal) {
2,004✔
1243
                ret = std::make_unique<Value<Decimal128>>(Decimal128(text));
412✔
1244
            }
412✔
1245
            else {
1,592✔
1246
                ret = std::make_unique<Value<double>>(strtod(text.c_str(), nullptr));
1,592✔
1247
            }
1,592✔
1248
            break;
2,108✔
UNCOV
1249
        }
×
1250
        case Type::INFINITY_VAL: {
152✔
1251
            bool negative = text[0] == '-';
152✔
1252
            switch (hint) {
152✔
1253
                case type_Float: {
48✔
1254
                    auto inf = std::numeric_limits<float>::infinity();
48✔
1255
                    ret = std::make_unique<Value<float>>(negative ? -inf : inf);
40✔
1256
                    break;
48✔
1257
                }
×
1258
                case type_Double: {
48✔
1259
                    auto inf = std::numeric_limits<double>::infinity();
48✔
1260
                    ret = std::make_unique<Value<double>>(negative ? -inf : inf);
40✔
1261
                    break;
48✔
UNCOV
1262
                }
×
1263
                case type_Decimal:
48✔
1264
                    ret = std::make_unique<Value<Decimal128>>(Decimal128(text));
48✔
1265
                    break;
48✔
1266
                default:
8✔
1267
                    throw InvalidQueryError(util::format("Infinity not supported for %1", get_data_type_name(hint)));
8✔
UNCOV
1268
                    break;
×
1269
            }
144✔
1270
            break;
144✔
1271
        }
144✔
1272
        case Type::NAN_VAL: {
104✔
1273
            switch (hint) {
64✔
1274
                case type_Float:
32✔
1275
                    ret = std::make_unique<Value<float>>(type_punning<float>(0x7fc00000));
32✔
1276
                    break;
32✔
1277
                case type_Double:
32✔
1278
                    ret = std::make_unique<Value<double>>(type_punning<double>(0x7ff8000000000000));
32✔
1279
                    break;
32✔
UNCOV
1280
                case type_Decimal:
✔
UNCOV
1281
                    ret = std::make_unique<Value<Decimal128>>(Decimal128::nan("0"));
×
UNCOV
1282
                    break;
×
UNCOV
1283
                default:
✔
UNCOV
1284
                    REALM_UNREACHABLE();
×
UNCOV
1285
                    break;
×
1286
            }
64✔
1287
            break;
64✔
1288
        }
64✔
1289
        case Type::STRING: {
6,180✔
1290
            std::string str = text.substr(1, text.size() - 2);
6,180✔
1291
            switch (hint) {
6,180✔
1292
                case type_Int:
408✔
1293
                    ret = std::make_unique<Value<int64_t>>(string_to<int64_t>(str));
408✔
1294
                    break;
408✔
UNCOV
1295
                case type_Float:
✔
UNCOV
1296
                    ret = std::make_unique<Value<float>>(string_to<float>(str));
×
UNCOV
1297
                    break;
×
UNCOV
1298
                case type_Double:
✔
UNCOV
1299
                    ret = std::make_unique<Value<double>>(string_to<double>(str));
×
UNCOV
1300
                    break;
×
UNCOV
1301
                case type_Decimal:
✔
UNCOV
1302
                    ret = std::make_unique<Value<Decimal128>>(Decimal128(str.c_str()));
×
UNCOV
1303
                    break;
×
1304
                default:
5,772✔
1305
                    if (hint == type_TypeOfValue) {
5,772✔
1306
                        ret = std::make_unique<Value<TypeOfValue>>(TypeOfValue(str));
496✔
1307
                    }
496✔
1308
                    else {
5,276✔
1309
                        ret = std::make_unique<ConstantStringValue>(str);
5,276✔
1310
                    }
5,276✔
1311
                    break;
5,772✔
1312
            }
6,152✔
1313
            break;
6,152✔
1314
        }
6,152✔
1315
        case Type::STRING_BASE64: {
3,434✔
1316
            decode_b64([&](StringData decoded) {
716✔
1317
                ret = std::make_unique<ConstantStringValue>(decoded);
716✔
1318
            });
716✔
1319
            break;
716✔
1320
        }
6,152✔
1321
        case Type::TIMESTAMP: {
3,382✔
1322
            auto s = text;
612✔
1323
            int64_t seconds;
612✔
1324
            int32_t nanoseconds;
612✔
1325
            if (s[0] == 'T') {
612✔
1326
                size_t colon_pos = s.find(":");
536✔
1327
                std::string s1 = s.substr(1, colon_pos - 1);
536✔
1328
                std::string s2 = s.substr(colon_pos + 1);
536✔
1329
                seconds = strtol(s1.c_str(), nullptr, 0);
536✔
1330
                nanoseconds = int32_t(strtol(s2.c_str(), nullptr, 0));
536✔
1331
            }
536✔
1332
            else {
76✔
1333
                // readable format YYYY-MM-DD-HH:MM:SS:NANOS nanos optional
38✔
1334
                struct tm tmp = tm();
76✔
1335
                char sep = s.find("@") < s.size() ? '@' : 'T';
62✔
1336
                std::string fmt = "%d-%d-%d"s + sep + "%d:%d:%d:%d"s;
76✔
1337
                int cnt = sscanf(s.c_str(), fmt.c_str(), &tmp.tm_year, &tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour,
76✔
1338
                                 &tmp.tm_min, &tmp.tm_sec, &nanoseconds);
76✔
1339
                REALM_ASSERT(cnt >= 6);
76✔
1340
                tmp.tm_year -= 1900; // epoch offset (see man mktime)
76✔
1341
                tmp.tm_mon -= 1;     // converts from 1-12 to 0-11
76✔
1342

38✔
1343
                if (tmp.tm_year < 0) {
76✔
1344
                    // platform timegm functions do not throw errors, they return -1 which is also a valid time
8✔
1345
                    throw InvalidQueryError("Conversion of dates before 1900 is not supported.");
16✔
1346
                }
16✔
1347

30✔
1348
                seconds = platform_timegm(tmp); // UTC time
60✔
1349
                if (cnt == 6) {
60✔
1350
                    nanoseconds = 0;
32✔
1351
                }
32✔
1352
                if (nanoseconds < 0) {
60✔
UNCOV
1353
                    throw SyntaxError("The nanoseconds of a Timestamp cannot be negative.");
×
UNCOV
1354
                }
×
1355
                if (seconds < 0) { // seconds determines the sign of the nanoseconds part
60✔
1356
                    nanoseconds *= -1;
24✔
1357
                }
24✔
1358
            }
60✔
1359
            ret = std::make_unique<Value<Timestamp>>(get_timestamp_if_valid(seconds, nanoseconds));
604✔
1360
            break;
596✔
1361
        }
612✔
1362
        case Type::UUID_T:
672✔
1363
            ret = std::make_unique<Value<UUID>>(UUID(text.substr(5, text.size() - 6)));
672✔
1364
            break;
672✔
1365
        case Type::OID:
772✔
1366
            ret = std::make_unique<Value<ObjectId>>(ObjectId(text.substr(4, text.size() - 5).c_str()));
772✔
1367
            break;
772✔
1368
        case Type::LINK: {
310✔
1369
            ret =
8✔
1370
                std::make_unique<Value<ObjKey>>(ObjKey(strtol(text.substr(1, text.size() - 1).c_str(), nullptr, 0)));
8✔
1371
            break;
8✔
1372
        }
612✔
1373
        case Type::TYPED_LINK: {
330✔
1374
            size_t colon_pos = text.find(":");
48✔
1375
            auto table_key_val = uint32_t(strtol(text.substr(1, colon_pos - 1).c_str(), nullptr, 0));
48✔
1376
            auto obj_key_val = strtol(text.substr(colon_pos + 1).c_str(), nullptr, 0);
48✔
1377
            ret = std::make_unique<Value<ObjLink>>(ObjLink(TableKey(table_key_val), ObjKey(obj_key_val)));
48✔
1378
            break;
48✔
1379
        }
612✔
1380
        case Type::NULL_VAL:
2,216✔
1381
            if (hint == type_String) {
2,216✔
1382
                ret = std::make_unique<ConstantStringValue>(StringData()); // Null string
320✔
1383
            }
320✔
1384
            else if (hint == type_Binary) {
1,896✔
1385
                ret = std::make_unique<Value<Binary>>(BinaryData()); // Null string
312✔
1386
            }
312✔
1387
            else {
1,584✔
1388
                ret = std::make_unique<Value<null>>(realm::null());
1,584✔
1389
            }
1,584✔
1390
            break;
2,216✔
1391
        case Type::TRUE:
386✔
1392
            ret = std::make_unique<Value<Bool>>(true);
160✔
1393
            break;
160✔
1394
        case Type::FALSE:
462✔
1395
            ret = std::make_unique<Value<Bool>>(false);
312✔
1396
            break;
312✔
1397
        case Type::ARG: {
433,060✔
1398
            size_t arg_no = size_t(strtol(text.substr(1).c_str(), nullptr, 10));
433,060✔
1399
            if (m_comp_type && !drv->m_args.is_argument_list(arg_no)) {
433,060✔
1400
                throw InvalidQueryError(util::format(
12✔
1401
                    "ANY/ALL/NONE are only allowed on arguments which contain a list but '%1' is not a list.",
12✔
1402
                    explain_value_message));
12✔
1403
            }
12✔
1404
            if (drv->m_args.is_argument_null(arg_no)) {
433,048✔
1405
                explain_value_message = util::format("argument '%1' which is NULL", explain_value_message);
256✔
1406
                ret = std::make_unique<Value<null>>(realm::null());
256✔
1407
            }
256✔
1408
            else if (drv->m_args.is_argument_list(arg_no)) {
432,792✔
1409
                std::vector<Mixed> mixed_list = drv->m_args.list_for_argument(arg_no);
144✔
1410
                ret = copy_list_of_args(mixed_list);
144✔
1411
            }
144✔
1412
            else {
432,648✔
1413
                auto type = drv->m_args.type_for_argument(arg_no);
432,648✔
1414
                explain_value_message =
432,648✔
1415
                    util::format("argument %1 of type '%2'", explain_value_message, get_data_type_name(type));
432,648✔
1416
                ret = copy_arg(drv, type, arg_no, hint, explain_value_message);
432,648✔
1417
            }
432,648✔
1418
            break;
433,048✔
1419
        }
433,048✔
1420
        case BINARY_STR: {
217,058✔
1421
            std::string str = text.substr(1, text.size() - 2);
1,068✔
1422
            ret = std::make_unique<ConstantBinaryValue>(BinaryData(str.data(), str.size()));
1,068✔
1423
            break;
1,068✔
1424
        }
433,048✔
1425
        case BINARY_BASE64:
216,882✔
1426
            decode_b64([&](StringData decoded) {
716✔
1427
                ret = std::make_unique<ConstantBinaryValue>(BinaryData(decoded.data(), decoded.size()));
716✔
1428
            });
716✔
1429
            break;
716✔
1430
    }
470,950✔
1431
    if (!ret) {
470,950✔
UNCOV
1432
        throw InvalidQueryError(
×
UNCOV
1433
            util::format("Unsupported comparison between property of type '%1' and constant value: %2",
×
UNCOV
1434
                         get_data_type_name(hint), explain_value_message));
×
UNCOV
1435
    }
×
1436
    return ret;
470,950✔
1437
}
470,950✔
1438

1439
std::unique_ptr<ConstantMixedList> ConstantNode::copy_list_of_args(std::vector<Mixed>& mixed_args)
1440
{
144✔
1441
    std::unique_ptr<ConstantMixedList> args_in_list = std::make_unique<ConstantMixedList>(mixed_args.size());
144✔
1442
    size_t ndx = 0;
144✔
1443
    for (const auto& mixed : mixed_args) {
352✔
1444
        args_in_list->set(ndx++, mixed);
352✔
1445
    }
352✔
1446
    if (m_comp_type) {
144✔
1447
        args_in_list->set_comparison_type(*m_comp_type);
20✔
1448
    }
20✔
1449
    return args_in_list;
144✔
1450
}
144✔
1451

1452
std::unique_ptr<Subexpr> ConstantNode::copy_arg(ParserDriver* drv, DataType type, size_t arg_no, DataType hint,
1453
                                                std::string& err)
1454
{
432,616✔
1455
    switch (type) {
432,616✔
1456
        case type_Int:
828✔
1457
            return std::make_unique<Value<int64_t>>(drv->m_args.long_for_argument(arg_no));
828✔
1458
        case type_String:
388✔
1459
            return std::make_unique<ConstantStringValue>(drv->m_args.string_for_argument(arg_no));
388✔
1460
        case type_Binary:
176✔
1461
            return std::make_unique<ConstantBinaryValue>(drv->m_args.binary_for_argument(arg_no));
176✔
1462
        case type_Bool:
316✔
1463
            return std::make_unique<Value<Bool>>(drv->m_args.bool_for_argument(arg_no));
316✔
1464
        case type_Float:
436✔
1465
            return std::make_unique<Value<float>>(drv->m_args.float_for_argument(arg_no));
436✔
1466
        case type_Double: {
524✔
1467
            // In realm-js all number type arguments are returned as double. If we don't cast to the
262✔
1468
            // expected type, we would in many cases miss the option to use the optimized query node
262✔
1469
            // instead of the general Compare class.
262✔
1470
            double val = drv->m_args.double_for_argument(arg_no);
524✔
1471
            switch (hint) {
524✔
1472
                case type_Int:
6✔
1473
                case type_Bool: {
8✔
1474
                    int64_t int_val = int64_t(val);
8✔
1475
                    // Only return an integer if it precisely represents val
4✔
1476
                    if (double(int_val) == val)
8✔
1477
                        return std::make_unique<Value<int64_t>>(int_val);
×
1478
                    else
8✔
1479
                        return std::make_unique<Value<double>>(val);
8✔
1480
                }
×
1481
                case type_Float:
4✔
1482
                    return std::make_unique<Value<float>>(float(val));
4✔
1483
                default:
512✔
1484
                    return std::make_unique<Value<double>>(val);
512✔
1485
            }
×
UNCOV
1486
            break;
×
UNCOV
1487
        }
×
1488
        case type_Timestamp: {
392✔
1489
            try {
392✔
1490
                return std::make_unique<Value<Timestamp>>(drv->m_args.timestamp_for_argument(arg_no));
392✔
1491
            }
392✔
UNCOV
1492
            catch (const std::exception&) {
×
UNCOV
1493
                return std::make_unique<Value<ObjectId>>(drv->m_args.objectid_for_argument(arg_no));
×
UNCOV
1494
            }
×
UNCOV
1495
        }
×
1496
        case type_ObjectId: {
428,612✔
1497
            try {
428,612✔
1498
                return std::make_unique<Value<ObjectId>>(drv->m_args.objectid_for_argument(arg_no));
428,612✔
1499
            }
428,612✔
1500
            catch (const std::exception&) {
×
1501
                return std::make_unique<Value<Timestamp>>(drv->m_args.timestamp_for_argument(arg_no));
×
UNCOV
1502
            }
×
UNCOV
1503
            break;
×
UNCOV
1504
        }
×
1505
        case type_Decimal:
492✔
1506
            return std::make_unique<Value<Decimal128>>(drv->m_args.decimal128_for_argument(arg_no));
492✔
1507
        case type_UUID:
400✔
1508
            return std::make_unique<Value<UUID>>(drv->m_args.uuid_for_argument(arg_no));
400✔
1509
        case type_Link:
12✔
1510
            return std::make_unique<Value<ObjKey>>(drv->m_args.object_index_for_argument(arg_no));
12✔
1511
        case type_TypedLink:
40✔
1512
            if (hint == type_Mixed || hint == type_Link || hint == type_TypedLink) {
40!
1513
                return std::make_unique<Value<ObjLink>>(drv->m_args.objlink_for_argument(arg_no));
40✔
1514
            }
40✔
UNCOV
1515
            err = util::format("%1 which links to %2", err,
×
UNCOV
1516
                               print_pretty_objlink(drv->m_args.objlink_for_argument(arg_no),
×
UNCOV
1517
                                                    drv->m_base_table->get_parent_group()));
×
UNCOV
1518
            break;
×
UNCOV
1519
        default:
✔
UNCOV
1520
            break;
×
UNCOV
1521
    }
×
UNCOV
1522
    return nullptr;
×
UNCOV
1523
}
×
1524

1525
#if REALM_ENABLE_GEOSPATIAL
1526
GeospatialNode::GeospatialNode(GeospatialNode::Box, GeoPoint& p1, GeoPoint& p2)
1527
    : m_geo{Geospatial{GeoBox{p1, p2}}}
1528
{
20✔
1529
}
20✔
1530

1531
GeospatialNode::GeospatialNode(Circle, GeoPoint& p, double radius)
1532
    : m_geo{Geospatial{GeoCircle{radius, p}}}
1533
{
60✔
1534
}
60✔
1535

1536
GeospatialNode::GeospatialNode(Polygon, GeoPoint& p)
1537
    : m_points({{p}})
UNCOV
1538
{
×
UNCOV
1539
}
×
1540

1541
GeospatialNode::GeospatialNode(Loop, GeoPoint& p)
1542
    : m_points({{p}})
1543
{
68✔
1544
}
68✔
1545

1546
void GeospatialNode::add_point_to_loop(GeoPoint& p)
1547
{
272✔
1548
    m_points.back().push_back(p);
272✔
1549
}
272✔
1550

1551
void GeospatialNode::add_loop_to_polygon(GeospatialNode* node)
1552
{
8✔
1553
    m_points.push_back(node->m_points.back());
8✔
1554
}
8✔
1555

1556
std::unique_ptr<Subexpr> GeospatialNode::visit(ParserDriver*, DataType)
1557
{
124✔
1558
    std::unique_ptr<Subexpr> ret;
124✔
1559
    if (m_geo.get_type() != Geospatial::Type::Invalid) {
124✔
1560
        ret = std::make_unique<ConstantGeospatialValue>(m_geo);
72✔
1561
    }
72✔
1562
    else {
52✔
1563
        ret = std::make_unique<ConstantGeospatialValue>(GeoPolygon{m_points});
52✔
1564
    }
52✔
1565
    return ret;
124✔
1566
}
124✔
1567
#endif
1568

1569
std::unique_ptr<Subexpr> ListNode::visit(ParserDriver* drv, DataType hint)
1570
{
1,196✔
1571
    if (hint == type_TypeOfValue) {
1,196✔
1572
        try {
12✔
1573
            std::unique_ptr<Value<TypeOfValue>> ret = std::make_unique<Value<TypeOfValue>>();
12✔
1574
            constexpr bool is_list = true;
12✔
1575
            ret->init(is_list, elements.size());
12✔
1576
            ret->set_comparison_type(m_comp_type);
12✔
1577
            size_t ndx = 0;
12✔
1578
            for (auto constant : elements) {
24✔
1579
                std::unique_ptr<Subexpr> evaluated = constant->visit(drv, hint);
24✔
1580
                if (auto converted = dynamic_cast<Value<TypeOfValue>*>(evaluated.get())) {
24✔
1581
                    ret->set(ndx++, converted->get(0));
20✔
1582
                }
20✔
1583
                else {
4✔
1584
                    throw InvalidQueryError(util::format("Invalid constant inside constant list: %1",
4✔
1585
                                                         evaluated->description(drv->m_serializer_state)));
4✔
1586
                }
4✔
1587
            }
24✔
1588
            return ret;
10✔
UNCOV
1589
        }
×
UNCOV
1590
        catch (const std::runtime_error& e) {
×
UNCOV
1591
            throw InvalidQueryArgError(e.what());
×
UNCOV
1592
        }
×
1593
    }
1,184✔
1594

592✔
1595
    auto ret = std::make_unique<ConstantMixedList>(elements.size());
1,184✔
1596
    ret->set_comparison_type(m_comp_type);
1,184✔
1597
    size_t ndx = 0;
1,184✔
1598
    for (auto constant : elements) {
3,120✔
1599
        auto evaulated_constant = constant->visit(drv, hint);
3,120✔
1600
        if (auto value = dynamic_cast<const ValueBase*>(evaulated_constant.get())) {
3,120✔
1601
            REALM_ASSERT_EX(value->size() == 1, value->size());
3,120✔
1602
            ret->set(ndx++, value->get(0));
3,120✔
1603
        }
3,120✔
UNCOV
1604
        else {
×
1605
            throw InvalidQueryError("Invalid constant inside constant list");
×
1606
        }
×
1607
    }
3,120✔
1608
    return ret;
1,184✔
1609
}
1,184✔
1610

1611
LinkChain PathNode::visit(ParserDriver* drv, util::Optional<ExpressionComparisonType> comp_type)
1612
{
476,456✔
1613
    LinkChain link_chain(drv->m_base_table, comp_type);
476,456✔
1614
    for (current_path_elem = path_elems.begin(); current_path_elem != path_elems.end(); ++current_path_elem) {
493,334✔
1615
        if (current_path_elem->is_key()) {
491,030✔
1616
            const std::string& raw_path_elem = current_path_elem->get_key();
490,946✔
1617
            auto path_elem = drv->translate(link_chain, raw_path_elem);
490,946✔
1618
            if (path_elem.find("@links.") == 0) {
490,946✔
1619
                std::string_view table_column_pair(path_elem);
504✔
1620
                table_column_pair = table_column_pair.substr(7);
504✔
1621
                auto dot_pos = table_column_pair.find('.');
504✔
1622
                auto table_name = table_column_pair.substr(0, dot_pos);
504✔
1623
                auto column_name = table_column_pair.substr(dot_pos + 1);
504✔
1624
                drv->backlink(link_chain, table_name, column_name);
504✔
1625
                continue;
504✔
1626
            }
504✔
1627
            if (path_elem == "@values") {
490,442✔
1628
                if (!link_chain.get_current_col().is_dictionary()) {
20✔
UNCOV
1629
                    throw InvalidQueryError("@values only allowed on dictionaries");
×
UNCOV
1630
                }
×
1631
                continue;
20✔
1632
            }
20✔
1633
            if (path_elem.empty()) {
490,422✔
1634
                continue; // this element has been removed, this happens in subqueries
284✔
1635
            }
284✔
1636

245,054✔
1637
            // Check if it is a link
245,054✔
1638
            if (link_chain.link(path_elem)) {
490,138✔
1639
                continue;
15,952✔
1640
            }
15,952✔
1641
            // The next identifier being a property on the linked to object takes precedence
237,078✔
1642
            if (link_chain.get_current_table()->get_column_key(path_elem)) {
474,186✔
1643
                break;
474,024✔
1644
            }
474,024✔
1645
        }
246✔
1646
        if (!link_chain.index(*current_path_elem))
246✔
1647
            break;
128✔
1648
    }
246✔
1649
    return link_chain;
476,456✔
1650
}
476,456✔
1651

1652
DescriptorNode::~DescriptorNode() {}
1,404✔
1653

1654
DescriptorOrderingNode::~DescriptorOrderingNode() {}
42,180✔
1655

1656
std::unique_ptr<DescriptorOrdering> DescriptorOrderingNode::visit(ParserDriver* drv)
1657
{
39,828✔
1658
    auto target = drv->m_base_table;
39,828✔
1659
    std::unique_ptr<DescriptorOrdering> ordering;
39,828✔
1660
    for (auto cur_ordering : orderings) {
20,482✔
1661
        if (!ordering)
1,140✔
1662
            ordering = std::make_unique<DescriptorOrdering>();
708✔
1663
        if (cur_ordering->get_type() == DescriptorNode::LIMIT) {
1,140✔
1664
            ordering->append_limit(LimitDescriptor(cur_ordering->limit));
340✔
1665
        }
340✔
1666
        else {
800✔
1667
            bool is_distinct = cur_ordering->get_type() == DescriptorNode::DISTINCT;
800✔
1668
            std::vector<std::vector<ExtendedColumnKey>> property_columns;
800✔
1669
            for (Path& path : cur_ordering->columns) {
836✔
1670
                std::vector<ExtendedColumnKey> columns;
836✔
1671
                LinkChain link_chain(target);
836✔
1672
                ColKey col_key;
836✔
1673
                for (size_t ndx_in_path = 0; ndx_in_path < path.size(); ++ndx_in_path) {
1,780✔
1674
                    std::string prop_name = drv->translate(link_chain, path[ndx_in_path].get_key());
952✔
1675
                    // If last column was a dictionary, We will treat the next entry as a key to
476✔
1676
                    // the dictionary
476✔
1677
                    if (col_key && col_key.is_dictionary()) {
952✔
1678
                        columns.back().set_index(prop_name);
32✔
1679
                    }
32✔
1680
                    else {
920✔
1681
                        col_key = link_chain.get_current_table()->get_column_key(prop_name);
920✔
1682
                        if (!col_key) {
920✔
1683
                            throw InvalidQueryError(util::format(
8✔
1684
                                "No property '%1' found on object type '%2' specified in '%3' clause", prop_name,
8✔
1685
                                link_chain.get_current_table()->get_class_name(), is_distinct ? "distinct" : "sort"));
6✔
1686
                        }
8✔
1687
                        columns.emplace_back(col_key);
912✔
1688
                        if (ndx_in_path < path.size() - 1) {
912✔
1689
                            link_chain.link(col_key);
116✔
1690
                        }
116✔
1691
                    }
912✔
1692
                }
952✔
1693
                property_columns.push_back(columns);
832✔
1694
            }
828✔
1695

400✔
1696
            if (is_distinct) {
796✔
1697
                ordering->append_distinct(DistinctDescriptor(property_columns));
252✔
1698
            }
252✔
1699
            else {
540✔
1700
                ordering->append_sort(SortDescriptor(property_columns, cur_ordering->ascending),
540✔
1701
                                      SortDescriptor::MergeMode::prepend);
540✔
1702
            }
540✔
1703
        }
792✔
1704
    }
1,140✔
1705

19,912✔
1706
    return ordering;
39,824✔
1707
}
39,828✔
1708

1709
// If one of the expresions is constant, it should be right
1710
static void verify_conditions(Subexpr* left, Subexpr* right, util::serializer::SerialisationState& state)
1711
{
470,840✔
1712
    if (dynamic_cast<ColumnListBase*>(left) && dynamic_cast<ColumnListBase*>(right)) {
470,840✔
1713
        throw InvalidQueryError(
32✔
1714
            util::format("Ordered comparison between two primitive lists is not implemented yet ('%1' and '%2')",
32✔
1715
                         left->description(state), right->description(state)));
32✔
1716
    }
32✔
1717
    if (dynamic_cast<Value<TypeOfValue>*>(left) && dynamic_cast<Value<TypeOfValue>*>(right)) {
470,808✔
1718
        throw InvalidQueryError(util::format("Comparison between two constants is not supported ('%1' and '%2')",
8✔
1719
                                             left->description(state), right->description(state)));
8✔
1720
    }
8✔
1721
    if (auto link_column = dynamic_cast<Columns<Link>*>(left)) {
470,800✔
1722
        if (link_column->has_multiple_values() && right->has_single_value() && right->get_mixed().is_null()) {
408✔
1723
            throw InvalidQueryError(
20✔
1724
                util::format("Cannot compare linklist ('%1') with NULL", left->description(state)));
20✔
1725
        }
20✔
1726
    }
408✔
1727
}
470,800✔
1728

1729
ParserDriver::ParserDriver(TableRef t, Arguments& args, const query_parser::KeyPathMapping& mapping)
1730
    : m_base_table(t)
1731
    , m_args(args)
1732
    , m_mapping(mapping)
1733
{
42,638✔
1734
    yylex_init(&m_yyscanner);
42,638✔
1735
}
42,638✔
1736

1737
ParserDriver::~ParserDriver()
1738
{
42,638✔
1739
    yylex_destroy(m_yyscanner);
42,638✔
1740
}
42,638✔
1741

1742
PathElement ParserDriver::get_arg_for_index(const std::string& i)
1743
{
4✔
1744
    REALM_ASSERT(i[0] == '$');
4✔
1745
    size_t arg_no = size_t(strtol(i.substr(1).c_str(), nullptr, 10));
4✔
1746
    if (m_args.is_argument_null(arg_no) || m_args.is_argument_list(arg_no)) {
4✔
UNCOV
1747
        throw InvalidQueryError("Invalid index parameter");
×
UNCOV
1748
    }
×
1749
    auto type = m_args.type_for_argument(arg_no);
4✔
1750
    switch (type) {
4✔
UNCOV
1751
        case type_Int:
✔
UNCOV
1752
            return size_t(m_args.long_for_argument(arg_no));
×
1753
        case type_String:
4✔
1754
            return m_args.string_for_argument(arg_no);
4✔
UNCOV
1755
        default:
✔
UNCOV
1756
            throw InvalidQueryError("Invalid index type");
×
1757
    }
4✔
1758
}
4✔
1759

1760
double ParserDriver::get_arg_for_coordinate(const std::string& str)
1761
{
80✔
1762
    REALM_ASSERT(str[0] == '$');
80✔
1763
    size_t arg_no = size_t(strtol(str.substr(1).c_str(), nullptr, 10));
80✔
1764
    if (m_args.is_argument_null(arg_no)) {
80✔
1765
        throw InvalidQueryError(util::format("NULL cannot be used in coordinate at argument '%1'", str));
4✔
1766
    }
4✔
1767
    if (m_args.is_argument_list(arg_no)) {
76✔
UNCOV
1768
        throw InvalidQueryError(util::format("A list cannot be used in a coordinate at argument '%1'", str));
×
UNCOV
1769
    }
×
1770

38✔
1771
    auto type = m_args.type_for_argument(arg_no);
76✔
1772
    switch (type) {
76✔
UNCOV
1773
        case type_Int:
✔
UNCOV
1774
            return double(m_args.long_for_argument(arg_no));
×
1775
        case type_Double:
68✔
1776
            return m_args.double_for_argument(arg_no);
68✔
UNCOV
1777
        case type_Float:
✔
UNCOV
1778
            return double(m_args.float_for_argument(arg_no));
×
1779
        default:
8✔
1780
            throw InvalidQueryError(util::format("Invalid parameter '%1' used in coordinate at argument '%2'",
8✔
1781
                                                 get_data_type_name(type), str));
8✔
1782
    }
76✔
1783
}
76✔
1784

1785
auto ParserDriver::cmp(const std::vector<ExpressionNode*>& values) -> std::pair<SubexprPtr, SubexprPtr>
1786
{
471,614✔
1787
    SubexprPtr left;
471,614✔
1788
    SubexprPtr right;
471,614✔
1789

235,806✔
1790
    auto left_is_constant = values[0]->is_constant();
471,614✔
1791
    auto right_is_constant = values[1]->is_constant();
471,614✔
1792

235,806✔
1793
    if (left_is_constant && right_is_constant) {
471,614✔
UNCOV
1794
        throw InvalidQueryError("Cannot compare two constants");
×
UNCOV
1795
    }
×
1796

235,806✔
1797
    if (right_is_constant) {
471,614✔
1798
        // Take left first - it cannot be a constant
233,822✔
1799
        left = values[0]->visit(this);
467,660✔
1800
        right = values[1]->visit(this, left->get_type());
467,660✔
1801
        verify_conditions(left.get(), right.get(), m_serializer_state);
467,660✔
1802
    }
467,660✔
1803
    else {
3,954✔
1804
        right = values[1]->visit(this);
3,954✔
1805
        if (left_is_constant) {
3,954✔
1806
            left = values[0]->visit(this, right->get_type());
1,408✔
1807
        }
1,408✔
1808
        else {
2,546✔
1809
            left = values[0]->visit(this);
2,546✔
1810
        }
2,546✔
1811
        verify_conditions(right.get(), left.get(), m_serializer_state);
3,954✔
1812
    }
3,954✔
1813
    return {std::move(left), std::move(right)};
471,614✔
1814
}
471,614✔
1815

1816
auto ParserDriver::column(LinkChain& link_chain, PathNode* path) -> SubexprPtr
1817
{
474,160✔
1818
    if (path->at_end()) {
474,160✔
1819
        // This is a link property. However Columns<Link> does not handle @keys and indexes
854✔
1820
        auto extended_col_key = link_chain.m_link_cols.back();
1,708✔
1821
        if (!extended_col_key.has_index()) {
1,708✔
1822
            return link_chain.create_subexpr<Link>(ColKey(extended_col_key));
1,704✔
1823
        }
1,704✔
1824
        link_chain.pop_back();
4✔
1825
        --path->current_path_elem;
4✔
1826
        --path->current_path_elem;
4✔
1827
    }
4✔
1828
    auto identifier = m_mapping.translate(link_chain, path->next_identifier());
473,308✔
1829
    if (auto col = link_chain.column(identifier)) {
472,456✔
1830
        return col;
472,302✔
1831
    }
472,302✔
1832
    throw InvalidQueryError(
154✔
1833
        util::format("'%1' has no property '%2'", link_chain.get_current_table()->get_class_name(), identifier));
154✔
1834
}
154✔
1835

1836
void ParserDriver::backlink(LinkChain& link_chain, std::string_view raw_table_name, std::string_view raw_column_name)
1837
{
504✔
1838
    std::string table_name = m_mapping.translate_table_name(raw_table_name);
504✔
1839
    auto origin_table = m_base_table->get_parent_group()->get_table(table_name);
504✔
1840
    ColKey origin_column;
504✔
1841
    std::string column_name{raw_column_name};
504✔
1842
    if (origin_table) {
504✔
1843
        column_name = m_mapping.translate(origin_table, column_name);
496✔
1844
        origin_column = origin_table->get_column_key(column_name);
496✔
1845
    }
496✔
1846
    if (!origin_column) {
504✔
1847
        auto origin_table_name = Group::table_name_to_class_name(table_name);
12✔
1848
        auto current_table_name = link_chain.get_current_table()->get_class_name();
12✔
1849
        throw InvalidQueryError(util::format("No property '%1' found in type '%2' which links to type '%3'",
12✔
1850
                                             column_name, origin_table_name, current_table_name));
12✔
1851
    }
12✔
1852
    link_chain.backlink(*origin_table, origin_column);
492✔
1853
}
492✔
1854

1855
std::string ParserDriver::translate(const LinkChain& link_chain, const std::string& identifier)
1856
{
492,632✔
1857
    return m_mapping.translate(link_chain, identifier);
492,632✔
1858
}
492,632✔
1859

1860
int ParserDriver::parse(const std::string& str)
1861
{
42,632✔
1862
    // std::cout << str << std::endl;
21,314✔
1863
    parse_buffer.append(str);
42,632✔
1864
    parse_buffer.append("\0\0", 2); // Flex requires 2 terminating zeroes
42,632✔
1865
    scan_begin(m_yyscanner, trace_scanning);
42,632✔
1866
    yy::parser parse(*this, m_yyscanner);
42,632✔
1867
    parse.set_debug_level(trace_parsing);
42,632✔
1868
    int res = parse();
42,632✔
1869
    if (parse_error) {
42,632✔
1870
        throw SyntaxError(util::format("Invalid predicate: '%1': %2", str, error_string));
716✔
1871
    }
716✔
1872
    return res;
41,916✔
1873
}
41,916✔
1874

1875
void parse(const std::string& str)
1876
{
1,004✔
1877
    ParserDriver driver;
1,004✔
1878
    driver.parse(str);
1,004✔
1879
}
1,004✔
1880

1881
std::string check_escapes(const char* str)
1882
{
493,658✔
1883
    std::string ret;
493,658✔
1884
    const char* p = strchr(str, '\\');
493,658✔
1885
    while (p) {
494,082✔
1886
        ret += std::string(str, p);
424✔
1887
        p++;
424✔
1888
        if (*p == ' ') {
424✔
1889
            ret += ' ';
144✔
1890
        }
144✔
1891
        else if (*p == 't') {
280✔
1892
            ret += '\t';
280✔
1893
        }
280✔
UNCOV
1894
        else if (*p == 'r') {
×
UNCOV
1895
            ret += '\r';
×
UNCOV
1896
        }
×
UNCOV
1897
        else if (*p == 'n') {
×
UNCOV
1898
            ret += '\n';
×
UNCOV
1899
        }
×
1900
        str = p + 1;
424✔
1901
        p = strchr(str, '\\');
424✔
1902
    }
424✔
1903
    return ret + std::string(str);
493,658✔
1904
}
493,658✔
1905

1906
} // namespace query_parser
1907

1908
Query Table::query(const std::string& query_string, const std::vector<MixedArguments::Arg>& arguments) const
1909
{
11,346✔
1910
    MixedArguments args(arguments);
11,346✔
1911
    return query(query_string, args, {});
11,346✔
1912
}
11,346✔
1913

1914
Query Table::query(const std::string& query_string, const std::vector<Mixed>& arguments) const
1915
{
4✔
1916
    MixedArguments args(arguments);
4✔
1917
    return query(query_string, args, {});
4✔
1918
}
4✔
1919

1920
Query Table::query(const std::string& query_string, const std::vector<Mixed>& arguments,
1921
                   const query_parser::KeyPathMapping& mapping) const
1922
{
1,688✔
1923
    MixedArguments args(arguments);
1,688✔
1924
    return query(query_string, args, mapping);
1,688✔
1925
}
1,688✔
1926

1927
Query Table::query(const std::string& query_string, const std::vector<MixedArguments::Arg>& arguments,
1928
                   const query_parser::KeyPathMapping& mapping) const
1929
{
320✔
1930
    MixedArguments args(arguments);
320✔
1931
    return query(query_string, args, mapping);
320✔
1932
}
320✔
1933

1934
Query Table::query(const std::string& query_string, query_parser::Arguments& args,
1935
                   const query_parser::KeyPathMapping& mapping) const
1936
{
41,612✔
1937
    ParserDriver driver(m_own_ref, args, mapping);
41,612✔
1938
    driver.parse(query_string);
41,612✔
1939
    driver.result->canonicalize();
41,612✔
1940
    return driver.result->visit(&driver).set_ordering(driver.ordering->visit(&driver));
41,612✔
1941
}
41,612✔
1942

1943
std::unique_ptr<Subexpr> LinkChain::column(const std::string& col)
1944
{
474,146✔
1945
    auto col_key = m_current_table->get_column_key(col);
474,146✔
1946
    if (!col_key) {
474,146✔
1947
        return nullptr;
124✔
1948
    }
124✔
1949
    size_t list_count = 0;
474,022✔
1950
    for (ColKey link_key : m_link_cols) {
244,082✔
1951
        if (link_key.get_type() == col_type_LinkList || link_key.get_type() == col_type_BackLink) {
14,160✔
1952
            list_count++;
2,112✔
1953
        }
2,112✔
1954
    }
14,160✔
1955

237,002✔
1956
    auto col_type{col_key.get_type()};
474,022✔
1957
    if (col_key.is_dictionary()) {
474,022✔
1958
        return create_subexpr<Dictionary>(col_key);
952✔
1959
    }
952✔
1960
    if (Table::is_link_type(col_type)) {
473,070✔
UNCOV
1961
        add(col_key);
×
1962
        return create_subexpr<Link>(col_key);
×
1963
    }
×
1964

236,526✔
1965
    if (col_key.is_set()) {
473,070✔
1966
        switch (col_type) {
3,984✔
1967
            case col_type_Int:
416✔
1968
                return create_subexpr<Set<Int>>(col_key);
416✔
UNCOV
1969
            case col_type_Bool:
✔
UNCOV
1970
                return create_subexpr<Set<Bool>>(col_key);
×
1971
            case col_type_String:
512✔
1972
                return create_subexpr<Set<String>>(col_key);
512✔
1973
            case col_type_Binary:
512✔
1974
                return create_subexpr<Set<Binary>>(col_key);
512✔
1975
            case col_type_Float:
416✔
1976
                return create_subexpr<Set<Float>>(col_key);
416✔
1977
            case col_type_Double:
416✔
1978
                return create_subexpr<Set<Double>>(col_key);
416✔
1979
            case col_type_Timestamp:
248✔
1980
                return create_subexpr<Set<Timestamp>>(col_key);
248✔
1981
            case col_type_Decimal:
416✔
1982
                return create_subexpr<Set<Decimal>>(col_key);
416✔
1983
            case col_type_UUID:
248✔
1984
                return create_subexpr<Set<UUID>>(col_key);
248✔
1985
            case col_type_ObjectId:
248✔
1986
                return create_subexpr<Set<ObjectId>>(col_key);
248✔
1987
            case col_type_Mixed:
552✔
1988
                return create_subexpr<Set<Mixed>>(col_key);
552✔
UNCOV
1989
            default:
✔
1990
                break;
×
1991
        }
469,086✔
1992
    }
469,086✔
1993
    else if (col_key.is_list()) {
469,086✔
1994
        switch (col_type) {
14,712✔
1995
            case col_type_Int:
3,040✔
1996
                return create_subexpr<Lst<Int>>(col_key);
3,040✔
1997
            case col_type_Bool:
880✔
1998
                return create_subexpr<Lst<Bool>>(col_key);
880✔
1999
            case col_type_String:
3,276✔
2000
                return create_subexpr<Lst<String>>(col_key);
3,276✔
2001
            case col_type_Binary:
1,660✔
2002
                return create_subexpr<Lst<Binary>>(col_key);
1,660✔
2003
            case col_type_Float:
880✔
2004
                return create_subexpr<Lst<Float>>(col_key);
880✔
2005
            case col_type_Double:
880✔
2006
                return create_subexpr<Lst<Double>>(col_key);
880✔
2007
            case col_type_Timestamp:
880✔
2008
                return create_subexpr<Lst<Timestamp>>(col_key);
880✔
2009
            case col_type_Decimal:
880✔
2010
                return create_subexpr<Lst<Decimal>>(col_key);
880✔
2011
            case col_type_UUID:
880✔
2012
                return create_subexpr<Lst<UUID>>(col_key);
880✔
2013
            case col_type_ObjectId:
880✔
2014
                return create_subexpr<Lst<ObjectId>>(col_key);
880✔
2015
            case col_type_Mixed:
576✔
2016
                return create_subexpr<Lst<Mixed>>(col_key);
576✔
UNCOV
2017
            default:
✔
UNCOV
2018
                break;
×
2019
        }
454,374✔
2020
    }
454,374✔
2021
    else {
454,374✔
2022
        if (m_comparison_type && list_count == 0) {
454,374✔
2023
            throw InvalidQueryError(util::format("The keypath following '%1' must contain a list",
44✔
2024
                                                 expression_cmp_type_to_str(m_comparison_type)));
44✔
2025
        }
44✔
2026

227,156✔
2027
        switch (col_type) {
454,330✔
2028
            case col_type_Int:
12,910✔
2029
                return create_subexpr<Int>(col_key);
12,910✔
2030
            case col_type_Bool:
224✔
2031
                return create_subexpr<Bool>(col_key);
224✔
2032
            case col_type_String:
4,440✔
2033
                return create_subexpr<String>(col_key);
4,440✔
2034
            case col_type_Binary:
2,052✔
2035
                return create_subexpr<Binary>(col_key);
2,052✔
2036
            case col_type_Float:
552✔
2037
                return create_subexpr<Float>(col_key);
552✔
2038
            case col_type_Double:
1,944✔
2039
                return create_subexpr<Double>(col_key);
1,944✔
2040
            case col_type_Timestamp:
728✔
2041
                return create_subexpr<Timestamp>(col_key);
728✔
2042
            case col_type_Decimal:
1,068✔
2043
                return create_subexpr<Decimal>(col_key);
1,068✔
2044
            case col_type_UUID:
520✔
2045
                return create_subexpr<UUID>(col_key);
520✔
2046
            case col_type_ObjectId:
428,804✔
2047
                return create_subexpr<ObjectId>(col_key);
428,804✔
2048
            case col_type_Mixed:
1,092✔
2049
                return create_subexpr<Mixed>(col_key);
1,092✔
UNCOV
2050
            default:
✔
UNCOV
2051
                break;
×
UNCOV
2052
        }
×
UNCOV
2053
    }
×
UNCOV
2054
    REALM_UNREACHABLE();
×
UNCOV
2055
    return nullptr;
×
UNCOV
2056
}
×
2057

2058
std::unique_ptr<Subexpr> LinkChain::subquery(Query subquery)
2059
{
280✔
2060
    REALM_ASSERT(m_link_cols.size() > 0);
280✔
2061
    auto col_key = m_link_cols.back();
280✔
2062
    return std::make_unique<SubQueryCount>(subquery, Columns<Link>(col_key, m_base_table, m_link_cols).link_map());
280✔
2063
}
280✔
2064

2065
template <class T>
2066
SubQuery<T> column(const Table& origin, ColKey origin_col_key, Query subquery)
2067
{
2068
    static_assert(std::is_same<T, BackLink>::value, "A subquery must involve a link list or backlink column");
2069
    return SubQuery<T>(column<T>(origin, origin_col_key), std::move(subquery));
2070
}
2071

2072
} // namespace realm
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