123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467 |
- #import "RLMQueryUtil.hpp"
- #import "RLMArray.h"
- #import "RLMObjectSchema_Private.h"
- #import "RLMObject_Private.hpp"
- #import "RLMPredicateUtil.hpp"
- #import "RLMProperty_Private.h"
- #import "RLMSchema.h"
- #import "RLMUtil.hpp"
- #import "object_store.hpp"
- #import "results.hpp"
- #include <realm/query_engine.hpp>
- #include <realm/query_expression.hpp>
- #include <realm/util/cf_ptr.hpp>
- #include <realm/util/overload.hpp>
- using namespace realm;
- NSString * const RLMPropertiesComparisonTypeMismatchException = @"RLMPropertiesComparisonTypeMismatchException";
- NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException = @"RLMUnsupportedTypesFoundInPropertyComparisonException";
- NSString * const RLMPropertiesComparisonTypeMismatchReason = @"Property type mismatch between %@ and %@";
- NSString * const RLMUnsupportedTypesFoundInPropertyComparisonReason = @"Comparison between %@ and %@";
- static NSException *RLMPredicateException(NSString *name, NSString *format, ...) {
- va_list args;
- va_start(args, format);
- NSString *reason = [[NSString alloc] initWithFormat:format arguments:args];
- va_end(args);
- return [NSException exceptionWithName:name reason:reason userInfo:nil];
- }
- static void RLMPrecondition(bool condition, NSString *name, NSString *format, ...) {
- if (__builtin_expect(condition, 1)) {
- return;
- }
- va_list args;
- va_start(args, format);
- NSString *reason = [[NSString alloc] initWithFormat:format arguments:args];
- va_end(args);
- @throw [NSException exceptionWithName:name reason:reason userInfo:nil];
- }
- RLMProperty *RLMValidatedProperty(RLMObjectSchema *desc, NSString *columnName) {
- RLMProperty *prop = desc[columnName];
- RLMPrecondition(prop, @"Invalid property name",
- @"Property '%@' not found in object of type '%@'", columnName, desc.className);
- return prop;
- }
- namespace {
- BOOL RLMPropertyTypeIsNumeric(RLMPropertyType propertyType) {
- switch (propertyType) {
- case RLMPropertyTypeInt:
- case RLMPropertyTypeFloat:
- case RLMPropertyTypeDouble:
- return YES;
- default:
- return NO;
- }
- }
- bool equal(CFStringCompareFlags options, StringData v1, StringData v2)
- {
- if (v1.is_null() || v2.is_null()) {
- return v1.is_null() == v2.is_null();
- }
- auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(),
- kCFStringEncodingUTF8, false, kCFAllocatorNull));
- auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(),
- kCFStringEncodingUTF8, false, kCFAllocatorNull));
- return CFStringCompare(s1.get(), s2.get(), options) == kCFCompareEqualTo;
- }
- template <CFStringCompareFlags options>
- struct Equal {
- using CaseSensitive = Equal<options & ~kCFCompareCaseInsensitive>;
- using CaseInsensitive = Equal<options | kCFCompareCaseInsensitive>;
- bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const
- {
- REALM_ASSERT_DEBUG(v1_null == v1.is_null());
- REALM_ASSERT_DEBUG(v2_null == v2.is_null());
- return equal(options, v1, v2);
- }
- static const char* description() { return options & kCFCompareCaseInsensitive ? "==[cd]" : "==[d]"; }
- };
- bool contains_substring(CFStringCompareFlags options, StringData v1, StringData v2)
- {
- if (v2.is_null()) {
-
- return true;
- }
- if (v1.is_null()) {
-
- return false;
- }
- if (v2.size() == 0) {
-
- return true;
- }
- auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(),
- kCFStringEncodingUTF8, false, kCFAllocatorNull));
- auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(),
- kCFStringEncodingUTF8, false, kCFAllocatorNull));
- return CFStringFind(s1.get(), s2.get(), options).location != kCFNotFound;
- }
- template <CFStringCompareFlags options>
- struct ContainsSubstring {
- using CaseSensitive = ContainsSubstring<options & ~kCFCompareCaseInsensitive>;
- using CaseInsensitive = ContainsSubstring<options | kCFCompareCaseInsensitive>;
- bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const
- {
- REALM_ASSERT_DEBUG(v1_null == v1.is_null());
- REALM_ASSERT_DEBUG(v2_null == v2.is_null());
- return contains_substring(options, v1, v2);
- }
- static const char* description() { return options & kCFCompareCaseInsensitive ? "CONTAINS[cd]" : "CONTAINS[d]"; }
- };
- NSString *operatorName(NSPredicateOperatorType operatorType)
- {
- switch (operatorType) {
- case NSLessThanPredicateOperatorType:
- return @"<";
- case NSLessThanOrEqualToPredicateOperatorType:
- return @"<=";
- case NSGreaterThanPredicateOperatorType:
- return @">";
- case NSGreaterThanOrEqualToPredicateOperatorType:
- return @">=";
- case NSEqualToPredicateOperatorType:
- return @"==";
- case NSNotEqualToPredicateOperatorType:
- return @"!=";
- case NSMatchesPredicateOperatorType:
- return @"MATCHES";
- case NSLikePredicateOperatorType:
- return @"LIKE";
- case NSBeginsWithPredicateOperatorType:
- return @"BEGINSWITH";
- case NSEndsWithPredicateOperatorType:
- return @"ENDSWITH";
- case NSInPredicateOperatorType:
- return @"IN";
- case NSContainsPredicateOperatorType:
- return @"CONTAINS";
- case NSBetweenPredicateOperatorType:
- return @"BETWEEN";
- case NSCustomSelectorPredicateOperatorType:
- return @"custom selector";
- }
- return [NSString stringWithFormat:@"unknown operator %lu", (unsigned long)operatorType];
- }
- Table& get_table(Group& group, RLMObjectSchema *objectSchema)
- {
- return *ObjectStore::table_for_object_type(group, objectSchema.objectName.UTF8String);
- }
- class ColumnReference {
- public:
- ColumnReference(Query& query, Group& group, RLMSchema *schema, RLMProperty* property, const std::vector<RLMProperty*>& links = {})
- : m_links(links), m_property(property), m_schema(schema), m_group(&group), m_query(&query), m_table(query.get_table())
- {
- auto& table = walk_link_chain([](Table const&, ColKey, RLMPropertyType) { });
- m_col = table.get_column_key(m_property.columnName.UTF8String);
- }
- template <typename T, typename... SubQuery>
- auto resolve(SubQuery&&... subquery) const
- {
- static_assert(sizeof...(SubQuery) < 2, "resolve() takes at most one subquery");
- LinkChain lc(m_table);
- walk_link_chain([&](Table const& link_origin, ColKey col, RLMPropertyType type) {
- if (type != RLMPropertyTypeLinkingObjects) {
- lc.link(col);
- }
- else {
- lc.backlink(link_origin, col);
- }
- });
- if (type() != RLMPropertyTypeLinkingObjects) {
- return lc.column<T>(column(), std::forward<SubQuery>(subquery)...);
- }
- if constexpr (std::is_same_v<T, Link>) {
- return with_link_origin(m_property, [&](Table& table, ColKey col) {
- return lc.column<T>(table, col, std::forward<SubQuery>(subquery)...);
- });
- }
- REALM_TERMINATE("LinkingObjects property did not have column type Link");
- }
- RLMProperty *property() const { return m_property; }
- ColKey column() const { return m_col; }
- RLMPropertyType type() const { return property().type; }
- Group& group() const { return *m_group; }
- RLMObjectSchema *link_target_object_schema() const
- {
- switch (type()) {
- case RLMPropertyTypeObject:
- case RLMPropertyTypeLinkingObjects:
- return m_schema[property().objectClassName];
- default:
- REALM_UNREACHABLE();
- }
- }
- bool has_links() const { return m_links.size(); }
- bool has_any_to_many_links() const {
- return std::any_of(begin(m_links), end(m_links),
- [](RLMProperty *property) { return property.array; });
- }
- ColumnReference last_link_column() const {
- REALM_ASSERT(!m_links.empty());
- return {*m_query, *m_group, m_schema, m_links.back(), {m_links.begin(), m_links.end() - 1}};
- }
- ColumnReference column_ignoring_links(Query& query) const {
- return {query, *m_group, m_schema, m_property};
- }
- private:
- template<typename Func>
- Table const& walk_link_chain(Func&& func) const
- {
- auto table = m_query->get_table().unchecked_ptr();
- for (const auto& link : m_links) {
- if (link.type != RLMPropertyTypeLinkingObjects) {
- auto index = table->get_column_key(link.columnName.UTF8String);
- func(*table, index, link.type);
- table = table->get_link_target(index).unchecked_ptr();
- }
- else {
- with_link_origin(link, [&](Table& link_origin_table, ColKey link_origin_column) {
- func(link_origin_table, link_origin_column, link.type);
- table = &link_origin_table;
- });
- }
- }
- return *table;
- }
- template<typename Func>
- auto with_link_origin(RLMProperty *prop, Func&& func) const
- {
- RLMObjectSchema *link_origin_schema = m_schema[prop.objectClassName];
- Table& link_origin_table = get_table(*m_group, link_origin_schema);
- NSString *column_name = link_origin_schema[prop.linkOriginPropertyName].columnName;
- auto link_origin_column = link_origin_table.get_column_key(column_name.UTF8String);
- return func(link_origin_table, link_origin_column);
- }
- std::vector<RLMProperty*> m_links;
- RLMProperty *m_property;
- RLMSchema *m_schema;
- Group *m_group;
- Query *m_query;
- ConstTableRef m_table;
- ColKey m_col;
- };
- class CollectionOperation {
- public:
- enum Type {
- Count,
- Minimum,
- Maximum,
- Sum,
- Average,
- };
- CollectionOperation(Type type, ColumnReference link_column, util::Optional<ColumnReference> column)
- : m_type(type)
- , m_link_column(std::move(link_column))
- , m_column(std::move(column))
- {
- RLMPrecondition(m_link_column.property().array,
- @"Invalid predicate", @"Collection operation can only be applied to a property of type RLMArray.");
- switch (m_type) {
- case Count:
- RLMPrecondition(!m_column, @"Invalid predicate", @"Result of @count does not have any properties.");
- break;
- case Minimum:
- case Maximum:
- case Sum:
- case Average:
- RLMPrecondition(m_column && RLMPropertyTypeIsNumeric(m_column->type()), @"Invalid predicate",
- @"%@ can only be applied to a numeric property.", name_for_type(m_type));
- break;
- }
- }
- CollectionOperation(NSString *operationName, ColumnReference link_column, util::Optional<ColumnReference> column = util::none)
- : CollectionOperation(type_for_name(operationName), std::move(link_column), std::move(column))
- {
- }
- Type type() const { return m_type; }
- const ColumnReference& link_column() const { return m_link_column; }
- const ColumnReference& column() const { return *m_column; }
- void validate_comparison(id value) const {
- switch (m_type) {
- case Count:
- case Average:
- RLMPrecondition([value isKindOfClass:[NSNumber class]], @"Invalid operand",
- @"%@ can only be compared with a numeric value.", name_for_type(m_type));
- break;
- case Minimum:
- case Maximum:
- case Sum:
- RLMPrecondition(RLMIsObjectValidForProperty(value, m_column->property()), @"Invalid operand",
- @"%@ on a property of type %@ cannot be compared with '%@'",
- name_for_type(m_type), RLMTypeToString(m_column->type()), value);
- break;
- }
- }
- void validate_comparison(const ColumnReference& column) const {
- switch (m_type) {
- case Count:
- RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand",
- @"%@ can only be compared with a numeric value.", name_for_type(m_type));
- break;
- case Average:
- case Minimum:
- case Maximum:
- case Sum:
- RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand",
- @"%@ on a property of type %@ cannot be compared with property of type '%@'",
- name_for_type(m_type), RLMTypeToString(m_column->type()), RLMTypeToString(column.type()));
- break;
- }
- }
- private:
- static Type type_for_name(NSString *name) {
- if ([name isEqualToString:@"@count"]) {
- return Count;
- }
- if ([name isEqualToString:@"@min"]) {
- return Minimum;
- }
- if ([name isEqualToString:@"@max"]) {
- return Maximum;
- }
- if ([name isEqualToString:@"@sum"]) {
- return Sum;
- }
- if ([name isEqualToString:@"@avg"]) {
- return Average;
- }
- @throw RLMPredicateException(@"Invalid predicate", @"Unsupported collection operation '%@'", name);
- }
- static NSString *name_for_type(Type type) {
- switch (type) {
- case Count: return @"@count";
- case Minimum: return @"@min";
- case Maximum: return @"@max";
- case Sum: return @"@sum";
- case Average: return @"@avg";
- }
- }
- Type m_type;
- ColumnReference m_link_column;
- util::Optional<ColumnReference> m_column;
- };
- class QueryBuilder {
- public:
- QueryBuilder(Query& query, Group& group, RLMSchema *schema)
- : m_query(query), m_group(group), m_schema(schema) { }
- void apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema);
- void apply_collection_operator_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred);
- void apply_value_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred);
- void apply_column_expression(RLMObjectSchema *desc, NSString *leftKeyPath, NSString *rightKeyPath, NSComparisonPredicate *predicate);
- void apply_subquery_count_expression(RLMObjectSchema *objectSchema, NSExpression *subqueryExpression,
- NSPredicateOperatorType operatorType, NSExpression *right);
- void apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
- NSPredicateOperatorType operatorType, NSExpression *right);
- void apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
- NSPredicateOperatorType operatorType, NSExpression *right);
- template <typename A, typename B>
- void add_numeric_constraint(RLMPropertyType datatype,
- NSPredicateOperatorType operatorType,
- A&& lhs, B&& rhs);
- template <typename A, typename B>
- void add_bool_constraint(NSPredicateOperatorType operatorType, A&& lhs, B&& rhs);
- void add_substring_constraint(null, Query condition);
- template<typename T>
- void add_substring_constraint(const T& value, Query condition);
- template<typename T>
- void add_substring_constraint(const Columns<T>& value, Query condition);
- template <typename T>
- void add_string_constraint(NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions,
- Columns<String> &&column,
- T value);
- void add_string_constraint(NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions,
- StringData value,
- Columns<String>&& column);
- template <typename L, typename R>
- void add_constraint(RLMPropertyType type,
- NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions,
- L const& lhs, R const& rhs);
- template <typename... T>
- void do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions, T&&... values);
- void do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null);
- void add_between_constraint(const ColumnReference& column, id value);
- void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, BinaryData value);
- void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value);
- void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null);
- void add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column);
- void add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&);
- void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, RLMObjectBase *obj);
- void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, realm::null);
- template<typename T>
- void add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column);
- void add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&);
- template <CollectionOperation::Type Operation, typename... T>
- void add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values);
- template <typename... T>
- void add_collection_operation_constraint(NSPredicateOperatorType operatorType,
- CollectionOperation collectionOperation, T... values);
- CollectionOperation collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath);
- ColumnReference column_reference_from_key_path(RLMObjectSchema *objectSchema, NSString *keyPath, bool isAggregate);
- private:
- Query& m_query;
- Group& m_group;
- RLMSchema *m_schema;
- };
- template <typename A, typename B>
- void QueryBuilder::add_numeric_constraint(RLMPropertyType datatype,
- NSPredicateOperatorType operatorType,
- A&& lhs, B&& rhs)
- {
- switch (operatorType) {
- case NSLessThanPredicateOperatorType:
- m_query.and_query(lhs < rhs);
- break;
- case NSLessThanOrEqualToPredicateOperatorType:
- m_query.and_query(lhs <= rhs);
- break;
- case NSGreaterThanPredicateOperatorType:
- m_query.and_query(lhs > rhs);
- break;
- case NSGreaterThanOrEqualToPredicateOperatorType:
- m_query.and_query(lhs >= rhs);
- break;
- case NSEqualToPredicateOperatorType:
- m_query.and_query(lhs == rhs);
- break;
- case NSNotEqualToPredicateOperatorType:
- m_query.and_query(lhs != rhs);
- break;
- default:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator '%@' not supported for type %@",
- operatorName(operatorType), RLMTypeToString(datatype));
- }
- }
- template <typename A, typename B>
- void QueryBuilder::add_bool_constraint(NSPredicateOperatorType operatorType, A&& lhs, B&& rhs) {
- switch (operatorType) {
- case NSEqualToPredicateOperatorType:
- m_query.and_query(lhs == rhs);
- break;
- case NSNotEqualToPredicateOperatorType:
- m_query.and_query(lhs != rhs);
- break;
- default:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator '%@' not supported for bool type", operatorName(operatorType));
- }
- }
- void QueryBuilder::add_substring_constraint(null, Query) {
-
- m_query.and_query(std::unique_ptr<Expression>(new FalseExpression));
- }
- template<typename T>
- void QueryBuilder::add_substring_constraint(const T& value, Query condition) {
-
- m_query.and_query(value.size()
- ? std::move(condition)
- : std::unique_ptr<Expression>(new FalseExpression));
- }
- template<typename T>
- void QueryBuilder::add_substring_constraint(const Columns<T>& value, Query condition) {
-
-
-
- m_query.and_query(const_cast<Columns<String>&>(value).size() != 0 && std::move(condition));
- }
- template <typename T>
- void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions,
- Columns<String> &&column,
- T value) {
- bool caseSensitive = !(predicateOptions & NSCaseInsensitivePredicateOption);
- bool diacriticSensitive = !(predicateOptions & NSDiacriticInsensitivePredicateOption);
- if (diacriticSensitive) {
- switch (operatorType) {
- case NSBeginsWithPredicateOperatorType:
- add_substring_constraint(value, column.begins_with(value, caseSensitive));
- break;
- case NSEndsWithPredicateOperatorType:
- add_substring_constraint(value, column.ends_with(value, caseSensitive));
- break;
- case NSContainsPredicateOperatorType:
- add_substring_constraint(value, column.contains(value, caseSensitive));
- break;
- case NSEqualToPredicateOperatorType:
- m_query.and_query(column.equal(value, caseSensitive));
- break;
- case NSNotEqualToPredicateOperatorType:
- m_query.and_query(column.not_equal(value, caseSensitive));
- break;
- case NSLikePredicateOperatorType:
- m_query.and_query(column.like(value, caseSensitive));
- break;
- default:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator '%@' not supported for string type",
- operatorName(operatorType));
- }
- return;
- }
- auto as_subexpr = util::overload([](StringData value) { return make_subexpr<ConstantStringValue>(value); },
- [](const Columns<String>& c) { return c.clone(); });
- auto left = as_subexpr(column);
- auto right = as_subexpr(value);
- auto make_constraint = [&](auto comparator) {
- using Comparator = decltype(comparator);
- using CompareCS = Compare<typename Comparator::CaseSensitive, StringData>;
- using CompareCI = Compare<typename Comparator::CaseInsensitive, StringData>;
- if (caseSensitive) {
- return make_expression<CompareCS>(std::move(left), std::move(right));
- }
- else {
- return make_expression<CompareCI>(std::move(left), std::move(right));
- }
- };
- switch (operatorType) {
- case NSBeginsWithPredicateOperatorType: {
- using C = ContainsSubstring<kCFCompareDiacriticInsensitive | kCFCompareAnchored>;
- add_substring_constraint(value, make_constraint(C{}));
- break;
- }
- case NSEndsWithPredicateOperatorType: {
- using C = ContainsSubstring<kCFCompareDiacriticInsensitive | kCFCompareAnchored | kCFCompareBackwards>;
- add_substring_constraint(value, make_constraint(C{}));
- break;
- }
- case NSContainsPredicateOperatorType: {
- using C = ContainsSubstring<kCFCompareDiacriticInsensitive>;
- add_substring_constraint(value, make_constraint(C{}));
- break;
- }
- case NSNotEqualToPredicateOperatorType:
- m_query.Not();
- REALM_FALLTHROUGH;
- case NSEqualToPredicateOperatorType:
- m_query.and_query(make_constraint(Equal<kCFCompareDiacriticInsensitive>{}));
- break;
- case NSLikePredicateOperatorType:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator 'LIKE' not supported with diacritic-insensitive modifier.");
- default:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator '%@' not supported for string type", operatorName(operatorType));
- }
- }
- void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions,
- StringData value,
- Columns<String>&& column) {
- switch (operatorType) {
- case NSEqualToPredicateOperatorType:
- case NSNotEqualToPredicateOperatorType:
- add_string_constraint(operatorType, predicateOptions, std::move(column), value);
- break;
- default:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator '%@' is not supported for string type with key path on right side of operator",
- operatorName(operatorType));
- }
- }
- id value_from_constant_expression_or_value(id value) {
- if (NSExpression *exp = RLMDynamicCast<NSExpression>(value)) {
- RLMPrecondition(exp.expressionType == NSConstantValueExpressionType,
- @"Invalid value",
- @"Expressions within predicate aggregates must be constant values");
- return exp.constantValue;
- }
- return value;
- }
- void validate_and_extract_between_range(id value, RLMProperty *prop, id *from, id *to) {
- NSArray *array = RLMDynamicCast<NSArray>(value);
- RLMPrecondition(array, @"Invalid value", @"object must be of type NSArray for BETWEEN operations");
- RLMPrecondition(array.count == 2, @"Invalid value", @"NSArray object must contain exactly two objects for BETWEEN operations");
- *from = value_from_constant_expression_or_value(array.firstObject);
- *to = value_from_constant_expression_or_value(array.lastObject);
- RLMPrecondition(RLMIsObjectValidForProperty(*from, prop) && RLMIsObjectValidForProperty(*to, prop),
- @"Invalid value",
- @"NSArray objects must be of type %@ for BETWEEN operations", RLMTypeToString(prop.type));
- }
- void QueryBuilder::add_between_constraint(const ColumnReference& column, id value) {
- if (column.has_any_to_many_links()) {
- auto link_column = column.last_link_column();
- Query subquery = get_table(m_group, link_column.link_target_object_schema()).where();
- QueryBuilder(subquery, m_group, m_schema).add_between_constraint(column.column_ignoring_links(subquery), value);
- m_query.and_query(link_column.resolve<Link>(std::move(subquery)).count() > 0);
- return;
- }
- id from, to;
- validate_and_extract_between_range(value, column.property(), &from, &to);
- RLMPropertyType type = column.type();
- m_query.group();
- add_constraint(type, NSGreaterThanOrEqualToPredicateOperatorType, 0, column, from);
- add_constraint(type, NSLessThanOrEqualToPredicateOperatorType, 0, column, to);
- m_query.end_group();
- }
- void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType,
- const ColumnReference& column,
- BinaryData value) {
- RLMPrecondition(!column.has_links(), @"Unsupported operator", @"NSData properties cannot be queried over an object link.");
- auto index = column.column();
- Query query = m_query.get_table()->where();
- switch (operatorType) {
- case NSBeginsWithPredicateOperatorType:
- add_substring_constraint(value, query.begins_with(index, value));
- break;
- case NSEndsWithPredicateOperatorType:
- add_substring_constraint(value, query.ends_with(index, value));
- break;
- case NSContainsPredicateOperatorType:
- add_substring_constraint(value, query.contains(index, value));
- break;
- case NSEqualToPredicateOperatorType:
- m_query.equal(index, value);
- break;
- case NSNotEqualToPredicateOperatorType:
- m_query.not_equal(index, value);
- break;
- default:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator '%@' not supported for binary type", operatorName(operatorType));
- }
- }
- void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value) {
- add_binary_constraint(operatorType, column, RLMBinaryDataForNSData(value));
- }
- void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null) {
- add_binary_constraint(operatorType, column, BinaryData());
- }
- void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column) {
- switch (operatorType) {
- case NSEqualToPredicateOperatorType:
- case NSNotEqualToPredicateOperatorType:
- add_binary_constraint(operatorType, column, value);
- break;
- default:
- @throw RLMPredicateException(@"Invalid operator type",
- @"Operator '%@' is not supported for binary type with key path on right side of operator",
- operatorName(operatorType));
- }
- }
- void QueryBuilder::add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) {
- @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two NSData properties are not supported");
- }
- void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType,
- const ColumnReference& column, RLMObjectBase *obj) {
- RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType,
- @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison");
- if (!obj->_row.is_valid()) {
-
-
- struct FakeObj : public ConstObj {
- FakeObj(ColumnReference const& column) {
- m_table = TableRef::unsafe_create(&::get_table(column.group(), column.link_target_object_schema()));
- }
- } fake(column);
- add_bool_constraint(operatorType, column.resolve<Link>(), fake);
- }
- else {
- add_bool_constraint(operatorType, column.resolve<Link>(), obj->_row);
- }
- }
- void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType,
- const ColumnReference& column,
- realm::null) {
- RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType,
- @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison");
- add_bool_constraint(operatorType, column.resolve<Link>(), null());
- }
- template<typename T>
- void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column) {
-
-
- add_link_constraint(operatorType, column, obj);
- }
- void QueryBuilder::add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) {
-
-
- @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two RLMArray properties are not supported");
- }
- template<typename Func>
- void process_or_group(Query &query, id array, Func&& func) {
- array = RLMAsFastEnumeration(array);
- RLMPrecondition(array, @"Invalid value", @"IN clause requires an array of items");
- query.group();
- bool first = true;
- for (id item in array) {
- if (!first) {
- query.Or();
- }
- first = false;
- func(item);
- }
- if (first) {
-
-
-
- query.and_query(std::unique_ptr<Expression>(new FalseExpression));
- }
- query.end_group();
- }
- template <typename RequestedType>
- RequestedType convert(id value);
- template <>
- Timestamp convert<Timestamp>(id value) {
- return RLMTimestampForNSDate(value);
- }
- template <>
- bool convert<bool>(id value) {
- return [value boolValue];
- }
- template <>
- Double convert<Double>(id value) {
- return [value doubleValue];
- }
- template <>
- Float convert<Float>(id value) {
- return [value floatValue];
- }
- template <>
- Int convert<Int>(id value) {
- return [value longLongValue];
- }
- template <>
- String convert<String>(id value) {
- return RLMStringDataWithNSString(value);
- }
- template <typename>
- realm::null value_of_type(realm::null) {
- return realm::null();
- }
- template <typename RequestedType>
- auto value_of_type(id value) {
- return ::convert<RequestedType>(value);
- }
- template <typename RequestedType>
- auto value_of_type(const ColumnReference& column) {
- return column.resolve<RequestedType>();
- }
- template <typename... T>
- void QueryBuilder::do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions, T&&... values)
- {
- static_assert(sizeof...(T) == 2, "do_add_constraint accepts only two values as arguments");
- switch (type) {
- case RLMPropertyTypeBool:
- add_bool_constraint(operatorType, value_of_type<bool>(values)...);
- break;
- case RLMPropertyTypeDate:
- add_numeric_constraint(type, operatorType, value_of_type<realm::Timestamp>(values)...);
- break;
- case RLMPropertyTypeDouble:
- add_numeric_constraint(type, operatorType, value_of_type<Double>(values)...);
- break;
- case RLMPropertyTypeFloat:
- add_numeric_constraint(type, operatorType, value_of_type<Float>(values)...);
- break;
- case RLMPropertyTypeInt:
- add_numeric_constraint(type, operatorType, value_of_type<Int>(values)...);
- break;
- case RLMPropertyTypeString:
- add_string_constraint(operatorType, predicateOptions, value_of_type<String>(values)...);
- break;
- case RLMPropertyTypeData:
- add_binary_constraint(operatorType, values...);
- break;
- case RLMPropertyTypeObject:
- case RLMPropertyTypeLinkingObjects:
- add_link_constraint(operatorType, values...);
- break;
- default:
- @throw RLMPredicateException(@"Unsupported predicate value type",
- @"Object type %@ not supported", RLMTypeToString(type));
- }
- }
- void QueryBuilder::do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null)
- {
-
-
- @throw RLMPredicateException(@"Invalid predicate expressions",
- @"Predicate expressions must compare a keypath and another keypath or a constant value");
- }
- bool is_nsnull(id value) {
- return !value || value == NSNull.null;
- }
- template<typename T>
- bool is_nsnull(T) {
- return false;
- }
- template <typename L, typename R>
- void QueryBuilder::add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
- NSComparisonPredicateOptions predicateOptions, L const& lhs, R const& rhs)
- {
-
- RLMPrecondition(!is_nsnull(lhs), @"Unsupported operator",
- @"Nil is only supported on the right side of operators");
- if (is_nsnull(rhs)) {
- do_add_constraint(type, operatorType, predicateOptions, lhs, realm::null());
- }
- else {
- do_add_constraint(type, operatorType, predicateOptions, lhs, rhs);
- }
- }
- struct KeyPath {
- std::vector<RLMProperty *> links;
- RLMProperty *property;
- bool containsToManyRelationship;
- };
- KeyPath key_path_from_string(RLMSchema *schema, RLMObjectSchema *objectSchema, NSString *keyPath)
- {
- RLMProperty *property;
- std::vector<RLMProperty *> links;
- bool keyPathContainsToManyRelationship = false;
- NSUInteger start = 0, length = keyPath.length, end = NSNotFound;
- do {
- end = [keyPath rangeOfString:@"." options:0 range:{start, length - start}].location;
- NSString *propertyName = [keyPath substringWithRange:{start, end == NSNotFound ? length - start : end - start}];
- property = objectSchema[propertyName];
- RLMPrecondition(property, @"Invalid property name",
- @"Property '%@' not found in object of type '%@'",
- propertyName, objectSchema.className);
- if (property.array)
- keyPathContainsToManyRelationship = true;
- if (end != NSNotFound) {
- RLMPrecondition(property.type == RLMPropertyTypeObject || property.type == RLMPropertyTypeLinkingObjects,
- @"Invalid value", @"Property '%@' is not a link in object of type '%@'",
- propertyName, objectSchema.className);
- links.push_back(property);
- REALM_ASSERT(property.objectClassName);
- objectSchema = schema[property.objectClassName];
- }
- start = end + 1;
- } while (end != NSNotFound);
- return {std::move(links), property, keyPathContainsToManyRelationship};
- }
- ColumnReference QueryBuilder::column_reference_from_key_path(RLMObjectSchema *objectSchema,
- NSString *keyPathString, bool isAggregate)
- {
- auto keyPath = key_path_from_string(m_schema, objectSchema, keyPathString);
- if (isAggregate && !keyPath.containsToManyRelationship) {
- @throw RLMPredicateException(@"Invalid predicate",
- @"Aggregate operations can only be used on key paths that include an array property");
- } else if (!isAggregate && keyPath.containsToManyRelationship) {
- @throw RLMPredicateException(@"Invalid predicate",
- @"Key paths that include an array property must use aggregate operations");
- }
- return ColumnReference(m_query, m_group, m_schema, keyPath.property, std::move(keyPath.links));
- }
- void validate_property_value(const ColumnReference& column,
- __unsafe_unretained id const value,
- __unsafe_unretained NSString *const err,
- __unsafe_unretained RLMObjectSchema *const objectSchema,
- __unsafe_unretained NSString *const keyPath) {
- RLMProperty *prop = column.property();
- if (prop.array) {
- RLMPrecondition([RLMObjectBaseObjectSchema(RLMDynamicCast<RLMObjectBase>(value)).className isEqualToString:prop.objectClassName],
- @"Invalid value", err, prop.objectClassName, keyPath, objectSchema.className, value);
- }
- else {
- RLMPrecondition(RLMIsObjectValidForProperty(value, prop),
- @"Invalid value", err, RLMTypeToString(prop.type), keyPath, objectSchema.className, value);
- }
- if (RLMObjectBase *obj = RLMDynamicCast<RLMObjectBase>(value)) {
- RLMPrecondition(!obj->_row.is_valid() || &column.group() == &obj->_realm.group,
- @"Invalid value origin", @"Object must be from the Realm being queried");
- }
- }
- template <typename RequestedType, CollectionOperation::Type OperationType>
- struct ValueOfTypeWithCollectionOperationHelper;
- template <>
- struct ValueOfTypeWithCollectionOperationHelper<Int, CollectionOperation::Count> {
- static auto convert(const CollectionOperation& operation)
- {
- assert(operation.type() == CollectionOperation::Count);
- return operation.link_column().resolve<Link>().count();
- }
- };
- #define VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(OperationType, function) \
- template <typename T> \
- struct ValueOfTypeWithCollectionOperationHelper<T, OperationType> { \
- static auto convert(const CollectionOperation& operation) \
- { \
- REALM_ASSERT(operation.type() == OperationType); \
- auto targetColumn = operation.link_column().resolve<Link>().template column<T>(operation.column().column()); \
- return targetColumn.function(); \
- } \
- } \
- VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Minimum, min);
- VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Maximum, max);
- VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Sum, sum);
- VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Average, average);
- #undef VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER
- template <typename Requested, CollectionOperation::Type OperationType, typename T>
- auto value_of_type_with_collection_operation(T&& value) {
- return value_of_type<Requested>(std::forward<T>(value));
- }
- template <typename Requested, CollectionOperation::Type OperationType>
- auto value_of_type_with_collection_operation(CollectionOperation operation) {
- using helper = ValueOfTypeWithCollectionOperationHelper<Requested, OperationType>;
- return helper::convert(operation);
- }
- template <CollectionOperation::Type Operation, typename... T>
- void QueryBuilder::add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values)
- {
- switch (propertyType) {
- case RLMPropertyTypeInt:
- add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation<Int, Operation>(values)...);
- break;
- case RLMPropertyTypeFloat:
- add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation<Float, Operation>(values)...);
- break;
- case RLMPropertyTypeDouble:
- add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation<Double, Operation>(values)...);
- break;
- default:
- REALM_ASSERT(false && "Only numeric property types should hit this path.");
- }
- }
- template <typename... T>
- void QueryBuilder::add_collection_operation_constraint(NSPredicateOperatorType operatorType,
- CollectionOperation collectionOperation, T... values)
- {
- static_assert(sizeof...(T) == 2, "add_collection_operation_constraint accepts only two values as arguments");
- switch (collectionOperation.type()) {
- case CollectionOperation::Count:
- add_numeric_constraint(RLMPropertyTypeInt, operatorType,
- value_of_type_with_collection_operation<Int, CollectionOperation::Count>(values)...);
- break;
- case CollectionOperation::Minimum:
- add_collection_operation_constraint<CollectionOperation::Minimum>(collectionOperation.column().type(), operatorType, values...);
- break;
- case CollectionOperation::Maximum:
- add_collection_operation_constraint<CollectionOperation::Maximum>(collectionOperation.column().type(), operatorType, values...);
- break;
- case CollectionOperation::Sum:
- add_collection_operation_constraint<CollectionOperation::Sum>(collectionOperation.column().type(), operatorType, values...);
- break;
- case CollectionOperation::Average:
- add_collection_operation_constraint<CollectionOperation::Average>(collectionOperation.column().type(), operatorType, values...);
- break;
- }
- }
- bool key_path_contains_collection_operator(NSString *keyPath) {
- return [keyPath rangeOfString:@"@"].location != NSNotFound;
- }
- NSString *get_collection_operation_name_from_key_path(NSString *keyPath, NSString **leadingKeyPath,
- NSString **trailingKey) {
- NSRange at = [keyPath rangeOfString:@"@"];
- if (at.location == NSNotFound || at.location >= keyPath.length - 1) {
- @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath);
- }
- if (at.location == 0 || [keyPath characterAtIndex:at.location - 1] != '.') {
- @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath);
- }
- NSRange trailingKeyRange = [keyPath rangeOfString:@"." options:0 range:{at.location, keyPath.length - at.location} locale:nil];
- *leadingKeyPath = [keyPath substringToIndex:at.location - 1];
- if (trailingKeyRange.location == NSNotFound) {
- *trailingKey = nil;
- return [keyPath substringFromIndex:at.location];
- } else {
- *trailingKey = [keyPath substringFromIndex:trailingKeyRange.location + 1];
- return [keyPath substringWithRange:{at.location, trailingKeyRange.location - at.location}];
- }
- }
- CollectionOperation QueryBuilder::collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath) {
- NSString *leadingKeyPath;
- NSString *trailingKey;
- NSString *collectionOperationName = get_collection_operation_name_from_key_path(keyPath, &leadingKeyPath, &trailingKey);
- ColumnReference linkColumn = column_reference_from_key_path(desc, leadingKeyPath, true);
- util::Optional<ColumnReference> column;
- if (trailingKey) {
- RLMPrecondition([trailingKey rangeOfString:@"."].location == NSNotFound, @"Invalid key path",
- @"Right side of collection operator may only have a single level key");
- NSString *fullKeyPath = [leadingKeyPath stringByAppendingFormat:@".%@", trailingKey];
- column = column_reference_from_key_path(desc, fullKeyPath, true);
- }
- return {collectionOperationName, std::move(linkColumn), std::move(column)};
- }
- void QueryBuilder::apply_collection_operator_expression(RLMObjectSchema *desc,
- NSString *keyPath, id value,
- NSComparisonPredicate *pred) {
- CollectionOperation operation = collection_operation_from_key_path(desc, keyPath);
- operation.validate_comparison(value);
- if (pred.leftExpression.expressionType == NSKeyPathExpressionType) {
- add_collection_operation_constraint(pred.predicateOperatorType, operation, operation, value);
- } else {
- add_collection_operation_constraint(pred.predicateOperatorType, operation, value, operation);
- }
- }
- void QueryBuilder::apply_value_expression(RLMObjectSchema *desc,
- NSString *keyPath, id value,
- NSComparisonPredicate *pred)
- {
- if (key_path_contains_collection_operator(keyPath)) {
- apply_collection_operator_expression(desc, keyPath, value, pred);
- return;
- }
- bool isAny = pred.comparisonPredicateModifier == NSAnyPredicateModifier;
- ColumnReference column = column_reference_from_key_path(desc, keyPath, isAny);
-
- if (pred.predicateOperatorType == NSBetweenPredicateOperatorType) {
- add_between_constraint(std::move(column), value);
- return;
- }
-
- if (pred.predicateOperatorType == NSInPredicateOperatorType) {
- process_or_group(m_query, value, [&](id item) {
- id normalized = value_from_constant_expression_or_value(item);
- validate_property_value(column, normalized,
- @"Expected object of type %@ in IN clause for property '%@' on object of type '%@', but received: %@", desc, keyPath);
- add_constraint(column.type(), NSEqualToPredicateOperatorType, pred.options, column, normalized);
- });
- return;
- }
- validate_property_value(column, value, @"Expected object of type %@ for property '%@' on object of type '%@', but received: %@", desc, keyPath);
- if (pred.leftExpression.expressionType == NSKeyPathExpressionType) {
- add_constraint(column.type(), pred.predicateOperatorType, pred.options, std::move(column), value);
- } else {
- add_constraint(column.type(), pred.predicateOperatorType, pred.options, value, std::move(column));
- }
- }
- void QueryBuilder::apply_column_expression(RLMObjectSchema *desc,
- NSString *leftKeyPath, NSString *rightKeyPath,
- NSComparisonPredicate *predicate)
- {
- bool left_key_path_contains_collection_operator = key_path_contains_collection_operator(leftKeyPath);
- bool right_key_path_contains_collection_operator = key_path_contains_collection_operator(rightKeyPath);
- if (left_key_path_contains_collection_operator && right_key_path_contains_collection_operator) {
- @throw RLMPredicateException(@"Unsupported predicate", @"Key paths including aggregate operations cannot be compared with other aggregate operations.");
- }
- if (left_key_path_contains_collection_operator) {
- CollectionOperation left = collection_operation_from_key_path(desc, leftKeyPath);
- ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, false);
- left.validate_comparison(right);
- add_collection_operation_constraint(predicate.predicateOperatorType, left, left, std::move(right));
- return;
- }
- if (right_key_path_contains_collection_operator) {
- ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, false);
- CollectionOperation right = collection_operation_from_key_path(desc, rightKeyPath);
- right.validate_comparison(left);
- add_collection_operation_constraint(predicate.predicateOperatorType, right, std::move(left), right);
- return;
- }
- bool isAny = false;
- ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, isAny);
- ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, isAny);
-
- RLMPrecondition(left.type() == right.type(),
- RLMPropertiesComparisonTypeMismatchException,
- RLMPropertiesComparisonTypeMismatchReason,
- RLMTypeToString(left.type()),
- RLMTypeToString(right.type()));
-
- add_constraint(left.type(), predicate.predicateOperatorType, predicate.options,
- std::move(left), std::move(right));
- }
- bool is_self_value_for_key_path_function_expression(NSExpression *expression)
- {
- if (expression.expressionType != NSFunctionExpressionType)
- return false;
- if (expression.operand.expressionType != NSEvaluatedObjectExpressionType)
- return false;
- return [expression.function isEqualToString:@"valueForKeyPath:"];
- }
- NSExpression *simplify_self_value_for_key_path_function_expression(NSExpression *expression) {
- if (is_self_value_for_key_path_function_expression(expression)) {
- if (NSString *keyPath = [expression.arguments.firstObject keyPath]) {
- return [NSExpression expressionForKeyPath:keyPath];
- }
- }
- return expression;
- }
- void QueryBuilder::apply_subquery_count_expression(RLMObjectSchema *objectSchema,
- NSExpression *subqueryExpression, NSPredicateOperatorType operatorType, NSExpression *right) {
- if (right.expressionType != NSConstantValueExpressionType || ![right.constantValue isKindOfClass:[NSNumber class]]) {
- @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY(…).@count is only supported when compared with a constant number.");
- }
- int64_t value = [right.constantValue integerValue];
- ColumnReference collectionColumn = column_reference_from_key_path(objectSchema, [subqueryExpression.collection keyPath], true);
- RLMObjectSchema *collectionMemberObjectSchema = m_schema[collectionColumn.property().objectClassName];
-
- NSPredicate *subqueryPredicate = [subqueryExpression.predicate predicateWithSubstitutionVariables:@{ subqueryExpression.variable : [NSExpression expressionForEvaluatedObject] }];
- subqueryPredicate = transformPredicate(subqueryPredicate, simplify_self_value_for_key_path_function_expression);
- Query subquery = RLMPredicateToQuery(subqueryPredicate, collectionMemberObjectSchema, m_schema, m_group);
- add_numeric_constraint(RLMPropertyTypeInt, operatorType,
- collectionColumn.resolve<Link>(std::move(subquery)).count(), value);
- }
- void QueryBuilder::apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
- NSPredicateOperatorType operatorType, NSExpression *right) {
- if (![functionExpression.function isEqualToString:@"valueForKeyPath:"] || functionExpression.arguments.count != 1) {
- @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported on the result of a SUBQUERY.", functionExpression.function);
- }
- NSExpression *keyPathExpression = functionExpression.arguments.firstObject;
- if ([keyPathExpression.keyPath isEqualToString:@"@count"]) {
- apply_subquery_count_expression(objectSchema, functionExpression.operand, operatorType, right);
- } else {
- @throw RLMPredicateException(@"Invalid predicate", @"SUBQUERY is only supported when immediately followed by .@count that is compared with a constant number.");
- }
- }
- void QueryBuilder::apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
- NSPredicateOperatorType operatorType, NSExpression *right) {
- if (functionExpression.operand.expressionType == NSSubqueryExpressionType) {
- apply_function_subquery_expression(objectSchema, functionExpression, operatorType, right);
- } else {
- @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported.", functionExpression.function);
- }
- }
- void QueryBuilder::apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema)
- {
-
- if ([predicate isMemberOfClass:[NSCompoundPredicate class]]) {
- NSCompoundPredicate *comp = (NSCompoundPredicate *)predicate;
- switch ([comp compoundPredicateType]) {
- case NSAndPredicateType:
- if (comp.subpredicates.count) {
-
- m_query.group();
- for (NSPredicate *subp in comp.subpredicates) {
- apply_predicate(subp, objectSchema);
- }
- m_query.end_group();
- } else {
-
- m_query.and_query(std::unique_ptr<Expression>(new TrueExpression));
- }
- break;
- case NSOrPredicateType: {
-
- process_or_group(m_query, comp.subpredicates, [&](__unsafe_unretained NSPredicate *const subp) {
- apply_predicate(subp, objectSchema);
- });
- break;
- }
- case NSNotPredicateType:
-
- m_query.Not();
- apply_predicate(comp.subpredicates.firstObject, objectSchema);
- break;
- default:
- @throw RLMPredicateException(@"Invalid compound predicate type",
- @"Only support AND, OR and NOT predicate types");
- }
- }
- else if ([predicate isMemberOfClass:[NSComparisonPredicate class]]) {
- NSComparisonPredicate *compp = (NSComparisonPredicate *)predicate;
-
- RLMPrecondition(compp.comparisonPredicateModifier != NSAllPredicateModifier,
- @"Invalid predicate", @"ALL modifier not supported");
- NSExpressionType exp1Type = compp.leftExpression.expressionType;
- NSExpressionType exp2Type = compp.rightExpression.expressionType;
- if (compp.comparisonPredicateModifier == NSAnyPredicateModifier) {
-
- RLMPrecondition(exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType,
- @"Invalid predicate",
- @"Predicate with ANY modifier must compare a KeyPath with RLMArray with a value");
- }
- if (compp.predicateOperatorType == NSBetweenPredicateOperatorType || compp.predicateOperatorType == NSInPredicateOperatorType) {
-
- if (exp1Type == NSKeyPathExpressionType && (exp2Type == NSAggregateExpressionType || exp2Type == NSConstantValueExpressionType)) {
-
- exp2Type = NSConstantValueExpressionType;
- }
- else if (compp.predicateOperatorType == NSInPredicateOperatorType && exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) {
-
- compp = [NSComparisonPredicate predicateWithLeftExpression:compp.rightExpression rightExpression:compp.leftExpression
- modifier:NSAnyPredicateModifier type:NSEqualToPredicateOperatorType options:0];
- exp1Type = NSKeyPathExpressionType;
- exp2Type = NSConstantValueExpressionType;
- }
- else {
- if (compp.predicateOperatorType == NSBetweenPredicateOperatorType) {
- @throw RLMPredicateException(@"Invalid predicate",
- @"Predicate with BETWEEN operator must compare a KeyPath with an aggregate with two values");
- }
- else if (compp.predicateOperatorType == NSInPredicateOperatorType) {
- @throw RLMPredicateException(@"Invalid predicate",
- @"Predicate with IN operator must compare a KeyPath with an aggregate");
- }
- }
- }
- if (exp1Type == NSKeyPathExpressionType && exp2Type == NSKeyPathExpressionType) {
-
- apply_column_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.keyPath, compp);
- }
- else if (exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType) {
-
- apply_value_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.constantValue, compp);
- }
- else if (exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) {
-
- apply_value_expression(objectSchema, compp.rightExpression.keyPath, compp.leftExpression.constantValue, compp);
- }
- else if (exp1Type == NSFunctionExpressionType) {
- apply_function_expression(objectSchema, compp.leftExpression, compp.predicateOperatorType, compp.rightExpression);
- }
- else if (exp1Type == NSSubqueryExpressionType) {
-
- @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY is only supported when immediately followed by .@count.");
- }
- else {
- @throw RLMPredicateException(@"Invalid predicate expressions",
- @"Predicate expressions must compare a keypath and another keypath or a constant value");
- }
- }
- else if ([predicate isEqual:[NSPredicate predicateWithValue:YES]]) {
- m_query.and_query(std::unique_ptr<Expression>(new TrueExpression));
- } else if ([predicate isEqual:[NSPredicate predicateWithValue:NO]]) {
- m_query.and_query(std::unique_ptr<Expression>(new FalseExpression));
- }
- else {
-
- @throw RLMPredicateException(@"Invalid predicate",
- @"Only support compound, comparison, and constant predicates");
- }
- }
- }
- realm::Query RLMPredicateToQuery(NSPredicate *predicate, RLMObjectSchema *objectSchema,
- RLMSchema *schema, Group &group)
- {
- auto query = get_table(group, objectSchema).where();
-
- if (!predicate) {
- return query;
- }
- @autoreleasepool {
- QueryBuilder(query, group, schema).apply_predicate(predicate, objectSchema);
- }
-
- std::string validateMessage = query.validate();
- RLMPrecondition(validateMessage.empty(), @"Invalid query", @"%.*s",
- (int)validateMessage.size(), validateMessage.c_str());
- return query;
- }
|