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

realm / realm-core / 2289

02 May 2024 09:50AM UTC coverage: 90.747% (+0.009%) from 90.738%
2289

push

Evergreen

web-flow
Also adapt argument list to target type (#7655)

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

101940 of 180246 branches covered (56.56%)

102 of 103 new or added lines in 3 files covered. (99.03%)

60 existing lines in 15 files now uncovered.

212524 of 234194 relevant lines covered (90.75%)

5682597.42 hits per line

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

87.96
/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
#include "realm/object-store/class.hpp"
28

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

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

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

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

44
namespace {
45

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

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

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

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

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

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

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

165
template <>
166
inline Decimal128 string_to<Decimal128>(const std::string& s)
167
{
4✔
168
    Decimal128 value(s);
4✔
169
    if (value.is_nan()) {
4✔
170
        throw InvalidQueryArgError(util::format("Cannot convert '%1' to a %2", s, get_type_name<Decimal128>()));
4✔
171
    }
4✔
172
    return value;
×
173
}
4✔
174

175
class MixedArguments : public query_parser::Arguments {
176
public:
177
    using Arg = mpark::variant<Mixed, std::vector<Mixed>>;
178

179
    MixedArguments(const std::vector<Mixed>& args)
180
        : Arguments(args.size())
896✔
181
        , m_args([](const std::vector<Mixed>& args) -> std::vector<Arg> {
1,792✔
182
            std::vector<Arg> ret;
1,792✔
183
            ret.reserve(args.size());
1,792✔
184
            for (const Mixed& m : args) {
15,836✔
185
                ret.push_back(m);
15,836✔
186
            }
15,836✔
187
            return ret;
1,792✔
188
        }(args))
1,792✔
189
    {
1,792✔
190
    }
1,792✔
191
    MixedArguments(const std::vector<Arg>& args)
192
        : Arguments(args.size())
6,042✔
193
        , m_args(args)
6,042✔
194
    {
12,084✔
195
    }
12,084✔
196
    bool bool_for_argument(size_t n) final
197
    {
×
198
        return mixed_for_argument(n).get<bool>();
×
199
    }
×
200
    long long long_for_argument(size_t n) final
201
    {
×
202
        return mixed_for_argument(n).get<int64_t>();
×
203
    }
×
204
    float float_for_argument(size_t n) final
205
    {
×
206
        return mixed_for_argument(n).get<float>();
×
207
    }
×
208
    double double_for_argument(size_t n) final
209
    {
68✔
210
        return mixed_for_argument(n).get<double>();
68✔
211
    }
68✔
212
    StringData string_for_argument(size_t n) final
213
    {
20✔
214
        return mixed_for_argument(n).get<StringData>();
20✔
215
    }
20✔
216
    BinaryData binary_for_argument(size_t n) final
217
    {
×
218
        return mixed_for_argument(n).get<BinaryData>();
×
219
    }
×
220
    Timestamp timestamp_for_argument(size_t n) final
221
    {
×
222
        return mixed_for_argument(n).get<Timestamp>();
×
223
    }
×
224
    ObjectId objectid_for_argument(size_t n) final
225
    {
×
226
        return mixed_for_argument(n).get<ObjectId>();
×
227
    }
×
228
    UUID uuid_for_argument(size_t n) final
229
    {
×
230
        return mixed_for_argument(n).get<UUID>();
×
231
    }
×
232
    Decimal128 decimal128_for_argument(size_t n) final
233
    {
×
234
        return mixed_for_argument(n).get<Decimal128>();
×
235
    }
×
236
    ObjKey object_index_for_argument(size_t n) final
237
    {
×
238
        return mixed_for_argument(n).get<ObjKey>();
×
239
    }
×
240
    ObjLink objlink_for_argument(size_t n) final
241
    {
×
242
        return mixed_for_argument(n).get<ObjLink>();
×
243
    }
×
244
#if REALM_ENABLE_GEOSPATIAL
245
    Geospatial geospatial_for_argument(size_t n) final
246
    {
16✔
247
        return mixed_for_argument(n).get<Geospatial>();
16✔
248
    }
16✔
249
#endif
250
    std::vector<Mixed> list_for_argument(size_t n) final
251
    {
116✔
252
        Arguments::verify_ndx(n);
116✔
253
        return mpark::get<std::vector<Mixed>>(m_args[n]);
116✔
254
    }
116✔
255
    bool is_argument_null(size_t n) final
256
    {
428,872✔
257
        Arguments::verify_ndx(n);
428,872✔
258
        return visit(util::overload{
428,872✔
259
                         [](const Mixed& m) {
428,872✔
260
                             return m.is_null();
428,872✔
261
                         },
428,872✔
262
                         [](const std::vector<Mixed>&) {
428,872✔
263
                             return false;
×
264
                         },
×
265
                     },
428,872✔
266
                     m_args[n]);
428,872✔
267
    }
428,872✔
268
    bool is_argument_list(size_t n) final
269
    {
857,872✔
270
        Arguments::verify_ndx(n);
857,872✔
271
        static_assert(std::is_same_v<mpark::variant_alternative_t<1, Arg>, std::vector<Mixed>>);
857,872✔
272
        return m_args[n].index() == 1;
857,872✔
273
    }
857,872✔
274
    DataType type_for_argument(size_t n) final
275
    {
120✔
276
        return mixed_for_argument(n).get_type();
120✔
277
    }
120✔
278

279
    Mixed mixed_for_argument(size_t n) final
280
    {
428,924✔
281
        Arguments::verify_ndx(n);
428,924✔
282
        if (is_argument_list(n)) {
428,924✔
283
            throw InvalidQueryArgError(
×
284
                util::format("Request for scalar argument at index %1 but a list was provided", n));
×
285
        }
×
286

287
        return mpark::get<Mixed>(m_args[n]);
428,924✔
288
    }
428,924✔
289

290
private:
291
    const std::vector<Arg> m_args;
292
};
293

294
Timestamp get_timestamp_if_valid(int64_t seconds, int32_t nanoseconds)
295
{
596✔
296
    const bool both_non_negative = seconds >= 0 && nanoseconds >= 0;
596✔
297
    const bool both_non_positive = seconds <= 0 && nanoseconds <= 0;
596✔
298
    if (both_non_negative || both_non_positive) {
596✔
299
        return Timestamp(seconds, nanoseconds);
580✔
300
    }
580✔
301
    throw SyntaxError("Invalid timestamp format");
16✔
302
}
596✔
303

304
} // namespace
305

306
namespace realm {
307

308
namespace query_parser {
309

310
std::string_view string_for_op(CompareType op)
311
{
3,052✔
312
    switch (op) {
3,052✔
313
        case CompareType::EQUAL:
164✔
314
            return "=";
164✔
315
        case CompareType::NOT_EQUAL:
40✔
316
            return "!=";
40✔
317
        case CompareType::GREATER:
✔
318
            return ">";
×
319
        case CompareType::LESS:
✔
320
            return "<";
×
321
        case CompareType::GREATER_EQUAL:
✔
322
            return ">=";
×
323
        case CompareType::LESS_EQUAL:
✔
324
            return "<=";
×
325
        case CompareType::BEGINSWITH:
632✔
326
            return "beginswith";
632✔
327
        case CompareType::ENDSWITH:
616✔
328
            return "endswith";
616✔
329
        case CompareType::CONTAINS:
968✔
330
            return "contains";
968✔
331
        case CompareType::LIKE:
584✔
332
            return "like";
584✔
333
        case CompareType::IN:
8✔
334
            return "in";
8✔
335
        case CompareType::TEXT:
40✔
336
            return "text";
40✔
337
    }
3,052✔
338
    return ""; // appease MSVC warnings
×
339
}
3,052✔
340

341
NoArguments ParserDriver::s_default_args;
342
query_parser::KeyPathMapping ParserDriver::s_default_mapping;
343

344
ParserNode::~ParserNode() = default;
2,407,946✔
345

346
QueryNode::~QueryNode() = default;
910,094✔
347

348
Query NotNode::visit(ParserDriver* drv)
349
{
1,232✔
350
    Query q = drv->m_base_table->where();
1,232✔
351
    q.Not();
1,232✔
352
    q.and_query(query->visit(drv));
1,232✔
353
    return {q};
1,232✔
354
}
1,232✔
355

356
Query OrNode::visit(ParserDriver* drv)
357
{
584✔
358
    Query q(drv->m_base_table);
584✔
359
    q.group();
584✔
360
    for (auto it : children) {
430,936✔
361
        q.Or();
430,936✔
362
        q.and_query(it->visit(drv));
430,936✔
363
    }
430,936✔
364
    q.end_group();
584✔
365

366
    return q;
584✔
367
}
584✔
368

369
Query AndNode::visit(ParserDriver* drv)
370
{
708✔
371
    Query q(drv->m_base_table);
708✔
372
    for (auto it : children) {
1,592✔
373
        q.and_query(it->visit(drv));
1,592✔
374
    }
1,592✔
375
    return q;
708✔
376
}
708✔
377

378
static void verify_only_string_types(DataType type, std::string_view op_string)
379
{
3,052✔
380
    if (type != type_String && type != type_Binary && type != type_Mixed) {
3,052✔
381
        throw InvalidQueryError(util::format(
348✔
382
            "Unsupported comparison operator '%1' against type '%2', right side must be a string or binary type",
348✔
383
            op_string, get_data_type_name(type)));
348✔
384
    }
348✔
385
}
3,052✔
386

387
std::unique_ptr<Subexpr> OperationNode::visit(ParserDriver* drv, DataType type)
388
{
1,056✔
389
    std::unique_ptr<Subexpr> left;
1,056✔
390
    std::unique_ptr<Subexpr> right;
1,056✔
391

392
    const bool left_is_constant = m_left->is_constant();
1,056✔
393
    const bool right_is_constant = m_right->is_constant();
1,056✔
394
    const bool produces_multiple_values = m_left->is_list() || m_right->is_list();
1,056✔
395

396
    if (left_is_constant && right_is_constant && !produces_multiple_values) {
1,056✔
397
        right = m_right->visit(drv, type);
48✔
398
        left = m_left->visit(drv, type);
48✔
399
        auto v_left = left->get_mixed();
48✔
400
        auto v_right = right->get_mixed();
48✔
401
        Mixed result;
48✔
402
        switch (m_op) {
48✔
403
            case '+':
28✔
404
                result = v_left + v_right;
28✔
405
                break;
28✔
406
            case '-':
✔
407
                result = v_left - v_right;
×
408
                break;
×
409
            case '*':
20✔
410
                result = v_left * v_right;
20✔
411
                break;
20✔
412
            case '/':
✔
413
                result = v_left / v_right;
×
414
                break;
×
415
            default:
✔
416
                break;
×
417
        }
48✔
418
        return std::make_unique<Value<Mixed>>(result);
48✔
419
    }
48✔
420

421
    if (right_is_constant) {
1,008✔
422
        // Take left first - it cannot be a constant
423
        left = m_left->visit(drv);
416✔
424

425
        right = m_right->visit(drv, left->get_type());
416✔
426
    }
416✔
427
    else {
592✔
428
        right = m_right->visit(drv);
592✔
429
        if (left_is_constant) {
592✔
430
            left = m_left->visit(drv, right->get_type());
152✔
431
        }
152✔
432
        else {
440✔
433
            left = m_left->visit(drv);
440✔
434
        }
440✔
435
    }
592✔
436
    if (!Mixed::is_numeric(left->get_type(), right->get_type())) {
1,008✔
437
        util::serializer::SerialisationState state;
16✔
438
        std::string op(&m_op, 1);
16✔
439
        throw InvalidQueryArgError(util::format("Cannot perform '%1' operation on '%2' and '%3'", op,
16✔
440
                                                left->description(state), right->description(state)));
16✔
441
    }
16✔
442

443
    switch (m_op) {
992✔
444
        case '+':
400✔
445
            return std::make_unique<Operator<Plus>>(std::move(left), std::move(right));
400✔
446
        case '-':
136✔
447
            return std::make_unique<Operator<Minus>>(std::move(left), std::move(right));
136✔
448
        case '*':
260✔
449
            return std::make_unique<Operator<Mul>>(std::move(left), std::move(right));
260✔
450
        case '/':
196✔
451
            return std::make_unique<Operator<Div>>(std::move(left), std::move(right));
196✔
452
        default:
✔
453
            break;
×
454
    }
992✔
455
    return {};
×
456
}
992✔
457

458
Query EqualityNode::visit(ParserDriver* drv)
459
{
467,450✔
460
    auto [left, right] = drv->cmp(values);
467,450✔
461

462
    auto left_type = left->get_type();
467,450✔
463
    auto right_type = right->get_type();
467,450✔
464

465
    auto handle_typed_links = [drv](std::unique_ptr<Subexpr>& list, std::unique_ptr<Subexpr>& expr, DataType& type) {
467,450✔
466
        if (auto link_column = dynamic_cast<const Columns<Link>*>(list.get())) {
400✔
467
            // Change all TypedLink values to ObjKey values
468
            auto value = dynamic_cast<ValueBase*>(expr.get());
400✔
469
            auto left_dest_table_key = link_column->link_map().get_target_table()->get_key();
400✔
470
            auto sz = value->size();
400✔
471
            auto obj_keys = std::make_unique<Value<ObjKey>>();
400✔
472
            obj_keys->init(expr->has_multiple_values(), sz);
400✔
473
            obj_keys->set_comparison_type(expr->get_comparison_type());
400✔
474
            for (size_t i = 0; i < sz; i++) {
808✔
475
                auto val = value->get(i);
416✔
476
                // i'th entry is already NULL
477
                if (!val.is_null()) {
416✔
478
                    TableKey right_table_key;
200✔
479
                    ObjKey right_obj_key;
200✔
480
                    if (val.is_type(type_Link)) {
200✔
481
                        right_table_key = left_dest_table_key;
20✔
482
                        right_obj_key = val.get<ObjKey>();
20✔
483
                    }
20✔
484
                    else if (val.is_type(type_TypedLink)) {
180✔
485
                        right_table_key = val.get_link().get_table_key();
180✔
486
                        right_obj_key = val.get_link().get_obj_key();
180✔
487
                    }
180✔
488
                    else {
×
489
                        const char* target_type = get_data_type_name(val.get_type());
×
490
                        throw InvalidQueryError(
×
491
                            util::format("Unsupported comparison between '%1' and type '%2'",
×
492
                                         link_column->link_map().description(drv->m_serializer_state), target_type));
×
493
                    }
×
494
                    if (left_dest_table_key == right_table_key) {
200✔
495
                        obj_keys->set(i, right_obj_key);
192✔
496
                    }
192✔
497
                    else {
8✔
498
                        const Group* g = drv->m_base_table->get_parent_group();
8✔
499
                        throw InvalidQueryArgError(
8✔
500
                            util::format("The relationship '%1' which links to type '%2' cannot be compared to "
8✔
501
                                         "an argument of type %3",
8✔
502
                                         link_column->link_map().description(drv->m_serializer_state),
8✔
503
                                         link_column->link_map().get_target_table()->get_class_name(),
8✔
504
                                         print_pretty_objlink(ObjLink(right_table_key, right_obj_key), g)));
8✔
505
                    }
8✔
506
                }
200✔
507
            }
416✔
508
            expr = std::move(obj_keys);
392✔
509
            type = type_Link;
392✔
510
        }
392✔
511
    };
400✔
512

513
    if (left_type == type_Link && right->has_constant_evaluation()) {
467,450✔
514
        handle_typed_links(left, right, right_type);
388✔
515
    }
388✔
516
    if (right_type == type_Link && left->has_constant_evaluation()) {
467,450✔
517
        handle_typed_links(right, left, left_type);
12✔
518
    }
12✔
519

520
    if (left_type.is_valid() && right_type.is_valid() && !Mixed::data_types_are_comparable(left_type, right_type)) {
467,450✔
521
        throw InvalidQueryError(util::format("Unsupported comparison between type '%1' and type '%2'",
16✔
522
                                             get_data_type_name(left_type), get_data_type_name(right_type)));
16✔
523
    }
16✔
524
    if (left_type == type_TypeOfValue || right_type == type_TypeOfValue) {
467,434✔
525
        if (left_type != right_type) {
572✔
526
            throw InvalidQueryArgError(
12✔
527
                util::format("Unsupported comparison between @type and raw value: '%1' and '%2'",
12✔
528
                             get_data_type_name(left_type), get_data_type_name(right_type)));
12✔
529
        }
12✔
530
    }
572✔
531

532
    if (op == CompareType::IN) {
467,422✔
533
        Subexpr* r = right.get();
840✔
534
        if (!r->has_multiple_values()) {
840✔
535
            throw InvalidQueryArgError("The keypath following 'IN' must contain a list. Found '" +
8✔
536
                                       r->description(drv->m_serializer_state) + "'");
8✔
537
        }
8✔
538
    }
840✔
539

540
    if (op == CompareType::IN || op == CompareType::EQUAL) {
467,414✔
541
        if (auto mixed_list = dynamic_cast<ConstantMixedList*>(right.get());
462,918✔
542
            mixed_list && mixed_list->size() &&
462,918✔
543
            mixed_list->get_comparison_type().value_or(ExpressionComparisonType::Any) ==
462,918✔
544
                ExpressionComparisonType::Any) {
920✔
545
            if (auto lhs = dynamic_cast<ObjPropertyBase*>(left.get());
608✔
546
                lhs && lhs->column_key() && !lhs->column_key().is_collection() && !lhs->links_exist() &&
608✔
547
                lhs->column_key().get_type() != col_type_Mixed) {
608✔
548
                return drv->m_base_table->where().in(lhs->column_key(), mixed_list->begin(), mixed_list->end());
336✔
549
            }
336✔
550
        }
608✔
551
    }
462,918✔
552

553
    if (left_type == type_Link && left_type == right_type && right->has_constant_evaluation()) {
467,078✔
554
        if (auto link_column = dynamic_cast<const Columns<Link>*>(left.get())) {
380✔
555
            if (link_column->link_map().get_nb_hops() == 1 &&
380✔
556
                link_column->get_comparison_type().value_or(ExpressionComparisonType::Any) ==
380✔
557
                    ExpressionComparisonType::Any) {
324✔
558
                REALM_ASSERT(dynamic_cast<const Value<ObjKey>*>(right.get()));
308✔
559
                auto link_values = static_cast<const Value<ObjKey>*>(right.get());
308✔
560
                // We can use a LinksToNode based query
561
                std::vector<ObjKey> values;
308✔
562
                values.reserve(link_values->size());
308✔
563
                for (auto val : *link_values) {
324✔
564
                    values.emplace_back(val.is_null() ? ObjKey() : val.get<ObjKey>());
324✔
565
                }
324✔
566
                if (op == CompareType::EQUAL) {
308✔
567
                    return drv->m_base_table->where().links_to(link_column->link_map().get_first_column_key(),
200✔
568
                                                               values);
200✔
569
                }
200✔
570
                else if (op == CompareType::NOT_EQUAL) {
108✔
571
                    return drv->m_base_table->where().not_links_to(link_column->link_map().get_first_column_key(),
104✔
572
                                                                   values);
104✔
573
                }
104✔
574
            }
308✔
575
        }
380✔
576
    }
380✔
577
    else if (right->has_single_value() && (left_type == right_type || left_type == type_Mixed)) {
466,698✔
578
        Mixed val = right->get_mixed();
459,216✔
579
        const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
459,216✔
580
        if (prop && !prop->links_exist() && !prop->has_path()) {
459,216✔
581
            auto col_key = prop->column_key();
444,098✔
582
            if (val.is_null()) {
444,098✔
583
                switch (op) {
212✔
584
                    case CompareType::EQUAL:
156✔
585
                    case CompareType::IN:
156✔
586
                        return drv->m_base_table->where().equal(col_key, realm::null());
156✔
587
                    case CompareType::NOT_EQUAL:
56✔
588
                        return drv->m_base_table->where().not_equal(col_key, realm::null());
56✔
589
                    default:
✔
590
                        break;
×
591
                }
212✔
592
            }
212✔
593
            switch (left->get_type()) {
443,886✔
594
                case type_Int:
10,036✔
595
                    return drv->simple_query(op, col_key, val.get_int());
10,036✔
596
                case type_Bool:
132✔
597
                    return drv->simple_query(op, col_key, val.get_bool());
132✔
598
                case type_String:
2,592✔
599
                    return drv->simple_query(op, col_key, val.get_string(), case_sensitive);
2,592✔
600
                case type_Binary:
1,416✔
601
                    return drv->simple_query(op, col_key, val.get_binary(), case_sensitive);
1,416✔
602
                case type_Timestamp:
140✔
603
                    return drv->simple_query(op, col_key, val.get<Timestamp>());
140✔
604
                case type_Float:
52✔
605
                    return drv->simple_query(op, col_key, val.get_float());
52✔
606
                case type_Double:
100✔
607
                    return drv->simple_query(op, col_key, val.get_double());
100✔
608
                case type_Decimal:
752✔
609
                    return drv->simple_query(op, col_key, val.get<Decimal128>());
752✔
610
                case type_ObjectId:
428,384✔
611
                    return drv->simple_query(op, col_key, val.get<ObjectId>());
428,384✔
612
                case type_UUID:
164✔
613
                    return drv->simple_query(op, col_key, val.get<UUID>());
164✔
614
                case type_Mixed:
120✔
615
                    return drv->simple_query(op, col_key, val, case_sensitive);
120✔
616
                default:
✔
617
                    break;
×
618
            }
443,886✔
619
        }
443,886✔
620
    }
459,216✔
621
    if (case_sensitive) {
22,676✔
622
        switch (op) {
21,852✔
623
            case CompareType::EQUAL:
17,816✔
624
            case CompareType::IN:
18,380✔
625
                return Query(std::unique_ptr<Expression>(new Compare<Equal>(std::move(left), std::move(right))));
18,380✔
626
            case CompareType::NOT_EQUAL:
3,472✔
627
                return Query(std::unique_ptr<Expression>(new Compare<NotEqual>(std::move(left), std::move(right))));
3,472✔
628
            default:
✔
629
                break;
×
630
        }
21,852✔
631
    }
21,852✔
632
    else {
824✔
633
        verify_only_string_types(right_type, util::format("%1%2", string_for_op(op), "[c]"));
824✔
634
        switch (op) {
824✔
635
            case CompareType::EQUAL:
104✔
636
            case CompareType::IN:
112✔
637
                return Query(std::unique_ptr<Expression>(new Compare<EqualIns>(std::move(left), std::move(right))));
112✔
638
            case CompareType::NOT_EQUAL:
40✔
639
                return Query(
40✔
640
                    std::unique_ptr<Expression>(new Compare<NotEqualIns>(std::move(left), std::move(right))));
40✔
641
            default:
✔
642
                break;
×
643
        }
824✔
644
    }
824✔
645
    return {};
×
646
}
22,676✔
647

648
Query BetweenNode::visit(ParserDriver* drv)
649
{
92✔
650
    if (limits->elements.size() != 2) {
92✔
651
        throw InvalidQueryError("Operator 'BETWEEN' requires list with 2 elements.");
8✔
652
    }
8✔
653

654
    if (dynamic_cast<ColumnListBase*>(prop->visit(drv, type_Int).get())) {
84✔
655
        // It's a list!
656
        util::Optional<ExpressionComparisonType> cmp_type = dynamic_cast<PropertyNode*>(prop)->comp_type;
16✔
657
        if (cmp_type.value_or(ExpressionComparisonType::Any) != ExpressionComparisonType::All) {
16✔
658
            throw InvalidQueryError("Only 'ALL' supported for operator 'BETWEEN' when applied to lists.");
12✔
659
        }
12✔
660
    }
16✔
661

662
    auto& min(limits->elements.at(0));
72✔
663
    auto& max(limits->elements.at(1));
72✔
664
    RelationalNode cmp1(prop, CompareType::GREATER_EQUAL, min);
72✔
665
    RelationalNode cmp2(prop, CompareType::LESS_EQUAL, max);
72✔
666

667
    Query q(drv->m_base_table);
72✔
668
    q.and_query(cmp1.visit(drv));
72✔
669
    q.and_query(cmp2.visit(drv));
72✔
670

671
    return q;
72✔
672
}
84✔
673

674
Query RelationalNode::visit(ParserDriver* drv)
675
{
5,308✔
676
    auto [left, right] = drv->cmp(values);
5,308✔
677

678
    auto left_type = left->get_type();
5,308✔
679
    auto right_type = right->get_type();
5,308✔
680
    const bool right_type_is_null = right->has_single_value() && right->get_mixed().is_null();
5,308✔
681
    const bool left_type_is_null = left->has_single_value() && left->get_mixed().is_null();
5,308✔
682
    REALM_ASSERT(!(left_type_is_null && right_type_is_null));
5,308✔
683

684
    if (left_type == type_Link || left_type == type_TypeOfValue) {
5,308✔
685
        throw InvalidQueryError(util::format(
×
686
            "Unsupported operator %1 in query. Only equal (==) and not equal (!=) are supported for this type.",
×
687
            string_for_op(op)));
×
688
    }
×
689

690
    if (!(left_type_is_null || right_type_is_null) && (!left_type.is_valid() || !right_type.is_valid() ||
5,308✔
691
                                                       !Mixed::data_types_are_comparable(left_type, right_type))) {
4,800✔
692
        throw InvalidQueryError(util::format("Unsupported comparison between type '%1' and type '%2'",
24✔
693
                                             get_data_type_name(left_type), get_data_type_name(right_type)));
24✔
694
    }
24✔
695

696
    const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
5,284✔
697
    if (prop && !prop->links_exist() && !prop->has_path() && right->has_single_value() &&
5,284✔
698
        (left_type == right_type || left_type == type_Mixed)) {
5,284✔
699
        auto col_key = prop->column_key();
1,556✔
700
        switch (left->get_type()) {
1,556✔
701
            case type_Int:
692✔
702
                return drv->simple_query(op, col_key, right->get_mixed().get_int());
692✔
703
            case type_Bool:
✔
704
                break;
×
705
            case type_String:
92✔
706
                return drv->simple_query(op, col_key, right->get_mixed().get_string());
92✔
707
            case type_Binary:
✔
708
                break;
×
709
            case type_Timestamp:
48✔
710
                return drv->simple_query(op, col_key, right->get_mixed().get<Timestamp>());
48✔
711
            case type_Float:
68✔
712
                return drv->simple_query(op, col_key, right->get_mixed().get_float());
68✔
713
                break;
×
714
            case type_Double:
144✔
715
                return drv->simple_query(op, col_key, right->get_mixed().get_double());
144✔
716
                break;
×
717
            case type_Decimal:
16✔
718
                return drv->simple_query(op, col_key, right->get_mixed().get<Decimal128>());
16✔
719
                break;
×
720
            case type_ObjectId:
288✔
721
                return drv->simple_query(op, col_key, right->get_mixed().get<ObjectId>());
288✔
722
                break;
×
723
            case type_UUID:
128✔
724
                return drv->simple_query(op, col_key, right->get_mixed().get<UUID>());
128✔
725
                break;
×
726
            case type_Mixed:
80✔
727
                return drv->simple_query(op, col_key, right->get_mixed());
80✔
728
                break;
×
729
            default:
✔
730
                break;
×
731
        }
1,556✔
732
    }
1,556✔
733
    switch (op) {
3,728✔
734
        case CompareType::GREATER:
2,316✔
735
            return Query(std::unique_ptr<Expression>(new Compare<Greater>(std::move(left), std::move(right))));
2,316✔
736
        case CompareType::LESS:
284✔
737
            return Query(std::unique_ptr<Expression>(new Compare<Less>(std::move(left), std::move(right))));
284✔
738
        case CompareType::GREATER_EQUAL:
540✔
739
            return Query(std::unique_ptr<Expression>(new Compare<GreaterEqual>(std::move(left), std::move(right))));
540✔
740
        case CompareType::LESS_EQUAL:
172✔
741
            return Query(std::unique_ptr<Expression>(new Compare<LessEqual>(std::move(left), std::move(right))));
172✔
742
        default:
✔
743
            break;
×
744
    }
3,728✔
745
    return {};
×
746
}
3,728✔
747

748
Query StringOpsNode::visit(ParserDriver* drv)
749
{
2,856✔
750
    auto [left, right] = drv->cmp(values);
2,856✔
751

752
    auto left_type = left->get_type();
2,856✔
753
    auto right_type = right->get_type();
2,856✔
754
    const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
2,856✔
755

756
    verify_only_string_types(right_type, string_for_op(op));
2,856✔
757

758
    if (prop && !prop->links_exist() && !prop->has_path() && right->has_single_value() &&
2,856✔
759
        (left_type == right_type || left_type == type_Mixed)) {
2,856✔
760
        auto col_key = prop->column_key();
548✔
761
        if (right_type == type_String) {
548✔
762
            StringData val = right->get_mixed().get_string();
332✔
763

764
            switch (op) {
332✔
765
                case CompareType::BEGINSWITH:
56✔
766
                    return drv->m_base_table->where().begins_with(col_key, val, case_sensitive);
56✔
767
                case CompareType::ENDSWITH:
64✔
768
                    return drv->m_base_table->where().ends_with(col_key, val, case_sensitive);
64✔
769
                case CompareType::CONTAINS:
120✔
770
                    return drv->m_base_table->where().contains(col_key, val, case_sensitive);
120✔
771
                case CompareType::LIKE:
56✔
772
                    return drv->m_base_table->where().like(col_key, val, case_sensitive);
56✔
773
                case CompareType::TEXT:
36✔
774
                    return drv->m_base_table->where().fulltext(col_key, val);
36✔
775
                case CompareType::IN:
✔
776
                case CompareType::EQUAL:
✔
777
                case CompareType::NOT_EQUAL:
✔
778
                case CompareType::GREATER:
✔
779
                case CompareType::LESS:
✔
780
                case CompareType::GREATER_EQUAL:
✔
781
                case CompareType::LESS_EQUAL:
✔
782
                    break;
×
783
            }
332✔
784
        }
332✔
785
        else if (right_type == type_Binary) {
216✔
786
            BinaryData val = right->get_mixed().get_binary();
216✔
787

788
            switch (op) {
216✔
789
                case CompareType::BEGINSWITH:
48✔
790
                    return drv->m_base_table->where().begins_with(col_key, val, case_sensitive);
48✔
791
                case CompareType::ENDSWITH:
56✔
792
                    return drv->m_base_table->where().ends_with(col_key, val, case_sensitive);
56✔
793
                case CompareType::CONTAINS:
72✔
794
                    return drv->m_base_table->where().contains(col_key, val, case_sensitive);
72✔
795
                case CompareType::LIKE:
40✔
796
                    return drv->m_base_table->where().like(col_key, val, case_sensitive);
40✔
797
                case CompareType::TEXT:
✔
798
                case CompareType::IN:
✔
799
                case CompareType::EQUAL:
✔
800
                case CompareType::NOT_EQUAL:
✔
801
                case CompareType::GREATER:
✔
802
                case CompareType::LESS:
✔
803
                case CompareType::GREATER_EQUAL:
✔
804
                case CompareType::LESS_EQUAL:
✔
805
                    break;
×
806
            }
216✔
807
        }
216✔
808
    }
548✔
809

810
    if (case_sensitive) {
2,308✔
811
        switch (op) {
732✔
812
            case CompareType::BEGINSWITH:
152✔
813
                return Query(std::unique_ptr<Expression>(new Compare<BeginsWith>(std::move(right), std::move(left))));
152✔
814
            case CompareType::ENDSWITH:
152✔
815
                return Query(std::unique_ptr<Expression>(new Compare<EndsWith>(std::move(right), std::move(left))));
152✔
816
            case CompareType::CONTAINS:
272✔
817
                return Query(std::unique_ptr<Expression>(new Compare<Contains>(std::move(right), std::move(left))));
272✔
818
            case CompareType::LIKE:
152✔
819
                return Query(std::unique_ptr<Expression>(new Compare<Like>(std::move(right), std::move(left))));
152✔
820
            case CompareType::TEXT: {
4✔
821
                StringData val = right->get_mixed().get_string();
4✔
822
                auto string_prop = dynamic_cast<Columns<StringData>*>(left.get());
4✔
823
                return string_prop->fulltext(val);
4✔
824
            }
×
825
            case CompareType::IN:
✔
826
            case CompareType::EQUAL:
✔
827
            case CompareType::NOT_EQUAL:
✔
828
            case CompareType::GREATER:
✔
829
            case CompareType::LESS:
✔
830
            case CompareType::GREATER_EQUAL:
✔
831
            case CompareType::LESS_EQUAL:
✔
832
                break;
×
833
        }
732✔
834
    }
732✔
835
    else {
1,576✔
836
        switch (op) {
1,576✔
837
            case CompareType::BEGINSWITH:
304✔
838
                return Query(
304✔
839
                    std::unique_ptr<Expression>(new Compare<BeginsWithIns>(std::move(right), std::move(left))));
304✔
840
            case CompareType::ENDSWITH:
272✔
841
                return Query(
272✔
842
                    std::unique_ptr<Expression>(new Compare<EndsWithIns>(std::move(right), std::move(left))));
272✔
843
            case CompareType::CONTAINS:
432✔
844
                return Query(
432✔
845
                    std::unique_ptr<Expression>(new Compare<ContainsIns>(std::move(right), std::move(left))));
432✔
846
            case CompareType::LIKE:
264✔
847
                return Query(std::unique_ptr<Expression>(new Compare<LikeIns>(std::move(right), std::move(left))));
264✔
848
            case CompareType::IN:
✔
849
            case CompareType::EQUAL:
✔
850
            case CompareType::NOT_EQUAL:
✔
851
            case CompareType::GREATER:
✔
852
            case CompareType::LESS:
✔
853
            case CompareType::GREATER_EQUAL:
✔
854
            case CompareType::LESS_EQUAL:
✔
855
            case CompareType::TEXT:
✔
856
                break;
×
857
        }
1,576✔
858
    }
1,576✔
859
    return {};
×
860
}
2,308✔
861

862
#if REALM_ENABLE_GEOSPATIAL
863
Query GeoWithinNode::visit(ParserDriver* drv)
864
{
176✔
865
    auto left = prop->visit(drv);
176✔
866
    auto left_type = left->get_type();
176✔
867
    if (left_type != type_Link) {
176✔
868
        throw InvalidQueryError(util::format("The left hand side of 'geoWithin' must be a link to geoJSON formatted "
4✔
869
                                             "data. But the provided type is '%1'",
4✔
870
                                             get_data_type_name(left_type)));
4✔
871
    }
4✔
872
    auto link_column = dynamic_cast<const Columns<Link>*>(left.get());
172✔
873

874
    if (geo) {
172✔
875
        auto right = geo->visit(drv, type_Int);
124✔
876
        auto geo_value = dynamic_cast<const ConstantGeospatialValue*>(right.get());
124✔
877
        return link_column->geo_within(geo_value->get_mixed().get<Geospatial>());
124✔
878
    }
124✔
879

880
    REALM_ASSERT_3(argument.size(), >, 1);
48✔
881
    REALM_ASSERT_3(argument[0], ==, '$');
48✔
882
    size_t arg_no = size_t(strtol(argument.substr(1).c_str(), nullptr, 10));
48✔
883
    auto right_type = drv->m_args.is_argument_null(arg_no) ? DataType(-1) : drv->m_args.type_for_argument(arg_no);
48✔
884

885
    Geospatial geo_from_argument;
48✔
886
    if (right_type == type_Geospatial) {
48✔
887
        geo_from_argument = drv->m_args.geospatial_for_argument(arg_no);
16✔
888
    }
16✔
889
    else if (right_type == type_String) {
32✔
890
        // This is a "hack" to allow users to pass in geospatial objects
891
        // serialized as a string instead of as a native type. This is because
892
        // the CAPI doesn't have support for marshalling polygons (of variable length)
893
        // yet and that project was deprioritized to geospatial phase 2. This should be
894
        // removed once SDKs are all using the binding generator.
895
        std::string str_val = drv->m_args.string_for_argument(arg_no);
20✔
896
        const std::string simulated_prefix = "simulated GEOWITHIN ";
20✔
897
        str_val = simulated_prefix + str_val;
20✔
898
        ParserDriver sub_driver;
20✔
899
        try {
20✔
900
            sub_driver.parse(str_val);
20✔
901
        }
20✔
902
        catch (const std::exception& ex) {
20✔
903
            std::string doctored_err = ex.what();
8✔
904
            size_t prefix_location = doctored_err.find(simulated_prefix);
8✔
905
            if (prefix_location != std::string::npos) {
8✔
906
                doctored_err.erase(prefix_location, simulated_prefix.size());
8✔
907
            }
8✔
908
            throw InvalidQueryError(util::format(
8✔
909
                "Invalid syntax in serialized geospatial object at argument %1: '%2'", arg_no, doctored_err));
8✔
910
        }
8✔
911
        GeoWithinNode* node = dynamic_cast<GeoWithinNode*>(sub_driver.result);
12✔
912
        REALM_ASSERT(node);
12✔
913
        if (node->geo) {
12✔
914
            if (node->geo->m_geo.get_type() != Geospatial::Type::Invalid) {
12✔
915
                geo_from_argument = node->geo->m_geo;
4✔
916
            }
4✔
917
            else {
8✔
918
                geo_from_argument = GeoPolygon{node->geo->m_points};
8✔
919
            }
8✔
920
        }
12✔
921
    }
12✔
922
    else {
12✔
923
        throw InvalidQueryError(util::format("The right hand side of 'geoWithin' must be a geospatial constant "
12✔
924
                                             "value. But the provided type is '%1'",
12✔
925
                                             get_data_type_name(right_type)));
12✔
926
    }
12✔
927

928
    if (geo_from_argument.get_type() == Geospatial::Type::Invalid) {
28✔
929
        throw InvalidQueryError(util::format(
4✔
930
            "The right hand side of 'geoWithin' must be a valid Geospatial value, got '%1'", geo_from_argument));
4✔
931
    }
4✔
932
    Status geo_status = geo_from_argument.is_valid();
24✔
933
    if (!geo_status.is_ok()) {
24✔
934
        throw InvalidQueryError(
×
935
            util::format("The Geospatial query argument region is invalid: '%1'", geo_status.reason()));
×
936
    }
×
937
    return link_column->geo_within(geo_from_argument);
24✔
938
}
24✔
939
#endif
940

941
Query TrueOrFalseNode::visit(ParserDriver* drv)
942
{
612✔
943
    Query q = drv->m_base_table->where();
612✔
944
    if (true_or_false) {
612✔
945
        q.and_query(std::unique_ptr<realm::Expression>(new TrueExpression));
460✔
946
    }
460✔
947
    else {
152✔
948
        q.and_query(std::unique_ptr<realm::Expression>(new FalseExpression));
152✔
949
    }
152✔
950
    return q;
612✔
951
}
612✔
952

953
std::unique_ptr<Subexpr> PropertyNode::visit(ParserDriver* drv, DataType)
954
{
478,552✔
955
    path->resolve_arg(drv);
478,552✔
956
    if (path->path_elems.back().is_key() && path->path_elems.back().get_key() == "@links") {
478,552✔
957
        identifier = "@links";
304✔
958
        // This is a backlink aggregate query
959
        path->path_elems.pop_back();
304✔
960
        auto link_chain = path->visit(drv, comp_type);
304✔
961
        auto sub = link_chain.get_backlink_count<Int>();
304✔
962
        return sub.clone();
304✔
963
    }
304✔
964
    m_link_chain = path->visit(drv, comp_type);
478,248✔
965
    if (!path->at_end()) {
478,248✔
966
        if (!path->current_path_elem->is_key()) {
476,428✔
967
            throw InvalidQueryError(util::format("[%1] not expected", *path->current_path_elem));
4✔
968
        }
4✔
969
        identifier = path->current_path_elem->get_key();
476,424✔
970
    }
476,424✔
971
    std::unique_ptr<Subexpr> subexpr{drv->column(m_link_chain, path)};
478,244✔
972

973
    Path indexes;
478,244✔
974
    while (!path->at_end()) {
482,336✔
975
        indexes.emplace_back(std::move(*(path->current_path_elem++)));
4,092✔
976
    }
4,092✔
977

978
    if (!indexes.empty()) {
478,244✔
979
        auto ok = false;
3,700✔
980
        const PathElement& first_index = indexes.front();
3,700✔
981
        if (indexes.size() > 1 && subexpr->get_type() != type_Mixed) {
3,700✔
982
            throw InvalidQueryError("Only Property of type 'any' can have nested collections");
×
983
        }
×
984
        if (auto mixed = dynamic_cast<Columns<Mixed>*>(subexpr.get())) {
3,700✔
985
            ok = true;
292✔
986
            mixed->path(indexes);
292✔
987
        }
292✔
988
        else if (auto dict = dynamic_cast<Columns<Dictionary>*>(subexpr.get())) {
3,408✔
989
            if (first_index.is_key()) {
256✔
990
                ok = true;
196✔
991
                auto trailing = first_index.get_key();
196✔
992
                if (trailing == "@values") {
196✔
993
                }
4✔
994
                else if (trailing == "@keys") {
192✔
995
                    subexpr = std::make_unique<ColumnDictionaryKeys>(*dict);
52✔
996
                }
52✔
997
                else {
140✔
998
                    dict->path(indexes);
140✔
999
                }
140✔
1000
            }
196✔
1001
            else if (first_index.is_all()) {
60✔
1002
                ok = true;
52✔
1003
                dict->path(indexes);
52✔
1004
            }
52✔
1005
        }
256✔
1006
        else if (auto coll = dynamic_cast<Columns<Lst<Mixed>>*>(subexpr.get())) {
3,152✔
1007
            ok = coll->indexes(indexes);
48✔
1008
        }
48✔
1009
        else if (auto coll = dynamic_cast<ColumnListBase*>(subexpr.get())) {
3,104✔
1010
            if (indexes.size() == 1) {
3,096✔
1011
                ok = coll->index(first_index);
3,096✔
1012
            }
3,096✔
1013
        }
3,096✔
1014

1015
        if (!ok) {
3,700✔
1016
            if (first_index.is_key()) {
1,760✔
1017
                auto trailing = first_index.get_key();
1,720✔
1018
                if (!post_op && is_length_suffix(trailing)) {
1,720✔
1019
                    // If 'length' is the operator, the last id in the path must be the name
1020
                    // of a list property
1021
                    path->path_elems.pop_back();
1,704✔
1022
                    const std::string& prop = path->path_elems.back().get_key();
1,704✔
1023
                    std::unique_ptr<Subexpr> subexpr{path->visit(drv, comp_type).column(prop, false)};
1,704✔
1024
                    if (auto list = dynamic_cast<ColumnListBase*>(subexpr.get())) {
1,704✔
1025
                        if (auto length_expr = list->get_element_length())
1,704✔
1026
                            return length_expr;
1,640✔
1027
                    }
1,704✔
1028
                }
1,704✔
1029
                throw InvalidQueryError(util::format("Property '%1.%2' has no property '%3'",
80✔
1030
                                                     m_link_chain.get_current_table()->get_class_name(), identifier,
80✔
1031
                                                     trailing));
80✔
1032
            }
1,720✔
1033
            else {
40✔
1034
                throw InvalidQueryError(util::format("Property '%1.%2' does not support index '%3'",
40✔
1035
                                                     m_link_chain.get_current_table()->get_class_name(), identifier,
40✔
1036
                                                     first_index));
40✔
1037
            }
40✔
1038
        }
1,760✔
1039
    }
3,700✔
1040
    if (post_op) {
476,484✔
1041
        return post_op->visit(drv, subexpr.get());
4,128✔
1042
    }
4,128✔
1043
    return subexpr;
472,356✔
1044
}
476,484✔
1045

1046
std::unique_ptr<Subexpr> SubqueryNode::visit(ParserDriver* drv, DataType)
1047
{
304✔
1048
    if (variable_name.size() < 2 || variable_name[0] != '$') {
304✔
1049
        throw SyntaxError(util::format("The subquery variable '%1' is invalid. The variable must start with "
4✔
1050
                                       "'$' and cannot be empty; for example '$x'.",
4✔
1051
                                       variable_name));
4✔
1052
    }
4✔
1053
    LinkChain lc = prop->path->visit(drv, prop->comp_type);
300✔
1054

1055
    ColKey col_key;
300✔
1056
    std::string identifier;
300✔
1057
    if (!prop->path->at_end()) {
300✔
1058
        identifier = prop->path->next_identifier();
8✔
1059
        col_key = lc.get_current_table()->get_column_key(identifier);
8✔
1060
    }
8✔
1061
    else {
292✔
1062
        identifier = prop->path->last_identifier();
292✔
1063
        col_key = lc.get_current_col();
292✔
1064
    }
292✔
1065

1066
    auto col_type = col_key.get_type();
300✔
1067
    if (col_key.is_list() && col_type != col_type_Link) {
300✔
1068
        throw InvalidQueryError(
4✔
1069
            util::format("A subquery can not operate on a list of primitive values (property '%1')", identifier));
4✔
1070
    }
4✔
1071
    // col_key.is_list => col_type == col_type_Link
1072
    if (!(col_key.is_list() || col_type == col_type_BackLink)) {
296✔
1073
        throw InvalidQueryError(util::format("A subquery must operate on a list property, but '%1' is type '%2'",
8✔
1074
                                             identifier, realm::get_data_type_name(DataType(col_type))));
8✔
1075
    }
8✔
1076

1077
    TableRef previous_table = drv->m_base_table;
288✔
1078
    drv->m_base_table = lc.get_current_table().cast_away_const();
288✔
1079
    bool did_add = drv->m_mapping.add_mapping(drv->m_base_table, variable_name, "");
288✔
1080
    if (!did_add) {
288✔
1081
        throw InvalidQueryError(util::format("Unable to create a subquery expression with variable '%1' since an "
4✔
1082
                                             "identical variable already exists in this context",
4✔
1083
                                             variable_name));
4✔
1084
    }
4✔
1085
    Query sub = subquery->visit(drv);
284✔
1086
    drv->m_mapping.remove_mapping(drv->m_base_table, variable_name);
284✔
1087
    drv->m_base_table = previous_table;
284✔
1088

1089
    return lc.subquery(sub);
284✔
1090
}
288✔
1091

1092
std::unique_ptr<Subexpr> PostOpNode::visit(ParserDriver*, Subexpr* subexpr)
1093
{
4,128✔
1094
    if (op_type == PostOpNode::SIZE) {
4,128✔
1095
        if (auto s = dynamic_cast<Columns<Link>*>(subexpr)) {
3,484✔
1096
            return s->count().clone();
344✔
1097
        }
344✔
1098
        if (auto s = dynamic_cast<ColumnListBase*>(subexpr)) {
3,140✔
1099
            return s->size().clone();
2,928✔
1100
        }
2,928✔
1101
        if (auto s = dynamic_cast<Columns<StringData>*>(subexpr)) {
212✔
1102
            return s->size().clone();
128✔
1103
        }
128✔
1104
        if (auto s = dynamic_cast<Columns<BinaryData>*>(subexpr)) {
84✔
1105
            return s->size().clone();
48✔
1106
        }
48✔
1107
        if (auto s = dynamic_cast<Columns<Mixed>*>(subexpr)) {
36✔
1108
            return s->size().clone();
24✔
1109
        }
24✔
1110
    }
36✔
1111
    else if (op_type == PostOpNode::TYPE) {
644✔
1112
        if (auto s = dynamic_cast<Columns<Mixed>*>(subexpr)) {
644✔
1113
            return s->type_of_value().clone();
512✔
1114
        }
512✔
1115
        if (auto s = dynamic_cast<ColumnsCollection<Mixed>*>(subexpr)) {
132✔
1116
            return s->type_of_value().clone();
112✔
1117
        }
112✔
1118
        if (auto s = dynamic_cast<ObjPropertyBase*>(subexpr)) {
20✔
1119
            return Value<TypeOfValue>(TypeOfValue(s->column_key())).clone();
8✔
1120
        }
8✔
1121
        if (dynamic_cast<Columns<Link>*>(subexpr)) {
12✔
1122
            return Value<TypeOfValue>(TypeOfValue(TypeOfValue::Attribute::ObjectLink)).clone();
12✔
1123
        }
12✔
1124
    }
12✔
1125

1126
    if (subexpr) {
12✔
1127
        throw InvalidQueryError(util::format("Operation '%1' is not supported on property of type '%2'", op_name,
12✔
1128
                                             get_data_type_name(DataType(subexpr->get_type()))));
12✔
1129
    }
12✔
1130
    REALM_UNREACHABLE();
1131
    return {};
×
1132
}
12✔
1133

1134
std::unique_ptr<Subexpr> LinkAggrNode::visit(ParserDriver* drv, DataType)
1135
{
848✔
1136
    auto subexpr = property->visit(drv);
848✔
1137
    auto link_prop = dynamic_cast<Columns<Link>*>(subexpr.get());
848✔
1138
    if (!link_prop) {
848✔
1139
        throw InvalidQueryError(util::format("Operation '%1' cannot apply to property '%2' because it is not a list",
40✔
1140
                                             agg_op_type_to_str(type), property->get_identifier()));
40✔
1141
    }
40✔
1142
    const LinkChain& link_chain = property->link_chain();
808✔
1143
    prop_name = drv->translate(link_chain, prop_name);
808✔
1144
    auto col_key = link_chain.get_current_table()->get_column_key(prop_name);
808✔
1145

1146
    switch (col_key.get_type()) {
808✔
1147
        case col_type_Int:
64✔
1148
            subexpr = link_prop->column<Int>(col_key).clone();
64✔
1149
            break;
64✔
1150
        case col_type_Float:
128✔
1151
            subexpr = link_prop->column<float>(col_key).clone();
128✔
1152
            break;
128✔
1153
        case col_type_Double:
344✔
1154
            subexpr = link_prop->column<double>(col_key).clone();
344✔
1155
            break;
344✔
1156
        case col_type_Decimal:
96✔
1157
            subexpr = link_prop->column<Decimal>(col_key).clone();
96✔
1158
            break;
96✔
1159
        case col_type_Timestamp:
56✔
1160
            subexpr = link_prop->column<Timestamp>(col_key).clone();
56✔
1161
            break;
56✔
1162
        case col_type_Mixed:
64✔
1163
            subexpr = link_prop->column<Mixed>(col_key).clone();
64✔
1164
            break;
64✔
1165
        default:
48✔
1166
            throw InvalidQueryError(util::format("collection aggregate not supported for type '%1'",
48✔
1167
                                                 get_data_type_name(DataType(col_key.get_type()))));
48✔
1168
    }
808✔
1169
    return aggregate(subexpr.get());
752✔
1170
}
808✔
1171

1172
std::unique_ptr<Subexpr> ListAggrNode::visit(ParserDriver* drv, DataType)
1173
{
2,744✔
1174
    auto subexpr = property->visit(drv);
2,744✔
1175
    return aggregate(subexpr.get());
2,744✔
1176
}
2,744✔
1177

1178
std::unique_ptr<Subexpr> AggrNode::aggregate(Subexpr* subexpr)
1179
{
3,496✔
1180
    std::unique_ptr<Subexpr> agg;
3,496✔
1181
    if (auto list_prop = dynamic_cast<ColumnListBase*>(subexpr)) {
3,496✔
1182
        switch (type) {
2,712✔
1183
            case MAX:
632✔
1184
                agg = list_prop->max_of();
632✔
1185
                break;
632✔
1186
            case MIN:
608✔
1187
                agg = list_prop->min_of();
608✔
1188
                break;
608✔
1189
            case SUM:
800✔
1190
                agg = list_prop->sum_of();
800✔
1191
                break;
800✔
1192
            case AVG:
672✔
1193
                agg = list_prop->avg_of();
672✔
1194
                break;
672✔
1195
        }
2,712✔
1196
    }
2,712✔
1197
    else if (auto prop = dynamic_cast<SubColumnBase*>(subexpr)) {
784✔
1198
        switch (type) {
752✔
1199
            case MAX:
216✔
1200
                agg = prop->max_of();
216✔
1201
                break;
216✔
1202
            case MIN:
208✔
1203
                agg = prop->min_of();
208✔
1204
                break;
208✔
1205
            case SUM:
148✔
1206
                agg = prop->sum_of();
148✔
1207
                break;
148✔
1208
            case AVG:
180✔
1209
                agg = prop->avg_of();
180✔
1210
                break;
180✔
1211
        }
752✔
1212
    }
752✔
1213
    if (!agg) {
3,496✔
1214
        throw InvalidQueryError(
232✔
1215
            util::format("Cannot use aggregate '%1' for this type of property", agg_op_type_to_str(type)));
232✔
1216
    }
232✔
1217

1218
    return agg;
3,264✔
1219
}
3,496✔
1220

1221
void ConstantNode::decode_b64()
1222
{
1,432✔
1223
    const size_t encoded_size = text.size() - 5;
1,432✔
1224
    size_t buffer_size = util::base64_decoded_size(encoded_size);
1,432✔
1225
    m_decode_buffer.resize(buffer_size);
1,432✔
1226
    StringData window(text.c_str() + 4, encoded_size);
1,432✔
1227
    util::Optional<size_t> decoded_size = util::base64_decode(window, m_decode_buffer);
1,432✔
1228
    if (!decoded_size) {
1,432✔
1229
        throw SyntaxError("Invalid base64 value");
×
1230
    }
×
1231
    REALM_ASSERT_DEBUG_EX(*decoded_size <= encoded_size, *decoded_size, encoded_size);
1,432✔
1232
    m_decode_buffer.resize(*decoded_size); // truncate
1,432✔
1233
}
1,432✔
1234

1235
Mixed ConstantNode::get_value()
1236
{
42,224✔
1237
    switch (type) {
42,224✔
1238
        case Type::NUMBER:
24,296✔
1239
            return int64_t(strtoll(text.c_str(), nullptr, 0));
24,296✔
1240
        case Type::FLOAT:
2,152✔
1241
            if (text[text.size() - 1] == 'f') {
2,152✔
1242
                return strtof(text.c_str(), nullptr);
4✔
1243
            }
4✔
1244
            return strtod(text.c_str(), nullptr);
2,148✔
1245
        case Type::INFINITY_VAL: {
152✔
1246
            bool negative = text[0] == '-';
152✔
1247
            constexpr auto inf = std::numeric_limits<double>::infinity();
152✔
1248
            return negative ? -inf : inf;
152✔
1249
        }
2,152✔
1250
        case Type::NAN_VAL:
64✔
1251
            return type_punning<double>(0x7ff8000000000000);
64✔
1252
        case Type::STRING:
8,176✔
1253
            return StringData(text.data() + 1, text.size() - 2);
8,176✔
1254
        case Type::STRING_BASE64:
716✔
1255
            decode_b64();
716✔
1256
            return StringData(m_decode_buffer.data(), m_decode_buffer.size());
716✔
1257
        case Type::TIMESTAMP: {
612✔
1258
            auto s = text;
612✔
1259
            int64_t seconds;
612✔
1260
            int32_t nanoseconds;
612✔
1261
            if (s[0] == 'T') {
612✔
1262
                size_t colon_pos = s.find(":");
536✔
1263
                std::string s1 = s.substr(1, colon_pos - 1);
536✔
1264
                std::string s2 = s.substr(colon_pos + 1);
536✔
1265
                seconds = strtol(s1.c_str(), nullptr, 0);
536✔
1266
                nanoseconds = int32_t(strtol(s2.c_str(), nullptr, 0));
536✔
1267
            }
536✔
1268
            else {
76✔
1269
                // readable format YYYY-MM-DD-HH:MM:SS:NANOS nanos optional
1270
                struct tm tmp = tm();
76✔
1271
                char sep = s.find("@") < s.size() ? '@' : 'T';
76✔
1272
                std::string fmt = "%d-%d-%d"s + sep + "%d:%d:%d:%d"s;
76✔
1273
                int cnt = sscanf(s.c_str(), fmt.c_str(), &tmp.tm_year, &tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour,
76✔
1274
                                 &tmp.tm_min, &tmp.tm_sec, &nanoseconds);
76✔
1275
                REALM_ASSERT(cnt >= 6);
76✔
1276
                tmp.tm_year -= 1900; // epoch offset (see man mktime)
76✔
1277
                tmp.tm_mon -= 1;     // converts from 1-12 to 0-11
76✔
1278

1279
                if (tmp.tm_year < 0) {
76✔
1280
                    // platform timegm functions do not throw errors, they return -1 which is also a valid time
1281
                    throw InvalidQueryError("Conversion of dates before 1900 is not supported.");
16✔
1282
                }
16✔
1283

1284
                seconds = platform_timegm(tmp); // UTC time
60✔
1285
                if (cnt == 6) {
60✔
1286
                    nanoseconds = 0;
32✔
1287
                }
32✔
1288
                if (nanoseconds < 0) {
60✔
1289
                    throw SyntaxError("The nanoseconds of a Timestamp cannot be negative.");
×
1290
                }
×
1291
                if (seconds < 0) { // seconds determines the sign of the nanoseconds part
60✔
1292
                    nanoseconds *= -1;
24✔
1293
                }
24✔
1294
            }
60✔
1295
            return get_timestamp_if_valid(seconds, nanoseconds);
596✔
1296
        }
612✔
1297
        case Type::UUID_T:
672✔
1298
            return UUID(text.substr(5, text.size() - 6));
672✔
1299
        case Type::OID:
772✔
1300
            return ObjectId(text.substr(4, text.size() - 5).c_str());
772✔
1301
        case Type::LINK:
8✔
1302
            return ObjKey(strtol(text.substr(1, text.size() - 1).c_str(), nullptr, 0));
8✔
1303
        case Type::TYPED_LINK: {
48✔
1304
            size_t colon_pos = text.find(":");
48✔
1305
            auto table_key_val = uint32_t(strtol(text.substr(1, colon_pos - 1).c_str(), nullptr, 0));
48✔
1306
            auto obj_key_val = strtol(text.substr(colon_pos + 1).c_str(), nullptr, 0);
48✔
1307
            return ObjLink(TableKey(table_key_val), ObjKey(obj_key_val));
48✔
1308
        }
612✔
1309
        case Type::NULL_VAL:
2,300✔
1310
            return {};
2,300✔
1311
        case Type::TRUE:
160✔
1312
            return {true};
160✔
1313
        case Type::FALSE:
312✔
1314
            return {false};
312✔
1315
        case Type::ARG:
✔
1316
            break;
×
1317
        case BINARY_STR: {
1,068✔
1318
            return BinaryData(text.data() + 1, text.size() - 2);
1,068✔
1319
        }
612✔
1320
        case BINARY_BASE64:
716✔
1321
            decode_b64();
716✔
1322
            return BinaryData(m_decode_buffer.data(), m_decode_buffer.size());
716✔
1323
    }
42,224✔
1324
    return {};
×
1325
}
42,224✔
1326

1327
std::unique_ptr<Subexpr> ConstantNode::visit(ParserDriver* drv, DataType hint)
1328
{
475,372✔
1329
    std::unique_ptr<Subexpr> ret;
475,372✔
1330
    std::string explain_value_message = text;
475,372✔
1331
    Mixed value;
475,372✔
1332

1333
    auto convert_if_needed = [&](Mixed& value) -> void {
475,372✔
1334
        switch (value.get_type()) {
472,838✔
1335
            case type_Int:
25,272✔
1336
                if (hint == type_Decimal) {
25,272✔
1337
                    value = Decimal128(value.get_int());
1,296✔
1338
                }
1,296✔
1339
                break;
25,272✔
1340
            case type_Double: {
2,928✔
1341
                auto double_val = value.get_double();
2,928✔
1342
                if (std::isinf(double_val) && (!Mixed::is_numeric(hint) || hint == type_Int)) {
2,928✔
1343
                    throw InvalidQueryError(util::format("Infinity not supported for %1", get_data_type_name(hint)));
8✔
1344
                }
8✔
1345

1346
                switch (hint) {
2,920✔
1347
                    case type_Float:
184✔
1348
                        value = float(double_val);
184✔
1349
                        break;
184✔
1350
                    case type_Decimal:
480✔
1351
                        // If not argument, try decode again to get full precision
1352
                        value = (type == Type::ARG) ? Decimal128(double_val) : Decimal128(text);
480✔
1353
                        break;
480✔
1354
                    case type_Int: {
80✔
1355
                        int64_t int_val = int64_t(double_val);
80✔
1356
                        // Only return an integer if it precisely represents val
1357
                        if (double(int_val) == double_val) {
80✔
1358
                            value = int_val;
24✔
1359
                        }
24✔
1360
                        break;
80✔
NEW
1361
                    }
×
1362
                    default:
2,176✔
1363
                        break;
2,176✔
1364
                }
2,920✔
1365
                break;
2,920✔
1366
            }
2,920✔
1367
            case type_Float: {
2,920✔
1368
                if (hint == type_Int) {
476✔
1369
                    float float_val = value.get_float();
52✔
1370
                    if (std::isinf(float_val)) {
52✔
1371
                        throw InvalidQueryError(
8✔
1372
                            util::format("Infinity not supported for %1", get_data_type_name(hint)));
8✔
1373
                    }
8✔
1374
                    if (std::isnan(float_val)) {
44✔
1375
                        throw InvalidQueryError(util::format("NaN not supported for %1", get_data_type_name(hint)));
8✔
1376
                    }
8✔
1377
                    int64_t int_val = int64_t(float_val);
36✔
1378
                    if (float(int_val) == float_val) {
36✔
1379
                        value = int_val;
16✔
1380
                    }
16✔
1381
                }
36✔
1382
                break;
460✔
1383
            }
476✔
1384
            case type_String: {
9,308✔
1385
                StringData str = value.get_string();
9,308✔
1386
                switch (hint) {
9,308✔
1387
                    case type_Int:
420✔
1388
                        value = string_to<int64_t>(str);
420✔
1389
                        break;
420✔
1390
                    case type_Float:
8✔
1391
                        value = string_to<float>(str);
8✔
1392
                        break;
8✔
1393
                    case type_Double:
8✔
1394
                        value = string_to<double>(str);
8✔
1395
                        break;
8✔
1396
                    case type_Decimal:
4✔
1397
                        value = string_to<Decimal128>(str);
4✔
1398
                        break;
4✔
1399
                    default:
8,868✔
1400
                        break;
8,868✔
1401
                }
9,308✔
1402
                break;
9,272✔
1403
            }
9,308✔
1404
            default:
434,860✔
1405
                break;
434,860✔
1406
        }
472,838✔
1407
    };
472,838✔
1408

1409
    if (type == Type::ARG) {
475,372✔
1410
        size_t arg_no = size_t(strtol(text.substr(1).c_str(), nullptr, 10));
433,148✔
1411
        if (m_comp_type && !drv->m_args.is_argument_list(arg_no)) {
433,148✔
1412
            throw InvalidQueryError(util::format(
12✔
1413
                "ANY/ALL/NONE are only allowed on arguments which contain a list but '%1' is not a list.",
12✔
1414
                explain_value_message));
12✔
1415
        }
12✔
1416
        if (drv->m_args.is_argument_list(arg_no)) {
433,136✔
1417
            std::vector<Mixed> mixed_list = drv->m_args.list_for_argument(arg_no);
160✔
1418
            for (auto& mixed : mixed_list) {
408✔
1419
                if (!mixed.is_null()) {
408✔
1420
                    convert_if_needed(mixed);
396✔
1421
                }
396✔
1422
            }
408✔
1423
            return copy_list_of_args(mixed_list);
160✔
1424
        }
160✔
1425
        if (drv->m_args.is_argument_null(arg_no)) {
432,976✔
1426
            explain_value_message = util::format("argument '%1' which is NULL", explain_value_message);
256✔
1427
        }
256✔
1428
        else {
432,720✔
1429
            value = drv->m_args.mixed_for_argument(arg_no);
432,720✔
1430
            if (value.is_null()) {
432,720✔
1431
                explain_value_message = util::format("argument %1 of type null", explain_value_message);
4✔
1432
            }
4✔
1433
            else if (value.is_type(type_TypedLink)) {
432,716✔
1434
                explain_value_message =
36✔
1435
                    util::format("%1 which links to %2", explain_value_message,
36✔
1436
                                 print_pretty_objlink(value.get<ObjLink>(), drv->m_base_table->get_parent_group()));
36✔
1437
            }
36✔
1438
            else {
432,680✔
1439
                explain_value_message = util::format("argument %1 with value '%2'", explain_value_message, value);
432,680✔
1440
                if (!(m_target_table || Mixed::data_types_are_comparable(value.get_type(), hint) ||
432,680✔
1441
                      Mixed::is_numeric(hint) || (value.is_type(type_String) && hint == type_TypeOfValue))) {
432,680✔
1442
                    throw InvalidQueryArgError(
124✔
1443
                        util::format("Cannot compare %1 to a %2", explain_value_message, get_data_type_name(hint)));
124✔
1444
                }
124✔
1445
            }
432,680✔
1446
        }
432,720✔
1447
    }
432,976✔
1448
    else {
42,224✔
1449
        value = get_value();
42,224✔
1450
    }
42,224✔
1451

1452
    if (m_target_table) {
475,076✔
1453
        // There is a table name set. This must be an ObjLink
1454
        const Group* g = drv->m_base_table->get_parent_group();
112✔
1455
        auto table = g->get_table(m_target_table);
112✔
1456
        if (!table) {
112✔
1457
            // Perhaps class prefix is missing
1458
            Group::TableNameBuffer buffer;
8✔
1459
            table = g->get_table(Group::class_name_to_table_name(m_target_table, buffer));
8✔
1460
        }
8✔
1461
        if (!table) {
112✔
1462
            throw InvalidQueryError(util::format("Unknown object type '%1'", m_target_table));
×
1463
        }
×
1464
        auto obj_key = table->find_primary_key(value);
112✔
1465
        value = ObjLink(table->get_key(), ObjKey(obj_key));
112✔
1466
    }
112✔
1467

1468
    if (value.is_null()) {
475,076✔
1469
        if (hint == type_String) {
2,560✔
1470
            return std::make_unique<ConstantStringValue>(StringData()); // Null string
348✔
1471
        }
348✔
1472
        else if (hint == type_Binary) {
2,212✔
1473
            return std::make_unique<Value<Binary>>(BinaryData()); // Null string
320✔
1474
        }
320✔
1475
        else {
1,892✔
1476
            return std::make_unique<Value<null>>(realm::null());
1,892✔
1477
        }
1,892✔
1478
    }
2,560✔
1479

1480
    convert_if_needed(value);
472,516✔
1481

1482
    switch (value.get_type()) {
472,516✔
1483
        case type_Int: {
24,218✔
1484
            ret = std::make_unique<Value<int64_t>>(value.get_int());
24,218✔
1485
            break;
24,218✔
1486
        }
×
1487
        case type_Float: {
616✔
1488
            ret = std::make_unique<Value<float>>(value.get_float());
616✔
1489
            break;
616✔
1490
        }
×
1491
        case type_Decimal:
2,264✔
1492
            ret = std::make_unique<Value<Decimal128>>(value.get_decimal());
2,264✔
1493
            break;
2,264✔
1494
        case type_Double: {
2,204✔
1495
            ret = std::make_unique<Value<double>>(value.get_double());
2,204✔
1496
            break;
2,204✔
UNCOV
1497
        }
×
1498
        case type_String: {
8,748✔
1499
            StringData str = value.get_string();
8,748✔
1500
            if (hint == type_TypeOfValue) {
8,748✔
1501
                TypeOfValue type_of_value(std::string_view(str.data(), str.size()));
556✔
1502
                ret = std::make_unique<Value<TypeOfValue>>(type_of_value);
556✔
1503
            }
556✔
1504
            else {
8,192✔
1505
                ret = std::make_unique<ConstantStringValue>(str);
8,192✔
1506
            }
8,192✔
1507
            break;
8,748✔
UNCOV
1508
        }
×
1509
        case type_Timestamp:
960✔
1510
            ret = std::make_unique<Value<Timestamp>>(value.get_timestamp());
960✔
1511
            break;
960✔
1512
        case type_UUID:
1,064✔
1513
            ret = std::make_unique<Value<UUID>>(value.get_uuid());
1,064✔
1514
            break;
1,064✔
1515
        case type_ObjectId:
429,376✔
1516
            ret = std::make_unique<Value<ObjectId>>(value.get_object_id());
429,376✔
1517
            break;
429,376✔
1518
        case type_Link:
20✔
1519
            ret = std::make_unique<Value<ObjKey>>(value.get<ObjKey>());
20✔
1520
            break;
20✔
1521
        case type_TypedLink:
196✔
1522
            ret = std::make_unique<Value<ObjLink>>(value.get<ObjLink>());
196✔
1523
            break;
196✔
1524
        case type_Bool:
776✔
1525
            ret = std::make_unique<Value<Bool>>(value.get_bool());
776✔
1526
            break;
776✔
1527
        case type_Binary:
1,948✔
1528
            ret = std::make_unique<ConstantBinaryValue>(value.get_binary());
1,948✔
1529
            break;
1,948✔
1530
        case type_Mixed:
✔
1531
            break;
×
1532
    }
472,516✔
1533
    if (!ret) {
472,372✔
1534
        throw InvalidQueryError(
×
1535
            util::format("Unsupported comparison between property of type '%1' and constant value: %2",
×
1536
                         get_data_type_name(hint), explain_value_message));
×
1537
    }
×
1538
    return ret;
472,372✔
1539
}
472,372✔
1540

1541
std::unique_ptr<ConstantMixedList> ConstantNode::copy_list_of_args(std::vector<Mixed>& mixed_args)
1542
{
160✔
1543
    std::unique_ptr<ConstantMixedList> args_in_list = std::make_unique<ConstantMixedList>(mixed_args.size());
160✔
1544
    size_t ndx = 0;
160✔
1545
    for (const auto& mixed : mixed_args) {
408✔
1546
        args_in_list->set(ndx++, mixed);
408✔
1547
    }
408✔
1548
    if (m_comp_type) {
160✔
1549
        args_in_list->set_comparison_type(*m_comp_type);
20✔
1550
    }
20✔
1551
    return args_in_list;
160✔
1552
}
160✔
1553

1554
Mixed Arguments::mixed_for_argument(size_t arg_no)
1555
{
3,988✔
1556
    switch (type_for_argument(arg_no)) {
3,988✔
1557
        case type_Int:
464✔
1558
            return int64_t(long_for_argument(arg_no));
464✔
1559
        case type_String:
380✔
1560
            return string_for_argument(arg_no);
380✔
1561
        case type_Binary:
176✔
1562
            return binary_for_argument(arg_no);
176✔
1563
        case type_Bool:
316✔
1564
            return bool_for_argument(arg_no);
316✔
1565
        case type_Float:
436✔
1566
            return float_for_argument(arg_no);
436✔
1567
        case type_Double:
440✔
1568
            return double_for_argument(arg_no);
440✔
1569
        case type_Timestamp:
392✔
1570
            try {
392✔
1571
                return timestamp_for_argument(arg_no);
392✔
1572
            }
392✔
1573
            catch (const std::exception&) {
392✔
1574
            }
×
1575
            return objectid_for_argument(arg_no);
×
1576
        case type_ObjectId:
524✔
1577
            try {
524✔
1578
                return objectid_for_argument(arg_no);
524✔
1579
            }
524✔
1580
            catch (const std::exception&) {
524✔
1581
            }
×
1582
            return timestamp_for_argument(arg_no);
×
1583
        case type_Decimal:
420✔
1584
            return decimal128_for_argument(arg_no);
420✔
1585
        case type_UUID:
388✔
1586
            return uuid_for_argument(arg_no);
388✔
1587
        case type_Link:
12✔
1588
            return object_index_for_argument(arg_no);
12✔
1589
        case type_TypedLink:
40✔
1590
            return objlink_for_argument(arg_no);
40✔
1591
        default:
✔
1592
            break;
×
1593
    }
3,988✔
1594
    return {};
×
1595
}
3,988✔
1596

1597
#if REALM_ENABLE_GEOSPATIAL
1598
GeospatialNode::GeospatialNode(GeospatialNode::Box, GeoPoint& p1, GeoPoint& p2)
1599
    : m_geo{Geospatial{GeoBox{p1, p2}}}
10✔
1600
{
20✔
1601
}
20✔
1602

1603
GeospatialNode::GeospatialNode(Circle, GeoPoint& p, double radius)
1604
    : m_geo{Geospatial{GeoCircle{radius, p}}}
30✔
1605
{
60✔
1606
}
60✔
1607

1608
GeospatialNode::GeospatialNode(Polygon, GeoPoint& p)
1609
    : m_points({{p}})
1610
{
×
1611
}
×
1612

1613
GeospatialNode::GeospatialNode(Loop, GeoPoint& p)
1614
    : m_points({{p}})
34✔
1615
{
68✔
1616
}
68✔
1617

1618
void GeospatialNode::add_point_to_loop(GeoPoint& p)
1619
{
272✔
1620
    m_points.back().push_back(p);
272✔
1621
}
272✔
1622

1623
void GeospatialNode::add_loop_to_polygon(GeospatialNode* node)
1624
{
8✔
1625
    m_points.push_back(node->m_points.back());
8✔
1626
}
8✔
1627

1628
std::unique_ptr<Subexpr> GeospatialNode::visit(ParserDriver*, DataType)
1629
{
124✔
1630
    std::unique_ptr<Subexpr> ret;
124✔
1631
    if (m_geo.get_type() != Geospatial::Type::Invalid) {
124✔
1632
        ret = std::make_unique<ConstantGeospatialValue>(m_geo);
72✔
1633
    }
72✔
1634
    else {
52✔
1635
        ret = std::make_unique<ConstantGeospatialValue>(GeoPolygon{m_points});
52✔
1636
    }
52✔
1637
    return ret;
124✔
1638
}
124✔
1639
#endif
1640

1641
std::unique_ptr<Subexpr> ListNode::visit(ParserDriver* drv, DataType hint)
1642
{
2,440✔
1643
    if (hint == type_TypeOfValue) {
2,440✔
1644
        try {
12✔
1645
            std::unique_ptr<Value<TypeOfValue>> ret = std::make_unique<Value<TypeOfValue>>();
12✔
1646
            constexpr bool is_list = true;
12✔
1647
            ret->init(is_list, elements.size());
12✔
1648
            ret->set_comparison_type(m_comp_type);
12✔
1649
            size_t ndx = 0;
12✔
1650
            for (auto constant : elements) {
24✔
1651
                std::unique_ptr<Subexpr> evaluated = constant->visit(drv, hint);
24✔
1652
                if (auto converted = dynamic_cast<Value<TypeOfValue>*>(evaluated.get())) {
24✔
1653
                    ret->set(ndx++, converted->get(0));
20✔
1654
                }
20✔
1655
                else {
4✔
1656
                    throw InvalidQueryError(util::format("Invalid constant inside constant list: %1",
4✔
1657
                                                         evaluated->description(drv->m_serializer_state)));
4✔
1658
                }
4✔
1659
            }
24✔
1660
            return ret;
8✔
1661
        }
12✔
1662
        catch (const std::runtime_error& e) {
12✔
1663
            throw InvalidQueryArgError(e.what());
×
1664
        }
×
1665
    }
12✔
1666

1667
    auto ret = std::make_unique<ConstantMixedList>(elements.size());
2,428✔
1668
    ret->set_comparison_type(m_comp_type);
2,428✔
1669
    size_t ndx = 0;
2,428✔
1670
    for (auto constant : elements) {
4,752✔
1671
        auto evaulated_constant = constant->visit(drv, hint);
4,752✔
1672
        if (auto value = dynamic_cast<const ValueBase*>(evaulated_constant.get())) {
4,752✔
1673
            REALM_ASSERT_EX(value->size() == 1, value->size());
4,752✔
1674
            ret->set(ndx++, value->get(0));
4,752✔
1675
        }
4,752✔
1676
        else {
×
1677
            throw InvalidQueryError("Invalid constant inside constant list");
×
1678
        }
×
1679
    }
4,752✔
1680
    return ret;
2,428✔
1681
}
2,428✔
1682

1683
void PathNode::resolve_arg(ParserDriver* drv)
1684
{
478,548✔
1685
    if (arg.size()) {
478,548✔
1686
        if (path_elems.size()) {
32✔
1687
            throw InvalidQueryError("Key path argument cannot be mixed with other elements");
×
1688
        }
×
1689
        auto arg_str = drv->get_arg_for_key_path(arg);
32✔
1690
        const char* path = arg_str.data();
32✔
1691
        do {
44✔
1692
            auto p = find_chr(path, '.');
44✔
1693
            StringData elem(path, p - path);
44✔
1694
            add_element(elem);
44✔
1695
            path = p;
44✔
1696
        } while (*path++ == '.');
44✔
1697
    }
32✔
1698
}
478,548✔
1699

1700
LinkChain PathNode::visit(ParserDriver* drv, util::Optional<ExpressionComparisonType> comp_type)
1701
{
480,538✔
1702
    LinkChain link_chain(drv->m_base_table, comp_type);
480,538✔
1703
    for (current_path_elem = path_elems.begin(); current_path_elem != path_elems.end(); ++current_path_elem) {
497,582✔
1704
        if (current_path_elem->is_key()) {
495,178✔
1705
            const std::string& raw_path_elem = current_path_elem->get_key();
495,092✔
1706
            auto path_elem = drv->translate(link_chain, raw_path_elem);
495,092✔
1707
            if (path_elem.find("@links.") == 0) {
495,092✔
1708
                std::string_view table_column_pair(path_elem);
504✔
1709
                table_column_pair = table_column_pair.substr(7);
504✔
1710
                auto dot_pos = table_column_pair.find('.');
504✔
1711
                auto table_name = table_column_pair.substr(0, dot_pos);
504✔
1712
                auto column_name = table_column_pair.substr(dot_pos + 1);
504✔
1713
                drv->backlink(link_chain, table_name, column_name);
504✔
1714
                continue;
504✔
1715
            }
504✔
1716
            if (path_elem == "@values") {
494,588✔
1717
                if (!link_chain.get_current_col().is_dictionary()) {
24✔
1718
                    throw InvalidQueryError("@values only allowed on dictionaries");
×
1719
                }
×
1720
                continue;
24✔
1721
            }
24✔
1722
            if (path_elem.empty()) {
494,564✔
1723
                continue; // this element has been removed, this happens in subqueries
284✔
1724
            }
284✔
1725

1726
            // Check if it is a link
1727
            if (link_chain.link(path_elem)) {
494,280✔
1728
                continue;
16,096✔
1729
            }
16,096✔
1730
            // The next identifier being a property on the linked to object takes precedence
1731
            if (link_chain.get_current_table()->get_column_key(path_elem)) {
478,184✔
1732
                break;
478,002✔
1733
            }
478,002✔
1734
        }
478,184✔
1735
        if (!link_chain.index(*current_path_elem))
268✔
1736
            break;
132✔
1737
    }
268✔
1738
    return link_chain;
480,538✔
1739
}
480,538✔
1740

1741
DescriptorNode::~DescriptorNode() {}
1,404✔
1742

1743
DescriptorOrderingNode::~DescriptorOrderingNode() {}
45,744✔
1744

1745
std::unique_ptr<DescriptorOrdering> DescriptorOrderingNode::visit(ParserDriver* drv)
1746
{
43,336✔
1747
    auto target = drv->m_base_table;
43,336✔
1748
    std::unique_ptr<DescriptorOrdering> ordering;
43,336✔
1749
    for (auto cur_ordering : orderings) {
43,336✔
1750
        if (!ordering)
1,140✔
1751
            ordering = std::make_unique<DescriptorOrdering>();
708✔
1752
        if (cur_ordering->get_type() == DescriptorNode::LIMIT) {
1,140✔
1753
            ordering->append_limit(LimitDescriptor(cur_ordering->limit));
340✔
1754
        }
340✔
1755
        else {
800✔
1756
            bool is_distinct = cur_ordering->get_type() == DescriptorNode::DISTINCT;
800✔
1757
            std::vector<std::vector<ExtendedColumnKey>> property_columns;
800✔
1758
            for (Path& path : cur_ordering->columns) {
836✔
1759
                std::vector<ExtendedColumnKey> columns;
836✔
1760
                LinkChain link_chain(target);
836✔
1761
                ColKey col_key;
836✔
1762
                for (size_t ndx_in_path = 0; ndx_in_path < path.size(); ++ndx_in_path) {
1,780✔
1763
                    std::string prop_name = drv->translate(link_chain, path[ndx_in_path].get_key());
952✔
1764
                    // If last column was a dictionary, We will treat the next entry as a key to
1765
                    // the dictionary
1766
                    if (col_key && col_key.is_dictionary()) {
952✔
1767
                        columns.back().set_index(prop_name);
32✔
1768
                    }
32✔
1769
                    else {
920✔
1770
                        col_key = link_chain.get_current_table()->get_column_key(prop_name);
920✔
1771
                        if (!col_key) {
920✔
1772
                            throw InvalidQueryError(util::format(
8✔
1773
                                "No property '%1' found on object type '%2' specified in '%3' clause", prop_name,
8✔
1774
                                link_chain.get_current_table()->get_class_name(), is_distinct ? "distinct" : "sort"));
8✔
1775
                        }
8✔
1776
                        columns.emplace_back(col_key);
912✔
1777
                        if (ndx_in_path < path.size() - 1) {
912✔
1778
                            link_chain.link(col_key);
116✔
1779
                        }
116✔
1780
                    }
912✔
1781
                }
952✔
1782
                property_columns.push_back(columns);
828✔
1783
            }
828✔
1784

1785
            if (is_distinct) {
792✔
1786
                ordering->append_distinct(DistinctDescriptor(property_columns));
252✔
1787
            }
252✔
1788
            else {
540✔
1789
                ordering->append_sort(SortDescriptor(property_columns, cur_ordering->ascending),
540✔
1790
                                      SortDescriptor::MergeMode::prepend);
540✔
1791
            }
540✔
1792
        }
792✔
1793
    }
1,140✔
1794

1795
    return ordering;
43,328✔
1796
}
43,336✔
1797

1798
// If one of the expresions is constant, it should be right
1799
static void verify_conditions(Subexpr* left, Subexpr* right, util::serializer::SerialisationState& state)
1800
{
474,634✔
1801
    if (dynamic_cast<ColumnListBase*>(left) && dynamic_cast<ColumnListBase*>(right)) {
474,634✔
1802
        throw InvalidQueryError(
32✔
1803
            util::format("Ordered comparison between two primitive lists is not implemented yet ('%1' and '%2')",
32✔
1804
                         left->description(state), right->description(state)));
32✔
1805
    }
32✔
1806
    if (dynamic_cast<Value<TypeOfValue>*>(left) && dynamic_cast<Value<TypeOfValue>*>(right)) {
474,602✔
1807
        throw InvalidQueryError(util::format("Comparison between two constants is not supported ('%1' and '%2')",
8✔
1808
                                             left->description(state), right->description(state)));
8✔
1809
    }
8✔
1810
    if (auto link_column = dynamic_cast<Columns<Link>*>(left)) {
474,594✔
1811
        if (link_column->has_multiple_values() && right->has_single_value() && right->get_mixed().is_null()) {
428✔
1812
            throw InvalidQueryError(
20✔
1813
                util::format("Cannot compare linklist ('%1') with NULL", left->description(state)));
20✔
1814
        }
20✔
1815
    }
428✔
1816
}
474,594✔
1817

1818
ParserDriver::ParserDriver(TableRef t, Arguments& args, const query_parser::KeyPathMapping& mapping)
1819
    : m_base_table(t)
23,102✔
1820
    , m_args(args)
23,102✔
1821
    , m_mapping(mapping)
23,102✔
1822
{
46,202✔
1823
    yylex_init(&m_yyscanner);
46,202✔
1824
}
46,202✔
1825

1826
ParserDriver::~ParserDriver()
1827
{
46,202✔
1828
    yylex_destroy(m_yyscanner);
46,202✔
1829
}
46,202✔
1830

1831
PathElement ParserDriver::get_arg_for_index(const std::string& i)
1832
{
4✔
1833
    REALM_ASSERT(i[0] == '$');
4✔
1834
    size_t arg_no = size_t(strtol(i.substr(1).c_str(), nullptr, 10));
4✔
1835
    if (m_args.is_argument_null(arg_no) || m_args.is_argument_list(arg_no)) {
4✔
1836
        throw InvalidQueryError("Invalid index parameter");
×
1837
    }
×
1838
    auto type = m_args.type_for_argument(arg_no);
4✔
1839
    switch (type) {
4✔
1840
        case type_Int:
✔
1841
            return size_t(m_args.long_for_argument(arg_no));
×
1842
        case type_String:
4✔
1843
            return m_args.string_for_argument(arg_no);
4✔
1844
        default:
✔
1845
            throw InvalidQueryError("Invalid index type");
×
1846
    }
4✔
1847
}
4✔
1848

1849
std::string ParserDriver::get_arg_for_key_path(const std::string& i)
1850
{
32✔
1851
    REALM_ASSERT(i[0] == '$');
32✔
1852
    REALM_ASSERT(i[1] == 'K');
32✔
1853
    size_t arg_no = size_t(strtol(i.substr(2).c_str(), nullptr, 10));
32✔
1854
    if (m_args.is_argument_null(arg_no) || m_args.is_argument_list(arg_no)) {
32✔
1855
        throw InvalidQueryArgError(util::format("Null or list cannot be used for parameter '%1'", i));
4✔
1856
    }
4✔
1857
    auto type = m_args.type_for_argument(arg_no);
28✔
1858
    if (type != type_String) {
28✔
1859
        throw InvalidQueryArgError(util::format("Invalid index type for '%1'. Expected a string, but found type '%2'",
4✔
1860
                                                i, get_data_type_name(type)));
4✔
1861
    }
4✔
1862
    return m_args.string_for_argument(arg_no);
24✔
1863
}
28✔
1864

1865
double ParserDriver::get_arg_for_coordinate(const std::string& str)
1866
{
80✔
1867
    REALM_ASSERT(str[0] == '$');
80✔
1868
    size_t arg_no = size_t(strtol(str.substr(1).c_str(), nullptr, 10));
80✔
1869
    if (m_args.is_argument_null(arg_no)) {
80✔
1870
        throw InvalidQueryError(util::format("NULL cannot be used in coordinate at argument '%1'", str));
4✔
1871
    }
4✔
1872
    if (m_args.is_argument_list(arg_no)) {
76✔
1873
        throw InvalidQueryError(util::format("A list cannot be used in a coordinate at argument '%1'", str));
×
1874
    }
×
1875

1876
    auto type = m_args.type_for_argument(arg_no);
76✔
1877
    switch (type) {
76✔
1878
        case type_Int:
✔
1879
            return double(m_args.long_for_argument(arg_no));
×
1880
        case type_Double:
68✔
1881
            return m_args.double_for_argument(arg_no);
68✔
1882
        case type_Float:
✔
1883
            return double(m_args.float_for_argument(arg_no));
×
1884
        default:
8✔
1885
            throw InvalidQueryError(util::format("Invalid parameter '%1' used in coordinate at argument '%2'",
8✔
1886
                                                 get_data_type_name(type), str));
8✔
1887
    }
76✔
1888
}
76✔
1889

1890
auto ParserDriver::cmp(const std::vector<ExpressionNode*>& values) -> std::pair<SubexprPtr, SubexprPtr>
1891
{
475,612✔
1892
    SubexprPtr left;
475,612✔
1893
    SubexprPtr right;
475,612✔
1894

1895
    auto left_is_constant = values[0]->is_constant();
475,612✔
1896
    auto right_is_constant = values[1]->is_constant();
475,612✔
1897

1898
    if (left_is_constant && right_is_constant) {
475,612✔
1899
        throw InvalidQueryError("Cannot compare two constants");
×
1900
    }
×
1901

1902
    if (right_is_constant) {
475,612✔
1903
        // Take left first - it cannot be a constant
1904
        left = values[0]->visit(this);
471,548✔
1905
        right = values[1]->visit(this, left->get_type());
471,548✔
1906
        verify_conditions(left.get(), right.get(), m_serializer_state);
471,548✔
1907
    }
471,548✔
1908
    else {
4,064✔
1909
        right = values[1]->visit(this);
4,064✔
1910
        if (left_is_constant) {
4,064✔
1911
            left = values[0]->visit(this, right->get_type());
1,492✔
1912
        }
1,492✔
1913
        else {
2,572✔
1914
            left = values[0]->visit(this);
2,572✔
1915
        }
2,572✔
1916
        verify_conditions(right.get(), left.get(), m_serializer_state);
4,064✔
1917
    }
4,064✔
1918
    return {std::move(left), std::move(right)};
475,612✔
1919
}
475,612✔
1920

1921
auto ParserDriver::column(LinkChain& link_chain, PathNode* path) -> SubexprPtr
1922
{
478,220✔
1923
    if (path->at_end()) {
478,220✔
1924
        // This is a link property. We can optimize by usingColumns<Link>.
1925
        // However Columns<Link> does not handle @keys and indexes
1926
        auto extended_col_key = link_chain.m_link_cols.back();
1,796✔
1927
        if (!extended_col_key.has_index()) {
1,796✔
1928
            return link_chain.create_subexpr<Link>(ColKey(extended_col_key));
1,792✔
1929
        }
1,792✔
1930
        link_chain.pop_back();
4✔
1931
        --path->current_path_elem;
4✔
1932
        --path->current_path_elem;
4✔
1933
    }
4✔
1934
    auto identifier = m_mapping.translate(link_chain, path->next_identifier());
476,428✔
1935
    if (auto col = link_chain.column(identifier, !path->at_end())) {
476,428✔
1936
        return col;
476,252✔
1937
    }
476,252✔
1938
    throw InvalidQueryError(
176✔
1939
        util::format("'%1' has no property '%2'", link_chain.get_current_table()->get_class_name(), identifier));
176✔
1940
}
476,428✔
1941

1942
void ParserDriver::backlink(LinkChain& link_chain, std::string_view raw_table_name, std::string_view raw_column_name)
1943
{
504✔
1944
    std::string table_name = m_mapping.translate_table_name(raw_table_name);
504✔
1945
    auto origin_table = m_base_table->get_parent_group()->get_table(table_name);
504✔
1946
    ColKey origin_column;
504✔
1947
    std::string column_name{raw_column_name};
504✔
1948
    if (origin_table) {
504✔
1949
        column_name = m_mapping.translate(origin_table, column_name);
496✔
1950
        origin_column = origin_table->get_column_key(column_name);
496✔
1951
    }
496✔
1952
    if (!origin_column) {
504✔
1953
        auto origin_table_name = Group::table_name_to_class_name(table_name);
12✔
1954
        auto current_table_name = link_chain.get_current_table()->get_class_name();
12✔
1955
        throw InvalidQueryError(util::format("No property '%1' found in type '%2' which links to type '%3'",
12✔
1956
                                             column_name, origin_table_name, current_table_name));
12✔
1957
    }
12✔
1958
    link_chain.backlink(*origin_table, origin_column);
492✔
1959
}
492✔
1960

1961
std::string ParserDriver::translate(const LinkChain& link_chain, const std::string& identifier)
1962
{
496,852✔
1963
    return m_mapping.translate(link_chain, identifier);
496,852✔
1964
}
496,852✔
1965

1966
int ParserDriver::parse(const std::string& str)
1967
{
46,202✔
1968
    // std::cout << str << std::endl;
1969
    parse_buffer.append(str);
46,202✔
1970
    parse_buffer.append("\0\0", 2); // Flex requires 2 terminating zeroes
46,202✔
1971
    scan_begin(m_yyscanner, trace_scanning);
46,202✔
1972
    yy::parser parse(*this, m_yyscanner);
46,202✔
1973
    parse.set_debug_level(trace_parsing);
46,202✔
1974
    int res = parse();
46,202✔
1975
    if (parse_error) {
46,202✔
1976
        throw SyntaxError(util::format("Invalid predicate: '%1': %2", str, error_string));
724✔
1977
    }
724✔
1978
    return res;
45,478✔
1979
}
46,202✔
1980

1981
void parse(const std::string& str)
1982
{
1,004✔
1983
    ParserDriver driver;
1,004✔
1984
    driver.parse(str);
1,004✔
1985
}
1,004✔
1986

1987
std::string check_escapes(const char* str)
1988
{
497,854✔
1989
    std::string ret;
497,854✔
1990
    const char* p = strchr(str, '\\');
497,854✔
1991
    while (p) {
498,278✔
1992
        ret += std::string(str, p);
424✔
1993
        p++;
424✔
1994
        if (*p == ' ') {
424✔
1995
            ret += ' ';
144✔
1996
        }
144✔
1997
        else if (*p == 't') {
280✔
1998
            ret += '\t';
280✔
1999
        }
280✔
2000
        else if (*p == 'r') {
×
2001
            ret += '\r';
×
2002
        }
×
2003
        else if (*p == 'n') {
×
2004
            ret += '\n';
×
2005
        }
×
2006
        str = p + 1;
424✔
2007
        p = strchr(str, '\\');
424✔
2008
    }
424✔
2009
    return ret + std::string(str);
497,854✔
2010
}
497,854✔
2011

2012
} // namespace query_parser
2013

2014
Query Table::query(const std::string& query_string, const std::vector<MixedArguments::Arg>& arguments) const
2015
{
11,732✔
2016
    MixedArguments args(arguments);
11,732✔
2017
    return query(query_string, args, {});
11,732✔
2018
}
11,732✔
2019

2020
Query Table::query(const std::string& query_string, const std::vector<Mixed>& arguments) const
2021
{
8✔
2022
    MixedArguments args(arguments);
8✔
2023
    return query(query_string, args, {});
8✔
2024
}
8✔
2025

2026
Query Table::query(const std::string& query_string, const std::vector<Mixed>& arguments,
2027
                   const query_parser::KeyPathMapping& mapping) const
2028
{
1,784✔
2029
    MixedArguments args(arguments);
1,784✔
2030
    return query(query_string, args, mapping);
1,784✔
2031
}
1,784✔
2032

2033
Query Table::query(const std::string& query_string, const std::vector<MixedArguments::Arg>& arguments,
2034
                   const query_parser::KeyPathMapping& mapping) const
2035
{
352✔
2036
    MixedArguments args(arguments);
352✔
2037
    return query(query_string, args, mapping);
352✔
2038
}
352✔
2039

2040
Query Table::query(const std::string& query_string, query_parser::Arguments& args,
2041
                   const query_parser::KeyPathMapping& mapping) const
2042
{
45,178✔
2043
    ParserDriver driver(m_own_ref, args, mapping);
45,178✔
2044
    driver.parse(query_string);
45,178✔
2045
    driver.result->canonicalize();
45,178✔
2046
    return driver.result->visit(&driver).set_ordering(driver.ordering->visit(&driver));
45,178✔
2047
}
45,178✔
2048

2049
std::unique_ptr<Subexpr> LinkChain::column(const std::string& col, bool has_path)
2050
{
478,130✔
2051
    auto col_key = m_current_table->get_column_key(col);
478,130✔
2052
    if (!col_key) {
478,130✔
2053
        return nullptr;
128✔
2054
    }
128✔
2055

2056
    auto col_type{col_key.get_type()};
478,002✔
2057
    if (col_key.is_dictionary()) {
478,002✔
2058
        return create_subexpr<Dictionary>(col_key);
984✔
2059
    }
984✔
2060
    if (Table::is_link_type(col_type)) {
477,018✔
2061
        add(col_key);
×
2062
        return create_subexpr<Link>(col_key);
×
2063
    }
×
2064

2065
    if (col_key.is_set()) {
477,018✔
2066
        switch (col_type) {
3,984✔
2067
            case col_type_Int:
416✔
2068
                return create_subexpr<Set<Int>>(col_key);
416✔
2069
            case col_type_Bool:
✔
2070
                return create_subexpr<Set<Bool>>(col_key);
×
2071
            case col_type_String:
512✔
2072
                return create_subexpr<Set<String>>(col_key);
512✔
2073
            case col_type_Binary:
512✔
2074
                return create_subexpr<Set<Binary>>(col_key);
512✔
2075
            case col_type_Float:
416✔
2076
                return create_subexpr<Set<Float>>(col_key);
416✔
2077
            case col_type_Double:
416✔
2078
                return create_subexpr<Set<Double>>(col_key);
416✔
2079
            case col_type_Timestamp:
248✔
2080
                return create_subexpr<Set<Timestamp>>(col_key);
248✔
2081
            case col_type_Decimal:
416✔
2082
                return create_subexpr<Set<Decimal>>(col_key);
416✔
2083
            case col_type_UUID:
248✔
2084
                return create_subexpr<Set<UUID>>(col_key);
248✔
2085
            case col_type_ObjectId:
248✔
2086
                return create_subexpr<Set<ObjectId>>(col_key);
248✔
2087
            case col_type_Mixed:
552✔
2088
                return create_subexpr<Set<Mixed>>(col_key);
552✔
2089
            default:
✔
2090
                break;
×
2091
        }
3,984✔
2092
    }
3,984✔
2093
    else if (col_key.is_list()) {
473,034✔
2094
        switch (col_type) {
16,480✔
2095
            case col_type_Int:
3,048✔
2096
                return create_subexpr<Lst<Int>>(col_key);
3,048✔
2097
            case col_type_Bool:
880✔
2098
                return create_subexpr<Lst<Bool>>(col_key);
880✔
2099
            case col_type_String:
5,024✔
2100
                return create_subexpr<Lst<String>>(col_key);
5,024✔
2101
            case col_type_Binary:
1,660✔
2102
                return create_subexpr<Lst<Binary>>(col_key);
1,660✔
2103
            case col_type_Float:
880✔
2104
                return create_subexpr<Lst<Float>>(col_key);
880✔
2105
            case col_type_Double:
880✔
2106
                return create_subexpr<Lst<Double>>(col_key);
880✔
2107
            case col_type_Timestamp:
880✔
2108
                return create_subexpr<Lst<Timestamp>>(col_key);
880✔
2109
            case col_type_Decimal:
880✔
2110
                return create_subexpr<Lst<Decimal>>(col_key);
880✔
2111
            case col_type_UUID:
880✔
2112
                return create_subexpr<Lst<UUID>>(col_key);
880✔
2113
            case col_type_ObjectId:
880✔
2114
                return create_subexpr<Lst<ObjectId>>(col_key);
880✔
2115
            case col_type_Mixed:
588✔
2116
                return create_subexpr<Lst<Mixed>>(col_key);
588✔
2117
            default:
✔
2118
                break;
×
2119
        }
16,480✔
2120
    }
16,480✔
2121
    else {
456,554✔
2122
        // Having a path implies a collection
2123
        if (m_comparison_type && !has_path) {
456,554✔
2124
            bool has_list = false;
1,260✔
2125
            for (ColKey link_key : m_link_cols) {
1,312✔
2126
                if (link_key.is_collection() || link_key.get_type() == col_type_BackLink) {
1,312✔
2127
                    has_list = true;
1,216✔
2128
                    break;
1,216✔
2129
                }
1,216✔
2130
            }
1,312✔
2131
            if (!has_list) {
1,260✔
2132
                throw InvalidQueryError(util::format("The keypath following '%1' must contain a list",
44✔
2133
                                                     expression_cmp_type_to_str(m_comparison_type)));
44✔
2134
            }
44✔
2135
        }
1,260✔
2136

2137
        switch (col_type) {
456,510✔
2138
            case col_type_Int:
14,028✔
2139
                return create_subexpr<Int>(col_key);
14,028✔
2140
            case col_type_Bool:
224✔
2141
                return create_subexpr<Bool>(col_key);
224✔
2142
            case col_type_String:
4,800✔
2143
                return create_subexpr<String>(col_key);
4,800✔
2144
            case col_type_Binary:
2,052✔
2145
                return create_subexpr<Binary>(col_key);
2,052✔
2146
            case col_type_Float:
552✔
2147
                return create_subexpr<Float>(col_key);
552✔
2148
            case col_type_Double:
1,944✔
2149
                return create_subexpr<Double>(col_key);
1,944✔
2150
            case col_type_Timestamp:
728✔
2151
                return create_subexpr<Timestamp>(col_key);
728✔
2152
            case col_type_Decimal:
1,484✔
2153
                return create_subexpr<Decimal>(col_key);
1,484✔
2154
            case col_type_UUID:
520✔
2155
                return create_subexpr<UUID>(col_key);
520✔
2156
            case col_type_ObjectId:
428,802✔
2157
                return create_subexpr<ObjectId>(col_key);
428,802✔
2158
            case col_type_Mixed:
1,376✔
2159
                return create_subexpr<Mixed>(col_key);
1,376✔
2160
            default:
✔
2161
                break;
×
2162
        }
456,510✔
2163
    }
456,510✔
2164
    REALM_UNREACHABLE();
2165
    return nullptr;
×
2166
}
477,018✔
2167

2168
std::unique_ptr<Subexpr> LinkChain::subquery(Query subquery)
2169
{
280✔
2170
    REALM_ASSERT(m_link_cols.size() > 0);
280✔
2171
    auto col_key = m_link_cols.back();
280✔
2172
    return std::make_unique<SubQueryCount>(subquery, Columns<Link>(col_key, m_base_table, m_link_cols).link_map());
280✔
2173
}
280✔
2174

2175
template <class T>
2176
SubQuery<T> column(const Table& origin, ColKey origin_col_key, Query subquery)
2177
{
2178
    static_assert(std::is_same<T, BackLink>::value, "A subquery must involve a link list or backlink column");
2179
    return SubQuery<T>(column<T>(origin, origin_col_key), std::move(subquery));
2180
}
2181

2182
} // 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