results.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 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. #include "catch2/catch.hpp"
  19. #include "util/event_loop.hpp"
  20. #include "util/index_helpers.hpp"
  21. #include "util/test_file.hpp"
  22. #include "impl/object_accessor_impl.hpp"
  23. #include "impl/realm_coordinator.hpp"
  24. #include "binding_context.hpp"
  25. #include "object_schema.hpp"
  26. #include "property.hpp"
  27. #include "results.hpp"
  28. #include "schema.hpp"
  29. #include "util/scheduler.hpp"
  30. #include <realm/db.hpp>
  31. #include <realm/group.hpp>
  32. #include <realm/query_engine.hpp>
  33. #include <realm/query_expression.hpp>
  34. #if REALM_ENABLE_SYNC
  35. #include "sync/sync_manager.hpp"
  36. #include "sync/sync_session.hpp"
  37. #endif
  38. namespace realm {
  39. class TestHelper {
  40. public:
  41. static DBRef& get_shared_group(SharedRealm const& shared_realm)
  42. {
  43. return Realm::Internal::get_db(*shared_realm);
  44. }
  45. };
  46. }
  47. using namespace realm;
  48. using namespace std::string_literals;
  49. namespace {
  50. using AnyDict = std::map<std::string, util::Any>;
  51. using AnyVec = std::vector<util::Any>;
  52. }
  53. struct TestContext : CppContext {
  54. std::map<std::string, AnyDict> defaults;
  55. using CppContext::CppContext;
  56. TestContext(TestContext& parent, realm::Property const& prop)
  57. : CppContext(parent, prop)
  58. , defaults(parent.defaults)
  59. { }
  60. void will_change(Object const&, Property const&) {}
  61. void did_change() {}
  62. std::string print(util::Any) { return "not implemented"; }
  63. bool allow_missing(util::Any) { return false; }
  64. };
  65. TEST_CASE("notifications: async delivery") {
  66. _impl::RealmCoordinator::assert_no_open_realms();
  67. InMemoryTestFile config;
  68. config.automatic_change_notifications = false;
  69. auto r = Realm::get_shared_realm(config);
  70. r->update_schema({
  71. {"object", {
  72. {"value", PropertyType::Int}
  73. }},
  74. });
  75. auto coordinator = _impl::RealmCoordinator::get_coordinator(config.path);
  76. auto table = r->read_group().get_table("class_object");
  77. auto col = table->get_column_key("value");
  78. r->begin_transaction();
  79. for (int i = 0; i < 10; ++i)
  80. table->create_object().set_all(i * 2);
  81. r->commit_transaction();
  82. Results results(r, table->where().greater(col, 0).less(col, 10));
  83. int notification_calls = 0;
  84. auto token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  85. REQUIRE_FALSE(err);
  86. ++notification_calls;
  87. });
  88. auto make_local_change = [&] {
  89. r->begin_transaction();
  90. table->begin()->set(col, 4);
  91. r->commit_transaction();
  92. };
  93. auto make_remote_change = [&] {
  94. auto r2 = coordinator->get_realm(util::Scheduler::get_frozen());
  95. r2->begin_transaction();
  96. r2->read_group().get_table("class_object")->begin()->set(col, 5);
  97. r2->commit_transaction();
  98. };
  99. SECTION("initial notification") {
  100. SECTION("is delivered on notify()") {
  101. REQUIRE(notification_calls == 0);
  102. advance_and_notify(*r);
  103. REQUIRE(notification_calls == 1);
  104. }
  105. SECTION("is delivered on refresh()") {
  106. coordinator->on_change();
  107. REQUIRE(notification_calls == 0);
  108. r->refresh();
  109. REQUIRE(notification_calls == 1);
  110. }
  111. SECTION("is delivered on begin_transaction()") {
  112. coordinator->on_change();
  113. REQUIRE(notification_calls == 0);
  114. r->begin_transaction();
  115. REQUIRE(notification_calls == 1);
  116. r->cancel_transaction();
  117. }
  118. SECTION("is delivered on notify() even with autorefresh disabled") {
  119. r->set_auto_refresh(false);
  120. REQUIRE(notification_calls == 0);
  121. advance_and_notify(*r);
  122. REQUIRE(notification_calls == 1);
  123. }
  124. SECTION("refresh() blocks due to initial results not being ready") {
  125. REQUIRE(notification_calls == 0);
  126. JoiningThread thread([&] {
  127. std::this_thread::sleep_for(std::chrono::microseconds(5000));
  128. coordinator->on_change();
  129. });
  130. r->refresh();
  131. REQUIRE(notification_calls == 1);
  132. }
  133. SECTION("begin_transaction() blocks due to initial results not being ready") {
  134. REQUIRE(notification_calls == 0);
  135. JoiningThread thread([&] {
  136. std::this_thread::sleep_for(std::chrono::microseconds(5000));
  137. coordinator->on_change();
  138. });
  139. r->begin_transaction();
  140. REQUIRE(notification_calls == 1);
  141. r->cancel_transaction();
  142. }
  143. SECTION("notify() does not block due to initial results not being ready") {
  144. REQUIRE(notification_calls == 0);
  145. r->notify();
  146. REQUIRE(notification_calls == 0);
  147. }
  148. SECTION("is delivered after invalidate()") {
  149. r->invalidate();
  150. SECTION("notify()") {
  151. coordinator->on_change();
  152. REQUIRE_FALSE(r->is_in_read_transaction());
  153. r->notify();
  154. REQUIRE(notification_calls == 1);
  155. }
  156. SECTION("notify() without autorefresh") {
  157. r->set_auto_refresh(false);
  158. coordinator->on_change();
  159. REQUIRE_FALSE(r->is_in_read_transaction());
  160. r->notify();
  161. REQUIRE(notification_calls == 1);
  162. }
  163. SECTION("refresh()") {
  164. coordinator->on_change();
  165. REQUIRE_FALSE(r->is_in_read_transaction());
  166. r->refresh();
  167. REQUIRE(notification_calls == 1);
  168. }
  169. SECTION("begin_transaction()") {
  170. coordinator->on_change();
  171. REQUIRE_FALSE(r->is_in_read_transaction());
  172. r->begin_transaction();
  173. REQUIRE(notification_calls == 1);
  174. r->cancel_transaction();
  175. }
  176. }
  177. SECTION("is delivered by notify() even if there are later versions") {
  178. REQUIRE(notification_calls == 0);
  179. coordinator->on_change();
  180. make_remote_change();
  181. r->notify();
  182. REQUIRE(notification_calls == 1);
  183. }
  184. }
  185. advance_and_notify(*r);
  186. SECTION("notifications for local changes") {
  187. make_local_change();
  188. coordinator->on_change();
  189. REQUIRE(notification_calls == 1);
  190. SECTION("notify()") {
  191. r->notify();
  192. REQUIRE(notification_calls == 2);
  193. }
  194. SECTION("notify() without autorefresh") {
  195. r->set_auto_refresh(false);
  196. r->notify();
  197. REQUIRE(notification_calls == 2);
  198. }
  199. SECTION("refresh()") {
  200. r->refresh();
  201. REQUIRE(notification_calls == 2);
  202. }
  203. SECTION("begin_transaction()") {
  204. r->begin_transaction();
  205. REQUIRE(notification_calls == 2);
  206. r->cancel_transaction();
  207. }
  208. }
  209. SECTION("notifications for remote changes") {
  210. make_remote_change();
  211. coordinator->on_change();
  212. REQUIRE(notification_calls == 1);
  213. SECTION("notify()") {
  214. r->notify();
  215. REQUIRE(notification_calls == 2);
  216. }
  217. SECTION("notify() without autorefresh") {
  218. r->set_auto_refresh(false);
  219. r->notify();
  220. REQUIRE(notification_calls == 1);
  221. r->refresh();
  222. REQUIRE(notification_calls == 2);
  223. }
  224. SECTION("refresh()") {
  225. r->refresh();
  226. REQUIRE(notification_calls == 2);
  227. }
  228. SECTION("begin_transaction()") {
  229. r->begin_transaction();
  230. REQUIRE(notification_calls == 2);
  231. r->cancel_transaction();
  232. }
  233. }
  234. SECTION("notifications are not delivered when the token is destroyed before they are calculated") {
  235. make_remote_change();
  236. REQUIRE(notification_calls == 1);
  237. token = {};
  238. advance_and_notify(*r);
  239. REQUIRE(notification_calls == 1);
  240. }
  241. SECTION("notifications are not delivered when the token is destroyed before they are delivered") {
  242. make_remote_change();
  243. REQUIRE(notification_calls == 1);
  244. coordinator->on_change();
  245. token = {};
  246. r->notify();
  247. REQUIRE(notification_calls == 1);
  248. }
  249. SECTION("notifications are delivered on the next cycle when a new callback is added from within a callback") {
  250. NotificationToken token2, token3;
  251. bool called = false;
  252. token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  253. token2 = {};
  254. token3 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  255. called = true;
  256. });
  257. });
  258. advance_and_notify(*r);
  259. REQUIRE_FALSE(called);
  260. advance_and_notify(*r);
  261. REQUIRE(called);
  262. }
  263. SECTION("notifications are delivered on the next cycle when a new callback is added from within a callback") {
  264. auto results2 = results;
  265. auto results3 = results;
  266. NotificationToken token2, token3, token4;
  267. bool called = false;
  268. auto check = [&](Results& outer, Results& inner) {
  269. token2 = outer.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  270. token2 = {};
  271. token3 = inner.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  272. called = true;
  273. });
  274. });
  275. advance_and_notify(*r);
  276. REQUIRE_FALSE(called);
  277. advance_and_notify(*r);
  278. REQUIRE(called);
  279. };
  280. SECTION("same Results") {
  281. check(results, results);
  282. }
  283. SECTION("Results which has never had a notifier") {
  284. check(results, results2);
  285. }
  286. SECTION("Results which used to have callbacks but no longer does") {
  287. SECTION("notifier before active") {
  288. token3 = results2.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  289. token3 = {};
  290. });
  291. check(results3, results2);
  292. }
  293. SECTION("notifier after active") {
  294. token3 = results2.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  295. token3 = {};
  296. });
  297. check(results, results2);
  298. }
  299. }
  300. SECTION("Results which already has callbacks") {
  301. SECTION("notifier before active") {
  302. token4 = results2.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) { });
  303. check(results3, results2);
  304. }
  305. SECTION("notifier after active") {
  306. token4 = results2.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) { });
  307. check(results, results2);
  308. }
  309. }
  310. }
  311. SECTION("remote changes made before adding a callback from within a callback are not reported") {
  312. NotificationToken token2, token3;
  313. bool called = false;
  314. token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  315. token2 = {};
  316. make_remote_change();
  317. coordinator->on_change();
  318. token3 = results.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr) {
  319. called = true;
  320. REQUIRE(c.empty());
  321. REQUIRE(table->begin()->get<int64_t>(col) == 5);
  322. });
  323. });
  324. advance_and_notify(*r);
  325. REQUIRE_FALSE(called);
  326. advance_and_notify(*r);
  327. REQUIRE(called);
  328. }
  329. SECTION("notifications are not delivered when a callback is removed from within a callback") {
  330. NotificationToken token2, token3;
  331. token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  332. token3 = {};
  333. });
  334. token3 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  335. REQUIRE(false);
  336. });
  337. advance_and_notify(*r);
  338. }
  339. SECTION("removing the current callback does not stop later ones from being called") {
  340. NotificationToken token2, token3;
  341. bool called = false;
  342. token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  343. token2 = {};
  344. });
  345. token3 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  346. called = true;
  347. });
  348. advance_and_notify(*r);
  349. REQUIRE(called);
  350. }
  351. SECTION("the first call of a notification can include changes if it previously ran for a different callback") {
  352. r->begin_transaction();
  353. auto token2 = results.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr) {
  354. REQUIRE(!c.empty());
  355. });
  356. table->create_object().set(col, 5);
  357. r->commit_transaction();
  358. advance_and_notify(*r);
  359. }
  360. SECTION("handling of results not ready") {
  361. make_remote_change();
  362. SECTION("notify() does nothing") {
  363. r->notify();
  364. REQUIRE(notification_calls == 1);
  365. coordinator->on_change();
  366. r->notify();
  367. REQUIRE(notification_calls == 2);
  368. }
  369. SECTION("refresh() blocks") {
  370. REQUIRE(notification_calls == 1);
  371. JoiningThread thread([&] {
  372. std::this_thread::sleep_for(std::chrono::microseconds(5000));
  373. coordinator->on_change();
  374. });
  375. r->refresh();
  376. REQUIRE(notification_calls == 2);
  377. }
  378. SECTION("refresh() advances to the first version with notifiers ready that is at least a recent as the newest at the time it is called") {
  379. JoiningThread thread([&] {
  380. std::this_thread::sleep_for(std::chrono::microseconds(5000));
  381. make_remote_change();
  382. coordinator->on_change();
  383. make_remote_change();
  384. });
  385. // advances to the version after the one it was waiting for, but still
  386. // not the latest
  387. r->refresh();
  388. REQUIRE(notification_calls == 2);
  389. thread.join();
  390. REQUIRE(notification_calls == 2);
  391. // now advances to the latest
  392. coordinator->on_change();
  393. r->refresh();
  394. REQUIRE(notification_calls == 3);
  395. }
  396. SECTION("begin_transaction() blocks") {
  397. REQUIRE(notification_calls == 1);
  398. JoiningThread thread([&] {
  399. std::this_thread::sleep_for(std::chrono::microseconds(5000));
  400. coordinator->on_change();
  401. });
  402. r->begin_transaction();
  403. REQUIRE(notification_calls == 2);
  404. r->cancel_transaction();
  405. }
  406. SECTION("refresh() does not block for results without callbacks") {
  407. token = {};
  408. // this would deadlock if it waits for the notifier to be ready
  409. r->refresh();
  410. }
  411. SECTION("begin_transaction() does not block for results without callbacks") {
  412. token = {};
  413. // this would deadlock if it waits for the notifier to be ready
  414. r->begin_transaction();
  415. r->cancel_transaction();
  416. }
  417. SECTION("begin_transaction() does not block for Results for different Realms") {
  418. // this would deadlock if beginning the write on the secondary Realm
  419. // waited for the primary Realm to be ready
  420. make_remote_change();
  421. // sanity check that the notifications never did run
  422. r->notify();
  423. REQUIRE(notification_calls == 1);
  424. }
  425. }
  426. SECTION("handling of stale results") {
  427. make_remote_change();
  428. coordinator->on_change();
  429. make_remote_change();
  430. SECTION("notify() uses the older version") {
  431. r->notify();
  432. REQUIRE(notification_calls == 2);
  433. coordinator->on_change();
  434. r->notify();
  435. REQUIRE(notification_calls == 3);
  436. r->notify();
  437. REQUIRE(notification_calls == 3);
  438. }
  439. SECTION("refresh() blocks") {
  440. REQUIRE(notification_calls == 1);
  441. JoiningThread thread([&] {
  442. std::this_thread::sleep_for(std::chrono::microseconds(5000));
  443. coordinator->on_change();
  444. });
  445. r->refresh();
  446. REQUIRE(notification_calls == 2);
  447. }
  448. SECTION("begin_transaction() blocks") {
  449. REQUIRE(notification_calls == 1);
  450. JoiningThread thread([&] {
  451. std::this_thread::sleep_for(std::chrono::microseconds(5000));
  452. coordinator->on_change();
  453. });
  454. r->begin_transaction();
  455. REQUIRE(notification_calls == 2);
  456. r->cancel_transaction();
  457. }
  458. }
  459. SECTION("updates are delivered after invalidate()") {
  460. r->invalidate();
  461. make_remote_change();
  462. SECTION("notify()") {
  463. coordinator->on_change();
  464. REQUIRE_FALSE(r->is_in_read_transaction());
  465. r->notify();
  466. REQUIRE(notification_calls == 2);
  467. }
  468. SECTION("notify() without autorefresh") {
  469. r->set_auto_refresh(false);
  470. coordinator->on_change();
  471. REQUIRE_FALSE(r->is_in_read_transaction());
  472. r->notify();
  473. REQUIRE(notification_calls == 1);
  474. r->refresh();
  475. REQUIRE(notification_calls == 2);
  476. }
  477. SECTION("refresh()") {
  478. coordinator->on_change();
  479. REQUIRE_FALSE(r->is_in_read_transaction());
  480. r->refresh();
  481. REQUIRE(notification_calls == 2);
  482. }
  483. SECTION("begin_transaction()") {
  484. coordinator->on_change();
  485. REQUIRE_FALSE(r->is_in_read_transaction());
  486. r->begin_transaction();
  487. REQUIRE(notification_calls == 2);
  488. r->cancel_transaction();
  489. }
  490. }
  491. SECTION("refresh() from within changes_available() do not interfere with notification delivery") {
  492. struct Context : BindingContext {
  493. Realm& realm;
  494. Context(Realm& realm) : realm(realm) { }
  495. void changes_available() override
  496. {
  497. REQUIRE(realm.refresh());
  498. }
  499. };
  500. make_remote_change();
  501. coordinator->on_change();
  502. r->set_auto_refresh(false);
  503. REQUIRE(notification_calls == 1);
  504. r->notify();
  505. REQUIRE(notification_calls == 1);
  506. r->m_binding_context.reset(new Context(*r));
  507. r->notify();
  508. REQUIRE(notification_calls == 2);
  509. }
  510. SECTION("refresh() from within a notification is a no-op") {
  511. token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  512. REQUIRE_FALSE(err);
  513. REQUIRE_FALSE(r->refresh()); // would deadlock if it actually tried to refresh
  514. });
  515. advance_and_notify(*r);
  516. make_remote_change(); // 1
  517. coordinator->on_change();
  518. make_remote_change(); // 2
  519. r->notify(); // advances to version from 1
  520. coordinator->on_change();
  521. REQUIRE(r->refresh()); // advances to version from 2
  522. REQUIRE_FALSE(r->refresh()); // does not advance since it's now up-to-date
  523. }
  524. SECTION("begin_transaction() from within a notification does not send notifications immediately") {
  525. bool first = true;
  526. auto token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  527. REQUIRE_FALSE(err);
  528. if (first)
  529. first = false;
  530. else {
  531. // would deadlock if it tried to send notifications as they aren't ready yet
  532. r->begin_transaction();
  533. r->cancel_transaction();
  534. }
  535. });
  536. advance_and_notify(*r);
  537. make_remote_change(); // 1
  538. coordinator->on_change();
  539. make_remote_change(); // 2
  540. r->notify(); // advances to version from 1
  541. REQUIRE(notification_calls == 2);
  542. coordinator->on_change();
  543. REQUIRE_FALSE(r->refresh()); // we made the commit locally, so no advancing here
  544. REQUIRE(notification_calls == 3);
  545. }
  546. SECTION("begin_transaction() from within a notification does not break delivering additional notifications") {
  547. size_t calls = 0;
  548. token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  549. REQUIRE_FALSE(err);
  550. if (++calls == 1)
  551. return;
  552. // force the read version to advance by beginning a transaction
  553. r->begin_transaction();
  554. r->cancel_transaction();
  555. });
  556. auto results2 = results;
  557. size_t calls2 = 0;
  558. auto token2 = results2.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  559. REQUIRE_FALSE(err);
  560. if (++calls2 == 1)
  561. return;
  562. REQUIRE_INDICES(c.insertions, 0);
  563. });
  564. advance_and_notify(*r);
  565. REQUIRE(calls == 1);
  566. REQUIRE(calls2 == 1);
  567. make_remote_change(); // 1
  568. coordinator->on_change();
  569. make_remote_change(); // 2
  570. r->notify(); // advances to version from 1
  571. REQUIRE(calls == 2);
  572. REQUIRE(calls2 == 2);
  573. }
  574. SECTION("begin_transaction() from within did_change() does not break delivering collection notification") {
  575. struct Context : BindingContext {
  576. Realm& realm;
  577. Context(Realm& realm) : realm(realm) { }
  578. void did_change(std::vector<ObserverState> const&, std::vector<void*> const&, bool) override
  579. {
  580. if (!realm.is_in_transaction()) {
  581. // advances to version from 2 (and recursively calls this, hence the check above)
  582. realm.begin_transaction();
  583. realm.cancel_transaction();
  584. }
  585. }
  586. };
  587. r->m_binding_context.reset(new Context(*r));
  588. make_remote_change(); // 1
  589. coordinator->on_change();
  590. make_remote_change(); // 2
  591. r->notify(); // advances to version from 1
  592. }
  593. SECTION("is_in_transaction() is reported correctly within a notification from begin_transaction() and changes can be made") {
  594. bool first = true;
  595. token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  596. REQUIRE_FALSE(err);
  597. if (first) {
  598. REQUIRE_FALSE(r->is_in_transaction());
  599. first = false;
  600. }
  601. else {
  602. REQUIRE(r->is_in_transaction());
  603. table->begin()->set(col, 100);
  604. }
  605. });
  606. advance_and_notify(*r);
  607. make_remote_change();
  608. coordinator->on_change();
  609. r->begin_transaction();
  610. REQUIRE(table->begin()->get<int64_t>(col) == 100);
  611. r->cancel_transaction();
  612. REQUIRE(table->begin()->get<int64_t>(col) != 100);
  613. }
  614. SECTION("invalidate() from within notification is a no-op") {
  615. token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  616. REQUIRE_FALSE(err);
  617. r->invalidate();
  618. REQUIRE(r->is_in_read_transaction());
  619. });
  620. advance_and_notify(*r);
  621. REQUIRE(r->is_in_read_transaction());
  622. make_remote_change();
  623. coordinator->on_change();
  624. r->begin_transaction();
  625. REQUIRE(r->is_in_transaction());
  626. r->cancel_transaction();
  627. }
  628. SECTION("cancel_transaction() from within notification ends the write transaction started by begin_transaction()") {
  629. token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  630. REQUIRE_FALSE(err);
  631. if (r->is_in_transaction())
  632. r->cancel_transaction();
  633. });
  634. advance_and_notify(*r);
  635. make_remote_change();
  636. coordinator->on_change();
  637. r->begin_transaction();
  638. REQUIRE_FALSE(r->is_in_transaction());
  639. }
  640. }
  641. TEST_CASE("notifications: skip") {
  642. _impl::RealmCoordinator::assert_no_open_realms();
  643. InMemoryTestFile config;
  644. config.automatic_change_notifications = false;
  645. auto r = Realm::get_shared_realm(config);
  646. r->update_schema({
  647. {"object", {
  648. {"value", PropertyType::Int}
  649. }},
  650. });
  651. auto coordinator = _impl::RealmCoordinator::get_coordinator(config.path);
  652. auto table = r->read_group().get_table("class_object");
  653. auto col = table->get_column_key("value");
  654. r->begin_transaction();
  655. for (int i = 0; i < 10; ++i)
  656. table->create_object().set(col, i * 2);
  657. r->commit_transaction();
  658. Results results(r, table->where());
  659. auto add_callback = [](Results& results, int& calls, CollectionChangeSet& changes) {
  660. return results.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  661. REQUIRE_FALSE(err);
  662. ++calls;
  663. changes = std::move(c);
  664. });
  665. };
  666. auto make_local_change = [&](auto& token) {
  667. r->begin_transaction();
  668. table->create_object();
  669. token.suppress_next();
  670. r->commit_transaction();
  671. };
  672. auto make_remote_change = [&] {
  673. auto r2 = coordinator->get_realm(util::Scheduler::get_frozen());
  674. r2->begin_transaction();
  675. r2->read_group().get_table("class_object")->create_object();
  676. r2->commit_transaction();
  677. };
  678. int calls1 = 0;
  679. CollectionChangeSet changes1;
  680. auto token1 = add_callback(results, calls1, changes1);
  681. SECTION("no notification is sent when only callback is skipped") {
  682. advance_and_notify(*r);
  683. REQUIRE(calls1 == 1);
  684. make_local_change(token1);
  685. advance_and_notify(*r);
  686. REQUIRE(calls1 == 1);
  687. REQUIRE(changes1.empty());
  688. }
  689. SECTION("unskipped tokens for the same Results are still delivered") {
  690. int calls2 = 0;
  691. CollectionChangeSet changes2;
  692. auto token2 = add_callback(results, calls2, changes2);
  693. advance_and_notify(*r);
  694. REQUIRE(calls1 == 1);
  695. REQUIRE(calls2 == 1);
  696. make_local_change(token1);
  697. advance_and_notify(*r);
  698. REQUIRE(calls1 == 1);
  699. REQUIRE(changes1.empty());
  700. REQUIRE(calls2 == 2);
  701. REQUIRE_INDICES(changes2.insertions, 10);
  702. }
  703. SECTION("unskipped tokens for different Results are still delivered") {
  704. Results results2(r, table->where());
  705. int calls2 = 0;
  706. CollectionChangeSet changes2;
  707. auto token2 = add_callback(results2, calls2, changes2);
  708. advance_and_notify(*r);
  709. REQUIRE(calls1 == 1);
  710. REQUIRE(calls2 == 1);
  711. make_local_change(token1);
  712. advance_and_notify(*r);
  713. REQUIRE(calls1 == 1);
  714. REQUIRE(changes1.empty());
  715. REQUIRE(calls2 == 2);
  716. REQUIRE_INDICES(changes2.insertions, 10);
  717. }
  718. SECTION("additional commits which occur before calculation are merged in") {
  719. int calls2 = 0;
  720. CollectionChangeSet changes2;
  721. auto token2 = add_callback(results, calls2, changes2);
  722. advance_and_notify(*r);
  723. REQUIRE(calls1 == 1);
  724. REQUIRE(calls2 == 1);
  725. make_local_change(token1);
  726. make_remote_change();
  727. advance_and_notify(*r);
  728. REQUIRE(calls1 == 2);
  729. REQUIRE_INDICES(changes1.insertions, 11);
  730. REQUIRE(calls2 == 2);
  731. REQUIRE_INDICES(changes2.insertions, 10, 11);
  732. }
  733. SECTION("additional commits which occur before delivery are merged in") {
  734. int calls2 = 0;
  735. CollectionChangeSet changes2;
  736. auto token2 = add_callback(results, calls2, changes2);
  737. advance_and_notify(*r);
  738. REQUIRE(calls1 == 1);
  739. REQUIRE(calls2 == 1);
  740. make_local_change(token1);
  741. coordinator->on_change();
  742. make_remote_change();
  743. advance_and_notify(*r);
  744. REQUIRE(calls1 == 2);
  745. REQUIRE_INDICES(changes1.insertions, 11);
  746. REQUIRE(calls2 == 2);
  747. REQUIRE_INDICES(changes2.insertions, 10, 11);
  748. }
  749. SECTION("skipping must be done from within a write transaction") {
  750. REQUIRE_THROWS(token1.suppress_next());
  751. }
  752. SECTION("skipping must be done from the Realm's thread") {
  753. advance_and_notify(*r);
  754. r->begin_transaction();
  755. std::thread([&] {
  756. REQUIRE_THROWS(token1.suppress_next());
  757. }).join();
  758. r->cancel_transaction();
  759. }
  760. SECTION("new notifiers do not interfere with skipping") {
  761. advance_and_notify(*r);
  762. REQUIRE(calls1 == 1);
  763. CollectionChangeSet changes;
  764. // new notifier at a version before the skipped one
  765. auto r2 = coordinator->get_realm();
  766. Results results2(r2, r2->read_group().get_table("class_object")->where());
  767. int calls2 = 0;
  768. auto token2 = add_callback(results2, calls2, changes);
  769. make_local_change(token1);
  770. // new notifier at the skipped version
  771. auto r3 = coordinator->get_realm();
  772. Results results3(r3, r3->read_group().get_table("class_object")->where());
  773. int calls3 = 0;
  774. auto token3 = add_callback(results3, calls3, changes);
  775. make_remote_change();
  776. // new notifier at version after the skipped one
  777. auto r4 = coordinator->get_realm();
  778. Results results4(r4, r4->read_group().get_table("class_object")->where());
  779. int calls4 = 0;
  780. auto token4 = add_callback(results4, calls4, changes);
  781. coordinator->on_change();
  782. r->notify();
  783. r2->notify();
  784. r3->notify();
  785. r4->notify();
  786. REQUIRE(calls1 == 2);
  787. REQUIRE(calls2 == 1);
  788. REQUIRE(calls3 == 1);
  789. REQUIRE(calls4 == 1);
  790. }
  791. SECTION("skipping only effects the current transaction even if no notification would occur anyway") {
  792. advance_and_notify(*r);
  793. REQUIRE(calls1 == 1);
  794. // would not produce a notification even if it wasn't skipped because no changes were made
  795. r->begin_transaction();
  796. token1.suppress_next();
  797. r->commit_transaction();
  798. advance_and_notify(*r);
  799. REQUIRE(calls1 == 1);
  800. // should now produce a notification
  801. r->begin_transaction();
  802. table->create_object();
  803. r->commit_transaction();
  804. advance_and_notify(*r);
  805. REQUIRE(calls1 == 2);
  806. }
  807. SECTION("removing skipped notifier before it gets the chance to run") {
  808. advance_and_notify(*r);
  809. REQUIRE(calls1 == 1);
  810. // Set the skip version
  811. make_local_change(token1);
  812. // Advance the file to a version after the skip version
  813. make_remote_change();
  814. REQUIRE(calls1 == 1);
  815. // Remove the skipped notifier and add an entirely new notifier, so that
  816. // notifications need to run but the skip logic shouldn't be used
  817. token1 = {};
  818. results = {};
  819. Results results2(r, table->where());
  820. auto token2 = add_callback(results2, calls1, changes1);
  821. advance_and_notify(*r);
  822. REQUIRE(calls1 == 2);
  823. }
  824. }
  825. TEST_CASE("notifications: TableView delivery") {
  826. _impl::RealmCoordinator::assert_no_open_realms();
  827. InMemoryTestFile config;
  828. config.automatic_change_notifications = false;
  829. config.max_number_of_active_versions = 5;
  830. auto r = Realm::get_shared_realm(config);
  831. r->update_schema({
  832. {"object", {
  833. {"value", PropertyType::Int}
  834. }},
  835. });
  836. auto coordinator = _impl::RealmCoordinator::get_coordinator(config.path);
  837. auto table = r->read_group().get_table("class_object");
  838. auto col = table->get_column_key("value");
  839. r->begin_transaction();
  840. for (int i = 0; i < 10; ++i)
  841. table->create_object().set(col, i * 2);
  842. r->commit_transaction();
  843. Results results(r, table->where());
  844. results.set_update_policy(Results::UpdatePolicy::AsyncOnly);
  845. SECTION("Initial run never happens with no callbacks") {
  846. advance_and_notify(*r);
  847. REQUIRE(results.get_mode() == Results::Mode::Query);
  848. }
  849. results.evaluate_query_if_needed();
  850. // Create and immediately remove a callback so that the notifier gets created
  851. // even though we have automatic change notifications disabled
  852. static_cast<void>(results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {}));
  853. REQUIRE(results.get_mode() == Results::Mode::TableView);
  854. REQUIRE(results.size() == 0);
  855. auto make_local_change = [&] {
  856. r->begin_transaction();
  857. table->create_object();
  858. r->commit_transaction();
  859. };
  860. auto make_remote_change = [&] {
  861. auto r2 = coordinator->get_realm(util::Scheduler::get_frozen());
  862. r2->begin_transaction();
  863. r2->read_group().get_table("class_object")->create_object();
  864. r2->commit_transaction();
  865. };
  866. SECTION("does not update after local change with no on_change") {
  867. make_local_change();
  868. REQUIRE(results.size() == 0);
  869. }
  870. SECTION("TV is delivered when no commit is made") {
  871. advance_and_notify(*r);
  872. REQUIRE(results.get_mode() == Results::Mode::TableView);
  873. REQUIRE(results.size() == 10);
  874. }
  875. SECTION("TV is not delivered when notifier version > local version") {
  876. make_remote_change();
  877. r->refresh();
  878. REQUIRE(results.size() == 0);
  879. }
  880. SECTION("TV is delivered when notifier version = local version") {
  881. make_remote_change();
  882. advance_and_notify(*r);
  883. REQUIRE(results.size() == 11);
  884. }
  885. SECTION("TV is delivered when previous TV wasn't used due to never refreshing") {
  886. // These two generate TVs that never get used
  887. make_remote_change();
  888. on_change_but_no_notify(*r);
  889. make_remote_change();
  890. on_change_but_no_notify(*r);
  891. // But we generate a third one anyway because the main thread never even
  892. // got a chance to use them, rather than it not wanting them
  893. make_remote_change();
  894. advance_and_notify(*r);
  895. REQUIRE(results.size() == 13);
  896. }
  897. SECTION("TV is not delivered when main thread refreshed but previous TV was not used") {
  898. // First run generates a TV that's unused
  899. make_remote_change();
  900. advance_and_notify(*r);
  901. // When the second run is delivered we discover first run wasn't used
  902. make_remote_change();
  903. advance_and_notify(*r);
  904. // And then third one doesn't run at all
  905. make_remote_change();
  906. advance_and_notify(*r);
  907. // And we can't use the old TV because it's out of date
  908. REQUIRE(results.size() == 0);
  909. // We don't start implicitly updating again even after it is used
  910. make_remote_change();
  911. advance_and_notify(*r);
  912. REQUIRE(results.size() == 0);
  913. }
  914. SECTION("TV can be delivered in a write transaction") {
  915. make_remote_change();
  916. advance_and_notify(*r);
  917. r->begin_transaction();
  918. REQUIRE(results.size() == 11);
  919. r->cancel_transaction();
  920. }
  921. SECTION("unused background TVs do not pin old versions forever") {
  922. // This will exceed the maximum active version count (5) if any
  923. // transactions are being pinned, resulting in make_remote_change() throwing
  924. for (int i = 0; i < 10; ++i) {
  925. REQUIRE_NOTHROW(make_remote_change());
  926. advance_and_notify(*r);
  927. }
  928. }
  929. }
  930. #if REALM_PLATFORM_APPLE && NOTIFIER_BACKGROUND_ERRORS
  931. TEST_CASE("notifications: async error handling") {
  932. _impl::RealmCoordinator::assert_no_open_realms();
  933. InMemoryTestFile config;
  934. config.automatic_change_notifications = false;
  935. auto r = Realm::get_shared_realm(config);
  936. r->update_schema({
  937. {"object", {
  938. {"value", PropertyType::Int},
  939. }},
  940. });
  941. auto coordinator = _impl::RealmCoordinator::get_coordinator(config.path);
  942. Results results(r, *r->read_group().get_table("class_object"));
  943. auto r2 = Realm::get_shared_realm(config);
  944. class OpenFileLimiter {
  945. public:
  946. OpenFileLimiter()
  947. {
  948. // Set the max open files to zero so that opening new files will fail
  949. getrlimit(RLIMIT_NOFILE, &m_old);
  950. rlimit rl = m_old;
  951. rl.rlim_cur = 0;
  952. setrlimit(RLIMIT_NOFILE, &rl);
  953. }
  954. ~OpenFileLimiter()
  955. {
  956. setrlimit(RLIMIT_NOFILE, &m_old);
  957. }
  958. private:
  959. rlimit m_old;
  960. };
  961. SECTION("error when opening the advancer SG") {
  962. OpenFileLimiter limiter;
  963. bool called = false;
  964. auto token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  965. REQUIRE(err);
  966. REQUIRE_FALSE(called);
  967. called = true;
  968. });
  969. REQUIRE(!called);
  970. SECTION("error is delivered on notify() without changes") {
  971. coordinator->on_change();
  972. REQUIRE(!called);
  973. r->notify();
  974. REQUIRE(called);
  975. }
  976. SECTION("error is delivered on notify() with changes") {
  977. r2->begin_transaction(); r2->commit_transaction();
  978. REQUIRE(!called);
  979. coordinator->on_change();
  980. REQUIRE(!called);
  981. r->notify();
  982. REQUIRE(called);
  983. }
  984. SECTION("error is delivered on refresh() without changes") {
  985. coordinator->on_change();
  986. REQUIRE(!called);
  987. r->refresh();
  988. REQUIRE(called);
  989. }
  990. SECTION("error is delivered on refresh() with changes") {
  991. r2->begin_transaction(); r2->commit_transaction();
  992. REQUIRE(!called);
  993. coordinator->on_change();
  994. REQUIRE(!called);
  995. r->refresh();
  996. REQUIRE(called);
  997. }
  998. SECTION("error is delivered on begin_transaction() without changes") {
  999. coordinator->on_change();
  1000. REQUIRE(!called);
  1001. r->begin_transaction();
  1002. REQUIRE(called);
  1003. r->cancel_transaction();
  1004. }
  1005. SECTION("error is delivered on begin_transaction() with changes") {
  1006. r2->begin_transaction(); r2->commit_transaction();
  1007. REQUIRE(!called);
  1008. coordinator->on_change();
  1009. REQUIRE(!called);
  1010. r->begin_transaction();
  1011. REQUIRE(called);
  1012. r->cancel_transaction();
  1013. }
  1014. SECTION("adding another callback sends the error to only the newly added one") {
  1015. advance_and_notify(*r);
  1016. REQUIRE(called);
  1017. bool called2 = false;
  1018. auto token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1019. REQUIRE(err);
  1020. REQUIRE_FALSE(called2);
  1021. called2 = true;
  1022. });
  1023. advance_and_notify(*r);
  1024. REQUIRE(called2);
  1025. }
  1026. SECTION("destroying a token from before the error does not remove newly added callbacks") {
  1027. advance_and_notify(*r);
  1028. bool called = false;
  1029. auto token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1030. REQUIRE(err);
  1031. REQUIRE_FALSE(called);
  1032. called = true;
  1033. });
  1034. token = {};
  1035. advance_and_notify(*r);
  1036. REQUIRE(called);
  1037. }
  1038. SECTION("adding another callback from within an error callback defers delivery") {
  1039. NotificationToken token2;
  1040. token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  1041. token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1042. REQUIRE(err);
  1043. REQUIRE_FALSE(called);
  1044. called = true;
  1045. });
  1046. });
  1047. advance_and_notify(*r);
  1048. REQUIRE(!called);
  1049. advance_and_notify(*r);
  1050. REQUIRE(called);
  1051. }
  1052. SECTION("adding a callback to a different collection from within the error callback defers delivery") {
  1053. auto results2 = results;
  1054. NotificationToken token2;
  1055. token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) {
  1056. token2 = results2.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1057. REQUIRE(err);
  1058. REQUIRE_FALSE(called);
  1059. called = true;
  1060. });
  1061. });
  1062. advance_and_notify(*r);
  1063. REQUIRE(!called);
  1064. advance_and_notify(*r);
  1065. REQUIRE(called);
  1066. }
  1067. }
  1068. SECTION("error when opening the executor SG") {
  1069. SECTION("error is delivered asynchronously") {
  1070. bool called = false;
  1071. auto token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1072. REQUIRE(err);
  1073. called = true;
  1074. });
  1075. OpenFileLimiter limiter;
  1076. REQUIRE(!called);
  1077. coordinator->on_change();
  1078. REQUIRE(!called);
  1079. r->notify();
  1080. REQUIRE(called);
  1081. }
  1082. SECTION("adding another callback only sends the error to the new one") {
  1083. bool called = false;
  1084. auto token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1085. REQUIRE(err);
  1086. REQUIRE_FALSE(called);
  1087. called = true;
  1088. });
  1089. OpenFileLimiter limiter;
  1090. advance_and_notify(*r);
  1091. bool called2 = false;
  1092. auto token2 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1093. REQUIRE(err);
  1094. REQUIRE_FALSE(called2);
  1095. called2 = true;
  1096. });
  1097. advance_and_notify(*r);
  1098. REQUIRE(called2);
  1099. }
  1100. }
  1101. }
  1102. #endif
  1103. #if REALM_ENABLE_SYNC
  1104. TEST_CASE("notifications: sync") {
  1105. _impl::RealmCoordinator::assert_no_open_realms();
  1106. SyncServer server(false);
  1107. SyncTestFile config(server);
  1108. config.schema = Schema{
  1109. {"object", {
  1110. {"value", PropertyType::Int},
  1111. }},
  1112. };
  1113. SECTION("sync progress commits do not distrupt notifications") {
  1114. auto r = Realm::get_shared_realm(config);
  1115. auto wait_realm = Realm::get_shared_realm(config);
  1116. Results results(r, r->read_group().get_table("class_object"));
  1117. Results wait_results(wait_realm, wait_realm->read_group().get_table("class_object"));
  1118. auto token1 = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) { });
  1119. auto token2 = wait_results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr) { });
  1120. // Add an object to the Realm so that notifications are needed
  1121. {
  1122. auto write_realm = Realm::get_shared_realm(config);
  1123. write_realm->begin_transaction();
  1124. write_realm->read_group().get_table("class_object")->create_object();
  1125. write_realm->commit_transaction();
  1126. }
  1127. // Wait for the notifications to become ready for the new version
  1128. wait_realm->refresh();
  1129. // Start the server and wait for the Realm to be uploaded so that sync
  1130. // makes some writes to the Realm and bumps the version
  1131. server.start();
  1132. wait_for_upload(*r);
  1133. // Make sure that the notifications still get delivered rather than
  1134. // waiting forever due to that we don't get a commit notification from
  1135. // the commits sync makes to store the upload progress
  1136. r->refresh();
  1137. }
  1138. }
  1139. #endif
  1140. TEST_CASE("notifications: results") {
  1141. _impl::RealmCoordinator::assert_no_open_realms();
  1142. InMemoryTestFile config;
  1143. config.automatic_change_notifications = false;
  1144. auto r = Realm::get_shared_realm(config);
  1145. r->update_schema({
  1146. {"object", {
  1147. {"value", PropertyType::Int},
  1148. {"link", PropertyType::Object|PropertyType::Nullable, "linked to object"}
  1149. }},
  1150. {"other object", {
  1151. {"value", PropertyType::Int}
  1152. }},
  1153. {"linking object", {
  1154. {"link", PropertyType::Object|PropertyType::Nullable, "object"}
  1155. }},
  1156. {"linked to object", {
  1157. {"value", PropertyType::Int}
  1158. }}
  1159. });
  1160. auto coordinator = _impl::RealmCoordinator::get_coordinator(config.path);
  1161. auto table = r->read_group().get_table("class_object");
  1162. auto col_value = table->get_column_key("value");
  1163. auto col_link = table->get_column_key("link");
  1164. r->begin_transaction();
  1165. std::vector<ObjKey> target_keys;
  1166. r->read_group().get_table("class_linked to object")->create_objects(10, target_keys);
  1167. ObjKeys object_keys({3, 4, 7, 9, 10, 21, 24, 34, 42, 50});
  1168. for (int i = 0; i < 10; ++i) {
  1169. table->create_object(object_keys[i]).set_all(i * 2, target_keys[i]);
  1170. }
  1171. r->commit_transaction();
  1172. auto r2 = coordinator->get_realm();
  1173. auto r2_table = r2->read_group().get_table("class_object");
  1174. Results results(r, table->where().greater(col_value, 0).less(col_value, 10));
  1175. SECTION("unsorted notifications") {
  1176. int notification_calls = 0;
  1177. CollectionChangeSet change;
  1178. auto token = results.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  1179. REQUIRE_FALSE(err);
  1180. change = c;
  1181. ++notification_calls;
  1182. });
  1183. advance_and_notify(*r);
  1184. auto write = [&](auto&& f) {
  1185. r->begin_transaction();
  1186. f();
  1187. r->commit_transaction();
  1188. advance_and_notify(*r);
  1189. };
  1190. SECTION("modifications to unrelated tables do not send notifications") {
  1191. write([&] {
  1192. r->read_group().get_table("class_other object")->create_object();
  1193. });
  1194. REQUIRE(notification_calls == 1);
  1195. }
  1196. SECTION("irrelevant modifications to linked tables do not send notifications") {
  1197. write([&] {
  1198. r->read_group().get_table("class_linked to object")->create_object();
  1199. });
  1200. REQUIRE(notification_calls == 1);
  1201. }
  1202. SECTION("irrelevant modifications to linking tables do not send notifications") {
  1203. write([&] {
  1204. r->read_group().get_table("class_linking object")->create_object();
  1205. });
  1206. REQUIRE(notification_calls == 1);
  1207. }
  1208. SECTION("modifications that leave a non-matching row non-matching do not send notifications") {
  1209. write([&] {
  1210. table->get_object(object_keys[6]).set(col_value, 13);
  1211. });
  1212. REQUIRE(notification_calls == 1);
  1213. }
  1214. SECTION("deleting non-matching rows does not send a notification") {
  1215. write([&] {
  1216. table->remove_object(object_keys[0]);
  1217. table->remove_object(object_keys[6]);
  1218. });
  1219. REQUIRE(notification_calls == 1);
  1220. }
  1221. SECTION("modifying a matching row and leaving it matching marks that row as modified") {
  1222. write([&] {
  1223. table->get_object(object_keys[1]).set(col_value, 3);
  1224. });
  1225. REQUIRE(notification_calls == 2);
  1226. REQUIRE_INDICES(change.modifications, 0);
  1227. REQUIRE_INDICES(change.modifications_new, 0);
  1228. }
  1229. SECTION("modifying a matching row to no longer match marks that row as deleted") {
  1230. write([&] {
  1231. table->get_object(object_keys[2]).set(col_value, 0);
  1232. });
  1233. REQUIRE(notification_calls == 2);
  1234. REQUIRE_INDICES(change.deletions, 1);
  1235. }
  1236. SECTION("modifying a non-matching row to match marks that row as inserted, but not modified") {
  1237. write([&] {
  1238. table->get_object(object_keys[7]).set(col_value, 3);
  1239. });
  1240. REQUIRE(notification_calls == 2);
  1241. REQUIRE_INDICES(change.insertions, 4);
  1242. REQUIRE(change.modifications.empty());
  1243. REQUIRE(change.modifications_new.empty());
  1244. }
  1245. SECTION("deleting a matching row marks that row as deleted") {
  1246. write([&] {
  1247. table->remove_object(object_keys[3]);
  1248. });
  1249. REQUIRE(notification_calls == 2);
  1250. REQUIRE_INDICES(change.deletions, 2);
  1251. }
  1252. SECTION("modifications from multiple transactions are collapsed") {
  1253. r2->begin_transaction();
  1254. r2_table->get_object(object_keys[0]).set(col_value, 6);
  1255. r2->commit_transaction();
  1256. coordinator->on_change();
  1257. r2->begin_transaction();
  1258. r2_table->get_object(object_keys[1]).set(col_value,03);
  1259. r2->commit_transaction();
  1260. REQUIRE(notification_calls == 1);
  1261. coordinator->on_change();
  1262. r->notify();
  1263. REQUIRE(notification_calls == 2);
  1264. }
  1265. SECTION("inserting a row then modifying it in a second transaction does not report it as modified") {
  1266. r2->begin_transaction();
  1267. ObjKey k = r2_table->create_object(ObjKey(53)).set(col_value, 6).get_key();
  1268. r2->commit_transaction();
  1269. coordinator->on_change();
  1270. r2->begin_transaction();
  1271. r2_table->get_object(k).set(col_value, 7);
  1272. r2->commit_transaction();
  1273. advance_and_notify(*r);
  1274. REQUIRE(notification_calls == 2);
  1275. REQUIRE_INDICES(change.insertions, 4);
  1276. REQUIRE(change.modifications.empty());
  1277. REQUIRE(change.modifications_new.empty());
  1278. }
  1279. SECTION("modification indices are pre-insert/delete") {
  1280. r->begin_transaction();
  1281. table->get_object(object_keys[2]).set(col_value, 0);
  1282. table->get_object(object_keys[3]).set(col_value, 6);
  1283. r->commit_transaction();
  1284. advance_and_notify(*r);
  1285. REQUIRE(notification_calls == 2);
  1286. REQUIRE_INDICES(change.deletions, 1);
  1287. REQUIRE_INDICES(change.modifications, 2);
  1288. REQUIRE_INDICES(change.modifications_new, 1);
  1289. }
  1290. SECTION("notifications are not delivered when collapsing transactions results in no net change") {
  1291. r2->begin_transaction();
  1292. ObjKey k = r2_table->create_object().set(col_value, 5).get_key();
  1293. r2->commit_transaction();
  1294. coordinator->on_change();
  1295. r2->begin_transaction();
  1296. r2_table->remove_object(k);
  1297. r2->commit_transaction();
  1298. REQUIRE(notification_calls == 1);
  1299. coordinator->on_change();
  1300. r->notify();
  1301. REQUIRE(notification_calls == 1);
  1302. }
  1303. SECTION("inserting a non-matching row at the beginning does not produce a notification") {
  1304. write([&] {
  1305. table->create_object(ObjKey(1));
  1306. });
  1307. REQUIRE(notification_calls == 1);
  1308. }
  1309. SECTION("inserting a matching row at the beginning marks just it as inserted") {
  1310. write([&] {
  1311. table->create_object(ObjKey(0)).set(col_value, 5);
  1312. });
  1313. REQUIRE(notification_calls == 2);
  1314. REQUIRE_INDICES(change.insertions, 0);
  1315. }
  1316. SECTION("modification to related table not included in query") {
  1317. write([&] {
  1318. auto table = r->read_group().get_table("class_linked to object");
  1319. auto col = table->get_column_key("value");
  1320. auto obj = table->get_object(target_keys[1]);
  1321. obj.set(col, 42); // Will affect first entry in results
  1322. });
  1323. REQUIRE(notification_calls == 2);
  1324. REQUIRE_INDICES(change.modifications, 0);
  1325. }
  1326. }
  1327. SECTION("before/after change callback") {
  1328. struct Callback {
  1329. size_t before_calls = 0;
  1330. size_t after_calls = 0;
  1331. CollectionChangeSet before_change;
  1332. CollectionChangeSet after_change;
  1333. std::function<void(void)> on_before = []{};
  1334. std::function<void(void)> on_after = []{};
  1335. void before(CollectionChangeSet c) {
  1336. before_change = c;
  1337. ++before_calls;
  1338. on_before();
  1339. }
  1340. void after(CollectionChangeSet c) {
  1341. after_change = c;
  1342. ++after_calls;
  1343. on_after();
  1344. }
  1345. void error(std::exception_ptr) {
  1346. FAIL("error() should not be called");
  1347. }
  1348. } callback;
  1349. auto token = results.add_notification_callback(&callback);
  1350. advance_and_notify(*r);
  1351. SECTION("only after() is called for initial results") {
  1352. REQUIRE(callback.before_calls == 0);
  1353. REQUIRE(callback.after_calls == 1);
  1354. REQUIRE(callback.after_change.empty());
  1355. }
  1356. auto write = [&](auto&& func) {
  1357. r2->begin_transaction();
  1358. func(*r2_table);
  1359. r2->commit_transaction();
  1360. advance_and_notify(*r);
  1361. };
  1362. SECTION("both are called after a write") {
  1363. write([&](auto&& t) {
  1364. t.create_object(ObjKey(53)).set(col_value, 5);
  1365. });
  1366. REQUIRE(callback.before_calls == 1);
  1367. REQUIRE(callback.after_calls == 2);
  1368. REQUIRE_INDICES(callback.before_change.insertions, 4);
  1369. REQUIRE_INDICES(callback.after_change.insertions, 4);
  1370. }
  1371. SECTION("deleted objects are usable in before()") {
  1372. callback.on_before = [&] {
  1373. REQUIRE(results.size() == 4);
  1374. REQUIRE_INDICES(callback.before_change.deletions, 0);
  1375. REQUIRE(results.get(0).is_valid());
  1376. REQUIRE(results.get(0).get<int64_t>(col_value) == 2);
  1377. };
  1378. write([&](auto&& t) {
  1379. t.remove_object(results.get(0).get_key());
  1380. });
  1381. REQUIRE(callback.before_calls == 1);
  1382. REQUIRE(callback.after_calls == 2);
  1383. }
  1384. SECTION("inserted objects are usable in after()") {
  1385. callback.on_after = [&] {
  1386. REQUIRE(results.size() == 5);
  1387. REQUIRE_INDICES(callback.after_change.insertions, 4);
  1388. REQUIRE(results.last()->get<int64_t>(col_value) == 5);
  1389. };
  1390. write([&](auto&& t) {
  1391. t.create_object(ObjKey(53)).set(col_value, 5);
  1392. });
  1393. REQUIRE(callback.before_calls == 1);
  1394. REQUIRE(callback.after_calls == 2);
  1395. }
  1396. }
  1397. SECTION("sorted notifications") {
  1398. // Sort in descending order
  1399. results = results.sort({{{col_value}}, {false}});
  1400. int notification_calls = 0;
  1401. CollectionChangeSet change;
  1402. auto token = results.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  1403. REQUIRE_FALSE(err);
  1404. change = c;
  1405. ++notification_calls;
  1406. });
  1407. advance_and_notify(*r);
  1408. auto write = [&](auto&& f) {
  1409. r->begin_transaction();
  1410. f();
  1411. r->commit_transaction();
  1412. advance_and_notify(*r);
  1413. };
  1414. SECTION("modifications that leave a non-matching row non-matching do not send notifications") {
  1415. write([&] {
  1416. table->get_object(object_keys[6]).set(col_value, 13);
  1417. });
  1418. REQUIRE(notification_calls == 1);
  1419. }
  1420. SECTION("deleting non-matching rows does not send a notification") {
  1421. write([&] {
  1422. table->remove_object(object_keys[0]);
  1423. table->remove_object(object_keys[6]);
  1424. });
  1425. REQUIRE(notification_calls == 1);
  1426. }
  1427. SECTION("modifying a matching row and leaving it matching marks that row as modified") {
  1428. write([&] {
  1429. table->get_object(object_keys[1]).set(col_value, 3);
  1430. });
  1431. REQUIRE(notification_calls == 2);
  1432. REQUIRE_INDICES(change.modifications, 3);
  1433. REQUIRE_INDICES(change.modifications_new, 3);
  1434. }
  1435. SECTION("modifying a matching row to no longer match marks that row as deleted") {
  1436. write([&] {
  1437. table->get_object(object_keys[2]).set(col_value, 0);
  1438. });
  1439. REQUIRE(notification_calls == 2);
  1440. REQUIRE_INDICES(change.deletions, 2);
  1441. }
  1442. SECTION("modifying a non-matching row to match marks that row as inserted") {
  1443. write([&] {
  1444. table->get_object(object_keys[7]).set(col_value, 3);
  1445. });
  1446. REQUIRE(notification_calls == 2);
  1447. REQUIRE_INDICES(change.insertions, 3);
  1448. }
  1449. SECTION("deleting a matching row marks that row as deleted") {
  1450. write([&] {
  1451. table->remove_object(object_keys[3]);
  1452. });
  1453. REQUIRE(notification_calls == 2);
  1454. REQUIRE_INDICES(change.deletions, 1);
  1455. }
  1456. SECTION("clearing the table marks all rows as deleted") {
  1457. size_t num_expected_deletes = results.size();
  1458. write([&] {
  1459. table->clear();
  1460. });
  1461. REQUIRE(notification_calls == 2);
  1462. REQUIRE(change.deletions.count() == num_expected_deletes);
  1463. }
  1464. SECTION("clear insert clear marks the correct rows as deleted") {
  1465. size_t num_expected_deletes = results.size();
  1466. write([&] {
  1467. table->clear();
  1468. });
  1469. REQUIRE(notification_calls == 2);
  1470. REQUIRE(change.deletions.count() == num_expected_deletes);
  1471. write([&] {
  1472. table->create_object().set(col_value, 3);
  1473. table->create_object().set(col_value, 4);
  1474. table->create_object().set(col_value, 5);
  1475. });
  1476. REQUIRE(notification_calls == 3);
  1477. REQUIRE_INDICES(change.insertions, 0, 1, 2);
  1478. REQUIRE(change.deletions.empty());
  1479. write([&] {
  1480. table->clear();
  1481. });
  1482. REQUIRE(notification_calls == 4);
  1483. REQUIRE_INDICES(change.deletions, 0, 1, 2);
  1484. REQUIRE(change.insertions.empty());
  1485. REQUIRE(change.modifications.empty());
  1486. }
  1487. SECTION("delete insert clear marks the correct rows as deleted") {
  1488. size_t num_expected_deletes = results.size();
  1489. write([&] {
  1490. results.clear(); // delete all 4 matches
  1491. });
  1492. REQUIRE(notification_calls == 2);
  1493. REQUIRE(change.deletions.count() == num_expected_deletes);
  1494. write([&] {
  1495. table->create_object(ObjKey(57)).set(col_value, 3);
  1496. table->create_object(ObjKey(58)).set(col_value, 4);
  1497. table->create_object(ObjKey(59)).set(col_value, 5);
  1498. });
  1499. REQUIRE(notification_calls == 3);
  1500. REQUIRE_INDICES(change.insertions, 0, 1, 2);
  1501. REQUIRE(change.deletions.empty());
  1502. write([&] {
  1503. table->clear();
  1504. });
  1505. REQUIRE(notification_calls == 4);
  1506. REQUIRE_INDICES(change.deletions, 0, 1, 2);
  1507. REQUIRE(change.insertions.empty());
  1508. REQUIRE(change.modifications.empty());
  1509. }
  1510. SECTION("modifying a matching row to change its position sends insert+delete") {
  1511. write([&] {
  1512. table->get_object(object_keys[2]).set(col_value, 9);
  1513. });
  1514. REQUIRE(notification_calls == 2);
  1515. REQUIRE_INDICES(change.deletions, 2);
  1516. REQUIRE_INDICES(change.insertions, 0);
  1517. }
  1518. SECTION("modifications from multiple transactions are collapsed") {
  1519. r2->begin_transaction();
  1520. r2_table->get_object(object_keys[0]).set(col_value, 5);
  1521. r2->commit_transaction();
  1522. r2->begin_transaction();
  1523. r2_table->get_object(object_keys[1]).set(col_value, 0);
  1524. r2->commit_transaction();
  1525. REQUIRE(notification_calls == 1);
  1526. advance_and_notify(*r);
  1527. REQUIRE(notification_calls == 2);
  1528. }
  1529. SECTION("moving a matching row by deleting all other rows") {
  1530. r->begin_transaction();
  1531. table->clear();
  1532. ObjKey k0 = table->create_object().set(col_value, 15).get_key();
  1533. table->create_object().set(col_value, 5);
  1534. r->commit_transaction();
  1535. advance_and_notify(*r);
  1536. write([&] {
  1537. table->remove_object(k0);
  1538. table->create_object().set(col_value, 3);
  1539. });
  1540. REQUIRE(notification_calls == 3);
  1541. REQUIRE(change.deletions.empty());
  1542. REQUIRE_INDICES(change.insertions, 1);
  1543. }
  1544. }
  1545. SECTION("distinct notifications") {
  1546. results = results.distinct(DistinctDescriptor({{col_value}}));
  1547. int notification_calls = 0;
  1548. CollectionChangeSet change;
  1549. auto token = results.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  1550. REQUIRE_FALSE(err);
  1551. change = c;
  1552. ++notification_calls;
  1553. });
  1554. advance_and_notify(*r);
  1555. auto write = [&](auto&& f) {
  1556. r->begin_transaction();
  1557. f();
  1558. r->commit_transaction();
  1559. advance_and_notify(*r);
  1560. };
  1561. SECTION("modifications that leave a non-matching row non-matching do not send notifications") {
  1562. write([&] {
  1563. table->get_object(object_keys[6]).set(col_value, 13);
  1564. });
  1565. REQUIRE(notification_calls == 1);
  1566. }
  1567. SECTION("deleting non-matching rows does not send a notification") {
  1568. write([&] {
  1569. table->remove_object(object_keys[0]);
  1570. table->remove_object(object_keys[6]);
  1571. });
  1572. REQUIRE(notification_calls == 1);
  1573. }
  1574. SECTION("modifying a matching row and leaving it matching marks that row as modified") {
  1575. write([&] {
  1576. table->get_object(object_keys[1]).set(col_value, 3);
  1577. });
  1578. REQUIRE(notification_calls == 2);
  1579. REQUIRE_INDICES(change.modifications, 0);
  1580. REQUIRE_INDICES(change.modifications_new, 0);
  1581. }
  1582. SECTION("modifying a non-matching row which is after the distinct results in the table to be a same value \
  1583. in the distinct results doesn't send notification.") {
  1584. write([&] {
  1585. table->get_object(object_keys[6]).set(col_value, 2);
  1586. });
  1587. REQUIRE(notification_calls == 1);
  1588. }
  1589. SECTION("modifying a non-matching row which is before the distinct results in the table to be a same value \
  1590. in the distinct results send insert + delete.") {
  1591. write([&] {
  1592. table->get_object(object_keys[0]).set(col_value, 2);
  1593. });
  1594. REQUIRE(notification_calls == 2);
  1595. REQUIRE_INDICES(change.deletions, 0);
  1596. REQUIRE_INDICES(change.insertions, 0);
  1597. }
  1598. SECTION("modifying a matching row to duplicated value in distinct results marks that row as deleted") {
  1599. write([&] {
  1600. table->get_object(object_keys[2]).set(col_value, 2);
  1601. });
  1602. REQUIRE(notification_calls == 2);
  1603. REQUIRE_INDICES(change.deletions, 1);
  1604. }
  1605. SECTION("modifying a non-matching row to match and different value marks that row as inserted") {
  1606. write([&] {
  1607. table->get_object(object_keys[0]).set(col_value, 1);
  1608. });
  1609. REQUIRE(notification_calls == 2);
  1610. REQUIRE_INDICES(change.insertions, 0);
  1611. }
  1612. }
  1613. SECTION("schema changes") {
  1614. CollectionChangeSet change;
  1615. auto token = results.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  1616. REQUIRE_FALSE(err);
  1617. change = c;
  1618. });
  1619. advance_and_notify(*r);
  1620. auto write = [&](auto&& f) {
  1621. r->begin_transaction();
  1622. f();
  1623. r->commit_transaction();
  1624. advance_and_notify(*r);
  1625. };
  1626. SECTION("insert table before observed table") {
  1627. write([&] {
  1628. table->create_object(ObjKey(53)).set(col_value, 5);
  1629. r->read_group().add_table("new table");
  1630. table->create_object(ObjKey(0)).set(col_value, 5);
  1631. });
  1632. REQUIRE_INDICES(change.insertions, 0, 5);
  1633. }
  1634. auto linked_table = table->get_link_target(col_link);
  1635. auto col = linked_table->get_column_key("value");
  1636. SECTION("insert new column before link column") {
  1637. write([&] {
  1638. linked_table->get_object(target_keys[1]).set(col, 5);
  1639. table->add_column(type_Int, "new col");
  1640. linked_table->get_object(target_keys[2]).set(col, 5);
  1641. });
  1642. REQUIRE_INDICES(change.modifications, 0, 1);
  1643. }
  1644. #ifdef UNITTESTS_NOT_PARSING
  1645. SECTION("insert table before link target") {
  1646. write([&] {
  1647. linked_table->get_object(target_keys[1]).set(col, 5);
  1648. r->read_group().add_table("new table");
  1649. linked_table->get_object(target_keys[2]).set(col, 5);
  1650. });
  1651. REQUIRE_INDICES(change.modifications, 0, 1);
  1652. }
  1653. #endif
  1654. }
  1655. }
  1656. TEST_CASE("results: notifications after move") {
  1657. InMemoryTestFile config;
  1658. config.automatic_change_notifications = false;
  1659. auto r = Realm::get_shared_realm(config);
  1660. r->update_schema({
  1661. {"object", {
  1662. {"value", PropertyType::Int},
  1663. }},
  1664. });
  1665. auto table = r->read_group().get_table("class_object");
  1666. auto results = std::make_unique<Results>(r, table);
  1667. int notification_calls = 0;
  1668. auto token = results->add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  1669. REQUIRE_FALSE(err);
  1670. ++notification_calls;
  1671. });
  1672. advance_and_notify(*r);
  1673. auto write = [&](auto&& f) {
  1674. r->begin_transaction();
  1675. f();
  1676. r->commit_transaction();
  1677. advance_and_notify(*r);
  1678. };
  1679. SECTION("notifications continue to work after Results is moved (move-constructor)") {
  1680. Results r(std::move(*results));
  1681. results.reset();
  1682. write([&] {
  1683. table->create_object().set_all(1);
  1684. });
  1685. REQUIRE(notification_calls == 2);
  1686. }
  1687. SECTION("notifications continue to work after Results is moved (move-assignment)") {
  1688. Results r;
  1689. r = std::move(*results);
  1690. results.reset();
  1691. write([&] {
  1692. table->create_object().set_all(1);
  1693. });
  1694. REQUIRE(notification_calls == 2);
  1695. }
  1696. }
  1697. TEST_CASE("results: notifier with no callbacks") {
  1698. _impl::RealmCoordinator::assert_no_open_realms();
  1699. InMemoryTestFile config;
  1700. config.automatic_change_notifications = false;
  1701. auto coordinator = _impl::RealmCoordinator::get_coordinator(config.path);
  1702. auto r = coordinator->get_realm(std::move(config), none);
  1703. r->update_schema({
  1704. {"object", {
  1705. {"value", PropertyType::Int},
  1706. }},
  1707. });
  1708. auto table = r->read_group().get_table("class_object");
  1709. Results results(r, table->where());
  1710. results.last(); // force evaluation and creation of TableView
  1711. SECTION("refresh() does not block due to implicit notifier") {
  1712. // Create and then immediately remove a callback because
  1713. // `automatic_change_notifications = false` makes Results not implicitly
  1714. // create a notifier
  1715. results.add_notification_callback([](CollectionChangeSet const&, std::exception_ptr) {});
  1716. auto r2 = coordinator->get_realm(util::Scheduler::get_frozen());
  1717. r2->begin_transaction();
  1718. r2->read_group().get_table("class_object")->create_object();
  1719. r2->commit_transaction();
  1720. r->refresh(); // would deadlock if there was a callback
  1721. }
  1722. SECTION("refresh() does not attempt to deliver stale results") {
  1723. results.add_notification_callback([](CollectionChangeSet const&, std::exception_ptr) {});
  1724. // Create version 1
  1725. r->begin_transaction();
  1726. table->create_object();
  1727. r->commit_transaction();
  1728. r->begin_transaction();
  1729. // Run async query for version 1
  1730. coordinator->on_change();
  1731. // Create version 2 without ever letting 1 be delivered
  1732. table->create_object();
  1733. r->commit_transaction();
  1734. // Give it a chance to deliver the async query results (and fail, becuse
  1735. // they're for version 1 and the realm is at 2)
  1736. r->refresh();
  1737. }
  1738. SECTION("should not pin the source version even after the Realm has been closed") {
  1739. auto r2 = coordinator->get_realm();
  1740. REQUIRE(r != r2);
  1741. r->close();
  1742. auto& shared_group = TestHelper::get_shared_group(r2);
  1743. // There's always at least 2 live versions because the previous version
  1744. // isn't clean up until the *next* commit
  1745. REQUIRE(shared_group->get_number_of_versions() == 2);
  1746. auto table = r2->read_group().get_table("class_object");
  1747. r2->begin_transaction();
  1748. table->create_object();
  1749. r2->commit_transaction();
  1750. r2->begin_transaction();
  1751. table->create_object();
  1752. r2->commit_transaction();
  1753. // Would now be 3 if the closed Realm is still pinning the version it was at
  1754. REQUIRE(shared_group->get_number_of_versions() == 2);
  1755. }
  1756. }
  1757. TEST_CASE("results: error messages") {
  1758. InMemoryTestFile config;
  1759. config.schema = Schema{
  1760. {"object", {
  1761. {"value", PropertyType::String},
  1762. }},
  1763. };
  1764. auto r = Realm::get_shared_realm(config);
  1765. auto table = r->read_group().get_table("class_object");
  1766. Results results(r, table);
  1767. r->begin_transaction();
  1768. table->create_object();
  1769. r->commit_transaction();
  1770. SECTION("out of bounds access") {
  1771. REQUIRE_THROWS_WITH(results.get(5), "Requested index 5 greater than max 0");
  1772. }
  1773. SECTION("unsupported aggregate operation") {
  1774. REQUIRE_THROWS_WITH(results.sum("value"), "Cannot sum property 'value': operation not supported for 'string' properties");
  1775. }
  1776. }
  1777. TEST_CASE("results: snapshots") {
  1778. InMemoryTestFile config;
  1779. config.automatic_change_notifications = false;
  1780. config.schema = Schema{
  1781. {"object", {
  1782. {"value", PropertyType::Int},
  1783. {"array", PropertyType::Array|PropertyType::Object, "linked to object"}
  1784. }},
  1785. {"linked to object", {
  1786. {"value", PropertyType::Int}
  1787. }}
  1788. };
  1789. auto r = Realm::get_shared_realm(config);
  1790. SECTION("snapshot of empty Results") {
  1791. Results results;
  1792. auto snapshot = results.snapshot();
  1793. REQUIRE(snapshot.size() == 0);
  1794. }
  1795. auto write = [&](auto&& f) {
  1796. r->begin_transaction();
  1797. f();
  1798. r->commit_transaction();
  1799. advance_and_notify(*r);
  1800. };
  1801. SECTION("snapshot of Results based on Table") {
  1802. auto table = r->read_group().get_table("class_object");
  1803. Results results(r, table);
  1804. {
  1805. // A newly-added row should not appear in the snapshot.
  1806. auto snapshot = results.snapshot();
  1807. REQUIRE(results.size() == 0);
  1808. REQUIRE(snapshot.size() == 0);
  1809. write([=]{
  1810. table->create_object();
  1811. });
  1812. REQUIRE(results.size() == 1);
  1813. REQUIRE(snapshot.size() == 0);
  1814. }
  1815. {
  1816. // Removing a row present in the snapshot should not affect the size of the snapshot,
  1817. // but will result in the snapshot returning a detached row accessor.
  1818. auto snapshot = results.snapshot();
  1819. REQUIRE(results.size() == 1);
  1820. REQUIRE(snapshot.size() == 1);
  1821. write([=]{
  1822. table->begin()->remove();
  1823. });
  1824. REQUIRE(results.size() == 0);
  1825. REQUIRE(snapshot.size() == 1);
  1826. REQUIRE(!snapshot.get(0).is_valid());
  1827. // Adding a row at the same index that was formerly present in the snapshot shouldn't
  1828. // affect the state of the snapshot.
  1829. write([=]{
  1830. table->create_object();
  1831. });
  1832. REQUIRE(snapshot.size() == 1);
  1833. REQUIRE(!snapshot.get(0).is_valid());
  1834. }
  1835. }
  1836. SECTION("snapshot of Results based on LinkView") {
  1837. auto object = r->read_group().get_table("class_object");
  1838. auto col_link = object->get_column_key("array");
  1839. auto linked_to = r->read_group().get_table("class_linked to object");
  1840. write([=]{
  1841. object->create_object();
  1842. });
  1843. std::shared_ptr<LnkLst> lv = object->begin()->get_linklist_ptr(col_link);
  1844. Results results(r, lv);
  1845. {
  1846. // A newly-added row should not appear in the snapshot.
  1847. auto snapshot = results.snapshot();
  1848. REQUIRE(results.size() == 0);
  1849. REQUIRE(snapshot.size() == 0);
  1850. write([&]{
  1851. lv->add(linked_to->create_object().get_key());
  1852. });
  1853. REQUIRE(results.size() == 1);
  1854. REQUIRE(snapshot.size() == 0);
  1855. }
  1856. {
  1857. // Removing a row from the link list should not affect the snapshot.
  1858. auto snapshot = results.snapshot();
  1859. REQUIRE(results.size() == 1);
  1860. REQUIRE(snapshot.size() == 1);
  1861. write([&]{
  1862. lv->remove(0);
  1863. });
  1864. REQUIRE(results.size() == 0);
  1865. REQUIRE(snapshot.size() == 1);
  1866. REQUIRE(snapshot.get(0).is_valid());
  1867. // Removing a row present in the snapshot from its table should result in the snapshot
  1868. // returning a detached row accessor.
  1869. write([&]{
  1870. linked_to->begin()->remove();
  1871. });
  1872. REQUIRE(snapshot.size() == 1);
  1873. REQUIRE(!snapshot.get(0).is_valid());
  1874. // Adding a new row to the link list shouldn't affect the state of the snapshot.
  1875. write([&]{
  1876. lv->add(linked_to->create_object().get_key());
  1877. });
  1878. REQUIRE(snapshot.size() == 1);
  1879. REQUIRE(!snapshot.get(0).is_valid());
  1880. }
  1881. }
  1882. SECTION("snapshot of Results based on Query") {
  1883. auto table = r->read_group().get_table("class_object");
  1884. auto col_value = table->get_column_key("value");
  1885. Query q = table->column<Int>(col_value) > 0;
  1886. Results results(r, std::move(q));
  1887. {
  1888. // A newly-added row should not appear in the snapshot.
  1889. auto snapshot = results.snapshot();
  1890. REQUIRE(results.size() == 0);
  1891. REQUIRE(snapshot.size() == 0);
  1892. write([=]{
  1893. table->create_object().set(col_value, 1);
  1894. });
  1895. REQUIRE(results.size() == 1);
  1896. REQUIRE(snapshot.size() == 0);
  1897. }
  1898. {
  1899. // Updating a row to no longer match the query criteria should not affect the snapshot.
  1900. auto snapshot = results.snapshot();
  1901. REQUIRE(results.size() == 1);
  1902. REQUIRE(snapshot.size() == 1);
  1903. write([=]{
  1904. table->begin()->set(col_value, 0);
  1905. });
  1906. REQUIRE(results.size() == 0);
  1907. REQUIRE(snapshot.size() == 1);
  1908. REQUIRE(snapshot.get(0).is_valid());
  1909. // Removing a row present in the snapshot from its table should result in the snapshot
  1910. // returning a detached row accessor.
  1911. write([=]{
  1912. table->begin()->remove();
  1913. });
  1914. REQUIRE(snapshot.size() == 1);
  1915. REQUIRE(!snapshot.get(0).is_valid());
  1916. // Adding a new row that matches the query criteria shouldn't affect the state of the snapshot.
  1917. write([=]{
  1918. table->create_object().set(col_value, 1);
  1919. });
  1920. REQUIRE(snapshot.size() == 1);
  1921. REQUIRE(!snapshot.get(0).is_valid());
  1922. }
  1923. }
  1924. SECTION("snapshot of Results based on TableView from query") {
  1925. auto table = r->read_group().get_table("class_object");
  1926. auto col_value = table->get_column_key("value");
  1927. Query q = table->column<Int>(col_value) > 0;
  1928. Results results(r, q.find_all());
  1929. {
  1930. // A newly-added row should not appear in the snapshot.
  1931. auto snapshot = results.snapshot();
  1932. REQUIRE(results.size() == 0);
  1933. REQUIRE(snapshot.size() == 0);
  1934. write([=]{
  1935. table->create_object().set(col_value, 1);
  1936. });
  1937. REQUIRE(results.size() == 1);
  1938. REQUIRE(snapshot.size() == 0);
  1939. }
  1940. {
  1941. // Updating a row to no longer match the query criteria should not affect the snapshot.
  1942. auto snapshot = results.snapshot();
  1943. REQUIRE(results.size() == 1);
  1944. REQUIRE(snapshot.size() == 1);
  1945. write([=]{
  1946. table->begin()->set(col_value, 0);
  1947. });
  1948. REQUIRE(results.size() == 0);
  1949. REQUIRE(snapshot.size() == 1);
  1950. REQUIRE(snapshot.get(0).is_valid());
  1951. // Removing a row present in the snapshot from its table should result in the snapshot
  1952. // returning a detached row accessor.
  1953. write([=]{
  1954. table->begin()->remove();
  1955. });
  1956. REQUIRE(snapshot.size() == 1);
  1957. REQUIRE(!snapshot.get(0).is_valid());
  1958. // Adding a new row that matches the query criteria shouldn't affect the state of the snapshot.
  1959. write([=]{
  1960. table->create_object().set(col_value, 1);
  1961. });
  1962. REQUIRE(snapshot.size() == 1);
  1963. REQUIRE(!snapshot.get(0).is_valid());
  1964. }
  1965. }
  1966. SECTION("snapshot of Results based on TableView from backlinks") {
  1967. auto object = r->read_group().get_table("class_object");
  1968. auto col_link = object->get_column_key("array");
  1969. auto linked_to = r->read_group().get_table("class_linked to object");
  1970. write([=]{
  1971. linked_to->create_object();
  1972. object->create_object();
  1973. });
  1974. auto linked_to_obj = *linked_to->begin();
  1975. auto lv = object->begin()->get_linklist_ptr(col_link);
  1976. TableView backlinks = linked_to_obj.get_backlink_view(object, col_link);
  1977. Results results(r, std::move(backlinks));
  1978. {
  1979. // A newly-added row should not appear in the snapshot.
  1980. auto snapshot = results.snapshot();
  1981. REQUIRE(results.size() == 0);
  1982. REQUIRE(snapshot.size() == 0);
  1983. write([&]{
  1984. lv->add(linked_to_obj.get_key());
  1985. });
  1986. REQUIRE(results.size() == 1);
  1987. REQUIRE(snapshot.size() == 0);
  1988. }
  1989. {
  1990. // Removing the link should not affect the snapshot.
  1991. auto snapshot = results.snapshot();
  1992. REQUIRE(results.size() == 1);
  1993. REQUIRE(snapshot.size() == 1);
  1994. write([&]{
  1995. if (lv->size() > 0)
  1996. lv->remove(0);
  1997. });
  1998. REQUIRE(results.size() == 0);
  1999. REQUIRE(snapshot.size() == 1);
  2000. REQUIRE(snapshot.get(0).is_valid());
  2001. // Removing a row present in the snapshot from its table should result in the snapshot
  2002. // returning a detached row accessor.
  2003. write([=]{
  2004. object->begin()->remove();
  2005. });
  2006. REQUIRE(snapshot.size() == 1);
  2007. REQUIRE(!snapshot.get(0).is_valid());
  2008. // Adding a new link shouldn't affect the state of the snapshot.
  2009. write([=]{
  2010. object->create_object().get_linklist(col_link).add(linked_to_obj.get_key());
  2011. });
  2012. REQUIRE(snapshot.size() == 1);
  2013. REQUIRE(!snapshot.get(0).is_valid());
  2014. }
  2015. }
  2016. SECTION("snapshot of Results with notification callback registered") {
  2017. auto table = r->read_group().get_table("class_object");
  2018. auto col_value = table->get_column_key("value");
  2019. Query q = table->column<Int>(col_value) > 0;
  2020. Results results(r, q.find_all());
  2021. auto token = results.add_notification_callback([&](CollectionChangeSet, std::exception_ptr err) {
  2022. REQUIRE_FALSE(err);
  2023. });
  2024. advance_and_notify(*r);
  2025. SECTION("snapshot of lvalue") {
  2026. auto snapshot = results.snapshot();
  2027. write([=] {
  2028. table->create_object().set(col_value, 1);
  2029. });
  2030. REQUIRE(snapshot.size() == 0);
  2031. }
  2032. SECTION("snapshot of rvalue") {
  2033. auto snapshot = std::move(results).snapshot();
  2034. write([=] {
  2035. table->create_object().set(col_value, 1);
  2036. });
  2037. REQUIRE(snapshot.size() == 0);
  2038. }
  2039. }
  2040. SECTION("adding notification callback to snapshot throws") {
  2041. auto table = r->read_group().get_table("class_object");
  2042. auto col_value = table->get_column_key("value");
  2043. Query q = table->column<Int>(col_value) > 0;
  2044. Results results(r, q.find_all());
  2045. auto snapshot = results.snapshot();
  2046. CHECK_THROWS(snapshot.add_notification_callback([](CollectionChangeSet, std::exception_ptr) {}));
  2047. }
  2048. SECTION("accessors should return none for detached row") {
  2049. auto table = r->read_group().get_table("class_object");
  2050. write([=] {
  2051. table->create_object();
  2052. });
  2053. Results results(r, table);
  2054. auto snapshot = results.snapshot();
  2055. write([=] {;
  2056. table->clear();
  2057. });
  2058. REQUIRE_FALSE(snapshot.get(0).is_valid());
  2059. REQUIRE_FALSE(snapshot.first()->is_valid());
  2060. REQUIRE_FALSE(snapshot.last()->is_valid());
  2061. }
  2062. }
  2063. TEST_CASE("results: distinct") {
  2064. const int N = 10;
  2065. InMemoryTestFile config;
  2066. config.automatic_change_notifications = false;
  2067. auto r = Realm::get_shared_realm(config);
  2068. r->update_schema({
  2069. {"object", {
  2070. {"num1", PropertyType::Int},
  2071. {"string", PropertyType::String},
  2072. {"num2", PropertyType::Int},
  2073. {"num3", PropertyType::Int}
  2074. }},
  2075. });
  2076. auto table = r->read_group().get_table("class_object");
  2077. r->begin_transaction();
  2078. for (int i = 0; i < N; ++i) {
  2079. table->create_object().set_all(i % 3, util::format("Foo_%1", i % 3).c_str(), N - i, i % 2);
  2080. }
  2081. // table:
  2082. // 0, Foo_0, 10, 0
  2083. // 1, Foo_1, 9, 1
  2084. // 2, Foo_2, 8, 0
  2085. // 0, Foo_0, 7, 1
  2086. // 1, Foo_1, 6, 0
  2087. // 2, Foo_2, 5, 1
  2088. // 0, Foo_0, 4, 0
  2089. // 1, Foo_1, 3, 1
  2090. // 2, Foo_2, 2, 0
  2091. // 0, Foo_0, 1, 1
  2092. r->commit_transaction();
  2093. Results results(r, table->where());
  2094. ColKey col_num1 = table->get_column_key("num1");
  2095. ColKey col_string = table->get_column_key("string");
  2096. ColKey col_num2 = table->get_column_key("num2");
  2097. ColKey col_num3 = table->get_column_key("num3");
  2098. SECTION("Single integer property") {
  2099. Results unique = results.distinct(DistinctDescriptor({{col_num1}}));
  2100. // unique:
  2101. // 0, Foo_0, 10
  2102. // 1, Foo_1, 9
  2103. // 2, Foo_2, 8
  2104. REQUIRE(unique.size() == 3);
  2105. REQUIRE(unique.get(0).get<Int>(col_num2) == 10);
  2106. REQUIRE(unique.get(1).get<Int>(col_num2) == 9);
  2107. REQUIRE(unique.get(2).get<Int>(col_num2) == 8);
  2108. }
  2109. SECTION("Single integer via apply_ordering") {
  2110. DescriptorOrdering ordering;
  2111. ordering.append_sort(SortDescriptor({{col_num1}}));
  2112. ordering.append_distinct(DistinctDescriptor({{col_num1}}));
  2113. Results unique = results.apply_ordering(std::move(ordering));
  2114. // unique:
  2115. // 0, Foo_0, 10
  2116. // 1, Foo_1, 9
  2117. // 2, Foo_2, 8
  2118. REQUIRE(unique.size() == 3);
  2119. REQUIRE(unique.get(0).get<Int>(col_num2) == 10);
  2120. REQUIRE(unique.get(1).get<Int>(col_num2) == 9);
  2121. REQUIRE(unique.get(2).get<Int>(col_num2) == 8);
  2122. }
  2123. SECTION("Single string property") {
  2124. Results unique = results.distinct(DistinctDescriptor({{col_string}}));
  2125. // unique:
  2126. // 0, Foo_0, 10
  2127. // 1, Foo_1, 9
  2128. // 2, Foo_2, 8
  2129. REQUIRE(unique.size() == 3);
  2130. REQUIRE(unique.get(0).get<Int>(col_num2) == 10);
  2131. REQUIRE(unique.get(1).get<Int>(col_num2) == 9);
  2132. REQUIRE(unique.get(2).get<Int>(col_num2) == 8);
  2133. }
  2134. SECTION("Two integer properties combined") {
  2135. Results unique = results.distinct(DistinctDescriptor({{col_num1}, {col_num2}}));
  2136. // unique is the same as the table
  2137. REQUIRE(unique.size() == N);
  2138. for (int i = 0; i < N; ++i) {
  2139. REQUIRE(unique.get(i).get<String>(col_string) == StringData(util::format("Foo_%1", i % 3).c_str()));
  2140. }
  2141. }
  2142. SECTION("String and integer combined") {
  2143. Results unique = results.distinct(DistinctDescriptor({{col_num2}, {col_string}}));
  2144. // unique is the same as the table
  2145. REQUIRE(unique.size() == N);
  2146. for (int i = 0; i < N; ++i) {
  2147. REQUIRE(unique.get(i).get<String>(col_string) == StringData(util::format("Foo_%1", i % 3).c_str()));
  2148. }
  2149. }
  2150. // This section and next section demonstrate that sort().distinct() != distinct().sort()
  2151. SECTION("Order after sort and distinct") {
  2152. Results reverse = results.sort(SortDescriptor({{col_num2}}, {true}));
  2153. // reverse:
  2154. // 0, Foo_0, 1
  2155. // ...
  2156. // 0, Foo_0, 10
  2157. REQUIRE(reverse.first()->get<Int>(col_num2) == 1);
  2158. REQUIRE(reverse.last()->get<Int>(col_num2) == 10);
  2159. // distinct() will be applied to the table, after sorting
  2160. Results unique = reverse.distinct(DistinctDescriptor({{col_num1}}));
  2161. // unique:
  2162. // 0, Foo_0, 1
  2163. // 2, Foo_2, 2
  2164. // 1, Foo_1, 3
  2165. REQUIRE(unique.size() == 3);
  2166. REQUIRE(unique.get(0).get<Int>(col_num2) == 1);
  2167. REQUIRE(unique.get(1).get<Int>(col_num2) == 2);
  2168. REQUIRE(unique.get(2).get<Int>(col_num2) == 3);
  2169. }
  2170. SECTION("Order after distinct and sort") {
  2171. Results unique = results.distinct(DistinctDescriptor({{col_num1}}));
  2172. // unique:
  2173. // 0, Foo_0, 10
  2174. // 1, Foo_1, 9
  2175. // 2, Foo_2, 8
  2176. REQUIRE(unique.size() == 3);
  2177. REQUIRE(unique.first()->get<Int>(col_num2) == 10);
  2178. REQUIRE(unique.last()->get<Int>(col_num2) == 8);
  2179. // sort() is only applied to unique
  2180. Results reverse = unique.sort(SortDescriptor({{col_num2}}, {true}));
  2181. // reversed:
  2182. // 2, Foo_2, 8
  2183. // 1, Foo_1, 9
  2184. // 0, Foo_0, 10
  2185. REQUIRE(reverse.size() == 3);
  2186. REQUIRE(reverse.get(0).get<Int>(col_num2) == 8);
  2187. REQUIRE(reverse.get(1).get<Int>(col_num2) == 9);
  2188. REQUIRE(reverse.get(2).get<Int>(col_num2) == 10);
  2189. }
  2190. SECTION("Chaining distinct") {
  2191. Results first = results.distinct(DistinctDescriptor({{col_num1}}));
  2192. REQUIRE(first.size() == 3);
  2193. // distinct() will not discard the previous applied distinct() calls
  2194. Results second = first.distinct(DistinctDescriptor({{col_num3}}));
  2195. REQUIRE(second.size() == 2);
  2196. }
  2197. SECTION("Chaining sort") {
  2198. using cols_0_3 = std::pair<int, int>;
  2199. Results first = results.sort(SortDescriptor({{col_num1}}));
  2200. Results second = first.sort(SortDescriptor({{col_num3}}));
  2201. REQUIRE(second.size() == 10);
  2202. // results are ordered first by the last sorted column
  2203. // if any duplicates exist in that column, they are resolved by sorting the
  2204. // previously sorted column. Eg. sort(a).sort(b) == sort(b, a)
  2205. std::vector<cols_0_3> results
  2206. = {{0, 0}, {0, 0}, {1, 0}, {2, 0}, {2, 0}, {0, 1}, {0, 1}, {1, 1}, {1, 1}, {2, 1}};
  2207. for (size_t i = 0; i < results.size(); ++i) {
  2208. REQUIRE(second.get(i).get<Int>(col_num1) == results[i].first);
  2209. REQUIRE(second.get(i).get<Int>(col_num3) == results[i].second);
  2210. }
  2211. }
  2212. SECTION("Distinct is carried over to new queries") {
  2213. Results unique = results.distinct(DistinctDescriptor({{col_num1}}));
  2214. // unique:
  2215. // 0, Foo_0, 10
  2216. // 1, Foo_1, 9
  2217. // 2, Foo_2, 8
  2218. REQUIRE(unique.size() == 3);
  2219. Results filtered = unique.filter(Query(table->where().less(col_num1, 2)));
  2220. // filtered:
  2221. // 0, Foo_0, 10
  2222. // 1, Foo_1, 9
  2223. REQUIRE(filtered.size() == 2);
  2224. REQUIRE(filtered.get(0).get<Int>(col_num2) == 10);
  2225. REQUIRE(filtered.get(1).get<Int>(col_num2) == 9);
  2226. }
  2227. SECTION("Distinct will not forget previous query") {
  2228. Results filtered = results.filter(Query(table->where().greater(col_num2, 5)));
  2229. // filtered:
  2230. // 0, Foo_0, 10
  2231. // 1, Foo_1, 9
  2232. // 2, Foo_2, 8
  2233. // 0, Foo_0, 7
  2234. // 1, Foo_1, 6
  2235. REQUIRE(filtered.size() == 5);
  2236. Results unique = filtered.distinct(DistinctDescriptor({{col_num1}}));
  2237. // unique:
  2238. // 0, Foo_0, 10
  2239. // 1, Foo_1, 9
  2240. // 2, Foo_2, 8
  2241. REQUIRE(unique.size() == 3);
  2242. REQUIRE(unique.get(0).get<Int>(col_num2) == 10);
  2243. REQUIRE(unique.get(1).get<Int>(col_num2) == 9);
  2244. REQUIRE(unique.get(2).get<Int>(col_num2) == 8);
  2245. Results further_filtered = unique.filter(Query(table->where().equal(col_num2, 9)));
  2246. // further_filtered:
  2247. // 1, Foo_1, 9
  2248. REQUIRE(further_filtered.size() == 1);
  2249. REQUIRE(further_filtered.get(0).get<Int>(col_num2) == 9);
  2250. }
  2251. }
  2252. TEST_CASE("results: sort") {
  2253. InMemoryTestFile config;
  2254. config.schema = Schema{
  2255. {"object", {
  2256. {"value", PropertyType::Int},
  2257. {"bool", PropertyType::Bool},
  2258. {"data prop", PropertyType::Data},
  2259. {"link", PropertyType::Object|PropertyType::Nullable, "object 2"},
  2260. {"array", PropertyType::Object|PropertyType::Array, "object 2"},
  2261. }},
  2262. {"object 2", {
  2263. {"value", PropertyType::Int},
  2264. {"link", PropertyType::Object|PropertyType::Nullable, "object"},
  2265. }},
  2266. };
  2267. auto realm = Realm::get_shared_realm(config);
  2268. auto table = realm->read_group().get_table("class_object");
  2269. auto table2 = realm->read_group().get_table("class_object 2");
  2270. Results r(realm, table);
  2271. SECTION("invalid keypaths") {
  2272. SECTION("empty property name") {
  2273. REQUIRE_THROWS_WITH(r.sort({{"", true}}), "Cannot sort on key path '': missing property name.");
  2274. REQUIRE_THROWS_WITH(r.sort({{".", true}}), "Cannot sort on key path '.': missing property name.");
  2275. REQUIRE_THROWS_WITH(r.sort({{"link.", true}}), "Cannot sort on key path 'link.': missing property name.");
  2276. REQUIRE_THROWS_WITH(r.sort({{".value", true}}), "Cannot sort on key path '.value': missing property name.");
  2277. REQUIRE_THROWS_WITH(r.sort({{"link..value", true}}), "Cannot sort on key path 'link..value': missing property name.");
  2278. }
  2279. SECTION("bad property name") {
  2280. REQUIRE_THROWS_WITH(r.sort({{"not a property", true}}),
  2281. "Cannot sort on key path 'not a property': property 'object.not a property' does not exist.");
  2282. REQUIRE_THROWS_WITH(r.sort({{"link.not a property", true}}),
  2283. "Cannot sort on key path 'link.not a property': property 'object 2.not a property' does not exist.");
  2284. }
  2285. SECTION("subscript primitive") {
  2286. REQUIRE_THROWS_WITH(r.sort({{"value.link", true}}),
  2287. "Cannot sort on key path 'value.link': property 'object.value' of type 'int' may only be the final property in the key path.");
  2288. }
  2289. SECTION("end in link") {
  2290. REQUIRE_THROWS_WITH(r.sort({{"link", true}}),
  2291. "Cannot sort on key path 'link': property 'object.link' of type 'object' cannot be the final property in the key path.");
  2292. REQUIRE_THROWS_WITH(r.sort({{"link.link", true}}),
  2293. "Cannot sort on key path 'link.link': property 'object 2.link' of type 'object' cannot be the final property in the key path.");
  2294. }
  2295. SECTION("sort involving bad property types") {
  2296. REQUIRE_THROWS_WITH(r.sort({{"array", true}}),
  2297. "Cannot sort on key path 'array': property 'object.array' is of unsupported type 'array'.");
  2298. REQUIRE_THROWS_WITH(r.sort({{"array.value", true}}),
  2299. "Cannot sort on key path 'array.value': property 'object.array' is of unsupported type 'array'.");
  2300. REQUIRE_THROWS_WITH(r.sort({{"link.link.array.value", true}}),
  2301. "Cannot sort on key path 'link.link.array.value': property 'object.array' is of unsupported type 'array'.");
  2302. REQUIRE_THROWS_WITH(r.sort({{"data prop", true}}),
  2303. "Cannot sort on key path 'data prop': property 'object.data prop' is of unsupported type 'data'.");
  2304. }
  2305. }
  2306. realm->begin_transaction();
  2307. ObjKeys table_keys;
  2308. ObjKeys table2_keys;
  2309. table->create_objects(4, table_keys);
  2310. table2->create_objects(4, table2_keys);
  2311. ColKey col_link = table->get_column_key("link");
  2312. ColKey col_link2 = table2->get_column_key("link");
  2313. for (int i = 0; i < 4; ++i) {
  2314. table->get_object(table_keys[i]).set_all((i + 2) % 4, bool(i % 2)).set(col_link, table2_keys[3 - i]);
  2315. table2->get_object(table2_keys[i]).set_all((i + 1) % 4).set(col_link2, table_keys[i]);
  2316. }
  2317. realm->commit_transaction();
  2318. /*
  2319. | index | value | bool | link.value | link.link.value |
  2320. |-------|-------|------|------------|-----------------|
  2321. | 0 | 2 | 0 | 0 | 1 |
  2322. | 1 | 3 | 1 | 3 | 0 |
  2323. | 2 | 0 | 0 | 2 | 3 |
  2324. | 3 | 1 | 1 | 1 | 2 |
  2325. */
  2326. #define REQUIRE_ORDER(sort, ...) do { \
  2327. ObjKeys expected({__VA_ARGS__}); \
  2328. auto results = sort; \
  2329. REQUIRE(results.size() == expected.size()); \
  2330. for (size_t i = 0; i < expected.size(); ++i) \
  2331. REQUIRE(results.get(i).get_key() == expected[i]); \
  2332. } while (0)
  2333. SECTION("sort on single property") {
  2334. REQUIRE_ORDER((r.sort({{"value", true}})),
  2335. 2, 3, 0, 1);
  2336. REQUIRE_ORDER((r.sort({{"value", false}})),
  2337. 1, 0, 3, 2);
  2338. }
  2339. SECTION("sort on two properties") {
  2340. REQUIRE_ORDER((r.sort({{"bool", true}, {"value", true}})),
  2341. 2, 0, 3, 1);
  2342. REQUIRE_ORDER((r.sort({{"bool", false}, {"value", true}})),
  2343. 3, 1, 2, 0);
  2344. REQUIRE_ORDER((r.sort({{"bool", true}, {"value", false}})),
  2345. 0, 2, 1, 3);
  2346. REQUIRE_ORDER((r.sort({{"bool", false}, {"value", false}})),
  2347. 1, 3, 0, 2);
  2348. }
  2349. SECTION("sort over link") {
  2350. REQUIRE_ORDER((r.sort({{"link.value", true}})),
  2351. 0, 3, 2, 1);
  2352. REQUIRE_ORDER((r.sort({{"link.value", false}})),
  2353. 1, 2, 3, 0);
  2354. }
  2355. SECTION("sort over two links") {
  2356. REQUIRE_ORDER((r.sort({{"link.link.value", true}})),
  2357. 1, 0, 3, 2);
  2358. REQUIRE_ORDER((r.sort({{"link.link.value", false}})),
  2359. 2, 3, 0, 1);
  2360. }
  2361. }
  2362. struct ResultsFromTable {
  2363. static Results call(std::shared_ptr<Realm> r, ConstTableRef table) {
  2364. return Results(std::move(r), table);
  2365. }
  2366. };
  2367. struct ResultsFromQuery {
  2368. static Results call(std::shared_ptr<Realm> r, ConstTableRef table) {
  2369. return Results(std::move(r), table->where());
  2370. }
  2371. };
  2372. struct ResultsFromTableView {
  2373. static Results call(std::shared_ptr<Realm> r, ConstTableRef table) {
  2374. return Results(std::move(r), table->where().find_all());
  2375. }
  2376. };
  2377. struct ResultsFromLinkView {
  2378. static Results call(std::shared_ptr<Realm> r, ConstTableRef table) {
  2379. r->begin_transaction();
  2380. auto link_table = r->read_group().get_table("class_linking_object");
  2381. std::shared_ptr<LnkLst> link_view = link_table->create_object().get_linklist_ptr(link_table->get_column_key("link"));
  2382. for (auto& o : *table)
  2383. link_view->add(o.get_key());
  2384. r->commit_transaction();
  2385. return Results(r, link_view);
  2386. }
  2387. };
  2388. TEMPLATE_TEST_CASE("results: get()", "", ResultsFromTable, ResultsFromQuery, ResultsFromTableView, ResultsFromLinkView) {
  2389. InMemoryTestFile config;
  2390. config.automatic_change_notifications = false;
  2391. auto r = Realm::get_shared_realm(config);
  2392. r->update_schema({
  2393. {"object", {
  2394. {"value", PropertyType::Int},
  2395. }},
  2396. {"linking_object", {
  2397. {"link", PropertyType::Array|PropertyType::Object, "object"}
  2398. }},
  2399. });
  2400. auto table = r->read_group().get_table("class_object");
  2401. ColKey col_value = table->get_column_key("value");
  2402. r->begin_transaction();
  2403. for (int i = 0; i < 10; ++i)
  2404. table->create_object().set_all(i);
  2405. r->commit_transaction();
  2406. Results results = TestType::call(r, table);
  2407. SECTION("sequential in increasing order") {
  2408. for (int i = 0; i < 10; ++i)
  2409. CHECK(results.get<Obj>(i).get<int64_t>(col_value) == i);
  2410. for (int i = 0; i < 10; ++i)
  2411. CHECK(results.get<Obj>(i).get<int64_t>(col_value) == i);
  2412. CHECK_THROWS(results.get(11));
  2413. }
  2414. SECTION("sequential in decreasing order") {
  2415. for (int i = 9; i >= 0; --i)
  2416. CHECK(results.get<Obj>(i).get<int64_t>(col_value) == i);
  2417. for (int i = 9; i >= 0; --i)
  2418. CHECK(results.get<Obj>(i).get<int64_t>(col_value) == i);
  2419. }
  2420. SECTION("random order") {
  2421. int indexes[10];
  2422. std::iota(std::begin(indexes), std::end(indexes), 0);
  2423. std::random_device rd;
  2424. std::mt19937 g(rd());
  2425. std::shuffle(std::begin(indexes), std::end(indexes), std::mt19937(rd()));
  2426. for (auto index : indexes)
  2427. CHECK(results.get<Obj>(index).get<int64_t>(col_value) == index);
  2428. }
  2429. }
  2430. TEMPLATE_TEST_CASE("results: aggregate", "[query][aggregate]", ResultsFromTable, ResultsFromQuery, ResultsFromTableView, ResultsFromLinkView) {
  2431. InMemoryTestFile config;
  2432. config.automatic_change_notifications = false;
  2433. auto r = Realm::get_shared_realm(config);
  2434. r->update_schema({
  2435. {"object", {
  2436. {"int", PropertyType::Int|PropertyType::Nullable},
  2437. {"float", PropertyType::Float|PropertyType::Nullable},
  2438. {"double", PropertyType::Double|PropertyType::Nullable},
  2439. {"date", PropertyType::Date|PropertyType::Nullable},
  2440. }},
  2441. {"linking_object", {
  2442. {"link", PropertyType::Array|PropertyType::Object, "object"}
  2443. }},
  2444. });
  2445. auto table = r->read_group().get_table("class_object");
  2446. ColKey col_int = table->get_column_key("int");
  2447. ColKey col_float = table->get_column_key("float");
  2448. ColKey col_double = table->get_column_key("double");
  2449. ColKey col_date = table->get_column_key("date");
  2450. SECTION("one row with null values") {
  2451. r->begin_transaction();
  2452. table->create_object();
  2453. table->create_object().set_all(0, 0.f, 0.0, Timestamp(0, 0));
  2454. table->create_object().set_all(2, 2.f, 2.0, Timestamp(2, 0));
  2455. // table:
  2456. // null, null, null, null,
  2457. // 0, 0, 0, (0, 0)
  2458. // 2, 2, 2, (2, 0)
  2459. r->commit_transaction();
  2460. Results results = TestType::call(r, table);
  2461. SECTION("max") {
  2462. REQUIRE(results.max(col_int)->get_int() == 2);
  2463. REQUIRE(results.max(col_float)->get_float() == 2.f);
  2464. REQUIRE(results.max(col_double)->get_double() == 2.0);
  2465. REQUIRE(results.max(col_date)->get_timestamp() == Timestamp(2, 0));
  2466. }
  2467. SECTION("min") {
  2468. REQUIRE(results.min(col_int)->get_int() == 0);
  2469. REQUIRE(results.min(col_float)->get_float() == 0.f);
  2470. REQUIRE(results.min(col_double)->get_double() == 0.0);
  2471. REQUIRE(results.min(col_date)->get_timestamp() == Timestamp(0, 0));
  2472. }
  2473. SECTION("average") {
  2474. REQUIRE(results.average(col_int) == 1.0);
  2475. REQUIRE(results.average(col_float) == 1.0);
  2476. REQUIRE(results.average(col_double) == 1.0);
  2477. REQUIRE_THROWS_AS(results.average(col_date), Results::UnsupportedColumnTypeException);
  2478. }
  2479. SECTION("sum") {
  2480. REQUIRE(results.sum(col_int)->get_int() == 2);
  2481. REQUIRE(results.sum(col_float)->get_double() == 2.0);
  2482. REQUIRE(results.sum(col_double)->get_double() == 2.0);
  2483. REQUIRE_THROWS_AS(results.sum(col_date), Results::UnsupportedColumnTypeException);
  2484. }
  2485. }
  2486. SECTION("rows with all null values") {
  2487. r->begin_transaction();
  2488. table->create_object();
  2489. table->create_object();
  2490. table->create_object();
  2491. // table:
  2492. // null, null, null, null, null
  2493. // null, null, null, null, null
  2494. // null, null, null, null, null
  2495. r->commit_transaction();
  2496. Results results = TestType::call(r, table);
  2497. SECTION("max") {
  2498. REQUIRE(!results.max(col_int));
  2499. REQUIRE(!results.max(col_float));
  2500. REQUIRE(!results.max(col_double));
  2501. REQUIRE(!results.max(col_date));
  2502. }
  2503. SECTION("min") {
  2504. REQUIRE(!results.min(col_int));
  2505. REQUIRE(!results.min(col_float));
  2506. REQUIRE(!results.min(col_double));
  2507. REQUIRE(!results.min(col_date));
  2508. }
  2509. SECTION("average") {
  2510. REQUIRE(!results.average(col_int));
  2511. REQUIRE(!results.average(col_float));
  2512. REQUIRE(!results.average(col_double));
  2513. REQUIRE_THROWS_AS(results.average(col_date), Results::UnsupportedColumnTypeException);
  2514. }
  2515. SECTION("sum") {
  2516. REQUIRE(results.sum(col_int)->get_int() == 0);
  2517. REQUIRE(results.sum(col_float)->get_double() == 0.0);
  2518. REQUIRE(results.sum(col_double)->get_double() == 0.0);
  2519. REQUIRE_THROWS_AS(results.sum(col_date), Results::UnsupportedColumnTypeException);
  2520. }
  2521. }
  2522. SECTION("empty") {
  2523. Results results = TestType::call(r, table);
  2524. SECTION("max") {
  2525. REQUIRE(!results.max(col_int));
  2526. REQUIRE(!results.max(col_float));
  2527. REQUIRE(!results.max(col_double));
  2528. REQUIRE(!results.max(col_date));
  2529. }
  2530. SECTION("min") {
  2531. REQUIRE(!results.min(col_int));
  2532. REQUIRE(!results.min(col_float));
  2533. REQUIRE(!results.min(col_double));
  2534. REQUIRE(!results.min(col_date));
  2535. }
  2536. SECTION("average") {
  2537. REQUIRE(!results.average(col_int));
  2538. REQUIRE(!results.average(col_float));
  2539. REQUIRE(!results.average(col_double));
  2540. REQUIRE_THROWS_AS(results.average(col_date), Results::UnsupportedColumnTypeException);
  2541. }
  2542. SECTION("sum") {
  2543. REQUIRE(results.sum(col_int)->get_int() == 0);
  2544. REQUIRE(results.sum(col_float)->get_double() == 0.0);
  2545. REQUIRE(results.sum(col_double)->get_double() == 0.0);
  2546. REQUIRE_THROWS_AS(results.sum(col_date), Results::UnsupportedColumnTypeException);
  2547. }
  2548. }
  2549. }
  2550. TEST_CASE("results: set property value on all objects", "[batch_updates]") {
  2551. InMemoryTestFile config;
  2552. config.automatic_change_notifications = false;
  2553. // config.cache = false;
  2554. config.schema = Schema{
  2555. {"AllTypes", {
  2556. {"pk", PropertyType::Int, Property::IsPrimary{true}},
  2557. {"bool", PropertyType::Bool},
  2558. {"int", PropertyType::Int},
  2559. {"float", PropertyType::Float},
  2560. {"double", PropertyType::Double},
  2561. {"string", PropertyType::String},
  2562. {"data", PropertyType::Data},
  2563. {"date", PropertyType::Date},
  2564. {"object", PropertyType::Object|PropertyType::Nullable, "AllTypes"},
  2565. {"list", PropertyType::Array|PropertyType::Object, "AllTypes"},
  2566. {"bool array", PropertyType::Array|PropertyType::Bool},
  2567. {"int array", PropertyType::Array|PropertyType::Int},
  2568. {"float array", PropertyType::Array|PropertyType::Float},
  2569. {"double array", PropertyType::Array|PropertyType::Double},
  2570. {"string array", PropertyType::Array|PropertyType::String},
  2571. {"data array", PropertyType::Array|PropertyType::Data},
  2572. {"date array", PropertyType::Array|PropertyType::Date},
  2573. {"object array", PropertyType::Array|PropertyType::Object, "AllTypes"},
  2574. }, {
  2575. {"parents", PropertyType::LinkingObjects|PropertyType::Array, "AllTypes", "object"},
  2576. }}
  2577. };
  2578. config.schema_version = 0;
  2579. auto realm = Realm::get_shared_realm(config);
  2580. auto table = realm->read_group().get_table("class_AllTypes");
  2581. realm->begin_transaction();
  2582. table->create_object();
  2583. table->create_object();
  2584. realm->commit_transaction();
  2585. Results r(realm, table);
  2586. TestContext ctx(realm);
  2587. SECTION("non-existing property name") {
  2588. realm->begin_transaction();
  2589. REQUIRE_THROWS_AS(r.set_property_value(ctx, "i dont exist", util::Any(false)), Results::InvalidPropertyException);
  2590. realm->cancel_transaction();
  2591. }
  2592. SECTION("readonly property") {
  2593. realm->begin_transaction();
  2594. REQUIRE_THROWS_AS(r.set_property_value(ctx, "parents", util::Any(false)), ReadOnlyPropertyException);
  2595. realm->cancel_transaction();
  2596. }
  2597. SECTION("primarykey property") {
  2598. realm->begin_transaction();
  2599. REQUIRE_THROWS_AS(r.set_property_value(ctx, "pk", util::Any(1)), std::logic_error);
  2600. realm->cancel_transaction();
  2601. }
  2602. SECTION("set property values removes object from Results") {
  2603. realm->begin_transaction();
  2604. Results results(realm, table->where().equal(table->get_column_key("int"),0));
  2605. CHECK(results.size() == 2);
  2606. r.set_property_value(ctx, "int", util::Any(INT64_C(42)));
  2607. CHECK(results.size() == 0);
  2608. realm->cancel_transaction();
  2609. }
  2610. SECTION("set property value") {
  2611. realm->begin_transaction();
  2612. r.set_property_value<util::Any>(ctx, "bool", util::Any(true));
  2613. for (size_t i = 0; i < r.size(); i++) {
  2614. CHECK(r.get(i).get<Bool>("bool") == true);
  2615. }
  2616. r.set_property_value(ctx, "int", util::Any(INT64_C(42)));
  2617. for (size_t i = 0; i < r.size(); i++) {
  2618. CHECK(r.get(i).get<Int>("int") == 42);
  2619. }
  2620. r.set_property_value(ctx, "float", util::Any(1.23f));
  2621. for (size_t i = 0; i < r.size(); i++) {
  2622. CHECK(r.get(i).get<float>("float") == 1.23f);
  2623. }
  2624. r.set_property_value(ctx, "double", util::Any(1.234));
  2625. for (size_t i = 0; i < r.size(); i++) {
  2626. CHECK(r.get(i).get<double>("double") == 1.234);
  2627. }
  2628. r.set_property_value(ctx, "string", util::Any(std::string("abc")));
  2629. for (size_t i = 0; i < r.size(); i++) {
  2630. CHECK(r.get(i).get<String>("string") == "abc");
  2631. }
  2632. r.set_property_value(ctx, "data", util::Any(std::string("abc")));
  2633. for (size_t i = 0; i < r.size(); i++) {
  2634. CHECK(r.get(i).get<Binary>("data") == BinaryData("abc", 3));
  2635. }
  2636. util::Any timestamp = Timestamp(1, 2);
  2637. r.set_property_value(ctx, "date", timestamp);
  2638. for (size_t i = 0; i < r.size(); i++) {
  2639. CHECK(r.get(i).get<Timestamp>("date") == any_cast<Timestamp>(timestamp));
  2640. }
  2641. ObjKey object_key = table->create_object().get_key();
  2642. Object linked_obj(realm, "AllTypes", object_key);
  2643. r.set_property_value(ctx, "object", util::Any(linked_obj));
  2644. for (size_t i = 0; i < r.size(); i++) {
  2645. CHECK(r.get(i).get<ObjKey>("object") == object_key);
  2646. }
  2647. ObjKey list_object_key = table->create_object().get_key();
  2648. Object list_object(realm, "AllTypes", list_object_key);
  2649. r.set_property_value(ctx, "list", util::Any(AnyVector{list_object, list_object}));
  2650. for (size_t i = 0; i < r.size(); i++) {
  2651. auto list = r.get(i).get_linklist("list");
  2652. CHECK(list.size() == 2);
  2653. CHECK(list.get(0) == list_object_key);
  2654. CHECK(list.get(1) == list_object_key);
  2655. }
  2656. auto check_array = [&](ColKey col, auto val0, auto... values) {
  2657. size_t rows = r.size();
  2658. for (size_t i = 0; i < rows; ++i) {
  2659. Obj row = r.get(i);
  2660. auto array = row.get_list<decltype(val0)>(col);
  2661. CAPTURE(0);
  2662. REQUIRE(val0 == array.get(0));
  2663. size_t j = 1;
  2664. for (auto& value : {values...}) {
  2665. CAPTURE(j);
  2666. REQUIRE(j < array.size());
  2667. REQUIRE(value == array.get(j));
  2668. ++j;
  2669. }
  2670. }
  2671. };
  2672. r.set_property_value(ctx, "bool array", util::Any(AnyVec{true, false}));
  2673. check_array(table->get_column_key("bool array"), true, false);
  2674. r.set_property_value(ctx, "int array", util::Any(AnyVec{INT64_C(5), INT64_C(6)}));
  2675. check_array(table->get_column_key("int array"), INT64_C(5), INT64_C(6));
  2676. r.set_property_value(ctx, "float array", util::Any(AnyVec{1.1f, 2.2f}));
  2677. check_array(table->get_column_key("float array"), 1.1f, 2.2f);
  2678. r.set_property_value(ctx, "double array", util::Any(AnyVec{3.3, 4.4}));
  2679. check_array(table->get_column_key("double array"), 3.3, 4.4);
  2680. r.set_property_value(ctx, "string array", util::Any(AnyVec{"a"s, "b"s, "c"s}));
  2681. check_array(table->get_column_key("string array"), StringData("a"), StringData("b"), StringData("c"));
  2682. r.set_property_value(ctx, "data array", util::Any(AnyVec{"d"s, "e"s, "f"s}));
  2683. check_array(table->get_column_key("data array"), BinaryData("d",1), BinaryData("e",1), BinaryData("f",1));
  2684. r.set_property_value(ctx, "date array", util::Any(AnyVec{Timestamp(10,20), Timestamp(20,30), Timestamp(30,40)}));
  2685. check_array(table->get_column_key("date array"), Timestamp(10,20), Timestamp(20,30), Timestamp(30,40));
  2686. }
  2687. }
  2688. TEST_CASE("results: limit", "[limit]") {
  2689. InMemoryTestFile config;
  2690. // config.cache = false;
  2691. config.automatic_change_notifications = false;
  2692. config.schema = Schema{
  2693. {"object", {
  2694. {"value", PropertyType::Int},
  2695. }},
  2696. };
  2697. auto realm = Realm::get_shared_realm(config);
  2698. auto table = realm->read_group().get_table("class_object");
  2699. auto col = table->get_column_key("value");
  2700. realm->begin_transaction();
  2701. for (int i = 0; i < 8; ++i) {
  2702. table->create_object().set(col, (i + 2) % 4);
  2703. }
  2704. realm->commit_transaction();
  2705. Results r(realm, table);
  2706. SECTION("unsorted") {
  2707. REQUIRE(r.limit(0).size() == 0);
  2708. REQUIRE_ORDER(r.limit(1), 0);
  2709. REQUIRE_ORDER(r.limit(2), 0, 1);
  2710. REQUIRE_ORDER(r.limit(8), 0, 1, 2, 3, 4, 5, 6, 7);
  2711. REQUIRE_ORDER(r.limit(100), 0, 1, 2, 3, 4, 5, 6, 7);
  2712. }
  2713. SECTION("sorted") {
  2714. auto sorted = r.sort({{"value", true}});
  2715. REQUIRE(sorted.limit(0).size() == 0);
  2716. REQUIRE_ORDER(sorted.limit(1), 2);
  2717. REQUIRE_ORDER(sorted.limit(2), 2, 6);
  2718. REQUIRE_ORDER(sorted.limit(8), 2, 6, 3, 7, 0, 4, 1, 5);
  2719. REQUIRE_ORDER(sorted.limit(100), 2, 6, 3, 7, 0, 4, 1, 5);
  2720. }
  2721. SECTION("sort after limit") {
  2722. REQUIRE(r.limit(0).sort({{"value", true}}).size() == 0);
  2723. REQUIRE_ORDER(r.limit(1).sort({{"value", true}}), 0);
  2724. REQUIRE_ORDER(r.limit(3).sort({{"value", true}}), 2, 0, 1);
  2725. REQUIRE_ORDER(r.limit(8).sort({{"value", true}}), 2, 6, 3, 7, 0, 4, 1, 5);
  2726. REQUIRE_ORDER(r.limit(100).sort({{"value", true}}), 2, 6, 3, 7, 0, 4, 1, 5);
  2727. }
  2728. SECTION("distinct") {
  2729. auto sorted = r.distinct({"value"});
  2730. REQUIRE(sorted.limit(0).size() == 0);
  2731. REQUIRE_ORDER(sorted.limit(1), 0);
  2732. REQUIRE_ORDER(sorted.limit(2), 0, 1);
  2733. REQUIRE_ORDER(sorted.limit(8), 0, 1, 2, 3);
  2734. sorted = r.sort({{"value", true}}).distinct({"value"});
  2735. REQUIRE(sorted.limit(0).size() == 0);
  2736. REQUIRE_ORDER(sorted.limit(1), 2);
  2737. REQUIRE_ORDER(sorted.limit(2), 2, 3);
  2738. REQUIRE_ORDER(sorted.limit(8), 2, 3, 0, 1);
  2739. }
  2740. SECTION("notifications on results using all descriptor types") {
  2741. r = r.distinct({"value"}).sort({{"value", false}}).limit(2);
  2742. int notification_calls = 0;
  2743. auto token = r.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  2744. REQUIRE_FALSE(err);
  2745. if (notification_calls == 0) {
  2746. REQUIRE(c.empty());
  2747. REQUIRE(r.size() == 2);
  2748. REQUIRE(r.get(0).get<Int>(col) == 3);
  2749. REQUIRE(r.get(1).get<Int>(col) == 2);
  2750. } else if (notification_calls == 1) {
  2751. REQUIRE(!c.empty());
  2752. REQUIRE_INDICES(c.insertions, 0);
  2753. REQUIRE_INDICES(c.deletions, 1);
  2754. REQUIRE(c.moves.size() == 0);
  2755. REQUIRE(c.modifications.count() == 0);
  2756. REQUIRE(r.size() == 2);
  2757. REQUIRE(r.get(0).get<Int>(col) == 5);
  2758. REQUIRE(r.get(1).get<Int>(col) == 3);
  2759. }
  2760. ++notification_calls;
  2761. });
  2762. advance_and_notify(*realm);
  2763. REQUIRE(notification_calls == 1);
  2764. realm->begin_transaction();
  2765. table->create_object().set(col, 5);
  2766. realm->commit_transaction();
  2767. advance_and_notify(*realm);
  2768. REQUIRE(notification_calls == 2);
  2769. }
  2770. SECTION("notifications on only limited results") {
  2771. r = r.limit(2);
  2772. int notification_calls = 0;
  2773. auto token = r.add_notification_callback([&](CollectionChangeSet c, std::exception_ptr err) {
  2774. REQUIRE_FALSE(err);
  2775. if (notification_calls == 0) {
  2776. REQUIRE(c.empty());
  2777. REQUIRE(r.size() == 2);
  2778. } else if (notification_calls == 1) {
  2779. REQUIRE(!c.empty());
  2780. REQUIRE(c.insertions.count() == 0);
  2781. REQUIRE(c.deletions.count() == 0);
  2782. REQUIRE(c.modifications.count() == 1);
  2783. REQUIRE_INDICES(c.modifications, 1);
  2784. REQUIRE(r.size() == 2);
  2785. }
  2786. ++notification_calls;
  2787. });
  2788. advance_and_notify(*realm);
  2789. REQUIRE(notification_calls == 1);
  2790. realm->begin_transaction();
  2791. table->get_object(1).set(col, 5);
  2792. realm->commit_transaction();
  2793. advance_and_notify(*realm);
  2794. REQUIRE(notification_calls == 2);
  2795. }
  2796. SECTION("does not support further filtering") {
  2797. auto limited = r.limit(0);
  2798. REQUIRE_THROWS_AS(limited.filter(table->where()), Results::UnimplementedOperationException);
  2799. }
  2800. }