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

realm / realm-core / 2365

31 May 2024 05:18PM UTC coverage: 90.856% (-0.005%) from 90.861%
2365

push

Evergreen

web-flow
RCORE-1990 Fix packaging for windows (#7762)

101720 of 180086 branches covered (56.48%)

214651 of 236255 relevant lines covered (90.86%)

5823514.79 hits per line

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

87.45
/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 std::optional<T> string_to(const std::string& s)
131
{
436✔
132
    std::istringstream iss(s);
436✔
133
    iss.imbue(std::locale::classic());
436✔
134
    T value;
436✔
135
    iss >> value;
436✔
136
    if (iss.fail()) {
436✔
137
        if (!try_parse_specials(s, value)) {
32✔
138
            return {};
32✔
139
        }
32✔
140
    }
32✔
141
    return value;
404✔
142
}
436✔
143

144
template <>
145
inline std::optional<Decimal128> string_to<Decimal128>(const std::string& s)
146
{
4✔
147
    Decimal128 value(s);
4✔
148
    if (value.is_nan()) {
4✔
149
        return {};
4✔
150
    }
4✔
151
    return value;
×
152
}
4✔
153

154
class MixedArguments : public query_parser::Arguments {
155
public:
156
    using Arg = mpark::variant<Mixed, std::vector<Mixed>>;
157

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

258
    Mixed mixed_for_argument(size_t n) final
259
    {
428,940✔
260
        Arguments::verify_ndx(n);
428,940✔
261
        if (is_argument_list(n)) {
428,940✔
262
            throw InvalidQueryArgError(
×
263
                util::format("Request for scalar argument at index %1 but a list was provided", n));
×
264
        }
×
265

266
        return mpark::get<Mixed>(m_args[n]);
428,940✔
267
    }
428,940✔
268

269
private:
270
    const std::vector<Arg> m_args;
271
};
272

273
Timestamp get_timestamp_if_valid(int64_t seconds, int32_t nanoseconds)
274
{
596✔
275
    const bool both_non_negative = seconds >= 0 && nanoseconds >= 0;
596✔
276
    const bool both_non_positive = seconds <= 0 && nanoseconds <= 0;
596✔
277
    if (both_non_negative || both_non_positive) {
596✔
278
        return Timestamp(seconds, nanoseconds);
580✔
279
    }
580✔
280
    throw SyntaxError("Invalid timestamp format");
16✔
281
}
596✔
282

283
} // namespace
284

