RLMQueryUtil.mm 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 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. #import "RLMQueryUtil.hpp"
  19. #import "RLMArray.h"
  20. #import "RLMObjectSchema_Private.h"
  21. #import "RLMObject_Private.hpp"
  22. #import "RLMPredicateUtil.hpp"
  23. #import "RLMProperty_Private.h"
  24. #import "RLMSchema.h"
  25. #import "RLMUtil.hpp"
  26. #import "object_store.hpp"
  27. #import "results.hpp"
  28. #include <realm/query_engine.hpp>
  29. #include <realm/query_expression.hpp>
  30. #include <realm/util/cf_ptr.hpp>
  31. #include <realm/util/overload.hpp>
  32. using namespace realm;
  33. NSString * const RLMPropertiesComparisonTypeMismatchException = @"RLMPropertiesComparisonTypeMismatchException";
  34. NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException = @"RLMUnsupportedTypesFoundInPropertyComparisonException";
  35. NSString * const RLMPropertiesComparisonTypeMismatchReason = @"Property type mismatch between %@ and %@";
  36. NSString * const RLMUnsupportedTypesFoundInPropertyComparisonReason = @"Comparison between %@ and %@";
  37. // small helper to create the many exceptions thrown when parsing predicates
  38. static NSException *RLMPredicateException(NSString *name, NSString *format, ...) {
  39. va_list args;
  40. va_start(args, format);
  41. NSString *reason = [[NSString alloc] initWithFormat:format arguments:args];
  42. va_end(args);
  43. return [NSException exceptionWithName:name reason:reason userInfo:nil];
  44. }
  45. // check a precondition and throw an exception if it is not met
  46. // this should be used iff the condition being false indicates a bug in the caller
  47. // of the function checking its preconditions
  48. static void RLMPrecondition(bool condition, NSString *name, NSString *format, ...) {
  49. if (__builtin_expect(condition, 1)) {
  50. return;
  51. }
  52. va_list args;
  53. va_start(args, format);
  54. NSString *reason = [[NSString alloc] initWithFormat:format arguments:args];
  55. va_end(args);
  56. @throw [NSException exceptionWithName:name reason:reason userInfo:nil];
  57. }
  58. // return the property for a validated column name
  59. RLMProperty *RLMValidatedProperty(RLMObjectSchema *desc, NSString *columnName) {
  60. RLMProperty *prop = desc[columnName];
  61. RLMPrecondition(prop, @"Invalid property name",
  62. @"Property '%@' not found in object of type '%@'", columnName, desc.className);
  63. return prop;
  64. }
  65. namespace {
  66. BOOL RLMPropertyTypeIsNumeric(RLMPropertyType propertyType) {
  67. switch (propertyType) {
  68. case RLMPropertyTypeInt:
  69. case RLMPropertyTypeFloat:
  70. case RLMPropertyTypeDouble:
  71. return YES;
  72. default:
  73. return NO;
  74. }
  75. }
  76. // Equal and ContainsSubstring are used by QueryBuilder::add_string_constraint as the comparator
  77. // for performing diacritic-insensitive comparisons.
  78. bool equal(CFStringCompareFlags options, StringData v1, StringData v2)
  79. {
  80. if (v1.is_null() || v2.is_null()) {
  81. return v1.is_null() == v2.is_null();
  82. }
  83. auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(),
  84. kCFStringEncodingUTF8, false, kCFAllocatorNull));
  85. auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(),
  86. kCFStringEncodingUTF8, false, kCFAllocatorNull));
  87. return CFStringCompare(s1.get(), s2.get(), options) == kCFCompareEqualTo;
  88. }
  89. template <CFStringCompareFlags options>
  90. struct Equal {
  91. using CaseSensitive = Equal<options & ~kCFCompareCaseInsensitive>;
  92. using CaseInsensitive = Equal<options | kCFCompareCaseInsensitive>;
  93. bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const
  94. {
  95. REALM_ASSERT_DEBUG(v1_null == v1.is_null());
  96. REALM_ASSERT_DEBUG(v2_null == v2.is_null());
  97. return equal(options, v1, v2);
  98. }
  99. // FIXME: Consider the options.
  100. static const char* description() { return "equal"; }
  101. };
  102. bool contains_substring(CFStringCompareFlags options, StringData v1, StringData v2)
  103. {
  104. if (v2.is_null()) {
  105. // Everything contains NULL
  106. return true;
  107. }
  108. if (v1.is_null()) {
  109. // NULL contains nothing (except NULL, handled above)
  110. return false;
  111. }
  112. if (v2.size() == 0) {
  113. // Everything (except NULL, handled above) contains the empty string
  114. return true;
  115. }
  116. auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(),
  117. kCFStringEncodingUTF8, false, kCFAllocatorNull));
  118. auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(),
  119. kCFStringEncodingUTF8, false, kCFAllocatorNull));
  120. return CFStringFind(s1.get(), s2.get(), options).location != kCFNotFound;
  121. }
  122. template <CFStringCompareFlags options>
  123. struct ContainsSubstring {
  124. using CaseSensitive = ContainsSubstring<options & ~kCFCompareCaseInsensitive>;
  125. using CaseInsensitive = ContainsSubstring<options | kCFCompareCaseInsensitive>;
  126. bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const
  127. {
  128. REALM_ASSERT_DEBUG(v1_null == v1.is_null());
  129. REALM_ASSERT_DEBUG(v2_null == v2.is_null());
  130. return contains_substring(options, v1, v2);
  131. }
  132. // FIXME: Consider the options.
  133. static const char* description() { return "contains"; }
  134. };
  135. NSString *operatorName(NSPredicateOperatorType operatorType)
  136. {
  137. switch (operatorType) {
  138. case NSLessThanPredicateOperatorType:
  139. return @"<";
  140. case NSLessThanOrEqualToPredicateOperatorType:
  141. return @"<=";
  142. case NSGreaterThanPredicateOperatorType:
  143. return @">";
  144. case NSGreaterThanOrEqualToPredicateOperatorType:
  145. return @">=";
  146. case NSEqualToPredicateOperatorType:
  147. return @"==";
  148. case NSNotEqualToPredicateOperatorType:
  149. return @"!=";
  150. case NSMatchesPredicateOperatorType:
  151. return @"MATCHES";
  152. case NSLikePredicateOperatorType:
  153. return @"LIKE";
  154. case NSBeginsWithPredicateOperatorType:
  155. return @"BEGINSWITH";
  156. case NSEndsWithPredicateOperatorType:
  157. return @"ENDSWITH";
  158. case NSInPredicateOperatorType:
  159. return @"IN";
  160. case NSContainsPredicateOperatorType:
  161. return @"CONTAINS";
  162. case NSBetweenPredicateOperatorType:
  163. return @"BETWEEN";
  164. case NSCustomSelectorPredicateOperatorType:
  165. return @"custom selector";
  166. }
  167. return [NSString stringWithFormat:@"unknown operator %lu", (unsigned long)operatorType];
  168. }
  169. Table& get_table(Group& group, RLMObjectSchema *objectSchema)
  170. {
  171. return *ObjectStore::table_for_object_type(group, objectSchema.objectName.UTF8String);
  172. }
  173. // A reference to a column within a query. Can be resolved to a Columns<T> for use in query expressions.
  174. class ColumnReference {
  175. public:
  176. ColumnReference(Query& query, Group& group, RLMSchema *schema, RLMProperty* property, const std::vector<RLMProperty*>& links = {})
  177. : m_links(links), m_property(property), m_schema(schema), m_group(&group), m_query(&query), m_table(query.get_table().get())
  178. {
  179. auto& table = walk_link_chain([](Table&, size_t, RLMPropertyType) { });
  180. m_index = table.get_column_index(m_property.columnName.UTF8String);
  181. }
  182. template <typename T, typename... SubQuery>
  183. auto resolve(SubQuery&&... subquery) const
  184. {
  185. static_assert(sizeof...(SubQuery) < 2, "resolve() takes at most one subquery");
  186. set_link_chain_on_table();
  187. if (type() != RLMPropertyTypeLinkingObjects) {
  188. return m_table->template column<T>(index(), std::forward<SubQuery>(subquery)...);
  189. }
  190. else {
  191. return resolve_backlink<T>(std::forward<SubQuery>(subquery)...);
  192. }
  193. }
  194. RLMProperty *property() const { return m_property; }
  195. size_t index() const { return m_index; }
  196. RLMPropertyType type() const { return property().type; }
  197. Group& group() const { return *m_group; }
  198. RLMObjectSchema *link_target_object_schema() const
  199. {
  200. switch (type()) {
  201. case RLMPropertyTypeObject:
  202. case RLMPropertyTypeLinkingObjects:
  203. return m_schema[property().objectClassName];
  204. default:
  205. REALM_UNREACHABLE();
  206. }
  207. }
  208. bool has_links() const { return m_links.size(); }
  209. bool has_any_to_many_links() const {
  210. return std::any_of(begin(m_links), end(m_links),
  211. [](RLMProperty *property) { return property.array; });
  212. }
  213. ColumnReference last_link_column() const {
  214. REALM_ASSERT(!m_links.empty());
  215. return {*m_query, *m_group, m_schema, m_links.back(), {m_links.begin(), m_links.end() - 1}};
  216. }
  217. ColumnReference column_ignoring_links(Query& query) const {
  218. return {query, *m_group, m_schema, m_property};
  219. }
  220. private:
  221. template <typename T, typename... SubQuery>
  222. auto resolve_backlink(SubQuery&&... subquery) const
  223. {
  224. // We actually just want `if constexpr (std::is_same<T, Link>::value) { ... }`,
  225. // so fake it by tag-dispatching on the conditional
  226. return do_resolve_backlink<T>(std::is_same<T, Link>(), std::forward<SubQuery>(subquery)...);
  227. }
  228. template <typename T, typename... SubQuery>
  229. auto do_resolve_backlink(std::true_type, SubQuery&&... subquery) const
  230. {
  231. return with_link_origin(m_property, [&](Table& table, size_t col) {
  232. return m_table->template column<T>(table, col, std::forward<SubQuery>(subquery)...);
  233. });
  234. }
  235. template <typename T, typename... SubQuery>
  236. Columns<T> do_resolve_backlink(std::false_type, SubQuery&&...) const
  237. {
  238. // This can't actually happen as we only call resolve_backlink() if
  239. // it's RLMPropertyTypeLinkingObjects
  240. __builtin_unreachable();
  241. }
  242. template<typename Func>
  243. Table& walk_link_chain(Func&& func) const
  244. {
  245. auto table = m_query->get_table().get();
  246. for (const auto& link : m_links) {
  247. if (link.type != RLMPropertyTypeLinkingObjects) {
  248. auto index = table->get_column_index(link.columnName.UTF8String);
  249. func(*table, index, link.type);
  250. table = table->get_link_target(index).get();
  251. }
  252. else {
  253. with_link_origin(link, [&](Table& link_origin_table, size_t link_origin_column) {
  254. func(link_origin_table, link_origin_column, link.type);
  255. table = &link_origin_table;
  256. });
  257. }
  258. }
  259. return *table;
  260. }
  261. template<typename Func>
  262. auto with_link_origin(RLMProperty *prop, Func&& func) const
  263. {
  264. RLMObjectSchema *link_origin_schema = m_schema[prop.objectClassName];
  265. Table& link_origin_table = get_table(*m_group, link_origin_schema);
  266. NSString *column_name = link_origin_schema[prop.linkOriginPropertyName].columnName;
  267. size_t link_origin_column = link_origin_table.get_column_index(column_name.UTF8String);
  268. return func(link_origin_table, link_origin_column);
  269. }
  270. void set_link_chain_on_table() const
  271. {
  272. walk_link_chain([&](Table& current_table, size_t column, RLMPropertyType type) {
  273. if (type == RLMPropertyTypeLinkingObjects) {
  274. m_table->backlink(current_table, column);
  275. }
  276. else {
  277. m_table->link(column);
  278. }
  279. });
  280. }
  281. std::vector<RLMProperty*> m_links;
  282. RLMProperty *m_property;
  283. RLMSchema *m_schema;
  284. Group *m_group;
  285. Query *m_query;
  286. Table *m_table;
  287. size_t m_index;
  288. };
  289. class CollectionOperation {
  290. public:
  291. enum Type {
  292. Count,
  293. Minimum,
  294. Maximum,
  295. Sum,
  296. Average,
  297. };
  298. CollectionOperation(Type type, ColumnReference link_column, util::Optional<ColumnReference> column)
  299. : m_type(type)
  300. , m_link_column(std::move(link_column))
  301. , m_column(std::move(column))
  302. {
  303. RLMPrecondition(m_link_column.property().array,
  304. @"Invalid predicate", @"Collection operation can only be applied to a property of type RLMArray.");
  305. switch (m_type) {
  306. case Count:
  307. RLMPrecondition(!m_column, @"Invalid predicate", @"Result of @count does not have any properties.");
  308. break;
  309. case Minimum:
  310. case Maximum:
  311. case Sum:
  312. case Average:
  313. RLMPrecondition(m_column && RLMPropertyTypeIsNumeric(m_column->type()), @"Invalid predicate",
  314. @"%@ can only be applied to a numeric property.", name_for_type(m_type));
  315. break;
  316. }
  317. }
  318. CollectionOperation(NSString *operationName, ColumnReference link_column, util::Optional<ColumnReference> column = util::none)
  319. : CollectionOperation(type_for_name(operationName), std::move(link_column), std::move(column))
  320. {
  321. }
  322. Type type() const { return m_type; }
  323. const ColumnReference& link_column() const { return m_link_column; }
  324. const ColumnReference& column() const { return *m_column; }
  325. void validate_comparison(id value) const {
  326. switch (m_type) {
  327. case Count:
  328. case Average:
  329. RLMPrecondition([value isKindOfClass:[NSNumber class]], @"Invalid operand",
  330. @"%@ can only be compared with a numeric value.", name_for_type(m_type));
  331. break;
  332. case Minimum:
  333. case Maximum:
  334. case Sum:
  335. RLMPrecondition(RLMIsObjectValidForProperty(value, m_column->property()), @"Invalid operand",
  336. @"%@ on a property of type %@ cannot be compared with '%@'",
  337. name_for_type(m_type), RLMTypeToString(m_column->type()), value);
  338. break;
  339. }
  340. }
  341. void validate_comparison(const ColumnReference& column) const {
  342. switch (m_type) {
  343. case Count:
  344. RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand",
  345. @"%@ can only be compared with a numeric value.", name_for_type(m_type));
  346. break;
  347. case Average:
  348. case Minimum:
  349. case Maximum:
  350. case Sum:
  351. RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand",
  352. @"%@ on a property of type %@ cannot be compared with property of type '%@'",
  353. name_for_type(m_type), RLMTypeToString(m_column->type()), RLMTypeToString(column.type()));
  354. break;
  355. }
  356. }
  357. private:
  358. static Type type_for_name(NSString *name) {
  359. if ([name isEqualToString:@"@count"]) {
  360. return Count;
  361. }
  362. if ([name isEqualToString:@"@min"]) {
  363. return Minimum;
  364. }
  365. if ([name isEqualToString:@"@max"]) {
  366. return Maximum;
  367. }
  368. if ([name isEqualToString:@"@sum"]) {
  369. return Sum;
  370. }
  371. if ([name isEqualToString:@"@avg"]) {
  372. return Average;
  373. }
  374. @throw RLMPredicateException(@"Invalid predicate", @"Unsupported collection operation '%@'", name);
  375. }
  376. static NSString *name_for_type(Type type) {
  377. switch (type) {
  378. case Count: return @"@count";
  379. case Minimum: return @"@min";
  380. case Maximum: return @"@max";
  381. case Sum: return @"@sum";
  382. case Average: return @"@avg";
  383. }
  384. }
  385. Type m_type;
  386. ColumnReference m_link_column;
  387. util::Optional<ColumnReference> m_column;
  388. };
  389. class QueryBuilder {
  390. public:
  391. QueryBuilder(Query& query, Group& group, RLMSchema *schema)
  392. : m_query(query), m_group(group), m_schema(schema) { }
  393. void apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema);
  394. void apply_collection_operator_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred);
  395. void apply_value_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred);
  396. void apply_column_expression(RLMObjectSchema *desc, NSString *leftKeyPath, NSString *rightKeyPath, NSComparisonPredicate *predicate);
  397. void apply_subquery_count_expression(RLMObjectSchema *objectSchema, NSExpression *subqueryExpression,
  398. NSPredicateOperatorType operatorType, NSExpression *right);
  399. void apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
  400. NSPredicateOperatorType operatorType, NSExpression *right);
  401. void apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
  402. NSPredicateOperatorType operatorType, NSExpression *right);
  403. template <typename A, typename B>
  404. void add_numeric_constraint(RLMPropertyType datatype,
  405. NSPredicateOperatorType operatorType,
  406. A&& lhs, B&& rhs);
  407. template <typename A, typename B>
  408. void add_bool_constraint(NSPredicateOperatorType operatorType, A lhs, B rhs);
  409. void add_substring_constraint(null, Query condition);
  410. template<typename T>
  411. void add_substring_constraint(const T& value, Query condition);
  412. template<typename T>
  413. void add_substring_constraint(const Columns<T>& value, Query condition);
  414. template <typename T>
  415. void add_string_constraint(NSPredicateOperatorType operatorType,
  416. NSComparisonPredicateOptions predicateOptions,
  417. Columns<String> &&column,
  418. T value);
  419. void add_string_constraint(NSPredicateOperatorType operatorType,
  420. NSComparisonPredicateOptions predicateOptions,
  421. StringData value,
  422. Columns<String>&& column);
  423. template <typename L, typename R>
  424. void add_constraint(RLMPropertyType type,
  425. NSPredicateOperatorType operatorType,
  426. NSComparisonPredicateOptions predicateOptions,
  427. L lhs, R rhs);
  428. template <typename... T>
  429. void do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
  430. NSComparisonPredicateOptions predicateOptions, T... values);
  431. void do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null);
  432. void add_between_constraint(const ColumnReference& column, id value);
  433. void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, BinaryData value);
  434. void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value);
  435. void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null);
  436. void add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column);
  437. void add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&);
  438. void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, RLMObject *obj);
  439. void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, realm::null);
  440. template<typename T>
  441. void add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column);
  442. void add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&);
  443. template <CollectionOperation::Type Operation, typename... T>
  444. void add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values);
  445. template <typename... T>
  446. void add_collection_operation_constraint(NSPredicateOperatorType operatorType,
  447. CollectionOperation collectionOperation, T... values);
  448. CollectionOperation collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath);
  449. ColumnReference column_reference_from_key_path(RLMObjectSchema *objectSchema, NSString *keyPath, bool isAggregate);
  450. private:
  451. Query& m_query;
  452. Group& m_group;
  453. RLMSchema *m_schema;
  454. };
  455. // add a clause for numeric constraints based on operator type
  456. template <typename A, typename B>
  457. void QueryBuilder::add_numeric_constraint(RLMPropertyType datatype,
  458. NSPredicateOperatorType operatorType,
  459. A&& lhs, B&& rhs)
  460. {
  461. switch (operatorType) {
  462. case NSLessThanPredicateOperatorType:
  463. m_query.and_query(lhs < rhs);
  464. break;
  465. case NSLessThanOrEqualToPredicateOperatorType:
  466. m_query.and_query(lhs <= rhs);
  467. break;
  468. case NSGreaterThanPredicateOperatorType:
  469. m_query.and_query(lhs > rhs);
  470. break;
  471. case NSGreaterThanOrEqualToPredicateOperatorType:
  472. m_query.and_query(lhs >= rhs);
  473. break;
  474. case NSEqualToPredicateOperatorType:
  475. m_query.and_query(lhs == rhs);
  476. break;
  477. case NSNotEqualToPredicateOperatorType:
  478. m_query.and_query(lhs != rhs);
  479. break;
  480. default:
  481. @throw RLMPredicateException(@"Invalid operator type",
  482. @"Operator '%@' not supported for type %@",
  483. operatorName(operatorType), RLMTypeToString(datatype));
  484. }
  485. }
  486. template <typename A, typename B>
  487. void QueryBuilder::add_bool_constraint(NSPredicateOperatorType operatorType, A lhs, B rhs) {
  488. switch (operatorType) {
  489. case NSEqualToPredicateOperatorType:
  490. m_query.and_query(lhs == rhs);
  491. break;
  492. case NSNotEqualToPredicateOperatorType:
  493. m_query.and_query(lhs != rhs);
  494. break;
  495. default:
  496. @throw RLMPredicateException(@"Invalid operator type",
  497. @"Operator '%@' not supported for bool type", operatorName(operatorType));
  498. }
  499. }
  500. void QueryBuilder::add_substring_constraint(null, Query) {
  501. // Foundation always returns false for substring operations with a RHS of null or "".
  502. m_query.and_query(std::unique_ptr<Expression>(new FalseExpression));
  503. }
  504. template<typename T>
  505. void QueryBuilder::add_substring_constraint(const T& value, Query condition) {
  506. // Foundation always returns false for substring operations with a RHS of null or "".
  507. m_query.and_query(value.size()
  508. ? std::move(condition)
  509. : std::unique_ptr<Expression>(new FalseExpression));
  510. }
  511. template<typename T>
  512. void QueryBuilder::add_substring_constraint(const Columns<T>& value, Query condition) {
  513. // Foundation always returns false for substring operations with a RHS of null or "".
  514. // We don't need to concern ourselves with the possibility of value traversing a link list
  515. // and producing multiple values per row as such expressions will have been rejected.
  516. m_query.and_query(const_cast<Columns<String>&>(value).size() != 0 && std::move(condition));
  517. }
  518. template <typename T>
  519. void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType,
  520. NSComparisonPredicateOptions predicateOptions,
  521. Columns<String> &&column,
  522. T value) {
  523. bool caseSensitive = !(predicateOptions & NSCaseInsensitivePredicateOption);
  524. bool diacriticSensitive = !(predicateOptions & NSDiacriticInsensitivePredicateOption);
  525. if (diacriticSensitive) {
  526. switch (operatorType) {
  527. case NSBeginsWithPredicateOperatorType:
  528. add_substring_constraint(value, column.begins_with(value, caseSensitive));
  529. break;
  530. case NSEndsWithPredicateOperatorType:
  531. add_substring_constraint(value, column.ends_with(value, caseSensitive));
  532. break;
  533. case NSContainsPredicateOperatorType:
  534. add_substring_constraint(value, column.contains(value, caseSensitive));
  535. break;
  536. case NSEqualToPredicateOperatorType:
  537. m_query.and_query(column.equal(value, caseSensitive));
  538. break;
  539. case NSNotEqualToPredicateOperatorType:
  540. m_query.and_query(column.not_equal(value, caseSensitive));
  541. break;
  542. case NSLikePredicateOperatorType:
  543. m_query.and_query(column.like(value, caseSensitive));
  544. break;
  545. default:
  546. @throw RLMPredicateException(@"Invalid operator type",
  547. @"Operator '%@' not supported for string type",
  548. operatorName(operatorType));
  549. }
  550. return;
  551. }
  552. auto as_subexpr = util::overload([](StringData value) { return make_subexpr<ConstantStringValue>(value); },
  553. [](const Columns<String>& c) { return c.clone(); });
  554. auto left = as_subexpr(column);
  555. auto right = as_subexpr(value);
  556. auto make_constraint = [&](auto comparator) {
  557. using Comparator = decltype(comparator);
  558. using CompareCS = Compare<typename Comparator::CaseSensitive, StringData>;
  559. using CompareCI = Compare<typename Comparator::CaseInsensitive, StringData>;
  560. if (caseSensitive) {
  561. return make_expression<CompareCS>(std::move(left), std::move(right));
  562. }
  563. else {
  564. return make_expression<CompareCI>(std::move(left), std::move(right));
  565. }
  566. };
  567. switch (operatorType) {
  568. case NSBeginsWithPredicateOperatorType: {
  569. using C = ContainsSubstring<kCFCompareDiacriticInsensitive | kCFCompareAnchored>;
  570. add_substring_constraint(value, make_constraint(C{}));
  571. break;
  572. }
  573. case NSEndsWithPredicateOperatorType: {
  574. using C = ContainsSubstring<kCFCompareDiacriticInsensitive | kCFCompareAnchored | kCFCompareBackwards>;
  575. add_substring_constraint(value, make_constraint(C{}));
  576. break;
  577. }
  578. case NSContainsPredicateOperatorType: {
  579. using C = ContainsSubstring<kCFCompareDiacriticInsensitive>;
  580. add_substring_constraint(value, make_constraint(C{}));
  581. break;
  582. }
  583. case NSNotEqualToPredicateOperatorType:
  584. m_query.Not();
  585. REALM_FALLTHROUGH;
  586. case NSEqualToPredicateOperatorType:
  587. m_query.and_query(make_constraint(Equal<kCFCompareDiacriticInsensitive>{}));
  588. break;
  589. case NSLikePredicateOperatorType:
  590. @throw RLMPredicateException(@"Invalid operator type",
  591. @"Operator 'LIKE' not supported with diacritic-insensitive modifier.");
  592. default:
  593. @throw RLMPredicateException(@"Invalid operator type",
  594. @"Operator '%@' not supported for string type", operatorName(operatorType));
  595. }
  596. }
  597. void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType,
  598. NSComparisonPredicateOptions predicateOptions,
  599. StringData value,
  600. Columns<String>&& column) {
  601. switch (operatorType) {
  602. case NSEqualToPredicateOperatorType:
  603. case NSNotEqualToPredicateOperatorType:
  604. add_string_constraint(operatorType, predicateOptions, std::move(column), value);
  605. break;
  606. default:
  607. @throw RLMPredicateException(@"Invalid operator type",
  608. @"Operator '%@' is not supported for string type with key path on right side of operator",
  609. operatorName(operatorType));
  610. }
  611. }
  612. id value_from_constant_expression_or_value(id value) {
  613. if (NSExpression *exp = RLMDynamicCast<NSExpression>(value)) {
  614. RLMPrecondition(exp.expressionType == NSConstantValueExpressionType,
  615. @"Invalid value",
  616. @"Expressions within predicate aggregates must be constant values");
  617. return exp.constantValue;
  618. }
  619. return value;
  620. }
  621. void validate_and_extract_between_range(id value, RLMProperty *prop, id *from, id *to) {
  622. NSArray *array = RLMDynamicCast<NSArray>(value);
  623. RLMPrecondition(array, @"Invalid value", @"object must be of type NSArray for BETWEEN operations");
  624. RLMPrecondition(array.count == 2, @"Invalid value", @"NSArray object must contain exactly two objects for BETWEEN operations");
  625. *from = value_from_constant_expression_or_value(array.firstObject);
  626. *to = value_from_constant_expression_or_value(array.lastObject);
  627. RLMPrecondition(RLMIsObjectValidForProperty(*from, prop) && RLMIsObjectValidForProperty(*to, prop),
  628. @"Invalid value",
  629. @"NSArray objects must be of type %@ for BETWEEN operations", RLMTypeToString(prop.type));
  630. }
  631. void QueryBuilder::add_between_constraint(const ColumnReference& column, id value) {
  632. if (column.has_any_to_many_links()) {
  633. auto link_column = column.last_link_column();
  634. Query subquery = get_table(m_group, link_column.link_target_object_schema()).where();
  635. QueryBuilder(subquery, m_group, m_schema).add_between_constraint(column.column_ignoring_links(subquery), value);
  636. m_query.and_query(link_column.resolve<Link>(std::move(subquery)).count() > 0);
  637. return;
  638. }
  639. id from, to;
  640. validate_and_extract_between_range(value, column.property(), &from, &to);
  641. RLMPropertyType type = column.type();
  642. m_query.group();
  643. add_constraint(type, NSGreaterThanOrEqualToPredicateOperatorType, 0, column, from);
  644. add_constraint(type, NSLessThanOrEqualToPredicateOperatorType, 0, column, to);
  645. m_query.end_group();
  646. }
  647. void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType,
  648. const ColumnReference& column,
  649. BinaryData value) {
  650. RLMPrecondition(!column.has_links(), @"Unsupported operator", @"NSData properties cannot be queried over an object link.");
  651. size_t index = column.index();
  652. Query query = m_query.get_table()->where();
  653. switch (operatorType) {
  654. case NSBeginsWithPredicateOperatorType:
  655. add_substring_constraint(value, query.begins_with(index, value));
  656. break;
  657. case NSEndsWithPredicateOperatorType:
  658. add_substring_constraint(value, query.ends_with(index, value));
  659. break;
  660. case NSContainsPredicateOperatorType:
  661. add_substring_constraint(value, query.contains(index, value));
  662. break;
  663. case NSEqualToPredicateOperatorType:
  664. m_query.equal(index, value);
  665. break;
  666. case NSNotEqualToPredicateOperatorType:
  667. m_query.not_equal(index, value);
  668. break;
  669. default:
  670. @throw RLMPredicateException(@"Invalid operator type",
  671. @"Operator '%@' not supported for binary type", operatorName(operatorType));
  672. }
  673. }
  674. void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value) {
  675. add_binary_constraint(operatorType, column, RLMBinaryDataForNSData(value));
  676. }
  677. void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null) {
  678. add_binary_constraint(operatorType, column, BinaryData());
  679. }
  680. void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column) {
  681. switch (operatorType) {
  682. case NSEqualToPredicateOperatorType:
  683. case NSNotEqualToPredicateOperatorType:
  684. add_binary_constraint(operatorType, column, value);
  685. break;
  686. default:
  687. @throw RLMPredicateException(@"Invalid operator type",
  688. @"Operator '%@' is not supported for binary type with key path on right side of operator",
  689. operatorName(operatorType));
  690. }
  691. }
  692. void QueryBuilder::add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) {
  693. @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two NSData properties are not supported");
  694. }
  695. void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType,
  696. const ColumnReference& column, RLMObject *obj) {
  697. RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType,
  698. @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison");
  699. if (operatorType == NSEqualToPredicateOperatorType) {
  700. m_query.and_query(column.resolve<Link>() == obj->_row);
  701. }
  702. else {
  703. m_query.and_query(column.resolve<Link>() != obj->_row);
  704. }
  705. }
  706. void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType,
  707. const ColumnReference& column,
  708. realm::null) {
  709. RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType,
  710. @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison");
  711. if (operatorType == NSEqualToPredicateOperatorType) {
  712. m_query.and_query(column.resolve<Link>() == null());
  713. }
  714. else {
  715. m_query.and_query(column.resolve<Link>() != null());
  716. }
  717. }
  718. template<typename T>
  719. void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column) {
  720. // Link constraints only support the equal-to and not-equal-to operators. The order of operands
  721. // is not important for those comparisons so we can delegate to the other implementation.
  722. add_link_constraint(operatorType, column, obj);
  723. }
  724. void QueryBuilder::add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) {
  725. // This is not actually reachable as this case is caught earlier, but this
  726. // overload is needed for the code to compile
  727. @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two RLMArray properties are not supported");
  728. }
  729. // iterate over an array of subpredicates, using @func to build a query from each
  730. // one and ORing them together
  731. template<typename Func>
  732. void process_or_group(Query &query, id array, Func&& func) {
  733. RLMPrecondition([array conformsToProtocol:@protocol(NSFastEnumeration)],
  734. @"Invalid value", @"IN clause requires an array of items");
  735. query.group();
  736. bool first = true;
  737. for (id item in array) {
  738. if (!first) {
  739. query.Or();
  740. }
  741. first = false;
  742. func(item);
  743. }
  744. if (first) {
  745. // Queries can't be empty, so if there's zero things in the OR group
  746. // validation will fail. Work around this by adding an expression which
  747. // will never find any rows in a table.
  748. query.and_query(std::unique_ptr<Expression>(new FalseExpression));
  749. }
  750. query.end_group();
  751. }
  752. template <typename RequestedType>
  753. RequestedType convert(id value);
  754. template <>
  755. Timestamp convert<Timestamp>(id value) {
  756. return RLMTimestampForNSDate(value);
  757. }
  758. template <>
  759. bool convert<bool>(id value) {
  760. return [value boolValue];
  761. }
  762. template <>
  763. Double convert<Double>(id value) {
  764. return [value doubleValue];
  765. }
  766. template <>
  767. Float convert<Float>(id value) {
  768. return [value floatValue];
  769. }
  770. template <>
  771. Int convert<Int>(id value) {
  772. return [value longLongValue];
  773. }
  774. template <>
  775. String convert<String>(id value) {
  776. return RLMStringDataWithNSString(value);
  777. }
  778. template <typename>
  779. realm::null value_of_type(realm::null) {
  780. return realm::null();
  781. }
  782. template <typename RequestedType>
  783. auto value_of_type(id value) {
  784. return ::convert<RequestedType>(value);
  785. }
  786. template <typename RequestedType>
  787. auto value_of_type(const ColumnReference& column) {
  788. return column.resolve<RequestedType>();
  789. }
  790. template <typename... T>
  791. void QueryBuilder::do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
  792. NSComparisonPredicateOptions predicateOptions, T... values)
  793. {
  794. static_assert(sizeof...(T) == 2, "do_add_constraint accepts only two values as arguments");
  795. switch (type) {
  796. case RLMPropertyTypeBool:
  797. add_bool_constraint(operatorType, value_of_type<bool>(values)...);
  798. break;
  799. case RLMPropertyTypeDate:
  800. add_numeric_constraint(type, operatorType, value_of_type<realm::Timestamp>(values)...);
  801. break;
  802. case RLMPropertyTypeDouble:
  803. add_numeric_constraint(type, operatorType, value_of_type<Double>(values)...);
  804. break;
  805. case RLMPropertyTypeFloat:
  806. add_numeric_constraint(type, operatorType, value_of_type<Float>(values)...);
  807. break;
  808. case RLMPropertyTypeInt:
  809. add_numeric_constraint(type, operatorType, value_of_type<Int>(values)...);
  810. break;
  811. case RLMPropertyTypeString:
  812. add_string_constraint(operatorType, predicateOptions, value_of_type<String>(values)...);
  813. break;
  814. case RLMPropertyTypeData:
  815. add_binary_constraint(operatorType, values...);
  816. break;
  817. case RLMPropertyTypeObject:
  818. case RLMPropertyTypeLinkingObjects:
  819. add_link_constraint(operatorType, values...);
  820. break;
  821. default:
  822. @throw RLMPredicateException(@"Unsupported predicate value type",
  823. @"Object type %@ not supported", RLMTypeToString(type));
  824. }
  825. }
  826. void QueryBuilder::do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null)
  827. {
  828. // This is not actually reachable as this case is caught earlier, but this
  829. // overload is needed for the code to compile
  830. @throw RLMPredicateException(@"Invalid predicate expressions",
  831. @"Predicate expressions must compare a keypath and another keypath or a constant value");
  832. }
  833. bool is_nsnull(id value) {
  834. return !value || value == NSNull.null;
  835. }
  836. template<typename T>
  837. bool is_nsnull(T) {
  838. return false;
  839. }
  840. template <typename L, typename R>
  841. void QueryBuilder::add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
  842. NSComparisonPredicateOptions predicateOptions, L lhs, R rhs)
  843. {
  844. // The expression operators are only overloaded for realm::null on the rhs
  845. RLMPrecondition(!is_nsnull(lhs), @"Unsupported operator",
  846. @"Nil is only supported on the right side of operators");
  847. if (is_nsnull(rhs)) {
  848. do_add_constraint(type, operatorType, predicateOptions, lhs, realm::null());
  849. }
  850. else {
  851. do_add_constraint(type, operatorType, predicateOptions, lhs, rhs);
  852. }
  853. }
  854. struct KeyPath {
  855. std::vector<RLMProperty *> links;
  856. RLMProperty *property;
  857. bool containsToManyRelationship;
  858. };
  859. KeyPath key_path_from_string(RLMSchema *schema, RLMObjectSchema *objectSchema, NSString *keyPath)
  860. {
  861. RLMProperty *property;
  862. std::vector<RLMProperty *> links;
  863. bool keyPathContainsToManyRelationship = false;
  864. NSUInteger start = 0, length = keyPath.length, end = NSNotFound;
  865. do {
  866. end = [keyPath rangeOfString:@"." options:0 range:{start, length - start}].location;
  867. NSString *propertyName = [keyPath substringWithRange:{start, end == NSNotFound ? length - start : end - start}];
  868. property = objectSchema[propertyName];
  869. RLMPrecondition(property, @"Invalid property name",
  870. @"Property '%@' not found in object of type '%@'",
  871. propertyName, objectSchema.className);
  872. if (property.array)
  873. keyPathContainsToManyRelationship = true;
  874. if (end != NSNotFound) {
  875. RLMPrecondition(property.type == RLMPropertyTypeObject || property.type == RLMPropertyTypeLinkingObjects,
  876. @"Invalid value", @"Property '%@' is not a link in object of type '%@'",
  877. propertyName, objectSchema.className);
  878. links.push_back(property);
  879. REALM_ASSERT(property.objectClassName);
  880. objectSchema = schema[property.objectClassName];
  881. }
  882. start = end + 1;
  883. } while (end != NSNotFound);
  884. return {std::move(links), property, keyPathContainsToManyRelationship};
  885. }
  886. ColumnReference QueryBuilder::column_reference_from_key_path(RLMObjectSchema *objectSchema,
  887. NSString *keyPathString, bool isAggregate)
  888. {
  889. auto keyPath = key_path_from_string(m_schema, objectSchema, keyPathString);
  890. if (isAggregate && !keyPath.containsToManyRelationship) {
  891. @throw RLMPredicateException(@"Invalid predicate",
  892. @"Aggregate operations can only be used on key paths that include an array property");
  893. } else if (!isAggregate && keyPath.containsToManyRelationship) {
  894. @throw RLMPredicateException(@"Invalid predicate",
  895. @"Key paths that include an array property must use aggregate operations");
  896. }
  897. return ColumnReference(m_query, m_group, m_schema, keyPath.property, std::move(keyPath.links));
  898. }
  899. void validate_property_value(const ColumnReference& column,
  900. __unsafe_unretained id const value,
  901. __unsafe_unretained NSString *const err,
  902. __unsafe_unretained RLMObjectSchema *const objectSchema,
  903. __unsafe_unretained NSString *const keyPath) {
  904. RLMProperty *prop = column.property();
  905. if (prop.array) {
  906. RLMPrecondition([RLMObjectBaseObjectSchema(RLMDynamicCast<RLMObjectBase>(value)).className isEqualToString:prop.objectClassName],
  907. @"Invalid value", err, prop.objectClassName, keyPath, objectSchema.className, value);
  908. }
  909. else {
  910. RLMPrecondition(RLMIsObjectValidForProperty(value, prop),
  911. @"Invalid value", err, RLMTypeToString(prop.type), keyPath, objectSchema.className, value);
  912. }
  913. if (RLMObjectBase *obj = RLMDynamicCast<RLMObjectBase>(value)) {
  914. RLMPrecondition(!obj->_row.is_attached() || &column.group() == &obj->_realm.group,
  915. @"Invalid value origin", @"Object must be from the Realm being queried");
  916. }
  917. }
  918. template <typename RequestedType, CollectionOperation::Type OperationType>
  919. struct ValueOfTypeWithCollectionOperationHelper;
  920. template <>
  921. struct ValueOfTypeWithCollectionOperationHelper<Int, CollectionOperation::Count> {
  922. static auto convert(const CollectionOperation& operation)
  923. {
  924. assert(operation.type() == CollectionOperation::Count);
  925. return operation.link_column().resolve<Link>().count();
  926. }
  927. };
  928. #define VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(OperationType, function) \
  929. template <typename T> \
  930. struct ValueOfTypeWithCollectionOperationHelper<T, OperationType> { \
  931. static auto convert(const CollectionOperation& operation) \
  932. { \
  933. REALM_ASSERT(operation.type() == OperationType); \
  934. auto targetColumn = operation.link_column().resolve<Link>().template column<T>(operation.column().index()); \
  935. return targetColumn.function(); \
  936. } \
  937. } \
  938. VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Minimum, min);
  939. VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Maximum, max);
  940. VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Sum, sum);
  941. VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Average, average);
  942. #undef VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER
  943. template <typename Requested, CollectionOperation::Type OperationType, typename T>
  944. auto value_of_type_with_collection_operation(T&& value) {
  945. return value_of_type<Requested>(std::forward<T>(value));
  946. }
  947. template <typename Requested, CollectionOperation::Type OperationType>
  948. auto value_of_type_with_collection_operation(CollectionOperation operation) {
  949. using helper = ValueOfTypeWithCollectionOperationHelper<Requested, OperationType>;
  950. return helper::convert(operation);
  951. }
  952. template <CollectionOperation::Type Operation, typename... T>
  953. void QueryBuilder::add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values)
  954. {
  955. switch (propertyType) {
  956. case RLMPropertyTypeInt:
  957. add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation<Int, Operation>(values)...);
  958. break;
  959. case RLMPropertyTypeFloat:
  960. add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation<Float, Operation>(values)...);
  961. break;
  962. case RLMPropertyTypeDouble:
  963. add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation<Double, Operation>(values)...);
  964. break;
  965. default:
  966. REALM_ASSERT(false && "Only numeric property types should hit this path.");
  967. }
  968. }
  969. template <typename... T>
  970. void QueryBuilder::add_collection_operation_constraint(NSPredicateOperatorType operatorType,
  971. CollectionOperation collectionOperation, T... values)
  972. {
  973. static_assert(sizeof...(T) == 2, "add_collection_operation_constraint accepts only two values as arguments");
  974. switch (collectionOperation.type()) {
  975. case CollectionOperation::Count:
  976. add_numeric_constraint(RLMPropertyTypeInt, operatorType,
  977. value_of_type_with_collection_operation<Int, CollectionOperation::Count>(values)...);
  978. break;
  979. case CollectionOperation::Minimum:
  980. add_collection_operation_constraint<CollectionOperation::Minimum>(collectionOperation.column().type(), operatorType, values...);
  981. break;
  982. case CollectionOperation::Maximum:
  983. add_collection_operation_constraint<CollectionOperation::Maximum>(collectionOperation.column().type(), operatorType, values...);
  984. break;
  985. case CollectionOperation::Sum:
  986. add_collection_operation_constraint<CollectionOperation::Sum>(collectionOperation.column().type(), operatorType, values...);
  987. break;
  988. case CollectionOperation::Average:
  989. add_collection_operation_constraint<CollectionOperation::Average>(collectionOperation.column().type(), operatorType, values...);
  990. break;
  991. }
  992. }
  993. bool key_path_contains_collection_operator(NSString *keyPath) {
  994. return [keyPath rangeOfString:@"@"].location != NSNotFound;
  995. }
  996. NSString *get_collection_operation_name_from_key_path(NSString *keyPath, NSString **leadingKeyPath,
  997. NSString **trailingKey) {
  998. NSRange at = [keyPath rangeOfString:@"@"];
  999. if (at.location == NSNotFound || at.location >= keyPath.length - 1) {
  1000. @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath);
  1001. }
  1002. if (at.location == 0 || [keyPath characterAtIndex:at.location - 1] != '.') {
  1003. @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath);
  1004. }
  1005. NSRange trailingKeyRange = [keyPath rangeOfString:@"." options:0 range:{at.location, keyPath.length - at.location} locale:nil];
  1006. *leadingKeyPath = [keyPath substringToIndex:at.location - 1];
  1007. if (trailingKeyRange.location == NSNotFound) {
  1008. *trailingKey = nil;
  1009. return [keyPath substringFromIndex:at.location];
  1010. } else {
  1011. *trailingKey = [keyPath substringFromIndex:trailingKeyRange.location + 1];
  1012. return [keyPath substringWithRange:{at.location, trailingKeyRange.location - at.location}];
  1013. }
  1014. }
  1015. CollectionOperation QueryBuilder::collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath) {
  1016. NSString *leadingKeyPath;
  1017. NSString *trailingKey;
  1018. NSString *collectionOperationName = get_collection_operation_name_from_key_path(keyPath, &leadingKeyPath, &trailingKey);
  1019. ColumnReference linkColumn = column_reference_from_key_path(desc, leadingKeyPath, true);
  1020. util::Optional<ColumnReference> column;
  1021. if (trailingKey) {
  1022. RLMPrecondition([trailingKey rangeOfString:@"."].location == NSNotFound, @"Invalid key path",
  1023. @"Right side of collection operator may only have a single level key");
  1024. NSString *fullKeyPath = [leadingKeyPath stringByAppendingFormat:@".%@", trailingKey];
  1025. column = column_reference_from_key_path(desc, fullKeyPath, true);
  1026. }
  1027. return {collectionOperationName, std::move(linkColumn), std::move(column)};
  1028. }
  1029. void QueryBuilder::apply_collection_operator_expression(RLMObjectSchema *desc,
  1030. NSString *keyPath, id value,
  1031. NSComparisonPredicate *pred) {
  1032. CollectionOperation operation = collection_operation_from_key_path(desc, keyPath);
  1033. operation.validate_comparison(value);
  1034. if (pred.leftExpression.expressionType == NSKeyPathExpressionType) {
  1035. add_collection_operation_constraint(pred.predicateOperatorType, operation, operation, value);
  1036. } else {
  1037. add_collection_operation_constraint(pred.predicateOperatorType, operation, value, operation);
  1038. }
  1039. }
  1040. void QueryBuilder::apply_value_expression(RLMObjectSchema *desc,
  1041. NSString *keyPath, id value,
  1042. NSComparisonPredicate *pred)
  1043. {
  1044. if (key_path_contains_collection_operator(keyPath)) {
  1045. apply_collection_operator_expression(desc, keyPath, value, pred);
  1046. return;
  1047. }
  1048. bool isAny = pred.comparisonPredicateModifier == NSAnyPredicateModifier;
  1049. ColumnReference column = column_reference_from_key_path(desc, keyPath, isAny);
  1050. // check to see if this is a between query
  1051. if (pred.predicateOperatorType == NSBetweenPredicateOperatorType) {
  1052. add_between_constraint(std::move(column), value);
  1053. return;
  1054. }
  1055. // turn "key.path IN collection" into ored together ==. "collection IN key.path" is handled elsewhere.
  1056. if (pred.predicateOperatorType == NSInPredicateOperatorType) {
  1057. process_or_group(m_query, value, [&](id item) {
  1058. id normalized = value_from_constant_expression_or_value(item);
  1059. validate_property_value(column, normalized,
  1060. @"Expected object of type %@ in IN clause for property '%@' on object of type '%@', but received: %@", desc, keyPath);
  1061. add_constraint(column.type(), NSEqualToPredicateOperatorType, pred.options, column, normalized);
  1062. });
  1063. return;
  1064. }
  1065. validate_property_value(column, value, @"Expected object of type %@ for property '%@' on object of type '%@', but received: %@", desc, keyPath);
  1066. if (pred.leftExpression.expressionType == NSKeyPathExpressionType) {
  1067. add_constraint(column.type(), pred.predicateOperatorType, pred.options, std::move(column), value);
  1068. } else {
  1069. add_constraint(column.type(), pred.predicateOperatorType, pred.options, value, std::move(column));
  1070. }
  1071. }
  1072. void QueryBuilder::apply_column_expression(RLMObjectSchema *desc,
  1073. NSString *leftKeyPath, NSString *rightKeyPath,
  1074. NSComparisonPredicate *predicate)
  1075. {
  1076. bool left_key_path_contains_collection_operator = key_path_contains_collection_operator(leftKeyPath);
  1077. bool right_key_path_contains_collection_operator = key_path_contains_collection_operator(rightKeyPath);
  1078. if (left_key_path_contains_collection_operator && right_key_path_contains_collection_operator) {
  1079. @throw RLMPredicateException(@"Unsupported predicate", @"Key paths including aggregate operations cannot be compared with other aggregate operations.");
  1080. }
  1081. if (left_key_path_contains_collection_operator) {
  1082. CollectionOperation left = collection_operation_from_key_path(desc, leftKeyPath);
  1083. ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, false);
  1084. left.validate_comparison(right);
  1085. add_collection_operation_constraint(predicate.predicateOperatorType, left, left, std::move(right));
  1086. return;
  1087. }
  1088. if (right_key_path_contains_collection_operator) {
  1089. ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, false);
  1090. CollectionOperation right = collection_operation_from_key_path(desc, rightKeyPath);
  1091. right.validate_comparison(left);
  1092. add_collection_operation_constraint(predicate.predicateOperatorType, right, std::move(left), right);
  1093. return;
  1094. }
  1095. bool isAny = false;
  1096. ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, isAny);
  1097. ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, isAny);
  1098. // NOTE: It's assumed that column type must match and no automatic type conversion is supported.
  1099. RLMPrecondition(left.type() == right.type(),
  1100. RLMPropertiesComparisonTypeMismatchException,
  1101. RLMPropertiesComparisonTypeMismatchReason,
  1102. RLMTypeToString(left.type()),
  1103. RLMTypeToString(right.type()));
  1104. // TODO: Should we handle special case where left row is the same as right row (tautology)
  1105. add_constraint(left.type(), predicate.predicateOperatorType, predicate.options,
  1106. std::move(left), std::move(right));
  1107. }
  1108. // Identify expressions of the form [SELF valueForKeyPath:]
  1109. bool is_self_value_for_key_path_function_expression(NSExpression *expression)
  1110. {
  1111. if (expression.expressionType != NSFunctionExpressionType)
  1112. return false;
  1113. if (expression.operand.expressionType != NSEvaluatedObjectExpressionType)
  1114. return false;
  1115. return [expression.function isEqualToString:@"valueForKeyPath:"];
  1116. }
  1117. // -[NSPredicate predicateWithSubtitutionVariables:] results in function expressions of the form [SELF valueForKeyPath:]
  1118. // that apply_predicate cannot handle. Replace such expressions with equivalent NSKeyPathExpressionType expressions.
  1119. NSExpression *simplify_self_value_for_key_path_function_expression(NSExpression *expression) {
  1120. if (is_self_value_for_key_path_function_expression(expression)) {
  1121. if (NSString *keyPath = [expression.arguments.firstObject keyPath]) {
  1122. return [NSExpression expressionForKeyPath:keyPath];
  1123. }
  1124. }
  1125. return expression;
  1126. }
  1127. void QueryBuilder::apply_subquery_count_expression(RLMObjectSchema *objectSchema,
  1128. NSExpression *subqueryExpression, NSPredicateOperatorType operatorType, NSExpression *right) {
  1129. if (right.expressionType != NSConstantValueExpressionType || ![right.constantValue isKindOfClass:[NSNumber class]]) {
  1130. @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY(…).@count is only supported when compared with a constant number.");
  1131. }
  1132. int64_t value = [right.constantValue integerValue];
  1133. ColumnReference collectionColumn = column_reference_from_key_path(objectSchema, [subqueryExpression.collection keyPath], true);
  1134. RLMObjectSchema *collectionMemberObjectSchema = m_schema[collectionColumn.property().objectClassName];
  1135. // Eliminate references to the iteration variable in the subquery.
  1136. NSPredicate *subqueryPredicate = [subqueryExpression.predicate predicateWithSubstitutionVariables:@{ subqueryExpression.variable : [NSExpression expressionForEvaluatedObject] }];
  1137. subqueryPredicate = transformPredicate(subqueryPredicate, simplify_self_value_for_key_path_function_expression);
  1138. Query subquery = RLMPredicateToQuery(subqueryPredicate, collectionMemberObjectSchema, m_schema, m_group);
  1139. add_numeric_constraint(RLMPropertyTypeInt, operatorType,
  1140. collectionColumn.resolve<LinkList>(std::move(subquery)).count(), value);
  1141. }
  1142. void QueryBuilder::apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
  1143. NSPredicateOperatorType operatorType, NSExpression *right) {
  1144. if (![functionExpression.function isEqualToString:@"valueForKeyPath:"] || functionExpression.arguments.count != 1) {
  1145. @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported on the result of a SUBQUERY.", functionExpression.function);
  1146. }
  1147. NSExpression *keyPathExpression = functionExpression.arguments.firstObject;
  1148. if ([keyPathExpression.keyPath isEqualToString:@"@count"]) {
  1149. apply_subquery_count_expression(objectSchema, functionExpression.operand, operatorType, right);
  1150. } else {
  1151. @throw RLMPredicateException(@"Invalid predicate", @"SUBQUERY is only supported when immediately followed by .@count that is compared with a constant number.");
  1152. }
  1153. }
  1154. void QueryBuilder::apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
  1155. NSPredicateOperatorType operatorType, NSExpression *right) {
  1156. if (functionExpression.operand.expressionType == NSSubqueryExpressionType) {
  1157. apply_function_subquery_expression(objectSchema, functionExpression, operatorType, right);
  1158. } else {
  1159. @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported.", functionExpression.function);
  1160. }
  1161. }
  1162. void QueryBuilder::apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema)
  1163. {
  1164. // Compound predicates.
  1165. if ([predicate isMemberOfClass:[NSCompoundPredicate class]]) {
  1166. NSCompoundPredicate *comp = (NSCompoundPredicate *)predicate;
  1167. switch ([comp compoundPredicateType]) {
  1168. case NSAndPredicateType:
  1169. if (comp.subpredicates.count) {
  1170. // Add all of the subpredicates.
  1171. m_query.group();
  1172. for (NSPredicate *subp in comp.subpredicates) {
  1173. apply_predicate(subp, objectSchema);
  1174. }
  1175. m_query.end_group();
  1176. } else {
  1177. // NSCompoundPredicate's documentation states that an AND predicate with no subpredicates evaluates to TRUE.
  1178. m_query.and_query(std::unique_ptr<Expression>(new TrueExpression));
  1179. }
  1180. break;
  1181. case NSOrPredicateType: {
  1182. // Add all of the subpredicates with ors inbetween.
  1183. process_or_group(m_query, comp.subpredicates, [&](__unsafe_unretained NSPredicate *const subp) {
  1184. apply_predicate(subp, objectSchema);
  1185. });
  1186. break;
  1187. }
  1188. case NSNotPredicateType:
  1189. // Add the negated subpredicate
  1190. m_query.Not();
  1191. apply_predicate(comp.subpredicates.firstObject, objectSchema);
  1192. break;
  1193. default:
  1194. @throw RLMPredicateException(@"Invalid compound predicate type",
  1195. @"Only support AND, OR and NOT predicate types");
  1196. }
  1197. }
  1198. else if ([predicate isMemberOfClass:[NSComparisonPredicate class]]) {
  1199. NSComparisonPredicate *compp = (NSComparisonPredicate *)predicate;
  1200. // check modifier
  1201. RLMPrecondition(compp.comparisonPredicateModifier != NSAllPredicateModifier,
  1202. @"Invalid predicate", @"ALL modifier not supported");
  1203. NSExpressionType exp1Type = compp.leftExpression.expressionType;
  1204. NSExpressionType exp2Type = compp.rightExpression.expressionType;
  1205. if (compp.comparisonPredicateModifier == NSAnyPredicateModifier) {
  1206. // for ANY queries
  1207. RLMPrecondition(exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType,
  1208. @"Invalid predicate",
  1209. @"Predicate with ANY modifier must compare a KeyPath with RLMArray with a value");
  1210. }
  1211. if (compp.predicateOperatorType == NSBetweenPredicateOperatorType || compp.predicateOperatorType == NSInPredicateOperatorType) {
  1212. // Inserting an array via %@ gives NSConstantValueExpressionType, but including it directly gives NSAggregateExpressionType
  1213. if (exp1Type == NSKeyPathExpressionType && (exp2Type == NSAggregateExpressionType || exp2Type == NSConstantValueExpressionType)) {
  1214. // "key.path IN %@", "key.path IN {…}", "key.path BETWEEN %@", or "key.path BETWEEN {…}".
  1215. exp2Type = NSConstantValueExpressionType;
  1216. }
  1217. else if (compp.predicateOperatorType == NSInPredicateOperatorType && exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) {
  1218. // "%@ IN key.path" is equivalent to "ANY key.path IN %@". Rewrite the former into the latter.
  1219. compp = [NSComparisonPredicate predicateWithLeftExpression:compp.rightExpression rightExpression:compp.leftExpression
  1220. modifier:NSAnyPredicateModifier type:NSEqualToPredicateOperatorType options:0];
  1221. exp1Type = NSKeyPathExpressionType;
  1222. exp2Type = NSConstantValueExpressionType;
  1223. }
  1224. else {
  1225. if (compp.predicateOperatorType == NSBetweenPredicateOperatorType) {
  1226. @throw RLMPredicateException(@"Invalid predicate",
  1227. @"Predicate with BETWEEN operator must compare a KeyPath with an aggregate with two values");
  1228. }
  1229. else if (compp.predicateOperatorType == NSInPredicateOperatorType) {
  1230. @throw RLMPredicateException(@"Invalid predicate",
  1231. @"Predicate with IN operator must compare a KeyPath with an aggregate");
  1232. }
  1233. }
  1234. }
  1235. if (exp1Type == NSKeyPathExpressionType && exp2Type == NSKeyPathExpressionType) {
  1236. // both expression are KeyPaths
  1237. apply_column_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.keyPath, compp);
  1238. }
  1239. else if (exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType) {
  1240. // comparing keypath to value
  1241. apply_value_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.constantValue, compp);
  1242. }
  1243. else if (exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) {
  1244. // comparing value to keypath
  1245. apply_value_expression(objectSchema, compp.rightExpression.keyPath, compp.leftExpression.constantValue, compp);
  1246. }
  1247. else if (exp1Type == NSFunctionExpressionType) {
  1248. apply_function_expression(objectSchema, compp.leftExpression, compp.predicateOperatorType, compp.rightExpression);
  1249. }
  1250. else if (exp1Type == NSSubqueryExpressionType) {
  1251. // The subquery expressions that we support are handled by the NSFunctionExpressionType case above.
  1252. @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY is only supported when immediately followed by .@count.");
  1253. }
  1254. else {
  1255. @throw RLMPredicateException(@"Invalid predicate expressions",
  1256. @"Predicate expressions must compare a keypath and another keypath or a constant value");
  1257. }
  1258. }
  1259. else if ([predicate isEqual:[NSPredicate predicateWithValue:YES]]) {
  1260. m_query.and_query(std::unique_ptr<Expression>(new TrueExpression));
  1261. } else if ([predicate isEqual:[NSPredicate predicateWithValue:NO]]) {
  1262. m_query.and_query(std::unique_ptr<Expression>(new FalseExpression));
  1263. }
  1264. else {
  1265. // invalid predicate type
  1266. @throw RLMPredicateException(@"Invalid predicate",
  1267. @"Only support compound, comparison, and constant predicates");
  1268. }
  1269. }
  1270. } // namespace
  1271. realm::Query RLMPredicateToQuery(NSPredicate *predicate, RLMObjectSchema *objectSchema,
  1272. RLMSchema *schema, Group &group)
  1273. {
  1274. auto query = get_table(group, objectSchema).where();
  1275. // passing a nil predicate is a no-op
  1276. if (!predicate) {
  1277. return query;
  1278. }
  1279. @autoreleasepool {
  1280. QueryBuilder(query, group, schema).apply_predicate(predicate, objectSchema);
  1281. }
  1282. // Test the constructed query in core
  1283. std::string validateMessage = query.validate();
  1284. RLMPrecondition(validateMessage.empty(), @"Invalid query", @"%.*s",
  1285. (int)validateMessage.size(), validateMessage.c_str());
  1286. return query;
  1287. }