285
namespace realm {
286

287
namespace query_parser {
288

289
std::string_view string_for_op(CompareType op)
290
{
3,052✔
291
    switch (op) {
3,052✔
292
        case CompareType::EQUAL:
164✔
293
            return "=";
164✔
294
        case CompareType::NOT_EQUAL:
40✔
295
            return "!=";
40✔
296
        case CompareType::GREATER:
✔
297
            return ">";
×
298
        case CompareType::LESS:
✔
299
            return "<";
×
300
        case CompareType::GREATER_EQUAL:
✔
301
            return ">=";
×
302
        case CompareType::LESS_EQUAL:
✔
303
            return "<=";
×
304
        case CompareType::BEGINSWITH:
632✔
305
            return "beginswith";
632✔
306
        case CompareType::ENDSWITH:
616✔
307
            return "endswith";
616✔
308
        case CompareType::CONTAINS:
968✔
309
            return "contains";
968✔
310
        case CompareType::LIKE:
584✔
311
            return "like";
584✔
312
        case CompareType::IN:
8✔
313
            return "in";
8✔
314
        case CompareType::TEXT:
40✔
315
            return "text";
40✔
316
    }
3,052✔
317
    return ""; // appease MSVC warnings
×
318
}
3,052✔
319

320
NoArguments ParserDriver::s_default_args;
321
query_parser::KeyPathMapping ParserDriver::s_default_mapping;
322

323
ParserNode::~ParserNode() = default;
2,410,438✔
324

325
QueryNode::~QueryNode() = default;
910,552✔
326

327
Query NotNode::visit(ParserDriver* drv)
328
{
1,232✔
329
    Query q = drv->m_base_table->where();
1,232✔
330
    q.Not();
1,232✔
331
    q.and_query(query->visit(drv));
1,232✔
332
    return {q};
1,232✔
333
}
1,232✔
334

335
Query OrNode::visit(ParserDriver* drv)
336
{
584✔
337
    Query q(drv->m_base_table);
584✔
338
    q.group();
584✔
339
    for (auto it : children) {
430,936✔
340
        q.Or();
430,936✔
341
        q.and_query(it->visit(drv));
430,936✔
342
    }
430,936✔
343
    q.end_group();
584✔
344

345
    return q;
584✔
346
}
584✔
347

348
Query AndNode::visit(ParserDriver* drv)
349
{
708✔
350
    Query q(drv->m_base_table);
708✔
351
    for (auto it : children) {
1,592✔
352
        q.and_query(it->visit(drv));
1,592✔
353
    }
1,592✔
354
    return q;
708✔
355
}
708✔
356

357
static void verify_only_string_types(DataType type, std::string_view op_string)
358
{
3,052✔
359
    if (type != type_String && type != type_Binary && type != type_Mixed) {
3,052✔
360
        throw InvalidQueryError(util::format(
348✔
361
            "Unsupported comparison operator '%1' against type '%2', right side must be a string or binary type",
348✔
362
            op_string, get_data_type_name(type)));
348✔
363
    }
348✔
364
}
3,052✔
365

366
std::unique_ptr<Subexpr> OperationNode::visit(ParserDriver* drv, DataType type)
367
{
1,056✔
368
    std::unique_ptr<Subexpr> left;
1,056✔
369
    std::unique_ptr<Subexpr> right;
1,056✔
370

371
    const bool left_is_constant = m_left->is_constant();
1,056✔
372
    const bool right_is_constant = m_right->is_constant();
1,056✔
373
    const bool produces_multiple_values = m_left->is_list() || m_right->is_list();
1,056✔
374

375
    if (left_is_constant && right_is_constant && !produces_multiple_values) {
1,056✔
376
        right = m_right->visit(drv, type);
48✔
377
        left = m_left->visit(drv, type);
48✔
378
        auto v_left = left->get_mixed();
48✔
379
        auto v_right = right->get_mixed();
48✔
380
        Mixed result;
48✔
381
        switch (m_op) {
48✔
382
            case '+':
28✔
383
                result = v_left + v_right;
28✔
384
                break;
28✔
385
            case '-':
✔
386
                result = v_left - v_right;
×
387
                break;
×
388
            case '*':
20✔
389
                result = v_left * v_right;
20✔
390
                break;
20✔
391
            case '/':
✔
392
                result = v_left / v_right;
×
393
                break;
×
394
            default:
✔
395
                break;
×
396
        }
48✔
397
        return std::make_unique<Value<Mixed>>(result);
48✔
398
    }
48✔
399

400
    if (right_is_constant) {
1,008✔
401
        // Take left first - it cannot be a constant
402
        left = m_left->visit(drv);
416✔
403

404
        right = m_right->visit(drv, left->get_type());
416✔
405
    }
416✔
406
    else {
592✔
407
        right = m_right->visit(drv);
592✔
408
        if (left_is_constant) {
592✔
409
            left = m_left->visit(drv, right->get_type());
152✔
410
        }
152✔
411
        else {
440✔
412
            left = m_left->visit(drv);
440✔
413
        }
440✔
414
    }
592✔
415
    if (!Mixed::is_numeric(left->get_type(), right->get_type())) {
1,008✔
416
        util::serializer::SerialisationState state;
16✔
417
        std::string op(&m_op, 1);
16✔
418
        throw InvalidQueryArgError(util::format("Cannot perform '%1' operation on '%2' and '%3'", op,
16✔
419
                                                left->description(state), right->description(state)));
16✔
420
    }
16✔
421

422
    switch (m_op) {
992✔
423
        case '+':
400✔
424
            return std::make_unique<Operator<Plus>>(std::move(left), std::move(right));
400✔
425
        case '-':
136✔
426
            return std::make_unique<Operator<Minus>>(std::move(left), std::move(right));
136✔
427
        case '*':
260✔
428
            return std::make_unique<Operator<Mul>>(std::move(left), std::move(right));
260✔
429
        case '/':
196✔
430
            return std::make_unique<Operator<Div>>(std::move(left), std::move(right));
196✔
431
        default:
✔
432
            break;
×
433
    }
992✔
434
    return {};
×
435
}
992✔
436

437
Query EqualityNode::visit(ParserDriver* drv)
438
{
467,902✔
439
    auto [left, right] = drv->cmp(values);
467,902✔
440

441
    auto left_type = left->get_type();
467,902✔
442
    auto right_type = right->get_type();
467,902✔
443

444
    auto handle_typed_links = [drv](std::unique_ptr<Subexpr>& list, std::unique_ptr<Subexpr>& expr, DataType& type) {
467,902✔
445
        if (auto link_column = dynamic_cast<const Columns<Link>*>(list.get())) {
400✔
446
            // Change all TypedLink values to ObjKey values
447
            auto value = dynamic_cast<ValueBase*>(expr.get());
400✔
448
            auto left_dest_table_key = link_column->link_map().get_target_table()->get_key();
400✔
449
            auto sz = value->size();
400✔
450
            auto obj_keys = std::make_unique<Value<ObjKey>>();
400✔
451
            obj_keys->init(expr->has_multiple_values(), sz);
400✔
452
            obj_keys->set_comparison_type(expr->get_comparison_type());
400✔
453
            for (size_t i = 0; i < sz; i++) {
808✔
454
                auto val = value->get(i);
416✔
455
                // i'th entry is already NULL
456
                if (!val.is_null()) {
416✔
457
                    TableKey right_table_key;
200✔
458
                    ObjKey right_obj_key;
200✔
459
                    if (val.is_type(type_Link)) {
200✔
460
                        right_table_key = left_dest_table_key;
20✔
461
                        right_obj_key = val.get<ObjKey>();
20✔
462
                    }
20✔
463
                    else if (val.is_type(type_TypedLink)) {
180✔
464
                        right_table_key = val.get_link().get_table_key();
180✔
465
                        right_obj_key = val.get_link().get_obj_key();
180✔
466
                    }
180✔
467
                    else {
×
468
                        const char* target_type = get_data_type_name(val.get_type());
×
469
                        throw InvalidQueryError(
×
470
                            util::format("Unsupported comparison between '%1' and type '%2'",
×
471
                                         link_column->link_map().description(drv->m_serializer_state), target_type));
×
472
                    }
×
473
                    if (left_dest_table_key == right_table_key) {
200✔
474
                        obj_keys->set(i, right_obj_key);
192✔
475
                    }
192✔
476
                    else {
8✔
477
                        const Group* g = drv->m_base_table->get_parent_group();
8✔
478
                        throw InvalidQueryArgError(
8✔
479
                            util::format("The relationship '%1' which links to type '%2' cannot be compared to "
8✔
480
                                         "an argument of type %3",
8✔
481
                                         link_column->link_map().description(drv->m_serializer_state),
8✔
482
                                         link_column->link_map().get_target_table()->get_class_name(),
8✔
483
                                         print_pretty_objlink(ObjLink(right_table_key, right_obj_key), g)));
8✔
484
                    }
8✔
485
                }
200✔
486
            }
416✔
487
            expr = std::move(obj_keys);
392✔
488
            type = type_Link;
392✔
489
        }
392✔
490
    };
400✔
491

492
    if (left_type == type_Link && right->has_constant_evaluation()) {
467,902✔
493
        handle_typed_links(left, right, right_type);
388✔
494
    }
388✔
495
    if (right_type == type_Link && left->has_constant_evaluation()) {
467,902✔
496
        handle_typed_links(right, left, left_type);
12✔
497
    }
12✔
498

499
    if (left_type.is_valid() && right_type.is_valid() && !Mixed::data_types_are_comparable(left_type, right_type)) {
467,902✔
500
        throw InvalidQueryError(util::format("Unsupported comparison between type '%1' and type '%2'",
24✔
501
                                             get_data_type_name(left_type), get_data_type_name(right_type)));
24✔
502
    }
24✔
503
    if (left_type == type_TypeOfValue || right_type == type_TypeOfValue) {
467,878✔
504
        if (left_type != right_type) {
696✔
505
            throw InvalidQueryArgError(
12✔
506
                util::format("Unsupported comparison between @type and raw value: '%1' and '%2'",
12✔
507
                             get_data_type_name(left_type), get_data_type_name(right_type)));
12✔
508
        }
12✔
509
    }
696✔
510

511
    if (op == CompareType::IN) {
467,866✔
512
        Subexpr* r = right.get();
840✔
513
        if (!r->has_multiple_values()) {
840✔
514
            throw InvalidQueryArgError("The keypath following 'IN' must contain a list. Found '" +
8✔
515
                                       r->description(drv->m_serializer_state) + "'");
8✔
516
        }
8✔
517
    }
840✔
518

519
    if (op == CompareType::IN || op == CompareType::EQUAL) {
467,858✔
520
        if (auto mixed_list = dynamic_cast<ConstantMixedList*>(right.get());
463,370✔
521
            mixed_list && mixed_list->size() &&
463,370✔
522
            mixed_list->get_comparison_type().value_or(ExpressionComparisonType::Any) ==
463,370✔
523
                ExpressionComparisonType::Any) {
920✔
524
            if (auto lhs = dynamic_cast<ObjPropertyBase*>(left.get());
608✔
525
                lhs && lhs->column_key() && !lhs->column_key().is_collection() && !lhs->links_exist() &&
608✔
526
                lhs->column_key().get_type() != col_type_Mixed) {
608✔
527
                return drv->m_base_table->where().in(lhs->column_key(), mixed_list->begin(), mixed_list->end());
336✔
528
            }
336✔
529
        }
608✔
530
    }
463,370✔
531

532
    if (left_type == type_Link && left_type == right_type && right->has_constant_evaluation()) {
467,522✔
533
        if (auto link_column = dynamic_cast<const Columns<Link>*>(left.get())) {
380✔
534
            if (link_column->link_map().get_nb_hops() == 1 &&
380✔
535
                link_column->get_comparison_type().value_or(ExpressionComparisonType::Any) ==
380✔
536
                    ExpressionComparisonType::Any) {
324✔
537
                REALM_ASSERT(dynamic_cast<const Value<ObjKey>*>(right.get()));
308✔
538
                auto link_values = static_cast<const Value<ObjKey>*>(right.get());
308✔
539
                // We can use a LinksToNode based query
540
                std::vector<ObjKey> values;
308✔
541
                values.reserve(link_values->size());
308✔
542
                for (auto val : *link_values) {
324✔
543
                    values.emplace_back(val.is_null() ? ObjKey() : val.get<ObjKey>());
324✔
544
                }
324✔
545
                if (op == CompareType::EQUAL) {
308✔
546
                    return drv->m_base_table->where().links_to(link_column->link_map().get_first_column_key(),
200✔
547
                                                               values);
200✔
548
                }
200✔
549
                else if (op == CompareType::NOT_EQUAL) {
108✔
550
                    return drv->m_base_table->where().not_links_to(link_column->link_map().get_first_column_key(),
104✔
551
                                                                   values);
104✔
552
                }
104✔
553
            }
308✔
554
        }
380✔
555
    }
380✔
556
    else if (right->has_single_value() && (left_type == right_type || left_type == type_Mixed)) {
467,142✔
557
        Mixed val = right->get_mixed();
459,668✔
558
        const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
459,668✔
559
        if (prop && !prop->links_exist() && !prop->has_path()) {
459,668✔
560
            auto col_key = prop->column_key();
444,096✔
561
            if (val.is_null()) {
444,096✔
562
                switch (op) {
212✔
563
                    case CompareType::EQUAL:
156✔
564
                    case CompareType::IN:
156✔
565
                        return drv->m_base_table->where().equal(col_key, realm::null());
156✔
566
                    case CompareType::NOT_EQUAL:
56✔
567
                        return drv->m_base_table->where().not_equal(col_key, realm::null());
56✔
568
                    default:
✔
569
                        break;
×
570
                }
212✔
571
            }
212✔
572
            switch (left->get_type()) {
443,884✔
573
                case type_Int:
10,030✔
574
                    return drv->simple_query(op, col_key, val.get_int());
10,030✔
575
                case type_Bool:
132✔
576
                    return drv->simple_query(op, col_key, val.get_bool());
132✔
577
                case type_String:
2,592✔
578
                    return drv->simple_query(op, col_key, val.get_string(), case_sensitive);
2,592✔
579
                case type_Binary:
1,416✔
580
                    return drv->simple_query(op, col_key, val.get_binary(), case_sensitive);
1,416✔
581
                case type_Timestamp:
140✔
582
                    return drv->simple_query(op, col_key, val.get<Timestamp>());
140✔
583
                case type_Float:
52✔
584
                    return drv->simple_query(op, col_key, val.get_float());
52✔
585
                case type_Double:
100✔
586
                    return drv->simple_query(op, col_key, val.get_double());
100✔
587
                case type_Decimal:
752✔
588
                    return drv->simple_query(op, col_key, val.get<Decimal128>());
752✔
589
                case type_ObjectId:
428,384✔
590
                    return drv->simple_query(op, col_key, val.get<ObjectId>());
428,384✔
591
                case type_UUID:
164✔
592
                    return drv->simple_query(op, col_key, val.get<UUID>());
164✔
593
                case type_Mixed:
120✔
594
                    return drv->simple_query(op, col_key, val, case_sensitive);
120✔
595
                default:
✔
596
                    break;
×
597
            }
443,884✔
598
        }
443,884✔
599
    }
459,668✔
600
    if (case_sensitive) {
23,122✔
601
        switch (op) {
22,312✔
602
            case CompareType::EQUAL:
18,276✔
603
            case CompareType::IN:
18,840✔
604
                return Query(std::unique_ptr<Expression>(new Compare<Equal>(std::move(left), std::move(right))));
18,840✔
605
            case CompareType::NOT_EQUAL:
3,472✔
606
                return Query(std::unique_ptr<Expression>(new Compare<NotEqual>(std::move(left), std::move(right))));
3,472✔
607
            default:
✔
608
                break;
×
609
        }
22,312✔
610
    }
22,312✔
611
    else {
810✔
612
        verify_only_string_types(right_type, util::format("%1%2", string_for_op(op), "[c]"));
810✔
613
        switch (op) {
810✔
614
            case CompareType::EQUAL:
104✔
615
            case CompareType::IN:
112✔
616
                return Query(std::unique_ptr<Expression>(new Compare<EqualIns>(std::move(left), std::move(right))));
112✔
617
            case CompareType::NOT_EQUAL:
40✔
618
                return Query(
40✔
619
                    std::unique_ptr<Expression>(new Compare<NotEqualIns>(std::move(left), std::move(right))));
40✔
620
            default:
✔
621
                break;
×
622
        }
810✔
623
    }
810✔
624
    return {};
×
625
}
23,122✔
626

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

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

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

646
    Query q(drv->m_base_table);
72✔
647
    q.and_query(cmp1.visit(drv));
72✔
648
    q.and_query(cmp2.visit(drv));
72✔
649

650
    return q;
72✔
651
}
84✔
652

653
Query RelationalNode::visit(ParserDriver* drv)
654
{
5,308✔
655
    auto [left, right] = drv->cmp(values);
5,308✔
656

657
    auto left_type = left->get_type();
5,308✔
658
    auto right_type = right->get_type();
5,308✔
659
    const bool right_type_is_null = right->has_single_value() && right->get_mixed().is_null();
5,308✔
660
    const bool left_type_is_null = left->has_single_value() && left->get_mixed().is_null();
5,308✔
661
    REALM_ASSERT(!(left_type_is_null && right_type_is_null));
5,308✔
662

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

669
    if (!(left_type_is_null || right_type_is_null) && (!left_type.is_valid() || !right_type.is_valid() ||
5,308✔
670
                                                       !Mixed::data_types_are_comparable(left_type, right_type))) {
4,776✔
671
        throw InvalidQueryError(util::format("Unsupported comparison between type '%1' and type '%2'",
×
672
                                             get_data_type_name(left_type), get_data_type_name(right_type)));
×
673
    }
×
674

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

727
Query StringOpsNode::visit(ParserDriver* drv)
728
{
2,856✔
729
    auto [left, right] = drv->cmp(values);
2,856✔
730

731
    auto left_type = left->get_type();
2,856✔
732
    auto right_type = right->get_type();
2,856✔
733
    const ObjPropertyBase* prop = dynamic_cast<const ObjPropertyBase*>(left.get());
2,856✔
734

735
    verify_only_string_types(right_type, string_for_op(op));
2,856✔
736

737
    if (prop && !prop->links_exist() && !prop->has_path() && right->has_single_value() &&
2,856✔
738
        (left_type == right_type || left_type == type_Mixed)) {
2,856✔
739
        auto col_key = prop->column_key();
548✔
740
        if (right_type == type_String) {
548✔
741
            StringData val = right->get_mixed().get_string();
332✔
742

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

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

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

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

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

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

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

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

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

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

952
    Path indexes;
478,690✔
953
    while (!path->at_end()) {
484,198✔
954
        indexes.emplace_back(std::move(*(path->current_path_elem++)));
5,508✔
955
    }
5,508✔
956

957
    if (!indexes.empty()) {
478,690✔
958
        auto ok = false;
4,152✔
959
        const PathElement& first_index = indexes.front();
4,152✔
960
        if (indexes.size() > 1 && subexpr->get_type() != type_Mixed) {
4,152✔
961
            throw InvalidQueryError("Only Property of type 'any' can have nested collections");
×
962
        }
×
963
        if (auto mixed = dynamic_cast<Columns<Mixed>*>(subexpr.get())) {
4,152✔
964
            ok = true;
744✔
965
            mixed->path(indexes);
744✔
966
        }
744✔
967
        else if (auto dict = dynamic_cast<Columns<Dictionary>*>(subexpr.get())) {
3,408✔
968
            if (first_index.is_key()) {
256✔
969
                ok = true;
196✔
970
                auto trailing = first_index.get_key();
196✔
971
                if (trailing == "@values") {
196✔
972
                }
4✔
973
                else if (trailing == "@keys") {
192✔
974
                    subexpr = std::make_unique<ColumnDictionaryKeys>(*dict);
52✔
975
                }
52✔
976
                else {
140✔
977
                    dict->path(indexes);
140✔
978
                }
140✔
979
            }
196✔
980
            else if (first_index.is_all()) {
60✔
981
                ok = true;
52✔
982
                dict->path(indexes);
52✔
983
            }
52✔
984
        }
256✔
985
        else if (auto coll = dynamic_cast<Columns<Lst<Mixed>>*>(subexpr.get())) {
3,152✔
986
            ok = coll->indexes(indexes);
48✔
987
        }
48✔
988
        else if (auto coll = dynamic_cast<ColumnListBase*>(subexpr.get())) {
3,104✔
989
            if (indexes.size() == 1) {
3,096✔
990
                ok = coll->index(first_index);
3,096✔
991
            }
3,096✔
992
        }
3,096✔
993

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

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

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

1045
    auto col_type = col_key.get_type();
300✔
1046
    if (col_key.is_list() && col_type != col_type_Link) {
300✔
1047
        throw InvalidQueryError(
4✔
1048
            util::format("A subquery can not operate on a list of primitive values (property '%1')", identifier));
4✔
1049
    }
4✔
1050
    // col_key.is_list => col_type == col_type_Link
1051
    if (!(col_key.is_list() || col_type == col_type_BackLink)) {
296✔
1052
        throw InvalidQueryError(util::format("A subquery must operate on a list property, but '%1' is type '%2'",
8✔
1053
                                             identifier, realm::get_data_type_name(DataType(col_type))));
8✔
1054
    }
8✔
1055

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

1068
    return lc.subquery(sub);
284✔
1069
}
288✔
1070

1071
std::unique_ptr<Subexpr> PostOpNode::visit(ParserDriver*, Subexpr* subexpr)
1072
{
4,352✔
1073
    if (op_type == PostOpNode::SIZE) {
4,352✔
1074
        if (auto s = dynamic_cast<Columns<Link>*>(subexpr)) {
3,584✔
1075
            return s->count().clone();
344✔
1076
        }
344✔
1077
        if (auto s = dynamic_cast<ColumnListBase*>(subexpr)) {
3,240✔
1078
            return s->size().clone();
2,928✔
1079
        }
2,928✔
1080
        if (auto s = dynamic_cast<Columns<StringData>*>(subexpr)) {
312✔
1081
            return s->size().clone();
128✔
1082
        }
128✔
1083
        if (auto s = dynamic_cast<Columns<BinaryData>*>(subexpr)) {
184✔
1084
            return s->size().clone();
48✔
1085
        }
48✔
1086
        if (auto s = dynamic_cast<Columns<Mixed>*>(subexpr)) {
136✔
1087
            return s->size().clone();
124✔
1088
        }
124✔
1089
    }
136✔
1090
    else if (op_type == PostOpNode::TYPE) {
768✔
1091
        if (auto s = dynamic_cast<Columns<Mixed>*>(subexpr)) {
768✔
1092
            return s->type_of_value().clone();
636✔
1093
        }
636✔
1094
        if (auto s = dynamic_cast<ColumnsCollection<Mixed>*>(subexpr)) {
132✔
1095
            return s->type_of_value().clone();
112✔
1096
        }
112✔
1097
        if (auto s = dynamic_cast<ObjPropertyBase*>(subexpr)) {
20✔
1098
            return Value<TypeOfValue>(TypeOfValue(s->column_key())).clone();
8✔
1099
        }
8✔
1100
        if (dynamic_cast<Columns<Link>*>(subexpr)) {
12✔
1101
            return Value<TypeOfValue>(TypeOfValue(TypeOfValue::Attribute::ObjectLink)).clone();
12✔
1102
        }
12✔
1103
    }
12✔
1104

1105
    if (subexpr) {
12✔
1106
        throw InvalidQueryError(util::format("Operation '%1' is not supported on property of type '%2'", op_name,
12✔
1107
                                             get_data_type_name(DataType(subexpr->get_type()))));
12✔
1108
    }
12✔
1109
    REALM_UNREACHABLE();
1110
    return {};
×
1111
}
12✔
1112

1113
std::unique_ptr<Subexpr> LinkAggrNode::visit(ParserDriver* drv, DataType)
1114
{
848✔
1115
    auto subexpr = property->visit(drv);
848✔
1116
    auto link_prop = dynamic_cast<Columns<Link>*>(subexpr.get());
848✔
1117
    if (!link_prop) {
848✔
1118
        throw InvalidQueryError(util::format("Operation '%1' cannot apply to property '%2' because it is not a list",
40✔
1119
                                             agg_op_type_to_str(type), property->get_identifier()));
40✔
1120
    }
40✔
1121
    const LinkChain& link_chain = property->link_chain();
808✔
1122
    prop_name = drv->translate(link_chain, prop_name);
808✔
1123
    auto col_key = link_chain.get_current_table()->get_column_key(prop_name);
808✔
1124

1125
    switch (col_key.get_type()) {
808✔
1126
        case col_type_Int:
64✔
1127
            subexpr = link_prop->column<Int>(col_key).clone();
64✔
1128
            break;
64✔
1129
        case col_type_Float:
128✔
1130
            subexpr = link_prop->column<float>(col_key).clone();
128✔
1131
            break;
128✔
1132
        case col_type_Double:
344✔
1133
            subexpr = link_prop->column<double>(col_key).clone();
344✔
1134
            break;
344✔
1135
        case col_type_Decimal:
96✔
1136
            subexpr = link_prop->column<Decimal>(col_key).clone();
96✔
1137
            break;
96✔
1138
        case col_type_Timestamp:
56✔
1139
            subexpr = link_prop->column<Timestamp>(col_key).clone();
56✔
1140
            break;
56✔
1141
        case col_type_Mixed:
64✔
1142
            subexpr = link_prop->column<Mixed>(col_key).clone();
64✔
1143
            break;
64✔
1144
        default:
48✔
1145
            throw InvalidQueryError(util::format("collection aggregate not supported for type '%1'",
48✔
1146
                                                 get_data_type_name(DataType(col_key.get_type()))));
48✔
1147
    }
808✔
1148
    return aggregate(subexpr.get());
752✔
1149
}
808✔
1150

1151
std::unique_ptr<Subexpr> ListAggrNode::visit(ParserDriver* drv, DataType)
1152
{
2,744✔
1153
    auto subexpr = property->visit(drv);
2,744✔
1154
    return aggregate(subexpr.get());
2,744✔
1155
}
2,744✔
1156

1157
std::unique_ptr<Subexpr> AggrNode::aggregate(Subexpr* subexpr)
1158
{
3,496✔
1159
    std::unique_ptr<Subexpr> agg;
3,496✔
1160
    if (auto list_prop = dynamic_cast<ColumnListBase*>(subexpr)) {
3,496✔
1161
        switch (type) {
2,712✔
1162
            case MAX:
632✔
1163
                agg = list_prop->max_of();
632✔
1164
                break;
632✔
1165
            case MIN:
608✔
1166
                agg = list_prop->min_of();
608✔
1167
                break;
608✔
1168
            case SUM:
800✔
1169
                agg = list_prop->sum_of();
800✔
1170
                break;
800✔
1171
            case AVG:
672✔
1172
                agg = list_prop->avg_of();
672✔
1173
                break;
672✔
1174
        }
2,712✔
1175
    }
2,712✔
1176
    else if (auto prop = dynamic_cast<SubColumnBase*>(subexpr)) {
784✔
1177
        switch (type) {
752✔
1178
            case MAX:
216✔
1179
                agg = prop->max_of();
216✔
1180
                break;
216✔
1181
            case MIN:
208✔
1182
                agg = prop->min_of();
208✔
1183
                break;
208✔
1184
            case SUM:
148✔
1185
                agg = prop->sum_of();
148✔
1186
                break;
148✔
1187
            case AVG:
180✔
1188
                agg = prop->avg_of();
180✔
1189
                break;
180✔
1190
        }
752✔
1191
    }
752✔
1192
    if (!agg) {
3,496✔
1193
        throw InvalidQueryError(
232✔
1194
            util::format("Cannot use aggregate '%1' for this type of property", agg_op_type_to_str(type)));
232✔
1195
    }
232✔
1196

1197
    return agg;
3,264✔
1198
}
3,496✔
1199

1200
void ConstantNode::decode_b64()
1201
{
1,432✔
1202
    const size_t encoded_size = text.size() - 5;
1,432✔
1203
    size_t buffer_size = util::base64_decoded_size(encoded_size);
1,432✔
1204
    m_decode_buffer.resize(buffer_size);
1,432✔
1205
    StringData window(text.c_str() + 4, encoded_size);
1,432✔
1206
    util::Optional<size_t> decoded_size = util::base64_decode(window, m_decode_buffer);
1,432✔
1207
    if (!decoded_size) {
1,432✔
1208
        throw SyntaxError("Invalid base64 value");
×
1209
    }
×
1210
    REALM_ASSERT_DEBUG_EX(*decoded_size <= encoded_size, *decoded_size, encoded_size);
1,432✔
1211
    m_decode_buffer.resize(*decoded_size); // truncate
1,432✔
1212
}
1,432✔
1213

1214
Mixed ConstantNode::get_value()
1215
{
42,658✔
1216
    switch (type) {
42,658✔
1217
        case Type::NUMBER:
24,592✔
1218
            return int64_t(strtoll(text.c_str(), nullptr, 0));
24,592✔
1219
        case Type::FLOAT:
2,152✔
1220
            if (text[text.size() - 1] == 'f') {
2,152✔
1221
                return strtof(text.c_str(), nullptr);
4✔
1222
            }
4✔
1223
            return strtod(text.c_str(), nullptr);
2,148✔
1224
        case Type::INFINITY_VAL: {
152✔
1225
            bool negative = text[0] == '-';
152✔
1226
            constexpr auto inf = std::numeric_limits<double>::infinity();
152✔
1227
            return negative ? -inf : inf;
152✔
1228
        }
2,152✔
1229
        case Type::NAN_VAL:
64✔
1230
            return type_punning<double>(0x7ff8000000000000);
64✔
1231
        case Type::STRING:
8,316✔
1232
            return StringData(text.data() + 1, text.size() - 2);
8,316✔
1233
        case Type::STRING_BASE64:
716✔
1234
            decode_b64();
716✔
1235
            return StringData(m_decode_buffer.data(), m_decode_buffer.size());
716✔
1236
        case Type::TIMESTAMP: {
612✔
1237
            auto s = text;
612✔
1238
            int64_t seconds;
612✔
1239
            int32_t nanoseconds;
612✔
1240
            if (s[0] == 'T') {
612✔
1241
                size_t colon_pos = s.find(":");
536✔
1242
                std::string s1 = s.substr(1, colon_pos - 1);
536✔
1243
                std::string s2 = s.substr(colon_pos + 1);
536✔
1244
                seconds = strtol(s1.c_str(), nullptr, 0);
536✔
1245
                nanoseconds = int32_t(strtol(s2.c_str(), nullptr, 0));
536✔
1246
            }
536✔
1247
            else {
76✔
1248
                // readable format YYYY-MM-DD-HH:MM:SS:NANOS nanos optional
1249
                struct tm tmp = tm();
76✔
1250
                char sep = s.find("@") < s.size() ? '@' : 'T';
76✔
1251
                std::string fmt = "%d-%d-%d"s + sep + "%d:%d:%d:%d"s;
76✔
1252
                int cnt = sscanf(s.c_str(), fmt.c_str(), &tmp.tm_year, &tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour,
76✔
1253
                                 &tmp.tm_min, &tmp.tm_sec, &nanoseconds);
76✔
1254
                REALM_ASSERT(cnt >= 6);
76✔
1255
                tmp.tm_year -= 1900; // epoch offset (see man mktime)
76✔
1256
                tmp.tm_mon -= 1;     // converts from 1-12 to 0-11
76✔
1257

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

1263
                seconds = platform_timegm(tmp); // UTC time
60✔
1264
                if (cnt == 6) {
60✔
1265
                    nanoseconds = 0;
32✔
1266
                }
32✔
1267
                if (nanoseconds < 0) {
60✔
1268
                    throw SyntaxError("The nanoseconds of a Timestamp cannot be negative.");
×
1269
                }
×
1270
                if (seconds < 0) { // seconds determines the sign of the nanoseconds part
60✔
1271
                    nanoseconds *= -1;
24✔
1272
                }
24✔
1273
            }
60✔
1274
            return get_timestamp_if_valid(seconds, nanoseconds);
596✔
1275
        }
612✔
1276
        case Type::UUID_T:
672✔
1277
            return UUID(text.substr(5, text.size() - 6));
672✔
1278
        case Type::OID:
772✔
1279
            return ObjectId(text.substr(4, text.size() - 5).c_str());
772✔
1280
        case Type::LINK:
8✔
1281
            return ObjKey(strtol(text.substr(1, text.size() - 1).c_str(), nullptr, 0));
8✔
1282
        case Type::TYPED_LINK: {
48✔
1283
            size_t colon_pos = text.find(":");
48✔
1284
            auto table_key_val = uint32_t(strtol(text.substr(1, colon_pos - 1).c_str(), nullptr, 0));
48✔
1285
            auto obj_key_val = strtol(text.substr(colon_pos + 1).c_str(), nullptr, 0);
48✔
1286
            return ObjLink(TableKey(table_key_val), ObjKey(obj_key_val));
48✔
1287
        }
612✔
1288
        case Type::NULL_VAL:
2,300✔
1289
            return {};
2,300✔
1290
        case Type::TRUE:
160✔
1291
            return {true};
160✔
1292
        case Type::FALSE:
312✔
1293
            return {false};
312✔
1294
        case Type::ARG:
✔
1295
            break;
×
1296
        case BINARY_STR: {
1,068✔
1297
            return BinaryData(text.data() + 1, text.size() - 2);
1,068✔
1298
        }
612✔
1299
        case BINARY_BASE64:
716✔
1300
            decode_b64();
716✔
1301
            return BinaryData(m_decode_buffer.data(), m_decode_buffer.size());
716✔
1302
    }
42,658✔
1303
    return {};
×
1304
}
42,658✔
1305

1306
std::unique_ptr<Subexpr> ConstantNode::visit(ParserDriver* drv, DataType hint)
1307
{
475,816✔
1308
    std::unique_ptr<Subexpr> ret;
475,816✔
1309
    std::string explain_value_message = text;
475,816✔
1310
    Mixed value;
475,816✔
1311

1312
    auto convert_if_needed = [&](Mixed& value) -> void {
475,816✔
1313
        switch (value.get_type()) {
473,426✔
1314
            case type_Int:
25,594✔
1315
                if (hint == type_Decimal) {
25,594✔
1316
                    value = Decimal128(value.get_int());
1,296✔
1317
                }
1,296✔
1318
                break;
25,594✔
1319
            case type_Double: {
2,944✔
1320
                auto double_val = value.get_double();
2,944✔
1321
                if (std::isinf(double_val) && (!Mixed::is_numeric(hint) || hint == type_Int)) {
2,944✔
1322
                    throw InvalidQueryError(util::format("Infinity not supported for %1", get_data_type_name(hint)));
8✔
1323
                }
8✔
1324

1325
                switch (hint) {
2,936✔
1326
                    case type_Float:
184✔
1327
                        value = float(double_val);
184✔
1328
                        break;
184✔
1329
                    case type_Decimal:
480✔
1330
                        // If not argument, try decode again to get full precision
1331
                        value = (type == Type::ARG) ? Decimal128(double_val) : Decimal128(text);
480✔
1332
                        break;
480✔
1333
                    case type_Int: {
80✔
1334
                        int64_t int_val = int64_t(double_val);
80✔
1335
                        // Only return an integer if it precisely represents val
1336
                        if (double(int_val) == double_val) {
80✔
1337
                            value = int_val;
24✔
1338
                        }
24✔
1339
                        break;
80✔
1340
                    }
×
1341
                    default:
2,192✔
1342
                        break;
2,192✔
1343
                }
2,936✔
1344
                break;
2,936✔
1345
            }
2,936✔
1346
            case type_Float: {
2,936✔
1347
                if (hint == type_Int) {
492✔
1348
                    float float_val = value.get_float();
52✔
1349
                    if (std::isinf(float_val)) {
52✔
1350
                        throw InvalidQueryError(
8✔
1351
                            util::format("Infinity not supported for %1", get_data_type_name(hint)));
8✔
1352
                    }
8✔
1353
                    if (std::isnan(float_val)) {
44✔
1354
                        throw InvalidQueryError(util::format("NaN not supported for %1", get_data_type_name(hint)));
8✔
1355
                    }
8✔
1356
                    int64_t int_val = int64_t(float_val);
36✔
1357
                    if (float(int_val) == float_val) {
36✔
1358
                        value = int_val;
16✔
1359
                    }
16✔
1360
                }
36✔
1361
                break;
476✔
1362
            }
492✔
1363
            case type_String: {
9,480✔
1364
                StringData str = value.get_string();
9,480✔
1365
                switch (hint) {
9,480✔
1366
                    case type_Int:
420✔
1367
                        if (auto val = string_to<int64_t>(str)) {
420✔
1368
                            value = *val;
404✔
1369
                        }
404✔
1370
                        break;
420✔
1371
                    case type_Float:
8✔
1372
                        if (auto val = string_to<float>(str)) {
8✔
1373
                            value = *val;
×
1374
                        }
×
1375
                        break;
8✔
1376
                    case type_Double:
8✔
1377
                        if (auto val = string_to<double>(str)) {
8✔
1378
                            value = *val;
×
1379
                        }
×
1380
                        break;
8✔
1381
                    case type_Decimal:
4✔
1382
                        if (auto val = string_to<Decimal128>(str)) {
4✔
1383
                            value = *val;
×
1384
                        }
×
1385
                        break;
4✔
1386
                    default:
9,040✔
1387
                        break;
9,040✔
1388
                }
9,480✔
1389
                break;
9,480✔
1390
            }
9,480✔
1391
            default:
434,914✔
1392
                break;
434,914✔
1393
        }
473,426✔
1394
    };
473,426✔
1395

1396
    if (type == Type::ARG) {
475,816✔
1397
        size_t arg_no = size_t(strtol(text.substr(1).c_str(), nullptr, 10));
433,162✔
1398
        if (m_comp_type && !drv->m_args.is_argument_list(arg_no)) {
433,162✔
1399
            throw InvalidQueryError(util::format(
12✔
1400
                "ANY/ALL/NONE are only allowed on arguments which contain a list but '%1' is not a list.",
12✔
1401
                explain_value_message));
12✔
1402
        }
12✔
1403
        if (drv->m_args.is_argument_list(arg_no)) {
433,150✔
1404
            std::vector<Mixed> mixed_list = drv->m_args.list_for_argument(arg_no);
160✔
1405
            for (auto& mixed : mixed_list) {
408✔
1406
                if (!mixed.is_null()) {
408✔
1407
                    convert_if_needed(mixed);
396✔
1408
                }
396✔
1409
            }
408✔
1410
            return copy_list_of_args(mixed_list);
160✔
1411
        }
160✔
1412
        if (drv->m_args.is_argument_null(arg_no)) {
432,990✔
1413
            explain_value_message = util::format("argument '%1' which is NULL", explain_value_message);
256✔
1414
        }
256✔
1415
        else {
432,734✔
1416
            value = drv->m_args.mixed_for_argument(arg_no);
432,734✔
1417
            if (value.is_null()) {
432,734✔
1418
                explain_value_message = util::format("argument %1 of type null", explain_value_message);
4✔
1419
            }
4✔
1420
            else if (value.is_type(type_TypedLink)) {
432,730✔
1421
                explain_value_message =
36✔
1422
                    util::format("%1 which links to %2", explain_value_message,
36✔
1423
                                 print_pretty_objlink(value.get<ObjLink>(), drv->m_base_table->get_parent_group()));
36✔
1424
            }
36✔
1425
            else {
432,694✔
1426
                explain_value_message = util::format("argument %1 with value '%2'", explain_value_message, value);
432,694✔
1427
            }
432,694✔
1428
        }
432,734✔
1429
    }
432,990✔
1430
    else {
42,654✔
1431
        value = get_value();
42,654✔
1432
    }
42,654✔
1433

1434
    if (m_target_table) {
475,644✔
1435
        // There is a table name set. This must be an ObjLink
1436
        const Group* g = drv->m_base_table->get_parent_group();
112✔
1437
        auto table = g->get_table(m_target_table);
112✔
1438
        if (!table) {
112✔
1439
            // Perhaps class prefix is missing
1440
            Group::TableNameBuffer buffer;
8✔
1441
            table = g->get_table(Group::class_name_to_table_name(m_target_table, buffer));
8✔
1442
        }
8✔
1443
        if (!table) {
112✔
1444
            throw InvalidQueryError(util::format("Unknown object type '%1'", m_target_table));
×
1445
        }
×
1446
        auto obj_key = table->find_primary_key(value);
112✔
1447
        value = ObjLink(table->get_key(), ObjKey(obj_key));
112✔
1448
    }
112✔
1449

1450
    if (value.is_null()) {
475,644✔
1451
        if (hint == type_String) {
2,560✔
1452
            return std::make_unique<ConstantStringValue>(StringData()); // Null string
348✔
1453
        }
348✔
1454
        else if (hint == type_Binary) {
2,212✔
1455
            return std::make_unique<Value<Binary>>(BinaryData()); // Null string
320✔
1456
        }
320✔
1457
        else {
1,892✔
1458
            return std::make_unique<Value<null>>(realm::null());
1,892✔
1459
        }
1,892✔
1460
    }
2,560✔
1461

1462
    convert_if_needed(value);
473,084✔
1463

1464
    if (type == Type::ARG && !(m_target_table || Mixed::data_types_are_comparable(value.get_type(), hint) ||
473,084✔
1465
                               (value.is_type(type_TypedLink) && hint == type_Link) ||
432,680✔
1466
                               (value.is_type(type_String) && hint == type_TypeOfValue))) {
432,680✔
1467
        throw InvalidQueryArgError(
176✔
1468
            util::format("Cannot compare %1 to a %2", explain_value_message, get_data_type_name(hint)));
176✔
1469
    }
176✔
1470

1471
    switch (value.get_type()) {
472,908✔
1472
        case type_Int: {
24,518✔
1473
            ret = std::make_unique<Value<int64_t>>(value.get_int());
24,518✔
1474
            break;
24,518✔
1475
        }
×
1476
        case type_Float: {
616✔
1477
            ret = std::make_unique<Value<float>>(value.get_float());
616✔
1478
            break;
616✔
1479
        }
×
1480
        case type_Decimal:
2,264✔
1481
            ret = std::make_unique<Value<Decimal128>>(value.get_decimal());
2,264✔
1482
            break;
2,264✔
1483
        case type_Double: {
2,204✔
1484
            ret = std::make_unique<Value<double>>(value.get_double());
2,204✔
1485
            break;
2,204✔
1486
        }
×
1487
        case type_String: {
8,896✔
1488
            StringData str = value.get_string();
8,896✔
1489
            if (hint == type_TypeOfValue) {
8,896✔
1490
                TypeOfValue type_of_value(std::string_view(str.data(), str.size()));
680✔
1491
                ret = std::make_unique<Value<TypeOfValue>>(type_of_value);
680✔
1492
            }
680✔
1493
            else {
8,216✔
1494
                ret = std::make_unique<ConstantStringValue>(str);
8,216✔
1495
            }
8,216✔
1496
            break;
8,896✔
1497
        }
×
1498
        case type_Timestamp:
948✔
1499
            ret = std::make_unique<Value<Timestamp>>(value.get_timestamp());
948✔
1500
            break;
948✔
1501
        case type_UUID:
1,064✔
1502
            ret = std::make_unique<Value<UUID>>(value.get_uuid());
1,064✔
1503
            break;
1,064✔
1504
        case type_ObjectId:
429,392✔
1505
            ret = std::make_unique<Value<ObjectId>>(value.get_object_id());
429,392✔
1506
            break;
429,392✔
1507
        case type_Link:
20✔
1508
            ret = std::make_unique<Value<ObjKey>>(value.get<ObjKey>());
20✔
1509
            break;
20✔
1510
        case type_TypedLink:
196✔
1511
            ret = std::make_unique<Value<ObjLink>>(value.get<ObjLink>());
196✔
1512
            break;
196✔
1513
        case type_Bool:
776✔
1514
            ret = std::make_unique<Value<Bool>>(value.get_bool());
776✔
1515
            break;
776✔
1516
        case type_Binary:
1,936✔
1517
            ret = std::make_unique<ConstantBinaryValue>(value.get_binary());
1,936✔
1518
            break;
1,936✔
1519
        case type_Mixed:
✔
1520
            break;
×
1521
    }
472,908✔
1522
    if (!ret) {
472,816✔
1523
        throw InvalidQueryError(
×
1524
            util::format("Unsupported comparison between property of type '%1' and constant value: %2",
×
1525
                         get_data_type_name(hint), explain_value_message));
×
1526
    }
×
1527
    return ret;
472,816✔
1528
}
472,816✔
1529

1530
std::unique_ptr<ConstantMixedList> ConstantNode::copy_list_of_args(std::vector<Mixed>& mixed_args)
1531
{
160✔
1532
    std::unique_ptr<ConstantMixedList> args_in_list = std::make_unique<ConstantMixedList>(mixed_args.size());
160✔
1533
    size_t ndx = 0;
160✔
1534
    for (const auto& mixed : mixed_args) {
408✔
1535
        args_in_list->set(ndx++, mixed);
408✔
1536
    }
408✔
1537
    if (m_comp_type) {
160✔
1538
        args_in_list->set_comparison_type(*m_comp_type);
20✔
1539
    }
20✔
1540
    return args_in_list;
160✔
1541
}
160✔
1542

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

1586
#if REALM_ENABLE_GEOSPATIAL
1587
GeospatialNode::GeospatialNode(GeospatialNode::Box, GeoPoint& p1, GeoPoint& p2)
1588
    : m_geo{Geospatial{GeoBox{p1, p2}}}
10✔
1589
{
20✔
1590
}
20✔
1591

1592
GeospatialNode::GeospatialNode(Circle, GeoPoint& p, double radius)
1593
    : m_geo{Geospatial{GeoCircle{radius, p}}}
30✔
1594
{
60✔
1595
}
60✔
1596

1597
GeospatialNode::GeospatialNode(Polygon, GeoPoint& p)
1598
    : m_points({{p}})
1599
{
×
1600
}
×
1601

1602
GeospatialNode::GeospatialNode(Loop, GeoPoint& p)
1603
    : m_points({{p}})
34✔
1604
{
68✔
1605
}
68✔
1606

1607
void GeospatialNode::add_point_to_loop(GeoPoint& p)
1608
{
272✔
1609
    m_points.back().push_back(p);
272✔
1610
}
272✔
1611

1612
void GeospatialNode::add_loop_to_polygon(GeospatialNode* node)
1613
{
8✔
1614
    m_points.push_back(node->m_points.back());
8✔
1615
}
8✔
1616

1617
std::unique_ptr<Subexpr> GeospatialNode::visit(ParserDriver*, DataType)
1618
{
124✔
1619
    std::unique_ptr<Subexpr> ret;
124✔
1620
    if (m_geo.get_type() != Geospatial::Type::Invalid) {
124✔
1621
        ret = std::make_unique<ConstantGeospatialValue>(m_geo);
72✔
1622
    }
72✔
1623
    else {
52✔
1624
        ret = std::make_unique<ConstantGeospatialValue>(GeoPolygon{m_points});
52✔
1625
    }
52✔
1626
    return ret;
124✔
1627
}
124✔
1628
#endif
1629

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

1656
    auto ret = std::make_unique<ConstantMixedList>(elements.size());
2,428✔
1657
    ret->set_comparison_type(m_comp_type);
2,428✔
1658
    size_t ndx = 0;
2,428✔
1659
    for (auto constant : elements) {
4,752✔
1660
        auto evaulated_constant = constant->visit(drv, hint);
4,752✔
1661
        if (auto value = dynamic_cast<const ValueBase*>(evaulated_constant.get())) {
4,752✔
1662
            REALM_ASSERT_EX(value->size() == 1, value->size());
4,752✔
1663
            ret->set(ndx++, value->get(0));
4,752✔
1664
        }
4,752✔
1665
        else {
×
1666
            throw InvalidQueryError("Invalid constant inside constant list");
×
1667
        }
×
1668
    }
4,752✔
1669
    return ret;
2,428✔
1670
}
2,428✔
1671

1672
void PathNode::resolve_arg(ParserDriver* drv)
1673
{
478,996✔
1674
    if (arg.size()) {
478,996✔
1675
        if (path_elems.size()) {
32✔
1676
            throw InvalidQueryError("Key path argument cannot be mixed with other elements");
×
1677
        }
×
1678
        auto arg_str = drv->get_arg_for_key_path(arg);
32✔
1679
        const char* path = arg_str.data();
32✔
1680
        do {
44✔
1681
            auto p = find_chr(path, '.');
44✔
1682
            StringData elem(path, p - path);
44✔
1683
            add_element(elem);
44✔
1684
            path = p;
44✔
1685
        } while (*path++ == '.');
44✔
1686
    }
32✔
1687
}
478,996✔
1688

1689
LinkChain PathNode::visit(ParserDriver* drv, util::Optional<ExpressionComparisonType> comp_type)
1690
{
480,988✔
1691
    LinkChain link_chain(drv->m_base_table, comp_type);
480,988✔
1692
    for (current_path_elem = path_elems.begin(); current_path_elem != path_elems.end(); ++current_path_elem) {
498,018✔
1693
        if (current_path_elem->is_key()) {
495,610✔
1694
            const std::string& raw_path_elem = current_path_elem->get_key();
495,524✔
1695
            auto path_elem = drv->translate(link_chain, raw_path_elem);
495,524✔
1696
            if (path_elem.find("@links.") == 0) {
495,524✔
1697
                std::string_view table_column_pair(path_elem);
504✔
1698
                table_column_pair = table_column_pair.substr(7);
504✔
1699
                auto dot_pos = table_column_pair.find('.');
504✔
1700
                auto table_name = table_column_pair.substr(0, dot_pos);
504✔
1701
                auto column_name = table_column_pair.substr(dot_pos + 1);
504✔
1702
                drv->backlink(link_chain, table_name, column_name);
504✔
1703
                continue;
504✔
1704
            }
504✔
1705
            if (path_elem == "@values") {
495,020✔
1706
                if (!link_chain.get_current_col().is_dictionary()) {
24✔
1707
                    throw InvalidQueryError("@values only allowed on dictionaries");
×
1708
                }
×
1709
                continue;
24✔
1710
            }
24✔
1711
            if (path_elem.empty()) {
494,996✔
1712
                continue; // this element has been removed, this happens in subqueries
284✔
1713
            }
284✔
1714

1715
            // Check if it is a link
1716
            if (link_chain.link(path_elem)) {
494,712✔
1717
                continue;
16,096✔
1718
            }
16,096✔
1719
            // The next identifier being a property on the linked to object takes precedence
1720
            if (link_chain.get_current_table()->get_column_key(path_elem)) {
478,616✔
1721
                break;
478,448✔
1722
            }
478,448✔
1723
        }
478,616✔
1724
        if (!link_chain.index(*current_path_elem))
254✔
1725
            break;
132✔
1726
    }
254✔
1727
    return link_chain;
480,988✔
1728
}
480,988✔
1729

1730
DescriptorNode::~DescriptorNode() {}
1,404✔
1731

1732
DescriptorOrderingNode::~DescriptorOrderingNode() {}
46,200✔
1733

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

1774
            if (is_distinct) {
792✔
1775
                ordering->append_distinct(DistinctDescriptor(property_columns));
252✔
1776
            }
252✔
1777
            else {
540✔
1778
                ordering->append_sort(SortDescriptor(property_columns, cur_ordering->ascending),
540✔
1779
                                      SortDescriptor::MergeMode::prepend);
540✔
1780
            }
540✔
1781
        }
792✔
1782
    }
1,140✔
1783

1784
    return ordering;
43,786✔
1785
}
43,794✔
1786

1787
// If one of the expresions is constant, it should be right
1788
static void verify_conditions(Subexpr* left, Subexpr* right, util::serializer::SerialisationState& state)
1789
{
475,066✔
1790
    if (dynamic_cast<ColumnListBase*>(left) && dynamic_cast<ColumnListBase*>(right)) {
475,066✔
1791
        throw InvalidQueryError(
32✔
1792
            util::format("Ordered comparison between two primitive lists is not implemented yet ('%1' and '%2')",
32✔
1793
                         left->description(state), right->description(state)));
32✔
1794
    }
32✔
1795
    if (dynamic_cast<Value<TypeOfValue>*>(left) && dynamic_cast<Value<TypeOfValue>*>(right)) {
475,034✔
1796
        throw InvalidQueryError(util::format("Comparison between two constants is not supported ('%1' and '%2')",
8✔
1797
                                             left->description(state), right->description(state)));
8✔
1798
    }
8✔
1799
    if (auto link_column = dynamic_cast<Columns<Link>*>(left)) {
475,026✔
1800
        if (link_column->has_multiple_values() && right->has_single_value() && right->get_mixed().is_null()) {
428✔
1801
            throw InvalidQueryError(
20✔
1802
                util::format("Cannot compare linklist ('%1') with NULL", left->description(state)));
20✔
1803
        }
20✔
1804
    }
428✔
1805
}
475,026✔
1806

1807
ParserDriver::ParserDriver(TableRef t, Arguments& args, const query_parser::KeyPathMapping& mapping)
1808
    : m_base_table(t)
23,328✔
1809
    , m_args(args)
23,328✔
1810
    , m_mapping(mapping)
23,328✔
1811
{
46,660✔
1812
    yylex_init(&m_yyscanner);
46,660✔
1813
}
46,660✔
1814

1815
ParserDriver::~ParserDriver()
1816
{
46,652✔
1817
    yylex_destroy(m_yyscanner);
46,652✔
1818
}
46,652✔
1819

1820
PathElement ParserDriver::get_arg_for_index(const std::string& i)
1821
{
4✔
1822
    REALM_ASSERT(i[0] == '$');
4✔
1823
    size_t arg_no = size_t(strtol(i.substr(1).c_str(), nullptr, 10));
4✔
1824
    if (m_args.is_argument_null(arg_no) || m_args.is_argument_list(arg_no)) {
4✔
1825
        throw InvalidQueryError("Invalid index parameter");
×
1826
    }
×
1827
    auto type = m_args.type_for_argument(arg_no);
4✔
1828
    switch (type) {
4✔
1829
        case type_Int:
✔
1830
            return size_t(m_args.long_for_argument(arg_no));
×
1831
        case type_String:
4✔
1832
            return m_args.string_for_argument(arg_no);
4✔
1833
        default:
✔
1834
            throw InvalidQueryError("Invalid index type");
×
1835
    }
4✔
1836
}
4✔
1837

1838
std::string ParserDriver::get_arg_for_key_path(const std::string& i)
1839
{
32✔
1840
    REALM_ASSERT(i[0] == '$');
32✔
1841
    REALM_ASSERT(i[1] == 'K');
32✔
1842
    size_t arg_no = size_t(strtol(i.substr(2).c_str(), nullptr, 10));
32✔
1843
    if (m_args.is_argument_null(arg_no) || m_args.is_argument_list(arg_no)) {
32✔
1844
        throw InvalidQueryArgError(util::format("Null or list cannot be used for parameter '%1'", i));
4✔
1845
    }
4✔
1846
    auto type = m_args.type_for_argument(arg_no);
28✔
1847
    if (type != type_String) {
28✔
1848
        throw InvalidQueryArgError(util::format("Invalid index type for '%1'. Expected a string, but found type '%2'",
4✔
1849
                                                i, get_data_type_name(type)));
4✔
1850
    }
4✔
1851
    return m_args.string_for_argument(arg_no);
24✔
1852
}
28✔
1853

1854
double ParserDriver::get_arg_for_coordinate(const std::string& str)
1855
{
80✔
1856
    REALM_ASSERT(str[0] == '$');
80✔
1857
    size_t arg_no = size_t(strtol(str.substr(1).c_str(), nullptr, 10));
80✔
1858
    if (m_args.is_argument_null(arg_no)) {
80✔
1859
        throw InvalidQueryError(util::format("NULL cannot be used in coordinate at argument '%1'", str));
4✔
1860
    }
4✔
1861
    if (m_args.is_argument_list(arg_no)) {
76✔
1862
        throw InvalidQueryError(util::format("A list cannot be used in a coordinate at argument '%1'", str));
×
1863
    }
×
1864

1865
    auto type = m_args.type_for_argument(arg_no);
76✔
1866
    switch (type) {
76✔
1867
        case type_Int:
✔
1868
            return double(m_args.long_for_argument(arg_no));
×
1869
        case type_Double:
68✔
1870
            return m_args.double_for_argument(arg_no);
68✔
1871
        case type_Float:
✔
1872
            return double(m_args.float_for_argument(arg_no));
×
1873
        default:
8✔
1874
            throw InvalidQueryError(util::format("Invalid parameter '%1' used in coordinate at argument '%2'",
8✔
1875
                                                 get_data_type_name(type), str));
8✔
1876
    }
76✔
1877
}
76✔
1878

1879
auto ParserDriver::cmp(const std::vector<ExpressionNode*>& values) -> std::pair<SubexprPtr, SubexprPtr>
1880
{
476,064✔
1881
    SubexprPtr left;
476,064✔
1882
    SubexprPtr right;
476,064✔
1883

1884
    auto left_is_constant = values[0]->is_constant();
476,064✔
1885
    auto right_is_constant = values[1]->is_constant();
476,064✔
1886

1887
    if (left_is_constant && right_is_constant) {
476,064✔
1888
        throw InvalidQueryError("Cannot compare two constants");
×
1889
    }
×
1890

1891
    if (right_is_constant) {
476,064✔
1892
        // Take left first - it cannot be a constant
1893
        left = values[0]->visit(this);
471,992✔
1894
        right = values[1]->visit(this, left->get_type());
471,992✔
1895
        verify_conditions(left.get(), right.get(), m_serializer_state);
471,992✔
1896
    }
471,992✔
1897
    else {
4,072✔
1898
        right = values[1]->visit(this);
4,072✔
1899
        if (left_is_constant) {
4,072✔
1900
            left = values[0]->visit(this, right->get_type());
1,492✔
1901
        }
1,492✔
1902
        else {
2,580✔
1903
            left = values[0]->visit(this);
2,580✔
1904
        }
2,580✔
1905
        verify_conditions(right.get(), left.get(), m_serializer_state);
4,072✔
1906
    }
4,072✔
1907
    return {std::move(left), std::move(right)};
476,064✔
1908
}
476,064✔
1909

1910
auto ParserDriver::column(LinkChain& link_chain, PathNode* path) -> SubexprPtr
1911
{
478,662✔
1912
    if (path->at_end()) {
478,662✔
1913
        // This is a link property. We can optimize by usingColumns<Link>.
1914
        // However Columns<Link> does not handle @keys and indexes
1915
        auto extended_col_key = link_chain.m_link_cols.back();
1,796✔
1916
        if (!extended_col_key.has_index()) {
1,796✔
1917
            return link_chain.create_subexpr<Link>(ColKey(extended_col_key));
1,792✔
1918
        }
1,792✔
1919
        link_chain.pop_back();
4✔
1920
        --path->current_path_elem;
4✔
1921
        --path->current_path_elem;
4✔
1922
    }
4✔
1923
    auto identifier = m_mapping.translate(link_chain, path->next_identifier());
476,870✔
1924
    if (auto col = link_chain.column(identifier, !path->at_end())) {
476,870✔
1925
        return col;
476,708✔
1926
    }
476,708✔
1927
    throw InvalidQueryError(
162✔
1928
        util::format("'%1' has no property '%2'", link_chain.get_current_table()->get_class_name(), identifier));
162✔
1929
}
476,870✔
1930

1931
void ParserDriver::backlink(LinkChain& link_chain, std::string_view raw_table_name, std::string_view raw_column_name)
1932
{
504✔
1933
    std::string table_name = m_mapping.translate_table_name(raw_table_name);
504✔
1934
    auto origin_table = m_base_table->get_parent_group()->get_table(table_name);
504✔
1935
    ColKey origin_column;
504✔
1936
    std::string column_name{raw_column_name};
504✔
1937
    if (origin_table) {
504✔
1938
        column_name = m_mapping.translate(origin_table, column_name);
496✔
1939
        origin_column = origin_table->get_column_key(column_name);
496✔
1940
    }
496✔
1941
    if (!origin_column) {
504✔
1942
        auto origin_table_name = Group::table_name_to_class_name(table_name);
12✔
1943
        auto current_table_name = link_chain.get_current_table()->get_class_name();
12✔
1944
        throw InvalidQueryError(util::format("No property '%1' found in type '%2' which links to type '%3'",
12✔
1945
                                             column_name, origin_table_name, current_table_name));
12✔
1946
    }
12✔
1947
    link_chain.backlink(*origin_table, origin_column);
492✔
1948
}
492✔
1949

1950
std::string ParserDriver::translate(const LinkChain& link_chain, const std::string& identifier)
1951
{
497,286✔
1952
    return m_mapping.translate(link_chain, identifier);
497,286✔
1953
}
497,286✔
1954

1955
int ParserDriver::parse(const std::string& str)
1956
{
46,660✔
1957
    // std::cout << str << std::endl;
1958
    parse_buffer.append(str);
46,660✔
1959
    parse_buffer.append("\0\0", 2); // Flex requires 2 terminating zeroes
46,660✔
1960
    scan_begin(m_yyscanner, trace_scanning);
46,660✔
1961
    yy::parser parse(*this, m_yyscanner);
46,660✔
1962
    parse.set_debug_level(trace_parsing);
46,660✔
1963
    int res = parse();
46,660✔
1964
    if (parse_error) {
46,660✔
1965
        throw SyntaxError(util::format("Invalid predicate: '%1': %2", str, error_string));
724✔
1966
    }
724✔
1967
    return res;
45,936✔
1968
}
46,660✔
1969

1970
void parse(const std::string& str)
1971
{
1,004✔
1972
    ParserDriver driver;
1,004✔
1973
    driver.parse(str);
1,004✔
1974
}
1,004✔
1975

1976
std::string check_escapes(const char* str)
1977
{
498,682✔
1978
    std::string ret;
498,682✔
1979
    const char* p = strchr(str, '\\');
498,682✔
1980
    while (p) {
499,106✔
1981
        ret += std::string(str, p);
424✔
1982
        p++;
424✔
1983
        if (*p == ' ') {
424✔
1984
            ret += ' ';
144✔
1985
        }
144✔
1986
        else if (*p == 't') {
280✔
1987
            ret += '\t';
280✔
1988
        }
280✔
1989
        else if (*p == 'r') {
×
1990
            ret += '\r';
×
1991
        }
×
1992
        else if (*p == 'n') {
×
1993
            ret += '\n';
×
1994
        }
×
1995
        str = p + 1;
424✔
1996
        p = strchr(str, '\\');
424✔
1997
    }
424✔
1998
    return ret + std::string(str);
498,682✔
1999
}
498,682✔
2000

2001
} // namespace query_parser
2002

2003
Query Table::query(const std::string& query_string, const std::vector<MixedArguments::Arg>& arguments) const
2004
{
12,174✔
2005
    MixedArguments args(arguments);
12,174✔
2006
    return query(query_string, args, {});
12,174✔
2007
}
12,174✔
2008

2009
Query Table::query(const std::string& query_string, const std::vector<Mixed>& arguments) const
2010
{
24✔
2011
    MixedArguments args(arguments);
24✔
2012
    return query(query_string, args, {});
24✔
2013
}
24✔
2014

2015
Query Table::query(const std::string& query_string, const std::vector<Mixed>& arguments,
2016
                   const query_parser::KeyPathMapping& mapping) const
2017
{
1,784✔
2018
    MixedArguments args(arguments);
1,784✔
2019
    return query(query_string, args, mapping);
1,784✔
2020
}
1,784✔
2021

2022
Query Table::query(const std::string& query_string, const std::vector<MixedArguments::Arg>& arguments,
2023
                   const query_parser::KeyPathMapping& mapping) const
2024
{
352✔
2025
    MixedArguments args(arguments);
352✔
2026
    return query(query_string, args, mapping);
352✔
2027
}
352✔
2028

2029
Query Table::query(const std::string& query_string, query_parser::Arguments& args,
2030
                   const query_parser::KeyPathMapping& mapping) const
2031
{
45,638✔
2032
    ParserDriver driver(m_own_ref, args, mapping);
45,638✔
2033
    driver.parse(query_string);
45,638✔
2034
    driver.result->canonicalize();
45,638✔
2035
    return driver.result->visit(&driver).set_ordering(driver.ordering->visit(&driver));
45,638✔
2036
}
45,638✔
2037

2038
std::unique_ptr<Subexpr> LinkChain::column(const std::string& col, bool has_path)
2039
{
478,586✔
2040
    auto col_key = m_current_table->get_column_key(col);
478,586✔
2041
    if (!col_key) {
478,586✔
2042
        return nullptr;
128✔
2043
    }
128✔
2044

2045
    auto col_type{col_key.get_type()};
478,458✔
2046
    if (col_key.is_dictionary()) {
478,458✔
2047
        return create_subexpr<Dictionary>(col_key);
984✔
2048
    }
984✔
2049
    if (Table::is_link_type(col_type)) {
477,474✔
2050
        add(col_key);
×
2051
        return create_subexpr<Link>(col_key);
×
2052
    }
×
2053

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

2126
        switch (col_type) {
456,966✔
2127
            case col_type_Int:
14,026✔
2128
                return create_subexpr<Int>(col_key);
14,026✔
2129
            case col_type_Bool:
224✔
2130
                return create_subexpr<Bool>(col_key);
224✔
2131
            case col_type_String:
4,800✔
2132
                return create_subexpr<String>(col_key);
4,800✔
2133
            case col_type_Binary:
2,052✔
2134
                return create_subexpr<Binary>(col_key);
2,052✔
2135
            case col_type_Float:
552✔
2136
                return create_subexpr<Float>(col_key);
552✔
2137
            case col_type_Double:
1,944✔
2138
                return create_subexpr<Double>(col_key);
1,944✔
2139
            case col_type_Timestamp:
728✔
2140
                return create_subexpr<Timestamp>(col_key);
728✔
2141
            case col_type_Decimal:
1,484✔
2142
                return create_subexpr<Decimal>(col_key);
1,484✔
2143
            case col_type_UUID:
520✔
2144
                return create_subexpr<UUID>(col_key);
520✔
2145
            case col_type_ObjectId:
428,804✔
2146
                return create_subexpr<ObjectId>(col_key);
428,804✔
2147
            case col_type_Mixed:
1,836✔
2148
                return create_subexpr<Mixed>(col_key);
1,836✔
2149
            default:
✔
2150
                break;
×
2151
        }
456,966✔
2152
    }
456,966✔
2153
    REALM_UNREACHABLE();
2154
    return nullptr;
×
2155
}
477,474✔
2156

2157
std::unique_ptr<Subexpr> LinkChain::subquery(Query subquery)
2158
{
280✔
2159
    REALM_ASSERT(m_link_cols.size() > 0);
280✔
2160
    auto col_key = m_link_cols.back();
280✔
2161
    return std::make_unique<SubQueryCount>(subquery, Columns<Link>(col_key, m_base_table, m_link_cols).link_map());
280✔
2162
}
280✔
2163

2164
template <class T>
2165
SubQuery<T> column(const Table& origin, ColKey origin_col_key, Query subquery)
2166
{
2167
    static_assert(std::is_same<T, BackLink>::value, "A subquery must involve a link list or backlink column");
2168
    return SubQuery<T>(column<T>(origin, origin_col_key), std::move(subquery));
2169
}
2170

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